idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
22,000
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 .
22,001
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 .
22,002
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 .
22,003
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 .
22,004
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 .
22,005
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 ) ) { 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 .
22,006
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 ( ) ) ; } } 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
22,007
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 .
22,008
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
22,009
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 ( ) ) ) { if ( markAsObsolete ( fsContent ) ) { cleanedContents . get ( DELETED_CONTENT ) . add ( fsContent . getContentIdentifier ( ) ) ; } else { cleanedContents . get ( MARKED_CONTENT ) . add ( fsContent . getContentIdentifier ( ) ) ; } } else { obsoleteContents . remove ( fsContent . getHexHash ( ) ) ; } } } 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 .
22,010
private boolean markAsObsolete ( ContentReference ref ) { if ( obsoleteContents . containsKey ( ref . getHexHash ( ) ) ) { 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 ( ) ) ; } return false ; }
Mark content as obsolete . If content was already marked for obsolescenceTimeout ms then it is removed .
22,011
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
22,012
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 .
22,013
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 .
22,014
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 ) ; if ( ! serverGroups . contains ( groupName ) && root . hasChild ( groupElement ) ) { final Resource serverGroup = root . getChild ( groupElement ) ; final ModelNode groupModel = serverGroup . getModel ( ) ; serverGroups . add ( groupName ) ; 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 .
22,015
public static Transformers . ResourceIgnoredTransformationRegistry createServerIgnoredRegistry ( final RequiredConfigurationHolder rc , final Transformers . ResourceIgnoredTransformationRegistry delegate ) { return new Transformers . ResourceIgnoredTransformationRegistry ( ) { 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 : return false ; 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 .
22,016
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
22,017
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
22,018
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
22,019
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 ) ; } } for ( final Resource . ResourceEntry serverGroup : domain . getChildren ( SERVER_GROUP ) ) { if ( ! serverGroups . remove ( serverGroup . getName ( ) ) ) { return true ; } final ModelNode model = serverGroup . getModel ( ) ; final String profile = model . require ( PROFILE ) . asString ( ) ; processProfile ( domain , profile , profiles ) ; processSocketBindingGroup ( domain , model . require ( SOCKET_BINDING_GROUP ) . asString ( ) , socketBindings ) ; } if ( ! serverGroups . isEmpty ( ) ) { return true ; } for ( final Resource . ResourceEntry profile : domain . getChildren ( PROFILE ) ) { if ( ! profiles . remove ( profile . getName ( ) ) ) { return true ; } } if ( ! profiles . isEmpty ( ) ) { return true ; } for ( final Resource . ResourceEntry socketBindingGroup : domain . getChildren ( SOCKET_BINDING_GROUP ) ) { if ( ! socketBindings . remove ( socketBindingGroup . getName ( ) ) ) { return true ; } } if ( ! socketBindings . isEmpty ( ) ) { return true ; } return false ; }
Determine whether all references are available locally .
22,020
public Result cmd ( String cliCommand ) { try { 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 .
22,021
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 .
22,022
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 .
22,023
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 ) { } 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 ) { } 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 ) { } 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 .
22,024
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 .
22,025
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 .
22,026
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 .
22,027
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 ) ; 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 .
22,028
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 .
22,029
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 ) { HostControllerLogger . ROOT_LOGGER . noDiscoveryOptionsLeft ( ) ; } }
Handles logging tasks related to a failure to connect to a remote HC .
22,030
public static AliasOperationTransformer replaceLastElement ( final PathElement element ) { return create ( new AddressTransformer ( ) { 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 .
22,031
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 .
22,032
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 .
22,033
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 .
22,034
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 .
22,035
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 .
22,036
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 .
22,037
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 .
22,038
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 .
22,039
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 .
22,040
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 .
22,041
public void logWarning ( final String message ) { messageQueue . add ( new LogEntry ( ) { public String getMessage ( ) { return message ; } } ) ; }
Log a free - form warning
22,042
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
22,043
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 .
22,044
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 .
22,045
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 ) ; } entry . updateElement ( element ) ; return entry ; }
Get the target entry for a given patch element .
22,046
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 { if ( stateUpdater . compareAndSet ( this , State . PREPARED , State . INVALIDATE ) ) { if ( mode == PatchingTaskContext . Mode . APPLY ) { 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 .
22,047
boolean undoChanges ( ) { final State state = stateUpdater . getAndSet ( this , State . ROLLBACK_ONLY ) ; if ( state == State . COMPLETED || state == State . ROLLBACK_ONLY ) { return false ; } PatchingTaskContext . Mode currentMode = this . mode ; mode = PatchingTaskContext . Mode . UNDO ; final PatchContentLoader loader = PatchContentLoader . create ( miscBackup , null , null ) ; undoChanges ( identityEntry , loader ) ; if ( state == State . INVALIDATE || currentMode == PatchingTaskContext . Mode . ROLLBACK ) { 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 .
22,048
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 ) { 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 .
22,049
private void recordRollbackLoader ( final String patchId , PatchableTarget . TargetInfo target ) { 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 .
22,050
protected void recordContentLoader ( final String patchID , final PatchContentLoader contentLoader ) { if ( contentLoaders . containsKey ( patchID ) ) { throw new IllegalStateException ( "Content loader already registered for patch " + patchID ) ; } contentLoaders . put ( patchID , contentLoader ) ; }
Record a content loader for a given patch id .
22,051
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 ( ) ; } }
Get the target file for misc items .
22,052
protected Patch createProcessedPatch ( final Patch original ) { final List < PatchElement > elements = new ArrayList < PatchElement > ( ) ; for ( final PatchEntry entry : getLayers ( ) ) { final PatchElement element = createPatchElement ( entry , entry . element . getId ( ) , entry . modifications ) ; elements . add ( element ) ; } for ( final PatchEntry entry : getAddOns ( ) ) { final PatchElement element = createPatchElement ( entry , entry . element . getId ( ) , entry . modifications ) ; elements . add ( element ) ; } 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 .
22,053
protected RollbackPatch createRollbackPatch ( final String patchId , final Patch . PatchType patchType ) { final List < PatchElement > elements = new ArrayList < PatchElement > ( ) ; for ( final PatchEntry entry : getLayers ( ) ) { final PatchElement element = createRollbackElement ( entry ) ; elements . add ( element ) ; } 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 .
22,054
static File getTargetFile ( final File root , final MiscContentItem item ) { return PatchContentLoader . getMiscPath ( root , item ) ; }
Get a misc file .
22,055
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 .
22,056
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 ( ) ) ; element . getModifications ( ) . addAll ( modifications ) ; element . setDescription ( patchElement . getDescription ( ) ) ; return element ; }
Copy a patch element
22,057
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 .
22,058
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 .
22,059
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
22,060
public CliCommandBuilder setController ( final String hostname , final int port ) { setController ( formatAddress ( null , hostname , port ) ) ; return this ; }
Sets the hostname and port to connect to .
22,061
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 .
22,062
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 .
22,063
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 .
22,064
public void handleChannelClosed ( final Channel closed , final IOException e ) { for ( final ActiveOperationImpl < ? , ? > activeOperation : activeRequests . values ( ) ) { if ( activeOperation . getChannel ( ) == closed ) { activeOperation . getResultHandler ( ) . cancel ( ) ; } } }
Receive a notification that the channel was closed .
22,065
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 .
22,066
protected < T , A > ActiveOperation < T , A > registerActiveOperation ( final Integer id , A attachment , ActiveOperation . CompletedCallback < T > callback ) { lock . lock ( ) ; try { final Integer operationId ; if ( id == null ) { operationId = operationIdManager . createBatchId ( ) ; } else { 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 ++ ; return request ; } finally { lock . unlock ( ) ; } }
Register an active operation with a specific operation id .
22,067
protected < T , A > ActiveOperation < T , A > getActiveOperation ( final ManagementRequestHeader header ) { return getActiveOperation ( header . getBatchId ( ) ) ; }
Get an active operation .
22,068
protected < T , A > ActiveOperation < T , A > getActiveOperation ( final Integer id ) { return ( ActiveOperation < T , A > ) activeRequests . get ( id ) ; }
Get the active operation .
22,069
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 .
22,070
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 .
22,071
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 .
22,072
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 .
22,073
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 .
22,074
protected static < T , A > ManagementRequestHandler < T , A > getFallbackHandler ( final ManagementRequestHeader header ) { return new ManagementRequestHandler < T , A > ( ) { 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 .
22,075
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 .
22,076
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 ) { PatchLogger . ROOT_LOGGER . cannotInvalidateZip ( file . getAbsolutePath ( ) ) ; } return ; } 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 .
22,077
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 ) { return false ; } else if ( getUnsignedInt ( endDirHeader , 0 ) != endSig ) { return false ; } long pos = getUnsignedInt ( endDirHeader , END_CENSTART ) ; 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 ) { if ( ! validateLocalFileRecord ( channel , 0 , firstSize ) ) { return false ; } } else { long fileFirstLoc = scanForLocSig ( channel ) ; if ( firstLoc != fileFirstLoc ) { if ( fileFirstLoc == 0 ) { return false ; } else { return false ; } } } int commentLen = getUnsignedShort ( endDirHeader , END_COMMENTLEN ) ; long commentEnd = startEndRecord + ENDLEN + commentLen ; return commentEnd <= channel . size ( ) ; } return false ; } catch ( EOFException eof ) { 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 .
22,078
private static long scanForEndSig ( final File file , final FileChannel channel , final ScanContext context ) throws IOException { 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 ) { int patternPos ; for ( patternPos = SIG_PATTERN_LENGTH - 1 ; patternPos >= 0 && context . matches ( patternPos , bb . get ( bufferPos - patternPos ) ) ; -- patternPos ) { } switch ( patternPos ) { case - 1 : { final State state = context . state ; long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1 ; if ( validateEndRecord ( file , channel , startEndRecord , context . getSig ( ) ) ) { if ( state == State . FOUND ) { return startEndRecord ; } else { return - 1 ; } } bufferPos -= 4 ; break ; } case 3 : { int idx = bb . get ( bufferPos - patternPos ) - Byte . MIN_VALUE ; bufferPos -= BAD_BYTE_SKIP [ idx ] ; break ; } default : bufferPos -= 4 ; } } 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
22,079
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 ) { int patternPos ; for ( patternPos = SIG_PATTERN_LENGTH - 1 ; patternPos >= 0 && LOCSIG_PATTERN [ patternPos ] == bb . get ( bufferPos + patternPos ) ; -- patternPos ) { } switch ( patternPos ) { case - 1 : { long startLocRecord = channel . position ( ) - bb . limit ( ) + bufferPos ; long currentPos = channel . position ( ) ; if ( validateLocalFileRecord ( channel , startLocRecord , - 1 ) ) { return startLocRecord ; } channel . position ( currentPos ) ; bufferPos += 4 ; break ; } case 3 : { int idx = bb . get ( bufferPos + patternPos ) - Byte . MIN_VALUE ; bufferPos += LOC_BAD_BYTE_SKIP [ idx ] ; break ; } default : bufferPos += 4 ; } } } return - 1 ; }
Boyer Moore scan that proceeds forwards from the end of the file looking for the first LOCSIG
22,080
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 ) { 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 .
22,081
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
22,082
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 .
22,083
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 .
22,084
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 .
22,085
public void resume ( ) { this . paused = false ; ServerActivityCallback listener = listenerUpdater . get ( this ) ; if ( listener != null ) { listenerUpdater . compareAndSet ( this , listener , null ) ; } }
Cancel the pause operation
22,086
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 .
22,087
public void addModuleDir ( final String moduleDir ) { if ( moduleDir == null ) { throw LauncherMessages . MESSAGES . nullParam ( "moduleDir" ) ; } final Path path = Paths . get ( moduleDir ) . normalize ( ) ; modulesDirs . add ( path . toString ( ) ) ; }
Adds a directory to the collection of module paths .
22,088
public String getModulePaths ( ) { final StringBuilder result = new StringBuilder ( ) ; if ( addDefaultModuleDir ) { result . append ( wildflyHome . resolve ( "modules" ) . toString ( ) ) ; } if ( ! modulesDirs . isEmpty ( ) ) { if ( addDefaultModuleDir ) result . append ( File . pathSeparator ) ; for ( Iterator < String > iterator = modulesDirs . iterator ( ) ; iterator . hasNext ( ) ; ) { result . append ( iterator . next ( ) ) ; if ( iterator . hasNext ( ) ) { result . append ( File . pathSeparator ) ; } } } return result . toString ( ) ; }
Returns the modules paths used on the command line .
22,089
public static ModelControllerClient createAndAdd ( final ManagementChannelHandler handler ) { final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient ( handler ) ; handler . addHandlerFactory ( client ) ; return client ; }
Create and add model controller handler to an existing management channel handler .
22,090
public static ModelControllerClient createReceiving ( final Channel channel , final ExecutorService executorService ) { final ManagementClientChannelStrategy strategy = ManagementClientChannelStrategy . create ( channel ) ; final ManagementChannelHandler handler = new ManagementChannelHandler ( strategy , executorService ) ; final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient ( handler ) ; handler . addHandlerFactory ( client ) ; channel . addCloseHandler ( new CloseHandler < Channel > ( ) { public void handleClose ( Channel closed , IOException exception ) { handler . shutdown ( ) ; try { handler . awaitCompletion ( 1 , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } finally { handler . shutdownNow ( ) ; } } } ) ; channel . receiveMessage ( handler . getReceiver ( ) ) ; return client ; }
Create a model controller client which is exclusively receiving messages on an existing channel .
22,091
protected void addLineContent ( BufferedReader bufferedFileReader , List < String > content , String line ) throws IOException { if ( line . startsWith ( COMMENT_PREFIX ) && line . length ( ) == 1 ) { String nextLine = bufferedFileReader . readLine ( ) ; if ( nextLine != null ) { if ( nextLine . startsWith ( COMMENT_PREFIX ) && nextLine . contains ( REALM_COMMENT_PREFIX ) ) { bufferedFileReader . readLine ( ) ; } else { content . add ( line ) ; content . add ( nextLine ) ; } } else { super . addLineContent ( bufferedFileReader , content , line ) ; } } else { super . addLineContent ( bufferedFileReader , content , line ) ; } }
Remove the realm name block .
22,092
public void validateOperation ( final ModelNode operation ) throws OperationFailedException { if ( operation . hasDefined ( ModelDescriptionConstants . OPERATION_NAME ) && deprecationData != null && deprecationData . isNotificationUseful ( ) ) { ControllerLogger . DEPRECATED_LOGGER . operationDeprecated ( getName ( ) , PathAddress . pathAddress ( operation . get ( ModelDescriptionConstants . OP_ADDR ) ) . toCLIStyleString ( ) ) ; } for ( AttributeDefinition ad : this . parameters ) { ad . validateOperation ( operation ) ; } }
Validates operation model against the definition and its parameters
22,093
@ SuppressWarnings ( "deprecation" ) public final void validateAndSet ( ModelNode operationObject , final ModelNode model ) throws OperationFailedException { validateOperation ( operationObject ) ; for ( AttributeDefinition ad : this . parameters ) { ad . validateAndSet ( operationObject , model ) ; } }
validates operation against the definition and sets model for the parameters passed .
22,094
< P extends PatchingArtifact . ArtifactState , S extends PatchingArtifact . ArtifactState > PatchingArtifactStateHandler < S > getHandlerForArtifact ( PatchingArtifact < P , S > artifact ) { return handlers . get ( artifact ) ; }
Get a state handler for a given patching artifact .
22,095
public < V > V getAttachment ( final AttachmentKey < V > key ) { assert key != null ; return key . cast ( contextAttachments . get ( key ) ) ; }
Retrieves an object that has been attached to this context .
22,096
public < V > V attach ( final AttachmentKey < V > key , final V value ) { assert key != null ; return key . cast ( contextAttachments . put ( key , value ) ) ; }
Attaches an arbitrary object to this context .
22,097
public < V > V attachIfAbsent ( final AttachmentKey < V > key , final V value ) { assert key != null ; return key . cast ( contextAttachments . putIfAbsent ( key , value ) ) ; }
Attaches an arbitrary object to this context only if the object was not already attached . If a value has already been attached with the key provided the current value associated with the key is returned .
22,098
public < V > V detach ( final AttachmentKey < V > key ) { assert key != null ; return key . cast ( contextAttachments . remove ( key ) ) ; }
Detaches or removes the value from this context .
22,099
private void writeInterfaceCriteria ( final XMLExtendedStreamWriter writer , final ModelNode subModel , final boolean nested ) throws XMLStreamException { for ( final Property property : subModel . asPropertyList ( ) ) { if ( property . getValue ( ) . isDefined ( ) ) { writeInterfaceCriteria ( writer , property , nested ) ; } } }
Write the criteria elements extracting the information of the sub - model .