code
stringlengths
73
34.1k
label
stringclasses
1 value
private boolean markAsObsolete(ContentReference ref) { if (obsoleteContents.containsKey(ref.getHexHash())) { //This content is already marked as obsolete if (obsoleteContents.get(ref.getHexHash()) + obsolescenceTimeout < System.currentTimeMillis()) { DeploymentRepositoryLogger.ROOT_LOGGER.obsoleteContentCleaned(ref.getContentIdentifier()); removeContent(ref); return true; } } else { obsoleteContents.put(ref.getHexHash(), System.currentTimeMillis()); //Mark content as obsolete } return false; }
java
static ReadMasterDomainModelUtil readMasterDomainResourcesForInitialConnect(final Transformers transformers, final Transformers.TransformationInputs transformationInputs, final Transformers.ResourceIgnoredTransformationRegistry ignoredTransformationRegistry, final Resource domainRoot) throws OperationFailedException { Resource transformedResource = transformers.transformRootResource(transformationInputs, domainRoot, ignoredTransformationRegistry); ReadMasterDomainModelUtil util = new ReadMasterDomainModelUtil(); util.describedResources = util.describeAsNodeList(PathAddress.EMPTY_ADDRESS, transformedResource, false); return util; }
java
private List<ModelNode> describeAsNodeList(PathAddress rootAddress, final Resource resource, boolean isRuntimeChange) { final List<ModelNode> list = new ArrayList<ModelNode>(); describe(rootAddress, resource, list, isRuntimeChange); return list; }
java
public static RequiredConfigurationHolder populateHostResolutionContext(final HostInfo hostInfo, final Resource root, final ExtensionRegistry extensionRegistry) { final RequiredConfigurationHolder rc = new RequiredConfigurationHolder(); for (IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo info : hostInfo.getServerConfigInfos()) { processServerConfig(root, rc, info, extensionRegistry); } return rc; }
java
static void processServerConfig(final Resource root, final RequiredConfigurationHolder requiredConfigurationHolder, final IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo serverConfig, final ExtensionRegistry extensionRegistry) { final Set<String> serverGroups = requiredConfigurationHolder.serverGroups; final Set<String> socketBindings = requiredConfigurationHolder.socketBindings; String sbg = serverConfig.getSocketBindingGroup(); if (sbg != null && !socketBindings.contains(sbg)) { processSocketBindingGroup(root, sbg, requiredConfigurationHolder); } final String groupName = serverConfig.getServerGroup(); final PathElement groupElement = PathElement.pathElement(SERVER_GROUP, groupName); // Also check the root, since this also gets executed on the slave which may not have the server-group configured yet if (!serverGroups.contains(groupName) && root.hasChild(groupElement)) { final Resource serverGroup = root.getChild(groupElement); final ModelNode groupModel = serverGroup.getModel(); serverGroups.add(groupName); // Include the socket binding groups if (groupModel.hasDefined(SOCKET_BINDING_GROUP)) { final String socketBindingGroup = groupModel.get(SOCKET_BINDING_GROUP).asString(); processSocketBindingGroup(root, socketBindingGroup, requiredConfigurationHolder); } final String profileName = groupModel.get(PROFILE).asString(); processProfile(root, profileName, requiredConfigurationHolder, extensionRegistry); } }
java
public static Transformers.ResourceIgnoredTransformationRegistry createServerIgnoredRegistry(final RequiredConfigurationHolder rc, final Transformers.ResourceIgnoredTransformationRegistry delegate) { return new Transformers.ResourceIgnoredTransformationRegistry() { @Override public boolean isResourceTransformationIgnored(PathAddress address) { final int length = address.size(); if (length == 0) { return false; } else if (length >= 1) { if (delegate.isResourceTransformationIgnored(address)) { return true; } final PathElement element = address.getElement(0); final String type = element.getKey(); switch (type) { case ModelDescriptionConstants.EXTENSION: // Don't ignore extensions for now return false; // if (local) { // return false; // Always include all local extensions // } else if (rc.getExtensions().contains(element.getValue())) { // return false; // } // break; case ModelDescriptionConstants.PROFILE: if (rc.getProfiles().contains(element.getValue())) { return false; } break; case ModelDescriptionConstants.SERVER_GROUP: if (rc.getServerGroups().contains(element.getValue())) { return false; } break; case ModelDescriptionConstants.SOCKET_BINDING_GROUP: if (rc.getSocketBindings().contains(element.getValue())) { return false; } break; } } return true; } }; }
java
public static ModelNode addCurrentServerGroupsToHostInfoModel(boolean ignoreUnaffectedServerGroups, Resource hostModel, ModelNode model) { if (!ignoreUnaffectedServerGroups) { return model; } model.get(IGNORE_UNUSED_CONFIG).set(ignoreUnaffectedServerGroups); addServerGroupsToModel(hostModel, model); return model; }
java
public boolean ignoreOperation(final Resource domainResource, final Collection<ServerConfigInfo> serverConfigs, final PathAddress pathAddress) { if (pathAddress.size() == 0) { return false; } boolean ignore = ignoreResourceInternal(domainResource, serverConfigs, pathAddress); return ignore; }
java
public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){ Set<ServerConfigInfo> groups = new HashSet<>(); for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) { groups.add(new ServerConfigInfoImpl(entry.getModel())); } return groups; }
java
private static boolean syncWithMaster(final Resource domain, final PathElement hostElement) { final Resource host = domain.getChild(hostElement); assert host != null; final Set<String> profiles = new HashSet<>(); final Set<String> serverGroups = new HashSet<>(); final Set<String> socketBindings = new HashSet<>(); for (final Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) { final ModelNode model = serverConfig.getModel(); final String group = model.require(GROUP).asString(); if (!serverGroups.contains(group)) { serverGroups.add(group); } if (model.hasDefined(SOCKET_BINDING_GROUP)) { processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings); } } // process referenced server-groups for (final Resource.ResourceEntry serverGroup : domain.getChildren(SERVER_GROUP)) { // If we have an unreferenced server-group if (!serverGroups.remove(serverGroup.getName())) { return true; } final ModelNode model = serverGroup.getModel(); final String profile = model.require(PROFILE).asString(); // Process the profile processProfile(domain, profile, profiles); // Process the socket-binding-group processSocketBindingGroup(domain, model.require(SOCKET_BINDING_GROUP).asString(), socketBindings); } // If we are missing a server group if (!serverGroups.isEmpty()) { return true; } // Process profiles for (final Resource.ResourceEntry profile : domain.getChildren(PROFILE)) { // We have an unreferenced profile if (!profiles.remove(profile.getName())) { return true; } } // We are missing a profile if (!profiles.isEmpty()) { return true; } // Process socket-binding groups for (final Resource.ResourceEntry socketBindingGroup : domain.getChildren(SOCKET_BINDING_GROUP)) { // We have an unreferenced socket-binding group if (!socketBindings.remove(socketBindingGroup.getName())) { return true; } } // We are missing a socket-binding group if (!socketBindings.isEmpty()) { return true; } // Looks good! return false; }
java
public Result cmd(String cliCommand) { try { // The intent here is to return a Response when this is doable. if (ctx.isWorkflowMode() || ctx.isBatchMode()) { ctx.handle(cliCommand); return new Result(cliCommand, ctx.getExitCode()); } handler.parse(ctx.getCurrentNodePath(), cliCommand, ctx); if (handler.getFormat() == OperationFormat.INSTANCE) { ModelNode request = ctx.buildRequest(cliCommand); ModelNode response = ctx.execute(request, cliCommand); return new Result(cliCommand, request, response); } else { ctx.handle(cliCommand); return new Result(cliCommand, ctx.getExitCode()); } } catch (CommandLineException cfe) { throw new IllegalArgumentException("Error handling command: " + cliCommand, cfe); } catch (IOException ioe) { throw new IllegalStateException("Unable to send command " + cliCommand + " to server.", ioe); } }
java
protected void boot(final BootContext context) throws ConfigurationPersistenceException { List<ModelNode> bootOps = configurationPersister.load(); ModelNode op = registerModelControllerServiceInitializationBootStep(context); if (op != null) { bootOps.add(op); } boot(bootOps, false); finishBoot(); }
java
protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException { return boot(bootOperations, rollbackOnRuntimeFailure, false, ModelControllerImpl.getMutableRootResourceRegistrationProvider()); }
java
public static <T> T getBundle(final Class<T> type) { return doPrivileged(new PrivilegedAction<T>() { public T run() { final Locale locale = Locale.getDefault(); final String lang = locale.getLanguage(); final String country = locale.getCountry(); final String variant = locale.getVariant(); Class<? extends T> bundleClass = null; if (variant != null && !variant.isEmpty()) try { bundleClass = Class.forName(join(type.getName(), "$bundle", lang, country, variant), true, type.getClassLoader()).asSubclass(type); } catch (ClassNotFoundException e) { // ignore } if (bundleClass == null && country != null && !country.isEmpty()) try { bundleClass = Class.forName(join(type.getName(), "$bundle", lang, country, null), true, type.getClassLoader()).asSubclass(type); } catch (ClassNotFoundException e) { // ignore } if (bundleClass == null && lang != null && !lang.isEmpty()) try { bundleClass = Class.forName(join(type.getName(), "$bundle", lang, null, null), true, type.getClassLoader()).asSubclass(type); } catch (ClassNotFoundException e) { // ignore } if (bundleClass == null) try { bundleClass = Class.forName(join(type.getName(), "$bundle", null, null, null), true, type.getClassLoader()).asSubclass(type); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Invalid bundle " + type + " (implementation not found)"); } final Field field; try { field = bundleClass.getField("INSTANCE"); } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Bundle implementation " + bundleClass + " has no instance field"); } try { return type.cast(field.get(null)); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Bundle implementation " + bundleClass + " could not be instantiated", e); } } }); }
java
public String getName() { if (name == null && securityIdentity != null) { name = securityIdentity.getPrincipal().getName(); } return name; }
java
public String getRealm() { if (UNDEFINED.equals(realm)) { Principal principal = securityIdentity.getPrincipal(); String realm = null; if (principal instanceof RealmPrincipal) { realm = ((RealmPrincipal)principal).getRealm(); } this.realm = realm; } return this.realm; }
java
private ModelNode resolveSubsystems(final List<ModelNode> extensions) { HostControllerLogger.ROOT_LOGGER.debug("Applying extensions provided by master"); final ModelNode result = operationExecutor.installSlaveExtensions(extensions); if (!SUCCESS.equals(result.get(OUTCOME).asString())) { throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION)); } final ModelNode subsystems = new ModelNode(); for (final ModelNode extension : extensions) { extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems); } return subsystems; }
java
private boolean applyRemoteDomainModel(final List<ModelNode> bootOperations, final HostInfo hostInfo) { try { HostControllerLogger.ROOT_LOGGER.debug("Applying domain level boot operations provided by master"); SyncModelParameters parameters = new SyncModelParameters(domainController, ignoredDomainResourceRegistry, hostControllerEnvironment, extensionRegistry, operationExecutor, true, serverProxies, remoteFileRepository, contentRepository); final SyncDomainModelOperationHandler handler = new SyncDomainModelOperationHandler(hostInfo, parameters); final ModelNode operation = APPLY_DOMAIN_MODEL.clone(); operation.get(DOMAIN_MODEL).set(bootOperations); final ModelNode result = operationExecutor.execute(OperationBuilder.create(operation).build(), OperationMessageHandler.DISCARD, ModelController.OperationTransactionControl.COMMIT, handler); final String outcome = result.get(OUTCOME).asString(); final boolean success = SUCCESS.equals(outcome); // check if anything we synced triggered reload-required or restart-required. // if they did we log a warning on the synced slave. if (result.has(RESPONSE_HEADERS)) { final ModelNode headers = result.get(RESPONSE_HEADERS); if (headers.hasDefined(OPERATION_REQUIRES_RELOAD) && headers.get(OPERATION_REQUIRES_RELOAD).asBoolean()) { HostControllerLogger.ROOT_LOGGER.domainModelAppliedButReloadIsRequired(); } if (headers.hasDefined(OPERATION_REQUIRES_RESTART) && headers.get(OPERATION_REQUIRES_RESTART).asBoolean()) { HostControllerLogger.ROOT_LOGGER.domainModelAppliedButRestartIsRequired(); } } if (!success) { ModelNode failureDesc = result.hasDefined(FAILURE_DESCRIPTION) ? result.get(FAILURE_DESCRIPTION) : new ModelNode(); HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(outcome, failureDesc); return false; } else { return true; } } catch (Exception e) { HostControllerLogger.ROOT_LOGGER.failedToApplyDomainConfig(e); return false; } }
java
static void rethrowIrrecoverableConnectionFailures(IOException e) throws SlaveRegistrationException { Throwable cause = e; while ((cause = cause.getCause()) != null) { if (cause instanceof SaslException) { throw HostControllerLogger.ROOT_LOGGER.authenticationFailureUnableToConnect(cause); } else if (cause instanceof SSLHandshakeException) { throw HostControllerLogger.ROOT_LOGGER.sslFailureUnableToConnect(cause); } else if (cause instanceof SlaveRegistrationException) { throw (SlaveRegistrationException) cause; } } }
java
static void logConnectionException(URI uri, DiscoveryOption discoveryOption, boolean moreOptions, Exception e) { if (uri == null) { HostControllerLogger.ROOT_LOGGER.failedDiscoveringMaster(discoveryOption, e); } else { HostControllerLogger.ROOT_LOGGER.cannotConnect(uri, e); } if (!moreOptions) { // All discovery options have been exhausted HostControllerLogger.ROOT_LOGGER.noDiscoveryOptionsLeft(); } }
java
public static AliasOperationTransformer replaceLastElement(final PathElement element) { return create(new AddressTransformer() { @Override public PathAddress transformAddress(final PathAddress original) { final PathAddress address = original.subAddress(0, original.size() -1); return address.append(element); } }); }
java
void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException { persist(key, value, enableDisableMode, disable, file, null); }
java
void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file, final String realm) throws IOException, StartException { final PropertiesFileLoader propertiesHandler = realm == null ? new PropertiesFileLoader(file.getAbsolutePath(), null) : new UserPropertiesFileLoader(file.getAbsolutePath(), null); try { propertiesHandler.start(null); if (realm != null) { ((UserPropertiesFileLoader) propertiesHandler).setRealmName(realm); } Properties prob = propertiesHandler.getProperties(); if (value != null) { prob.setProperty(key, value); } if (enableDisableMode) { prob.setProperty(key + "!disable", String.valueOf(disable)); } propertiesHandler.persistProperties(); } finally { propertiesHandler.stop(null); } }
java
public static ServiceName deploymentUnitName(String name, Phase phase) { return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name()); }
java
protected void updateModel(final ModelNode operation, final Resource resource) throws OperationFailedException { updateModel(operation, resource.getModel()); }
java
public void logAttributeWarning(PathAddress address, String attribute) { logAttributeWarning(address, null, null, attribute); }
java
public void logAttributeWarning(PathAddress address, Set<String> attributes) { logAttributeWarning(address, null, null, attributes); }
java
public void logAttributeWarning(PathAddress address, String message, String attribute) { logAttributeWarning(address, null, message, attribute); }
java
public void logAttributeWarning(PathAddress address, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, null, message, attributes)); }
java
public void logAttributeWarning(PathAddress address, ModelNode operation, String message, String attribute) { messageQueue.add(new AttributeLogEntry(address, operation, message, attribute)); }
java
public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) { messageQueue.add(new AttributeLogEntry(address, operation, message, attributes)); }
java
public void logWarning(final String message) { messageQueue.add(new LogEntry() { @Override public String getMessage() { return message; } }); }
java
void flushLogQueue() { Set<String> problems = new LinkedHashSet<String>(); synchronized (messageQueue) { Iterator<LogEntry> i = messageQueue.iterator(); while (i.hasNext()) { problems.add("\t\t" + i.next().getMessage() + "\n"); i.remove(); } } if (!problems.isEmpty()) { logger.transformationWarnings(target.getHostName(), problems); } }
java
PatchEntry getEntry(final String name, boolean addOn) { return addOn ? addOns.get(name) : layers.get(name); }
java
protected void failedToCleanupDir(final File file) { checkForGarbageOnRestart = true; PatchLogger.ROOT_LOGGER.cannotDeleteFile(file.getAbsolutePath()); }
java
protected PatchEntry resolveForElement(final PatchElement element) throws PatchingException { assert state == State.NEW; final PatchElementProvider provider = element.getProvider(); final String layerName = provider.getName(); final LayerType layerType = provider.getLayerType(); final Map<String, PatchEntry> map; if (layerType == LayerType.Layer) { map = layers; } else { map = addOns; } PatchEntry entry = map.get(layerName); if (entry == null) { final InstallationManager.MutablePatchingTarget target = modification.resolve(layerName, layerType); if (target == null) { throw PatchLogger.ROOT_LOGGER.noSuchLayer(layerName); } entry = new PatchEntry(target, element); map.put(layerName, entry); } // Maintain the most recent element entry.updateElement(element); return entry; }
java
private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) { final List<File> processed = new ArrayList<File>(); List<File> reenabled = Collections.emptyList(); List<File> disabled = Collections.emptyList(); try { try { // Update the state to invalidate and process module resources if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) { if (mode == PatchingTaskContext.Mode.APPLY) { // Only invalidate modules when applying patches; on rollback files are immediately restored for (final File invalidation : moduleInvalidations) { processed.add(invalidation); PatchModuleInvalidationUtils.processFile(this, invalidation, mode); } if (!modulesToReenable.isEmpty()) { reenabled = new ArrayList<File>(modulesToReenable.size()); for (final File path : modulesToReenable) { reenabled.add(path); PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK); } } } else if(mode == PatchingTaskContext.Mode.ROLLBACK) { if (!modulesToDisable.isEmpty()) { disabled = new ArrayList<File>(modulesToDisable.size()); for (final File path : modulesToDisable) { disabled.add(path); PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY); } } } } modification.complete(); callback.completed(this); state = State.COMPLETED; } catch (Exception e) { this.moduleInvalidations.clear(); this.moduleInvalidations.addAll(processed); this.modulesToReenable.clear(); this.modulesToReenable.addAll(reenabled); this.modulesToDisable.clear(); this.moduleInvalidations.addAll(disabled); throw new RuntimeException(e); } } finally { if (state != State.COMPLETED) { try { modification.cancel(); } finally { try { undoChanges(); } finally { callback.operationCancelled(this); } } } else { try { if (checkForGarbageOnRestart) { final File cleanupMarker = new File(installedImage.getInstallationMetadata(), "cleanup-patching-dirs"); cleanupMarker.createNewFile(); } storeFailedRenaming(); } catch (IOException e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to create cleanup marker"); } } } }
java
boolean undoChanges() { final State state = stateUpdater.getAndSet(this, State.ROLLBACK_ONLY); if (state == State.COMPLETED || state == State.ROLLBACK_ONLY) { // Was actually completed already return false; } PatchingTaskContext.Mode currentMode = this.mode; mode = PatchingTaskContext.Mode.UNDO; final PatchContentLoader loader = PatchContentLoader.create(miscBackup, null, null); // Undo changes for the identity undoChanges(identityEntry, loader); // TODO maybe check if we need to do something for the layers too !? if (state == State.INVALIDATE || currentMode == PatchingTaskContext.Mode.ROLLBACK) { // For apply the state needs to be invalidate // For rollback the files are invalidated as part of the tasks final PatchingTaskContext.Mode mode = currentMode == PatchingTaskContext.Mode.APPLY ? PatchingTaskContext.Mode.ROLLBACK : PatchingTaskContext.Mode.APPLY; for (final File file : moduleInvalidations) { try { PatchModuleInvalidationUtils.processFile(this, file, mode); } catch (Exception e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to restore state for %s", file); } } if(!modulesToReenable.isEmpty()) { for (final File file : modulesToReenable) { try { PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.APPLY); } catch (Exception e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to restore state for %s", file); } } } if(!modulesToDisable.isEmpty()) { for (final File file : modulesToDisable) { try { PatchModuleInvalidationUtils.processFile(this, file, PatchingTaskContext.Mode.ROLLBACK); } catch (Exception e) { PatchLogger.ROOT_LOGGER.debugf(e, "failed to restore state for %s", file); } } } } return true; }
java
static void undoChanges(final PatchEntry entry, final PatchContentLoader loader) { final List<ContentModification> modifications = new ArrayList<ContentModification>(entry.rollbackActions); for (final ContentModification modification : modifications) { final ContentItem item = modification.getItem(); if (item.getContentType() != ContentType.MISC) { // Skip modules and bundles they should be removed as part of the {@link FinalizeCallback} continue; } final PatchingTaskDescription description = new PatchingTaskDescription(entry.applyPatchId, modification, loader, false, false, false); try { final PatchingTask task = PatchingTask.Factory.create(description, entry); task.execute(entry); } catch (Exception e) { PatchLogger.ROOT_LOGGER.failedToUndoChange(item.toString()); } } }
java
private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) { // setup the content loader paths final DirectoryStructure structure = target.getDirectoryStructure(); final InstalledImage image = structure.getInstalledImage(); final File historyDir = image.getPatchHistoryDir(patchId); final File miscRoot = new File(historyDir, PatchContentLoader.MISC); final File modulesRoot = structure.getModulePatchDirectory(patchId); final File bundlesRoot = structure.getBundlesPatchDirectory(patchId); final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot); // recordContentLoader(patchId, loader); }
java
protected void recordContentLoader(final String patchID, final PatchContentLoader contentLoader) { if (contentLoaders.containsKey(patchID)) { throw new IllegalStateException("Content loader already registered for patch " + patchID); // internal wrong usage, no i18n } contentLoaders.put(patchID, contentLoader); }
java
public File getTargetFile(final MiscContentItem item) { final State state = this.state; if (state == State.NEW || state == State.ROLLBACK_ONLY) { return getTargetFile(miscTargetRoot, item); } else { throw new IllegalStateException(); // internal wrong usage, no i18n } }
java
protected Patch createProcessedPatch(final Patch original) { // Process elements final List<PatchElement> elements = new ArrayList<PatchElement>(); // Process layers for (final PatchEntry entry : getLayers()) { final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications); elements.add(element); } // Process add-ons for (final PatchEntry entry : getAddOns()) { final PatchElement element = createPatchElement(entry, entry.element.getId(), entry.modifications); elements.add(element); } // Swap the patch element modifications, keep the identity ones since we don't need to fix the misc modifications return new PatchImpl(original.getPatchId(), original.getDescription(), original.getLink(), original.getIdentity(), elements, identityEntry.modifications); }
java
protected RollbackPatch createRollbackPatch(final String patchId, final Patch.PatchType patchType) { // Process elements final List<PatchElement> elements = new ArrayList<PatchElement>(); // Process layers for (final PatchEntry entry : getLayers()) { final PatchElement element = createRollbackElement(entry); elements.add(element); } // Process add-ons for (final PatchEntry entry : getAddOns()) { final PatchElement element = createRollbackElement(entry); elements.add(element); } final InstalledIdentity installedIdentity = modification.getUnmodifiedInstallationState(); final String name = installedIdentity.getIdentity().getName(); final IdentityImpl identity = new IdentityImpl(name, modification.getVersion()); if (patchType == Patch.PatchType.CUMULATIVE) { identity.setPatchType(Patch.PatchType.CUMULATIVE); identity.setResultingVersion(installedIdentity.getIdentity().getVersion()); } else if (patchType == Patch.PatchType.ONE_OFF) { identity.setPatchType(Patch.PatchType.ONE_OFF); } final List<ContentModification> modifications = identityEntry.rollbackActions; final Patch delegate = new PatchImpl(patchId, "rollback patch", identity, elements, modifications); return new PatchImpl.RollbackPatchImpl(delegate, installedIdentity); }
java
static File getTargetFile(final File root, final MiscContentItem item) { return PatchContentLoader.getMiscPath(root, item); }
java
protected static PatchElement createRollbackElement(final PatchEntry entry) { final PatchElement patchElement = entry.element; final String patchId; final Patch.PatchType patchType = patchElement.getProvider().getPatchType(); if (patchType == Patch.PatchType.CUMULATIVE) { patchId = entry.getCumulativePatchID(); } else { patchId = patchElement.getId(); } return createPatchElement(entry, patchId, entry.rollbackActions); }
java
protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) { final PatchElement patchElement = entry.element; final PatchElementImpl element = new PatchElementImpl(patchId); element.setProvider(patchElement.getProvider()); // Add all the rollback actions element.getModifications().addAll(modifications); element.setDescription(patchElement.getDescription()); return element; }
java
void backupConfiguration() throws IOException { final String configuration = Constants.CONFIGURATION; final File a = new File(installedImage.getAppClientDir(), configuration); final File d = new File(installedImage.getDomainDir(), configuration); final File s = new File(installedImage.getStandaloneDir(), configuration); if (a.exists()) { final File ab = new File(configBackup, Constants.APP_CLIENT); backupDirectory(a, ab); } if (d.exists()) { final File db = new File(configBackup, Constants.DOMAIN); backupDirectory(d, db); } if (s.exists()) { final File sb = new File(configBackup, Constants.STANDALONE); backupDirectory(s, sb); } }
java
static void backupDirectory(final File source, final File target) throws IOException { if (!target.exists()) { if (!target.mkdirs()) { throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath()); } } final File[] files = source.listFiles(CONFIG_FILTER); for (final File file : files) { final File t = new File(target, file.getName()); IoUtils.copyFile(file, t); } }
java
static void writePatch(final Patch rollbackPatch, final File file) throws IOException { final File parent = file.getParentFile(); if (!parent.isDirectory()) { if (!parent.mkdirs() && !parent.exists()) { throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath()); } } try { try (final OutputStream os = new FileOutputStream(file)){ PatchXml.marshal(os, rollbackPatch); } } catch (XMLStreamException e) { throw new IOException(e); } }
java
public CliCommandBuilder setController(final String hostname, final int port) { setController(formatAddress(null, hostname, port)); return this; }
java
public CliCommandBuilder setController(final String protocol, final String hostname, final int port) { setController(formatAddress(protocol, hostname, port)); return this; }
java
public CliCommandBuilder setTimeout(final int timeout) { if (timeout > 0) { addCliArgument(CliArgument.TIMEOUT, Integer.toString(timeout)); } else { addCliArgument(CliArgument.TIMEOUT, null); } return this; }
java
@Deprecated public static <T> ServiceBuilder<T> addServerExecutorDependency(ServiceBuilder<T> builder, Injector<ExecutorService> injector) { return builder.addDependency(ServerService.MANAGEMENT_EXECUTOR, ExecutorService.class, injector); }
java
public void handleChannelClosed(final Channel closed, final IOException e) { for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) { if (activeOperation.getChannel() == closed) { // Only call cancel, to also interrupt still active threads activeOperation.getResultHandler().cancel(); } } }
java
@Override public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { long deadline = unit.toMillis(timeout) + System.currentTimeMillis(); lock.lock(); try { assert shutdown; while(activeCount != 0) { long remaining = deadline - System.currentTimeMillis(); if (remaining <= 0) { break; } condition.await(remaining, TimeUnit.MILLISECONDS); } boolean allComplete = activeCount == 0; if (!allComplete) { ProtocolLogger.ROOT_LOGGER.debugf("ActiveOperation(s) %s have not completed within %d %s", activeRequests.keySet(), timeout, unit); } return allComplete; } finally { lock.unlock(); } }
java
protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) { lock.lock(); try { // Check that we still allow registration // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests // TODO WFCORE-845 consider using an IllegalStateException for this //assert ! shutdown; final Integer operationId; if(id == null) { // If we did not get an operationId, create a new one operationId = operationIdManager.createBatchId(); } else { // Check that the operationId is not already taken if(! operationIdManager.lockBatchId(id)) { throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id); } operationId = id; } final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this); final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request); if(existing != null) { throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId); } ProtocolLogger.ROOT_LOGGER.tracef("Registered active operation %d", operationId); activeCount++; // condition.signalAll(); return request; } finally { lock.unlock(); } }
java
protected <T, A> ActiveOperation<T, A> getActiveOperation(final ManagementRequestHeader header) { return getActiveOperation(header.getBatchId()); }
java
protected <T, A> ActiveOperation<T, A> getActiveOperation(final Integer id) { //noinspection unchecked return (ActiveOperation<T, A>) activeRequests.get(id); }
java
protected List<Integer> cancelAllActiveOperations() { final List<Integer> operations = new ArrayList<Integer>(); for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) { activeOperation.asyncCancel(false); operations.add(activeOperation.getOperationId()); } return operations; }
java
protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) { final ActiveOperation<T, A> removed = removeUnderLock(id); if(removed != null) { for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) { final ActiveRequest<?, ?> request = requestEntry.getValue(); if(request.context == removed) { requests.remove(requestEntry.getKey()); } } } return removed; }
java
protected static void safeWriteErrorResponse(final Channel channel, final ManagementProtocolHeader header, final Throwable error) { if(header.getType() == ManagementProtocol.TYPE_REQUEST) { try { writeErrorResponse(channel, (ManagementRequestHeader) header, error); } catch(IOException ioe) { ProtocolLogger.ROOT_LOGGER.tracef(ioe, "failed to write error response for %s on channel: %s", header, channel); } } }
java
protected static void writeErrorResponse(final Channel channel, final ManagementRequestHeader header, final Throwable error) throws IOException { final ManagementResponseHeader response = ManagementResponseHeader.create(header, error); final MessageOutputStream output = channel.writeMessage(); try { writeHeader(response, output); output.close(); } finally { StreamUtils.safeClose(output); } }
java
protected static FlushableDataOutput writeHeader(final ManagementProtocolHeader header, final OutputStream os) throws IOException { final FlushableDataOutput output = FlushableDataOutputImpl.create(os); header.write(output); return output; }
java
protected static <T, A> ManagementRequestHandler<T, A> getFallbackHandler(final ManagementRequestHeader header) { return new ManagementRequestHandler<T, A>() { @Override public void handleRequest(final DataInput input, ActiveOperation.ResultHandler<T> resultHandler, ManagementRequestContext<A> context) throws IOException { final Exception error = ProtocolLogger.ROOT_LOGGER.noSuchResponseHandler(Integer.toHexString(header.getRequestId())); if(resultHandler.failed(error)) { safeWriteErrorResponse(context.getChannel(), context.getRequestHeader(), error); } } }; }
java
static void processFile(final IdentityPatchContext context, final File file, final PatchingTaskContext.Mode mode) throws IOException { if (mode == PatchingTaskContext.Mode.APPLY) { if (ENABLE_INVALIDATION) { updateJar(file, GOOD_ENDSIG_PATTERN, BAD_BYTE_SKIP, CRIPPLED_ENDSIG, GOOD_ENDSIG); backup(context, file); } } else if (mode == PatchingTaskContext.Mode.ROLLBACK) { updateJar(file, CRIPPLED_ENDSIG_PATTERN, BAD_BYTE_SKIP, GOOD_ENDSIG, CRIPPLED_ENDSIG); restore(context, file); } else { throw new IllegalStateException(); } }
java
private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException { final RandomAccessFile raf = new RandomAccessFile(file, "rw"); try { final FileChannel channel = raf.getChannel(); try { long pos = channel.size() - ENDLEN; final ScanContext context; if (newSig == CRIPPLED_ENDSIG) { context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN); } else if (newSig == GOOD_ENDSIG) { context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN); } else { context = null; } if (!validateEndRecord(file, channel, pos, endSig)) { pos = scanForEndSig(file, channel, context); } if (pos == -1) { if (context.state == State.NOT_FOUND) { // Don't fail patching if we cannot validate a valid zip PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath()); } return; } // Update the central directory record channel.position(pos); final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(newSig); buffer.flip(); while (buffer.hasRemaining()) { channel.write(buffer); } } finally { safeClose(channel); } } finally { safeClose(raf); } }
java
private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException { try { channel.position(startEndRecord); final ByteBuffer endDirHeader = getByteBuffer(ENDLEN); read(endDirHeader, channel); if (endDirHeader.limit() < ENDLEN) { // Couldn't read the full end of central directory record header return false; } else if (getUnsignedInt(endDirHeader, 0) != endSig) { return false; } long pos = getUnsignedInt(endDirHeader, END_CENSTART); // TODO deal with Zip64 if (pos == ZIP64_MARKER) { return false; } ByteBuffer cdfhBuffer = getByteBuffer(CENLEN); read(cdfhBuffer, channel, pos); long header = getUnsignedInt(cdfhBuffer, 0); if (header == CENSIG) { long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET); long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ); if (firstLoc == 0) { // normal case -- first bytes are the first local file if (!validateLocalFileRecord(channel, 0, firstSize)) { return false; } } else { // confirm that firstLoc is indeed the first local file long fileFirstLoc = scanForLocSig(channel); if (firstLoc != fileFirstLoc) { if (fileFirstLoc == 0) { return false; } else { // scanForLocSig() found a LOCSIG, but not at position zero and not // at the expected position. // With a file like this, we can't tell if we're in a nested zip // or we're in an outer zip and had the bad luck to find random bytes // that look like LOCSIG. return false; } } } // At this point, endDirHeader points to the correct end of central dir record. // Just need to validate the record is complete, including any comment int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN); long commentEnd = startEndRecord + ENDLEN + commentLen; return commentEnd <= channel.size(); } return false; } catch (EOFException eof) { // pos or firstLoc weren't really positions and moved us to an invalid location return false; } }
java
private static long scanForEndSig(final File file, final FileChannel channel, final ScanContext context) throws IOException { // TODO Consider just reading in MAX_REVERSE_SCAN bytes -- increased peak memory cost but less complex ByteBuffer bb = getByteBuffer(CHUNK_SIZE); long start = channel.size(); long end = Math.max(0, start - MAX_REVERSE_SCAN); long channelPos = Math.max(0, start - CHUNK_SIZE); long lastChannelPos = channelPos; while (lastChannelPos >= end) { read(bb, channel, channelPos); int actualRead = bb.limit(); int bufferPos = actualRead - 1; while (bufferPos >= SIG_PATTERN_LENGTH) { // Following is based on the Boyer Moore algorithm but simplified to reflect // a) the pattern is static // b) the pattern has no repeating bytes int patternPos; for (patternPos = SIG_PATTERN_LENGTH - 1; patternPos >= 0 && context.matches(patternPos, bb.get(bufferPos - patternPos)); --patternPos) { // empty loop while bytes match } // Switch gives same results as checking the "good suffix array" in the Boyer Moore algorithm switch (patternPos) { case -1: { final State state = context.state; // Pattern matched. Confirm is this is the start of a valid end of central dir record long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1; if (validateEndRecord(file, channel, startEndRecord, context.getSig())) { if (state == State.FOUND) { return startEndRecord; } else { return -1; } } // wasn't a valid end record; continue scan bufferPos -= 4; break; } case 3: { // No bytes matched; the common case. // With our pattern, this is the only case where the Boyer Moore algorithm's "bad char array" may // produce a shift greater than the "good suffix array" (which would shift 1 byte) int idx = bb.get(bufferPos - patternPos) - Byte.MIN_VALUE; bufferPos -= BAD_BYTE_SKIP[idx]; break; } default: // 1 or more bytes matched bufferPos -= 4; } } // Move back a full chunk. If we didn't read a full chunk, that's ok, // it means we read all data and the outer while loop will terminate if (channelPos <= bufferPos) { break; } lastChannelPos = channelPos; channelPos -= Math.min(channelPos - bufferPos, CHUNK_SIZE - bufferPos); } return -1; }
java
private static long scanForLocSig(FileChannel channel) throws IOException { channel.position(0); ByteBuffer bb = getByteBuffer(CHUNK_SIZE); long end = channel.size(); while (channel.position() <= end) { read(bb, channel); int bufferPos = 0; while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) { // Following is based on the Boyer Moore algorithm but simplified to reflect // a) the size of the pattern is static // b) the pattern is static and has no repeating bytes int patternPos; for (patternPos = SIG_PATTERN_LENGTH - 1; patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos); --patternPos) { // empty loop while bytes match } // Outer switch gives same results as checking the "good suffix array" in the Boyer Moore algorithm switch (patternPos) { case -1: { // Pattern matched. Confirm is this is the start of a valid local file record long startLocRecord = channel.position() - bb.limit() + bufferPos; long currentPos = channel.position(); if (validateLocalFileRecord(channel, startLocRecord, -1)) { return startLocRecord; } // Restore position in case it shifted channel.position(currentPos); // wasn't a valid local file record; continue scan bufferPos += 4; break; } case 3: { // No bytes matched; the common case. // With our pattern, this is the only case where the Boyer Moore algorithm's "bad char array" may // produce a shift greater than the "good suffix array" (which would shift 1 byte) int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE; bufferPos += LOC_BAD_BYTE_SKIP[idx]; break; } default: // 1 or more bytes matched bufferPos += 4; } } } return -1; }
java
private static boolean validateLocalFileRecord(FileChannel channel, long startLocRecord, long compressedSize) throws IOException { ByteBuffer lfhBuffer = getByteBuffer(LOCLEN); read(lfhBuffer, channel, startLocRecord); if (lfhBuffer.limit() < LOCLEN || getUnsignedInt(lfhBuffer, 0) != LOCSIG) { return false; } if (compressedSize == -1) { // We can't further evaluate return true; } int fnLen = getUnsignedShort(lfhBuffer, LOC_FILENAMELEN); int extFieldLen = getUnsignedShort(lfhBuffer, LOC_EXTFLDLEN); long nextSigPos = startLocRecord + LOCLEN + compressedSize + fnLen + extFieldLen; read(lfhBuffer, channel, nextSigPos); long header = getUnsignedInt(lfhBuffer, 0); return header == LOCSIG || header == EXTSIG || header == CENSIG; }
java
private static void computeBadByteSkipArray(byte[] pattern, int[] badByteArray) { for (int a = 0; a < ALPHABET_SIZE; a++) { badByteArray[a] = pattern.length; } for (int j = 0; j < pattern.length - 1; j++) { badByteArray[pattern[j] - Byte.MIN_VALUE] = pattern.length - j - 1; } }
java
public static HostController createHostController(String jbossHomePath, String modulePath, String[] systemPackages, String[] cmdargs) { if (jbossHomePath == null || jbossHomePath.isEmpty()) { throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath); } File jbossHomeDir = new File(jbossHomePath); if (!jbossHomeDir.isDirectory()) { throw EmbeddedLogger.ROOT_LOGGER.invalidJBossHome(jbossHomePath); } return createHostController( Configuration.Builder.of(jbossHomeDir) .setModulePath(modulePath) .setSystemPackages(systemPackages) .setCommandArguments(cmdargs) .build() ); }
java
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final ResourceRoot deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT); final ModuleSpecification moduleSpecification = phaseContext.getDeploymentUnit().getAttachment( Attachments.MODULE_SPECIFICATION); if(deploymentRoot == null) return; final ServicesAttachment servicesAttachments = phaseContext.getDeploymentUnit().getAttachment(Attachments.SERVICES); if(servicesAttachments != null && !servicesAttachments.getServiceImplementations(ServiceActivator.class.getName()).isEmpty()) { moduleSpecification.addSystemDependency(MSC_DEP); } }
java
public void pause(ServerActivityCallback requestCountListener) { if (paused) { throw ServerLogger.ROOT_LOGGER.serverAlreadyPaused(); } this.paused = true; listenerUpdater.set(this, requestCountListener); if (activeRequestCountUpdater.get(this) == 0) { if (listenerUpdater.compareAndSet(this, requestCountListener, null)) { requestCountListener.done(); } } }
java
public void resume() { this.paused = false; ServerActivityCallback listener = listenerUpdater.get(this); if (listener != null) { listenerUpdater.compareAndSet(this, listener, null); } }
java
public static ModelNode createLocalHostHostInfo(final LocalHostControllerInfo hostInfo, final ProductConfig productConfig, final IgnoredDomainResourceRegistry ignoredResourceRegistry, final Resource hostModelResource) { final ModelNode info = new ModelNode(); info.get(NAME).set(hostInfo.getLocalHostName()); info.get(RELEASE_VERSION).set(Version.AS_VERSION); info.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME); info.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION); info.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION); info.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION); final String productName = productConfig.getProductName(); final String productVersion = productConfig.getProductVersion(); if(productName != null) { info.get(PRODUCT_NAME).set(productName); } if(productVersion != null) { info.get(PRODUCT_VERSION).set(productVersion); } ModelNode ignoredModel = ignoredResourceRegistry.getIgnoredResourcesAsModel(); if (ignoredModel.hasDefined(IGNORED_RESOURCE_TYPE)) { info.get(IGNORED_RESOURCES).set(ignoredModel.require(IGNORED_RESOURCE_TYPE)); } boolean ignoreUnaffectedServerGroups = hostInfo.isRemoteDomainControllerIgnoreUnaffectedConfiguration(); IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel(ignoreUnaffectedServerGroups, hostModelResource, info); return info; }
java
public void addModuleDir(final String moduleDir) { if (moduleDir == null) { throw LauncherMessages.MESSAGES.nullParam("moduleDir"); } // Validate the path final Path path = Paths.get(moduleDir).normalize(); modulesDirs.add(path.toString()); }
java
public String getModulePaths() { final StringBuilder result = new StringBuilder(); if (addDefaultModuleDir) { result.append(wildflyHome.resolve("modules").toString()); } if (!modulesDirs.isEmpty()) { if (addDefaultModuleDir) result.append(File.pathSeparator); for (Iterator<String> iterator = modulesDirs.iterator(); iterator.hasNext(); ) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(File.pathSeparator); } } } return result.toString(); }
java
public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) { final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler); handler.addHandlerFactory(client); return client; }
java
public static ModelControllerClient createReceiving(final Channel channel, final ExecutorService executorService) { final ManagementClientChannelStrategy strategy = ManagementClientChannelStrategy.create(channel); final ManagementChannelHandler handler = new ManagementChannelHandler(strategy, executorService); final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler); handler.addHandlerFactory(client); channel.addCloseHandler(new CloseHandler<Channel>() { @Override public void handleClose(Channel closed, IOException exception) { handler.shutdown(); try { handler.awaitCompletion(1, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { handler.shutdownNow(); } } }); channel.receiveMessage(handler.getReceiver()); return client; }
java
@Override protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException { // Is the line an empty comment "#" ? if (line.startsWith(COMMENT_PREFIX) && line.length() == 1) { String nextLine = bufferedFileReader.readLine(); if (nextLine != null) { // Is the next line the realm name "#$REALM_NAME=" ? if (nextLine.startsWith(COMMENT_PREFIX) && nextLine.contains(REALM_COMMENT_PREFIX)) { // Realm name block detected! // The next line must be and empty comment "#" bufferedFileReader.readLine(); // Avoid adding the realm block } else { // It's a user comment... content.add(line); content.add(nextLine); } } else { super.addLineContent(bufferedFileReader, content, line); } } else { super.addLineContent(bufferedFileReader, content, line); } }
java
@Deprecated public void validateOperation(final ModelNode operation) throws OperationFailedException { if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) { ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(), PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString()); } for (AttributeDefinition ad : this.parameters) { ad.validateOperation(operation); } }
java
@SuppressWarnings("deprecation") @Deprecated public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException { validateOperation(operationObject); for (AttributeDefinition ad : this.parameters) { ad.validateAndSet(operationObject, model); } }
java
<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) { return handlers.get(artifact); }
java
public <V> V getAttachment(final AttachmentKey<V> key) { assert key != null; return key.cast(contextAttachments.get(key)); }
java
public <V> V attach(final AttachmentKey<V> key, final V value) { assert key != null; return key.cast(contextAttachments.put(key, value)); }
java
public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) { assert key != null; return key.cast(contextAttachments.putIfAbsent(key, value)); }
java
public <V> V detach(final AttachmentKey<V> key) { assert key != null; return key.cast(contextAttachments.remove(key)); }
java
private void writeInterfaceCriteria(final XMLExtendedStreamWriter writer, final ModelNode subModel, final boolean nested) throws XMLStreamException { for (final Property property : subModel.asPropertyList()) { if (property.getValue().isDefined()) { writeInterfaceCriteria(writer, property, nested); } } }
java
public static ExtensibleConfigurationPersister createHostXmlConfigurationPersister(final ConfigurationFile file, final HostControllerEnvironment environment, final ExecutorService executorService, final ExtensionRegistry hostExtensionRegistry, final LocalHostControllerInfo localHostControllerInfo) { String defaultHostname = localHostControllerInfo.getLocalHostName(); if (environment.getRunningModeControl().isReloaded()) { if (environment.getRunningModeControl().getReloadHostName() != null) { defaultHostname = environment.getRunningModeControl().getReloadHostName(); } } HostXml hostXml = new HostXml(defaultHostname, environment.getRunningModeControl().getRunningMode(), environment.isUseCachedDc(), Module.getBootModuleLoader(), executorService, hostExtensionRegistry); BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), "host"), hostXml, hostXml, false); for (Namespace namespace : Namespace.domainValues()) { if (!namespace.equals(Namespace.CURRENT)) { persister.registerAdditionalRootElement(new QName(namespace.getUriString(), "host"), hostXml); } } hostExtensionRegistry.setWriterRegistry(persister); return persister; }
java
public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) { DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry); boolean suppressLoad = false; ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy(); final boolean isReloaded = environment.getRunningModeControl().isReloaded(); if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) { throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName()); } if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) { suppressLoad = true; } BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), "domain"), domainXml, domainXml, suppressLoad); for (Namespace namespace : Namespace.domainValues()) { if (!namespace.equals(Namespace.CURRENT)) { persister.registerAdditionalRootElement(new QName(namespace.getUriString(), "domain"), domainXml); } } extensionRegistry.setWriterRegistry(persister); return persister; }
java
public static ExtensibleConfigurationPersister createTransientDomainXmlConfigurationPersister(ExecutorService executorService, ExtensionRegistry extensionRegistry) { DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry); ExtensibleConfigurationPersister persister = new NullConfigurationPersister(domainXml); extensionRegistry.setWriterRegistry(persister); return persister; }
java
static void apply(final String patchId, final Collection<ContentModification> modifications, final PatchEntry patchEntry, final ContentItemFilter filter) { for (final ContentModification modification : modifications) { final ContentItem item = modification.getItem(); // Check if we accept the item if (!filter.accepts(item)) { continue; } final Location location = new Location(item); final ContentEntry contentEntry = new ContentEntry(patchId, modification); ContentTaskDefinition definition = patchEntry.get(location); if (definition == null) { definition = new ContentTaskDefinition(location, contentEntry, false); patchEntry.put(location, definition); } else { definition.setTarget(contentEntry); } } }
java
protected ServiceName serviceName(final String name) { return baseServiceName != null ? baseServiceName.append(name) : null; }
java
private boolean subModuleExists(File dir) { if (isSlotDirectory(dir)) { return true; } else { File[] children = dir.listFiles(File::isDirectory); for (File child : children) { if (subModuleExists(child)) { return true; } } } return false; }
java
private String tail(String moduleName) { if (moduleName.indexOf(MODULE_NAME_SEPARATOR) > 0) { return moduleName.substring(moduleName.indexOf(MODULE_NAME_SEPARATOR) + 1); } else { return ""; } }
java
void resolveBootUpdates(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception { connection.openConnection(controller, callback); // Keep a reference to the the controller this.controller = controller; }
java
static VaultConfig loadExternalFile(File f) throws XMLStreamException { if(f == null) { throw new IllegalArgumentException("File is null"); } if(!f.exists()) { throw new XMLStreamException("Failed to locate vault file " + f.getAbsolutePath()); } final VaultConfig config = new VaultConfig(); BufferedInputStream input = null; try { final XMLMapper mapper = XMLMapper.Factory.create(); final XMLElementReader<VaultConfig> reader = new ExternalVaultConfigReader(); mapper.registerRootElement(new QName(VAULT), reader); FileInputStream is = new FileInputStream(f); input = new BufferedInputStream(is); XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(input); mapper.parseDocument(config, streamReader); streamReader.close(); } catch(FileNotFoundException e) { throw new XMLStreamException("Vault file not found", e); } catch(XMLStreamException t) { throw t; } finally { StreamUtils.safeClose(input); } return config; }
java
static VaultConfig readVaultElement_3_0(XMLExtendedStreamReader reader, Namespace expectedNs) throws XMLStreamException { final VaultConfig config = new VaultConfig(); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final String value = reader.getAttributeValue(i); String name = reader.getAttributeLocalName(i); if (name.equals(CODE)){ config.code = value; } else if (name.equals(MODULE)){ config.module = value; } else { unexpectedVaultAttribute(reader.getAttributeLocalName(i), reader); } } if (config.code == null && config.module != null){ throw new XMLStreamException("Attribute 'module' was specified without an attribute" + " 'code' for element '" + VAULT + "' at " + reader.getLocation()); } readVaultOptions(reader, config); return config; }
java