idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
145,400
void rejectAttributes ( RejectedAttributesLogContext rejectedAttributes , ModelNode attributeValue ) { for ( RejectAttributeChecker checker : checks ) { rejectedAttributes . checkAttribute ( checker , name , attributeValue ) ; } }
Checks attributes for rejection
48
5
145,401
private OperationEntry getInheritableOperationEntryLocked ( final String operationName ) { final OperationEntry entry = operations == null ? null : operations . get ( operationName ) ; if ( entry != null && entry . isInherited ( ) ) { return entry ; } return null ; }
Only call with the read lock held
61
7
145,402
private void registerChildInternal ( IgnoreDomainResourceTypeResource child ) { child . setParent ( this ) ; children . put ( child . getName ( ) , child ) ; }
call with lock on children held
37
6
145,403
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 ) ; } } } }
Get the underlying channel . This may block until the channel is set .
142
14
145,404
protected boolean prepareClose ( ) { synchronized ( lock ) { final State state = this . state ; if ( state == State . OPEN ) { this . state = State . CLOSING ; lock . notifyAll ( ) ; return true ; } } return false ; }
Signal that we are about to close the channel . This will not have any affect on the underlying channel however prevent setting a new channel .
55
28
145,405
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 ; } }
Set the channel . This will return whether the channel could be set successfully or not .
140
17
145,406
private boolean isRedeployAfterRemoval ( ModelNode operation ) { return operation . hasDefined ( DEPLOYMENT_OVERLAY_LINK_REMOVAL ) && operation . get ( DEPLOYMENT_OVERLAY_LINK_REMOVAL ) . asBoolean ( ) ; }
Check if this is a redeployment triggered after the removal of a link .
67
16
145,407
protected void createNewFile ( final File file ) { try { file . createNewFile ( ) ; setFileNotWorldReadablePermissions ( file ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
This creates a new audit log file with default permissions .
51
11
145,408
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 ) ; }
This procedure sets permissions to the given file to not allow everybody to read it .
71
16
145,409
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 ) ; } }
Lookup Seam integration resource loader .
389
8
145,410
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 ; } }
Creates a PathAddress from the given ModelNode address . The given node is expected to be an address node .
378
23
145,411
public PathElement getElement ( int index ) { final List < PathElement > list = pathAddressList ; return list . get ( index ) ; }
Gets the element at the given index .
31
9
145,412
public PathElement getLastElement ( ) { final List < PathElement > list = pathAddressList ; return list . size ( ) == 0 ? null : list . get ( list . size ( ) - 1 ) ; }
Gets the last element in the address .
46
9
145,413
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 ) ; }
Create a new path address by appending more elements to the end of this address .
81
17
145,414
@ 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 ; }
Navigate to this address in the given model node .
149
11
145,415
@ 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 ; }
Navigate to and remove this address in the given model node .
134
13
145,416
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 ; }
Convert this path address to its model node representation .
108
11
145,417
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 ; }
Check if this path matches the address path . An address matches this address if its path elements match or are valid multi targets for this path elements . Addresses that are equal are matching .
192
37
145,418
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 ) ; } }
Creates and attaches the annotation index to a resource root if it has not already been attached
696
18
145,419
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 ) ; } }
Validate the consistency of patches to the point we rollback .
85
13
145,420
public static void mark ( DeploymentUnit unit ) { unit = DeploymentUtils . getTopDeploymentUnit ( unit ) ; unit . putAttachment ( MARKER , Boolean . TRUE ) ; }
Mark the top level deployment as being a JPA deployment . If the deployment is not a top level deployment the parent is marked instead
42
26
145,421
@ 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 ; }
Clean obsolete contents from the content repository . It will first mark contents as obsolete then after some time if these contents are still obsolete they will be removed .
266
30
145,422
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 ; }
Mark content as obsolete . If content was already marked for obsolescenceTimeout ms then it is removed .
146
21
145,423
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 ; }
Used to read the domain model when a slave host connects to the DC
132
14
145,424
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 ; }
Describe the model as a list of resources with their address and model which the HC can directly apply to create the model . Although the format might appear similar as the operations generated at boot - time this description is only useful to create the resource tree and cannot be used to invoke any operation .
62
58
145,425
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 ; }
Process the host info and determine which configuration elements are required on the slave host .
97
16
145,426
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 ) ; } }
Determine the relevant pieces of configuration which need to be included when processing the domain model .
370
19
145,427
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 ; } } ; }
Create the ResourceIgnoredTransformationRegistry when fetching missing content only including relevant pieces to a server - config .
340
24
145,428
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 ; }
Used by the slave host when creating the host info dmr sent across to the DC during the registration process
88
21
145,429
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 ; }
For the DC to check whether an operation should be ignored on the slave if the slave is set up to ignore config not relevant to it
66
27
145,430
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 ; }
For use on a slave HC to get all the server groups used by the host
80
16
145,431
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 ; }
Determine whether all references are available locally .
569
10
145,432
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 ) ; } }
Execute a CLI command . This can be any command that you might execute on the CLI command line including both server - side operations and local commands such as cd or cn .
263
36
145,433
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 ( ) ; }
Boot the controller . Called during service start .
77
9
145,434
protected boolean boot ( List < ModelNode > bootOperations , boolean rollbackOnRuntimeFailure ) throws ConfigurationPersistenceException { return boot ( bootOperations , rollbackOnRuntimeFailure , false , ModelControllerImpl . getMutableRootResourceRegistrationProvider ( ) ) ; }
Boot with the given operations performing full model and capability registry validation .
57
13
145,435
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 ) ; } } } ) ; }
Get a message bundle of the given type .
537
9
145,436
public String getName ( ) { if ( name == null && securityIdentity != null ) { name = securityIdentity . getPrincipal ( ) . getName ( ) ; } return name ; }
Obtain the name of the caller most likely a user but could also be a remote process .
42
19
145,437
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 ; }
Obtain the realm used for authentication .
80
8
145,438
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 ; }
Resolve the subsystem versions .
163
6
145,439
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 ; } }
Apply the remote domain model to the local host controller .
540
11
145,440
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 ; } } }
Analyzes a failure thrown connecting to the master for causes that indicate some problem not likely to be resolved by immediately retrying . If found throws an exception highlighting the underlying cause . If the cause is not one of the ones understood by this method the method returns normally .
134
53
145,441
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 ( ) ; } }
Handles logging tasks related to a failure to connect to a remote HC .
112
15
145,442
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 ) ; } } ) ; }
Replace the last element of an address with a static path element .
76
14
145,443
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 ) ; }
Implement the persistence handler for storing the group properties .
50
11
145,444
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 ) ; } }
Implement the persistence handler for storing the user properties .
202
11
145,445
public static ServiceName deploymentUnitName ( String name , Phase phase ) { return JBOSS_DEPLOYMENT_UNIT . append ( name , phase . name ( ) ) ; }
Get the service name of a top - level deployment unit .
40
12
145,446
protected void updateModel ( final ModelNode operation , final Resource resource ) throws OperationFailedException { updateModel ( operation , resource . getModel ( ) ) ; }
Update the given resource in the persistent configuration model based on the values in the given operation .
34
18
145,447
public void logAttributeWarning ( PathAddress address , String attribute ) { logAttributeWarning ( address , null , null , attribute ) ; }
Log a warning for the resource at the provided address and a single attribute . The detail message is a default Attributes are not understood in the target model version and this resource will need to be ignored on the target host .
28
43
145,448
public void logAttributeWarning ( PathAddress address , Set < String > attributes ) { logAttributeWarning ( address , null , null , attributes ) ; }
Log a warning for the resource at the provided address and the given attributes . The detail message is a default Attributes are not understood in the target model version and this resource will need to be ignored on the target host .
31
43
145,449
public void logAttributeWarning ( PathAddress address , String message , String attribute ) { logAttributeWarning ( address , null , message , attribute ) ; }
Log warning for the resource at the provided address and single attribute using the provided detail message .
31
18
145,450
public void logAttributeWarning ( PathAddress address , String message , Set < String > attributes ) { messageQueue . add ( new AttributeLogEntry ( address , null , message , attributes ) ) ; }
Log a warning for the resource at the provided address and the given attributes using the provided detail message .
42
20
145,451
public void logAttributeWarning ( PathAddress address , ModelNode operation , String message , String attribute ) { messageQueue . add ( new AttributeLogEntry ( address , operation , message , attribute ) ) ; }
Log a warning for the given operation at the provided address for the given attribute using the provided detail message .
43
21
145,452
public void logAttributeWarning ( PathAddress address , ModelNode operation , String message , Set < String > attributes ) { messageQueue . add ( new AttributeLogEntry ( address , operation , message , attributes ) ) ; }
Log a warning for the given operation at the provided address for the given attributes using the provided detail message .
46
21
145,453
public void logWarning ( final String message ) { messageQueue . add ( new LogEntry ( ) { @ Override public String getMessage ( ) { return message ; } } ) ; }
Log a free - form warning
39
6
145,454
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 ) ; } }
flushes log queue this actually writes combined log message into system log
120
13
145,455
PatchEntry getEntry ( final String name , boolean addOn ) { return addOn ? addOns . get ( name ) : layers . get ( name ) ; }
Get a patch entry for either a layer or add - on .
35
13
145,456
protected void failedToCleanupDir ( final File file ) { checkForGarbageOnRestart = true ; PatchLogger . ROOT_LOGGER . cannotDeleteFile ( file . getAbsolutePath ( ) ) ; }
In case we cannot delete a directory create a marker to recheck whether we can garbage collect some not referenced directories and files .
48
26
145,457
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 ; }
Get the target entry for a given patch element .
207
10
145,458
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" ) ; } } } }
Complete the current operation and persist the current state to the disk . This will also trigger the invalidation of outdated modules .
609
24
145,459
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 ; }
Internally undo recorded changes we did so far .
490
10
145,460
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 ( ) ) ; } } }
Undo changes for a single patch entry .
198
9
145,461
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 ) ; }
Add a rollback loader for a give patch .
160
10
145,462
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 ) ; }
Record a content loader for a given patch id .
76
10
145,463
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 } }
Get the target file for misc items .
75
8
145,464
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 ) ; }
Create a patch representing what we actually processed . This may contain some fixed content hashes for removed modules .
201
20
145,465
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 ) ; }
Create a rollback patch based on the recorded actions .
329
11
145,466
static File getTargetFile ( final File root , final MiscContentItem item ) { return PatchContentLoader . getMiscPath ( root , item ) ; }
Get a misc file .
33
5
145,467
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 ) ; }
Create a patch element for the rollback patch .
116
10
145,468
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 ; }
Copy a patch element
105
4
145,469
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 ) ; } }
Backup the current configuration as part of the patch history .
194
12
145,470
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 ) ; } }
Backup all xml files in a given directory .
123
10
145,471
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 ) ; } }
Write the patch . xml
140
5
145,472
public CliCommandBuilder setController ( final String hostname , final int port ) { setController ( formatAddress ( null , hostname , port ) ) ; return this ; }
Sets the hostname and port to connect to .
37
11
145,473
public CliCommandBuilder setController ( final String protocol , final String hostname , final int port ) { setController ( formatAddress ( protocol , hostname , port ) ) ; return this ; }
Sets the protocol hostname and port to connect to .
41
12
145,474
public CliCommandBuilder setTimeout ( final int timeout ) { if ( timeout > 0 ) { addCliArgument ( CliArgument . TIMEOUT , Integer . toString ( timeout ) ) ; } else { addCliArgument ( CliArgument . TIMEOUT , null ) ; } return this ; }
Sets the timeout used when connecting to the server .
68
11
145,475
@ Deprecated public static < T > ServiceBuilder < T > addServerExecutorDependency ( ServiceBuilder < T > builder , Injector < ExecutorService > injector ) { return builder . addDependency ( ServerService . MANAGEMENT_EXECUTOR , ExecutorService . class , injector ) ; }
Creates dependency on management executor .
71
8
145,476
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 ( ) ; } } }
Receive a notification that the channel was closed .
80
10
145,477
@ 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 ( ) ; } }
Await the completion of all currently active operations .
179
10
145,478
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 ( ) ; } }
Register an active operation with a specific operation id .
353
10
145,479
protected < T , A > ActiveOperation < T , A > getActiveOperation ( final ManagementRequestHeader header ) { return getActiveOperation ( header . getBatchId ( ) ) ; }
Get an active operation .
40
5
145,480
protected < T , A > ActiveOperation < T , A > getActiveOperation ( final Integer id ) { //noinspection unchecked return ( ActiveOperation < T , A > ) activeRequests . get ( id ) ; }
Get the active operation .
47
5
145,481
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 ; }
Cancel all currently active operations .
81
7
145,482
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 ; }
Remove an active operation .
120
5
145,483
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 ) ; } } }
Safe write error response .
111
5
145,484
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 ) ; } }
Write an error response .
87
5
145,485
protected static FlushableDataOutput writeHeader ( final ManagementProtocolHeader header , final OutputStream os ) throws IOException { final FlushableDataOutput output = FlushableDataOutputImpl . create ( os ) ; header . write ( output ) ; return output ; }
Write the management protocol header .
57
6
145,486
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 ) ; } } } ; }
Get a fallback handler .
151
6
145,487
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 ( ) ; } }
Process a file .
183
4
145,488
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 ) ; } }
Update the central directory signature of a . jar .
391
10
145,489
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 ; } }
Validates that the data structure at position startEndRecord has a field in the expected position that points to the start of the first central directory file and if so that the file has a complete end of central directory record comment at the end .
540
48
145,490
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 ; }
Boyer Moore scan that proceeds backwards from the end of the file looking for endsig
603
17
145,491
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 ; }
Boyer Moore scan that proceeds forwards from the end of the file looking for the first LOCSIG
449
20
145,492
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 ; }
Checks that the data starting at startLocRecord looks like a local file record header .
232
18
145,493
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 ; } }
Fills the Boyer Moore bad character array for the given pattern
99
13
145,494
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 ( ) ) ; }
Create an embedded host controller .
179
6
145,495
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 ) ; } }
Add the dependencies if the deployment contains a service activator loader entry .
178
14
145,496
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 ( ) ; } } }
Pause the current entry point and invoke the provided listener when all current requests have finished .
105
17
145,497
public void resume ( ) { this . paused = false ; ServerActivityCallback listener = listenerUpdater . get ( this ) ; if ( listener != null ) { listenerUpdater . compareAndSet ( this , listener , null ) ; } }
Cancel the pause operation
52
5
145,498
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 ; }
Create the metadata which gets send to the DC when registering .
413
12
145,499
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 ( ) ) ; }
Adds a directory to the collection of module paths .
78
10