_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q2200
HostXml_4.addLocalHost
train
private ModelNode addLocalHost(final ModelNode address, final List<ModelNode> operationList, final String hostName) { String resolvedHost = hostName != null ? hostName : defaultHostControllerName; // All further operations should modify the newly added host so the address passed in is updated. address.add(HOST, resolvedHost); // Add a step to setup the ManagementResourceRegistrations for the root host resource final ModelNode hostAddOp = new ModelNode(); hostAddOp.get(OP).set(HostAddHandler.OPERATION_NAME); hostAddOp.get(OP_ADDR).set(address); operationList.add(hostAddOp); // Add a step to store the HC name ModelNode nameValue = hostName == null ? new ModelNode() : new ModelNode(hostName); final ModelNode writeName = Util.getWriteAttributeOperation(address, NAME, nameValue); operationList.add(writeName); return hostAddOp; }
java
{ "resource": "" }
q2201
HashUtil.hashPath
train
public static byte[] hashPath(MessageDigest messageDigest, Path path) throws IOException { try (InputStream in = getRecursiveContentStream(path)) { return hashContent(messageDigest, in); } }
java
{ "resource": "" }
q2202
CommandExecutor.doCommand
train
public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException { ModelNode request = cmdCtx.buildRequest(command); return execute(request, isSlowCommand(command)).getResponseNode(); }
java
{ "resource": "" }
q2203
CommandExecutor.doCommandFullResponse
train
public synchronized Response doCommandFullResponse(String command) throws CommandFormatException, IOException { ModelNode request = cmdCtx.buildRequest(command); boolean replacedBytes = replaceFilePathsWithBytes(request); OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes); return new Response(command, request, response); }
java
{ "resource": "" }
q2204
ServerEnvironment.getFilesFromProperty
train
private File[] getFilesFromProperty(final String name, final Properties props) { String sep = WildFlySecurityManager.getPropertyPrivileged("path.separator", null); String value = props.getProperty(name, null); if (value != null) { final String[] paths = value.split(Pattern.quote(sep)); final int len = paths.length; final File[] files = new File[len]; for (int i = 0; i < len; i++) { files[i] = new File(paths[i]); } return files; } return NO_FILES; }
java
{ "resource": "" }
q2205
AtomicMapFieldUpdater.putAtomic
train
public boolean putAtomic(C instance, K key, V value, Map<K, V> snapshot) { Assert.checkNotNullParam("key", key); final Map<K, V> newMap; final int oldSize = snapshot.size(); if (oldSize == 0) { newMap = Collections.singletonMap(key, value); } else if (oldSize == 1) { final Map.Entry<K, V> entry = snapshot.entrySet().iterator().next(); final K oldKey = entry.getKey(); if (oldKey.equals(key)) { return false; } else { newMap = new FastCopyHashMap<K, V>(snapshot); newMap.put(key, value); } } else { newMap = new FastCopyHashMap<K, V>(snapshot); newMap.put(key, value); } return updater.compareAndSet(instance, snapshot, newMap); }
java
{ "resource": "" }
q2206
ListAttributeDefinition.parseAndSetParameter
train
@Deprecated public void parseAndSetParameter(String value, ModelNode operation, XMLStreamReader reader) throws XMLStreamException { //we use manual parsing here, and not #getParser().. to preserve backward compatibility. if (value != null) { for (String element : value.split(",")) { parseAndAddParameterElement(element.trim(), operation, reader); } } }
java
{ "resource": "" }
q2207
ModelControllerLock.lock
train
boolean lock(final Integer permit, final long timeout, final TimeUnit unit) { boolean result = false; try { result = lockInterruptibly(permit, timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return result; }
java
{ "resource": "" }
q2208
ModelControllerLock.lockShared
train
boolean lockShared(final Integer permit, final long timeout, final TimeUnit unit) { boolean result = false; try { result = lockSharedInterruptibly(permit, timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return result; }
java
{ "resource": "" }
q2209
ModelControllerLock.lockInterruptibly
train
void lockInterruptibly(final Integer permit) throws InterruptedException { if (permit == null) { throw new IllegalArgumentException(); } sync.acquireInterruptibly(permit); }
java
{ "resource": "" }
q2210
ModelControllerLock.lockSharedInterruptibly
train
void lockSharedInterruptibly(final Integer permit) throws InterruptedException { if (permit == null) { throw new IllegalArgumentException(); } sync.acquireSharedInterruptibly(permit); }
java
{ "resource": "" }
q2211
ModelControllerLock.lockInterruptibly
train
boolean lockInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException { if (permit == null) { throw new IllegalArgumentException(); } return sync.tryAcquireNanos(permit, unit.toNanos(timeout)); }
java
{ "resource": "" }
q2212
ModelControllerLock.lockSharedInterruptibly
train
boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException { if (permit == null) { throw new IllegalArgumentException(); } return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout)); }
java
{ "resource": "" }
q2213
CapabilityRegistry.createShadowCopy
train
CapabilityRegistry createShadowCopy() { CapabilityRegistry result = new CapabilityRegistry(forServer, this); readLock.lock(); try { try { result.writeLock.lock(); copy(this, result); } finally { result.writeLock.unlock(); } } finally { readLock.unlock(); } return result; }
java
{ "resource": "" }
q2214
CapabilityRegistry.registerRequirement
train
private void registerRequirement(RuntimeRequirementRegistration requirement) { assert writeLock.isHeldByCurrentThread(); CapabilityId dependentId = requirement.getDependentId(); if (!capabilities.containsKey(dependentId)) { throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(), dependentId.getScope().getName()); } Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap = requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements; Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId); if (dependents == null) { dependents = new HashMap<>(); requirementMap.put(dependentId, dependents); } RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName()); if (existing == null) { dependents.put(requirement.getRequiredName(), requirement); } else { existing.addRegistrationPoint(requirement.getOldestRegistrationPoint()); } modified = true; }
java
{ "resource": "" }
q2215
CapabilityRegistry.removeCapabilityRequirement
train
@Override public void removeCapabilityRequirement(RuntimeRequirementRegistration requirementRegistration) { // We don't know if this got registered as an runtime-only requirement or a hard one // so clean it from both maps writeLock.lock(); try { removeRequirement(requirementRegistration, false); removeRequirement(requirementRegistration, true); } finally { writeLock.unlock(); } }
java
{ "resource": "" }
q2216
CapabilityRegistry.publish
train
void publish() { assert publishedFullRegistry != null : "Cannot write directly to main registry"; writeLock.lock(); try { if (!modified) { return; } publishedFullRegistry.writeLock.lock(); try { publishedFullRegistry.clear(true); copy(this, publishedFullRegistry); pendingRemoveCapabilities.clear(); pendingRemoveRequirements.clear(); modified = false; } finally { publishedFullRegistry.writeLock.unlock(); } } finally { writeLock.unlock(); } }
java
{ "resource": "" }
q2217
CapabilityRegistry.rollback
train
void rollback() { if (publishedFullRegistry == null) { return; } writeLock.lock(); try { publishedFullRegistry.readLock.lock(); try { clear(true); copy(publishedFullRegistry, this); modified = false; } finally { publishedFullRegistry.readLock.unlock(); } } finally { writeLock.unlock(); } }
java
{ "resource": "" }
q2218
LoggingSubsystemParser.addOperationAddress
train
static void addOperationAddress(final ModelNode operation, final PathAddress base, final String key, final String value) { operation.get(OP_ADDR).set(base.append(key, value).toModelNode()); }
java
{ "resource": "" }
q2219
FindNonProgressingOperationHandler.findNonProgressingOp
train
static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException { Resource.ResourceEntry nonProgressing = null; for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) { ModelNode model = child.getModel(); if (model.get(EXCLUSIVE_RUNNING_TIME).asLong() > timeout) { nonProgressing = child; ControllerLogger.MGMT_OP_LOGGER.tracef("non-progressing op: %s", nonProgressing.getModel()); break; } } if (nonProgressing != null && !forServer) { // WFCORE-263 // See if the op is non-progressing because it's the HC op waiting for commit // from the DC while other ops (i.e. ops proxied to our servers) associated // with the same domain-uuid are not completing ModelNode model = nonProgressing.getModel(); if (model.get(DOMAIN_ROLLOUT).asBoolean() && OperationContext.ExecutionStatus.COMPLETING.toString().equals(model.get(EXECUTION_STATUS).asString()) && model.hasDefined(DOMAIN_UUID)) { ControllerLogger.MGMT_OP_LOGGER.trace("Potential domain rollout issue"); String domainUUID = model.get(DOMAIN_UUID).asString(); Set<String> relatedIds = null; List<Resource.ResourceEntry> relatedExecutingOps = null; for (Resource.ResourceEntry activeOp : resource.getChildren(ACTIVE_OPERATION)) { if (nonProgressing.getName().equals(activeOp.getName())) { continue; // ignore self } ModelNode opModel = activeOp.getModel(); if (opModel.hasDefined(DOMAIN_UUID) && domainUUID.equals(opModel.get(DOMAIN_UUID).asString()) && opModel.get(RUNNING_TIME).asLong() > timeout) { if (relatedIds == null) { relatedIds = new TreeSet<String>(); // order these as an aid to unit testing } relatedIds.add(activeOp.getName()); // If the op is ExecutionStatus.EXECUTING that means it's still EXECUTING on the // server or a prepare message got lost. It would be COMPLETING if the server // had sent a prepare message, as that would result in ProxyStepHandler calling completeStep if (OperationContext.ExecutionStatus.EXECUTING.toString().equals(opModel.get(EXECUTION_STATUS).asString())) { if (relatedExecutingOps == null) { relatedExecutingOps = new ArrayList<Resource.ResourceEntry>(); } relatedExecutingOps.add(activeOp); ControllerLogger.MGMT_OP_LOGGER.tracef("Related executing: %s", opModel); } else ControllerLogger.MGMT_OP_LOGGER.tracef("Related non-executing: %s", opModel); } else ControllerLogger.MGMT_OP_LOGGER.tracef("unrelated: %s", opModel); } if (relatedIds != null) { // There are other ops associated with this domain-uuid that are also not completing // in the desired time, so we can't treat the one holding the lock as the problem. if (relatedExecutingOps != null && relatedExecutingOps.size() == 1) { // There's a single related op that's executing for too long. So we can report that one. // Note that it's possible that the same problem exists on other hosts as well // and that this cancellation will not resolve the overall problem. But, we only // get here on a slave HC and if the user is invoking this on a slave and not the // master, we'll assume they have a reason for doing that and want us to treat this // as a problem on this particular host. nonProgressing = relatedExecutingOps.get(0); } else { // Fail and provide a useful failure message. throw DomainManagementLogger.ROOT_LOGGER.domainRolloutNotProgressing(nonProgressing.getName(), timeout, domainUUID, relatedIds); } } } } return nonProgressing == null ? null : nonProgressing.getName(); }
java
{ "resource": "" }
q2220
FileSystemDeploymentService.bootTimeScan
train
void bootTimeScan(final DeploymentOperations deploymentOperations) { // WFCORE-1579: skip the scan if deployment dir is not available if (!checkDeploymentDir(this.deploymentDir)) { DeploymentScannerLogger.ROOT_LOGGER.bootTimeScanFailed(deploymentDir.getAbsolutePath()); return; } this.establishDeployedContentList(this.deploymentDir, deploymentOperations); deployedContentEstablished = true; if (acquireScanLock()) { try { scan(true, deploymentOperations); } finally { releaseScanLock(); } } }
java
{ "resource": "" }
q2221
FileSystemDeploymentService.scan
train
void scan() { if (acquireScanLock()) { boolean scheduleRescan = false; try { scheduleRescan = scan(false, deploymentOperations); } finally { try { if (scheduleRescan) { synchronized (this) { if (scanEnabled) { rescanIncompleteTask = scheduledExecutor.schedule(scanRunnable, 200, TimeUnit.MILLISECONDS); } } } } finally { releaseScanLock(); } } } }
java
{ "resource": "" }
q2222
FileSystemDeploymentService.forcedUndeployScan
train
void forcedUndeployScan() { if (acquireScanLock()) { try { ROOT_LOGGER.tracef("Performing a post-boot forced undeploy scan for scan directory %s", deploymentDir.getAbsolutePath()); ScanContext scanContext = new ScanContext(deploymentOperations); // Add remove actions to the plan for anything we count as // deployed that we didn't find on the scan for (Map.Entry<String, DeploymentMarker> missing : scanContext.toRemove.entrySet()) { // remove successful deployment and left will be removed if (scanContext.registeredDeployments.containsKey(missing.getKey())) { scanContext.registeredDeployments.remove(missing.getKey()); } } Set<String> scannedDeployments = new HashSet<String>(scanContext.registeredDeployments.keySet()); scannedDeployments.removeAll(scanContext.persistentDeployments); List<ScannerTask> scannerTasks = scanContext.scannerTasks; for (String toUndeploy : scannedDeployments) { scannerTasks.add(new UndeployTask(toUndeploy, deploymentDir, scanContext.scanStartTime, true)); } try { executeScannerTasks(scannerTasks, deploymentOperations, true); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ROOT_LOGGER.tracef("Forced undeploy scan complete"); } catch (Exception e) { ROOT_LOGGER.scanException(e, deploymentDir.getAbsolutePath()); } finally { releaseScanLock(); } } }
java
{ "resource": "" }
q2223
FileSystemDeploymentService.checkDeploymentDir
train
private boolean checkDeploymentDir(File directory) { if (!directory.exists()) { if (deploymentDirAccessible) { deploymentDirAccessible = false; ROOT_LOGGER.directoryIsNonexistent(deploymentDir.getAbsolutePath()); } } else if (!directory.isDirectory()) { if (deploymentDirAccessible) { deploymentDirAccessible = false; ROOT_LOGGER.isNotADirectory(deploymentDir.getAbsolutePath()); } } else if (!directory.canRead()) { if (deploymentDirAccessible) { deploymentDirAccessible = false; ROOT_LOGGER.directoryIsNotReadable(deploymentDir.getAbsolutePath()); } } else if (!directory.canWrite()) { if (deploymentDirAccessible) { deploymentDirAccessible = false; ROOT_LOGGER.directoryIsNotWritable(deploymentDir.getAbsolutePath()); } } else { deploymentDirAccessible = true; } return deploymentDirAccessible; }
java
{ "resource": "" }
q2224
LdapCacheResourceDefinition.createOperation
train
private static ModelNode createOperation(final ModelNode operationToValidate) { PathAddress pa = PathAddress.pathAddress(operationToValidate.require(OP_ADDR)); PathAddress validationAddress = pa.subAddress(0, pa.size() - 1); return Util.getEmptyOperation("validate-cache", validationAddress.toModelNode()); }
java
{ "resource": "" }
q2225
RequirementRegistration.getOldestRegistrationPoint
train
public synchronized RegistrationPoint getOldestRegistrationPoint() { return registrationPoints.size() == 0 ? null : registrationPoints.values().iterator().next().get(0); }
java
{ "resource": "" }
q2226
RequirementRegistration.getRegistrationPoints
train
public synchronized Set<RegistrationPoint> getRegistrationPoints() { Set<RegistrationPoint> result = new HashSet<>(); for (List<RegistrationPoint> registrationPoints : registrationPoints.values()) { result.addAll(registrationPoints); } return Collections.unmodifiableSet(result); }
java
{ "resource": "" }
q2227
DeploymentHandlerUtils.hasValidContentAdditionParameterDefined
train
public static boolean hasValidContentAdditionParameterDefined(ModelNode operation) { for (String s : DeploymentAttributes.MANAGED_CONTENT_ATTRIBUTES.keySet()) { if (operation.hasDefined(s)) { return true; } } return false; }
java
{ "resource": "" }
q2228
LayersFactory.load
train
static InstalledIdentity load(final InstalledImage image, final ProductConfig productConfig, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException { // build the identity information final String productVersion = productConfig.resolveVersion(); final String productName = productConfig.resolveName(); final Identity identity = new AbstractLazyIdentity() { @Override public String getName() { return productName; } @Override public String getVersion() { return productVersion; } @Override public InstalledImage getInstalledImage() { return image; } }; final Properties properties = PatchUtils.loadProperties(identity.getDirectoryStructure().getInstallationInfo()); final List<String> allPatches = PatchUtils.readRefs(properties, Constants.ALL_PATCHES); // Step 1 - gather the installed layers data final InstalledConfiguration conf = createInstalledConfig(image); // Step 2 - process the actual module and bundle roots final ProcessedLayers processedLayers = process(conf, moduleRoots, bundleRoots); final InstalledConfiguration config = processedLayers.getConf(); // Step 3 - create the actual config objects // Process layers final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl(identity, allPatches, image); for (final LayerPathConfig layer : processedLayers.getLayers().values()) { final String name = layer.name; installedIdentity.putLayer(name, createPatchableTarget(name, layer, config.getLayerMetadataDir(name), image)); } // Process add-ons for (final LayerPathConfig addOn : processedLayers.getAddOns().values()) { final String name = addOn.name; installedIdentity.putAddOn(name, createPatchableTarget(name, addOn, config.getAddOnMetadataDir(name), image)); } return installedIdentity; }
java
{ "resource": "" }
q2229
LayersFactory.process
train
static ProcessedLayers process(final InstalledConfiguration conf, final List<File> moduleRoots, final List<File> bundleRoots) throws IOException { final ProcessedLayers layers = new ProcessedLayers(conf); // Process module roots final LayerPathSetter moduleSetter = new LayerPathSetter() { @Override public boolean setPath(final LayerPathConfig pending, final File root) { if (pending.modulePath == null) { pending.modulePath = root; return true; } return false; } }; for (final File moduleRoot : moduleRoots) { processRoot(moduleRoot, layers, moduleSetter); } // Process bundle root final LayerPathSetter bundleSetter = new LayerPathSetter() { @Override public boolean setPath(LayerPathConfig pending, File root) { if (pending.bundlePath == null) { pending.bundlePath = root; return true; } return false; } }; for (final File bundleRoot : bundleRoots) { processRoot(bundleRoot, layers, bundleSetter); } // if (conf.getInstalledLayers().size() != layers.getLayers().size()) { // throw processingError("processed layers don't match expected %s, but was %s", conf.getInstalledLayers(), layers.getLayers().keySet()); // } // if (conf.getInstalledAddOns().size() != layers.getAddOns().size()) { // throw processingError("processed add-ons don't match expected %s, but was %s", conf.getInstalledAddOns(), layers.getAddOns().keySet()); // } return layers; }
java
{ "resource": "" }
q2230
LayersFactory.processRoot
train
static void processRoot(final File root, final ProcessedLayers layers, final LayerPathSetter setter) throws IOException { final LayersConfig layersConfig = LayersConfig.getLayersConfig(root); // Process layers final File layersDir = new File(root, layersConfig.getLayersPath()); if (!layersDir.exists()) { if (layersConfig.isConfigured()) { // Bad config from user throw PatchLogger.ROOT_LOGGER.installationNoLayersConfigFound(layersDir.getAbsolutePath()); } // else this isn't a root that has layers and add-ons } else { // check for a valid layer configuration for (final String layer : layersConfig.getLayers()) { File layerDir = new File(layersDir, layer); if (!layerDir.exists()) { if (layersConfig.isConfigured()) { // Bad config from user throw PatchLogger.ROOT_LOGGER.installationMissingLayer(layer, layersDir.getAbsolutePath()); } // else this isn't a standard layers and add-ons structure return; } layers.addLayer(layer, layerDir, setter); } } // Finally process the add-ons final File addOnsDir = new File(root, layersConfig.getAddOnsPath()); final File[] addOnsList = addOnsDir.listFiles(); if (addOnsList != null) { for (final File addOn : addOnsList) { layers.addAddOn(addOn.getName(), addOn, setter); } } }
java
{ "resource": "" }
q2231
LayersFactory.createPatchableTarget
train
static AbstractLazyPatchableTarget createPatchableTarget(final String name, final LayerPathConfig layer, final File metadata, final InstalledImage image) throws IOException { // patchable target return new AbstractLazyPatchableTarget() { @Override public InstalledImage getInstalledImage() { return image; } @Override public File getModuleRoot() { return layer.modulePath; } @Override public File getBundleRepositoryRoot() { return layer.bundlePath; } public File getPatchesMetadata() { return metadata; } @Override public String getName() { return name; } }; }
java
{ "resource": "" }
q2232
AttributeDefinition.getAllowedValues
train
public List<ModelNode> getAllowedValues() { if (allowedValues == null) { return Collections.emptyList(); } return Arrays.asList(this.allowedValues); }
java
{ "resource": "" }
q2233
AttributeDefinition.addAllowedValuesToDescription
train
protected void addAllowedValuesToDescription(ModelNode result, ParameterValidator validator) { if (allowedValues != null) { for (ModelNode allowedValue : allowedValues) { result.get(ModelDescriptionConstants.ALLOWED).add(allowedValue); } } else if (validator instanceof AllowedValuesValidator) { AllowedValuesValidator avv = (AllowedValuesValidator) validator; List<ModelNode> allowed = avv.getAllowedValues(); if (allowed != null) { for (ModelNode ok : allowed) { result.get(ModelDescriptionConstants.ALLOWED).add(ok); } } } }
java
{ "resource": "" }
q2234
Util.validateRequest
train
public static ModelNode validateRequest(CommandContext ctx, ModelNode request) throws CommandFormatException { final Set<String> keys = request.keys(); if (keys.size() == 2) { // no props return null; } ModelNode outcome = (ModelNode) ctx.get(Scope.REQUEST, DESCRIPTION_RESPONSE); if (outcome == null) { outcome = retrieveDescription(ctx, request, true); if (outcome == null) { return null; } else { ctx.set(Scope.REQUEST, DESCRIPTION_RESPONSE, outcome); } } if(!outcome.has(Util.RESULT)) { throw new CommandFormatException("Failed to perform " + Util.READ_OPERATION_DESCRIPTION + " to validate the request: result is not available."); } final String operationName = request.get(Util.OPERATION).asString(); final ModelNode result = outcome.get(Util.RESULT); final Set<String> definedProps = result.hasDefined(Util.REQUEST_PROPERTIES) ? result.get(Util.REQUEST_PROPERTIES).keys() : Collections.emptySet(); if(definedProps.isEmpty()) { if(!(keys.size() == 3 && keys.contains(Util.OPERATION_HEADERS))) { throw new CommandFormatException("Operation '" + operationName + "' does not expect any property."); } } else { int skipped = 0; for(String prop : keys) { if(skipped < 2 && (prop.equals(Util.ADDRESS) || prop.equals(Util.OPERATION))) { ++skipped; continue; } if(!definedProps.contains(prop)) { if(!Util.OPERATION_HEADERS.equals(prop)) { throw new CommandFormatException("'" + prop + "' is not found among the supported properties: " + definedProps); } } } } return outcome; }
java
{ "resource": "" }
q2235
Util.reconnectContext
train
public static boolean reconnectContext(RedirectException re, CommandContext ctx) { boolean reconnected = false; try { ConnectionInfo info = ctx.getConnectionInfo(); ControllerAddress address = null; if (info != null) { address = info.getControllerAddress(); } if (address != null && isHttpsRedirect(re, address.getProtocol())) { LOG.debug("Trying to reconnect an http to http upgrade"); try { ctx.connectController(); reconnected = true; } catch (Exception ex) { LOG.warn("Exception reconnecting", ex); // Proper https redirect but error. // Ignoring it. } } } catch (URISyntaxException ex) { LOG.warn("Invalid URI: ", ex); // OK, invalid redirect. } return reconnected; }
java
{ "resource": "" }
q2236
Util.compactToString
train
public static String compactToString(ModelNode node) { Objects.requireNonNull(node); final StringWriter stringWriter = new StringWriter(); final PrintWriter writer = new PrintWriter(stringWriter, true); node.writeString(writer, true); return stringWriter.toString(); }
java
{ "resource": "" }
q2237
S3Discovery.init
train
private void init() { validatePreSignedUrls(); try { conn = new AWSAuthConnection(access_key, secret_access_key); // Determine the bucket name if prefix is set or if pre-signed URLs are being used if (prefix != null && prefix.length() > 0) { ListAllMyBucketsResponse bucket_list = conn.listAllMyBuckets(null); List buckets = bucket_list.entries; if (buckets != null) { boolean found = false; for (Object tmp : buckets) { if (tmp instanceof Bucket) { Bucket bucket = (Bucket) tmp; if (bucket.name.startsWith(prefix)) { location = bucket.name; found = true; } } } if (!found) { location = prefix + "-" + java.util.UUID.randomUUID().toString(); } } } if (usingPreSignedUrls()) { PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url); location = parsedPut.getBucket(); } if (!conn.checkBucketExists(location)) { conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage(); } } catch (Exception e) { throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3Bucket(location, e.getLocalizedMessage()); } }
java
{ "resource": "" }
q2238
S3Discovery.readFromFile
train
private List<DomainControllerData> readFromFile(String directoryName) { List<DomainControllerData> data = new ArrayList<DomainControllerData>(); if (directoryName == null) { return data; } if (conn == null) { init(); } try { if (usingPreSignedUrls()) { PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url); directoryName = parsedPut.getPrefix(); } String key = S3Util.sanitize(directoryName) + "/" + S3Util.sanitize(DC_FILE_NAME); GetResponse val = conn.get(location, key, null); if (val.object != null) { byte[] buf = val.object.data; if (buf != null && buf.length > 0) { try { data = S3Util.domainControllerDataFromByteBuffer(buf); } catch (Exception e) { throw HostControllerLogger.ROOT_LOGGER.failedMarshallingDomainControllerData(); } } } return data; } catch (IOException e) { throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3File(e.getLocalizedMessage()); } }
java
{ "resource": "" }
q2239
S3Discovery.writeToFile
train
private void writeToFile(List<DomainControllerData> data, String domainName) throws IOException { if(domainName == null || data == null) { return; } if (conn == null) { init(); } try { String key = S3Util.sanitize(domainName) + "/" + S3Util.sanitize(DC_FILE_NAME); byte[] buf = S3Util.domainControllerDataToByteBuffer(data); S3Object val = new S3Object(buf, null); if (usingPreSignedUrls()) { Map headers = new TreeMap(); headers.put("x-amz-acl", Arrays.asList("public-read")); conn.put(pre_signed_put_url, val, headers).connection.getResponseMessage(); } else { Map headers = new TreeMap(); headers.put("Content-Type", Arrays.asList("text/plain")); conn.put(location, key, val, headers).connection.getResponseMessage(); } } catch(Exception e) { throw HostControllerLogger.ROOT_LOGGER.cannotWriteToS3File(e.getLocalizedMessage()); } }
java
{ "resource": "" }
q2240
S3Discovery.remove
train
private void remove(String directoryName) { if ((directoryName == null) || (conn == null)) return; String key = S3Util.sanitize(directoryName) + "/" + S3Util.sanitize(DC_FILE_NAME); try { Map headers = new TreeMap(); headers.put("Content-Type", Arrays.asList("text/plain")); if (usingPreSignedUrls()) { conn.delete(pre_signed_delete_url).connection.getResponseMessage(); } else { conn.delete(location, key, headers).connection.getResponseMessage(); } } catch(Exception e) { ROOT_LOGGER.cannotRemoveS3File(e); } }
java
{ "resource": "" }
q2241
GlobalTransformerRegistry.mergeSubtree
train
public void mergeSubtree(final OperationTransformerRegistry targetRegistry, final Map<PathAddress, ModelVersion> subTree) { for(Map.Entry<PathAddress, ModelVersion> entry: subTree.entrySet()) { mergeSubtree(targetRegistry, entry.getKey(), entry.getValue()); } }
java
{ "resource": "" }
q2242
HandlerOperations.isDisabledHandler
train
private static boolean isDisabledHandler(final LogContext logContext, final String handlerName) { final Map<String, String> disableHandlers = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY); return disableHandlers != null && disableHandlers.containsKey(handlerName); }
java
{ "resource": "" }
q2243
ObjectNameAddressUtil.toPathAddress
train
static PathAddress toPathAddress(String domain, ImmutableManagementResourceRegistration registry, ObjectName name) { if (!name.getDomain().equals(domain)) { return PathAddress.EMPTY_ADDRESS; } if (name.equals(ModelControllerMBeanHelper.createRootObjectName(domain))) { return PathAddress.EMPTY_ADDRESS; } final Hashtable<String, String> properties = name.getKeyPropertyList(); return searchPathAddress(PathAddress.EMPTY_ADDRESS, registry, properties); }
java
{ "resource": "" }
q2244
WorkerService.stopDone
train
private void stopDone() { synchronized (stopLock) { final StopContext stopContext = this.stopContext; this.stopContext = null; if (stopContext != null) { stopContext.complete(); } stopLock.notifyAll(); } }
java
{ "resource": "" }
q2245
DefaultCheckersAndConverter.getRejectionLogMessageId
train
public String getRejectionLogMessageId() { String id = logMessageId; if (id == null) { id = getRejectionLogMessage(Collections.<String, ModelNode>emptyMap()); } logMessageId = id; return logMessageId; }
java
{ "resource": "" }
q2246
ServerInventoryService.stop
train
@Override public synchronized void stop(final StopContext context) { final boolean shutdownServers = runningModeControl.getRestartMode() == RestartMode.SERVERS; if (shutdownServers) { Runnable task = new Runnable() { @Override public void run() { try { serverInventory.shutdown(true, -1, true); // TODO graceful shutdown serverInventory = null; // client.getValue().setServerInventory(null); } finally { serverCallback.getValue().setCallbackHandler(null); context.complete(); } } }; try { executorService.getValue().execute(task); } catch (RejectedExecutionException e) { task.run(); } finally { context.asynchronous(); } } else { // We have to set the shutdown flag in any case serverInventory.shutdown(false, -1, true); serverInventory = null; } }
java
{ "resource": "" }
q2247
IgnoredDomainResourceRegistry.isResourceExcluded
train
public boolean isResourceExcluded(final PathAddress address) { if (!localHostControllerInfo.isMasterDomainController() && address.size() > 0) { IgnoredDomainResourceRoot root = this.rootResource; PathElement firstElement = address.getElement(0); IgnoreDomainResourceTypeResource typeResource = root == null ? null : root.getChildInternal(firstElement.getKey()); if (typeResource != null) { if (typeResource.hasName(firstElement.getValue())) { return true; } } } return false; }
java
{ "resource": "" }
q2248
DomainHostExcludeRegistry.getVersionIgnoreData
train
VersionExcludeData getVersionIgnoreData(int major, int minor, int micro) { VersionExcludeData result = registry.get(new VersionKey(major, minor, micro)); if (result == null) { result = registry.get(new VersionKey(major, minor, null)); } return result; }
java
{ "resource": "" }
q2249
PathUtil.copyRecursively
train
public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException { final CopyOption[] options; if (overwrite) { options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING}; } else { options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES}; } Files.walkFileTree(source, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Files.copy(dir, target.resolve(source.relativize(dir)), options); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, target.resolve(source.relativize(file)), options); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { DeploymentRepositoryLogger.ROOT_LOGGER.cannotCopyFile(exc, file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); }
java
{ "resource": "" }
q2250
PathUtil.deleteSilentlyRecursively
train
public static void deleteSilentlyRecursively(final Path path) { if (path != null) { try { deleteRecursively(path); } catch (IOException ioex) { DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(ioex, path); } } }
java
{ "resource": "" }
q2251
PathUtil.deleteRecursively
train
public static void deleteRecursively(final Path path) throws IOException { DeploymentRepositoryLogger.ROOT_LOGGER.debugf("Deleting %s recursively", path); if (Files.exists(path)) { Files.walkFileTree(path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(exc, path); throw exc; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } }
java
{ "resource": "" }
q2252
PathUtil.resolveSecurely
train
public static final Path resolveSecurely(Path rootPath, String path) { Path resolvedPath; if(path == null || path.isEmpty()) { resolvedPath = rootPath.normalize(); } else { String relativePath = removeSuperflousSlashes(path); resolvedPath = rootPath.resolve(relativePath).normalize(); } if(!resolvedPath.startsWith(rootPath)) { throw DeploymentRepositoryLogger.ROOT_LOGGER.forbiddenPath(path); } return resolvedPath; }
java
{ "resource": "" }
q2253
PathUtil.listFiles
train
public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException { List<ContentRepositoryElement> result = new ArrayList<>(); if (Files.exists(rootPath)) { if(isArchive(rootPath)) { return listZipContent(rootPath, filter); } Files.walkFileTree(rootPath, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (filter.acceptFile(rootPath, file)) { result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file))); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (filter.acceptDirectory(rootPath, dir)) { String directoryPath = formatDirectoryPath(rootPath.relativize(dir)); if(! "/".equals(directoryPath)) { result.add(ContentRepositoryElement.createFolder(directoryPath)); } } return FileVisitResult.CONTINUE; } private String formatDirectoryPath(Path path) { return formatPath(path) + '/'; } private String formatPath(Path path) { return path.toString().replace(File.separatorChar, '/'); } }); } else { Path file = getFile(rootPath); if(isArchive(file)) { Path relativePath = file.relativize(rootPath); Path target = createTempDirectory(tempDir, "unarchive"); unzip(file, target); return listFiles(target.resolve(relativePath), tempDir, filter); } else { throw new FileNotFoundException(rootPath.toString()); } } return result; }
java
{ "resource": "" }
q2254
PathUtil.createTempDirectory
train
public static Path createTempDirectory(Path dir, String prefix) throws IOException { try { return Files.createTempDirectory(dir, prefix); } catch (UnsupportedOperationException ex) { } return Files.createTempDirectory(dir, prefix); }
java
{ "resource": "" }
q2255
PathUtil.unzip
train
public static void unzip(Path zip, Path target) throws IOException { try (final ZipFile zipFile = new ZipFile(zip.toFile())){ unzip(zipFile, target); } }
java
{ "resource": "" }
q2256
RelativePathService.addService
train
public static ServiceController<String> addService(final ServiceName name, final String path, boolean possiblyAbsolute, final String relativeTo, final ServiceTarget serviceTarget) { if (possiblyAbsolute && isAbsoluteUnixOrWindowsPath(path)) { return AbsolutePathService.addService(name, path, serviceTarget); } RelativePathService service = new RelativePathService(path); ServiceBuilder<String> builder = serviceTarget.addService(name, service) .addDependency(pathNameOf(relativeTo), String.class, service.injectedPath); ServiceController<String> svc = builder.install(); return svc; }
java
{ "resource": "" }
q2257
PatchingGarbageLocator.getInactiveHistory
train
public List<File> getInactiveHistory() throws PatchingException { if (validHistory == null) { walk(); } final File[] inactiveDirs = installedIdentity.getInstalledImage().getPatchesDir().listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() && !validHistory.contains(pathname.getName()); } }); return inactiveDirs == null ? Collections.<File>emptyList() : Arrays.asList(inactiveDirs); }
java
{ "resource": "" }
q2258
PatchingGarbageLocator.getInactiveOverlays
train
public List<File> getInactiveOverlays() throws PatchingException { if (referencedOverlayDirectories == null) { walk(); } List<File> inactiveDirs = null; for (Layer layer : installedIdentity.getLayers()) { final File overlaysDir = new File(layer.getDirectoryStructure().getModuleRoot(), Constants.OVERLAYS); final File[] inactiveLayerDirs = overlaysDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() && !referencedOverlayDirectories.contains(pathname); } }); if (inactiveLayerDirs != null && inactiveLayerDirs.length > 0) { if (inactiveDirs == null) { inactiveDirs = new ArrayList<File>(); } inactiveDirs.addAll(Arrays.asList(inactiveLayerDirs)); } } return inactiveDirs == null ? Collections.<File>emptyList() : inactiveDirs; }
java
{ "resource": "" }
q2259
PatchingGarbageLocator.deleteInactiveContent
train
public void deleteInactiveContent() throws PatchingException { List<File> dirs = getInactiveHistory(); if (!dirs.isEmpty()) { for (File dir : dirs) { deleteDir(dir, ALL); } } dirs = getInactiveOverlays(); if (!dirs.isEmpty()) { for (File dir : dirs) { deleteDir(dir, ALL); } } }
java
{ "resource": "" }
q2260
HostControllerBootstrap.bootstrap
train
public void bootstrap() throws Exception { final HostRunningModeControl runningModeControl = environment.getRunningModeControl(); final ControlledProcessState processState = new ControlledProcessState(true); shutdownHook.setControlledProcessState(processState); ServiceTarget target = serviceContainer.subTarget(); ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService.addService(target, processState).getValue(); RunningStateJmx.registerMBean(controlledProcessStateService, null, runningModeControl, false); final HostControllerService hcs = new HostControllerService(environment, runningModeControl, authCode, processState); target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install(); }
java
{ "resource": "" }
q2261
PersistentResourceXMLDescription.persistDecorator
train
private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException { if (shouldWriteDecoratorAndElements(model)) { writer.writeStartElement(decoratorElement); persistChildren(writer, model); writer.writeEndElement(); } }
java
{ "resource": "" }
q2262
PersistentResourceXMLDescription.decorator
train
@Deprecated public static PersistentResourceXMLBuilder decorator(final String elementName) { return new PersistentResourceXMLBuilder(PathElement.pathElement(elementName), null).setDecoratorGroup(elementName); }
java
{ "resource": "" }
q2263
AttributeTransformationDescription.rejectAttributes
train
void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) { for (RejectAttributeChecker checker : checks) { rejectedAttributes.checkAttribute(checker, name, attributeValue); } }
java
{ "resource": "" }
q2264
ConcreteResourceRegistration.getInheritableOperationEntryLocked
train
private OperationEntry getInheritableOperationEntryLocked(final String operationName) { final OperationEntry entry = operations == null ? null : operations.get(operationName); if (entry != null && entry.isInherited()) { return entry; } return null; }
java
{ "resource": "" }
q2265
IgnoredDomainResourceRoot.registerChildInternal
train
private void registerChildInternal(IgnoreDomainResourceTypeResource child) { child.setParent(this); children.put(child.getName(), child); }
java
{ "resource": "" }
q2266
FutureManagementChannel.awaitChannel
train
protected Channel awaitChannel() throws IOException { Channel channel = this.channel; if(channel != null) { return channel; } synchronized (lock) { for(;;) { if(state == State.CLOSED) { throw ProtocolLogger.ROOT_LOGGER.channelClosed(); } channel = this.channel; if(channel != null) { return channel; } if(state == State.CLOSING) { throw ProtocolLogger.ROOT_LOGGER.channelClosed(); } try { lock.wait(); } catch (InterruptedException e) { throw new IOException(e); } } } }
java
{ "resource": "" }
q2267
FutureManagementChannel.prepareClose
train
protected boolean prepareClose() { synchronized (lock) { final State state = this.state; if (state == State.OPEN) { this.state = State.CLOSING; lock.notifyAll(); return true; } } return false; }
java
{ "resource": "" }
q2268
FutureManagementChannel.setChannel
train
protected boolean setChannel(final Channel newChannel) { if(newChannel == null) { return false; } synchronized (lock) { if(state != State.OPEN || channel != null) { return false; } this.channel = newChannel; this.channel.addCloseHandler(new CloseHandler<Channel>() { @Override public void handleClose(final Channel closed, final IOException exception) { synchronized (lock) { if(FutureManagementChannel.this.channel == closed) { FutureManagementChannel.this.channel = null; } lock.notifyAll(); } } }); lock.notifyAll(); return true; } }
java
{ "resource": "" }
q2269
DomainDeploymentOverlayRedeployLinksHandler.isRedeployAfterRemoval
train
private boolean isRedeployAfterRemoval(ModelNode operation) { return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) && operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean(); }
java
{ "resource": "" }
q2270
AbstractFileAuditLogHandler.createNewFile
train
protected void createNewFile(final File file) { try { file.createNewFile(); setFileNotWorldReadablePermissions(file); } catch (IOException e){ throw new RuntimeException(e); } }
java
{ "resource": "" }
q2271
AbstractFileAuditLogHandler.setFileNotWorldReadablePermissions
train
private void setFileNotWorldReadablePermissions(File file) { file.setReadable(false, false); file.setWritable(false, false); file.setExecutable(false, false); file.setReadable(true, true); file.setWritable(true, true); }
java
{ "resource": "" }
q2272
Seam2Processor.getSeamIntResourceRoot
train
protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException { try { if (seamIntResourceRoot == null) { final ModuleLoader moduleLoader = Module.getBootModuleLoader(); Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE); URL url = extModule.getExportedResource(SEAM_INT_JAR); if (url == null) throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule); File file = new File(url.toURI()); VirtualFile vf = VFS.getChild(file.toURI()); final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider()); Service<Closeable> mountHandleService = new Service<Closeable>() { public void start(StartContext startContext) throws StartException { } public void stop(StopContext stopContext) { VFSUtils.safeClose(mountHandle); } public Closeable getValue() throws IllegalStateException, IllegalArgumentException { return mountHandle; } }; ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR), mountHandleService); builder.setInitialMode(ServiceController.Mode.ACTIVE).install(); serviceTarget = null; // our cleanup service install work is done MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above seamIntResourceRoot = new ResourceRoot(vf, dummy); } return seamIntResourceRoot; } catch (Exception e) { throw new DeploymentUnitProcessingException(e); } }
java
{ "resource": "" }
q2273
PathAddress.pathAddress
train
public static PathAddress pathAddress(final ModelNode node) { if (node.isDefined()) { // final List<Property> props = node.asPropertyList(); // Following bit is crap TODO; uncomment above and delete below // when bug is fixed final List<Property> props = new ArrayList<Property>(); String key = null; for (ModelNode element : node.asList()) { Property prop = null; if (element.getType() == ModelType.PROPERTY || element.getType() == ModelType.OBJECT) { prop = element.asProperty(); } else if (key == null) { key = element.asString(); } else { prop = new Property(key, element); } if (prop != null) { props.add(prop); key = null; } } if (props.size() == 0) { return EMPTY_ADDRESS; } else { final Set<String> seen = new HashSet<String>(); final List<PathElement> values = new ArrayList<PathElement>(); int index = 0; for (final Property prop : props) { final String name = prop.getName(); if (seen.add(name)) { values.add(new PathElement(name, prop.getValue().asString())); } else { throw duplicateElement(name); } if (index == 1 && name.equals(SERVER) && seen.contains(HOST)) { seen.clear(); } index++; } return new PathAddress(Collections.unmodifiableList(values)); } } else { return EMPTY_ADDRESS; } }
java
{ "resource": "" }
q2274
PathAddress.getElement
train
public PathElement getElement(int index) { final List<PathElement> list = pathAddressList; return list.get(index); }
java
{ "resource": "" }
q2275
PathAddress.getLastElement
train
public PathElement getLastElement() { final List<PathElement> list = pathAddressList; return list.size() == 0 ? null : list.get(list.size() - 1); }
java
{ "resource": "" }
q2276
PathAddress.append
train
public PathAddress append(List<PathElement> additionalElements) { final ArrayList<PathElement> newList = new ArrayList<PathElement>(pathAddressList.size() + additionalElements.size()); newList.addAll(pathAddressList); newList.addAll(additionalElements); return pathAddress(newList); }
java
{ "resource": "" }
q2277
PathAddress.navigate
train
@Deprecated public ModelNode navigate(ModelNode model, boolean create) throws NoSuchElementException { final Iterator<PathElement> i = pathAddressList.iterator(); while (i.hasNext()) { final PathElement element = i.next(); if (create && !i.hasNext()) { if (element.isMultiTarget()) { throw new IllegalStateException(); } model = model.require(element.getKey()).get(element.getValue()); } else { model = model.require(element.getKey()).require(element.getValue()); } } return model; }
java
{ "resource": "" }
q2278
PathAddress.remove
train
@Deprecated public ModelNode remove(ModelNode model) throws NoSuchElementException { final Iterator<PathElement> i = pathAddressList.iterator(); while (i.hasNext()) { final PathElement element = i.next(); if (i.hasNext()) { model = model.require(element.getKey()).require(element.getValue()); } else { final ModelNode parent = model.require(element.getKey()); model = parent.remove(element.getValue()).clone(); } } return model; }
java
{ "resource": "" }
q2279
PathAddress.toModelNode
train
public ModelNode toModelNode() { final ModelNode node = new ModelNode().setEmptyList(); for (PathElement element : pathAddressList) { final String value; if (element.isMultiTarget() && !element.isWildcard()) { value = '[' + element.getValue() + ']'; } else { value = element.getValue(); } node.add(element.getKey(), value); } return node; }
java
{ "resource": "" }
q2280
PathAddress.matches
train
public boolean matches(PathAddress address) { if (address == null) { return false; } if (equals(address)) { return true; } if (size() != address.size()) { return false; } for (int i = 0; i < size(); i++) { PathElement pe = getElement(i); PathElement other = address.getElement(i); if (!pe.matches(other)) { // Could be a multiTarget with segments if (pe.isMultiTarget() && !pe.isWildcard()) { boolean matched = false; for (String segment : pe.getSegments()) { if (segment.equals(other.getValue())) { matched = true; break; } } if (!matched) { return false; } } else { return false; } } } return true; }
java
{ "resource": "" }
q2281
ResourceRootIndexer.indexResourceRoot
train
public static void indexResourceRoot(final ResourceRoot resourceRoot) throws DeploymentUnitProcessingException { if (resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX) != null) { return; } VirtualFile indexFile = resourceRoot.getRoot().getChild(ModuleIndexBuilder.INDEX_LOCATION); if (indexFile.exists()) { try { IndexReader reader = new IndexReader(indexFile.openStream()); resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, reader.read()); ServerLogger.DEPLOYMENT_LOGGER.tracef("Found and read index at: %s", indexFile); return; } catch (Exception e) { ServerLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndex(indexFile.getPathName()); } } // if this flag is present and set to false then do not index the resource Boolean shouldIndexResource = resourceRoot.getAttachment(Attachments.INDEX_RESOURCE_ROOT); if (shouldIndexResource != null && !shouldIndexResource) { return; } final List<String> indexIgnorePathList = resourceRoot.getAttachment(Attachments.INDEX_IGNORE_PATHS); final Set<String> indexIgnorePaths; if (indexIgnorePathList != null && !indexIgnorePathList.isEmpty()) { indexIgnorePaths = new HashSet<String>(indexIgnorePathList); } else { indexIgnorePaths = null; } final VirtualFile virtualFile = resourceRoot.getRoot(); final Indexer indexer = new Indexer(); try { final VisitorAttributes visitorAttributes = new VisitorAttributes(); visitorAttributes.setLeavesOnly(true); visitorAttributes.setRecurseFilter(new VirtualFileFilter() { public boolean accepts(VirtualFile file) { return indexIgnorePaths == null || !indexIgnorePaths.contains(file.getPathNameRelativeTo(virtualFile)); } }); final List<VirtualFile> classChildren = virtualFile.getChildren(new SuffixMatchFilter(".class", visitorAttributes)); for (VirtualFile classFile : classChildren) { InputStream inputStream = null; try { inputStream = classFile.openStream(); indexer.index(inputStream); } catch (Exception e) { ServerLogger.DEPLOYMENT_LOGGER.cannotIndexClass(classFile.getPathNameRelativeTo(virtualFile), virtualFile.getPathName(), e); } finally { VFSUtils.safeClose(inputStream); } } final Index index = indexer.complete(); resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, index); ServerLogger.DEPLOYMENT_LOGGER.tracef("Generated index for archive %s", virtualFile); } catch (Throwable t) { throw ServerLogger.ROOT_LOGGER.deploymentIndexingFailed(t); } }
java
{ "resource": "" }
q2282
PatchHistoryValidations.validateRollbackState
train
public static void validateRollbackState(final String patchID, final InstalledIdentity identity) throws PatchingException { final Set<String> validHistory = processRollbackState(patchID, identity); if (patchID != null && !validHistory.contains(patchID)) { throw PatchLogger.ROOT_LOGGER.patchNotFoundInHistory(patchID); } }
java
{ "resource": "" }
q2283
JPADeploymentMarker.mark
train
public static void mark(DeploymentUnit unit) { unit = DeploymentUtils.getTopDeploymentUnit(unit); unit.putAttachment(MARKER, Boolean.TRUE); }
java
{ "resource": "" }
q2284
ContentRepositoryImpl.cleanObsoleteContent
train
@Override public Map<String, Set<String>> cleanObsoleteContent() { if(!readWrite) { return Collections.emptyMap(); } Map<String, Set<String>> cleanedContents = new HashMap<>(2); cleanedContents.put(MARKED_CONTENT, new HashSet<>()); cleanedContents.put(DELETED_CONTENT, new HashSet<>()); synchronized (contentHashReferences) { for (ContentReference fsContent : listLocalContents()) { if (!readWrite) { return Collections.emptyMap(); } if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content if (markAsObsolete(fsContent)) { cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier()); } else { cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier()); } } else { obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents } } } return cleanedContents; }
java
{ "resource": "" }
q2285
ContentRepositoryImpl.markAsObsolete
train
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
{ "resource": "" }
q2286
ReadMasterDomainModelUtil.readMasterDomainResourcesForInitialConnect
train
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
{ "resource": "" }
q2287
ReadMasterDomainModelUtil.describeAsNodeList
train
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
{ "resource": "" }
q2288
ReadMasterDomainModelUtil.populateHostResolutionContext
train
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
{ "resource": "" }
q2289
ReadMasterDomainModelUtil.processServerConfig
train
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
{ "resource": "" }
q2290
ReadMasterDomainModelUtil.createServerIgnoredRegistry
train
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
{ "resource": "" }
q2291
IgnoredNonAffectedServerGroupsUtil.addCurrentServerGroupsToHostInfoModel
train
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
{ "resource": "" }
q2292
IgnoredNonAffectedServerGroupsUtil.ignoreOperation
train
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
{ "resource": "" }
q2293
IgnoredNonAffectedServerGroupsUtil.getServerConfigsOnSlave
train
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
{ "resource": "" }
q2294
SyncModelOperationHandlerWrapper.syncWithMaster
train
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
{ "resource": "" }
q2295
CLI.cmd
train
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
{ "resource": "" }
q2296
AbstractControllerService.boot
train
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
{ "resource": "" }
q2297
AbstractControllerService.boot
train
protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException { return boot(bootOperations, rollbackOnRuntimeFailure, false, ModelControllerImpl.getMutableRootResourceRegistrationProvider()); }
java
{ "resource": "" }
q2298
Messages.getBundle
train
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
{ "resource": "" }
q2299
Caller.getName
train
public String getName() { if (name == null && securityIdentity != null) { name = securityIdentity.getPrincipal().getName(); } return name; }
java
{ "resource": "" }