_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3 values | text stringlengths 73 34.1k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q2600 | ManagementRemotingServices.installManagementChannelServices | train | public static void installManagementChannelServices(
final ServiceTarget serviceTarget,
final ServiceName endpointName,
final AbstractModelControllerOperationHandlerFactoryService operationHandlerService,
final ServiceName modelControllerName,
final String channelName,
final ServiceName executorServiceName,
final ServiceName scheduledExecutorServiceName) {
final OptionMap options = OptionMap.EMPTY;
final ServiceName operationHandlerName = endpointName.append(channelName).append(ModelControllerClientOperationHandlerFactoryService.OPERATION_HANDLER_NAME_SUFFIX);
serviceTarget.addService(operationHandlerName, operationHandlerService)
.addDependency(modelControllerName, ModelController.class, operationHandlerService.getModelControllerInjector())
.addDependency(executorServiceName, ExecutorService.class, operationHandlerService.getExecutorInjector())
.addDependency(scheduledExecutorServiceName, ScheduledExecutorService.class, operationHandlerService.getScheduledExecutorInjector())
.setInitialMode(ACTIVE)
.install();
installManagementChannelOpenListenerService(serviceTarget, endpointName, channelName, operationHandlerName, options, false);
} | java | {
"resource": ""
} |
q2601 | ManagementRemotingServices.isManagementResourceRemoveable | train | public static void isManagementResourceRemoveable(OperationContext context, PathAddress otherManagementEndpoint) throws OperationFailedException {
ModelNode remotingConnector;
try {
remotingConnector = context.readResourceFromRoot(
PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, "jmx"), PathElement.pathElement("remoting-connector", "jmx")), false).getModel();
} catch (Resource.NoSuchResourceException ex) {
return;
}
if (!remotingConnector.hasDefined(USE_MGMT_ENDPOINT) ||
(remotingConnector.hasDefined(USE_MGMT_ENDPOINT) && context.resolveExpressions(remotingConnector.get(USE_MGMT_ENDPOINT)).asBoolean(true))) {
try {
context.readResourceFromRoot(otherManagementEndpoint, false);
} catch (NoSuchElementException ex) {
throw RemotingLogger.ROOT_LOGGER.couldNotRemoveResource(context.getCurrentAddress());
}
}
} | java | {
"resource": ""
} |
q2602 | CertificateChainAttributeDefinitions.writeCertificates | train | static void writeCertificates(final ModelNode result, final Certificate[] certificates) throws CertificateEncodingException, NoSuchAlgorithmException {
if (certificates != null) {
for (Certificate current : certificates) {
ModelNode certificate = new ModelNode();
writeCertificate(certificate, current);
result.add(certificate);
}
}
} | java | {
"resource": ""
} |
q2603 | ModelControllerMBeanHelper.setQueryExpServer | train | private static MBeanServer setQueryExpServer(QueryExp query, MBeanServer toSet) {
// We assume the QueryExp is a QueryEval subclass or uses the QueryEval thread local
// mechanism to store any existing MBeanServer. If that's not the case we have no
// way to access the old mbeanserver to let us restore it
MBeanServer result = QueryEval.getMBeanServer();
query.setMBeanServer(toSet);
return result;
} | java | {
"resource": ""
} |
q2604 | ModelControllerMBeanHelper.toPathAddress | train | PathAddress toPathAddress(final ObjectName name) {
return ObjectNameAddressUtil.toPathAddress(rootObjectInstance.getObjectName(), getRootResourceAndRegistration().getRegistration(), name);
} | java | {
"resource": ""
} |
q2605 | TransactionalProtocolHandlers.createClient | train | public static TransactionalProtocolClient createClient(final ManagementChannelHandler channelAssociation) {
final TransactionalProtocolClientImpl client = new TransactionalProtocolClientImpl(channelAssociation);
channelAssociation.addHandlerFactory(client);
return client;
} | java | {
"resource": ""
} |
q2606 | TransactionalProtocolHandlers.wrap | train | public static TransactionalProtocolClient.Operation wrap(final ModelNode operation, final OperationMessageHandler messageHandler, final OperationAttachments attachments) {
return new TransactionalOperationImpl(operation, messageHandler, attachments);
} | java | {
"resource": ""
} |
q2607 | TransactionalProtocolHandlers.executeBlocking | train | public static TransactionalProtocolClient.PreparedOperation<TransactionalProtocolClient.Operation> executeBlocking(final ModelNode operation, TransactionalProtocolClient client) throws IOException, InterruptedException {
final BlockingQueueOperationListener<TransactionalProtocolClient.Operation> listener = new BlockingQueueOperationListener<>();
client.execute(listener, operation, OperationMessageHandler.DISCARD, OperationAttachments.EMPTY);
return listener.retrievePreparedOperation();
} | java | {
"resource": ""
} |
q2608 | ServerLogsTableModel.init | train | private void init() {
if (initialized.compareAndSet(false, true)) {
final RowSorter<? extends TableModel> rowSorter = table.getRowSorter();
rowSorter.toggleSortOrder(1); // sort by date
rowSorter.toggleSortOrder(1); // descending
final TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(1).setCellRenderer(dateRenderer);
columnModel.getColumn(2).setCellRenderer(sizeRenderer);
}
} | java | {
"resource": ""
} |
q2609 | DeleteOp.execute | train | public void execute() throws IOException {
try {
prepare();
boolean commitResult = commit();
if (commitResult == false) {
throw PatchLogger.ROOT_LOGGER.failedToDeleteBackup();
}
} catch (PrepareException pe){
rollback();
throw PatchLogger.ROOT_LOGGER.failedToDelete(pe.getPath());
}
} | java | {
"resource": ""
} |
q2610 | GitRepository.rollback | train | public void rollback() throws GitAPIException {
try (Git git = getGit()) {
git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();
}
} | java | {
"resource": ""
} |
q2611 | GitRepository.commit | train | public void commit(String msg) throws GitAPIException {
try (Git git = getGit()) {
Status status = git.status().call();
if (!status.isClean()) {
git.commit().setMessage(msg).setAll(true).setNoVerify(true).call();
}
}
} | java | {
"resource": ""
} |
q2612 | ExtensionAddHandler.initializeExtension | train | static void initializeExtension(ExtensionRegistry extensionRegistry, String module,
ManagementResourceRegistration rootRegistration,
ExtensionRegistryType extensionRegistryType) {
try {
boolean unknownModule = false;
boolean initialized = false;
for (Extension extension : Module.loadServiceFromCallerModuleLoader(module, Extension.class)) {
ClassLoader oldTccl = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(extension.getClass());
try {
if (unknownModule || !extensionRegistry.getExtensionModuleNames().contains(module)) {
// This extension wasn't handled by the standalone.xml or domain.xml parsing logic, so we
// need to initialize its parsers so we can display what XML namespaces it supports
extensionRegistry.initializeParsers(extension, module, null);
// AS7-6190 - ensure we initialize parsers for other extensions from this module
// now that we know the registry was unaware of the module
unknownModule = true;
}
extension.initialize(extensionRegistry.getExtensionContext(module, rootRegistration, extensionRegistryType));
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
}
initialized = true;
}
if (!initialized) {
throw ControllerLogger.ROOT_LOGGER.notFound("META-INF/services/", Extension.class.getName(), module);
}
} catch (ModuleNotFoundException e) {
// Treat this as a user mistake, e.g. incorrect module name.
// Throw OFE so post-boot it only gets logged at DEBUG.
throw ControllerLogger.ROOT_LOGGER.extensionModuleNotFound(e, module);
} catch (ModuleLoadException e) {
// The module is there but can't be loaded. Treat this as an internal problem.
// Throw a runtime exception so it always gets logged at ERROR in the server log with stack trace details.
throw ControllerLogger.ROOT_LOGGER.extensionModuleLoadingFailure(e, module);
}
} | java | {
"resource": ""
} |
q2613 | PathManagerService.addDependent | train | private void addDependent(String pathName, String relativeTo) {
if (relativeTo != null) {
Set<String> dependents = dependenctRelativePaths.get(relativeTo);
if (dependents == null) {
dependents = new HashSet<String>();
dependenctRelativePaths.put(relativeTo, dependents);
}
dependents.add(pathName);
}
} | java | {
"resource": ""
} |
q2614 | PathManagerService.getAllDependents | train | private void getAllDependents(Set<PathEntry> result, String name) {
Set<String> depNames = dependenctRelativePaths.get(name);
if (depNames == null) {
return;
}
for (String dep : depNames) {
PathEntry entry = pathEntries.get(dep);
if (entry != null) {
result.add(entry);
getAllDependents(result, dep);
}
}
} | java | {
"resource": ""
} |
q2615 | JvmOptionsElement.addOption | train | void addOption(final String value) {
Assert.checkNotNullParam("value", value);
synchronized (options) {
options.add(value);
}
} | java | {
"resource": ""
} |
q2616 | AttachmentKey.create | train | @SuppressWarnings("unchecked")
public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {
return new SimpleAttachmentKey(valueClass);
} | java | {
"resource": ""
} |
q2617 | PatchContentLoader.openContentStream | train | InputStream openContentStream(final ContentItem item) throws IOException {
final File file = getFile(item);
if (file == null) {
throw new IllegalStateException();
}
return new FileInputStream(file);
} | java | {
"resource": ""
} |
q2618 | SSLSecurityBuilder.buildExecutableRequest | train | public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {
try {
for (FailureDescProvider h : providers) {
effectiveProviders.add(h);
}
// In case some key-store needs to be persisted
for (String ks : ksToStore) {
composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));
effectiveProviders.add(new FailureDescProvider() {
@Override
public String stepFailedDescription() {
return "Storing the key-store " + ksToStore;
}
});
}
// Final steps
for (int i = 0; i < finalSteps.size(); i++) {
composite.get(Util.STEPS).add(finalSteps.get(i));
effectiveProviders.add(finalProviders.get(i));
}
return composite;
} catch (Exception ex) {
try {
failureOccured(ctx, null);
} catch (Exception ex2) {
ex.addSuppressed(ex2);
}
throw ex;
}
} | java | {
"resource": ""
} |
q2619 | ManifestAttachmentProcessor.deploy | train | @Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
for (ResourceRoot resourceRoot : resourceRoots) {
if (IgnoreMetaInfMarker.isIgnoreMetaInf(resourceRoot)) {
continue;
}
Manifest manifest = getManifest(resourceRoot);
if (manifest != null)
resourceRoot.putAttachment(Attachments.MANIFEST, manifest);
}
} | java | {
"resource": ""
} |
q2620 | MapperParser.getSimpleMapperParser | train | private PersistentResourceXMLDescription getSimpleMapperParser() {
if (version.equals(Version.VERSION_1_0)) {
return simpleMapperParser_1_0;
} else if (version.equals(Version.VERSION_1_1)) {
return simpleMapperParser_1_1;
}
return simpleMapperParser;
} | java | {
"resource": ""
} |
q2621 | DeploymentUtils.getTopDeploymentUnit | train | public static DeploymentUnit getTopDeploymentUnit(DeploymentUnit unit) {
Assert.checkNotNullParam("unit", unit);
DeploymentUnit parent = unit.getParent();
while (parent != null) {
unit = parent;
parent = unit.getParent();
}
return unit;
} | java | {
"resource": ""
} |
q2622 | RemoteDomainConnection.openConnection | train | protected Connection openConnection() throws IOException {
// Perhaps this can just be done once?
CallbackHandler callbackHandler = null;
SSLContext sslContext = null;
if (realm != null) {
sslContext = realm.getSSLContext();
CallbackHandlerFactory handlerFactory = realm.getSecretCallbackHandlerFactory();
if (handlerFactory != null) {
String username = this.username != null ? this.username : localHostName;
callbackHandler = handlerFactory.getCallbackHandler(username);
}
}
final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);
config.setCallbackHandler(callbackHandler);
config.setSslContext(sslContext);
config.setUri(uri);
AuthenticationContext authenticationContext = this.authenticationContext != null ? this.authenticationContext : AuthenticationContext.captureCurrent();
// Connect
try {
return authenticationContext.run((PrivilegedExceptionAction<Connection>) () -> ProtocolConnectionUtils.connectSync(config));
} catch (PrivilegedActionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
throw new IOException(e);
}
} | java | {
"resource": ""
} |
q2623 | RemoteDomainConnection.applyDomainModel | train | boolean applyDomainModel(ModelNode result) {
if(! result.hasDefined(ModelDescriptionConstants.RESULT)) {
return false;
}
final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList();
return callback.applyDomainModel(bootOperations);
} | java | {
"resource": ""
} |
q2624 | ProcessHelper.addShutdownHook | train | public static Thread addShutdownHook(final Process process) {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
if (process != null) {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
thread.setDaemon(true);
Runtime.getRuntime().addShutdownHook(thread);
return thread;
} | java | {
"resource": ""
} |
q2625 | OrderedChildTypesAttachment.addOrderedChildResourceTypes | train | public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {
Set<String> orderedChildTypes = resource.getOrderedChildTypes();
if (orderedChildTypes.size() > 0) {
orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());
}
} | java | {
"resource": ""
} |
q2626 | DeploymentPlanResultImpl.buildServerGroupResults | train | private static Map<String, ServerGroupDeploymentPlanResult> buildServerGroupResults(Map<UUID, DeploymentActionResult> deploymentActionResults) {
Map<String, ServerGroupDeploymentPlanResult> serverGroupResults = new HashMap<String, ServerGroupDeploymentPlanResult>();
for (Map.Entry<UUID, DeploymentActionResult> entry : deploymentActionResults.entrySet()) {
UUID actionId = entry.getKey();
DeploymentActionResult actionResult = entry.getValue();
Map<String, ServerGroupDeploymentActionResult> actionResultsByServerGroup = actionResult.getResultsByServerGroup();
for (ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup.values()) {
String serverGroupName = serverGroupActionResult.getServerGroupName();
ServerGroupDeploymentPlanResultImpl sgdpr = (ServerGroupDeploymentPlanResultImpl) serverGroupResults.get(serverGroupName);
if (sgdpr == null) {
sgdpr = new ServerGroupDeploymentPlanResultImpl(serverGroupName);
serverGroupResults.put(serverGroupName, sgdpr);
}
for (Map.Entry<String, ServerUpdateResult> serverEntry : serverGroupActionResult.getResultByServer().entrySet()) {
String serverName = serverEntry.getKey();
ServerUpdateResult sud = serverEntry.getValue();
ServerDeploymentPlanResultImpl sdpr = (ServerDeploymentPlanResultImpl) sgdpr.getServerResult(serverName);
if (sdpr == null) {
sdpr = new ServerDeploymentPlanResultImpl(serverName);
sgdpr.storeServerResult(serverName, sdpr);
}
sdpr.storeServerUpdateResult(actionId, sud);
}
}
}
return serverGroupResults;
} | java | {
"resource": ""
} |
q2627 | AbstractTransformationDescriptionBuilder.buildDefault | train | protected TransformationDescription buildDefault(final DiscardPolicy discardPolicy, boolean inherited, final AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry, List<String> discardedOperations) {
// Build attribute rules
final Map<String, AttributeTransformationDescription> attributes = registry.buildAttributes();
// Create operation transformers
final Map<String, OperationTransformer> operations = buildOperationTransformers(registry);
// Process children
final List<TransformationDescription> children = buildChildren();
if (discardPolicy == DiscardPolicy.NEVER) {
// TODO override more global operations?
if(! operations.containsKey(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) {
operations.put(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, OperationTransformationRules.createWriteOperation(attributes));
}
if(! operations.containsKey(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION)) {
operations.put(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, OperationTransformationRules.createUndefinedOperation(attributes));
}
}
// Create the description
Set<String> discarded = new HashSet<>();
discarded.addAll(discardedOperations);
return new TransformingDescription(pathElement, pathAddressTransformer, discardPolicy, inherited,
resourceTransformer, attributes, operations, children, discarded, dynamicDiscardPolicy);
} | java | {
"resource": ""
} |
q2628 | AbstractTransformationDescriptionBuilder.buildOperationTransformers | train | protected Map<String, OperationTransformer> buildOperationTransformers(AttributeTransformationDescriptionBuilderImpl.AttributeTransformationDescriptionBuilderRegistry registry) {
final Map<String, OperationTransformer> operations = new HashMap<String, OperationTransformer>();
for(final Map.Entry<String, OperationTransformationEntry> entry: operationTransformers.entrySet()) {
final OperationTransformer transformer = entry.getValue().getOperationTransformer(registry);
operations.put(entry.getKey(), transformer);
}
return operations;
} | java | {
"resource": ""
} |
q2629 | AbstractTransformationDescriptionBuilder.buildChildren | train | protected List<TransformationDescription> buildChildren() {
if(children.isEmpty()) {
return Collections.emptyList();
}
final List<TransformationDescription> children = new ArrayList<TransformationDescription>();
for(final TransformationDescriptionBuilder builder : this.children) {
children.add(builder.build());
}
return children;
} | java | {
"resource": ""
} |
q2630 | EndpointConfigFactory.create | train | @Deprecated
public static OptionMap create(final ExpressionResolver resolver, final ModelNode model, final OptionMap defaults) throws OperationFailedException {
final OptionMap map = OptionMap.builder()
.addAll(defaults)
.set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())
.set(Options.WORKER_TASK_CORE_THREADS, RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.resolveModelAttribute(resolver, model).asInt())
.set(Options.WORKER_TASK_KEEPALIVE, RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.resolveModelAttribute(resolver, model).asInt())
.set(Options.WORKER_TASK_LIMIT, RemotingSubsystemRootResource.WORKER_TASK_LIMIT.resolveModelAttribute(resolver, model).asInt())
.set(Options.WORKER_TASK_MAX_THREADS, RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.resolveModelAttribute(resolver, model).asInt())
.set(Options.WORKER_WRITE_THREADS, RemotingSubsystemRootResource.WORKER_WRITE_THREADS.resolveModelAttribute(resolver, model).asInt())
.set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())
.getMap();
return map;
} | java | {
"resource": ""
} |
q2631 | ElytronSubsystemParser2_0.getParserDescription | train | @Override
public PersistentResourceXMLDescription getParserDescription() {
return PersistentResourceXMLDescription.builder(ElytronExtension.SUBSYSTEM_PATH, getNameSpace())
.addAttribute(ElytronDefinition.DEFAULT_AUTHENTICATION_CONTEXT)
.addAttribute(ElytronDefinition.INITIAL_PROVIDERS)
.addAttribute(ElytronDefinition.FINAL_PROVIDERS)
.addAttribute(ElytronDefinition.DISALLOWED_PROVIDERS)
.addAttribute(ElytronDefinition.SECURITY_PROPERTIES, new AttributeParsers.PropertiesParser(null, SECURITY_PROPERTY, true), new AttributeMarshallers.PropertiesAttributeMarshaller(null, SECURITY_PROPERTY, true))
.addChild(getAuthenticationClientParser())
.addChild(getProviderParser())
.addChild(getAuditLoggingParser())
.addChild(getDomainParser())
.addChild(getRealmParser())
.addChild(getCredentialSecurityFactoryParser())
.addChild(getMapperParser())
.addChild(getHttpParser())
.addChild(getSaslParser())
.addChild(getTlsParser())
.addChild(decorator(CREDENTIAL_STORES).addChild(new CredentialStoreParser().parser))
.addChild(getDirContextParser())
.addChild(getPolicyParser())
.build();
} | java | {
"resource": ""
} |
q2632 | WritableAuthorizerConfiguration.reset | train | public synchronized void reset() {
this.authorizerDescription = StandardRBACAuthorizer.AUTHORIZER_DESCRIPTION;
this.useIdentityRoles = this.nonFacadeMBeansSensitive = false;
this.roleMappings = new HashMap<String, RoleMappingImpl>();
RoleMaps oldRoleMaps = this.roleMaps;
this.roleMaps = new RoleMaps(authorizerDescription.getStandardRoles(), Collections.<String, ScopedRole>emptyMap());
for (ScopedRole role : oldRoleMaps.scopedRoles.values()) {
for (ScopedRoleListener listener : scopedRoleListeners) {
try {
listener.scopedRoleRemoved(role);
} catch (Exception ignored) {
// TODO log an ERROR
}
}
}
} | java | {
"resource": ""
} |
q2633 | WritableAuthorizerConfiguration.addRoleMapping | train | public synchronized void addRoleMapping(final String roleName) {
HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);
if (newRoles.containsKey(roleName) == false) {
newRoles.put(roleName, new RoleMappingImpl(roleName));
roleMappings = Collections.unmodifiableMap(newRoles);
}
} | java | {
"resource": ""
} |
q2634 | WritableAuthorizerConfiguration.removeRoleMapping | train | public synchronized Object removeRoleMapping(final String roleName) {
/*
* Would not expect this to happen during boot so don't offer the 'immediate' optimisation.
*/
HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);
if (newRoles.containsKey(roleName)) {
RoleMappingImpl removed = newRoles.remove(roleName);
Object removalKey = new Object();
removedRoles.put(removalKey, removed);
roleMappings = Collections.unmodifiableMap(newRoles);
return removalKey;
}
return null;
} | java | {
"resource": ""
} |
q2635 | WritableAuthorizerConfiguration.undoRoleMappingRemove | train | public synchronized boolean undoRoleMappingRemove(final Object removalKey) {
HashMap<String, RoleMappingImpl> newRoles = new HashMap<String, RoleMappingImpl>(roleMappings);
RoleMappingImpl toRestore = removedRoles.remove(removalKey);
if (toRestore != null && newRoles.containsKey(toRestore.getName()) == false) {
newRoles.put(toRestore.getName(), toRestore);
roleMappings = Collections.unmodifiableMap(newRoles);
return true;
}
return false;
} | java | {
"resource": ""
} |
q2636 | ServerOperationResolver.getDeploymentOverlayOperations | train | private Map<Set<ServerIdentity>, ModelNode> getDeploymentOverlayOperations(ModelNode operation,
ModelNode host) {
final PathAddress realAddress = PathAddress.pathAddress(operation.get(OP_ADDR));
if (realAddress.size() == 0 && COMPOSITE.equals(operation.get(OP).asString())) {
//We have a composite operation resulting from a transformation to redeploy affected deployments
//See redeploying deployments affected by an overlay.
ModelNode serverOp = operation.clone();
Map<ServerIdentity, Operations.CompositeOperationBuilder> composite = new HashMap<>();
for (ModelNode step : serverOp.get(STEPS).asList()) {
ModelNode newStep = step.clone();
String groupName = PathAddress.pathAddress(step.get(OP_ADDR)).getElement(0).getValue();
newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());
Set<ServerIdentity> servers = getServersForGroup(groupName, host, localHostName, serverProxies);
for(ServerIdentity server : servers) {
if(!composite.containsKey(server)) {
composite.put(server, Operations.CompositeOperationBuilder.create());
}
composite.get(server).addStep(newStep);
}
if(!servers.isEmpty()) {
newStep.get(OP_ADDR).set(PathAddress.pathAddress(step.get(OP_ADDR)).subAddress(1).toModelNode());
}
}
if(!composite.isEmpty()) {
Map<Set<ServerIdentity>, ModelNode> result = new HashMap<>();
for(Entry<ServerIdentity, Operations.CompositeOperationBuilder> entry : composite.entrySet()) {
result.put(Collections.singleton(entry.getKey()), entry.getValue().build().getOperation());
}
return result;
}
return Collections.emptyMap();
}
final Set<ServerIdentity> allServers = getAllRunningServers(host, localHostName, serverProxies);
return Collections.singletonMap(allServers, operation.clone());
} | java | {
"resource": ""
} |
q2637 | ServerLogsPanel.isLogDownloadAvailable | train | public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {
ModelNode readOps = null;
try {
readOps = cliGuiCtx.getExecutor().doCommand("/subsystem=logging:read-children-types");
} catch (CommandFormatException | IOException e) {
return false;
}
if (!readOps.get("result").isDefined()) return false;
for (ModelNode op: readOps.get("result").asList()) {
if ("log-file".equals(op.asString())) return true;
}
return false;
} | java | {
"resource": ""
} |
q2638 | InetAddressUtil.getLocalHost | train | public static InetAddress getLocalHost() throws UnknownHostException {
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
} catch (ArrayIndexOutOfBoundsException e) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404
addr = InetAddress.getByName(null);
}
return addr;
} | java | {
"resource": ""
} |
q2639 | ConfigurationFile.getBootFile | train | public File getBootFile() {
if (bootFile == null) {
synchronized (this) {
if (bootFile == null) {
if (bootFileReset) {
//Reset the done bootup and the sequence, so that the old file we are reloading from
// overwrites the main file on successful boot, and history is reset as when booting new
doneBootup.set(false);
sequence.set(0);
}
// If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile,
// as that's where we persist
if (bootFileReset && !interactionPolicy.isReadOnly() && newReloadBootFileName == null) {
// we boot from mainFile
bootFile = mainFile;
} else {
// It's either first boot, or a reload where we're not persisting our config or with a new boot file.
// So we need to figure out which file we're meant to boot from
String bootFileName = this.bootFileName;
if (newReloadBootFileName != null) {
//A non-null new boot file on reload takes precedence over the reloadUsingLast functionality
//A new boot file was specified. Use that and reset the new name to null
bootFileName = newReloadBootFileName;
newReloadBootFileName = null;
} else if (interactionPolicy.isReadOnly() && reloadUsingLast) {
//If we were reloaded, and it is not a persistent configuration we want to use the last from the history
bootFileName = LAST;
}
boolean usingRawFile = bootFileName.equals(rawFileName);
if (usingRawFile) {
bootFile = mainFile;
} else {
bootFile = determineBootFile(configurationDir, bootFileName);
try {
bootFile = bootFile.getCanonicalFile();
} catch (IOException ioe) {
throw ControllerLogger.ROOT_LOGGER.canonicalBootFileNotFound(ioe, bootFile);
}
}
if (!bootFile.exists()) {
if (!usingRawFile) { // TODO there's no reason usingRawFile should be an exception,
// but the test infrastructure stuff is built around an assumption
// that ConfigurationFile doesn't fail if test files are not
// in the normal spot
if (bootFileReset || interactionPolicy.isRequireExisting()) {
throw ControllerLogger.ROOT_LOGGER.fileNotFound(bootFile.getAbsolutePath());
}
}
// Create it for the NEW and DISCARD cases
if (!bootFileReset && !interactionPolicy.isRequireExisting()) {
createBootFile(bootFile);
}
} else if (!bootFileReset) {
if (interactionPolicy.isRejectExisting() && bootFile.length() > 0) {
throw ControllerLogger.ROOT_LOGGER.rejectEmptyConfig(bootFile.getAbsolutePath());
} else if (interactionPolicy.isRemoveExisting() && bootFile.length() > 0) {
if (!bootFile.delete()) {
throw ControllerLogger.ROOT_LOGGER.cannotDelete(bootFile.getAbsoluteFile());
}
createBootFile(bootFile);
}
} // else after first boot we want the file to exist
}
}
}
}
return bootFile;
} | java | {
"resource": ""
} |
q2640 | ConfigurationFile.successfulBoot | train | void successfulBoot() throws ConfigurationPersistenceException {
synchronized (this) {
if (doneBootup.get()) {
return;
}
final File copySource;
if (!interactionPolicy.isReadOnly()) {
copySource = mainFile;
} else {
if ( FilePersistenceUtils.isParentFolderWritable(mainFile) ) {
copySource = new File(mainFile.getParentFile(), mainFile.getName() + ".boot");
} else{
copySource = new File(configurationDir, mainFile.getName() + ".boot");
}
FilePersistenceUtils.deleteFile(copySource);
}
try {
if (!bootFile.equals(copySource)) {
FilePersistenceUtils.copyFile(bootFile, copySource);
}
createHistoryDirectory();
final File historyBase = new File(historyRoot, mainFile.getName());
lastFile = addSuffixToFile(historyBase, LAST);
final File boot = addSuffixToFile(historyBase, BOOT);
final File initial = addSuffixToFile(historyBase, INITIAL);
if (!initial.exists()) {
FilePersistenceUtils.copyFile(copySource, initial);
}
FilePersistenceUtils.copyFile(copySource, lastFile);
FilePersistenceUtils.copyFile(copySource, boot);
} catch (IOException e) {
throw ControllerLogger.ROOT_LOGGER.failedToCreateConfigurationBackup(e, bootFile);
} finally {
if (interactionPolicy.isReadOnly()) {
//Delete the temporary file
try {
FilePersistenceUtils.deleteFile(copySource);
} catch (Exception ignore) {
}
}
}
doneBootup.set(true);
}
} | java | {
"resource": ""
} |
q2641 | ConfigurationFile.backup | train | void backup() throws ConfigurationPersistenceException {
if (!doneBootup.get()) {
return;
}
try {
if (!interactionPolicy.isReadOnly()) {
//Move the main file to the versioned history
moveFile(mainFile, getVersionedFile(mainFile));
} else {
//Copy the Last file to the versioned history
moveFile(lastFile, getVersionedFile(mainFile));
}
int seq = sequence.get();
// delete unwanted backup files
int currentHistoryLength = getInteger(CURRENT_HISTORY_LENGTH_PROPERTY, CURRENT_HISTORY_LENGTH, 0);
if (seq > currentHistoryLength) {
for (int k = seq - currentHistoryLength; k > 0; k--) {
File delete = getVersionedFile(mainFile, k);
if (! delete.exists()) {
break;
}
delete.delete();
}
}
} catch (IOException e) {
throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);
}
} | java | {
"resource": ""
} |
q2642 | ConfigurationFile.commitTempFile | train | void commitTempFile(File temp) throws ConfigurationPersistenceException {
if (!doneBootup.get()) {
return;
}
if (!interactionPolicy.isReadOnly()) {
FilePersistenceUtils.moveTempFileToMain(temp, mainFile);
} else {
FilePersistenceUtils.moveTempFileToMain(temp, lastFile);
}
} | java | {
"resource": ""
} |
q2643 | ConfigurationFile.fileWritten | train | void fileWritten() throws ConfigurationPersistenceException {
if (!doneBootup.get() || interactionPolicy.isReadOnly()) {
return;
}
try {
FilePersistenceUtils.copyFile(mainFile, lastFile);
} catch (IOException e) {
throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);
}
} | java | {
"resource": ""
} |
q2644 | ConfigurationFile.deleteRecursive | train | private void deleteRecursive(final File file) {
if (file.isDirectory()) {
final String[] files = file.list();
if (files != null) {
for (String name : files) {
deleteRecursive(new File(file, name));
}
}
}
if (!file.delete()) {
ControllerLogger.ROOT_LOGGER.cannotDeleteFileOrDirectory(file);
}
} | java | {
"resource": ""
} |
q2645 | RestartParentResourceRemoveHandler.updateModel | train | protected void updateModel(final OperationContext context, final ModelNode operation) throws OperationFailedException {
// verify that the resource exist before removing it
context.readResource(PathAddress.EMPTY_ADDRESS, false);
Resource resource = context.removeResource(PathAddress.EMPTY_ADDRESS);
recordCapabilitiesAndRequirements(context, operation, resource);
} | java | {
"resource": ""
} |
q2646 | AbstractOperationContext.executeOperation | train | ResultAction executeOperation() {
assert isControllingThread();
try {
/** Execution has begun */
executing = true;
processStages();
if (resultAction == ResultAction.KEEP) {
report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationSucceeded());
} else {
report(MessageSeverity.INFO, ControllerLogger.ROOT_LOGGER.operationRollingBack());
}
} catch (RuntimeException e) {
handleUncaughtException(e);
ControllerLogger.MGMT_OP_LOGGER.unexpectedOperationExecutionException(e, controllerOperations);
} finally {
// On failure close any attached response streams
if (resultAction != ResultAction.KEEP && !isBooting()) {
synchronized (this) {
if (responseStreams != null) {
int i = 0;
for (OperationResponse.StreamEntry is : responseStreams.values()) {
try {
is.getStream().close();
} catch (Exception e) {
ControllerLogger.MGMT_OP_LOGGER.debugf(e, "Failed closing stream at index %d", i);
}
i++;
}
responseStreams.clear();
}
}
}
}
return resultAction;
} | java | {
"resource": ""
} |
q2647 | AbstractOperationContext.logAuditRecord | train | void logAuditRecord() {
trackConfigurationChange();
if (!auditLogged) {
try {
AccessAuditContext accessContext = SecurityActions.currentAccessAuditContext();
Caller caller = getCaller();
auditLogger.log(
isReadOnly(),
resultAction,
caller == null ? null : caller.getName(),
accessContext == null ? null : accessContext.getDomainUuid(),
accessContext == null ? null : accessContext.getAccessMechanism(),
accessContext == null ? null : accessContext.getRemoteAddress(),
getModel(),
controllerOperations);
auditLogged = true;
} catch (Exception e) {
ControllerLogger.MGMT_OP_LOGGER.failedToUpdateAuditLog(e);
}
}
} | java | {
"resource": ""
} |
q2648 | AbstractOperationContext.processStages | train | private void processStages() {
// Locate the next step to execute.
ModelNode primaryResponse = null;
Step step;
do {
step = steps.get(currentStage).pollFirst();
if (step == null) {
if (currentStage == Stage.MODEL && addModelValidationSteps()) {
continue;
}
// No steps remain in this stage; give subclasses a chance to check status
// and approve moving to the next stage
if (!tryStageCompleted(currentStage)) {
// Can't continue
resultAction = ResultAction.ROLLBACK;
executeResultHandlerPhase(null);
return;
}
// Proceed to the next stage
if (currentStage.hasNext()) {
currentStage = currentStage.next();
if (currentStage == Stage.VERIFY) {
// a change was made to the runtime. Thus, we must wait
// for stability before resuming in to verify.
try {
awaitServiceContainerStability();
} catch (InterruptedException e) {
cancelled = true;
handleContainerStabilityFailure(primaryResponse, e);
executeResultHandlerPhase(null);
return;
} catch (TimeoutException te) {
// The service container is in an unknown state; but we don't require restart
// because rollback may allow the container to stabilize. We force require-restart
// in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)
//processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback
handleContainerStabilityFailure(primaryResponse, te);
executeResultHandlerPhase(null);
return;
}
}
}
} else {
// The response to the first step is what goes to the outside caller
if (primaryResponse == null) {
primaryResponse = step.response;
}
// Execute the step, but make sure we always finalize any steps
Throwable toThrow = null;
// Whether to return after try/finally
boolean exit = false;
try {
CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);
if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {
executeStep(step);
} else {
String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED
? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;
step.response.get(RESPONSE_HEADERS, header).set(true);
}
} catch (RuntimeException | Error re) {
resultAction = ResultAction.ROLLBACK;
toThrow = re;
} finally {
// See if executeStep put us in a state where we shouldn't do any more
if (toThrow != null || !canContinueProcessing()) {
// We're done.
executeResultHandlerPhase(toThrow);
exit = true; // we're on the return path
}
}
if (exit) {
return;
}
}
} while (currentStage != Stage.DONE);
assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps
// All steps ran and canContinueProcessing returned true for the last one, so...
executeDoneStage(primaryResponse);
} | java | {
"resource": ""
} |
q2649 | AbstractOperationContext.checkUndefinedNotification | train | private void checkUndefinedNotification(Notification notification) {
String type = notification.getType();
PathAddress source = notification.getSource();
Map<String, NotificationEntry> descriptions = getRootResourceRegistration().getNotificationDescriptions(source, true);
if (!descriptions.keySet().contains(type)) {
missingNotificationDescriptionWarnings.add(ControllerLogger.ROOT_LOGGER.notificationIsNotDescribed(type, source));
}
} | java | {
"resource": ""
} |
q2650 | AbstractOperationContext.getFailedResultAction | train | private ResultAction getFailedResultAction(Throwable cause) {
if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()
|| (cause != null && !(cause instanceof OperationFailedException))) {
return ResultAction.ROLLBACK;
}
return ResultAction.KEEP;
} | java | {
"resource": ""
} |
q2651 | ServerUpdatePolicy.canUpdateServer | train | public boolean canUpdateServer(ServerIdentity server) {
if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {
throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);
}
if (!parent.canChildProceed())
return false;
synchronized (this) {
return failureCount <= maxFailed;
}
} | java | {
"resource": ""
} |
q2652 | ServerUpdatePolicy.recordServerResult | train | public void recordServerResult(ServerIdentity server, ModelNode response) {
if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {
throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);
}
boolean serverFailed = response.has(FAILURE_DESCRIPTION);
DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Recording server result for '%s': failed = %s",
server, server);
synchronized (this) {
int previousFailed = failureCount;
if (serverFailed) {
failureCount++;
}
else {
successCount++;
}
if (previousFailed <= maxFailed) {
if (!serverFailed && (successCount + failureCount) == servers.size()) {
// All results are in; notify parent of success
parent.recordServerGroupResult(serverGroupName, false);
}
else if (serverFailed && failureCount > maxFailed) {
parent.recordServerGroupResult(serverGroupName, true);
}
}
}
} | java | {
"resource": ""
} |
q2653 | Arguments.set | train | public void set(final Argument argument) {
if (argument != null) {
map.put(argument.getKey(), Collections.singleton(argument));
}
} | java | {
"resource": ""
} |
q2654 | Arguments.get | train | public String get(final String key) {
final Collection<Argument> args = map.get(key);
if (args != null) {
return args.iterator().hasNext() ? args.iterator().next().getValue() : null;
}
return null;
} | java | {
"resource": ""
} |
q2655 | Arguments.getArguments | train | public Collection<Argument> getArguments(final String key) {
final Collection<Argument> args = map.get(key);
if (args != null) {
return new ArrayList<>(args);
}
return Collections.emptyList();
} | java | {
"resource": ""
} |
q2656 | Arguments.asList | train | public List<String> asList() {
final List<String> result = new ArrayList<>();
for (Collection<Argument> args : map.values()) {
for (Argument arg : args) {
result.add(arg.asCommandLineArgument());
}
}
return result;
} | java | {
"resource": ""
} |
q2657 | ManagementXml_Legacy.parseLdapAuthorization_1_5 | train | private void parseLdapAuthorization_1_5(final XMLExtendedStreamReader reader,
final ModelNode realmAddress, final List<ModelNode> list) throws XMLStreamException {
ModelNode addr = realmAddress.clone().add(AUTHORIZATION, LDAP);
ModelNode ldapAuthorization = Util.getEmptyOperation(ADD, addr);
list.add(ldapAuthorization);
Set<Attribute> required = EnumSet.of(Attribute.CONNECTION);
final int count = reader.getAttributeCount();
for (int i = 0; i < count; i++) {
final String value = reader.getAttributeValue(i);
if (!isNoNamespaceAttribute(reader, i)) {
throw unexpectedAttribute(reader, i);
} else {
final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
required.remove(attribute);
switch (attribute) {
case CONNECTION: {
LdapAuthorizationResourceDefinition.CONNECTION.parseAndSetParameter(value, ldapAuthorization, reader);
break;
}
default: {
throw unexpectedAttribute(reader, i);
}
}
}
}
if (required.isEmpty() == false) {
throw missingRequired(reader, required);
}
Set<Element> foundElements = new HashSet<Element>();
while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
requireNamespace(reader, namespace);
final Element element = Element.forName(reader.getLocalName());
if (foundElements.add(element) == false) {
throw unexpectedElement(reader); // Only one of each allowed.
}
switch (element) {
case USERNAME_TO_DN: {
switch (namespace.getMajorVersion()) {
case 1: // 1.5 up to but not including 2.0
parseUsernameToDn_1_5(reader, addr, list);
break;
default: // 2.0 and onwards
parseUsernameToDn_2_0(reader, addr, list);
break;
}
break;
}
case GROUP_SEARCH: {
switch (namespace) {
case DOMAIN_1_5:
case DOMAIN_1_6:
parseGroupSearch_1_5(reader, addr, list);
break;
default:
parseGroupSearch_1_7_and_2_0(reader, addr, list);
break;
}
break;
}
default: {
throw unexpectedElement(reader);
}
}
}
} | java | {
"resource": ""
} |
q2658 | ResourceRoot.merge | train | public void merge(final ResourceRoot additionalResourceRoot) {
if(!additionalResourceRoot.getRoot().equals(root)) {
throw ServerLogger.ROOT_LOGGER.cannotMergeResourceRoot(root, additionalResourceRoot.getRoot());
}
usePhysicalCodeSource = additionalResourceRoot.usePhysicalCodeSource;
if(additionalResourceRoot.getExportFilters().isEmpty()) {
//new root has no filters, so we don't want our existing filters to break anything
//see WFLY-1527
this.exportFilters.clear();
} else {
this.exportFilters.addAll(additionalResourceRoot.getExportFilters());
}
} | java | {
"resource": ""
} |
q2659 | SecurityManagerExtensionTransformerRegistration.registerTransformers | train | @Override
public void registerTransformers(SubsystemTransformerRegistration subsystemRegistration) {
ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance();
builder.addChildResource(DeploymentPermissionsResourceDefinition.DEPLOYMENT_PERMISSIONS_PATH).
getAttributeBuilder().addRejectCheck(new RejectAttributeChecker.DefaultRejectAttributeChecker() {
@Override
protected boolean rejectAttribute(PathAddress address, String attributeName, ModelNode value, TransformationContext context) {
// reject the maximum set if it is defined and empty as that would result in complete incompatible policies
// being used in nodes running earlier versions of the subsystem.
if (value.isDefined() && value.asList().isEmpty()) { return true; }
return false;
}
@Override
public String getRejectionLogMessage(Map<String, ModelNode> attributes) {
return SecurityManagerLogger.ROOT_LOGGER.rejectedEmptyMaximumSet();
}
}, DeploymentPermissionsResourceDefinition.MAXIMUM_PERMISSIONS);
TransformationDescription.Tools.register(builder.build(), subsystemRegistration, EAP_7_0_0_MODEL_VERSION);
} | java | {
"resource": ""
} |
q2660 | FilteredData.toModelNode | train | ModelNode toModelNode() {
ModelNode result = null;
if (map != null) {
result = new ModelNode();
for (Map.Entry<PathAddress, ResourceData> entry : map.entrySet()) {
ModelNode item = new ModelNode();
PathAddress pa = entry.getKey();
item.get(ABSOLUTE_ADDRESS).set(pa.toModelNode());
ResourceData rd = entry.getValue();
item.get(RELATIVE_ADDRESS).set(pa.subAddress(baseAddressLength).toModelNode());
ModelNode attrs = new ModelNode().setEmptyList();
if (rd.attributes != null) {
for (String attr : rd.attributes) {
attrs.add(attr);
}
}
if (attrs.asInt() > 0) {
item.get(FILTERED_ATTRIBUTES).set(attrs);
}
ModelNode children = new ModelNode().setEmptyList();
if (rd.children != null) {
for (PathElement pe : rd.children) {
children.add(new Property(pe.getKey(), new ModelNode(pe.getValue())));
}
}
if (children.asInt() > 0) {
item.get(UNREADABLE_CHILDREN).set(children);
}
ModelNode childTypes = new ModelNode().setEmptyList();
if (rd.childTypes != null) {
Set<String> added = new HashSet<String>();
for (PathElement pe : rd.childTypes) {
if (added.add(pe.getKey())) {
childTypes.add(pe.getKey());
}
}
}
if (childTypes.asInt() > 0) {
item.get(FILTERED_CHILDREN_TYPES).set(childTypes);
}
result.add(item);
}
}
return result;
} | java | {
"resource": ""
} |
q2661 | IdentityPatchRunner.rollbackLast | train | public PatchingResult rollbackLast(final ContentVerificationPolicy contentPolicy, final boolean resetConfiguration, InstallationManager.InstallationModification modification) throws PatchingException {
// Determine the patch id to rollback
String patchId;
final List<String> oneOffs = modification.getPatchIDs();
if (oneOffs.isEmpty()) {
patchId = modification.getCumulativePatchID();
if (patchId == null || Constants.NOT_PATCHED.equals(patchId)) {
throw PatchLogger.ROOT_LOGGER.noPatchesApplied();
}
} else {
patchId = oneOffs.get(0);//oneOffs.get(oneOffs.size() - 1);
}
return rollbackPatch(patchId, contentPolicy, false, resetConfiguration, modification);
} | java | {
"resource": ""
} |
q2662 | IdentityPatchRunner.restoreFromHistory | train | static void restoreFromHistory(final InstallationManager.MutablePatchingTarget target, final String rollbackPatchId,
final Patch.PatchType patchType, final PatchableTarget.TargetInfo history) throws PatchingException {
if (patchType == Patch.PatchType.CUMULATIVE) {
assert history.getCumulativePatchID().equals(rollbackPatchId);
target.apply(rollbackPatchId, patchType);
// Restore one off state
final List<String> oneOffs = new ArrayList<String>(history.getPatchIDs());
Collections.reverse(oneOffs);
for (final String oneOff : oneOffs) {
target.apply(oneOff, Patch.PatchType.ONE_OFF);
}
}
checkState(history, history); // Just check for tests, that rollback should restore the old state
} | java | {
"resource": ""
} |
q2663 | IdentityPatchRunner.portForward | train | void portForward(final Patch patch, IdentityPatchContext context) throws PatchingException, IOException, XMLStreamException {
assert patch.getIdentity().getPatchType() == Patch.PatchType.CUMULATIVE;
final PatchingHistory history = context.getHistory();
for (final PatchElement element : patch.getElements()) {
final PatchElementProvider provider = element.getProvider();
final String name = provider.getName();
final boolean addOn = provider.isAddOn();
final IdentityPatchContext.PatchEntry target = context.resolveForElement(element);
final String cumulativePatchID = target.getCumulativePatchID();
if (Constants.BASE.equals(cumulativePatchID)) {
reenableRolledBackInBase(target);
continue;
}
boolean found = false;
final PatchingHistory.Iterator iterator = history.iterator();
while (iterator.hasNextCP()) {
final PatchingHistory.Entry entry = iterator.nextCP();
final String patchId = addOn ? entry.getAddOnPatches().get(name) : entry.getLayerPatches().get(name);
if (patchId != null && patchId.equals(cumulativePatchID)) {
final Patch original = loadPatchInformation(entry.getPatchId(), installedImage);
for (final PatchElement originalElement : original.getElements()) {
if (name.equals(originalElement.getProvider().getName())
&& addOn == originalElement.getProvider().isAddOn()) {
PatchingTasks.addMissingModifications(target, originalElement.getModifications(), ContentItemFilter.ALL_BUT_MISC);
}
}
// Record a loader to have access to the current modules
final DirectoryStructure structure = target.getDirectoryStructure();
final File modulesRoot = structure.getModulePatchDirectory(patchId);
final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);
final PatchContentLoader loader = PatchContentLoader.create(null, bundlesRoot, modulesRoot);
context.recordContentLoader(patchId, loader);
found = true;
break;
}
}
if (!found) {
throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(cumulativePatchID);
}
reenableRolledBackInBase(target);
}
} | java | {
"resource": ""
} |
q2664 | IdentityPatchRunner.executeTasks | train | static PatchingResult executeTasks(final IdentityPatchContext context, final IdentityPatchContext.FinalizeCallback callback) throws Exception {
final List<PreparedTask> tasks = new ArrayList<PreparedTask>();
final List<ContentItem> conflicts = new ArrayList<ContentItem>();
// Identity
prepareTasks(context.getIdentityEntry(), context, tasks, conflicts);
// Layers
for (final IdentityPatchContext.PatchEntry layer : context.getLayers()) {
prepareTasks(layer, context, tasks, conflicts);
}
// AddOns
for (final IdentityPatchContext.PatchEntry addOn : context.getAddOns()) {
prepareTasks(addOn, context, tasks, conflicts);
}
// If there were problems report them
if (!conflicts.isEmpty()) {
throw PatchLogger.ROOT_LOGGER.conflictsDetected(conflicts);
}
// Execute the tasks
for (final PreparedTask task : tasks) {
// Unless it's excluded by the user
final ContentItem item = task.getContentItem();
if (item != null && context.isExcluded(item)) {
continue;
}
// Run the task
task.execute();
}
return context.finalize(callback);
} | java | {
"resource": ""
} |
q2665 | IdentityPatchRunner.prepareTasks | train | static void prepareTasks(final IdentityPatchContext.PatchEntry entry, final IdentityPatchContext context, final List<PreparedTask> tasks, final List<ContentItem> conflicts) throws PatchingException {
for (final PatchingTasks.ContentTaskDefinition definition : entry.getTaskDefinitions()) {
final PatchingTask task = createTask(definition, context, entry);
if(!task.isRelevant(entry)) {
continue;
}
try {
// backup and validate content
if (!task.prepare(entry) || definition.hasConflicts()) {
// Unless it a content item was manually ignored (or excluded)
final ContentItem item = task.getContentItem();
if (!context.isIgnored(item)) {
conflicts.add(item);
}
}
tasks.add(new PreparedTask(task, entry));
} catch (IOException e) {
throw new PatchingException(e);
}
}
} | java | {
"resource": ""
} |
q2666 | IdentityPatchRunner.createTask | train | static PatchingTask createTask(final PatchingTasks.ContentTaskDefinition definition, final PatchContentProvider provider, final IdentityPatchContext.PatchEntry context) {
final PatchContentLoader contentLoader = provider.getLoader(definition.getTarget().getPatchId());
final PatchingTaskDescription description = PatchingTaskDescription.create(definition, contentLoader);
return PatchingTask.Factory.create(description, context);
} | java | {
"resource": ""
} |
q2667 | IdentityPatchRunner.checkUpgradeConditions | train | static void checkUpgradeConditions(final UpgradeCondition condition, final InstallationManager.MutablePatchingTarget target) throws PatchingException {
// See if the prerequisites are met
for (final String required : condition.getRequires()) {
if (!target.isApplied(required)) {
throw PatchLogger.ROOT_LOGGER.requiresPatch(required);
}
}
// Check for incompatibilities
for (final String incompatible : condition.getIncompatibleWith()) {
if (target.isApplied(incompatible)) {
throw PatchLogger.ROOT_LOGGER.incompatiblePatch(incompatible);
}
}
} | java | {
"resource": ""
} |
q2668 | S3Util.domainControllerDataFromByteBuffer | train | public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception {
List<DomainControllerData> retval = new ArrayList<DomainControllerData>();
if (buffer == null) {
return retval;
}
ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer);
DataInputStream in = new DataInputStream(in_stream);
String content = SEPARATOR;
while (SEPARATOR.equals(content)) {
DomainControllerData data = new DomainControllerData();
data.readFrom(in);
retval.add(data);
try {
content = readString(in);
} catch (EOFException ex) {
content = null;
}
}
in.close();
return retval;
} | java | {
"resource": ""
} |
q2669 | S3Util.domainControllerDataToByteBuffer | train | public static byte[] domainControllerDataToByteBuffer(List<DomainControllerData> data) throws Exception {
final ByteArrayOutputStream out_stream = new ByteArrayOutputStream(512);
byte[] result;
try (DataOutputStream out = new DataOutputStream(out_stream)) {
Iterator<DomainControllerData> iter = data.iterator();
while (iter.hasNext()) {
DomainControllerData dcData = iter.next();
dcData.writeTo(out);
if (iter.hasNext()) {
S3Util.writeString(SEPARATOR, out);
}
}
result = out_stream.toByteArray();
}
return result;
} | java | {
"resource": ""
} |
q2670 | ConcurrentGroupServerUpdatePolicy.canSuccessorProceed | train | private boolean canSuccessorProceed() {
if (predecessor != null && !predecessor.canSuccessorProceed()) {
return false;
}
synchronized (this) {
while (responseCount < groups.size()) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return !failed;
}
} | java | {
"resource": ""
} |
q2671 | ConcurrentGroupServerUpdatePolicy.recordServerGroupResult | train | public void recordServerGroupResult(final String serverGroup, final boolean failed) {
synchronized (this) {
if (groups.contains(serverGroup)) {
responseCount++;
if (failed) {
this.failed = true;
}
DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Recorded group result for '%s': failed = %s",
serverGroup, failed);
notifyAll();
}
else {
throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServerGroup(serverGroup);
}
}
} | java | {
"resource": ""
} |
q2672 | ModelControllerImpl.executeReadOnlyOperation | train | @SuppressWarnings("deprecation")
protected ModelNode executeReadOnlyOperation(final ModelNode operation, final OperationMessageHandler handler, final OperationTransactionControl control, final OperationStepHandler prepareStep, final int operationId) {
final AbstractOperationContext delegateContext = getDelegateContext(operationId);
CurrentOperationIdHolder.setCurrentOperationID(operationId);
try {
return executeReadOnlyOperation(operation, delegateContext.getManagementModel(), control, prepareStep, delegateContext);
} finally {
CurrentOperationIdHolder.setCurrentOperationID(null);
}
} | java | {
"resource": ""
} |
q2673 | ManagementHttpRequestProcessor.addShutdownListener | train | public synchronized void addShutdownListener(ShutdownListener listener) {
if (state == CLOSED) {
listener.handleCompleted();
} else {
listeners.add(listener);
}
} | java | {
"resource": ""
} |
q2674 | ManagementHttpRequestProcessor.handleCompleted | train | protected synchronized void handleCompleted() {
latch.countDown();
for (final ShutdownListener listener : listeners) {
listener.handleCompleted();
}
listeners.clear();
} | java | {
"resource": ""
} |
q2675 | DeploymentResourceSupport.hasDeploymentSubsystemModel | train | public boolean hasDeploymentSubsystemModel(final String subsystemName) {
final Resource root = deploymentUnit.getAttachment(DEPLOYMENT_RESOURCE);
final PathElement subsystem = PathElement.pathElement(SUBSYSTEM, subsystemName);
return root.hasChild(subsystem);
} | java | {
"resource": ""
} |
q2676 | DeploymentResourceSupport.getDeploymentSubsystemModel | train | public ModelNode getDeploymentSubsystemModel(final String subsystemName) {
assert subsystemName != null : "The subsystemName cannot be null";
return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);
} | java | {
"resource": ""
} |
q2677 | DeploymentResourceSupport.registerDeploymentSubsystemResource | train | public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {
assert subsystemName != null : "The subsystemName cannot be null";
assert resource != null : "The resource cannot be null";
return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);
} | java | {
"resource": ""
} |
q2678 | DeploymentResourceSupport.getOrCreateSubDeployment | train | static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {
final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);
return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));
} | java | {
"resource": ""
} |
q2679 | DeploymentResourceSupport.cleanup | train | static void cleanup(final Resource resource) {
synchronized (resource) {
for (final Resource.ResourceEntry entry : resource.getChildren(SUBSYSTEM)) {
resource.removeChild(entry.getPathElement());
}
for (final Resource.ResourceEntry entry : resource.getChildren(SUBDEPLOYMENT)) {
resource.removeChild(entry.getPathElement());
}
}
} | java | {
"resource": ""
} |
q2680 | SystemPropertyContext.resolveBaseDir | train | Path resolveBaseDir(final String name, final String dirName) {
final String currentDir = SecurityActions.getPropertyPrivileged(name);
if (currentDir == null) {
return jbossHomeDir.resolve(dirName);
}
return Paths.get(currentDir);
} | java | {
"resource": ""
} |
q2681 | SystemPropertyContext.resolvePath | train | static Path resolvePath(final Path base, final String... paths) {
return Paths.get(base.toString(), paths);
} | java | {
"resource": ""
} |
q2682 | GlobalOperationHandlers.getChildAddresses | train | static Map<String, Set<String>> getChildAddresses(final OperationContext context, final PathAddress addr, final ImmutableManagementResourceRegistration registry, Resource resource, final String validChildType) {
Map<String, Set<String>> result = new HashMap<>();
Predicate<String> validChildTypeFilter = childType -> (validChildType == null) || validChildType.equals(childType);
if (resource != null) {
for (String childType : registry.getChildNames(PathAddress.EMPTY_ADDRESS)) {
if (validChildTypeFilter.test(childType)) {
List<String> list = new ArrayList<>();
for (String child : resource.getChildrenNames(childType)) {
if (registry.getSubModel(PathAddress.pathAddress(PathElement.pathElement(childType, child))) != null) {
list.add(child);
}
}
result.put(childType, new LinkedHashSet<>(list));
}
}
}
Set<PathElement> paths = registry.getChildAddresses(PathAddress.EMPTY_ADDRESS);
for (PathElement path : paths) {
String childType = path.getKey();
if (validChildTypeFilter.test(childType)) {
Set<String> children = result.get(childType);
if (children == null) {
// WFLY-3306 Ensure we have an entry for any valid child type
children = new LinkedHashSet<>();
result.put(childType, children);
}
ImmutableManagementResourceRegistration childRegistration = registry.getSubModel(PathAddress.pathAddress(path));
if (childRegistration != null) {
AliasEntry aliasEntry = childRegistration.getAliasEntry();
if (aliasEntry != null) {
PathAddress childAddr = addr.append(path);
PathAddress target = aliasEntry.convertToTargetAddress(childAddr, AliasContext.create(childAddr, context));
assert !childAddr.equals(target) : "Alias was not translated";
PathAddress targetParent = target.getParent();
Resource parentResource = context.readResourceFromRoot(targetParent, false);
if (parentResource != null) {
PathElement targetElement = target.getLastElement();
if (targetElement.isWildcard()) {
children.addAll(parentResource.getChildrenNames(targetElement.getKey()));
} else if (parentResource.hasChild(targetElement)) {
children.add(path.getValue());
}
}
}
if (!path.isWildcard() && childRegistration.isRemote()) {
children.add(path.getValue());
}
}
}
}
return result;
} | java | {
"resource": ""
} |
q2683 | DiscreteInterval.plus | train | public DiscreteInterval plus(DiscreteInterval other) {
return new DiscreteInterval(this.min + other.min, this.max + other.max);
} | java | {
"resource": ""
} |
q2684 | DiscreteInterval.minus | train | public DiscreteInterval minus(DiscreteInterval other) {
return new DiscreteInterval(this.min - other.max, this.max - other.min);
} | java | {
"resource": ""
} |
q2685 | AnnotatedMethodScanner.findAnnotatedMethods | train | public Set<Method> findAnnotatedMethods(String scanBase, Class<? extends Annotation> annotationClass) {
Set<BeanDefinition> filteredComponents = findCandidateBeans(scanBase, annotationClass);
return extractAnnotatedMethods(filteredComponents, annotationClass);
} | java | {
"resource": ""
} |
q2686 | CircuitBreaker.reset | train | public void reset() {
state = BreakerState.CLOSED;
isHardTrip = false;
byPass = false;
isAttemptLive = false;
notifyBreakerStateChange(getStatus());
} | java | {
"resource": ""
} |
q2687 | WebMBeanServerAdapter.createWebMBeanAdapter | train | public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding)
throws JMException, UnsupportedEncodingException {
return new WebMBeanAdapter(mBeanServer, mBeanName, encoding);
} | java | {
"resource": ""
} |
q2688 | WindowedEventCounter.mark | train | public void mark() {
final long currentTimeMillis = clock.currentTimeMillis();
synchronized (queue) {
if (queue.size() == capacity) {
/*
* we're all filled up already, let's dequeue the oldest
* timestamp to make room for this new one.
*/
queue.removeFirst();
}
queue.addLast(currentTimeMillis);
}
} | java | {
"resource": ""
} |
q2689 | WindowedEventCounter.tally | train | public int tally() {
long currentTimeMillis = clock.currentTimeMillis();
// calculates time for which we remove any errors before
final long removeTimesBeforeMillis = currentTimeMillis - windowMillis;
synchronized (queue) {
// drain out any expired timestamps but don't drain past empty
while (!queue.isEmpty() && queue.peek() < removeTimesBeforeMillis) {
queue.removeFirst();
}
return queue.size();
}
} | java | {
"resource": ""
} |
q2690 | WindowedEventCounter.setCapacity | train | public void setCapacity(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity must be greater than 0");
}
synchronized (queue) {
// If the capacity was reduced, we remove oldest elements until the
// queue fits inside the specified capacity
if (capacity < this.capacity) {
while (queue.size() > capacity) {
queue.removeFirst();
}
}
}
this.capacity = capacity;
} | java | {
"resource": ""
} |
q2691 | RetryableAspect.call | train | @Around("@annotation(retryableAnnotation)")
public Object call(final ProceedingJoinPoint pjp, Retryable retryableAnnotation) throws Throwable {
final int maxTries = retryableAnnotation.maxTries();
final int retryDelayMillies = retryableAnnotation.retryDelayMillis();
final Class<? extends Throwable>[] retryOn = retryableAnnotation.retryOn();
final boolean doubleDelay = retryableAnnotation.doubleDelay();
final boolean throwCauseException = retryableAnnotation.throwCauseException();
if (logger.isDebugEnabled()) {
logger.debug("Have @Retryable method wrapping call on method {} of target object {}",
new Object[] {
pjp.getSignature().getName(),
pjp.getTarget()
});
}
ServiceRetrier serviceRetrier =
new ServiceRetrier(retryDelayMillies, maxTries, doubleDelay, throwCauseException, retryOn);
return serviceRetrier.invoke(
new Callable<Object>() {
public Object call() throws Exception {
try {
return pjp.proceed();
}
catch (Exception e) {
throw e;
}
catch (Error e) {
throw e;
}
catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
);
} | java | {
"resource": ""
} |
q2692 | WebMBeanAdapter.getAttributeMetadata | train | public Map<String, MBeanAttributeInfo> getAttributeMetadata() {
MBeanAttributeInfo[] attributeList = mBeanInfo.getAttributes();
Map<String, MBeanAttributeInfo> attributeMap = new TreeMap<String, MBeanAttributeInfo>();
for (MBeanAttributeInfo attribute: attributeList) {
attributeMap.put(attribute.getName(), attribute);
}
return attributeMap;
} | java | {
"resource": ""
} |
q2693 | WebMBeanAdapter.getOperationMetadata | train | public Map<String, MBeanOperationInfo> getOperationMetadata() {
MBeanOperationInfo[] operations = mBeanInfo.getOperations();
Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();
for (MBeanOperationInfo operation: operations) {
operationMap.put(operation.getName(), operation);
}
return operationMap;
} | java | {
"resource": ""
} |
q2694 | WebMBeanAdapter.getOperationInfo | train | public MBeanOperationInfo getOperationInfo(String operationName)
throws OperationNotFoundException, UnsupportedEncodingException {
String decodedOperationName = sanitizer.urlDecode(operationName, encoding);
Map<String, MBeanOperationInfo> operationMap = getOperationMetadata();
if (operationMap.containsKey(decodedOperationName)) {
return operationMap.get(decodedOperationName);
}
throw new OperationNotFoundException("Could not find operation " + operationName + " on MBean " +
objectName.getCanonicalName());
} | java | {
"resource": ""
} |
q2695 | WebMBeanAdapter.getAttributeValues | train | public Map<String,Object> getAttributeValues()
throws AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
HashSet<String> attributeSet = new HashSet<String>();
for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {
attributeSet.add(attributeInfo.getName());
}
AttributeList attributeList =
mBeanServer.getAttributes(objectName, attributeSet.toArray(new String[attributeSet.size()]));
Map<String, Object> attributeValueMap = new TreeMap<String, Object>();
for (Attribute attribute : attributeList.asList()) {
attributeValueMap.put(attribute.getName(), sanitizer.escapeValue(attribute.getValue()));
}
return attributeValueMap;
} | java | {
"resource": ""
} |
q2696 | WebMBeanAdapter.getAttributeValue | train | public String getAttributeValue(String attributeName)
throws JMException, UnsupportedEncodingException {
String decodedAttributeName = sanitizer.urlDecode(attributeName, encoding);
return sanitizer.escapeValue(mBeanServer.getAttribute(objectName, decodedAttributeName));
} | java | {
"resource": ""
} |
q2697 | WebMBeanAdapter.invokeOperation | train | public String invokeOperation(String operationName, Map<String, String[]> parameterMap)
throws JMException, UnsupportedEncodingException {
MBeanOperationInfo operationInfo = getOperationInfo(operationName);
MBeanOperationInvoker invoker = createMBeanOperationInvoker(mBeanServer, objectName, operationInfo);
return sanitizer.escapeValue(invoker.invokeOperation(parameterMap));
} | java | {
"resource": ""
} |
q2698 | MBeanStringSanitizer.urlDecode | train | String urlDecode(String name, String encoding) throws UnsupportedEncodingException {
return URLDecoder.decode(name, encoding);
} | java | {
"resource": ""
} |
q2699 | MBeanStringSanitizer.escapeValue | train | String escapeValue(Object value) {
return HtmlUtils.htmlEscape(value != null ? value.toString() : "<null>");
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.