_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q2300
Caller.getRealm
train
public String getRealm() { if (UNDEFINED.equals(realm)) { Principal principal = securityIdentity.getPrincipal(); String realm = null; if (principal instanceof RealmPrincipal) { realm = ((RealmPrincipal)principal).getRealm(); } this.realm = realm; } return this.realm; }
java
{ "resource": "" }
q2301
RemoteDomainConnectionService.resolveSubsystems
train
private ModelNode resolveSubsystems(final List<ModelNode> extensions) { HostControllerLogger.ROOT_LOGGER.debug("Applying extensions provided by master"); final ModelNode result = operationExecutor.installSlaveExtensions(extensions); if (!SUCCESS.equals(result.get(OUTCOME).asString())) { throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION)); } final ModelNode subsystems = new ModelNode(); for (final ModelNode extension : extensions) { extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems); } return subsystems; }
java
{ "resource": "" }
q2302
RemoteDomainConnectionService.applyRemoteDomainModel
train
private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) { try { HostControllerLogger.ROOT_LOGGER.debug("Applying domain level boot operations provided by master"); SyncModelParameters parameters = new SyncModelParameters(domainController, ignoredDomainResourceRegistry, hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository); final SyncDomainModelOperationHandler handler = new SyncDomainModelOperationHandler(hostInfo, parameters); final ModelNode operation = APPLY_DOMAIN_MODEL.clone(); operation.get(DOMAIN_MODEL).set(bootOperations); final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler); final String outcome = result.get(OUTCOME).asString(); final boolean success = SUCCESS.equals(outcome); // check if anything we synced triggered reload-required or restart-required. // if they did we log a warning on the synced slave. if (result.has(RESPONSE_HEADERS)) { final ModelNode headers = result.get(RESPONSE_HEADERS); if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) { HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired(); } if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) { HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired(); } } if (!success) { ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode(); HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc); return false; } else { return true; } } catch (Exception e) { HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e); return false; } }
java
{ "resource": "" }
q2303
RemoteDomainConnectionService.rethrowIrrecoverableConnectionFailures
train
static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException { Throwable cause = e; while ((cause = cause.getCause()) != null) { if (cause instanceof SaslException) { throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause); } else if (cause instanceof SSLHandshakeException) { throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause); } else if (cause instanceof SlaveRegistrationException) { throw (SlaveRegistrationException) cause; } } }
java
{ "resource": "" }
q2304
RemoteDomainConnectionService.logConnectionException
train
static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) { if (uri == null) { HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e); } else { HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e); } if (!moreOptions) { // All discovery options have been exhausted HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft(); } }
java
{ "resource": "" }
q2305
AliasOperationTransformer.replaceLastElement
train
public static AliasOperationTransformer replaceLastElement(final PathElement element) { return create(new AddressTransformer() { @Override public PathAddress transformAddress(final PathAddress original) { final PathAddress address = original.subAddress(0, original.size() -1); return address.append(element); } }); }
java
{ "resource": "" }
q2306
UpdatePropertiesHandler.persist
train
void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException { persist(key, value, enableDisableMode, disable, file, null); }
java
{ "resource": "" }
q2307
UpdatePropertiesHandler.persist
train
void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file, final String realm) throws IOException, StartException { final PropertiesFileLoader propertiesHandler = realm == null ? new PropertiesFileLoader(file.getAbsolutePath(), null) : new UserPropertiesFileLoader(file.getAbsolutePath(), null); try { propertiesHandler.start(null); if (realm != null) { ((UserPropertiesFileLoader) propertiesHandler).setRealmName(realm); } Properties prob = propertiesHandler.getProperties(); if (value != null) { prob.setProperty(key, value); } if (enableDisableMode) { prob.setProperty(key + "!disable", String.valueOf(disable)); } propertiesHandler.persistProperties(); } finally { propertiesHandler.stop(null); } }
java
{ "resource": "" }
q2308
Services.deploymentUnitName
train
public static ServiceName deploymentUnitName(String name, Phase phase) { return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name()); }
java
{ "resource": "" }
q2309
AbstractModelUpdateHandler.updateModel
train
protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException { updateModel(operation, resource.getModel()); }
java
{ "resource": "" }
q2310
TransformersLogger.logAttributeWarning
train
public void logAttributeWarning(PathAddress address, String attribute) { logAttributeWarning(address, null, null, attribute); }
java
{ "resource": "" }
q2311
TransformersLogger.logAttributeWarning
train
public void logAttributeWarning(PathAddress address, Set<String> attributes) { logAttributeWarning(address, null, null, attributes); }
java
{ "resource": "" }
q2312
TransformersLogger.logAttributeWarning
train
public void logAttributeWarning(PathAddress address, String message, String attribute) { logAttributeWarning(address, null, message, attribute); }
java
{ "resource": "" }
q2313
TransformersLogger.logAttributeWarning
train
public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, null, message, attributes)); }
java
{ "resource": "" }
q2314
TransformersLogger.logAttributeWarning
train
public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) { messageQueue.add(new AttributeLogEntry(address, operation, message, attribute)); }
java
{ "resource": "" }
q2315
TransformersLogger.logAttributeWarning
train
public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, operation, message, attributes)); }
java
{ "resource": "" }
q2316
TransformersLogger.logWarning
train
public void logWarning(final String message) { messageQueue.add(new LogEntry() { @Override public String getMessage() { return message; } }); }
java
{ "resource": "" }
q2317
TransformersLogger.flushLogQueue
train
void flushLogQueue() { Set<String> problems = new LinkedHashSet<String>(); synchronized (messageQueue) { Iterator<LogEntry> i = messageQueue.iterator(); while (i.hasNext()) { problems.add("\t\t" + i.next().getMessage() + "\n"); i.remove(); } } if (!problems.isEmpty()) { logger.transformationWarnings(target.getHostName(), problems); } }
java
{ "resource": "" }
q2318
IdentityPatchContext.getEntry
train
PatchEntry getEntry(final String name, boolean addOn) { return addOn ? addOns.get(name) : layers.get(name); }
java
{ "resource": "" }
q2319
IdentityPatchContext.failedToCleanupDir
train
protected void failedToCleanupDir(final File file) { checkForGarbageOnRestart = true; PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath()); }
java
{ "resource": "" }
q2320
IdentityPatchContext.resolveForElement
train
protected PatchEntry resolveForElement(final PatchElement element) throws PatchingException { assert state == State.NEW; final PatchElementProvider provider = element.getProvider(); final String layerName = provider.getName(); final LayerType layerType = provider.getLayerType(); final Map<String, PatchEntry> map; if (layerType == LayerType.Layer) { map = layers; } else { map = addOns; } PatchEntry entry = map.get(layerName); if (entry == null) { final InstallationManager.MutablePatchingTarget target = modification.resolve(layerName, layerType); if (target == null) { throw PatchLogger.ROOT_LOGGER.noSuchLayer(layerName); } entry = new PatchEntry(target, element); map.put(layerName, entry); } // Maintain the most recent element entry.updateElement(element); return entry; }
java
{ "resource": "" }
q2321
IdentityPatchContext.complete
train
private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) { final List<File> processed = new ArrayList<File>(); List<File> reenabled = Collections.emptyList(); List<File> disabled = Collections.emptyList(); try { try { // Update the state to invalidate and process module resources if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) { if (mode == PatchingTaskContext.Mode.APPLY) { // Only invalidate modules when applying patches; on rollback files are immediately restored for (final File invalidation : moduleInvalidations) { processed.add(invalidation); PatchModuleInvalidationUtils.processFile(this, invalidation, mode); } if (!modulesToReenable.isEmpty()) { reenabled = new ArrayList<File>(modulesToReenable.size()); for (final File path : modulesToReenable) { reenabled.add(path); PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK); } } } else if(mode == PatchingTaskContext.Mode.ROLLBACK) { if (!modulesToDisable.isEmpty()) { disabled = new ArrayList<File>(modulesToDisable.size()); for (final File path : modulesToDisable) { disabled.add(path); PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY); } } } } modification.complete(); callback.completed(this); state = State.COMPLETED; } catch (Exception e) { this.moduleInvalidations.clear(); this.moduleInvalidations.addAll(processed); this.modulesToReenable.clear(); this.modulesToReenable.addAll(reenabled); this.modulesToDisable.clear(); this.moduleInvalidations.addAll(disabled); throw new RuntimeException(e); } } finally { if (state != State.COMPLETED) { try { modification.cancel(); } finally { try { undoChanges(); } finally { callback.operationCancelled(this); } } } else { try { if (checkForGarbageOnRestart) { final File cleanupMarker = new File(installedImage.getInstallationMetadata(), "cleanup-patching-dirs"); cleanupMarker.createNewFile(); } storeFailedRenaming(); } catch (IOException e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to create cleanup marker"); } } } }
java
{ "resource": "" }
q2322
IdentityPatchContext.undoChanges
train
boolean undoChanges() { final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY); if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) { // Was actually completed already return false; } PatchingTaskContext.Mode currentMode = this.mode; mode = PatchingTaskContext.Mode.UNDO; final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null); // Undo changes for the identity undoChanges(identityEntry, loader); // TODO maybe check if we need to do something for the layers too !? if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) { // For apply the state needs to be invalidate // For rollback the files are invalidated as part of the tasks final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY; for (final File file : moduleInvalidations) { try { PatchModuleInvalidationUtils.processFile(this, file, mode); } catch (Exception e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to restore state for %s", file); } } if(!modulesToReenable.isEmpty()) { for (final File file : modulesToReenable) { try { PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY); } catch (Exception e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to restore state for %s", file); } } } if(!modulesToDisable.isEmpty()) { for (final File file : modulesToDisable) { try { PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK); } catch (Exception e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to restore state for %s", file); } } } } return true; }
java
{ "resource": "" }
q2323
IdentityPatchContext.undoChanges
train
static void undoChanges(final PatchEntry entry, final PatchContentLoader loader) { final List<ContentModification> modifications = new ArrayList<ContentModification>(entry.rollbackActions); for (final ContentModification modification : modifications) { final ContentItem item = modification.getItem(); if (item.getContentType() != ContentType.MISC) { // Skip modules and bundles they should be removed as part of the {@link FinalizeCallback} continue; } final PatchingTaskDescription description = new PatchingTaskDescription(entry.applyPatchId, modification, loader, false, false, false); try { final PatchingTask task = PatchingTask.Factory.create(description, entry); task.execute(entry); } catch (Exception e) { PatchLogger.ROOT_LOGGER.failedToUndoChange(item.toString()); } } }
java
{ "resource": "" }
q2324
IdentityPatchContext.recordRollbackLoader
train
private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) { // setup the content loader paths final DirectoryStructure structure = target.getDirectoryStructure(); final InstalledImage image = structure.getInstalledImage(); final File historyDir = image.getPatchHistoryDir(patchId); final File miscRoot = new File(historyDir, PatchContentLoader.MISC); final File modulesRoot = structure.getModulePatchDirectory(patchId); final File bundlesRoot = structure.getBundlesPatchDirectory(patchId); final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot); // recordContentLoader(patchId, loader); }
java
{ "resource": "" }
q2325
IdentityPatchContext.recordContentLoader
train
protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) { if (contentLoaders.containsKey(patchID)) { throw new IllegalStateException("Content loader already registered for patch " + patchID); // internal wrong usage, no i18n } contentLoaders.put(patchID, contentLoader); }
java
{ "resource": "" }
q2326
IdentityPatchContext.getTargetFile
train
public File getTargetFile(final MiscContentItem item) { final State state = this.state; if (state == State.NEW || state == State.ROLLBACK_ONLY) { return getTargetFile(miscTargetRoot, item); } else { throw new IllegalStateException(); // internal wrong usage, no i18n } }
java
{ "resource": "" }
q2327
IdentityPatchContext.createProcessedPatch
train
protected Patch createProcessedPatch(final Patch original) { // Process elements final List<PatchElement> elements = new ArrayList<PatchElement>(); // Process layers for (final PatchEntry entry : getLayers()) { final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications); elements.add(element); } // Process add-ons for (final PatchEntry entry : getAddOns()) { final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications); elements.add(element); } // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications); }
java
{ "resource": "" }
q2328
IdentityPatchContext.createRollbackPatch
train
protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) { // Process elements final List<PatchElement> elements = new ArrayList<PatchElement>(); // Process layers for (final PatchEntry entry : getLayers()) { final PatchElement element = createRollbackElement(entry); elements.add(element); } // Process add-ons for (final PatchEntry entry : getAddOns()) { final PatchElement element = createRollbackElement(entry); elements.add(element); } final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState(); final String name = installedIdentity.getIdentity().getName(); final IdentityImpl identity = new IdentityImpl(name, modification.getVersion()); if (patchType == Patch.PatchType.CUMULATIVE) { identity.setPatchType(Patch.PatchType.CUMULATIVE); identity.setResultingVersion(installedIdentity.getIdentity().getVersion()); } else if (patchType == Patch.PatchType.ONE_OFF) { identity.setPatchType(Patch.PatchType.ONE_OFF); } final List<ContentModification> modifications = identityEntry.rollbackActions; final Patch delegate = new PatchImpl(patchId, "rollback patch", identity, elements, modifications); return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity); }
java
{ "resource": "" }
q2329
IdentityPatchContext.getTargetFile
train
static File getTargetFile(final File root, final MiscContentItem item) { return PatchContentLoader.getMiscPath(root, item); }
java
{ "resource": "" }
q2330
IdentityPatchContext.createRollbackElement
train
protected static PatchElement createRollbackElement(final PatchEntry entry) { final PatchElement patchElement = entry.element; final String patchId; final Patch.PatchType patchType = patchElement.getProvider().getPatchType(); if (patchType == Patch.PatchType.CUMULATIVE) { patchId = entry.getCumulativePatchID(); } else { patchId = patchElement.getId(); } return createPatchElement(entry, patchId, entry.rollbackActions); }
java
{ "resource": "" }
q2331
IdentityPatchContext.createPatchElement
train
protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) { final PatchElement patchElement = entry.element; final PatchElementImpl element = new PatchElementImpl(patchId); element.setProvider(patchElement.getProvider()); // Add all the rollback actions element.getModifications().addAll(modifications); element.setDescription(patchElement.getDescription()); return element; }
java
{ "resource": "" }
q2332
IdentityPatchContext.backupConfiguration
train
void backupConfiguration() throws IOException { final String configuration = Constants.CONFIGURATION; final File a = new File(installedImage.getAppClientDir(), configuration); final File d = new File(installedImage.getDomainDir(), configuration); final File s = new File(installedImage.getStandaloneDir(), configuration); if (a.exists()) { final File ab = new File(configBackup, Constants.APP_CLIENT); backupDirectory(a, ab); } if (d.exists()) { final File db = new File(configBackup, Constants.DOMAIN); backupDirectory(d, db); } if (s.exists()) { final File sb = new File(configBackup, Constants.STANDALONE); backupDirectory(s, sb); } }
java
{ "resource": "" }
q2333
IdentityPatchContext.backupDirectory
train
static void backupDirectory(final File source, final File target) throws IOException { if (!target.exists()) { if (!target.mkdirs()) { throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath()); } } final File[] files = source.listFiles(CONFIG_FILTER); for (final File file : files) { final File t = new File(target, file.getName()); IoUtils.copyFile(file, t); } }
java
{ "resource": "" }
q2334
IdentityPatchContext.writePatch
train
static void writePatch(final Patch rollbackPatch, final File file) throws IOException { final File parent = file.getParentFile(); if (!parent.isDirectory()) { if (!parent.mkdirs() && !parent.exists()) { throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath()); } } try { try (final OutputStream os = new FileOutputStream(file)){ PatchXml.marshal(os, rollbackPatch); } } catch (XMLStreamException e) { throw new IOException(e); } }
java
{ "resource": "" }
q2335
CliCommandBuilder.setController
train
public CliCommandBuilder setController(final String hostname, final int port) { setController(formatAddress(null, hostname, port)); return this; }
java
{ "resource": "" }
q2336
CliCommandBuilder.setController
train
public CliCommandBuilder setController(final String protocol, final String hostname, final int port) { setController(formatAddress(protocol, hostname, port)); return this; }
java
{ "resource": "" }
q2337
CliCommandBuilder.setTimeout
train
public CliCommandBuilder setTimeout(final int timeout) { if (timeout > 0) { addCliArgument(CliArgument.TIMEOUT, Integer.toString(timeout)); } else { addCliArgument(CliArgument.TIMEOUT, null); } return this; }
java
{ "resource": "" }
q2338
Services.addServerExecutorDependency
train
@Deprecated public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) { return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector); }
java
{ "resource": "" }
q2339
AbstractMessageHandler.handleChannelClosed
train
public void handleChannelClosed(final Channel closed, final IOException e) { for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) { if (activeOperation.getChannel() == closed) { // Only call cancel, to also interrupt still active threads activeOperation.getResultHandler().cancel(); } } }
java
{ "resource": "" }
q2340
AbstractMessageHandler.awaitCompletion
train
@Override public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { long deadline = unit.toMillis(timeout) + System.currentTimeMillis(); lock.lock(); try { assert shutdown; while(activeCount != 0) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } condition.await(remaining, TimeUnit.MILLISECONDS); } boolean allComplete = activeCount == 0; if (!allComplete) { ProtocolLogger.ROOT_LOGGER.debugf("ActiveOperation(s) %s have not completed within %d %s", activeRequests.keySet(), timeout, unit); } return allComplete; } finally { lock.unlock(); } }
java
{ "resource": "" }
q2341
AbstractMessageHandler.registerActiveOperation
train
protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) { lock.lock(); try { // Check that we still allow registration // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests // TODO WFCORE-845 consider using an IllegalStateException for this //assert ! shutdown; final Integer operationId; if(id == null) { // If we did not get an operationId, create a new one operationId = operationIdManager.createBatchId(); } else { // Check that the operationId is not already taken if(! operationIdManager.lockBatchId(id)) { throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id); } operationId = id; } final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this); final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request); if(existing != null) { throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId); } ProtocolLogger.ROOT_LOGGER.tracef("Registered active operation %d", operationId); activeCount++; // condition.signalAll(); return request; } finally { lock.unlock(); } }
java
{ "resource": "" }
q2342
AbstractMessageHandler.getActiveOperation
train
protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) { return getActiveOperation(header.getBatchId()); }
java
{ "resource": "" }
q2343
AbstractMessageHandler.getActiveOperation
train
protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) { //noinspection unchecked return (ActiveOperation<T, A>) activeRequests.get(id); }
java
{ "resource": "" }
q2344
AbstractMessageHandler.cancelAllActiveOperations
train
protected List<Integer> cancelAllActiveOperations() { final List<Integer> operations = new ArrayList<Integer>(); for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) { activeOperation.asyncCancel(false); operations.add(activeOperation.getOperationId()); } return operations; }
java
{ "resource": "" }
q2345
AbstractMessageHandler.removeActiveOperation
train
protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) { final ActiveOperation<T, A> removed = removeUnderLock(id); if(removed != null) { for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) { final ActiveRequest<?, ?> request = requestEntry.getValue(); if(request.context == removed) { requests.remove(requestEntry.getKey()); } } } return removed; }
java
{ "resource": "" }
q2346
AbstractMessageHandler.safeWriteErrorResponse
train
protected static void safeWriteErrorResponse(final Channel channel, final ManagementProtocolHeader header, final Throwable error) { if(header.getType() == ManagementProtocol.TYPE_REQUEST) { try { writeErrorResponse(channel, (ManagementRequestHeader) header, error); } catch(IOException ioe) { ProtocolLogger.ROOT_LOGGER.tracef(ioe, "failed to write error response for %s on channel: %s", header, channel); } } }
java
{ "resource": "" }
q2347
AbstractMessageHandler.writeErrorResponse
train
protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException { final ManagementResponseHeader response = ManagementResponseHeader.create(header, error); final MessageOutputStream output = channel.writeMessage(); try { writeHeader(response, output); output.close(); } finally { StreamUtils.safeClose(output); } }
java
{ "resource": "" }
q2348
AbstractMessageHandler.writeHeader
train
protected static FlushableDataOutput writeHeader(final ManagementProtocolHeader header, final OutputStream os) throws IOException { final FlushableDataOutput output = FlushableDataOutputImpl.create(os); header.write(output); return output; }
java
{ "resource": "" }
q2349
AbstractMessageHandler.getFallbackHandler
train
protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) { return new ManagementRequestHandler<T, A>() { @Override public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException { final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId())); if(resultHandler.failed(error)) { safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error); } } }; }
java
{ "resource": "" }
q2350
PatchModuleInvalidationUtils.processFile
train
static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException { if (mode == PatchingTaskContext.Mode.APPLY) { if (ENABLE_INVALIDATION) { updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG); backup(context, file); } } else if (mode == PatchingTaskContext.Mode.ROLLBACK) { updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG); restore(context, file); } else { throw new IllegalStateException(); } }
java
{ "resource": "" }
q2351
PatchModuleInvalidationUtils.updateJar
train
private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException { final RandomAccessFile raf = new RandomAccessFile(file, "rw"); try { final FileChannel channel = raf.getChannel(); try { long pos = channel.size() - ENDLEN; final ScanContext context; if (newSig == CRIPPLED_ENDSIG) { context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN); } else if (newSig == GOOD_ENDSIG) { context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN); } else { context = null; } if (!validateEndRecord(file, channel, pos, endSig)) { pos = scanForEndSig(file, channel, context); } if (pos == -1) { if (context.state == State.NOT_FOUND) { // Don't fail patching if we cannot validate a valid zip PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath()); } return; } // Update the central directory record channel.position(pos); final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(newSig); buffer.flip(); while (buffer.hasRemaining()) { channel.write(buffer); } } finally { safeClose(channel); } } finally { safeClose(raf); } }
java
{ "resource": "" }
q2352
PatchModuleInvalidationUtils.validateEndRecord
train
private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException { try { channel.position(startEndRecord); final ByteBuffer endDirHeader = getByteBuffer(ENDLEN); read(endDirHeader, channel); if (endDirHeader.limit() < ENDLEN) { // Couldn't read the full end of central directory record header return false; } else if (getUnsignedInt(endDirHeader, 0) != endSig) { return false; } long pos = getUnsignedInt(endDirHeader, END_CENSTART); // TODO deal with Zip64 if (pos == ZIP64_MARKER) { return false; } ByteBuffer cdfhBuffer = getByteBuffer(CENLEN); read(cdfhBuffer, channel, pos); long header = getUnsignedInt(cdfhBuffer, 0); if (header == CENSIG) { long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET); long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ); if (firstLoc == 0) { // normal case -- first bytes are the first local file if (!validateLocalFileRecord(channel, 0, firstSize)) { return false; } } else { // confirm that firstLoc is indeed the first local file long fileFirstLoc = scanForLocSig(channel); if (firstLoc != fileFirstLoc) { if (fileFirstLoc == 0) { return false; } else { // scanForLocSig() found a LOCSIG, but not at position zero and not // at the expected position. // With a file like this, we can't tell if we're in a nested zip // or we're in an outer zip and had the bad luck to find random bytes // that look like LOCSIG. return false; } } } // At this point, endDirHeader points to the correct end of central dir record. // Just need to validate the record is complete, including any comment int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN); long commentEnd = startEndRecord + ENDLEN + commentLen; return commentEnd <= channel.size(); } return false; } catch (EOFException eof) { // pos or firstLoc weren't really positions and moved us to an invalid location return false; } }
java
{ "resource": "" }
q2353
PatchModuleInvalidationUtils.scanForEndSig
train
private static long scanForEndSig(final File file, final FileChannel channel, final ScanContext context) throws IOException { // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex ByteBuffer bb = getByteBuffer(CHUNK_SIZE); long start = channel.size(); long end = Math.max(0, start - MAX_REVERSE_SCAN); long channelPos = Math.max(0, start - CHUNK_SIZE); long lastChannelPos = channelPos; while (lastChannelPos >= end) { read(bb, channel, channelPos); int actualRead = bb.limit(); int bufferPos = actualRead - 1; while (bufferPos >= SIG_PATTERN_LENGTH) { // Following is based on the Boyer Moore algorithm but simplified to reflect // a) the pattern is static // b) the pattern has no repeating bytes int patternPos; for (patternPos = SIG_PATTERN_LENGTH - 1; patternPos >= 0 && context.matches(patternPos, bb.get(bufferPos - patternPos)); --patternPos) { // empty loop while bytes match } // Switch gives same results as checking the "good suffix array" in the Boyer Moore algorithm switch (patternPos) { case -1: { final State state = context.state; // Pattern matched. Confirm is this is the start of a valid end of central dir record long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1; if (validateEndRecord(file, channel, startEndRecord, context.getSig())) { if (state == State.FOUND) { return startEndRecord; } else { return -1; } } // wasn't a valid end record; continue scan bufferPos -= 4; break; } case 3: { // No bytes matched; the common case. // With our pattern, this is the only case where the Boyer Moore algorithm's "bad char array" may // produce a shift greater than the "good suffix array" (which would shift 1 byte) int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE; bufferPos -= BAD_BYTE_SKIP[idx]; break; } default: // 1 or more bytes matched bufferPos -= 4; } } // Move back a full chunk. If we didn't read a full chunk, that's ok, // it means we read all data and the outer while loop will terminate if (channelPos <= bufferPos) { break; } lastChannelPos = channelPos; channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos); } return -1; }
java
{ "resource": "" }
q2354
PatchModuleInvalidationUtils.scanForLocSig
train
private static long scanForLocSig(FileChannel channel) throws IOException { channel.position(0); ByteBuffer bb = getByteBuffer(CHUNK_SIZE); long end = channel.size(); while (channel.position() <= end) { read(bb, channel); int bufferPos = 0; while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) { // Following is based on the Boyer Moore algorithm but simplified to reflect // a) the size of the pattern is static // b) the pattern is static and has no repeating bytes int patternPos; for (patternPos = SIG_PATTERN_LENGTH - 1; patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos); --patternPos) { // empty loop while bytes match } // Outer switch gives same results as checking the "good suffix array" in the Boyer Moore algorithm switch (patternPos) { case -1: { // Pattern matched. Confirm is this is the start of a valid local file record long startLocRecord = channel.position() - bb.limit() + bufferPos; long currentPos = channel.position(); if (validateLocalFileRecord(channel, startLocRecord, -1)) { return startLocRecord; } // Restore position in case it shifted channel.position(currentPos); // wasn't a valid local file record; continue scan bufferPos += 4; break; } case 3: { // No bytes matched; the common case. // With our pattern, this is the only case where the Boyer Moore algorithm's "bad char array" may // produce a shift greater than the "good suffix array" (which would shift 1 byte) int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE; bufferPos += LOC_BAD_BYTE_SKIP[idx]; break; } default: // 1 or more bytes matched bufferPos += 4; } } } return -1; }
java
{ "resource": "" }
q2355
PatchModuleInvalidationUtils.validateLocalFileRecord
train
private static boolean validateLocalFileRecord(FileChannel channel, long startLocRecord, long compressedSize) throws IOException { ByteBuffer lfhBuffer = getByteBuffer(LOCLEN); read(lfhBuffer, channel, startLocRecord); if (lfhBuffer.limit() < LOCLEN || getUnsignedInt(lfhBuffer, 0) != LOCSIG) { return false; } if (compressedSize == -1) { // We can't further evaluate return true; } int fnLen = getUnsignedShort(lfhBuffer, LOC_FILENAMELEN); int extFieldLen = getUnsignedShort(lfhBuffer, LOC_EXTFLDLEN); long nextSigPos = startLocRecord + LOCLEN + compressedSize + fnLen + extFieldLen; read(lfhBuffer, channel, nextSigPos); long header = getUnsignedInt(lfhBuffer, 0); return header == LOCSIG || header == EXTSIG || header == CENSIG; }
java
{ "resource": "" }
q2356
PatchModuleInvalidationUtils.computeBadByteSkipArray
train
private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) { for (int a = 0; a < ALPHABET_SIZE; a++) { badByteArray[a] = pattern.length; } for (int j = 0; j < pattern.length - 1; j++) { badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1; } }
java
{ "resource": "" }
q2357
EmbeddedProcessFactory.createHostController
train
public static HostController createHostController(String jbossHomePath, String modulePath, String[] systemPackages, String[] cmdargs) { if (jbossHomePath == null || jbossHomePath.isEmpty()) { throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath); } File jbossHomeDir = new File(jbossHomePath); if (!jbossHomeDir.isDirectory()) { throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath); } return createHostController( Configuration.Builder.of(jbossHomeDir) .setModulePath(modulePath) .setSystemPackages(systemPackages) .setCommandArguments(cmdargs) .build() ); }
java
{ "resource": "" }
q2358
ServiceActivatorDependencyProcessor.deploy
train
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final ResourceRoot deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT); final ModuleSpecification moduleSpecification = phaseContext.getDeploymentUnit().getAttachment( Attachments.MODULE_SPECIFICATION); if(deploymentRoot == null) return; final ServicesAttachment servicesAttachments = phaseContext.getDeploymentUnit().getAttachment(Attachments.SERVICES); if(servicesAttachments != null && !servicesAttachments.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) { moduleSpecification.addSystemDependency(MSC_DEP); } }
java
{ "resource": "" }
q2359
ControlPoint.pause
train
public void pause(ServerActivityCallback requestCountListener) { if (paused) { throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused(); } this.paused = true; listenerUpdater.set(this, requestCountListener); if (activeRequestCountUpdater.get(this) == 0) { if (listenerUpdater.compareAndSet(this, requestCountListener, null)) { requestCountListener.done(); } } }
java
{ "resource": "" }
q2360
ControlPoint.resume
train
public void resume() { this.paused = false; ServerActivityCallback listener = listenerUpdater.get(this); if (listener != null) { listenerUpdater.compareAndSet(this, listener, null); } }
java
{ "resource": "" }
q2361
HostInfo.createLocalHostHostInfo
train
public static ModelNode createLocalHostHostInfo(final LocalHostControllerInfo hostInfo, final ProductConfig productConfig, final IgnoredDomainResourceRegistry ignoredResourceRegistry, final Resource hostModelResource) { final ModelNode info = new ModelNode(); info.get(NAME).set(hostInfo.getLocalHostName()); info.get(RELEASE_VERSION).set(Version.AS_VERSION); info.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME); info.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION); info.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION); info.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION); final String productName = productConfig.getProductName(); final String productVersion = productConfig.getProductVersion(); if(productName != null) { info.get(PRODUCT_NAME).set(productName); } if(productVersion != null) { info.get(PRODUCT_VERSION).set(productVersion); } ModelNode ignoredModel = ignoredResourceRegistry.getIgnoredResourcesAsModel(); if (ignoredModel.hasDefined(IGNORED_RESOURCE_TYPE)) { info.get(IGNORED_RESOURCES).set(ignoredModel.require(IGNORED_RESOURCE_TYPE)); } boolean ignoreUnaffectedServerGroups = hostInfo.isRemoteDomainControllerIgnoreUnaffectedConfiguration(); IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel(ignoreUnaffectedServerGroups, hostModelResource, info); return info; }
java
{ "resource": "" }
q2362
Environment.addModuleDir
train
public void addModuleDir(final String moduleDir) { if (moduleDir == null) { throw LauncherMessages.MESSAGES.nullParam("moduleDir"); } // Validate the path final Path path = Paths.get(moduleDir).normalize(); modulesDirs.add(path.toString()); }
java
{ "resource": "" }
q2363
Environment.getModulePaths
train
public String getModulePaths() { final StringBuilder result = new StringBuilder(); if (addDefaultModuleDir) { result.append(wildflyHome.resolve("modules").toString()); } if (!modulesDirs.isEmpty()) { if (addDefaultModuleDir) result.append(File.pathSeparator); for (Iterator<String> iterator = modulesDirs.iterator(); iterator.hasNext(); ) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(File.pathSeparator); } } } return result.toString(); }
java
{ "resource": "" }
q2364
ExistingChannelModelControllerClient.createAndAdd
train
public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) { final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler); handler.addHandlerFactory(client); return client; }
java
{ "resource": "" }
q2365
ExistingChannelModelControllerClient.createReceiving
train
public static ModelControllerClient createReceiving(final Channel channel, final ExecutorService executorService) { final ManagementClientChannelStrategy strategy = ManagementClientChannelStrategy.create(channel); final ManagementChannelHandler handler = new ManagementChannelHandler(strategy, executorService); final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler); handler.addHandlerFactory(client); channel.addCloseHandler(new CloseHandler<Channel>() { @Override public void handleClose(Channel closed, IOException exception) { handler.shutdown(); try { handler.awaitCompletion(1, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { handler.shutdownNow(); } } }); channel.receiveMessage(handler.getReceiver()); return client; }
java
{ "resource": "" }
q2366
UserPropertiesFileLoader.addLineContent
train
@Override protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException { // Is the line an empty comment "#" ? if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) { String nextLine = bufferedFileReader.readLine(); if (nextLine != null) { // Is the next line the realm name "#$REALM_NAME=" ? if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) { // Realm name block detected! // The next line must be and empty comment "#" bufferedFileReader.readLine(); // Avoid adding the realm block } else { // It's a user comment... content.add(line); content.add(nextLine); } } else { super.addLineContent(bufferedFileReader, content, line); } } else { super.addLineContent(bufferedFileReader, content, line); } }
java
{ "resource": "" }
q2367
OperationDefinition.validateOperation
train
@Deprecated public void validateOperation(final ModelNode operation) throws OperationFailedException { if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) { ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(), PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString()); } for (AttributeDefinition ad : this.parameters) { ad.validateOperation(operation); } }
java
{ "resource": "" }
q2368
OperationDefinition.validateAndSet
train
@SuppressWarnings("deprecation") @Deprecated public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException { validateOperation(operationObject); for (AttributeDefinition ad : this.parameters) { ad.validateAndSet(operationObject, model); } }
java
{ "resource": "" }
q2369
BasicArtifactProcessor.getHandlerForArtifact
train
<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) { return handlers.get(artifact); }
java
{ "resource": "" }
q2370
CapabilityResolutionContext.getAttachment
train
public <V> V getAttachment(final AttachmentKey<V> key) { assert key != null; return key.cast(contextAttachments.get(key)); }
java
{ "resource": "" }
q2371
CapabilityResolutionContext.attach
train
public <V> V attach(final AttachmentKey<V> key, final V value) { assert key != null; return key.cast(contextAttachments.put(key, value)); }
java
{ "resource": "" }
q2372
CapabilityResolutionContext.attachIfAbsent
train
public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) { assert key != null; return key.cast(contextAttachments.putIfAbsent(key, value)); }
java
{ "resource": "" }
q2373
CapabilityResolutionContext.detach
train
public <V> V detach(final AttachmentKey<V> key) { assert key != null; return key.cast(contextAttachments.remove(key)); }
java
{ "resource": "" }
q2374
InterfacesXml.writeInterfaceCriteria
train
private void writeInterfaceCriteria(final XMLExtendedStreamWriter writer, final ModelNode subModel, final boolean nested) throws XMLStreamException { for (final Property property : subModel.asPropertyList()) { if (property.getValue().isDefined()) { writeInterfaceCriteria(writer, property, nested); } } }
java
{ "resource": "" }
q2375
ConfigurationPersisterFactory.createHostXmlConfigurationPersister
train
public static ExtensibleConfigurationPersister createHostXmlConfigurationPersister(final ConfigurationFile file, final HostControllerEnvironment environment, final ExecutorService executorService, final ExtensionRegistry hostExtensionRegistry, final LocalHostControllerInfo localHostControllerInfo) { String defaultHostname = localHostControllerInfo.getLocalHostName(); if (environment.getRunningModeControl().isReloaded()) { if (environment.getRunningModeControl().getReloadHostName() != null) { defaultHostname = environment.getRunningModeControl().getReloadHostName(); } } HostXml hostXml = new HostXml(defaultHostname, environment.getRunningModeControl().getRunningMode(), environment.isUseCachedDc(), Module.getBootModuleLoader(), executorService, hostExtensionRegistry); BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), "host"), hostXml, hostXml, false); for (Namespace namespace : Namespace.domainValues()) { if (!namespace.equals(Namespace.CURRENT)) { persister.registerAdditionalRootElement(new QName(namespace.getUriString(), "host"), hostXml); } } hostExtensionRegistry.setWriterRegistry(persister); return persister; }
java
{ "resource": "" }
q2376
ConfigurationPersisterFactory.createDomainXmlConfigurationPersister
train
public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) { DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry); boolean suppressLoad = false; ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy(); final boolean isReloaded = environment.getRunningModeControl().isReloaded(); if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) { throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName()); } if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) { suppressLoad = true; } BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), "domain"), domainXml, domainXml, suppressLoad); for (Namespace namespace : Namespace.domainValues()) { if (!namespace.equals(Namespace.CURRENT)) { persister.registerAdditionalRootElement(new QName(namespace.getUriString(), "domain"), domainXml); } } extensionRegistry.setWriterRegistry(persister); return persister; }
java
{ "resource": "" }
q2377
ConfigurationPersisterFactory.createTransientDomainXmlConfigurationPersister
train
public static ExtensibleConfigurationPersister createTransientDomainXmlConfigurationPersister(ExecutorService executorService, ExtensionRegistry extensionRegistry) { DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry); ExtensibleConfigurationPersister persister = new NullConfigurationPersister(domainXml); extensionRegistry.setWriterRegistry(persister); return persister; }
java
{ "resource": "" }
q2378
PatchingTasks.apply
train
static void apply(final String patchId, final Collection<ContentModification> modifications, final PatchEntry patchEntry, final ContentItemFilter filter) { for (final ContentModification modification : modifications) { final ContentItem item = modification.getItem(); // Check if we accept the item if (!filter.accepts(item)) { continue; } final Location location = new Location(item); final ContentEntry contentEntry = new ContentEntry(patchId, modification); ContentTaskDefinition definition = patchEntry.get(location); if (definition == null) { definition = new ContentTaskDefinition(location, contentEntry, false); patchEntry.put(location, definition); } else { definition.setTarget(contentEntry); } } }
java
{ "resource": "" }
q2379
ServiceRemoveStepHandler.serviceName
train
protected ServiceName serviceName(final String name) { return baseServiceName != null ? baseServiceName.append(name) : null; }
java
{ "resource": "" }
q2380
ModuleNameTabCompleter.subModuleExists
train
private boolean subModuleExists(File dir) { if (isSlotDirectory(dir)) { return true; } else { File[] children = dir.listFiles(File::isDirectory); for (File child : children) { if (subModuleExists(child)) { return true; } } } return false; }
java
{ "resource": "" }
q2381
ModuleNameTabCompleter.tail
train
private String tail(String moduleName) { if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) { return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1); } else { return ""; } }
java
{ "resource": "" }
q2382
HostControllerClient.resolveBootUpdates
train
void resolveBootUpdates(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception { connection.openConnection(controller, callback); // Keep a reference to the the controller this.controller = controller; }
java
{ "resource": "" }
q2383
VaultConfig.loadExternalFile
train
static VaultConfig loadExternalFile(File f) throws XMLStreamException { if(f == null) { throw new IllegalArgumentException("File is null"); } if(!f.exists()) { throw new XMLStreamException("Failed to locate vault file " + f.getAbsolutePath()); } final VaultConfig config = new VaultConfig(); BufferedInputStream input = null; try { final XMLMapper mapper = XMLMapper.Factory.create(); final XMLElementReader<VaultConfig> reader = new ExternalVaultConfigReader(); mapper.registerRootElement(new QName(VAULT), reader); FileInputStream is = new FileInputStream(f); input = new BufferedInputStream(is); XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(input); mapper.parseDocument(config, streamReader); streamReader.close(); } catch(FileNotFoundException e) { throw new XMLStreamException("Vault file not found", e); } catch(XMLStreamException t) { throw t; } finally { StreamUtils.safeClose(input); } return config; }
java
{ "resource": "" }
q2384
VaultConfig.readVaultElement_3_0
train
static VaultConfig readVaultElement_3_0(XMLExtendedStreamReader reader, Namespace expectedNs) throws XMLStreamException { final VaultConfig config = new VaultConfig(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final String value = reader.getAttributeValue(i); String name = reader.getAttributeLocalName(i); if (name.equals(CODE)){ config.code = value; } else if (name.equals(MODULE)){ config.module = value; } else { unexpectedVaultAttribute(reader.getAttributeLocalName(i), reader); } } if (config.code == null && config.module != null){ throw new XMLStreamException("Attribute 'module' was specified without an attribute" + " 'code' for element '" + VAULT + "' at " + reader.getLocation()); } readVaultOptions(reader, config); return config; }
java
{ "resource": "" }
q2385
RejectExpressionValuesTransformer.checkModel
train
private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException { final Set<String> attributes = new HashSet<String>(); AttributeTransformationRequirementChecker checker; for (final String attribute : attributeNames) { if (model.hasDefined(attribute)) { if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) { if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) { attributes.add(attribute); } } else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) { attributes.add(attribute); } } } return attributes; }
java
{ "resource": "" }
q2386
OperationDialog.setValue
train
public void setValue(String propName, Object value) { for (RequestProp prop : props) { if (prop.getName().equals(propName)) { JComponent valComp = prop.getValueComponent(); if (valComp instanceof JTextComponent) { ((JTextComponent)valComp).setText(value.toString()); } if (valComp instanceof AbstractButton) { ((AbstractButton)valComp).setSelected((Boolean)value); } if (valComp instanceof JComboBox) { ((JComboBox)valComp).setSelectedItem(value); } return; } } }
java
{ "resource": "" }
q2387
SecurityPropertiesWriteHandler.doDifference
train
static void doDifference( Map<String, String> left, Map<String, String> right, Map<String, String> onlyOnLeft, Map<String, String> onlyOnRight, Map<String, String> updated ) { onlyOnRight.clear(); onlyOnRight.putAll(right); for (Map.Entry<String, String> entry : left.entrySet()) { String leftKey = entry.getKey(); String leftValue = entry.getValue(); if (right.containsKey(leftKey)) { String rightValue = onlyOnRight.remove(leftKey); if (!leftValue.equals(rightValue)) { updated.put(leftKey, leftValue); } } else { onlyOnLeft.put(leftKey, leftValue); } } }
java
{ "resource": "" }
q2388
OutboundSocketBinding.close
train
public void close() throws IOException { final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name); if (binding == null) { return; } binding.close(); }
java
{ "resource": "" }
q2389
Logging.requiresReload
train
public static boolean requiresReload(final Set<Flag> flags) { return flags.contains(Flag.RESTART_ALL_SERVICES) || flags.contains(Flag.RESTART_RESOURCE_SERVICES); }
java
{ "resource": "" }
q2390
InstalledIdentityImpl.updateState
train
@Override protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) { final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState(); this.identity = new Identity() { @Override public String getVersion() { return modification.getVersion(); } @Override public String getName() { return name; } @Override public TargetInfo loadTargetInfo() throws IOException { return identityInfo; } @Override public DirectoryStructure getDirectoryStructure() { return modification.getDirectoryStructure(); } }; this.allPatches = Collections.unmodifiableList(modification.getAllPatches()); this.layers.clear(); for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) { final String layerName = entry.getKey(); final MutableTargetImpl target = entry.getValue(); putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure())); } this.addOns.clear(); for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) { final String addOnName = entry.getKey(); final MutableTargetImpl target = entry.getValue(); putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure())); } }
java
{ "resource": "" }
q2391
AffectedDeploymentOverlay.listAllLinks
train
public static Set<String> listAllLinks(OperationContext context, String overlay) { Set<String> serverGoupNames = listServerGroupsReferencingOverlay(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS), overlay); Set<String> links = new HashSet<>(); for (String serverGoupName : serverGoupNames) { links.addAll(listLinks(context, PathAddress.pathAddress( PathElement.pathElement(SERVER_GROUP, serverGoupName), PathElement.pathElement(DEPLOYMENT_OVERLAY, overlay)))); } return links; }
java
{ "resource": "" }
q2392
AffectedDeploymentOverlay.listLinks
train
public static Set<String> listLinks(OperationContext context, PathAddress overlayAddress) { Resource overlayResource = context.readResourceFromRoot(overlayAddress); if (overlayResource.hasChildren(DEPLOYMENT)) { return overlayResource.getChildrenNames(DEPLOYMENT); } return Collections.emptySet(); }
java
{ "resource": "" }
q2393
AffectedDeploymentOverlay.redeployDeployments
train
public static void redeployDeployments(OperationContext context, PathAddress deploymentsRootAddress, Set<String> deploymentNames) throws OperationFailedException { for (String deploymentName : deploymentNames) { PathAddress address = deploymentsRootAddress.append(DEPLOYMENT, deploymentName); OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(address, REDEPLOY); ModelNode operation = addRedeployStep(address); ServerLogger.AS_ROOT_LOGGER.debugf("Redeploying %s at address %s with handler %s", deploymentName, address, handler); assert handler != null; assert operation.isDefined(); context.addStep(operation, handler, OperationContext.Stage.MODEL); } }
java
{ "resource": "" }
q2394
AffectedDeploymentOverlay.redeployLinksAndTransformOperation
train
public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException { Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames); Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create(); if (deploymentNames.isEmpty()) { for (String s : runtimeNames) { ServerLogger.ROOT_LOGGER.debugf("We haven't found any deployment for %s in server-group %s", s, deploymentsRootAddress.getLastElement().getValue()); } } if(removeOperation != null) { opBuilder.addStep(removeOperation); } for (String deploymentName : deploymentNames) { opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName))); } List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS); if (transformers == null) { context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>()); } final ModelNode slave = opBuilder.build().getOperation(); transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress())); }
java
{ "resource": "" }
q2395
AffectedDeploymentOverlay.listDeployments
train
public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) { Set<Pattern> set = new HashSet<>(); for (String wildcardExpr : runtimeNames) { Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr); set.add(pattern); } return listDeploymentNames(deploymentRootResource, set); }
java
{ "resource": "" }
q2396
CommandExecutor.execute
train
public void execute(CommandHandler handler, int timeout, TimeUnit unit) throws CommandLineException, InterruptedException, ExecutionException, TimeoutException { ExecutableBuilder builder = new ExecutableBuilder() { CommandContext c = newTimeoutCommandContext(ctx); @Override public Executable build() { return () -> { handler.handle(c); }; } @Override public CommandContext getCommandContext() { return c; } }; execute(builder, timeout, unit); }
java
{ "resource": "" }
q2397
CommandExecutor.execute
train
void execute(ExecutableBuilder builder, int timeout, TimeUnit unit) throws CommandLineException, InterruptedException, ExecutionException, TimeoutException { Future<Void> task = executorService.submit(() -> { builder.build().execute(); return null; }); try { if (timeout <= 0) { //Synchronous task.get(); } else { // Guarded execution try { task.get(timeout, unit); } catch (TimeoutException ex) { // First make the context unusable CommandContext c = builder.getCommandContext(); if (c instanceof TimeoutCommandContext) { ((TimeoutCommandContext) c).timeout(); } // Then cancel the task. task.cancel(true); throw ex; } } } catch (InterruptedException ex) { // Could have been interrupted by user (Ctrl-C) Thread.currentThread().interrupt(); cancelTask(task, builder.getCommandContext(), null); // Interrupt running operation. CommandContext c = builder.getCommandContext(); if (c instanceof TimeoutCommandContext) { ((TimeoutCommandContext) c).interrupted(); } throw ex; } }
java
{ "resource": "" }
q2398
ArgumentWithValue.getOriginalValue
train
public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException { String value = null; if(parsedLine.hasProperties()) { if(index >= 0) { List<String> others = parsedLine.getOtherProperties(); if(others.size() > index) { return others.get(index); } } value = parsedLine.getPropertyValue(fullName); if(value == null && shortName != null) { value = parsedLine.getPropertyValue(shortName); } } if(required && value == null && !isPresent(parsedLine)) { StringBuilder buf = new StringBuilder(); buf.append("Required argument "); buf.append('\'').append(fullName).append('\''); buf.append(" is missing."); throw new CommandFormatException(buf.toString()); } return value; }
java
{ "resource": "" }
q2399
SystemExiter.logBeforeExit
train
public static void logBeforeExit(ExitLogger logger) { try { if (logged.compareAndSet(false, true)) { logger.logExit(); } } catch (Throwable ignored){ // ignored } }
java
{ "resource": "" }