idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
145,700
public T addBundle ( final String moduleName , final String slot , final byte [ ] newHash ) { final ContentItem item = createBundleItem ( moduleName , slot , newHash ) ; addContentModification ( createContentModification ( item , ModificationType . ADD , NO_CONTENT ) ) ; return returnThis ( ) ; }
Add a bundle .
74
4
145,701
public T modifyBundle ( final String moduleName , final String slot , final byte [ ] existingHash , final byte [ ] newHash ) { final ContentItem item = createBundleItem ( moduleName , slot , newHash ) ; addContentModification ( createContentModification ( item , ModificationType . MODIFY , existingHash ) ) ; return returnThis ( ) ; }
Modify a bundle .
81
5
145,702
public T removeBundle ( final String moduleName , final String slot , final byte [ ] existingHash ) { final ContentItem item = createBundleItem ( moduleName , slot , NO_CONTENT ) ; addContentModification ( createContentModification ( item , ModificationType . REMOVE , existingHash ) ) ; return returnThis ( ) ; }
Remove a bundle .
76
4
145,703
public T addFile ( final String name , final List < String > path , final byte [ ] newHash , final boolean isDirectory ) { return addFile ( name , path , newHash , isDirectory , null ) ; }
Add a misc file .
47
5
145,704
public T modifyFile ( final String name , final List < String > path , final byte [ ] existingHash , final byte [ ] newHash , final boolean isDirectory ) { return modifyFile ( name , path , existingHash , newHash , isDirectory , null ) ; }
Modify a misc file .
57
6
145,705
public T removeFile ( final String name , final List < String > path , final byte [ ] existingHash , final boolean isDirectory ) { return removeFile ( name , path , existingHash , isDirectory , null ) ; }
Remove a misc file .
47
5
145,706
public T addModule ( final String moduleName , final String slot , final byte [ ] newHash ) { final ContentItem item = createModuleItem ( moduleName , slot , newHash ) ; addContentModification ( createContentModification ( item , ModificationType . ADD , NO_CONTENT ) ) ; return returnThis ( ) ; }
Add a module .
72
4
145,707
public T modifyModule ( final String moduleName , final String slot , final byte [ ] existingHash , final byte [ ] newHash ) { final ContentItem item = createModuleItem ( moduleName , slot , newHash ) ; addContentModification ( createContentModification ( item , ModificationType . MODIFY , existingHash ) ) ; return returnThis ( ) ; }
Modify a module .
79
5
145,708
public T removeModule ( final String moduleName , final String slot , final byte [ ] existingHash ) { final ContentItem item = createModuleItem ( moduleName , slot , NO_CONTENT ) ; addContentModification ( createContentModification ( item , ModificationType . REMOVE , existingHash ) ) ; return returnThis ( ) ; }
Remove a module .
74
4
145,709
private static String getLogManagerLoggerName ( final String name ) { return ( name . equals ( RESOURCE_NAME ) ? CommonAttributes . ROOT_LOGGER_NAME : name ) ; }
Returns the logger name that should be used in the log manager .
42
13
145,710
public static XMLStreamException unexpectedEndElement ( final XMLExtendedStreamReader reader ) { return ControllerLogger . ROOT_LOGGER . unexpectedEndElement ( reader . getName ( ) , reader . getLocation ( ) ) ; }
Get an exception reporting an unexpected end tag for an XML element .
51
13
145,711
public static XMLStreamException missingRequiredElement ( final XMLExtendedStreamReader reader , final Set < ? > required ) { final StringBuilder b = new StringBuilder ( ) ; Iterator < ? > iterator = required . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Object o = iterator . next ( ) ; b . append ( o . toString ( ) ) ; if ( iterator . hasNext ( ) ) { b . append ( ", " ) ; } } final XMLStreamException ex = ControllerLogger . ROOT_LOGGER . missingRequiredElements ( b , reader . getLocation ( ) ) ; Set < String > set = new HashSet <> ( ) ; for ( Object o : required ) { String toString = o . toString ( ) ; set . add ( toString ) ; } return new XMLStreamValidationException ( ex . getMessage ( ) , ValidationError . from ( ex , ErrorType . REQUIRED_ELEMENTS_MISSING ) . element ( reader . getName ( ) ) . alternatives ( set ) , ex ) ; }
Get an exception reporting a missing required XML child element .
234
11
145,712
public static void requireNamespace ( final XMLExtendedStreamReader reader , final Namespace requiredNs ) throws XMLStreamException { Namespace actualNs = Namespace . forUri ( reader . getNamespaceURI ( ) ) ; if ( actualNs != requiredNs ) { throw unexpectedElement ( reader ) ; } }
Require that the namespace of the current element matches the required namespace .
68
14
145,713
public static boolean readBooleanAttributeElement ( final XMLExtendedStreamReader reader , final String attributeName ) throws XMLStreamException { requireSingleAttribute ( reader , attributeName ) ; final boolean value = Boolean . parseBoolean ( reader . getAttributeValue ( 0 ) ) ; requireNoContent ( reader ) ; return value ; }
Read an element which contains only a single boolean attribute .
70
11
145,714
@ SuppressWarnings ( { "unchecked" , "WeakerAccess" } ) public static < T > List < T > readListAttributeElement ( final XMLExtendedStreamReader reader , final String attributeName , final Class < T > type ) throws XMLStreamException { requireSingleAttribute ( reader , attributeName ) ; // todo: fix this when this method signature is corrected final List < T > value = ( List < T > ) reader . getListAttributeValue ( 0 , type ) ; requireNoContent ( reader ) ; return value ; }
Read an element which contains only a single list attribute of a given type .
119
15
145,715
@ SuppressWarnings ( { "unchecked" } ) public static < T > T [ ] readArrayAttributeElement ( final XMLExtendedStreamReader reader , final String attributeName , final Class < T > type ) throws XMLStreamException { final List < T > list = readListAttributeElement ( reader , attributeName , type ) ; return list . toArray ( ( T [ ] ) Array . newInstance ( type , list . size ( ) ) ) ; }
Read an element which contains only a single list attribute of a given type returning it as an array .
101
20
145,716
@ Override public ModelNode resolveValue ( ExpressionResolver resolver , ModelNode value ) throws OperationFailedException { // Pass non-OBJECT values through the superclass so it can reject weird values and, in the odd chance // that's how this object is set up, turn undefined into a default list value. ModelNode superResult = value . getType ( ) == ModelType . OBJECT ? value : super . resolveValue ( resolver , value ) ; // If it's not an OBJECT (almost certainly UNDEFINED), then nothing more we can do if ( superResult . getType ( ) != ModelType . OBJECT ) { return superResult ; } // Resolve each field. // Don't mess with the original value ModelNode clone = superResult == value ? value . clone ( ) : superResult ; ModelNode result = new ModelNode ( ) ; for ( AttributeDefinition field : valueTypes ) { String fieldName = field . getName ( ) ; if ( clone . has ( fieldName ) ) { result . get ( fieldName ) . set ( field . resolveValue ( resolver , clone . get ( fieldName ) ) ) ; } else { // Input doesn't have a child for this field. // Don't create one in the output unless the AD produces a default value. // TBH this doesn't make a ton of sense, since any object should have // all of its fields, just some may be undefined. But doing it this // way may avoid breaking some code that is incorrectly checking node.has("xxx") // instead of node.hasDefined("xxx") ModelNode val = field . resolveValue ( resolver , new ModelNode ( ) ) ; if ( val . isDefined ( ) ) { result . get ( fieldName ) . set ( val ) ; } } } // Validate the entire object getValidator ( ) . validateParameter ( getName ( ) , result ) ; return result ; }
Overrides the superclass implementation to allow the AttributeDefinition for each field in the object to in turn resolve that field .
408
26
145,717
public static void handleDomainOperationResponseStreams ( final OperationContext context , final ModelNode responseNode , final List < OperationResponse . StreamEntry > streams ) { if ( responseNode . hasDefined ( RESPONSE_HEADERS ) ) { ModelNode responseHeaders = responseNode . get ( RESPONSE_HEADERS ) ; // Strip out any stream header as the header created by this process is what counts responseHeaders . remove ( ATTACHED_STREAMS ) ; if ( responseHeaders . asInt ( ) == 0 ) { responseNode . remove ( RESPONSE_HEADERS ) ; } } for ( OperationResponse . StreamEntry streamEntry : streams ) { context . attachResultStream ( streamEntry . getUUID ( ) , streamEntry . getMimeType ( ) , streamEntry . getStream ( ) ) ; } }
Deal with streams attached to an operation response from a proxied domain process .
179
15
145,718
public final synchronized void shutdown ( ) { // synchronize on 'this' to avoid races with registerStreams stopped = true ; // If the cleanup task is running tell it to stop looping, and then remove it from the scheduled executor if ( cleanupTaskFuture != null ) { cleanupTaskFuture . cancel ( false ) ; } // Close remaining streams for ( Map . Entry < InputStreamKey , TimedStreamEntry > entry : streamMap . entrySet ( ) ) { InputStreamKey key = entry . getKey ( ) ; TimedStreamEntry timedStreamEntry = entry . getValue ( ) ; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized ( timedStreamEntry ) { // ensure there's no race with a request that got a ref before we removed it closeStreamEntry ( timedStreamEntry , key . requestId , key . index ) ; } } }
Closes any registered stream entries that have not yet been consumed
183
12
145,719
void gc ( ) { if ( stopped ) { return ; } long expirationTime = System . currentTimeMillis ( ) - timeout ; for ( Iterator < Map . Entry < InputStreamKey , TimedStreamEntry > > iter = streamMap . entrySet ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { if ( stopped ) { return ; } Map . Entry < InputStreamKey , TimedStreamEntry > entry = iter . next ( ) ; TimedStreamEntry timedStreamEntry = entry . getValue ( ) ; if ( timedStreamEntry . timestamp . get ( ) <= expirationTime ) { iter . remove ( ) ; InputStreamKey key = entry . getKey ( ) ; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized ( timedStreamEntry ) { // ensure there's no race with a request that got a ref before we removed it closeStreamEntry ( timedStreamEntry , key . requestId , key . index ) ; } } } }
Close and remove expired streams . Package protected to allow unit tests to invoke it .
208
16
145,720
private List < PermissionFactory > retrievePermissionSet ( final OperationContext context , final ModelNode node ) throws OperationFailedException { final List < PermissionFactory > permissions = new ArrayList <> ( ) ; if ( node != null && node . isDefined ( ) ) { for ( ModelNode permissionNode : node . asList ( ) ) { String permissionClass = CLASS . resolveModelAttribute ( context , permissionNode ) . asString ( ) ; String permissionName = null ; if ( permissionNode . hasDefined ( PERMISSION_NAME ) ) permissionName = NAME . resolveModelAttribute ( context , permissionNode ) . asString ( ) ; String permissionActions = null ; if ( permissionNode . hasDefined ( PERMISSION_ACTIONS ) ) permissionActions = ACTIONS . resolveModelAttribute ( context , permissionNode ) . asString ( ) ; String moduleName = null ; if ( permissionNode . hasDefined ( PERMISSION_MODULE ) ) { moduleName = MODULE . resolveModelAttribute ( context , permissionNode ) . asString ( ) ; } ClassLoader cl = WildFlySecurityManager . getClassLoaderPrivileged ( this . getClass ( ) ) ; if ( moduleName != null ) { try { cl = Module . getBootModuleLoader ( ) . loadModule ( ModuleIdentifier . fromString ( moduleName ) ) . getClassLoader ( ) ; } catch ( ModuleLoadException e ) { throw new OperationFailedException ( e ) ; } } permissions . add ( new LoadedPermissionFactory ( cl , permissionClass , permissionName , permissionActions ) ) ; } } return permissions ; }
This method retrieves all security permissions contained within the specified node .
344
13
145,721
public static ServiceController < DeploymentScanner > addService ( final OperationContext context , final PathAddress resourceAddress , final String relativeTo , final String path , final int scanInterval , TimeUnit unit , final boolean autoDeployZip , final boolean autoDeployExploded , final boolean autoDeployXml , final boolean scanEnabled , final long deploymentTimeout , boolean rollbackOnRuntimeFailure , final FileSystemDeploymentService bootTimeService , final ScheduledExecutorService scheduledExecutorService ) { final DeploymentScannerService service = new DeploymentScannerService ( resourceAddress , relativeTo , path , scanInterval , unit , autoDeployZip , autoDeployExploded , autoDeployXml , scanEnabled , deploymentTimeout , rollbackOnRuntimeFailure , bootTimeService ) ; final ServiceName serviceName = getServiceName ( resourceAddress . getLastElement ( ) . getValue ( ) ) ; service . scheduledExecutorValue . inject ( scheduledExecutorService ) ; final ServiceBuilder < DeploymentScanner > sb = context . getServiceTarget ( ) . addService ( serviceName , service ) ; sb . addDependency ( context . getCapabilityServiceName ( PATH_MANAGER_CAPABILITY , PathManager . class ) , PathManager . class , service . pathManagerValue ) ; sb . addDependency ( context . getCapabilityServiceName ( "org.wildfly.management.notification-handler-registry" , null ) , NotificationHandlerRegistry . class , service . notificationRegistryValue ) ; sb . addDependency ( context . getCapabilityServiceName ( "org.wildfly.management.model-controller-client-factory" , null ) , ModelControllerClientFactory . class , service . clientFactoryValue ) ; sb . requires ( org . jboss . as . server . deployment . Services . JBOSS_DEPLOYMENT_CHAINS ) ; sb . addDependency ( ControlledProcessStateService . SERVICE_NAME , ControlledProcessStateService . class , service . controlledProcessStateServiceValue ) ; return sb . install ( ) ; }
Add the deployment scanner service to a batch .
450
9
145,722
public ManagementModelNode findNode ( String address ) { ManagementModelNode root = ( ManagementModelNode ) tree . getModel ( ) . getRoot ( ) ; Enumeration < javax . swing . tree . TreeNode > allNodes = root . depthFirstEnumeration ( ) ; while ( allNodes . hasMoreElements ( ) ) { ManagementModelNode node = ( ManagementModelNode ) allNodes . nextElement ( ) ; if ( node . addressPath ( ) . equals ( address ) ) return node ; } return null ; }
Find a node in the tree . The node must be visible to be found .
117
16
145,723
public ManagementModelNode getSelectedNode ( ) { if ( tree . getSelectionPath ( ) == null ) return null ; return ( ManagementModelNode ) tree . getSelectionPath ( ) . getLastPathComponent ( ) ; }
Get the node that has been selected by the user or null if nothing is selected .
50
17
145,724
public static Connection connectSync ( final ProtocolConnectionConfiguration configuration ) throws IOException { long timeoutMillis = configuration . getConnectionTimeout ( ) ; CallbackHandler handler = configuration . getCallbackHandler ( ) ; final CallbackHandler actualHandler ; ProtocolTimeoutHandler timeoutHandler = configuration . getTimeoutHandler ( ) ; // Note: If a client supplies a ProtocolTimeoutHandler it is taking on full responsibility for timeout management. if ( timeoutHandler == null ) { GeneralTimeoutHandler defaultTimeoutHandler = new GeneralTimeoutHandler ( ) ; // No point wrapping our AnonymousCallbackHandler. actualHandler = handler != null ? new WrapperCallbackHandler ( defaultTimeoutHandler , handler ) : null ; timeoutHandler = defaultTimeoutHandler ; } else { actualHandler = handler ; } final IoFuture < Connection > future = connect ( actualHandler , configuration ) ; IoFuture . Status status = timeoutHandler . await ( future , timeoutMillis ) ; if ( status == IoFuture . Status . DONE ) { return future . get ( ) ; } if ( status == IoFuture . Status . FAILED ) { throw ProtocolLogger . ROOT_LOGGER . failedToConnect ( configuration . getUri ( ) , future . getException ( ) ) ; } throw ProtocolLogger . ROOT_LOGGER . couldNotConnect ( configuration . getUri ( ) ) ; }
Connect sync .
279
3
145,725
public void openBlockingInterruptable ( ) throws InterruptedException { // We need to thread this call in order to interrupt it (when Ctrl-C occurs). connectionThread = new Thread ( ( ) -> { // This thread can't be interrupted from another thread. // Will stay alive until System.exit is called. Thread thr = new Thread ( ( ) -> super . openBlocking ( ) , "CLI Terminal Connection (uninterruptable)" ) ; thr . start ( ) ; try { thr . join ( ) ; } catch ( InterruptedException ex ) { // XXX OK, interrupted, just leaving. } } , "CLI Terminal Connection (interruptable)" ) ; connectionThread . start ( ) ; connectionThread . join ( ) ; }
Required to close the connection reading on the terminal otherwise it can t be interrupted .
158
16
145,726
protected static void validateSignature ( final DataInput input ) throws IOException { final byte [ ] signatureBytes = new byte [ 4 ] ; input . readFully ( signatureBytes ) ; if ( ! Arrays . equals ( ManagementProtocol . SIGNATURE , signatureBytes ) ) { throw ProtocolLogger . ROOT_LOGGER . invalidSignature ( Arrays . toString ( signatureBytes ) ) ; } }
Validate the header signature .
87
6
145,727
public static ManagementProtocolHeader parse ( DataInput input ) throws IOException { validateSignature ( input ) ; expectHeader ( input , ManagementProtocol . VERSION_FIELD ) ; int version = input . readInt ( ) ; expectHeader ( input , ManagementProtocol . TYPE ) ; byte type = input . readByte ( ) ; switch ( type ) { case ManagementProtocol . TYPE_REQUEST : return new ManagementRequestHeader ( version , input ) ; case ManagementProtocol . TYPE_RESPONSE : return new ManagementResponseHeader ( version , input ) ; case ManagementProtocol . TYPE_BYE_BYE : return new ManagementByeByeHeader ( version ) ; case ManagementProtocol . TYPE_PING : return new ManagementPingHeader ( version ) ; case ManagementProtocol . TYPE_PONG : return new ManagementPongHeader ( version ) ; default : throw ProtocolLogger . ROOT_LOGGER . invalidType ( "0x" + Integer . toHexString ( type ) ) ; } }
Parses the input stream to read the header
217
10
145,728
protected void checkConsecutiveAlpha ( ) { Pattern symbolsPatter = Pattern . compile ( REGEX_ALPHA_UC + "+" ) ; Matcher matcher = symbolsPatter . matcher ( this . password ) ; int met = 0 ; while ( matcher . find ( ) ) { int start = matcher . start ( ) ; int end = matcher . end ( ) ; if ( start == end ) { continue ; } int diff = end - start ; if ( diff >= 3 ) { met += diff ; } } this . result . negative ( met * CONSECUTIVE_ALPHA_WEIGHT ) ; // alpha lower case symbolsPatter = Pattern . compile ( REGEX_ALPHA_LC + "+" ) ; matcher = symbolsPatter . matcher ( this . password ) ; met = 0 ; while ( matcher . find ( ) ) { int start = matcher . start ( ) ; int end = matcher . end ( ) ; if ( start == end ) { continue ; } int diff = end - start ; if ( diff >= 3 ) { met += diff ; } } this . result . negative ( met * CONSECUTIVE_ALPHA_WEIGHT ) ; }
those could be incorporated with above but that would blurry everything .
261
12
145,729
public static ModelNode createBootUpdates ( final String serverName , final ModelNode domainModel , final ModelNode hostModel , final DomainController domainController , final ExpressionResolver expressionResolver ) { final ManagedServerOperationsFactory factory = new ManagedServerOperationsFactory ( serverName , domainModel , hostModel , domainController , expressionResolver ) ; return factory . getBootUpdates ( ) ; }
Create a list of operations required to a boot a managed server .
86
13
145,730
private synchronized HostServerGroupEffect getMappableDomainEffect ( PathAddress address , String key , Map < String , Set < String > > map , Resource root ) { if ( requiresMapping ) { map ( root ) ; requiresMapping = false ; } Set < String > mapped = map . get ( key ) ; return mapped != null ? HostServerGroupEffect . forDomain ( address , mapped ) : HostServerGroupEffect . forUnassignedDomain ( address ) ; }
Creates an appropriate HSGE for a domain - wide resource of a type that is mappable to server groups
100
23
145,731
private synchronized HostServerGroupEffect getHostEffect ( PathAddress address , String host , Resource root ) { if ( requiresMapping ) { map ( root ) ; requiresMapping = false ; } Set < String > mapped = hostsToGroups . get ( host ) ; if ( mapped == null ) { // Unassigned host. Treat like an unassigned profile or socket-binding-group; // i.e. available to all server group scoped roles. // Except -- WFLY-2085 -- the master HC is not open to all s-g-s-rs Resource hostResource = root . getChild ( PathElement . pathElement ( HOST , host ) ) ; if ( hostResource != null ) { ModelNode dcModel = hostResource . getModel ( ) . get ( DOMAIN_CONTROLLER ) ; if ( ! dcModel . hasDefined ( REMOTE ) ) { mapped = Collections . emptySet ( ) ; // prevents returning HostServerGroupEffect.forUnassignedHost(address, host) } } } return mapped == null ? HostServerGroupEffect . forUnassignedHost ( address , host ) : HostServerGroupEffect . forMappedHost ( address , mapped , host ) ; }
Creates an appropriate HSGE for resources in the host tree excluding the server and server - config subtrees
261
21
145,732
private void map ( Resource root ) { for ( Resource . ResourceEntry serverGroup : root . getChildren ( SERVER_GROUP ) ) { String serverGroupName = serverGroup . getName ( ) ; ModelNode serverGroupModel = serverGroup . getModel ( ) ; String profile = serverGroupModel . require ( PROFILE ) . asString ( ) ; store ( serverGroupName , profile , profilesToGroups ) ; String socketBindingGroup = serverGroupModel . require ( SOCKET_BINDING_GROUP ) . asString ( ) ; store ( serverGroupName , socketBindingGroup , socketsToGroups ) ; for ( Resource . ResourceEntry deployment : serverGroup . getChildren ( DEPLOYMENT ) ) { store ( serverGroupName , deployment . getName ( ) , deploymentsToGroups ) ; } for ( Resource . ResourceEntry overlay : serverGroup . getChildren ( DEPLOYMENT_OVERLAY ) ) { store ( serverGroupName , overlay . getName ( ) , overlaysToGroups ) ; } } for ( Resource . ResourceEntry host : root . getChildren ( HOST ) ) { String hostName = host . getPathElement ( ) . getValue ( ) ; for ( Resource . ResourceEntry serverConfig : host . getChildren ( SERVER_CONFIG ) ) { ModelNode serverConfigModel = serverConfig . getModel ( ) ; String serverGroupName = serverConfigModel . require ( GROUP ) . asString ( ) ; store ( serverGroupName , hostName , hostsToGroups ) ; } } }
Only call with monitor for this held
329
7
145,733
@ Override public void registerAttributes ( ManagementResourceRegistration resourceRegistration ) { for ( AttributeAccess attr : attributes . values ( ) ) { resourceRegistration . registerReadOnlyAttribute ( attr . getAttributeDefinition ( ) , null ) ; } }
Register operations associated with this resource .
52
7
145,734
@ Override public void registerChildren ( ManagementResourceRegistration resourceRegistration ) { // Register wildcard children last to prevent duplicate registration errors when override definitions exist for ( ResourceDefinition rd : singletonChildren ) { resourceRegistration . registerSubModel ( rd ) ; } for ( ResourceDefinition rd : wildcardChildren ) { resourceRegistration . registerSubModel ( rd ) ; } }
Register child resources associated with this resource .
79
8
145,735
public static void installDomainConnectorServices ( final OperationContext context , final ServiceTarget serviceTarget , final ServiceName endpointName , final ServiceName networkInterfaceBinding , final int port , final OptionMap options , final ServiceName securityRealm , final ServiceName saslAuthenticationFactory , final ServiceName sslContext ) { String sbmCap = "org.wildfly.management.socket-binding-manager" ; ServiceName sbmName = context . hasOptionalCapability ( sbmCap , NATIVE_MANAGEMENT_RUNTIME_CAPABILITY . getName ( ) , null ) ? context . getCapabilityServiceName ( sbmCap , SocketBindingManager . class ) : null ; installConnectorServicesForNetworkInterfaceBinding ( serviceTarget , endpointName , MANAGEMENT_CONNECTOR , networkInterfaceBinding , port , options , securityRealm , saslAuthenticationFactory , sslContext , sbmName ) ; }
Installs a remoting stream server for a domain instance
202
11
145,736
public static void installManagementChannelServices ( final ServiceTarget serviceTarget , final ServiceName endpointName , final AbstractModelControllerOperationHandlerFactoryService operationHandlerService , final ServiceName modelControllerName , final String channelName , final ServiceName executorServiceName , final ServiceName scheduledExecutorServiceName ) { final OptionMap options = OptionMap . EMPTY ; final ServiceName operationHandlerName = endpointName . append ( channelName ) . append ( ModelControllerClientOperationHandlerFactoryService . OPERATION_HANDLER_NAME_SUFFIX ) ; serviceTarget . addService ( operationHandlerName , operationHandlerService ) . addDependency ( modelControllerName , ModelController . class , operationHandlerService . getModelControllerInjector ( ) ) . addDependency ( executorServiceName , ExecutorService . class , operationHandlerService . getExecutorInjector ( ) ) . addDependency ( scheduledExecutorServiceName , ScheduledExecutorService . class , operationHandlerService . getScheduledExecutorInjector ( ) ) . setInitialMode ( ACTIVE ) . install ( ) ; installManagementChannelOpenListenerService ( serviceTarget , endpointName , channelName , operationHandlerName , options , false ) ; }
Set up the services to create a channel listener and operation handler service .
260
14
145,737
public static void isManagementResourceRemoveable ( OperationContext context , PathAddress otherManagementEndpoint ) throws OperationFailedException { ModelNode remotingConnector ; try { remotingConnector = context . readResourceFromRoot ( PathAddress . pathAddress ( PathElement . pathElement ( SUBSYSTEM , "jmx" ) , PathElement . pathElement ( "remoting-connector" , "jmx" ) ) , false ) . getModel ( ) ; } catch ( Resource . NoSuchResourceException ex ) { return ; } if ( ! remotingConnector . hasDefined ( USE_MGMT_ENDPOINT ) || ( remotingConnector . hasDefined ( USE_MGMT_ENDPOINT ) && context . resolveExpressions ( remotingConnector . get ( USE_MGMT_ENDPOINT ) ) . asBoolean ( true ) ) ) { try { context . readResourceFromRoot ( otherManagementEndpoint , false ) ; } catch ( NoSuchElementException ex ) { throw RemotingLogger . ROOT_LOGGER . couldNotRemoveResource ( context . getCurrentAddress ( ) ) ; } } }
Manual check because introducing a capability can t be done without a full refactoring . This has to go as soon as the management interfaces are redesigned .
243
31
145,738
static void writeCertificates ( final ModelNode result , final Certificate [ ] certificates ) throws CertificateEncodingException , NoSuchAlgorithmException { if ( certificates != null ) { for ( Certificate current : certificates ) { ModelNode certificate = new ModelNode ( ) ; writeCertificate ( certificate , current ) ; result . add ( certificate ) ; } } }
Populate the supplied response with the model representation of the certificates .
74
13
145,739
private static MBeanServer setQueryExpServer ( QueryExp query , MBeanServer toSet ) { // We assume the QueryExp is a QueryEval subclass or uses the QueryEval thread local // mechanism to store any existing MBeanServer. If that's not the case we have no // way to access the old mbeanserver to let us restore it MBeanServer result = QueryEval . getMBeanServer ( ) ; query . setMBeanServer ( toSet ) ; return result ; }
Set the mbean server on the QueryExp and try and pass back any previously set one
111
18
145,740
PathAddress toPathAddress ( final ObjectName name ) { return ObjectNameAddressUtil . toPathAddress ( rootObjectInstance . getObjectName ( ) , getRootResourceAndRegistration ( ) . getRegistration ( ) , name ) ; }
Convert an ObjectName to a PathAddress .
50
10
145,741
public static TransactionalProtocolClient createClient ( final ManagementChannelHandler channelAssociation ) { final TransactionalProtocolClientImpl client = new TransactionalProtocolClientImpl ( channelAssociation ) ; channelAssociation . addHandlerFactory ( client ) ; return client ; }
Create a transactional protocol client .
59
7
145,742
public static TransactionalProtocolClient . Operation wrap ( final ModelNode operation , final OperationMessageHandler messageHandler , final OperationAttachments attachments ) { return new TransactionalOperationImpl ( operation , messageHandler , attachments ) ; }
Wrap an operation s parameters in a simple encapsulating object
48
12
145,743
public static TransactionalProtocolClient . PreparedOperation < TransactionalProtocolClient . Operation > executeBlocking ( final ModelNode operation , TransactionalProtocolClient client ) throws IOException , InterruptedException { final BlockingQueueOperationListener < TransactionalProtocolClient . Operation > listener = new BlockingQueueOperationListener <> ( ) ; client . execute ( listener , operation , OperationMessageHandler . DISCARD , OperationAttachments . EMPTY ) ; return listener . retrievePreparedOperation ( ) ; }
Execute blocking for a prepared result .
111
8
145,744
private void init ( ) { if ( initialized . compareAndSet ( false , true ) ) { final RowSorter < ? extends TableModel > rowSorter = table . getRowSorter ( ) ; rowSorter . toggleSortOrder ( 1 ) ; // sort by date rowSorter . toggleSortOrder ( 1 ) ; // descending final TableColumnModel columnModel = table . getColumnModel ( ) ; columnModel . getColumn ( 1 ) . setCellRenderer ( dateRenderer ) ; columnModel . getColumn ( 2 ) . setCellRenderer ( sizeRenderer ) ; } }
Initializes the model
130
4
145,745
public void execute ( ) throws IOException { try { prepare ( ) ; boolean commitResult = commit ( ) ; if ( commitResult == false ) { throw PatchLogger . ROOT_LOGGER . failedToDeleteBackup ( ) ; } } catch ( PrepareException pe ) { rollback ( ) ; throw PatchLogger . ROOT_LOGGER . failedToDelete ( pe . getPath ( ) ) ; } }
remove files from directory . All - or - nothing operation - if any of the files fails to be removed all deleted files are restored .
89
27
145,746
public void rollback ( ) throws GitAPIException { try ( Git git = getGit ( ) ) { git . reset ( ) . setMode ( ResetCommand . ResetType . HARD ) . setRef ( HEAD ) . call ( ) ; } }
Reset hard on HEAD .
54
6
145,747
public void commit ( String msg ) throws GitAPIException { try ( Git git = getGit ( ) ) { Status status = git . status ( ) . call ( ) ; if ( ! status . isClean ( ) ) { git . commit ( ) . setMessage ( msg ) . setAll ( true ) . setNoVerify ( true ) . call ( ) ; } } }
Commit all changes if there are uncommitted changes .
81
11
145,748
static void initializeExtension ( ExtensionRegistry extensionRegistry , String module , ManagementResourceRegistration rootRegistration , ExtensionRegistryType extensionRegistryType ) { try { boolean unknownModule = false ; boolean initialized = false ; for ( Extension extension : Module . loadServiceFromCallerModuleLoader ( module , Extension . class ) ) { ClassLoader oldTccl = WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( extension . getClass ( ) ) ; try { if ( unknownModule || ! extensionRegistry . getExtensionModuleNames ( ) . contains ( module ) ) { // This extension wasn't handled by the standalone.xml or domain.xml parsing logic, so we // need to initialize its parsers so we can display what XML namespaces it supports extensionRegistry . initializeParsers ( extension , module , null ) ; // AS7-6190 - ensure we initialize parsers for other extensions from this module // now that we know the registry was unaware of the module unknownModule = true ; } extension . initialize ( extensionRegistry . getExtensionContext ( module , rootRegistration , extensionRegistryType ) ) ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( oldTccl ) ; } initialized = true ; } if ( ! initialized ) { throw ControllerLogger . ROOT_LOGGER . notFound ( "META-INF/services/" , Extension . class . getName ( ) , module ) ; } } catch ( ModuleNotFoundException e ) { // Treat this as a user mistake, e.g. incorrect module name. // Throw OFE so post-boot it only gets logged at DEBUG. throw ControllerLogger . ROOT_LOGGER . extensionModuleNotFound ( e , module ) ; } catch ( ModuleLoadException e ) { // The module is there but can't be loaded. Treat this as an internal problem. // Throw a runtime exception so it always gets logged at ERROR in the server log with stack trace details. throw ControllerLogger . ROOT_LOGGER . extensionModuleLoadingFailure ( e , module ) ; } }
Initialise an extension module s extensions in the extension registry
440
11
145,749
private void addDependent ( String pathName , String relativeTo ) { if ( relativeTo != null ) { Set < String > dependents = dependenctRelativePaths . get ( relativeTo ) ; if ( dependents == null ) { dependents = new HashSet < String > ( ) ; dependenctRelativePaths . put ( relativeTo , dependents ) ; } dependents . add ( pathName ) ; } }
Must be called with pathEntries lock taken
93
9
145,750
private void getAllDependents ( Set < PathEntry > result , String name ) { Set < String > depNames = dependenctRelativePaths . get ( name ) ; if ( depNames == null ) { return ; } for ( String dep : depNames ) { PathEntry entry = pathEntries . get ( dep ) ; if ( entry != null ) { result . add ( entry ) ; getAllDependents ( result , dep ) ; } } }
Call with pathEntries lock taken
100
7
145,751
void addOption ( final String value ) { Assert . checkNotNullParam ( "value" , value ) ; synchronized ( options ) { options . add ( value ) ; } }
Adds an option to the Jvm options
38
8
145,752
@ SuppressWarnings ( "unchecked" ) public static < T > AttachmentKey < T > create ( final Class < ? super T > valueClass ) { return new SimpleAttachmentKey ( valueClass ) ; }
Construct a new simple attachment key .
48
7
145,753
InputStream openContentStream ( final ContentItem item ) throws IOException { final File file = getFile ( item ) ; if ( file == null ) { throw new IllegalStateException ( ) ; } return new FileInputStream ( file ) ; }
Open a new content stream .
51
6
145,754
public ModelNode buildExecutableRequest ( CommandContext ctx ) throws Exception { try { for ( FailureDescProvider h : providers ) { effectiveProviders . add ( h ) ; } // In case some key-store needs to be persisted for ( String ks : ksToStore ) { composite . get ( Util . STEPS ) . add ( ElytronUtil . storeKeyStore ( ctx , ks ) ) ; effectiveProviders . add ( new FailureDescProvider ( ) { @ Override public String stepFailedDescription ( ) { return "Storing the key-store " + ksToStore ; } } ) ; } // Final steps for ( int i = 0 ; i < finalSteps . size ( ) ; i ++ ) { composite . get ( Util . STEPS ) . add ( finalSteps . get ( i ) ) ; effectiveProviders . add ( finalProviders . get ( i ) ) ; } return composite ; } catch ( Exception ex ) { try { failureOccured ( ctx , null ) ; } catch ( Exception ex2 ) { ex . addSuppressed ( ex2 ) ; } throw ex ; } }
Sort and order steps to avoid unwanted generation
247
8
145,755
@ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; List < ResourceRoot > resourceRoots = DeploymentUtils . allResourceRoots ( deploymentUnit ) ; for ( ResourceRoot resourceRoot : resourceRoots ) { if ( IgnoreMetaInfMarker . isIgnoreMetaInf ( resourceRoot ) ) { continue ; } Manifest manifest = getManifest ( resourceRoot ) ; if ( manifest != null ) resourceRoot . putAttachment ( Attachments . MANIFEST , manifest ) ; } }
Process the deployment root for the manifest .
133
8
145,756
private PersistentResourceXMLDescription getSimpleMapperParser ( ) { if ( version . equals ( Version . VERSION_1_0 ) ) { return simpleMapperParser_1_0 ; } else if ( version . equals ( Version . VERSION_1_1 ) ) { return simpleMapperParser_1_1 ; } return simpleMapperParser ; }
1 . 0 version of parser is different at simple mapperParser
79
13
145,757
public static DeploymentUnit getTopDeploymentUnit ( DeploymentUnit unit ) { Assert . checkNotNullParam ( "unit" , unit ) ; DeploymentUnit parent = unit . getParent ( ) ; while ( parent != null ) { unit = parent ; parent = unit . getParent ( ) ; } return unit ; }
Get top deployment unit .
69
5
145,758
protected Connection openConnection ( ) throws IOException { // Perhaps this can just be done once? CallbackHandler callbackHandler = null ; SSLContext sslContext = null ; if ( realm != null ) { sslContext = realm . getSSLContext ( ) ; CallbackHandlerFactory handlerFactory = realm . getSecretCallbackHandlerFactory ( ) ; if ( handlerFactory != null ) { String username = this . username != null ? this . username : localHostName ; callbackHandler = handlerFactory . getCallbackHandler ( username ) ; } } final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration . copy ( configuration ) ; config . setCallbackHandler ( callbackHandler ) ; config . setSslContext ( sslContext ) ; config . setUri ( uri ) ; AuthenticationContext authenticationContext = this . authenticationContext != null ? this . authenticationContext : AuthenticationContext . captureCurrent ( ) ; // Connect try { return authenticationContext . run ( ( PrivilegedExceptionAction < Connection > ) ( ) -> ProtocolConnectionUtils . connectSync ( config ) ) ; } catch ( PrivilegedActionException e ) { if ( e . getCause ( ) instanceof IOException ) { throw ( IOException ) e . getCause ( ) ; } throw new IOException ( e ) ; } }
Connect and register at the remote domain controller .
264
9
145,759
boolean applyDomainModel ( ModelNode result ) { if ( ! result . hasDefined ( ModelDescriptionConstants . RESULT ) ) { return false ; } final List < ModelNode > bootOperations = result . get ( ModelDescriptionConstants . RESULT ) . asList ( ) ; return callback . applyDomainModel ( bootOperations ) ; }
Apply the remote read domain model result .
75
8
145,760
public static Thread addShutdownHook ( final Process process ) { final Thread thread = new Thread ( new Runnable ( ) { @ Override public void run ( ) { if ( process != null ) { process . destroy ( ) ; try { process . waitFor ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } } } ) ; thread . setDaemon ( true ) ; Runtime . getRuntime ( ) . addShutdownHook ( thread ) ; return thread ; }
Adds a shutdown hook for the process .
111
8
145,761
public void addOrderedChildResourceTypes ( PathAddress resourceAddress , Resource resource ) { Set < String > orderedChildTypes = resource . getOrderedChildTypes ( ) ; if ( orderedChildTypes . size ( ) > 0 ) { orderedChildren . put ( resourceAddress , resource . getOrderedChildTypes ( ) ) ; } }
If the resource has ordered child types those child types will be stored in the attachment . If there are no ordered child types this method is a no - op .
70
32
145,762
private static Map < String , ServerGroupDeploymentPlanResult > buildServerGroupResults ( Map < UUID , DeploymentActionResult > deploymentActionResults ) { Map < String , ServerGroupDeploymentPlanResult > serverGroupResults = new HashMap < String , ServerGroupDeploymentPlanResult > ( ) ; for ( Map . Entry < UUID , DeploymentActionResult > entry : deploymentActionResults . entrySet ( ) ) { UUID actionId = entry . getKey ( ) ; DeploymentActionResult actionResult = entry . getValue ( ) ; Map < String , ServerGroupDeploymentActionResult > actionResultsByServerGroup = actionResult . getResultsByServerGroup ( ) ; for ( ServerGroupDeploymentActionResult serverGroupActionResult : actionResultsByServerGroup . values ( ) ) { String serverGroupName = serverGroupActionResult . getServerGroupName ( ) ; ServerGroupDeploymentPlanResultImpl sgdpr = ( ServerGroupDeploymentPlanResultImpl ) serverGroupResults . get ( serverGroupName ) ; if ( sgdpr == null ) { sgdpr = new ServerGroupDeploymentPlanResultImpl ( serverGroupName ) ; serverGroupResults . put ( serverGroupName , sgdpr ) ; } for ( Map . Entry < String , ServerUpdateResult > serverEntry : serverGroupActionResult . getResultByServer ( ) . entrySet ( ) ) { String serverName = serverEntry . getKey ( ) ; ServerUpdateResult sud = serverEntry . getValue ( ) ; ServerDeploymentPlanResultImpl sdpr = ( ServerDeploymentPlanResultImpl ) sgdpr . getServerResult ( serverName ) ; if ( sdpr == null ) { sdpr = new ServerDeploymentPlanResultImpl ( serverName ) ; sgdpr . storeServerResult ( serverName , sdpr ) ; } sdpr . storeServerUpdateResult ( actionId , sud ) ; } } } return serverGroupResults ; }
Builds the data structures that show the effects of the plan by server group
410
15
145,763
protected TransformationDescription buildDefault ( final DiscardPolicy discardPolicy , boolean inherited , final AttributeTransformationDescriptionBuilderImpl . AttributeTransformationDescriptionBuilderRegistry registry , List < String > discardedOperations ) { // Build attribute rules final Map < String , AttributeTransformationDescription > attributes = registry . buildAttributes ( ) ; // Create operation transformers final Map < String , OperationTransformer > operations = buildOperationTransformers ( registry ) ; // Process children final List < TransformationDescription > children = buildChildren ( ) ; if ( discardPolicy == DiscardPolicy . NEVER ) { // TODO override more global operations? if ( ! operations . containsKey ( ModelDescriptionConstants . WRITE_ATTRIBUTE_OPERATION ) ) { operations . put ( ModelDescriptionConstants . WRITE_ATTRIBUTE_OPERATION , OperationTransformationRules . createWriteOperation ( attributes ) ) ; } if ( ! operations . containsKey ( ModelDescriptionConstants . UNDEFINE_ATTRIBUTE_OPERATION ) ) { operations . put ( ModelDescriptionConstants . UNDEFINE_ATTRIBUTE_OPERATION , OperationTransformationRules . createUndefinedOperation ( attributes ) ) ; } } // Create the description Set < String > discarded = new HashSet <> ( ) ; discarded . addAll ( discardedOperations ) ; return new TransformingDescription ( pathElement , pathAddressTransformer , discardPolicy , inherited , resourceTransformer , attributes , operations , children , discarded , dynamicDiscardPolicy ) ; }
Build the default transformation description .
316
6
145,764
protected Map < String , OperationTransformer > buildOperationTransformers ( AttributeTransformationDescriptionBuilderImpl . AttributeTransformationDescriptionBuilderRegistry registry ) { final Map < String , OperationTransformer > operations = new HashMap < String , OperationTransformer > ( ) ; for ( final Map . Entry < String , OperationTransformationEntry > entry : operationTransformers . entrySet ( ) ) { final OperationTransformer transformer = entry . getValue ( ) . getOperationTransformer ( registry ) ; operations . put ( entry . getKey ( ) , transformer ) ; } return operations ; }
Build the operation transformers .
123
6
145,765
protected List < TransformationDescription > buildChildren ( ) { if ( children . isEmpty ( ) ) { return Collections . emptyList ( ) ; } final List < TransformationDescription > children = new ArrayList < TransformationDescription > ( ) ; for ( final TransformationDescriptionBuilder builder : this . children ) { children . add ( builder . build ( ) ) ; } return children ; }
Build all children .
77
4
145,766
@ Deprecated public static OptionMap create ( final ExpressionResolver resolver , final ModelNode model , final OptionMap defaults ) throws OperationFailedException { final OptionMap map = OptionMap . builder ( ) . addAll ( defaults ) . set ( Options . WORKER_READ_THREADS , RemotingSubsystemRootResource . WORKER_READ_THREADS . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . set ( Options . WORKER_TASK_CORE_THREADS , RemotingSubsystemRootResource . WORKER_TASK_CORE_THREADS . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . set ( Options . WORKER_TASK_KEEPALIVE , RemotingSubsystemRootResource . WORKER_TASK_KEEPALIVE . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . set ( Options . WORKER_TASK_LIMIT , RemotingSubsystemRootResource . WORKER_TASK_LIMIT . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . set ( Options . WORKER_TASK_MAX_THREADS , RemotingSubsystemRootResource . WORKER_TASK_MAX_THREADS . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . set ( Options . WORKER_WRITE_THREADS , RemotingSubsystemRootResource . WORKER_WRITE_THREADS . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . set ( Options . WORKER_READ_THREADS , RemotingSubsystemRootResource . WORKER_READ_THREADS . resolveModelAttribute ( resolver , model ) . asInt ( ) ) . getMap ( ) ; return map ; }
creates option map for remoting connections
404
8
145,767
@ Override public PersistentResourceXMLDescription getParserDescription ( ) { return PersistentResourceXMLDescription . builder ( ElytronExtension . SUBSYSTEM_PATH , getNameSpace ( ) ) . addAttribute ( ElytronDefinition . DEFAULT_AUTHENTICATION_CONTEXT ) . addAttribute ( ElytronDefinition . INITIAL_PROVIDERS ) . addAttribute ( ElytronDefinition . FINAL_PROVIDERS ) . addAttribute ( ElytronDefinition . DISALLOWED_PROVIDERS ) . addAttribute ( ElytronDefinition . SECURITY_PROPERTIES , new AttributeParsers . PropertiesParser ( null , SECURITY_PROPERTY , true ) , new AttributeMarshallers . PropertiesAttributeMarshaller ( null , SECURITY_PROPERTY , true ) ) . addChild ( getAuthenticationClientParser ( ) ) . addChild ( getProviderParser ( ) ) . addChild ( getAuditLoggingParser ( ) ) . addChild ( getDomainParser ( ) ) . addChild ( getRealmParser ( ) ) . addChild ( getCredentialSecurityFactoryParser ( ) ) . addChild ( getMapperParser ( ) ) . addChild ( getHttpParser ( ) ) . addChild ( getSaslParser ( ) ) . addChild ( getTlsParser ( ) ) . addChild ( decorator ( CREDENTIAL_STORES ) . addChild ( new CredentialStoreParser ( ) . parser ) ) . addChild ( getDirContextParser ( ) ) . addChild ( getPolicyParser ( ) ) . build ( ) ; }
at this point definition below is not really needed as it is the same as for 1 . 1 but it is here as place holder when subsystem parser evolves .
356
31
145,768
public synchronized void reset ( ) { this . authorizerDescription = StandardRBACAuthorizer . AUTHORIZER_DESCRIPTION ; this . useIdentityRoles = this . nonFacadeMBeansSensitive = false ; this . roleMappings = new HashMap < String , RoleMappingImpl > ( ) ; RoleMaps oldRoleMaps = this . roleMaps ; this . roleMaps = new RoleMaps ( authorizerDescription . getStandardRoles ( ) , Collections . < String , ScopedRole > emptyMap ( ) ) ; for ( ScopedRole role : oldRoleMaps . scopedRoles . values ( ) ) { for ( ScopedRoleListener listener : scopedRoleListeners ) { try { listener . scopedRoleRemoved ( role ) ; } catch ( Exception ignored ) { // TODO log an ERROR } } } }
Reset the internal state of this object back to what it originally was .
178
15
145,769
public synchronized void addRoleMapping ( final String roleName ) { HashMap < String , RoleMappingImpl > newRoles = new HashMap < String , RoleMappingImpl > ( roleMappings ) ; if ( newRoles . containsKey ( roleName ) == false ) { newRoles . put ( roleName , new RoleMappingImpl ( roleName ) ) ; roleMappings = Collections . unmodifiableMap ( newRoles ) ; } }
Adds a new role to the list of defined roles .
99
11
145,770
public synchronized Object removeRoleMapping ( final String roleName ) { /* * Would not expect this to happen during boot so don't offer the 'immediate' optimisation. */ HashMap < String , RoleMappingImpl > newRoles = new HashMap < String , RoleMappingImpl > ( roleMappings ) ; if ( newRoles . containsKey ( roleName ) ) { RoleMappingImpl removed = newRoles . remove ( roleName ) ; Object removalKey = new Object ( ) ; removedRoles . put ( removalKey , removed ) ; roleMappings = Collections . unmodifiableMap ( newRoles ) ; return removalKey ; } return null ; }
Remove a role from the list of defined roles .
144
10
145,771
public synchronized boolean undoRoleMappingRemove ( final Object removalKey ) { HashMap < String , RoleMappingImpl > newRoles = new HashMap < String , RoleMappingImpl > ( roleMappings ) ; RoleMappingImpl toRestore = removedRoles . remove ( removalKey ) ; if ( toRestore != null && newRoles . containsKey ( toRestore . getName ( ) ) == false ) { newRoles . put ( toRestore . getName ( ) , toRestore ) ; roleMappings = Collections . unmodifiableMap ( newRoles ) ; return true ; } return false ; }
Undo a prior removal using the supplied undo key .
136
11
145,772
private Map < Set < ServerIdentity > , ModelNode > getDeploymentOverlayOperations ( ModelNode operation , ModelNode host ) { final PathAddress realAddress = PathAddress . pathAddress ( operation . get ( OP_ADDR ) ) ; if ( realAddress . size ( ) == 0 && COMPOSITE . equals ( operation . get ( OP ) . asString ( ) ) ) { //We have a composite operation resulting from a transformation to redeploy affected deployments //See redeploying deployments affected by an overlay. ModelNode serverOp = operation . clone ( ) ; Map < ServerIdentity , Operations . CompositeOperationBuilder > composite = new HashMap <> ( ) ; for ( ModelNode step : serverOp . get ( STEPS ) . asList ( ) ) { ModelNode newStep = step . clone ( ) ; String groupName = PathAddress . pathAddress ( step . get ( OP_ADDR ) ) . getElement ( 0 ) . getValue ( ) ; newStep . get ( OP_ADDR ) . set ( PathAddress . pathAddress ( step . get ( OP_ADDR ) ) . subAddress ( 1 ) . toModelNode ( ) ) ; Set < ServerIdentity > servers = getServersForGroup ( groupName , host , localHostName , serverProxies ) ; for ( ServerIdentity server : servers ) { if ( ! composite . containsKey ( server ) ) { composite . put ( server , Operations . CompositeOperationBuilder . create ( ) ) ; } composite . get ( server ) . addStep ( newStep ) ; } if ( ! servers . isEmpty ( ) ) { newStep . get ( OP_ADDR ) . set ( PathAddress . pathAddress ( step . get ( OP_ADDR ) ) . subAddress ( 1 ) . toModelNode ( ) ) ; } } if ( ! composite . isEmpty ( ) ) { Map < Set < ServerIdentity > , ModelNode > result = new HashMap <> ( ) ; for ( Entry < ServerIdentity , Operations . CompositeOperationBuilder > entry : composite . entrySet ( ) ) { result . put ( Collections . singleton ( entry . getKey ( ) ) , entry . getValue ( ) . build ( ) . getOperation ( ) ) ; } return result ; } return Collections . emptyMap ( ) ; } final Set < ServerIdentity > allServers = getAllRunningServers ( host , localHostName , serverProxies ) ; return Collections . singletonMap ( allServers , operation . clone ( ) ) ; }
Convert an operation for deployment overlays to be executed on local servers . Since this might be called in the case of redeployment of affected deployments we need to take into account the composite op resulting from such a transformation
543
44
145,773
public static boolean isLogDownloadAvailable ( CliGuiContext cliGuiCtx ) { ModelNode readOps = null ; try { readOps = cliGuiCtx . getExecutor ( ) . doCommand ( "/subsystem=logging:read-children-types" ) ; } catch ( CommandFormatException | IOException e ) { return false ; } if ( ! readOps . get ( "result" ) . isDefined ( ) ) return false ; for ( ModelNode op : readOps . get ( "result" ) . asList ( ) ) { if ( "log-file" . equals ( op . asString ( ) ) ) return true ; } return false ; }
Does the server support log downloads?
150
7
145,774
public static InetAddress getLocalHost ( ) throws UnknownHostException { InetAddress addr ; try { addr = InetAddress . getLocalHost ( ) ; } catch ( ArrayIndexOutOfBoundsException e ) { //this is workaround for mac osx bug see AS7-3223 and JGRP-1404 addr = InetAddress . getByName ( null ) ; } return addr ; }
Methods returns InetAddress for localhost
87
8
145,775
public File getBootFile ( ) { if ( bootFile == null ) { synchronized ( this ) { if ( bootFile == null ) { if ( bootFileReset ) { //Reset the done bootup and the sequence, so that the old file we are reloading from // overwrites the main file on successful boot, and history is reset as when booting new doneBootup . set ( false ) ; sequence . set ( 0 ) ; } // If it's a reload with no new boot file name and we're persisting our config, we boot from mainFile, // as that's where we persist if ( bootFileReset && ! interactionPolicy . isReadOnly ( ) && newReloadBootFileName == null ) { // we boot from mainFile bootFile = mainFile ; } else { // It's either first boot, or a reload where we're not persisting our config or with a new boot file. // So we need to figure out which file we're meant to boot from String bootFileName = this . bootFileName ; if ( newReloadBootFileName != null ) { //A non-null new boot file on reload takes precedence over the reloadUsingLast functionality //A new boot file was specified. Use that and reset the new name to null bootFileName = newReloadBootFileName ; newReloadBootFileName = null ; } else if ( interactionPolicy . isReadOnly ( ) && reloadUsingLast ) { //If we were reloaded, and it is not a persistent configuration we want to use the last from the history bootFileName = LAST ; } boolean usingRawFile = bootFileName . equals ( rawFileName ) ; if ( usingRawFile ) { bootFile = mainFile ; } else { bootFile = determineBootFile ( configurationDir , bootFileName ) ; try { bootFile = bootFile . getCanonicalFile ( ) ; } catch ( IOException ioe ) { throw ControllerLogger . ROOT_LOGGER . canonicalBootFileNotFound ( ioe , bootFile ) ; } } if ( ! bootFile . exists ( ) ) { if ( ! usingRawFile ) { // TODO there's no reason usingRawFile should be an exception, // but the test infrastructure stuff is built around an assumption // that ConfigurationFile doesn't fail if test files are not // in the normal spot if ( bootFileReset || interactionPolicy . isRequireExisting ( ) ) { throw ControllerLogger . ROOT_LOGGER . fileNotFound ( bootFile . getAbsolutePath ( ) ) ; } } // Create it for the NEW and DISCARD cases if ( ! bootFileReset && ! interactionPolicy . isRequireExisting ( ) ) { createBootFile ( bootFile ) ; } } else if ( ! bootFileReset ) { if ( interactionPolicy . isRejectExisting ( ) && bootFile . length ( ) > 0 ) { throw ControllerLogger . ROOT_LOGGER . rejectEmptyConfig ( bootFile . getAbsolutePath ( ) ) ; } else if ( interactionPolicy . isRemoveExisting ( ) && bootFile . length ( ) > 0 ) { if ( ! bootFile . delete ( ) ) { throw ControllerLogger . ROOT_LOGGER . cannotDelete ( bootFile . getAbsoluteFile ( ) ) ; } createBootFile ( bootFile ) ; } } // else after first boot we want the file to exist } } } } return bootFile ; }
Gets the file from which boot operations should be parsed .
734
12
145,776
void successfulBoot ( ) throws ConfigurationPersistenceException { synchronized ( this ) { if ( doneBootup . get ( ) ) { return ; } final File copySource ; if ( ! interactionPolicy . isReadOnly ( ) ) { copySource = mainFile ; } else { if ( FilePersistenceUtils . isParentFolderWritable ( mainFile ) ) { copySource = new File ( mainFile . getParentFile ( ) , mainFile . getName ( ) + ".boot" ) ; } else { copySource = new File ( configurationDir , mainFile . getName ( ) + ".boot" ) ; } FilePersistenceUtils . deleteFile ( copySource ) ; } try { if ( ! bootFile . equals ( copySource ) ) { FilePersistenceUtils . copyFile ( bootFile , copySource ) ; } createHistoryDirectory ( ) ; final File historyBase = new File ( historyRoot , mainFile . getName ( ) ) ; lastFile = addSuffixToFile ( historyBase , LAST ) ; final File boot = addSuffixToFile ( historyBase , BOOT ) ; final File initial = addSuffixToFile ( historyBase , INITIAL ) ; if ( ! initial . exists ( ) ) { FilePersistenceUtils . copyFile ( copySource , initial ) ; } FilePersistenceUtils . copyFile ( copySource , lastFile ) ; FilePersistenceUtils . copyFile ( copySource , boot ) ; } catch ( IOException e ) { throw ControllerLogger . ROOT_LOGGER . failedToCreateConfigurationBackup ( e , bootFile ) ; } finally { if ( interactionPolicy . isReadOnly ( ) ) { //Delete the temporary file try { FilePersistenceUtils . deleteFile ( copySource ) ; } catch ( Exception ignore ) { } } } doneBootup . set ( true ) ; } }
Notification that boot has completed successfully and the configuration history should be updated
400
14
145,777
void backup ( ) throws ConfigurationPersistenceException { if ( ! doneBootup . get ( ) ) { return ; } try { if ( ! interactionPolicy . isReadOnly ( ) ) { //Move the main file to the versioned history moveFile ( mainFile , getVersionedFile ( mainFile ) ) ; } else { //Copy the Last file to the versioned history moveFile ( lastFile , getVersionedFile ( mainFile ) ) ; } int seq = sequence . get ( ) ; // delete unwanted backup files int currentHistoryLength = getInteger ( CURRENT_HISTORY_LENGTH_PROPERTY , CURRENT_HISTORY_LENGTH , 0 ) ; if ( seq > currentHistoryLength ) { for ( int k = seq - currentHistoryLength ; k > 0 ; k -- ) { File delete = getVersionedFile ( mainFile , k ) ; if ( ! delete . exists ( ) ) { break ; } delete . delete ( ) ; } } } catch ( IOException e ) { throw ControllerLogger . ROOT_LOGGER . failedToBackup ( e , mainFile ) ; } }
Backup the current version of the configuration to the versioned configuration history
238
14
145,778
void commitTempFile ( File temp ) throws ConfigurationPersistenceException { if ( ! doneBootup . get ( ) ) { return ; } if ( ! interactionPolicy . isReadOnly ( ) ) { FilePersistenceUtils . moveTempFileToMain ( temp , mainFile ) ; } else { FilePersistenceUtils . moveTempFileToMain ( temp , lastFile ) ; } }
Commit the contents of the given temp file to either the main file or if we are not persisting to the main file to the . last file in the configuration history
83
34
145,779
void fileWritten ( ) throws ConfigurationPersistenceException { if ( ! doneBootup . get ( ) || interactionPolicy . isReadOnly ( ) ) { return ; } try { FilePersistenceUtils . copyFile ( mainFile , lastFile ) ; } catch ( IOException e ) { throw ControllerLogger . ROOT_LOGGER . failedToBackup ( e , mainFile ) ; } }
Notification that the configuration has been written and its current content should be stored to the . last file
85
20
145,780
private void deleteRecursive ( final File file ) { if ( file . isDirectory ( ) ) { final String [ ] files = file . list ( ) ; if ( files != null ) { for ( String name : files ) { deleteRecursive ( new File ( file , name ) ) ; } } } if ( ! file . delete ( ) ) { ControllerLogger . ROOT_LOGGER . cannotDeleteFileOrDirectory ( file ) ; } }
note this just logs an error and doesn t throw as its only used to remove old configuration files and shouldn t stop boot
95
24
145,781
protected void updateModel ( final OperationContext context , final ModelNode operation ) throws OperationFailedException { // verify that the resource exist before removing it context . readResource ( PathAddress . EMPTY_ADDRESS , false ) ; Resource resource = context . removeResource ( PathAddress . EMPTY_ADDRESS ) ; recordCapabilitiesAndRequirements ( context , operation , resource ) ; }
Performs the update to the persistent configuration model . This default implementation simply removes the targeted resource .
81
19
145,782
ResultAction executeOperation ( ) { assert isControllingThread ( ) ; try { /** Execution has begun */ executing = true ; processStages ( ) ; if ( resultAction == ResultAction . KEEP ) { report ( MessageSeverity . INFO , ControllerLogger . ROOT_LOGGER . operationSucceeded ( ) ) ; } else { report ( MessageSeverity . INFO , ControllerLogger . ROOT_LOGGER . operationRollingBack ( ) ) ; } } catch ( RuntimeException e ) { handleUncaughtException ( e ) ; ControllerLogger . MGMT_OP_LOGGER . unexpectedOperationExecutionException ( e , controllerOperations ) ; } finally { // On failure close any attached response streams if ( resultAction != ResultAction . KEEP && ! isBooting ( ) ) { synchronized ( this ) { if ( responseStreams != null ) { int i = 0 ; for ( OperationResponse . StreamEntry is : responseStreams . values ( ) ) { try { is . getStream ( ) . close ( ) ; } catch ( Exception e ) { ControllerLogger . MGMT_OP_LOGGER . debugf ( e , "Failed closing stream at index %d" , i ) ; } i ++ ; } responseStreams . clear ( ) ; } } } } return resultAction ; }
Package - protected method used to initiate operation execution .
285
10
145,783
void logAuditRecord ( ) { trackConfigurationChange ( ) ; if ( ! auditLogged ) { try { AccessAuditContext accessContext = SecurityActions . currentAccessAuditContext ( ) ; Caller caller = getCaller ( ) ; auditLogger . log ( isReadOnly ( ) , resultAction , caller == null ? null : caller . getName ( ) , accessContext == null ? null : accessContext . getDomainUuid ( ) , accessContext == null ? null : accessContext . getAccessMechanism ( ) , accessContext == null ? null : accessContext . getRemoteAddress ( ) , getModel ( ) , controllerOperations ) ; auditLogged = true ; } catch ( Exception e ) { ControllerLogger . MGMT_OP_LOGGER . failedToUpdateAuditLog ( e ) ; } } }
Log an audit record of this operation .
178
8
145,784
private void processStages ( ) { // Locate the next step to execute. ModelNode primaryResponse = null ; Step step ; do { step = steps . get ( currentStage ) . pollFirst ( ) ; if ( step == null ) { if ( currentStage == Stage . MODEL && addModelValidationSteps ( ) ) { continue ; } // No steps remain in this stage; give subclasses a chance to check status // and approve moving to the next stage if ( ! tryStageCompleted ( currentStage ) ) { // Can't continue resultAction = ResultAction . ROLLBACK ; executeResultHandlerPhase ( null ) ; return ; } // Proceed to the next stage if ( currentStage . hasNext ( ) ) { currentStage = currentStage . next ( ) ; if ( currentStage == Stage . VERIFY ) { // a change was made to the runtime. Thus, we must wait // for stability before resuming in to verify. try { awaitServiceContainerStability ( ) ; } catch ( InterruptedException e ) { cancelled = true ; handleContainerStabilityFailure ( primaryResponse , e ) ; executeResultHandlerPhase ( null ) ; return ; } catch ( TimeoutException te ) { // The service container is in an unknown state; but we don't require restart // because rollback may allow the container to stabilize. We force require-restart // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks) //processState.setRestartRequired(); // don't use our restartRequired() method as this is not reversible in rollback handleContainerStabilityFailure ( primaryResponse , te ) ; executeResultHandlerPhase ( null ) ; return ; } } } } else { // The response to the first step is what goes to the outside caller if ( primaryResponse == null ) { primaryResponse = step . response ; } // Execute the step, but make sure we always finalize any steps Throwable toThrow = null ; // Whether to return after try/finally boolean exit = false ; try { CapabilityRegistry . RuntimeStatus stepStatus = getStepExecutionStatus ( step ) ; if ( stepStatus == RuntimeCapabilityRegistry . RuntimeStatus . NORMAL ) { executeStep ( step ) ; } else { String header = stepStatus == RuntimeCapabilityRegistry . RuntimeStatus . RESTART_REQUIRED ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD ; step . response . get ( RESPONSE_HEADERS , header ) . set ( true ) ; } } catch ( RuntimeException | Error re ) { resultAction = ResultAction . ROLLBACK ; toThrow = re ; } finally { // See if executeStep put us in a state where we shouldn't do any more if ( toThrow != null || ! canContinueProcessing ( ) ) { // We're done. executeResultHandlerPhase ( toThrow ) ; exit = true ; // we're on the return path } } if ( exit ) { return ; } } } while ( currentStage != Stage . DONE ) ; assert primaryResponse != null ; // else ModelControllerImpl executed an op with no steps // All steps ran and canContinueProcessing returned true for the last one, so... executeDoneStage ( primaryResponse ) ; }
Perform the work of processing the various OperationContext . Stage queues and then the DONE stage .
695
20
145,785
private void checkUndefinedNotification ( Notification notification ) { String type = notification . getType ( ) ; PathAddress source = notification . getSource ( ) ; Map < String , NotificationEntry > descriptions = getRootResourceRegistration ( ) . getNotificationDescriptions ( source , true ) ; if ( ! descriptions . keySet ( ) . contains ( type ) ) { missingNotificationDescriptionWarnings . add ( ControllerLogger . ROOT_LOGGER . notificationIsNotDescribed ( type , source ) ) ; } }
Check that each emitted notification is properly described by its source .
111
12
145,786
private ResultAction getFailedResultAction ( Throwable cause ) { if ( currentStage == Stage . MODEL || cancelled || isRollbackOnRuntimeFailure ( ) || isRollbackOnly ( ) || ( cause != null && ! ( cause instanceof OperationFailedException ) ) ) { return ResultAction . ROLLBACK ; } return ResultAction . KEEP ; }
Decide whether failure should trigger a rollback .
77
10
145,787
public boolean canUpdateServer ( ServerIdentity server ) { if ( ! serverGroupName . equals ( server . getServerGroupName ( ) ) || ! servers . contains ( server ) ) { throw DomainControllerLogger . HOST_CONTROLLER_LOGGER . unknownServer ( server ) ; } if ( ! parent . canChildProceed ( ) ) return false ; synchronized ( this ) { return failureCount <= maxFailed ; } }
Gets whether the given server can be updated .
95
10
145,788
public void recordServerResult ( ServerIdentity server , ModelNode response ) { if ( ! serverGroupName . equals ( server . getServerGroupName ( ) ) || ! servers . contains ( server ) ) { throw DomainControllerLogger . HOST_CONTROLLER_LOGGER . unknownServer ( server ) ; } boolean serverFailed = response . has ( FAILURE_DESCRIPTION ) ; DomainControllerLogger . HOST_CONTROLLER_LOGGER . tracef ( "Recording server result for '%s': failed = %s" , server , server ) ; synchronized ( this ) { int previousFailed = failureCount ; if ( serverFailed ) { failureCount ++ ; } else { successCount ++ ; } if ( previousFailed <= maxFailed ) { if ( ! serverFailed && ( successCount + failureCount ) == servers . size ( ) ) { // All results are in; notify parent of success parent . recordServerGroupResult ( serverGroupName , false ) ; } else if ( serverFailed && failureCount > maxFailed ) { parent . recordServerGroupResult ( serverGroupName , true ) ; } } } }
Records the result of updating a server .
250
9
145,789
public void set ( final Argument argument ) { if ( argument != null ) { map . put ( argument . getKey ( ) , Collections . singleton ( argument ) ) ; } }
Sets an argument to the collection of arguments . This guarantees only one value will be assigned to the argument key .
38
23
145,790
public String get ( final String key ) { final Collection < Argument > args = map . get ( key ) ; if ( args != null ) { return args . iterator ( ) . hasNext ( ) ? args . iterator ( ) . next ( ) . getValue ( ) : null ; } return null ; }
Gets the first value for the key .
64
9
145,791
public Collection < Argument > getArguments ( final String key ) { final Collection < Argument > args = map . get ( key ) ; if ( args != null ) { return new ArrayList <> ( args ) ; } return Collections . emptyList ( ) ; }
Gets the value for the key .
55
8
145,792
public List < String > asList ( ) { final List < String > result = new ArrayList <> ( ) ; for ( Collection < Argument > args : map . values ( ) ) { for ( Argument arg : args ) { result . add ( arg . asCommandLineArgument ( ) ) ; } } return result ; }
Returns the arguments as a list in their command line form .
69
12
145,793
private void parseLdapAuthorization_1_5 ( final XMLExtendedStreamReader reader , final ModelNode realmAddress , final List < ModelNode > list ) throws XMLStreamException { ModelNode addr = realmAddress . clone ( ) . add ( AUTHORIZATION , LDAP ) ; ModelNode ldapAuthorization = Util . getEmptyOperation ( ADD , addr ) ; list . add ( ldapAuthorization ) ; Set < Attribute > required = EnumSet . of ( Attribute . CONNECTION ) ; final int count = reader . getAttributeCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { final String value = reader . getAttributeValue ( i ) ; if ( ! isNoNamespaceAttribute ( reader , i ) ) { throw unexpectedAttribute ( reader , i ) ; } else { final Attribute attribute = Attribute . forName ( reader . getAttributeLocalName ( i ) ) ; required . remove ( attribute ) ; switch ( attribute ) { case CONNECTION : { LdapAuthorizationResourceDefinition . CONNECTION . parseAndSetParameter ( value , ldapAuthorization , reader ) ; break ; } default : { throw unexpectedAttribute ( reader , i ) ; } } } } if ( required . isEmpty ( ) == false ) { throw missingRequired ( reader , required ) ; } Set < Element > foundElements = new HashSet < Element > ( ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { requireNamespace ( reader , namespace ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; if ( foundElements . add ( element ) == false ) { throw unexpectedElement ( reader ) ; // Only one of each allowed. } switch ( element ) { case USERNAME_TO_DN : { switch ( namespace . getMajorVersion ( ) ) { case 1 : // 1.5 up to but not including 2.0 parseUsernameToDn_1_5 ( reader , addr , list ) ; break ; default : // 2.0 and onwards parseUsernameToDn_2_0 ( reader , addr , list ) ; break ; } break ; } case GROUP_SEARCH : { switch ( namespace ) { case DOMAIN_1_5 : case DOMAIN_1_6 : parseGroupSearch_1_5 ( reader , addr , list ) ; break ; default : parseGroupSearch_1_7_and_2_0 ( reader , addr , list ) ; break ; } break ; } default : { throw unexpectedElement ( reader ) ; } } } }
1 . 5 and on 2 . 0 and on 3 . 0 and on .
568
16
145,794
public void merge ( final ResourceRoot additionalResourceRoot ) { if ( ! additionalResourceRoot . getRoot ( ) . equals ( root ) ) { throw ServerLogger . ROOT_LOGGER . cannotMergeResourceRoot ( root , additionalResourceRoot . getRoot ( ) ) ; } usePhysicalCodeSource = additionalResourceRoot . usePhysicalCodeSource ; if ( additionalResourceRoot . getExportFilters ( ) . isEmpty ( ) ) { //new root has no filters, so we don't want our existing filters to break anything //see WFLY-1527 this . exportFilters . clear ( ) ; } else { this . exportFilters . addAll ( additionalResourceRoot . getExportFilters ( ) ) ; } }
Merges information from the resource root into this resource root
155
11
145,795
@ Override public void registerTransformers ( SubsystemTransformerRegistration subsystemRegistration ) { ResourceTransformationDescriptionBuilder builder = ResourceTransformationDescriptionBuilder . Factory . createSubsystemInstance ( ) ; builder . addChildResource ( DeploymentPermissionsResourceDefinition . DEPLOYMENT_PERMISSIONS_PATH ) . getAttributeBuilder ( ) . addRejectCheck ( new RejectAttributeChecker . DefaultRejectAttributeChecker ( ) { @ Override protected boolean rejectAttribute ( PathAddress address , String attributeName , ModelNode value , TransformationContext context ) { // reject the maximum set if it is defined and empty as that would result in complete incompatible policies // being used in nodes running earlier versions of the subsystem. if ( value . isDefined ( ) && value . asList ( ) . isEmpty ( ) ) { return true ; } return false ; } @ Override public String getRejectionLogMessage ( Map < String , ModelNode > attributes ) { return SecurityManagerLogger . ROOT_LOGGER . rejectedEmptyMaximumSet ( ) ; } } , DeploymentPermissionsResourceDefinition . MAXIMUM_PERMISSIONS ) ; TransformationDescription . Tools . register ( builder . build ( ) , subsystemRegistration , EAP_7_0_0_MODEL_VERSION ) ; }
Registers the transformers for JBoss EAP 7 . 0 . 0 .
272
16
145,796
ModelNode toModelNode ( ) { ModelNode result = null ; if ( map != null ) { result = new ModelNode ( ) ; for ( Map . Entry < PathAddress , ResourceData > entry : map . entrySet ( ) ) { ModelNode item = new ModelNode ( ) ; PathAddress pa = entry . getKey ( ) ; item . get ( ABSOLUTE_ADDRESS ) . set ( pa . toModelNode ( ) ) ; ResourceData rd = entry . getValue ( ) ; item . get ( RELATIVE_ADDRESS ) . set ( pa . subAddress ( baseAddressLength ) . toModelNode ( ) ) ; ModelNode attrs = new ModelNode ( ) . setEmptyList ( ) ; if ( rd . attributes != null ) { for ( String attr : rd . attributes ) { attrs . add ( attr ) ; } } if ( attrs . asInt ( ) > 0 ) { item . get ( FILTERED_ATTRIBUTES ) . set ( attrs ) ; } ModelNode children = new ModelNode ( ) . setEmptyList ( ) ; if ( rd . children != null ) { for ( PathElement pe : rd . children ) { children . add ( new Property ( pe . getKey ( ) , new ModelNode ( pe . getValue ( ) ) ) ) ; } } if ( children . asInt ( ) > 0 ) { item . get ( UNREADABLE_CHILDREN ) . set ( children ) ; } ModelNode childTypes = new ModelNode ( ) . setEmptyList ( ) ; if ( rd . childTypes != null ) { Set < String > added = new HashSet < String > ( ) ; for ( PathElement pe : rd . childTypes ) { if ( added . add ( pe . getKey ( ) ) ) { childTypes . add ( pe . getKey ( ) ) ; } } } if ( childTypes . asInt ( ) > 0 ) { item . get ( FILTERED_CHILDREN_TYPES ) . set ( childTypes ) ; } result . add ( item ) ; } } return result ; }
Report on the filtered data in DMR .
462
9
145,797
public PatchingResult rollbackLast ( final ContentVerificationPolicy contentPolicy , final boolean resetConfiguration , InstallationManager . InstallationModification modification ) throws PatchingException { // Determine the patch id to rollback String patchId ; final List < String > oneOffs = modification . getPatchIDs ( ) ; if ( oneOffs . isEmpty ( ) ) { patchId = modification . getCumulativePatchID ( ) ; if ( patchId == null || Constants . NOT_PATCHED . equals ( patchId ) ) { throw PatchLogger . ROOT_LOGGER . noPatchesApplied ( ) ; } } else { patchId = oneOffs . get ( 0 ) ; //oneOffs.get(oneOffs.size() - 1); } return rollbackPatch ( patchId , contentPolicy , false , resetConfiguration , modification ) ; }
Rollback the last applied patch .
185
7
145,798
static void restoreFromHistory ( final InstallationManager . MutablePatchingTarget target , final String rollbackPatchId , final Patch . PatchType patchType , final PatchableTarget . TargetInfo history ) throws PatchingException { if ( patchType == Patch . PatchType . CUMULATIVE ) { assert history . getCumulativePatchID ( ) . equals ( rollbackPatchId ) ; target . apply ( rollbackPatchId , patchType ) ; // Restore one off state final List < String > oneOffs = new ArrayList < String > ( history . getPatchIDs ( ) ) ; Collections . reverse ( oneOffs ) ; for ( final String oneOff : oneOffs ) { target . apply ( oneOff , Patch . PatchType . ONE_OFF ) ; } } checkState ( history , history ) ; // Just check for tests, that rollback should restore the old state }
Restore the recorded state from the rollback xml .
188
11
145,799
void portForward ( final Patch patch , IdentityPatchContext context ) throws PatchingException , IOException , XMLStreamException { assert patch . getIdentity ( ) . getPatchType ( ) == Patch . PatchType . CUMULATIVE ; final PatchingHistory history = context . getHistory ( ) ; for ( final PatchElement element : patch . getElements ( ) ) { final PatchElementProvider provider = element . getProvider ( ) ; final String name = provider . getName ( ) ; final boolean addOn = provider . isAddOn ( ) ; final IdentityPatchContext . PatchEntry target = context . resolveForElement ( element ) ; final String cumulativePatchID = target . getCumulativePatchID ( ) ; if ( Constants . BASE . equals ( cumulativePatchID ) ) { reenableRolledBackInBase ( target ) ; continue ; } boolean found = false ; final PatchingHistory . Iterator iterator = history . iterator ( ) ; while ( iterator . hasNextCP ( ) ) { final PatchingHistory . Entry entry = iterator . nextCP ( ) ; final String patchId = addOn ? entry . getAddOnPatches ( ) . get ( name ) : entry . getLayerPatches ( ) . get ( name ) ; if ( patchId != null && patchId . equals ( cumulativePatchID ) ) { final Patch original = loadPatchInformation ( entry . getPatchId ( ) , installedImage ) ; for ( final PatchElement originalElement : original . getElements ( ) ) { if ( name . equals ( originalElement . getProvider ( ) . getName ( ) ) && addOn == originalElement . getProvider ( ) . isAddOn ( ) ) { PatchingTasks . addMissingModifications ( target , originalElement . getModifications ( ) , ContentItemFilter . ALL_BUT_MISC ) ; } } // Record a loader to have access to the current modules final DirectoryStructure structure = target . getDirectoryStructure ( ) ; final File modulesRoot = structure . getModulePatchDirectory ( patchId ) ; final File bundlesRoot = structure . getBundlesPatchDirectory ( patchId ) ; final PatchContentLoader loader = PatchContentLoader . create ( null , bundlesRoot , modulesRoot ) ; context . recordContentLoader ( patchId , loader ) ; found = true ; break ; } } if ( ! found ) { throw PatchLogger . ROOT_LOGGER . patchNotFoundInHistory ( cumulativePatchID ) ; } reenableRolledBackInBase ( target ) ; } }
Port forward missing module changes for each layer .
534
9