code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
private Set<String> checkModel(final ModelNode model, TransformationContext context) throws OperationFailedException {
final Set<String> attributes = new HashSet<String>();
AttributeTransformationRequirementChecker checker;
for (final String attribute : attributeNames) {
if (model.hasDefined(attribute)) {
if (attributeCheckers != null && (checker = attributeCheckers.get(attribute)) != null) {
if (checker.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {
attributes.add(attribute);
}
} else if (SIMPLE_EXPRESSIONS.isAttributeTransformationRequired(attribute, model.get(attribute), context)) {
attributes.add(attribute);
}
}
}
return attributes;
} | java |
public void setValue(String propName, Object value) {
for (RequestProp prop : props) {
if (prop.getName().equals(propName)) {
JComponent valComp = prop.getValueComponent();
if (valComp instanceof JTextComponent) {
((JTextComponent)valComp).setText(value.toString());
}
if (valComp instanceof AbstractButton) {
((AbstractButton)valComp).setSelected((Boolean)value);
}
if (valComp instanceof JComboBox) {
((JComboBox)valComp).setSelectedItem(value);
}
return;
}
}
} | java |
static void doDifference(
Map<String, String> left,
Map<String, String> right,
Map<String, String> onlyOnLeft,
Map<String, String> onlyOnRight,
Map<String, String> updated
) {
onlyOnRight.clear();
onlyOnRight.putAll(right);
for (Map.Entry<String, String> entry : left.entrySet()) {
String leftKey = entry.getKey();
String leftValue = entry.getValue();
if (right.containsKey(leftKey)) {
String rightValue = onlyOnRight.remove(leftKey);
if (!leftValue.equals(rightValue)) {
updated.put(leftKey, leftValue);
}
} else {
onlyOnLeft.put(leftKey, leftValue);
}
}
} | java |
public void close() throws IOException {
final ManagedBinding binding = this.socketBindingManager.getNamedRegistry().getManagedBinding(this.name);
if (binding == null) {
return;
}
binding.close();
} | java |
public static boolean requiresReload(final Set<Flag> flags) {
return flags.contains(Flag.RESTART_ALL_SERVICES) || flags.contains(Flag.RESTART_RESOURCE_SERVICES);
} | java |
@Override
protected void updateState(final String name, final InstallationModificationImpl modification, final InstallationModificationImpl.InstallationState state) {
final PatchableTarget.TargetInfo identityInfo = modification.getModifiedState();
this.identity = new Identity() {
@Override
public String getVersion() {
return modification.getVersion();
}
@Override
public String getName() {
return name;
}
@Override
public TargetInfo loadTargetInfo() throws IOException {
return identityInfo;
}
@Override
public DirectoryStructure getDirectoryStructure() {
return modification.getDirectoryStructure();
}
};
this.allPatches = Collections.unmodifiableList(modification.getAllPatches());
this.layers.clear();
for (final Map.Entry<String, MutableTargetImpl> entry : state.getLayers().entrySet()) {
final String layerName = entry.getKey();
final MutableTargetImpl target = entry.getValue();
putLayer(layerName, new LayerInfo(layerName, target.getModifiedState(), target.getDirectoryStructure()));
}
this.addOns.clear();
for (final Map.Entry<String, MutableTargetImpl> entry : state.getAddOns().entrySet()) {
final String addOnName = entry.getKey();
final MutableTargetImpl target = entry.getValue();
putAddOn(addOnName, new LayerInfo(addOnName, target.getModifiedState(), target.getDirectoryStructure()));
}
} | java |
public static Set<String> listAllLinks(OperationContext context, String overlay) {
Set<String> serverGoupNames = listServerGroupsReferencingOverlay(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS), overlay);
Set<String> links = new HashSet<>();
for (String serverGoupName : serverGoupNames) {
links.addAll(listLinks(context, PathAddress.pathAddress(
PathElement.pathElement(SERVER_GROUP, serverGoupName),
PathElement.pathElement(DEPLOYMENT_OVERLAY, overlay))));
}
return links;
} | java |
public static Set<String> listLinks(OperationContext context, PathAddress overlayAddress) {
Resource overlayResource = context.readResourceFromRoot(overlayAddress);
if (overlayResource.hasChildren(DEPLOYMENT)) {
return overlayResource.getChildrenNames(DEPLOYMENT);
}
return Collections.emptySet();
} | java |
public static void redeployDeployments(OperationContext context, PathAddress deploymentsRootAddress, Set<String> deploymentNames) throws OperationFailedException {
for (String deploymentName : deploymentNames) {
PathAddress address = deploymentsRootAddress.append(DEPLOYMENT, deploymentName);
OperationStepHandler handler = context.getRootResourceRegistration().getOperationHandler(address, REDEPLOY);
ModelNode operation = addRedeployStep(address);
ServerLogger.AS_ROOT_LOGGER.debugf("Redeploying %s at address %s with handler %s", deploymentName, address, handler);
assert handler != null;
assert operation.isDefined();
context.addStep(operation, handler, OperationContext.Stage.MODEL);
}
} | java |
public static void redeployLinksAndTransformOperation(OperationContext context, ModelNode removeOperation, PathAddress deploymentsRootAddress, Set<String> runtimeNames) throws OperationFailedException {
Set<String> deploymentNames = listDeployments(context.readResourceFromRoot(deploymentsRootAddress), runtimeNames);
Operations.CompositeOperationBuilder opBuilder = Operations.CompositeOperationBuilder.create();
if (deploymentNames.isEmpty()) {
for (String s : runtimeNames) {
ServerLogger.ROOT_LOGGER.debugf("We haven't found any deployment for %s in server-group %s", s, deploymentsRootAddress.getLastElement().getValue());
}
}
if(removeOperation != null) {
opBuilder.addStep(removeOperation);
}
for (String deploymentName : deploymentNames) {
opBuilder.addStep(addRedeployStep(deploymentsRootAddress.append(DEPLOYMENT, deploymentName)));
}
List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);
if (transformers == null) {
context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());
}
final ModelNode slave = opBuilder.build().getOperation();
transformers.add(new OverlayOperationTransmuter(slave, context.getCurrentAddress()));
} | java |
public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {
Set<Pattern> set = new HashSet<>();
for (String wildcardExpr : runtimeNames) {
Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);
set.add(pattern);
}
return listDeploymentNames(deploymentRootResource, set);
} | java |
public void execute(CommandHandler handler,
int timeout,
TimeUnit unit) throws
CommandLineException,
InterruptedException, ExecutionException, TimeoutException {
ExecutableBuilder builder = new ExecutableBuilder() {
CommandContext c = newTimeoutCommandContext(ctx);
@Override
public Executable build() {
return () -> {
handler.handle(c);
};
}
@Override
public CommandContext getCommandContext() {
return c;
}
};
execute(builder, timeout, unit);
} | java |
void execute(ExecutableBuilder builder,
int timeout,
TimeUnit unit) throws
CommandLineException,
InterruptedException, ExecutionException, TimeoutException {
Future<Void> task = executorService.submit(() -> {
builder.build().execute();
return null;
});
try {
if (timeout <= 0) { //Synchronous
task.get();
} else { // Guarded execution
try {
task.get(timeout, unit);
} catch (TimeoutException ex) {
// First make the context unusable
CommandContext c = builder.getCommandContext();
if (c instanceof TimeoutCommandContext) {
((TimeoutCommandContext) c).timeout();
}
// Then cancel the task.
task.cancel(true);
throw ex;
}
}
} catch (InterruptedException ex) {
// Could have been interrupted by user (Ctrl-C)
Thread.currentThread().interrupt();
cancelTask(task, builder.getCommandContext(), null);
// Interrupt running operation.
CommandContext c = builder.getCommandContext();
if (c instanceof TimeoutCommandContext) {
((TimeoutCommandContext) c).interrupted();
}
throw ex;
}
} | java |
public String getOriginalValue(ParsedCommandLine parsedLine, boolean required) throws CommandFormatException {
String value = null;
if(parsedLine.hasProperties()) {
if(index >= 0) {
List<String> others = parsedLine.getOtherProperties();
if(others.size() > index) {
return others.get(index);
}
}
value = parsedLine.getPropertyValue(fullName);
if(value == null && shortName != null) {
value = parsedLine.getPropertyValue(shortName);
}
}
if(required && value == null && !isPresent(parsedLine)) {
StringBuilder buf = new StringBuilder();
buf.append("Required argument ");
buf.append('\'').append(fullName).append('\'');
buf.append(" is missing.");
throw new CommandFormatException(buf.toString());
}
return value;
} | java |
public static void logBeforeExit(ExitLogger logger) {
try {
if (logged.compareAndSet(false, true)) {
logger.logExit();
}
} catch (Throwable ignored){
// ignored
}
} | java |
private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException {
final ParsedCommandLine args = ctx.getParsedCommandLine();
final String name = this.name.getValue(args, true);
if (name == null) {
throw new CommandFormatException(this.name + " is missing value.");
}
if (!ctx.isBatchMode() || failInBatch) {
if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) {
throw new CommandFormatException("Deployment overlay " + name + " does not exist.");
}
}
return name;
} | java |
public static ServiceName moduleSpecServiceName(ModuleIdentifier identifier) {
if (!isDynamicModule(identifier)) {
throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);
}
return MODULE_SPEC_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());
} | java |
public static ServiceName moduleResolvedServiceName(ModuleIdentifier identifier) {
if (!isDynamicModule(identifier)) {
throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);
}
return MODULE_RESOLVED_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());
} | java |
public static ServiceName moduleServiceName(ModuleIdentifier identifier) {
if (!identifier.getName().startsWith(MODULE_PREFIX)) {
throw ServerLogger.ROOT_LOGGER.missingModulePrefix(identifier, MODULE_PREFIX);
}
return MODULE_SERVICE_PREFIX.append(identifier.getName()).append(identifier.getSlot());
} | java |
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ServicesAttachment servicesAttachment = deploymentUnit.getAttachment(Attachments.SERVICES);
if (servicesAttachment == null || servicesAttachment.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) {
return; // Skip it if it has not been marked
}
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
if (module == null) {
return; // Skip deployments with no module
}
AttachmentList<DeploymentUnit> duList = deploymentUnit.getAttachment(Attachments.SUB_DEPLOYMENTS);
List<String> serviceAcitvatorList = new ArrayList<String>();
if (duList!=null && !duList.isEmpty()) {
for (DeploymentUnit du : duList) {
ServicesAttachment duServicesAttachment = du.getAttachment(Attachments.SERVICES);
for (String serv : duServicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {
serviceAcitvatorList.add(serv);
}
}
}
ServiceRegistry serviceRegistry = phaseContext.getServiceRegistry();
if (WildFlySecurityManager.isChecking()) {
//service registry allows you to modify internal server state across all deployments
//if a security manager is present we use a version that has permission checks
serviceRegistry = new SecuredServiceRegistry(serviceRegistry);
}
final ServiceActivatorContext serviceActivatorContext = new ServiceActivatorContextImpl(phaseContext.getServiceTarget(), serviceRegistry);
final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
for (ServiceActivator serviceActivator : module.loadService(ServiceActivator.class)) {
try {
for (String serv : servicesAttachment.getServiceImplementations(ServiceActivator.class.getName())) {
if (serv.compareTo(serviceActivator.getClass().getName()) == 0 && !serviceAcitvatorList.contains(serv)) {
serviceActivator.activate(serviceActivatorContext);
break;
}
}
} catch (ServiceRegistryException e) {
throw new DeploymentUnitProcessingException(e);
}
}
} finally {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);
}
} | java |
synchronized void openConnection(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {
boolean ok = false;
final Connection connection = connectionManager.connect();
try {
channelHandler.executeRequest(new ServerRegisterRequest(), null, callback);
// HC is the same version, so it will support sending the subject
channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IDENTITY, Boolean.TRUE);
channelHandler.getAttachments().attach(TransactionalProtocolClient.SEND_IN_VM, Boolean.TRUE);
channelHandler.addHandlerFactory(new TransactionalProtocolOperationHandler(controller, channelHandler, responseAttachmentSupport));
ok = true;
} finally {
if(!ok) {
connection.close();
}
}
} | java |
synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) {
if (getState() != State.OPEN) {
return;
}
// Update the configuration with the new credentials
final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration);
config.setCallbackHandler(createClientCallbackHandler(userName, authKey));
config.setUri(reconnectUri);
this.configuration = config;
final ReconnectRunner reconnectTask = this.reconnectRunner;
if (reconnectTask == null) {
final ReconnectRunner task = new ReconnectRunner();
task.callback = callback;
task.future = executorService.submit(task);
} else {
reconnectTask.callback = callback;
}
} | java |
synchronized boolean doReConnect() throws IOException {
// In case we are still connected, test the connection and see if we can reuse it
if(connectionManager.isConnected()) {
try {
final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();
result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much
return true;
} catch (Exception e) {
ServerLogger.AS_ROOT_LOGGER.debugf(e, "failed to ping the host-controller, going to reconnect");
}
// Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect
final Connection connection = connectionManager.getConnection();
StreamUtils.safeClose(connection);
if(connection != null) {
try {
// Wait for the connection to be closed
connection.awaitClosed();
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
boolean ok = false;
final Connection connection = connectionManager.connect();
try {
// Reconnect to the host-controller
final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);
try {
boolean inSync = result.getResult().get();
ok = true;
reconnectRunner = null;
return inSync;
} catch (ExecutionException e) {
throw new IOException(e);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
} finally {
if(!ok) {
StreamUtils.safeClose(connection);
}
}
} | java |
synchronized void started() {
try {
if(isConnected()) {
channelHandler.executeRequest(new ServerStartedRequest(), null).getResult().await();
}
} catch (Exception e) {
ServerLogger.AS_ROOT_LOGGER.debugf(e, "failed to send started notification");
}
} | java |
public int executeTask(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, final ServerUpdateTask task) {
try {
return execute(listener, task.getServerIdentity(), task.getOperation());
} catch (OperationFailedException e) {
// Handle failures operation transformation failures
final ServerIdentity identity = task.getServerIdentity();
final ServerOperation serverOperation = new ServerOperation(identity, task.getOperation(), null, null, OperationResultTransformer.ORIGINAL_RESULT);
final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);
listener.operationPrepared(result);
recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), OperationResultTransformer.ORIGINAL_RESULT));
return 1; // 1 ms timeout since there is no reason to wait for the locally stored result
}
} | java |
protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {
if(client == null) {
return false;
}
final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);
final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);
final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);
try {
DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef("Sending %s to %s", operation, identity);
final Future<OperationResponse> result = client.execute(listener, serverOperation);
recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));
} catch (IOException e) {
final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);
listener.operationPrepared(result);
recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));
}
return true;
} | java |
void recordPreparedOperation(final TransactionalProtocolClient.PreparedOperation<ServerTaskExecutor.ServerOperation> preparedOperation) {
recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(preparedOperation));
} | java |
void recordOperationPrepareTimeout(final BlockingQueueOperationListener.FailedOperation<ServerOperation> failedOperation) {
recordPreparedTask(new ServerTaskExecutor.ServerPreparedResponse(failedOperation));
// Swap out the submitted task so we don't wait for the final result. Use a future the returns
// prepared response
ServerIdentity identity = failedOperation.getOperation().getIdentity();
AsyncFuture<OperationResponse> finalResult = failedOperation.getFinalResult();
synchronized (submittedTasks) {
submittedTasks.put(identity, new ServerTaskExecutor.ExecutedServerRequest(identity, finalResult));
}
} | java |
public static ServiceController<InstallationManager> installService(ServiceTarget serviceTarget) {
final InstallationManagerService service = new InstallationManagerService();
return serviceTarget.addService(InstallationManagerService.NAME, service)
.addDependency(JBOSS_PRODUCT_CONFIG_SERVICE, ProductConfig.class, service.productConfig)
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
} | java |
public Method getMethod(Method method) {
return getMethod(method.getReturnType(), method.getName(), method.getParameterTypes());
} | java |
public Collection<Method> getAllMethods(String name) {
final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);
if (nameMap == null) {
return Collections.emptySet();
}
final Collection<Method> methods = new ArrayList<Method>();
for (Map<Class<?>, Method> map : nameMap.values()) {
methods.addAll(map.values());
}
return methods;
} | java |
public Collection<Method> getAllMethods(String name, int paramCount) {
final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);
if (nameMap == null) {
return Collections.emptySet();
}
final Collection<Method> methods = new ArrayList<Method>();
for (Map<Class<?>, Method> map : nameMap.values()) {
for (Method method : map.values()) {
if (method.getParameterTypes().length == paramCount) {
methods.add(method);
}
}
}
return methods;
} | java |
public static ServiceActivator create(final ModelNode endpointConfig, final URI managementURI, final String serverName, final String serverProcessName,
final String authKey, final boolean managementSubsystemEndpoint, final Supplier<SSLContext> sslContextSupplier) {
return new DomainServerCommunicationServices(endpointConfig, managementURI, serverName, serverProcessName, authKey, managementSubsystemEndpoint, sslContextSupplier);
} | java |
public InetSocketAddress getMulticastSocketAddress() {
if (multicastAddress == null) {
throw MESSAGES.noMulticastBinding(name);
}
return new InetSocketAddress(multicastAddress, multicastPort);
} | java |
public ServerSocket createServerSocket() throws IOException {
final ServerSocket socket = getServerSocketFactory().createServerSocket(name);
socket.bind(getSocketAddress());
return socket;
} | java |
public static void registerDeploymentResource(final DeploymentResourceSupport deploymentResourceSupport, final LoggingConfigurationService service) {
final PathElement base = PathElement.pathElement("configuration", service.getConfiguration());
deploymentResourceSupport.getDeploymentSubModel(LoggingExtension.SUBSYSTEM_NAME, base);
final LogContextConfiguration configuration = service.getValue();
// Register the child resources if the configuration is not null in cases where a log4j configuration was used
if (configuration != null) {
registerDeploymentResource(deploymentResourceSupport, base, HANDLER, configuration.getHandlerNames());
registerDeploymentResource(deploymentResourceSupport, base, LOGGER, configuration.getLoggerNames());
registerDeploymentResource(deploymentResourceSupport, base, FORMATTER, configuration.getFormatterNames());
registerDeploymentResource(deploymentResourceSupport, base, FILTER, configuration.getFilterNames());
registerDeploymentResource(deploymentResourceSupport, base, POJO, configuration.getPojoNames());
registerDeploymentResource(deploymentResourceSupport, base, ERROR_MANAGER, configuration.getErrorManagerNames());
}
} | java |
public static String constructUrl(final HttpServerExchange exchange, final String path) {
final HeaderMap headers = exchange.getRequestHeaders();
String host = headers.getFirst(HOST);
String protocol = exchange.getConnection().getSslSessionInfo() != null ? "https" : "http";
return protocol + "://" + host + path;
} | java |
public boolean matches(Property property) {
return property.getName().equals(key) && (value == WILDCARD_VALUE || property.getValue().asString().equals(value));
} | java |
public boolean matches(PathElement pe) {
return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));
} | java |
public void setAppender(final Appender appender) {
if (this.appender != null) {
close();
}
checkAccess(this);
if (applyLayout && appender != null) {
final Formatter formatter = getFormatter();
appender.setLayout(formatter == null ? null : new FormatterLayout(formatter));
}
appenderUpdater.set(this, appender);
} | java |
private ModelNode createOSNode() throws OperationFailedException {
String osName = getProperty("os.name");
final ModelNode os = new ModelNode();
if (osName != null && osName.toLowerCase().contains("linux")) {
try {
os.set(GnuLinuxDistribution.discover());
} catch (IOException ex) {
throw new OperationFailedException(ex);
}
} else {
os.set(osName);
}
return os;
} | java |
private ModelNode createJVMNode() throws OperationFailedException {
ModelNode jvm = new ModelNode().setEmptyObject();
jvm.get(NAME).set(getProperty("java.vm.name"));
jvm.get(JAVA_VERSION).set(getProperty("java.vm.specification.version"));
jvm.get(JVM_VERSION).set(getProperty("java.version"));
jvm.get(JVM_VENDOR).set(getProperty("java.vm.vendor"));
jvm.get(JVM_HOME).set(getProperty("java.home"));
return jvm;
} | java |
private ModelNode createCPUNode() throws OperationFailedException {
ModelNode cpu = new ModelNode().setEmptyObject();
cpu.get(ARCH).set(getProperty("os.arch"));
cpu.get(AVAILABLE_PROCESSORS).set(ProcessorInfo.availableProcessors());
return cpu;
} | java |
private String getProperty(String name) {
return System.getSecurityManager() == null ? System.getProperty(name) : doPrivileged(new ReadPropertyAction(name));
} | java |
public void explore() {
if (isLeaf) return;
if (isGeneric) return;
removeAllChildren();
try {
String addressPath = addressPath();
ModelNode resourceDesc = executor.doCommand(addressPath + ":read-resource-description");
resourceDesc = resourceDesc.get("result");
ModelNode response = executor.doCommand(addressPath + ":read-resource(include-runtime=true,include-defaults=true)");
ModelNode result = response.get("result");
if (!result.isDefined()) return;
List<String> childrenTypes = getChildrenTypes(addressPath);
for (ModelNode node : result.asList()) {
Property prop = node.asProperty();
if (childrenTypes.contains(prop.getName())) { // resource node
if (hasGenericOperations(addressPath, prop.getName())) {
add(new ManagementModelNode(cliGuiCtx, new UserObject(node, prop.getName())));
}
if (prop.getValue().isDefined()) {
for (ModelNode innerNode : prop.getValue().asList()) {
UserObject usrObj = new UserObject(innerNode, prop.getName(), innerNode.asProperty().getName());
add(new ManagementModelNode(cliGuiCtx, usrObj));
}
}
} else { // attribute node
UserObject usrObj = new UserObject(node, resourceDesc, prop.getName(), prop.getValue().asString());
add(new ManagementModelNode(cliGuiCtx, usrObj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | java |
public String addressPath() {
if (isLeaf) {
ManagementModelNode parent = (ManagementModelNode)getParent();
return parent.addressPath();
}
StringBuilder builder = new StringBuilder();
for (Object pathElement : getUserObjectPath()) {
UserObject userObj = (UserObject)pathElement;
if (userObj.isRoot()) { // don't want to escape root
builder.append(userObj.getName());
continue;
}
builder.append(userObj.getName());
builder.append("=");
builder.append(userObj.getEscapedValue());
builder.append("/");
}
return builder.toString();
} | java |
private static boolean mayBeIPv6Address(String input) {
if (input == null) {
return false;
}
boolean result = false;
int colonsCounter = 0;
int length = input.length();
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == '.' || c == '%') {
// IPv4 in IPv6 or Zone ID detected, end of checking.
break;
}
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F') || c == ':')) {
return false;
} else if (c == ':') {
colonsCounter++;
}
}
if (colonsCounter >= 2) {
result = true;
}
return result;
} | java |
public static void initializeDomainRegistry(final TransformerRegistry registry) {
//The chains for transforming will be as follows
//For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0
registerRootTransformers(registry);
registerChainedManagementTransformers(registry);
registerChainedServerGroupTransformers(registry);
registerProfileTransformers(registry);
registerSocketBindingGroupTransformers(registry);
registerDeploymentTransformers(registry);
} | java |
static boolean killProcess(final String processName, int id) {
int pid;
try {
pid = processUtils.resolveProcessId(processName, id);
if(pid > 0) {
try {
Runtime.getRuntime().exec(processUtils.getKillCommand(pid));
return true;
} catch (Throwable t) {
ProcessLogger.ROOT_LOGGER.debugf(t, "failed to kill process '%s' with pid '%s'", processName, pid);
}
}
} catch (Throwable t) {
ProcessLogger.ROOT_LOGGER.debugf(t, "failed to resolve pid of process '%s'", processName);
}
return false;
} | java |
public Launcher addEnvironmentVariable(final String key, final String value) {
env.put(key, value);
return this;
} | java |
private void buildTransformers_3_0(ResourceTransformationDescriptionBuilder builder) {
/*
====== Resource root address: ["subsystem" => "remoting"] - Current version: 4.0.0; legacy version: 3.0.0 =======
--- Problems for relative address to root ["configuration" => "endpoint"]:
Different 'default' for attribute 'sasl-protocol'. Current: "remote"; legacy: "remoting" ## both are valid also for legacy servers
--- Problems for relative address to root ["connector" => "*"]:
Missing attributes in current: []; missing in legacy [sasl-authentication-factory, ssl-context]
Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory, ssl-context]
--- Problems for relative address to root ["http-connector" => "*"]:
Missing attributes in current: []; missing in legacy [sasl-authentication-factory]
Missing parameters for operation 'add' in current: []; missing in legacy [sasl-authentication-factory]
--- Problems for relative address to root ["remote-outbound-connection" => "*"]:
Missing attributes in current: []; missing in legacy [authentication-context]
Different 'alternatives' for attribute 'protocol'. Current: ["authentication-context"]; legacy: undefined
Different 'alternatives' for attribute 'security-realm'. Current: ["authentication-context"]; legacy: undefined
Different 'alternatives' for attribute 'username'. Current: ["authentication-context"]; legacy: undefined
Missing parameters for operation 'add' in current: []; missing in legacy [authentication-context]
Different 'alternatives' for parameter 'protocol' of operation 'add'. Current: ["authentication-context"]; legacy: undefined
Different 'alternatives' for parameter 'security-realm' of operation 'add'. Current: ["authentication-context"]; legacy: undefined
Different 'alternatives' for parameter 'username' of operation 'add'. Current: ["authentication-context"]; legacy: undefined
*/
builder.addChildResource(ConnectorResource.PATH).getAttributeBuilder()
.setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT)
.addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY, ConnectorResource.SSL_CONTEXT);
builder.addChildResource(RemotingEndpointResource.ENDPOINT_PATH).getAttributeBuilder()
.setValueConverter(new AttributeConverter.DefaultAttributeConverter() {
@Override
protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {
if (!attributeValue.isDefined()) {
attributeValue.set("remoting"); //if value is not defined, set it to EAP 7.0 default valueRemotingSubsystemTransformersTestCase
}
}
}, RemotingSubsystemRootResource.SASL_PROTOCOL);
builder.addChildResource(HttpConnectorResource.PATH).getAttributeBuilder()
.setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)
.addRejectCheck(RejectAttributeChecker.DEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY);
builder.addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS).getAttributeBuilder()
.setDiscard(DiscardAttributeChecker.UNDEFINED, ConnectorCommon.SASL_AUTHENTICATION_FACTORY)
.addRejectCheck(RejectAttributeChecker.DEFINED, RemoteOutboundConnectionResourceDefinition.AUTHENTICATION_CONTEXT);
} | java |
private void buildTransformers_4_0(ResourceTransformationDescriptionBuilder builder) {
// We need to do custom transformation of the attribute in the root resource
// related to endpoint configs, as these were moved to the root from a previous child resource
EndPointWriteTransformer endPointWriteTransformer = new EndPointWriteTransformer();
builder.getAttributeBuilder()
.setDiscard(DiscardAttributeChecker.ALWAYS, endpointAttrArray)
.end()
.addOperationTransformationOverride("add")
//.inheritResourceAttributeDefinitions() // don't inherit as we discard
.setCustomOperationTransformer(new EndPointAddTransformer())
.end()
.addOperationTransformationOverride("write-attribute")
//.inheritResourceAttributeDefinitions() // don't inherit as we discard
.setCustomOperationTransformer(endPointWriteTransformer)
.end()
.addOperationTransformationOverride("undefine-attribute")
//.inheritResourceAttributeDefinitions() // don't inherit as we discard
.setCustomOperationTransformer(endPointWriteTransformer)
.end();
} | java |
ServerStatus getState() {
final InternalState requiredState = this.requiredState;
final InternalState state = internalState;
if(requiredState == InternalState.FAILED) {
return ServerStatus.FAILED;
}
switch (state) {
case STOPPED:
return ServerStatus.STOPPED;
case SERVER_STARTED:
return ServerStatus.STARTED;
default: {
if(requiredState == InternalState.SERVER_STARTED) {
return ServerStatus.STARTING;
} else {
return ServerStatus.STOPPING;
}
}
}
} | java |
synchronized boolean reload(int permit, boolean suspend) {
return internalSetState(new ReloadTask(permit, suspend), InternalState.SERVER_STARTED, InternalState.RELOADING);
} | java |
synchronized void start(final ManagedServerBootCmdFactory factory) {
final InternalState required = this.requiredState;
// Ignore if the server is already started
if(required == InternalState.SERVER_STARTED) {
return;
}
// In case the server failed to start, try to start it again
if(required != InternalState.FAILED) {
final InternalState current = this.internalState;
if(current != required) {
// TODO this perhaps should wait?
throw new IllegalStateException();
}
}
operationID = CurrentOperationIdHolder.getCurrentOperationID();
bootConfiguration = factory.createConfiguration();
requiredState = InternalState.SERVER_STARTED;
ROOT_LOGGER.startingServer(serverName);
transition();
} | java |
synchronized void stop(Integer timeout) {
final InternalState required = this.requiredState;
if(required != InternalState.STOPPED) {
this.requiredState = InternalState.STOPPED;
ROOT_LOGGER.stoppingServer(serverName);
// Only send the stop operation if the server is started
if (internalState == InternalState.SERVER_STARTED) {
internalSetState(new ServerStopTask(timeout), internalState, InternalState.PROCESS_STOPPING);
} else {
transition(false);
}
}
} | java |
synchronized void reconnectServerProcess(final ManagedServerBootCmdFactory factory) {
if(this.requiredState != InternalState.SERVER_STARTED) {
this.bootConfiguration = factory;
this.requiredState = InternalState.SERVER_STARTED;
ROOT_LOGGER.reconnectingServer(serverName);
internalSetState(new ReconnectTask(), InternalState.STOPPED, InternalState.SEND_STDIN);
}
} | java |
synchronized void removeServerProcess() {
this.requiredState = InternalState.STOPPED;
internalSetState(new ProcessRemoveTask(), InternalState.STOPPED, InternalState.PROCESS_REMOVING);
} | java |
synchronized void setServerProcessStopping() {
this.requiredState = InternalState.STOPPED;
internalSetState(null, InternalState.STOPPED, InternalState.PROCESS_STOPPING);
} | java |
boolean awaitState(final InternalState expected) {
synchronized (this) {
final InternalState initialRequired = this.requiredState;
for(;;) {
final InternalState required = this.requiredState;
// Stop in case the server failed to reach the state
if(required == InternalState.FAILED) {
return false;
// Stop in case the required state changed
} else if (initialRequired != required) {
return false;
}
final InternalState current = this.internalState;
if(expected == current) {
return true;
}
try {
wait();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
}
} | java |
boolean processUnstable() {
boolean change = !unstable;
if (change) { // Only once until the process is removed. A process is unstable until removed.
unstable = true;
HostControllerLogger.ROOT_LOGGER.managedServerUnstable(serverName);
}
return change;
} | java |
boolean callbackUnregistered(final TransactionalProtocolClient old, final boolean shuttingDown) {
// Disconnect the remote connection.
// WFCORE-196 Do this out of the sync block to avoid deadlocks where in-flight requests can't
// be informed that the channel has closed
protocolClient.disconnected(old);
synchronized (this) {
// If the connection dropped without us stopping the process ask for reconnection
if (!shuttingDown && requiredState == InternalState.SERVER_STARTED) {
final InternalState state = internalState;
if (state == InternalState.PROCESS_STOPPED
|| state == InternalState.PROCESS_STOPPING
|| state == InternalState.STOPPED) {
// In case it stopped we don't reconnect
return true;
}
// In case we are reloading, it will reconnect automatically
if (state == InternalState.RELOADING) {
return true;
}
try {
ROOT_LOGGER.logf(DEBUG_LEVEL, "trying to reconnect to %s current-state (%s) required-state (%s)", serverName, state, requiredState);
internalSetState(new ReconnectTask(), state, InternalState.SEND_STDIN);
} catch (Exception e) {
ROOT_LOGGER.logf(DEBUG_LEVEL, e, "failed to send reconnect task");
}
return false;
} else {
return true;
}
}
} | java |
synchronized void processFinished() {
final InternalState required = this.requiredState;
final InternalState state = this.internalState;
// If the server was not stopped
if(required == InternalState.STOPPED && state == InternalState.PROCESS_STOPPING) {
finishTransition(InternalState.PROCESS_STOPPING, InternalState.PROCESS_STOPPED);
} else {
this.requiredState = InternalState.STOPPED;
if ( !(internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), internalState, InternalState.PROCESS_STOPPING)
&& internalSetState(getTransitionTask(InternalState.PROCESS_REMOVING), internalState, InternalState.PROCESS_REMOVING)
&& internalSetState(getTransitionTask(InternalState.STOPPED), internalState, InternalState.STOPPED)) ){
this.requiredState = InternalState.FAILED;
internalSetState(null, internalState, InternalState.PROCESS_STOPPED);
}
}
} | java |
synchronized void transitionFailed(final InternalState state) {
final InternalState current = this.internalState;
if(state == current) {
// Revert transition and mark as failed
switch (current) {
case PROCESS_ADDING:
this.internalState = InternalState.PROCESS_STOPPED;
break;
case PROCESS_STARTED:
internalSetState(getTransitionTask(InternalState.PROCESS_STOPPING), InternalState.PROCESS_STARTED, InternalState.PROCESS_ADDED);
break;
case PROCESS_STARTING:
this.internalState = InternalState.PROCESS_ADDED;
break;
case SEND_STDIN:
case SERVER_STARTING:
this.internalState = InternalState.PROCESS_STARTED;
break;
}
this.requiredState = InternalState.FAILED;
notifyAll();
}
} | java |
private synchronized void finishTransition(final InternalState current, final InternalState next) {
internalSetState(getTransitionTask(next), current, next);
transition();
} | java |
@Override
public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {
if (capabilities!=null) {
for (RuntimeCapability c : capabilities) {
resourceRegistration.registerCapability(c);
}
}
if (incorporatingCapabilities != null) {
resourceRegistration.registerIncorporatingCapabilities(incorporatingCapabilities);
}
assert requirements != null;
resourceRegistration.registerRequirements(requirements);
} | java |
@Deprecated
@SuppressWarnings("deprecation")
protected void registerAddOperation(final ManagementResourceRegistration registration, final OperationStepHandler handler, OperationEntry.Flag... flags) {
if (handler instanceof DescriptionProvider) {
registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,
(DescriptionProvider) handler, OperationEntry.EntryType.PUBLIC,flags)
, handler);
} else {
registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD,
new DefaultResourceAddDescriptionProvider(registration, descriptionResolver, orderedChild),
OperationEntry.EntryType.PUBLIC,
flags)
, handler);
}
} | java |
private static void handlePing(final Channel channel, final ManagementProtocolHeader header) throws IOException {
final ManagementProtocolHeader response = new ManagementPongHeader(header.getVersion());
final MessageOutputStream output = channel.writeMessage();
try {
writeHeader(response, output);
output.close();
} finally {
StreamUtils.safeClose(output);
}
} | java |
public static String resolveOrOriginal(String input) {
try {
return resolve(input, true);
} catch (UnresolvedExpressionException e) {
return input;
}
} | java |
private OperationResponse executeForResult(final OperationExecutionContext executionContext) throws IOException {
try {
return execute(executionContext).get();
} catch(Exception e) {
throw new IOException(e);
}
} | java |
public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {
final File layersList = new File(repoRoot, LAYERS_CONF);
if (!layersList.exists()) {
return new LayersConfig();
}
final Properties properties = PatchUtils.loadProperties(layersList);
return new LayersConfig(properties);
} | java |
private boolean parseRemoteDomainControllerAttributes_1_5(final XMLExtendedStreamReader reader, final ModelNode address,
final List<ModelNode> list, boolean allowDiscoveryOptions) throws XMLStreamException {
final ModelNode update = new ModelNode();
update.get(OP_ADDR).set(address);
update.get(OP).set(RemoteDomainControllerAddHandler.OPERATION_NAME);
// Handle attributes
AdminOnlyDomainConfigPolicy adminOnlyPolicy = AdminOnlyDomainConfigPolicy.DEFAULT;
boolean requireDiscoveryOptions = false;
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));
switch (attribute) {
case HOST: {
DomainControllerWriteAttributeHandler.HOST.parseAndSetParameter(value, update, reader);
break;
}
case PORT: {
DomainControllerWriteAttributeHandler.PORT.parseAndSetParameter(value, update, reader);
break;
}
case SECURITY_REALM: {
DomainControllerWriteAttributeHandler.SECURITY_REALM.parseAndSetParameter(value, update, reader);
break;
}
case USERNAME: {
DomainControllerWriteAttributeHandler.USERNAME.parseAndSetParameter(value, update, reader);
break;
}
case ADMIN_ONLY_POLICY: {
DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.parseAndSetParameter(value, update, reader);
ModelNode nodeValue = update.get(DomainControllerWriteAttributeHandler.ADMIN_ONLY_POLICY.getName());
if (nodeValue.getType() != ModelType.EXPRESSION) {
adminOnlyPolicy = AdminOnlyDomainConfigPolicy.getPolicy(nodeValue.asString());
}
break;
}
default:
throw unexpectedAttribute(reader, i);
}
}
}
if (!update.hasDefined(DomainControllerWriteAttributeHandler.HOST.getName())) {
if (allowDiscoveryOptions) {
requireDiscoveryOptions = isRequireDiscoveryOptions(adminOnlyPolicy);
} else {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.HOST.getLocalName()));
}
}
if (!update.hasDefined(DomainControllerWriteAttributeHandler.PORT.getName())) {
if (allowDiscoveryOptions) {
requireDiscoveryOptions = requireDiscoveryOptions || isRequireDiscoveryOptions(adminOnlyPolicy);
} else {
throw ParseUtils.missingRequired(reader, Collections.singleton(Attribute.PORT.getLocalName()));
}
}
list.add(update);
return requireDiscoveryOptions;
} | java |
public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,
final ProxyOperationAddressTranslator addressTranslator,
final ModelVersion targetKernelVersion) {
return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);
} | java |
@Deprecated
public static RemoteProxyController create(final ManagementChannelHandler channelAssociation, final PathAddress pathAddress, final ProxyOperationAddressTranslator addressTranslator) {
final TransactionalProtocolClient client = TransactionalProtocolHandlers.createClient(channelAssociation);
// the remote proxy
return create(client, pathAddress, addressTranslator, ModelVersion.CURRENT);
} | java |
public ModelNode translateOperationForProxy(final ModelNode op) {
return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));
} | java |
private void flush(final boolean propagate) throws IOException {
final int avail = baseNCodec.available(context);
if (avail > 0) {
final byte[] buf = new byte[avail];
final int c = baseNCodec.readResults(buf, 0, avail, context);
if (c > 0) {
out.write(buf, 0, c);
}
}
if (propagate) {
out.flush();
}
} | java |
@Override
public void close() throws IOException {
// Notify encoder of EOF (-1).
if (doEncode) {
baseNCodec.encode(singleByte, 0, EOF, context);
} else {
baseNCodec.decode(singleByte, 0, EOF, context);
}
flush();
out.close();
} | java |
private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {
if (!node.isDefined()) {
return node;
}
ModelType type = node.getType();
ModelNode resolved;
if (type == ModelType.EXPRESSION) {
resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);
} else if (type == ModelType.OBJECT) {
resolved = node.clone();
for (Property prop : resolved.asPropertyList()) {
resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));
}
} else if (type == ModelType.LIST) {
resolved = node.clone();
ModelNode list = new ModelNode();
list.setEmptyList();
for (ModelNode current : resolved.asList()) {
list.add(resolveExpressionsRecursively(current));
}
resolved = list;
} else if (type == ModelType.PROPERTY) {
resolved = node.clone();
resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));
} else {
resolved = node;
}
return resolved;
} | java |
private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure,
final boolean initial) throws OperationFailedException {
ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure);
if (resolved.recursive) {
// Some part of expressionString resolved into a different expression.
// So, start over, ignoring failures. Ignore failures because we don't require
// that expressions must not resolve to something that *looks like* an expression but isn't
return resolveExpressionStringRecursively(resolved.result, true, false);
} else if (resolved.modified) {
// Typical case
return new ModelNode(resolved.result);
} else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) {
// We should only get an unmodified expression string back if there was a resolution
// failure that we ignored.
assert ignoreDMRResolutionFailure;
// expressionString came from a node of type expression, so since we did nothing send it back in the same type
return new ModelNode(new ValueExpression(expressionString));
} else {
// The string wasn't really an expression. Two possible cases:
// 1) if initial == true, someone created a expression node with a non-expression string, which is legal
// 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an
// expression but can't be resolved. We don't require that expressions must not resolve to something that
// *looks like* an expression but isn't, so we'll just treat this as a string
return new ModelNode(expressionString);
}
} | java |
private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {
// parseAndResolve should only be providing expressions with no leading or trailing chars
assert unresolvedString.startsWith("${") && unresolvedString.endsWith("}");
// Default result is no change from input
String result = unresolvedString;
ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));
// Try plug-in resolution; i.e. vault
resolvePluggableExpression(resolveNode);
if (resolveNode.getType() == ModelType.EXPRESSION ) {
// resolvePluggableExpression did nothing. Try standard resolution
String resolvedString = resolveStandardExpression(resolveNode);
if (!unresolvedString.equals(resolvedString)) {
// resolveStandardExpression made progress
result = resolvedString;
} // else there is nothing more we can do with this string
} else {
// resolvePluggableExpression made progress
result = resolveNode.asString();
}
return result;
} | java |
private static XMLStreamException unexpectedElement(final XMLStreamReader reader) {
return SecurityManagerLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());
} | java |
private static XMLStreamException unexpectedAttribute(final XMLStreamReader reader, final int index) {
return SecurityManagerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation());
} | java |
public static byte[] storeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws IOException, OperationFailedException {
if (!operation.hasDefined(CONTENT)) {
throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());
}
final ModelNode content = operation.get(CONTENT).get(0);
if (content.hasDefined(HASH)) {
// This should be handled as part of the OSH
throw createFailureException(DomainControllerLogger.ROOT_LOGGER.invalidContentDeclaration());
}
final byte[] hash = storeDeploymentContent(context, operation, contentRepository);
// Clear the contents and update with the hash
final ModelNode slave = operation.clone();
slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);
// Add the domain op transformer
List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);
if (transformers == null) {
context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());
}
transformers.add(new CompositeOperationAwareTransmuter(slave));
return hash;
} | java |
public static byte[] explodeContentAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {
final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);
ModelNode contentItem = getContentItem(deploymentResource);
ModelNode explodedPath = DEPLOYMENT_CONTENT_PATH.resolveModelAttribute(context, operation);
byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();
final byte[] hash;
if (explodedPath.isDefined()) {
hash = contentRepository.explodeSubContent(oldHash, explodedPath.asString());
} else {
hash = contentRepository.explodeContent(oldHash);
}
// Clear the contents and update with the hash
final ModelNode slave = operation.clone();
ModelNode addedContent = new ModelNode().setEmptyObject();
addedContent.get(HASH).set(hash);
addedContent.get(TARGET_PATH.getName()).set("./");
slave.get(CONTENT).setEmptyList().add(addedContent);
// Add the domain op transformer
List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);
if (transformers == null) {
context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());
}
transformers.add(new CompositeOperationAwareTransmuter(slave));
return hash;
} | java |
public static byte[] addContentToExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {
final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);
ModelNode contentItem = getContentItem(deploymentResource);
byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItem).asBytes();
List<ModelNode> contents = CONTENT_PARAM_ALL_EXPLODED.resolveModelAttribute(context, operation).asList();
final List<ExplodedContent> addedFiles = new ArrayList<>(contents.size());
final ModelNode slave = operation.clone();
ModelNode slaveAddedfiles = slave.get(UPDATED_PATHS.getName()).setEmptyList();
for(ModelNode content : contents) {
InputStream in;
if(hasValidContentAdditionParameterDefined(content)) {
in = getInputStream(context, content);
} else {
in = null;
}
String path = TARGET_PATH.resolveModelAttribute(context, content).asString();
addedFiles.add(new ExplodedContent(path, in));
slaveAddedfiles.add(path);
}
final boolean overwrite = OVERWRITE.resolveModelAttribute(context, operation).asBoolean(true);
final byte[] hash = contentRepository.addContentToExploded(oldHash, addedFiles, overwrite);
// Clear the contents and update with the hash
ModelNode addedContent = new ModelNode().setEmptyObject();
addedContent.get(HASH).set(hash);
addedContent.get(TARGET_PATH.getName()).set(".");
slave.get(CONTENT).setEmptyList().add(addedContent);
// Add the domain op transformer
List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);
if (transformers == null) {
context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());
}
transformers.add(new CompositeOperationAwareTransmuter(slave));
return hash;
} | java |
public static byte[] removeContentFromExplodedAndTransformOperation(OperationContext context, ModelNode operation, ContentRepository contentRepository) throws OperationFailedException, ExplodedContentException {
final Resource deploymentResource = context.readResource(PathAddress.EMPTY_ADDRESS);
ModelNode contentItemNode = getContentItem(deploymentResource);
final byte[] oldHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes();
final List<String> paths = REMOVED_PATHS.unwrap(context, operation);
final byte[] hash = contentRepository.removeContentFromExploded(oldHash, paths);
// Clear the contents and update with the hash
final ModelNode slave = operation.clone();
slave.get(CONTENT).setEmptyList().add().get(HASH).set(hash);
slave.get(CONTENT).add().get(ARCHIVE).set(false);
// Add the domain op transformer
List<DomainOperationTransmuter> transformers = context.getAttachment(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS);
if (transformers == null) {
context.attach(OperationAttachments.SLAVE_SERVER_OPERATION_TRANSMUTERS, transformers = new ArrayList<>());
}
transformers.add(new CompositeOperationAwareTransmuter(slave));
return hash;
} | java |
public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {
ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);
byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();
if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content
fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));
}
return newHash;
} | java |
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
for (ResourceRoot resourceRoot : DeploymentUtils.allResourceRoots(deploymentUnit)) {
ResourceRootIndexer.indexResourceRoot(resourceRoot);
}
} | java |
public static File newFile(File baseDir, String... segments) {
File f = baseDir;
for (String segment : segments) {
f = new File(f, segment);
}
return f;
} | java |
public PasswordCheckResult check(boolean isAdminitrative, String userName, String password) {
// TODO: allow custom restrictions?
List<PasswordRestriction> passwordValuesRestrictions = getPasswordRestrictions();
final PasswordStrengthCheckResult strengthResult = this.passwordStrengthChecker.check(userName, password, passwordValuesRestrictions);
final int failedRestrictions = strengthResult.getRestrictionFailures().size();
final PasswordStrength strength = strengthResult.getStrength();
final boolean strongEnough = assertStrength(strength);
PasswordCheckResult.Result resultAction;
String resultMessage = null;
if (isAdminitrative) {
if (strongEnough) {
if (failedRestrictions > 0) {
resultAction = Result.WARN;
resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();
} else {
resultAction = Result.ACCEPT;
}
} else {
resultAction = Result.WARN;
resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());
}
} else {
if (strongEnough) {
if (failedRestrictions > 0) {
resultAction = Result.REJECT;
resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();
} else {
resultAction = Result.ACCEPT;
}
} else {
if (failedRestrictions > 0) {
resultAction = Result.REJECT;
resultMessage = strengthResult.getRestrictionFailures().get(0).getMessage();
} else {
resultAction = Result.REJECT;
resultMessage = ROOT_LOGGER.passwordNotStrongEnough(strength.toString(), this.acceptable.toString());
}
}
}
return new PasswordCheckResult(resultAction, resultMessage);
} | java |
public String getCmdLineArg() {
StringBuilder builder = new StringBuilder(" --server-groups=");
boolean foundSelected = false;
for (JCheckBox serverGroup : serverGroups) {
if (serverGroup.isSelected()) {
foundSelected = true;
builder.append(serverGroup.getText());
builder.append(",");
}
}
builder.deleteCharAt(builder.length() - 1); // remove trailing comma
if (!foundSelected) return "";
return builder.toString();
} | java |
public static boolean isCompleteZip(File file) throws IOException, NonScannableZipException {
FileChannel channel = null;
try {
channel = new FileInputStream(file).getChannel();
long size = channel.size();
if (size < ENDLEN) { // Obvious case
return false;
}
else if (validateEndRecord(file, channel, size - ENDLEN)) { // typical case where file is complete and end record has no comment
return true;
}
// Either file is incomplete or the end of central directory record includes an arbitrary length comment
// So, we have to scan backwards looking for an end of central directory record
return scanForEndSig(file, channel);
}
finally {
safeClose(channel);
}
} | java |
private static boolean scanForEndSig(File file, FileChannel channel) throws IOException, NonScannableZipException {
// TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex
ByteBuffer bb = getByteBuffer(CHUNK_SIZE);
long start = channel.size();
long end = Math.max(0, start - MAX_REVERSE_SCAN);
long channelPos = Math.max(0, start - CHUNK_SIZE);
long lastChannelPos = channelPos;
boolean firstRead = true;
while (lastChannelPos >= end) {
read(bb, channel, channelPos);
int actualRead = bb.limit();
if (firstRead) {
long expectedRead = Math.min(CHUNK_SIZE, start);
if (actualRead > expectedRead) {
// File is still growing
return false;
}
firstRead = false;
}
int bufferPos = actualRead -1;
while (bufferPos >= SIG_PATTERN_LENGTH) {
// Following is based on the Boyer Moore algorithm but simplified to reflect
// a) the pattern is static
// b) the pattern has no repeating bytes
int patternPos;
for (patternPos = SIG_PATTERN_LENGTH - 1;
patternPos >= 0 && ENDSIG_PATTERN[patternPos] == bb.get(bufferPos - patternPos);
--patternPos) {
// empty loop while bytes match
}
// Switch gives same results as checking the "good suffix array" in the Boyer Moore algorithm
switch (patternPos) {
case -1: {
// Pattern matched. Confirm is this is the start of a valid end of central dir record
long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1;
if (validateEndRecord(file, channel, startEndRecord)) {
return true;
}
// wasn't a valid end record; continue scan
bufferPos -= 4;
break;
}
case 3: {
// No bytes matched; the common case.
// With our pattern, this is the only case where the Boyer Moore algorithm's "bad char array" may
// produce a shift greater than the "good suffix array" (which would shift 1 byte)
int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE;
bufferPos -= END_BAD_BYTE_SKIP[idx];
break;
}
default:
// 1 or more bytes matched
bufferPos -= 4;
}
}
// Move back a full chunk. If we didn't read a full chunk, that's ok,
// it means we read all data and the outer while loop will terminate
if (channelPos <= bufferPos) {
break;
}
lastChannelPos = channelPos;
channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos);
}
return false;
} | java |
static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {
final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
final FlushableDataOutput output = context.writeMessage(header);
try {
// This is an error
output.writeByte(DomainControllerProtocol.PARAM_ERROR);
// send error code
output.writeByte(errorCode);
// error message
if (message == null) {
output.writeUTF("unknown error");
} else {
output.writeUTF(message);
}
// response end
output.writeByte(ManagementProtocol.RESPONSE_END);
output.close();
} finally {
StreamUtils.safeClose(output);
}
} | java |
public static boolean isOperationDefined(final ModelNode operation) {
for (final AttributeDefinition def : ROOT_ATTRIBUTES) {
if (operation.hasDefined(def.getName())) {
return true;
}
}
return false;
} | java |
@Deprecated
private static ListAttributeDefinition wrapAsList(final AttributeDefinition def) {
final ListAttributeDefinition list = new ListAttributeDefinition(new SimpleListAttributeDefinition.Builder(def.getName(), def)
.setElementValidator(def.getValidator())) {
@Override
public ModelNode getNoTextDescription(boolean forOperation) {
final ModelNode model = super.getNoTextDescription(forOperation);
setValueType(model);
return model;
}
@Override
protected void addValueTypeDescription(final ModelNode node, final ResourceBundle bundle) {
setValueType(node);
}
@Override
public void marshallAsElement(final ModelNode resourceModel, final boolean marshalDefault, final XMLStreamWriter writer) throws XMLStreamException {
throw new RuntimeException();
}
@Override
protected void addAttributeValueTypeDescription(ModelNode node, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
setValueType(node);
}
@Override
protected void addOperationParameterValueTypeDescription(ModelNode node, String operationName, ResourceDescriptionResolver resolver, Locale locale, ResourceBundle bundle) {
setValueType(node);
}
private void setValueType(ModelNode node) {
node.get(ModelDescriptionConstants.VALUE_TYPE).set(ModelType.STRING);
}
};
return list;
} | java |
private static int resolveDomainTimeoutAdder() {
String propValue = WildFlySecurityManager.getPropertyPrivileged(DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_STRING);
if (sysPropDomainValue == null || !sysPropDomainValue.equals(propValue)) {
// First call or the system property changed
sysPropDomainValue = propValue;
int number = -1;
try {
number = Integer.valueOf(sysPropDomainValue);
} catch (NumberFormatException nfe) {
// ignored
}
if (number > 0) {
defaultDomainValue = number; // this one is in ms
} else {
ControllerLogger.MGMT_OP_LOGGER.invalidDefaultBlockingTimeout(sysPropDomainValue, DOMAIN_TEST_SYSTEM_PROPERTY, DEFAULT_DOMAIN_TIMEOUT_ADDER);
defaultDomainValue = DEFAULT_DOMAIN_TIMEOUT_ADDER;
}
}
return defaultDomainValue;
} | java |
public TransformersSubRegistration getDomainRegistration(final ModelVersionRange range) {
final PathAddress address = PathAddress.EMPTY_ADDRESS;
return new TransformersSubRegistrationImpl(range, domain, address);
} | java |
public TransformersSubRegistration getHostRegistration(final ModelVersionRange range) {
final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST);
return new TransformersSubRegistrationImpl(range, domain, address);
} | java |
public TransformersSubRegistration getServerRegistration(final ModelVersionRange range) {
final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST, SERVER);
return new TransformersSubRegistrationImpl(range, domain, address);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.