code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public static ServiceController<DeploymentScanner> addService(final OperationContext context, final PathAddress resourceAddress, final String relativeTo, final String path,
final int scanInterval, TimeUnit unit, final boolean autoDeployZip,
final boolean autoDeployExploded, final boolean autoDeployXml, final boolean scanEnabled, final long deploymentTimeout, boolean rollbackOnRuntimeFailure,
final FileSystemDeploymentService bootTimeService, final ScheduledExecutorService scheduledExecutorService) {
final DeploymentScannerService service = new DeploymentScannerService(resourceAddress, relativeTo, path, scanInterval, unit, autoDeployZip,
autoDeployExploded, autoDeployXml, scanEnabled, deploymentTimeout, rollbackOnRuntimeFailure, bootTimeService);
final ServiceName serviceName = getServiceName(resourceAddress.getLastElement().getValue());
service.scheduledExecutorValue.inject(scheduledExecutorService);
final ServiceBuilder<DeploymentScanner> sb = context.getServiceTarget().addService(serviceName, service);
sb.addDependency(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class), PathManager.class, service.pathManagerValue);
sb.addDependency(context.getCapabilityServiceName("org.wildfly.management.notification-handler-registry", null),
NotificationHandlerRegistry.class, service.notificationRegistryValue);
sb.addDependency(context.getCapabilityServiceName("org.wildfly.management.model-controller-client-factory", null),
ModelControllerClientFactory.class, service.clientFactoryValue);
sb.requires(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_CHAINS);
sb.addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.controlledProcessStateServiceValue);
return sb.install();
} | java |
public ManagementModelNode findNode(String address) {
ManagementModelNode root = (ManagementModelNode)tree.getModel().getRoot();
Enumeration<javax.swing.tree.TreeNode> allNodes = root.depthFirstEnumeration();
while (allNodes.hasMoreElements()) {
ManagementModelNode node = (ManagementModelNode)allNodes.nextElement();
if (node.addressPath().equals(address)) return node;
}
return null;
} | java |
public ManagementModelNode getSelectedNode() {
if (tree.getSelectionPath() == null) return null;
return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();
} | java |
public static Connection connectSync(final ProtocolConnectionConfiguration configuration) throws IOException {
long timeoutMillis = configuration.getConnectionTimeout();
CallbackHandler handler = configuration.getCallbackHandler();
final CallbackHandler actualHandler;
ProtocolTimeoutHandler timeoutHandler = configuration.getTimeoutHandler();
// Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management.
if (timeoutHandler == null) {
GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler();
// No point wrapping our AnonymousCallbackHandler.
actualHandler = handler != null ? new WrapperCallbackHandler(defaultTimeoutHandler, handler) : null;
timeoutHandler = defaultTimeoutHandler;
} else {
actualHandler = handler;
}
final IoFuture<Connection> future = connect(actualHandler, configuration);
IoFuture.Status status = timeoutHandler.await(future, timeoutMillis);
if (status == IoFuture.Status.DONE) {
return future.get();
}
if (status == IoFuture.Status.FAILED) {
throw ProtocolLogger.ROOT_LOGGER.failedToConnect(configuration.getUri(), future.getException());
}
throw ProtocolLogger.ROOT_LOGGER.couldNotConnect(configuration.getUri());
} | java |
public void openBlockingInterruptable()
throws InterruptedException {
// We need to thread this call in order to interrupt it (when Ctrl-C occurs).
connectionThread = new Thread(() -> {
// This thread can't be interrupted from another thread.
// Will stay alive until System.exit is called.
Thread thr = new Thread(() -> super.openBlocking(),
"CLI Terminal Connection (uninterruptable)");
thr.start();
try {
thr.join();
} catch (InterruptedException ex) {
// XXX OK, interrupted, just leaving.
}
}, "CLI Terminal Connection (interruptable)");
connectionThread.start();
connectionThread.join();
} | java |
protected static void validateSignature(final DataInput input) throws IOException {
final byte[] signatureBytes = new byte[4];
input.readFully(signatureBytes);
if (!Arrays.equals(ManagementProtocol.SIGNATURE, signatureBytes)) {
throw ProtocolLogger.ROOT_LOGGER.invalidSignature(Arrays.toString(signatureBytes));
}
} | java |
public static ManagementProtocolHeader parse(DataInput input) throws IOException {
validateSignature(input);
expectHeader(input, ManagementProtocol.VERSION_FIELD);
int version = input.readInt();
expectHeader(input, ManagementProtocol.TYPE);
byte type = input.readByte();
switch (type) {
case ManagementProtocol.TYPE_REQUEST:
return new ManagementRequestHeader(version, input);
case ManagementProtocol.TYPE_RESPONSE:
return new ManagementResponseHeader(version, input);
case ManagementProtocol.TYPE_BYE_BYE:
return new ManagementByeByeHeader(version);
case ManagementProtocol.TYPE_PING:
return new ManagementPingHeader(version);
case ManagementProtocol.TYPE_PONG:
return new ManagementPongHeader(version);
default:
throw ProtocolLogger.ROOT_LOGGER.invalidType("0x" + Integer.toHexString(type));
}
} | java |
protected void checkConsecutiveAlpha() {
Pattern symbolsPatter = Pattern.compile(REGEX_ALPHA_UC + "+");
Matcher matcher = symbolsPatter.matcher(this.password);
int met = 0;
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
if (start == end) {
continue;
}
int diff = end - start;
if (diff >= 3) {
met += diff;
}
}
this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);
// alpha lower case
symbolsPatter = Pattern.compile(REGEX_ALPHA_LC + "+");
matcher = symbolsPatter.matcher(this.password);
met = 0;
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
if (start == end) {
continue;
}
int diff = end - start;
if (diff >= 3) {
met += diff;
}
}
this.result.negative(met * CONSECUTIVE_ALPHA_WEIGHT);
} | java |
public static ModelNode createBootUpdates(final String serverName, final ModelNode domainModel, final ModelNode hostModel,
final DomainController domainController, final ExpressionResolver expressionResolver) {
final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory(serverName, domainModel,
hostModel, domainController, expressionResolver);
return factory.getBootUpdates();
} | java |
private synchronized HostServerGroupEffect getMappableDomainEffect(PathAddress address, String key,
Map<String, Set<String>> map, Resource root) {
if (requiresMapping) {
map(root);
requiresMapping = false;
}
Set<String> mapped = map.get(key);
return mapped != null ? HostServerGroupEffect.forDomain(address, mapped)
: HostServerGroupEffect.forUnassignedDomain(address);
} | java |
private synchronized HostServerGroupEffect getHostEffect(PathAddress address, String host, Resource root) {
if (requiresMapping) {
map(root);
requiresMapping = false;
}
Set<String> mapped = hostsToGroups.get(host);
if (mapped == null) {
// Unassigned host. Treat like an unassigned profile or socket-binding-group;
// i.e. available to all server group scoped roles.
// Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs
Resource hostResource = root.getChild(PathElement.pathElement(HOST, host));
if (hostResource != null) {
ModelNode dcModel = hostResource.getModel().get(DOMAIN_CONTROLLER);
if (!dcModel.hasDefined(REMOTE)) {
mapped = Collections.emptySet(); // prevents returning HostServerGroupEffect.forUnassignedHost(address, host)
}
}
}
return mapped == null ? HostServerGroupEffect.forUnassignedHost(address, host)
: HostServerGroupEffect.forMappedHost(address, mapped, host);
} | java |
private void map(Resource root) {
for (Resource.ResourceEntry serverGroup : root.getChildren(SERVER_GROUP)) {
String serverGroupName = serverGroup.getName();
ModelNode serverGroupModel = serverGroup.getModel();
String profile = serverGroupModel.require(PROFILE).asString();
store(serverGroupName, profile, profilesToGroups);
String socketBindingGroup = serverGroupModel.require(SOCKET_BINDING_GROUP).asString();
store(serverGroupName, socketBindingGroup, socketsToGroups);
for (Resource.ResourceEntry deployment : serverGroup.getChildren(DEPLOYMENT)) {
store(serverGroupName, deployment.getName(), deploymentsToGroups);
}
for (Resource.ResourceEntry overlay : serverGroup.getChildren(DEPLOYMENT_OVERLAY)) {
store(serverGroupName, overlay.getName(), overlaysToGroups);
}
}
for (Resource.ResourceEntry host : root.getChildren(HOST)) {
String hostName = host.getPathElement().getValue();
for (Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {
ModelNode serverConfigModel = serverConfig.getModel();
String serverGroupName = serverConfigModel.require(GROUP).asString();
store(serverGroupName, hostName, hostsToGroups);
}
}
} | java |
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
for (AttributeAccess attr : attributes.values()) {
resourceRegistration.registerReadOnlyAttribute(attr.getAttributeDefinition(), null);
}
} | java |
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
// Register wildcard children last to prevent duplicate registration errors when override definitions exist
for (ResourceDefinition rd : singletonChildren) {
resourceRegistration.registerSubModel(rd);
}
for (ResourceDefinition rd : wildcardChildren) {
resourceRegistration.registerSubModel(rd);
}
} | java |
public static void installDomainConnectorServices(final OperationContext context,
final ServiceTarget serviceTarget,
final ServiceName endpointName,
final ServiceName networkInterfaceBinding,
final int port,
final OptionMap options,
final ServiceName securityRealm,
final ServiceName saslAuthenticationFactory,
final ServiceName sslContext) {
String sbmCap = "org.wildfly.management.socket-binding-manager";
ServiceName sbmName = context.hasOptionalCapability(sbmCap, NATIVE_MANAGEMENT_RUNTIME_CAPABILITY.getName(), null)
? context.getCapabilityServiceName(sbmCap, SocketBindingManager.class) : null;
installConnectorServicesForNetworkInterfaceBinding(serviceTarget, endpointName, MANAGEMENT_CONNECTOR,
networkInterfaceBinding, port, options, securityRealm, saslAuthenticationFactory, sslContext, sbmName);
} | java |
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 |
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 |
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 |
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 |
PathAddress toPathAddress(final ObjectName name) {
return ObjectNameAddressUtil.toPathAddress(rootObjectInstance.getObjectName(), getRootResourceAndRegistration().getRegistration(), name);
} | java |
public static TransactionalProtocolClient createClient(final ManagementChannelHandler channelAssociation) {
final TransactionalProtocolClientImpl client = new TransactionalProtocolClientImpl(channelAssociation);
channelAssociation.addHandlerFactory(client);
return client;
} | java |
public static TransactionalProtocolClient.Operation wrap(final ModelNode operation, final OperationMessageHandler messageHandler, final OperationAttachments attachments) {
return new TransactionalOperationImpl(operation, messageHandler, attachments);
} | java |
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 |
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 |
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 |
public void rollback() throws GitAPIException {
try (Git git = getGit()) {
git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();
}
} | java |
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 |
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 |
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 |
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 |
void addOption(final String value) {
Assert.checkNotNullParam("value", value);
synchronized (options) {
options.add(value);
}
} | java |
@SuppressWarnings("unchecked")
public static <T> AttachmentKey<T> create(final Class<? super T> valueClass) {
return new SimpleAttachmentKey(valueClass);
} | java |
InputStream openContentStream(final ContentItem item) throws IOException {
final File file = getFile(item);
if (file == null) {
throw new IllegalStateException();
}
return new FileInputStream(file);
} | java |
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 |
@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 |
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 |
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 |
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 |
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 |
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 |
public void addOrderedChildResourceTypes(PathAddress resourceAddress, Resource resource) {
Set<String> orderedChildTypes = resource.getOrderedChildTypes();
if (orderedChildTypes.size() > 0) {
orderedChildren.put(resourceAddress, resource.getOrderedChildTypes());
}
} | java |
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 |
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 |
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 |
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 |
@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 |
@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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
void commitTempFile(File temp) throws ConfigurationPersistenceException {
if (!doneBootup.get()) {
return;
}
if (!interactionPolicy.isReadOnly()) {
FilePersistenceUtils.moveTempFileToMain(temp, mainFile);
} else {
FilePersistenceUtils.moveTempFileToMain(temp, lastFile);
}
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
private ResultAction getFailedResultAction(Throwable cause) {
if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()
|| (cause != null && !(cause instanceof OperationFailedException))) {
return ResultAction.ROLLBACK;
}
return ResultAction.KEEP;
} | java |
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 |
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 |
public void set(final Argument argument) {
if (argument != null) {
map.put(argument.getKey(), Collections.singleton(argument));
}
} | java |
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 |
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 |
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 |
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 |
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 |
@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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
@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 |
public synchronized void addShutdownListener(ShutdownListener listener) {
if (state == CLOSED) {
listener.handleCompleted();
} else {
listeners.add(listener);
}
} | java |
protected synchronized void handleCompleted() {
latch.countDown();
for (final ShutdownListener listener : listeners) {
listener.handleCompleted();
}
listeners.clear();
} | java |
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 |
public ModelNode getDeploymentSubsystemModel(final String subsystemName) {
assert subsystemName != null : "The subsystemName cannot be null";
return getDeploymentSubModel(subsystemName, PathAddress.EMPTY_ADDRESS, null, deploymentUnit);
} | java |
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 |
static Resource getOrCreateSubDeployment(final String deploymentName, final DeploymentUnit parent) {
final Resource root = parent.getAttachment(DEPLOYMENT_RESOURCE);
return getOrCreate(root, PathElement.pathElement(SUBDEPLOYMENT, deploymentName));
} | java |
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 |
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 |
static Path resolvePath(final Path base, final String... paths) {
return Paths.get(base.toString(), paths);
} | java |
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 |
public DiscreteInterval plus(DiscreteInterval other) {
return new DiscreteInterval(this.min + other.min, this.max + other.max);
} | java |
public DiscreteInterval minus(DiscreteInterval other) {
return new DiscreteInterval(this.min - other.max, this.max - other.min);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.