public boolean isMethodLevel(MethodIntf methodIntf, Method method, MethodIntf defaultMethodIntf) {
        assert methodIntf != null : "methodIntf is null";
        assert method != null : "method is null";

        Method classMethod = resolveRealMethod(method);
        String[] methodParams = MethodInfoHelper.getCanonicalParameterTypes(classMethod);
        final String methodName = classMethod.getName();
        final String className = classMethod.getDeclaringClass().getName();

        ArrayKey methodParamsKey = new ArrayKey((Object[]) methodParams);
        T attr = get(get(get(perViewStyle3, methodIntf), methodName), methodParamsKey);
        if (attr != null)
            return true;
        attr = get(get(perViewStyle2, methodIntf), methodName);
        if (attr != null)
            return true;
        attr = get(perViewStyle1, methodIntf);
        if (attr != null)
            return false;
        attr = get(get(get(style3, className), methodName), methodParamsKey);
        if (attr != null)
            return true;
        attr = get(style2, methodName);
        if (attr != null)
            return true;
        attr = get(style1, className);
        if (attr != null)
            return false;
        if(defaultMethodIntf == null) {
            return false;
        } else {
            return isMethodLevel(defaultMethodIntf, method, null);
        }
    }

public
boolean
isMethodLevel
(
MethodIntf
methodIntf
,
Method
method
,
MethodIntf
defaultMethodIntf
)
{
assert
methodIntf
!=
:
"methodIntf is null"
;
assert
method
!=
:
"method is null"
;
Method
classMethod
=
resolveRealMethod
(
method
)
;
String
[
]
methodParams
=
MethodInfoHelper
.
getCanonicalParameterTypes
(
classMethod
)
;
final
String
methodName
=
classMethod
.
getName
(
)
;
final
String
className
=
classMethod
.
getDeclaringClass
(
)
.
getName
(
)
;
ArrayKey
methodParamsKey
=
new
ArrayKey
(
(
Object
[
]
)
methodParams
)
;
T
attr
=
get
(
get
(
get
(
perViewStyle3
,
methodIntf
)
,
methodName
)
,
methodParamsKey
)
;
if
(
attr
!=
)
return
true
;
attr
=
get
(
get
(
perViewStyle2
,
methodIntf
)
,
methodName
)
;
if
(
attr
!=
)
return
true
;
attr
=
get
(
perViewStyle1
,
methodIntf
)
;
if
(
attr
!=
)
return
false
;
attr
=
get
(
get
(
get
(
style3
,
className
)
,
methodName
)
,
methodParamsKey
)
;
if
(
attr
!=
)
return
true
;
attr
=
get
(
style2
,
methodName
)
;
if
(
attr
!=
)
return
true
;
attr
=
get
(
style1
,
className
)
;
if
(
attr
!=
)
return
false
;
if
(
defaultMethodIntf
==
)
{
return
false
;
}
else
{
return
isMethodLevel
(
defaultMethodIntf
,
method
,
)
;
}
}

Returns true if the given transaction specification was expliitly specified at a method level, returns
false if it was inherited from the default

Returns true if the given transaction specification was expliitly specified at a method level returns false if it was inherited from the default


protected static void checkOnlyOneOfElements(XMLExtendedStreamReader reader, Set<Element> seen, Element element1, Element element2) throws XMLStreamException {
        if (!seen.contains(element1) && !seen.contains(element2)) {
            throw new XMLStreamException(MessagingLogger.ROOT_LOGGER.required(element1.getLocalName(), element2.getLocalName()), reader.getLocation());
        }
        if (seen.contains(element1) && seen.contains(element2)) {
            throw new XMLStreamException(MessagingLogger.ROOT_LOGGER.onlyOneRequired(element1.getLocalName(), element2.getLocalName()), reader.getLocation());
        }
    }

protected static void checkOnlyOneOfElements ( XMLExtendedStreamReader reader , Set < Element > seen , Element element1 , Element element2 ) throws XMLStreamException { if ( ! seen . contains ( element1 ) && ! seen . contains ( element2 ) ) { throw new XMLStreamException ( MessagingLogger . ROOT_LOGGER . required ( element1 . getLocalName ( ) , element2 . getLocalName ( ) ) , reader . getLocation ( ) ) ; } if ( seen . contains ( element1 ) && seen . contains ( element2 ) ) { throw new XMLStreamException ( MessagingLogger . ROOT_LOGGER . onlyOneRequired ( element1 . getLocalName ( ) , element2 . getLocalName ( ) ) , reader . getLocation ( ) ) ; } }

Check one and only one of the 2 elements has been defined


protected static Class<?> getType(ConfigVisitor visitor, String className) {
        if (className != null) {
            try {
                return visitor.getModule().getClassLoader().loadClass(className);
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
        }
        return null;
    }

protected static Class < ? > getType ( ConfigVisitor visitor , String className ) { if ( className != null ) { try { return visitor . getModule ( ) . getClassLoader ( ) . loadClass ( className ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } } return null ; }

Load class.

@param visitor   the visitor
@param className the class name
@return class or null if null class name


static Type getComponentType(ParameterizedType type, int index) {
        Type[] tp = type.getActualTypeArguments();
        if (index + 1 > tp.length)
            return null;

        return tp[index];
    }

static Type getComponentType ( ParameterizedType type , int index ) { Type [ ] tp = type . getActualTypeArguments ( ) ; if ( index + 1 > tp . length ) return null ; return tp [ index ] ; }

Get component type.

@param type the type
@param index the component index
@return component's class or null if cannot be determined


public static ResourceDefinition getElytronKeyStoreResourceDefinition() {
        final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
        final AbstractAddStepHandler addHandler = new BasicAddHandler<KeyStore>(attributes, KEY_STORE_RUNTIME_CAPABILITY) {

            @Override
            protected BasicService.ValueSupplier<KeyStore> getValueSupplier(ServiceBuilder<KeyStore> serviceBuilder, OperationContext context, ModelNode model) throws OperationFailedException {
                final String legacyJSSEConfig = asStringIfDefined(context, LEGACY_JSSE_CONFIG, model);
                final InjectedValue<SecurityDomainContext> securityDomainContextInjector = new InjectedValue<>();
                if (legacyJSSEConfig != null) {
                    serviceBuilder.addDependency(SecurityDomainService.SERVICE_NAME.append(legacyJSSEConfig), SecurityDomainContext.class, securityDomainContextInjector);
                }

                return () -> {
                    final SecurityDomainContext domainContext = securityDomainContextInjector.getValue();
                    final JSSESecurityDomain jsseDomain = domainContext.getJSSE();
                    if (jsseDomain == null) {
                        throw SecurityLogger.ROOT_LOGGER.unableToLocateJSSEConfig(legacyJSSEConfig);
                    }
                    final KeyStore keyStore = jsseDomain.getKeyStore();
                    if (keyStore == null) {
                        throw SecurityLogger.ROOT_LOGGER.unableToLocateComponentInJSSEDomain("KeyStore", legacyJSSEConfig);
                    }
                    return keyStore;
                };
            }
        };

        return new BasicResourceDefinition(Constants.ELYTRON_KEY_STORE, addHandler, attributes, KEY_STORE_RUNTIME_CAPABILITY);
    }

public static ResourceDefinition getElytronKeyStoreResourceDefinition ( ) { final AttributeDefinition [ ] attributes = new AttributeDefinition [ ] { LEGACY_JSSE_CONFIG } ; final AbstractAddStepHandler addHandler = new BasicAddHandler < KeyStore > ( attributes , KEY_STORE_RUNTIME_CAPABILITY ) { @ Override protected BasicService . ValueSupplier < KeyStore > getValueSupplier ( ServiceBuilder < KeyStore > serviceBuilder , OperationContext context , ModelNode model ) throws OperationFailedException { final String legacyJSSEConfig = asStringIfDefined ( context , LEGACY_JSSE_CONFIG , model ) ; final InjectedValue < SecurityDomainContext > securityDomainContextInjector = new InjectedValue <> ( ) ; if ( legacyJSSEConfig != null ) { serviceBuilder . addDependency ( SecurityDomainService . SERVICE_NAME . append ( legacyJSSEConfig ) , SecurityDomainContext . class , securityDomainContextInjector ) ; } return ( ) -> { final SecurityDomainContext domainContext = securityDomainContextInjector . getValue ( ) ; final JSSESecurityDomain jsseDomain = domainContext . getJSSE ( ) ; if ( jsseDomain == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateJSSEConfig ( legacyJSSEConfig ) ; } final KeyStore keyStore = jsseDomain . getKeyStore ( ) ; if ( keyStore == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateComponentInJSSEDomain ( "KeyStore" , legacyJSSEConfig ) ; } return keyStore ; } ; } } ; return new BasicResourceDefinition ( Constants . ELYTRON_KEY_STORE , addHandler , attributes , KEY_STORE_RUNTIME_CAPABILITY ) ; }

Defines a resource that represents an Elytron-compatible key store that can be exported by a JSSE-enabled domain
in the legacy security subsystem.

To export the key store the resource uses a {@code BasicAddHandler} implementation that registers the elytron key-store
capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses the injected
{@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its configured key
store is obtained and returned.

The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
domain or if the domain doesn't contain a key store configuration.

Defines a resource that represents an Elytron - compatible key store that can be exported by a JSSE - enabled domain in the legacy security subsystem .


public static ResourceDefinition getElytronKeyManagersResourceDefinition() {
        final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
        final AbstractAddStepHandler addHandler = new BasicAddHandler<KeyManager>(attributes, KEY_MANAGER_RUNTIME_CAPABILITY) {

            @Override
            protected BasicService.ValueSupplier<KeyManager> getValueSupplier(ServiceBuilder<KeyManager> serviceBuilder, OperationContext context, ModelNode model) throws OperationFailedException {
                final String legacyJSSEConfig = asStringIfDefined(context, LEGACY_JSSE_CONFIG, model);
                final InjectedValue<SecurityDomainContext> securityDomainContextInjector = new InjectedValue<>();
                if (legacyJSSEConfig != null) {
                    serviceBuilder.addDependency(SecurityDomainService.SERVICE_NAME.append(legacyJSSEConfig), SecurityDomainContext.class, securityDomainContextInjector);
                }

                return () -> {
                    final SecurityDomainContext domainContext = securityDomainContextInjector.getValue();
                    final JSSESecurityDomain jsseDomain = domainContext.getJSSE();
                    if (jsseDomain == null) {
                        throw SecurityLogger.ROOT_LOGGER.unableToLocateJSSEConfig(legacyJSSEConfig);
                    }
                    final KeyManager[] keyManagers = jsseDomain.getKeyManagers();
                    if (keyManagers == null) {
                        throw SecurityLogger.ROOT_LOGGER.unableToLocateComponentInJSSEDomain("KeyManager", legacyJSSEConfig);
                    }
                    for (KeyManager keyManager : keyManagers) {
                        if (keyManager instanceof X509ExtendedKeyManager) {
                            return keyManager;
                        }
                    }
                    throw SecurityLogger.ROOT_LOGGER.expectedManagerTypeNotFound("KeyManager", X509ExtendedKeyManager.class.getSimpleName(), legacyJSSEConfig);
                };
            }
        };

        return new BasicResourceDefinition(Constants.ELYTRON_KEY_MANAGER, addHandler, attributes, KEY_MANAGER_RUNTIME_CAPABILITY);
    }

public static ResourceDefinition getElytronKeyManagersResourceDefinition ( ) { final AttributeDefinition [ ] attributes = new AttributeDefinition [ ] { LEGACY_JSSE_CONFIG } ; final AbstractAddStepHandler addHandler = new BasicAddHandler < KeyManager > ( attributes , KEY_MANAGER_RUNTIME_CAPABILITY ) { @ Override protected BasicService . ValueSupplier < KeyManager > getValueSupplier ( ServiceBuilder < KeyManager > serviceBuilder , OperationContext context , ModelNode model ) throws OperationFailedException { final String legacyJSSEConfig = asStringIfDefined ( context , LEGACY_JSSE_CONFIG , model ) ; final InjectedValue < SecurityDomainContext > securityDomainContextInjector = new InjectedValue <> ( ) ; if ( legacyJSSEConfig != null ) { serviceBuilder . addDependency ( SecurityDomainService . SERVICE_NAME . append ( legacyJSSEConfig ) , SecurityDomainContext . class , securityDomainContextInjector ) ; } return ( ) -> { final SecurityDomainContext domainContext = securityDomainContextInjector . getValue ( ) ; final JSSESecurityDomain jsseDomain = domainContext . getJSSE ( ) ; if ( jsseDomain == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateJSSEConfig ( legacyJSSEConfig ) ; } final KeyManager [ ] keyManagers = jsseDomain . getKeyManagers ( ) ; if ( keyManagers == null ) { throw SecurityLogger . ROOT_LOGGER . unableToLocateComponentInJSSEDomain ( "KeyManager" , legacyJSSEConfig ) ; } for ( KeyManager keyManager : keyManagers ) { if ( keyManager instanceof X509ExtendedKeyManager ) { return keyManager ; } } throw SecurityLogger . ROOT_LOGGER . expectedManagerTypeNotFound ( "KeyManager" , X509ExtendedKeyManager . class . getSimpleName ( ) , legacyJSSEConfig ) ; } ; } } ; return new BasicResourceDefinition ( Constants . ELYTRON_KEY_MANAGER , addHandler , attributes , KEY_MANAGER_RUNTIME_CAPABILITY ) ; }

Defines a resource that represents Elytron-compatible key managers that can be exported by a JSSE-enabled domain
in the legacy security subsystem.

To export the key managers the resource uses a {@code BasicAddHandler} implementation that registers the elytron
key-managers capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses
the injected {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its
configured key manager array is obtained and returned.

The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
domain or if the domain doesn't contain a key store configuration that can be used to build the key managers.

Defines a resource that represents Elytron - compatible key managers that can be exported by a JSSE - enabled domain in the legacy security subsystem .


public static ResourceDefinition getElytronTrustManagersResourceDefinition() {
        final AttributeDefinition[] attributes = new AttributeDefinition[] {LEGACY_JSSE_CONFIG};
        final AbstractAddStepHandler addHandler = new BasicAddHandler<TrustManager>(attributes, TRUST_MANAGER_RUNTIME_CAPABILITY) {

            @Override
            protected BasicService.ValueSupplier<TrustManager> getValueSupplier(ServiceBuilder<TrustManager> serviceBuilder, OperationContext context, ModelNode model) throws OperationFailedException {
                final String legacyJSSEConfig = asStringIfDefined(context, LEGACY_JSSE_CONFIG, model);
                final InjectedValue<SecurityDomainContext> securityDomainContextInjector = new InjectedValue<>();
                if (legacyJSSEConfig != null) {
                    serviceBuilder.addDependency(SecurityDomainService.SERVICE_NAME.append(legacyJSSEConfig), SecurityDomainContext.class, securityDomainContextInjector);
                }

                return () -> {
                    final SecurityDomainContext domainContext = securityDomainContextInjector.getValue();
                    final JSSESecurityDomain jsseDomain = domainContext.getJSSE();
                    if (jsseDomain == null) {
                        throw SecurityLogger.ROOT_LOGGER.unableToLocateJSSEConfig(legacyJSSEConfig);
                    }
                    final TrustManager[] trustManagers = jsseDomain.getTrustManagers();
                    if (trustManagers == null) {
                        throw SecurityLogger.ROOT_LOGGER.unableToLocateComponentInJSSEDomain("TrustManager", legacyJSSEConfig);
                    }
                    for (TrustManager trustManager : trustManagers) {
                        if (trustManager instanceof X509ExtendedTrustManager)
                            return trustManager;
                    }
                    throw SecurityLogger.ROOT_LOGGER.expectedManagerTypeNotFound("TrustManager", X509ExtendedTrustManager.class.getSimpleName(), legacyJSSEConfig);
                };
            }
        };

        return new BasicResourceDefinition(Constants.ELYTRON_TRUST_MANAGER, addHandler, attributes, TRUST_MANAGER_RUNTIME_CAPABILITY);
    }

Defines a resource that represents Elytron-compatible trust managers that can be exported by a JSSE-enabled domain
in the legacy security subsystem.

To export the trust managers the resource uses a {@code BasicAddHandler} implementation that registers the elytron
trust-managers capability and implements a {@code org.jboss.as.security.elytron.BasicService.ValueSupplier} that uses
the injected {@code SecurityDomainContext} to obtain a {@code JSSESecurityDomain}. If such domain is found, its
configured trust manager array is obtained and returned.

The {@code ValueSupplier} implementation throws an exception if the referenced legacy domain is not a JSSE-enabled
domain or if the domain doesn't contain a trust store configuration that can be used to build the trust managers.

NOTE: The {@code PicketBox} implementation of a {@code JSSESecurityDomain} returns a reference to the key store if
a trust store was not configured. This means that the trust managers that it builds will use the configured key store
instead of throwing an exception to alert about a missing trust store configuration. So extra care must be taken
to ensure that the exported trust managers are being built using the correct trust stores.

Defines a resource that represents Elytron - compatible trust managers that can be exported by a JSSE - enabled domain in the legacy security subsystem .


public Name parse(String name) throws NamingException {
        Vector comps = insStringToStringifiedComps(name);
        return new CNCompoundName(comps.elements());
    }

public Name parse ( String name ) throws NamingException { Vector comps = insStringToStringifiedComps ( name ) ; return new CNCompoundName ( comps . elements ( ) ) ; }

Returns a CompoundName given a string in INS syntax.

@param name The non-null string representation of the name.
@return a non-null CompoundName

Returns a CompoundName given a string in INS syntax .


private static Vector insStringToStringifiedComps(String str)
            throws InvalidNameException {

        int len = str.length();
        Vector components = new Vector(10);
        char[] id = new char[len];
        char[] kind = new char[len];
        int idCount, kindCount;
        boolean idMode;
        for (int i = 0; i < len; ) {
            idCount = kindCount = 0; // reset for new component
            idMode = true;           // always start off parsing id
            while (i < len) {
                if (str.charAt(i) == compSeparator) {
                    break;

                } else if (str.charAt(i) == escapeChar) {
                    if (i + 1 >= len) {
                        throw IIOPLogger.ROOT_LOGGER.unescapedCharacter(str);
                    } else if (isMeta(str.charAt(i + 1))) {
                        ++i; // skip escape and let meta through
                        if (idMode) {
                            id[idCount++] = str.charAt(i++);
                        } else {
                            kind[kindCount++] = str.charAt(i++);
                        }
                    } else {
                        throw IIOPLogger.ROOT_LOGGER.invalidEscapedCharacter(str);
                    }

                } else if (idMode && str.charAt(i) == kindSeparator) {
                    // just look for the first kindSeparator
                    ++i; // skip kind separator
                    idMode = false;

                } else {
                    if (idMode) {
                        id[idCount++] = str.charAt(i++);
                    } else {
                        kind[kindCount++] = str.charAt(i++);
                    }
                }
            }
            components.addElement(stringifyComponent(
                    new NameComponent(new String(id, 0, idCount),
                            new String(kind, 0, kindCount))));

            if (i < len) {
                ++i; // skip separator
            }
        }

        return components;
    }

Converts an INS-syntax string name into a Vector in which
each element of the vector contains a stringified form of
a NameComponent.

Converts an INS - syntax string name into a Vector in which each element of the vector contains a stringified form of a NameComponent .


private static NameComponent parseComponent(String compStr)
            throws InvalidNameException {
        NameComponent comp = new NameComponent();
        int kindSep = -1;
        int len = compStr.length();

        int j = 0;
        char[] newStr = new char[len];
        boolean escaped = false;

        // Find the kind separator
        for (int i = 0; i < len && kindSep < 0; i++) {
            if (escaped) {
                newStr[j++] = compStr.charAt(i);
                escaped = false;
            } else if (compStr.charAt(i) == escapeChar) {
                if (i + 1 >= len) {
                    throw IIOPLogger.ROOT_LOGGER.unescapedCharacter(compStr);
                } else if (isMeta(compStr.charAt(i + 1))) {
                    escaped = true;
                } else {
                    throw IIOPLogger.ROOT_LOGGER.invalidEscapedCharacter(compStr);
                }
            } else if (compStr.charAt(i) == kindSeparator) {
                kindSep = i;
            } else {
                newStr[j++] = compStr.charAt(i);
            }
        }

        // Set id
        comp.id = new String(newStr, 0, j);

        // Set kind
        if (kindSep < 0) {
            comp.kind = "";  // no kind separator
        } else {
            // unescape kind
            j = 0;
            escaped = false;
            for (int i = kindSep + 1; i < len; i++) {
                if (escaped) {
                    newStr[j++] = compStr.charAt(i);
                    escaped = false;
                } else if (compStr.charAt(i) == escapeChar) {
                    if (i + 1 >= len) {
                        throw IIOPLogger.ROOT_LOGGER.unescapedCharacter(compStr);
                    } else if (isMeta(compStr.charAt(i + 1))) {
                        escaped = true;
                    } else {
                        throw IIOPLogger.ROOT_LOGGER.invalidEscapedCharacter(compStr);
                    }
                } else {
                    newStr[j++] = compStr.charAt(i);
                }
            }
            comp.kind = new String(newStr, 0, j);
        }
        return comp;
    }

private
static
NameComponent
parseComponent
(
String
compStr
)
throws
InvalidNameException
{
NameComponent
comp
=
new
NameComponent
(
)
;
int
kindSep
=
1
;
int
len
=
compStr
.
length
(
)
;
int
j
=
0
;
char
[
]
newStr
=
new
char
[
len
]
;
boolean
escaped
=
false
;
// Find the kind separator
for
(
int
i
=
0
;
i
<
len
&&
kindSep
<
0
;
i
++
)
{
if
(
escaped
)
{
newStr
[
j
++
]
=
compStr
.
charAt
(
i
)
;
escaped
=
false
;
}
else
if
(
compStr
.
charAt
(
i
)
==
escapeChar
)
{
if
(
i
+
1
>=
len
)
{
throw
IIOPLogger
.
ROOT_LOGGER
.
unescapedCharacter
(
compStr
)
;
}
else
if
(
isMeta
(
compStr
.
charAt
(
i
+
1
)
)
)
{
escaped
=
true
;
}
else
{
throw
IIOPLogger
.
ROOT_LOGGER
.
invalidEscapedCharacter
(
compStr
)
;
}
}
else
if
(
compStr
.
charAt
(
i
)
==
kindSeparator
)
{
kindSep
=
i
;
}
else
{
newStr
[
j
++
]
=
compStr
.
charAt
(
i
)
;
}
}
// Set id
comp
.
id
=
new
String
(
newStr
,
0
,
j
)
;
// Set kind
if
(
kindSep
<
0
)
{
comp
.
kind
=
""
;
// no kind separator
}
else
{
// unescape kind
j
=
0
;
escaped
=
false
;
for
(
int
i
=
kindSep
+
1
;
i
<
len
;
i
++
)
{
if
(
escaped
)
{
newStr
[
j
++
]
=
compStr
.
charAt
(
i
)
;
escaped
=
false
;
}
else
if
(
compStr
.
charAt
(
i
)
==
escapeChar
)
{
if
(
i
+
1
>=
len
)
{
throw
IIOPLogger
.
ROOT_LOGGER
.
unescapedCharacter
(
compStr
)
;
}
else
if
(
isMeta
(
compStr
.
charAt
(
i
+
1
)
)
)
{
escaped
=
true
;
}
else
{
throw
IIOPLogger
.
ROOT_LOGGER
.
invalidEscapedCharacter
(
compStr
)
;
}
}
else
{
newStr
[
j
++
]
=
compStr
.
charAt
(
i
)
;
}
}
comp
.
kind
=
new
String
(
newStr
,
0
,
j
)
;
}
return
comp
;
}

Return a NameComponent given its stringified form.

Return a NameComponent given its stringified form .


public void shutdown() {
        POA poa = getPOA();
        try {
            poa.deactivate_object(poa.reference_to_id(getReference()));
        } catch (UserException ex) {
            IIOPLogger.ROOT_LOGGER.warnCouldNotDeactivateIRObject(ex);
        }
    }

public void shutdown ( ) { POA poa = getPOA ( ) ; try { poa . deactivate_object ( poa . reference_to_id ( getReference ( ) ) ) ; } catch ( UserException ex ) { IIOPLogger . ROOT_LOGGER . warnCouldNotDeactivateIRObject ( ex ) ; } }


protected org.omg.CORBA.Object servantToReference(Servant servant) {
        byte[] id = getObjectId();

        try {
            repository.poa.activate_object_with_id(id, servant);
            org.omg.CORBA.Object ref = repository.poa.id_to_reference(id);
            return ref;
        } catch (WrongPolicy ex) {
            IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex);
        } catch (ServantAlreadyActive ex) {
            IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex);
        } catch (ObjectAlreadyActive ex) {
            IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex);
        } catch (ObjectNotActive ex) {
            IIOPLogger.ROOT_LOGGER.debug("Exception converting CORBA servant to reference", ex);
        }
        return null;
    }


private SecurityIdentity authenticate(final String username, final String password) {

        ServerAuthenticationContext context = this.securityDomain.createNewAuthenticationContext();
        PasswordGuessEvidence evidence = null;
        try {
            if (password == null) {
                if (username == null) {
                    if (context.authorizeAnonymous()) {
                        context.succeed();
                        return context.getAuthorizedIdentity();
                    } else {
                        context.fail();
                        return null;
                    }
                } else {
                    // treat a non-null user name with a null password as a auth failure
                    context.fail();
                    return null;
                }
            }

            context.setAuthenticationName(username);
            evidence = new PasswordGuessEvidence(password.toCharArray());
            if (context.verifyEvidence(evidence)) {
                if (context.authorize()) {
                    context.succeed();
                    return context.getAuthorizedIdentity();
                }
                else {
                    context.fail();
                    MessagingLogger.ROOT_LOGGER.failedAuthorization(username);
                }
            } else {
                context.fail();
                MessagingLogger.ROOT_LOGGER.failedAuthentication(username);
            }
        } catch (IllegalArgumentException | IllegalStateException | RealmUnavailableException e) {
            context.fail();
            MessagingLogger.ROOT_LOGGER.failedAuthenticationWithException(e, username, e.getMessage());
        } finally {
            if (evidence != null) {
                evidence.destroy();
            }
        }
        return null;
    }

Attempt to authenticate and authorize an username with the specified password evidence.

@param username the username being authenticated.
@param password the password to be verified.
@return a reference to the {@link SecurityIdentity} if the user was successfully authenticated and authorized;
{@code null} otherwise.

Attempt to authenticate and authorize an username with the specified password evidence .


private static boolean isTypeMatched(Class<?> clz) {
        if (clz.equals(String.class)) {
            return true;
        } else if (clz.equals(byte.class) || clz.equals(Byte.class)) {
            return true;
        } else if (clz.equals(short.class) || clz.equals(Short.class)) {
            return true;
        } else if (clz.equals(int.class) || clz.equals(Integer.class)) {
            return true;
        } else if (clz.equals(long.class) || clz.equals(Long.class)) {
            return true;
        } else if (clz.equals(float.class) || clz.equals(Float.class)) {
            return true;
        } else if (clz.equals(double.class) || clz.equals(Double.class)) {
            return true;
        } else if (clz.equals(boolean.class) || clz.equals(Boolean.class)) {
            return true;
        } else if (clz.equals(char.class) || clz.equals(Character.class)) {
            return true;
        } else if (clz.equals(InetAddress.class)) {
            return true;
        } else if (clz.equals(Class.class)) {
            return true;
        } else if (clz.equals(Properties.class)) {
            return true;
        }
        return false;
    }

private static boolean isTypeMatched ( Class < ? > clz ) { if ( clz . equals ( String . class ) ) { return true ; } else if ( clz . equals ( byte . class ) || clz . equals ( Byte . class ) ) { return true ; } else if ( clz . equals ( short . class ) || clz . equals ( Short . class ) ) { return true ; } else if ( clz . equals ( int . class ) || clz . equals ( Integer . class ) ) { return true ; } else if ( clz . equals ( long . class ) || clz . equals ( Long . class ) ) { return true ; } else if ( clz . equals ( float . class ) || clz . equals ( Float . class ) ) { return true ; } else if ( clz . equals ( double . class ) || clz . equals ( Double . class ) ) { return true ; } else if ( clz . equals ( boolean . class ) || clz . equals ( Boolean . class ) ) { return true ; } else if ( clz . equals ( char . class ) || clz . equals ( Character . class ) ) { return true ; } else if ( clz . equals ( InetAddress . class ) ) { return true ; } else if ( clz . equals ( Class . class ) ) { return true ; } else if ( clz . equals ( Properties . class ) ) { return true ; } return false ; }

Check whether the types that JCA Injection knows.

@see Injection.findMethod()
@param clz the class
@return whether it is understandable

Check whether the types that JCA Injection knows .


@Override
    public Object lookup(String name) {
        final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
        ServiceController<?> bindingService = container.getService(bindInfo.getBinderServiceName());
        if (bindingService == null) {
            return null;
        }
        ManagedReferenceFactory managedReferenceFactory = ManagedReferenceFactory.class.cast(bindingService.getValue());
        return managedReferenceFactory.getReference().getInstance();
    }

@ Override public Object lookup ( String name ) { final ContextNames . BindInfo bindInfo = ContextNames . bindInfoFor ( name ) ; ServiceController < ? > bindingService = container . getService ( bindInfo . getBinderServiceName ( ) ) ; if ( bindingService == null ) { return null ; } ManagedReferenceFactory managedReferenceFactory = ManagedReferenceFactory . class . cast ( bindingService . getValue ( ) ) ; return managedReferenceFactory . getReference ( ) . getInstance ( ) ; }


@Override
    public void unbind(String name) {
        if (name == null || name.isEmpty()) {
            throw MessagingLogger.ROOT_LOGGER.cannotUnbindJndiName();
        }
        final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(name);
        ServiceController<?> bindingService = container.getService(bindInfo.getBinderServiceName());
        if (bindingService == null) {
            ROOT_LOGGER.debugf("Cannot unbind %s since no binding exists with that name", name);
            return;
        }
        // remove the binding service
        bindingService.setMode(ServiceController.Mode.REMOVE);
        final StabilityMonitor monitor = new StabilityMonitor();
        monitor.addController(bindingService);
        try {
            monitor.awaitStability();
            ROOT_LOGGER.unboundJndiName(bindInfo.getAbsoluteJndiName());
        } catch (InterruptedException e) {
            ROOT_LOGGER.failedToUnbindJndiName(name, 5, SECONDS.toString().toLowerCase(Locale.US));
        } finally {
            monitor.removeController(bindingService);
        }
    }

Unbind the resource and wait until the corresponding binding service is effectively removed.

Unbind the resource and wait until the corresponding binding service is effectively removed .


public static Object instantiateBean(BeanMetaDataConfig beanConfig, BeanInfo beanInfo, DeploymentReflectionIndex index, Module module) throws Throwable {
        Joinpoint instantiateJoinpoint = null;
        ValueConfig[] parameters = new ValueConfig[0];
        String[] types = Configurator.NO_PARAMS_TYPES;
        ConstructorConfig ctorConfig = beanConfig.getConstructor();
        if (ctorConfig != null) {
            parameters = ctorConfig.getParameters();
            types = Configurator.getTypes(parameters);

            String factoryClass = ctorConfig.getFactoryClass();
            FactoryConfig factory = ctorConfig.getFactory();
            if (factoryClass != null || factory != null) {
                String factoryMethod = ctorConfig.getFactoryMethod();
                if (factoryMethod == null)
                    throw PojoLogger.ROOT_LOGGER.missingFactoryMethod(beanConfig);

                if (factoryClass != null) {
                    // static factory
                    Class<?> factoryClazz = Class.forName(factoryClass, false, module.getClassLoader());
                    Method method = Configurator.findMethod(index, factoryClazz, factoryMethod, types, true, true, true);
                    MethodJoinpoint mj = new MethodJoinpoint(method);
                    mj.setTarget(new ImmediateValue<Object>(null)); // null, since this is static call
                    mj.setParameters(parameters);
                    instantiateJoinpoint = mj;
                } else if (factory != null) {
                    ReflectionJoinpoint rj = new ReflectionJoinpoint(factory.getBeanInfo(), factoryMethod, types);
                    // null type is ok, as this should be plain injection
                    rj.setTarget(new ImmediateValue<Object>(factory.getValue(null)));
                    rj.setParameters(parameters);
                    instantiateJoinpoint = rj;
                }
            }
        }
        // plain bean's ctor
        if (instantiateJoinpoint == null) {
            if (beanInfo == null)
                throw new StartException(PojoLogger.ROOT_LOGGER.missingBeanInfo(beanConfig));

            Constructor ctor = (types.length == 0) ? beanInfo.getConstructor() : beanInfo.findConstructor(types);
            ConstructorJoinpoint constructorJoinpoint = new ConstructorJoinpoint(ctor);
            constructorJoinpoint.setParameters(parameters);
            instantiateJoinpoint = constructorJoinpoint;
        }

        return instantiateJoinpoint.dispatch();
    }

Instantiate bean.

@param beanConfig the bean metadata config, must not be null
@param beanInfo the bean info, can be null if enough info
@param index the reflection index, must not be null
@param module the current CL module, must not be null
@return new bean instance
@throws Throwable for any error


public static void configure(BeanMetaDataConfig beanConfig, BeanInfo beanInfo, Module module, Object bean, boolean nullify) throws Throwable {
        Set<PropertyConfig> properties = beanConfig.getProperties();
        if (properties != null) {
            List<PropertyConfig> used = new ArrayList<PropertyConfig>();
            for (PropertyConfig pc : properties) {
                try {
                    configure(beanInfo, module, bean, pc, nullify);
                    used.add(pc);
                } catch (Throwable t) {
                    if (nullify == false) {
                        for (PropertyConfig upc : used) {
                            try {
                                configure(beanInfo, module, bean,upc, true);
                            } catch (Throwable ignored) {
                            }
                        }
                        throw new StartException(t);
                    }
                }
            }
        }
    }

public static void configure ( BeanMetaDataConfig beanConfig , BeanInfo beanInfo , Module module , Object bean , boolean nullify ) throws Throwable { Set < PropertyConfig > properties = beanConfig . getProperties ( ) ; if ( properties != null ) { List < PropertyConfig > used = new ArrayList < PropertyConfig > ( ) ; for ( PropertyConfig pc : properties ) { try { configure ( beanInfo , module , bean , pc , nullify ) ; used . add ( pc ) ; } catch ( Throwable t ) { if ( nullify == false ) { for ( PropertyConfig upc : used ) { try { configure ( beanInfo , module , bean , upc , true ) ; } catch ( Throwable ignored ) { } } throw new StartException ( t ) ; } } } } }

Configure bean.

@param beanConfig the bean metadata config, must not be null
@param beanInfo the bean info, can be null if enough info
@param module the current CL module, must not be null
@param bean the bean instance
@param nullify do we nullify property
@throws Throwable for any error


public static void dispatchLifecycleJoinpoint(BeanInfo beanInfo, Object bean, LifecycleConfig config, String defaultMethod) throws Throwable {
        if (config != null && config.isIgnored())
            return;

        Joinpoint joinpoint = createJoinpoint(beanInfo, bean, config, defaultMethod);
        if (joinpoint != null)
            joinpoint.dispatch();
    }

public static void dispatchLifecycleJoinpoint ( BeanInfo beanInfo , Object bean , LifecycleConfig config , String defaultMethod ) throws Throwable { if ( config != null && config . isIgnored ( ) ) return ; Joinpoint joinpoint = createJoinpoint ( beanInfo , bean , config , defaultMethod ) ; if ( joinpoint != null ) joinpoint . dispatch ( ) ; }

Dispatch lifecycle joinpoint.

@param beanInfo the bean info
@param bean the bean instance
@param config the lifecycle config
@param defaultMethod the default method
@throws Throwable for any error


public static NamespaceContextSelector getCurrentSelector() {
        NamespaceContextSelector selector = currentSelector.peek();
        if(selector != null) {
            return selector;
        }
        return defaultSelector;
    }

public static NamespaceContextSelector getCurrentSelector ( ) { NamespaceContextSelector selector = currentSelector . peek ( ) ; if ( selector != null ) { return selector ; } return defaultSelector ; }

Get the current context selector for the current thread.

@return The current context selector.

Get the current context selector for the current thread .


public static ServiceName toBeanName(String name, BeanState state) {
        if (state == null)
            state = BeanState.INSTALLED;

        return JBOSS_POJO.append(name).append(state.name());
    }

public static ServiceName toBeanName ( String name , BeanState state ) { if ( state == null ) state = BeanState . INSTALLED ; return JBOSS_POJO . append ( name ) . append ( state . name ( ) ) ; }

Get MC bean name.

@param name the original bean name
@param state the state
@return bean service name


public static ServiceName toInstancesName(Class<?> clazz, BeanState state) {
        String clName;
        ClassLoader classLoader = clazz.getClassLoader();
        if (classLoader != null)
            clName = classLoader.toString();
        else
            clName = "SystemClassLoader";

        if (state == null)
            state = BeanState.INSTALLED;

        return JBOSS_POJO.append(clName, clazz.getName(), state.name());
    }

public static ServiceName toInstancesName ( Class < ? > clazz , BeanState state ) { String clName ; ClassLoader classLoader = clazz . getClassLoader ( ) ; if ( classLoader != null ) clName = classLoader . toString ( ) ; else clName = "SystemClassLoader" ; if ( state == null ) state = BeanState . INSTALLED ; return JBOSS_POJO . append ( clName , clazz . getName ( ) , state . name ( ) ) ; }

To instances name.

@param clazz the class
@param state the bean state
@return unique instance name


public EEModuleClassDescription getClassByName(String name) {
        for(EEModuleDescription module : availableModules) {
            final EEModuleClassDescription desc = module.getClassDescription(name);
            if(desc != null) {
                return desc;
            }
        }
        return null;
    }

public EEModuleClassDescription getClassByName ( String name ) { for ( EEModuleDescription module : availableModules ) { final EEModuleClassDescription desc = module . getClassDescription ( name ) ; if ( desc != null ) { return desc ; } } return null ; }

Look for a class description in all available modules.
@param name The class to lookup
@return

Look for a class description in all available modules .


@Override
    protected void processAnnotations(final DeploymentUnit deploymentUnit, final CompositeIndex compositeIndex) throws DeploymentUnitProcessingException {

        if (MetadataCompleteMarker.isMetadataComplete(deploymentUnit)) {
            return;
        }

        // Find and process any @Stateless bean annotations
        final List<AnnotationInstance> slsbAnnotations = compositeIndex.getAnnotations(STATELESS_ANNOTATION);
        if (!slsbAnnotations.isEmpty()) {
            processSessionBeans(deploymentUnit, slsbAnnotations, SessionBeanComponentDescription.SessionBeanType.STATELESS);
        }

        // Find and process any @Stateful bean annotations
        final List<AnnotationInstance> sfsbAnnotations = compositeIndex.getAnnotations(STATEFUL_ANNOTATION);
        if (!sfsbAnnotations.isEmpty()) {
            processSessionBeans(deploymentUnit, sfsbAnnotations, SessionBeanComponentDescription.SessionBeanType.STATEFUL);
        }

        // Find and process any @Singleton bean annotations
        final List<AnnotationInstance> sbAnnotations = compositeIndex.getAnnotations(SINGLETON_ANNOTATION);
        if (!sbAnnotations.isEmpty()) {
            processSessionBeans(deploymentUnit, sbAnnotations, SessionBeanComponentDescription.SessionBeanType.SINGLETON);
        }
    }

Process annotations and merge any available metadata at the same time.

Process annotations and merge any available metadata at the same time .


private void postParseSteps(
        final VirtualFile persistence_xml,
        final PersistenceUnitMetadataHolder puHolder,
        final DeploymentUnit deploymentUnit ) {

        for (PersistenceUnitMetadata pu : puHolder.getPersistenceUnits()) {
            // set URLs
            List<URL> jarfilesUrls = new ArrayList<URL>();
            if (pu.getJarFiles() != null) {
                for (String jar : pu.getJarFiles()) {
                    jarfilesUrls.add(getRelativeURL(persistence_xml, jar));
                }
            }
            pu.setJarFileUrls(jarfilesUrls);
            URL url = getPersistenceUnitURL(persistence_xml);
            pu.setPersistenceUnitRootUrl(url);
            String scopedPersistenceUnitName;

            /**
             * WFLY-5478 allow custom scoped persistence unit name hint in persistence unit definition.
             * Specified scoped persistence unit name needs to be unique across application server deployments.
             * Application is responsible for picking a unique name.
             * Currently, a non-unique name will result in a DuplicateServiceException deployment failure:
             *   org.jboss.msc.service.DuplicateServiceException: Service jboss.persistenceunit.my2lccustom#test_pu.__FIRST_PHASE__ is already registered
             */
            scopedPersistenceUnitName = Configuration.getScopedPersistenceUnitName(pu);
            if (scopedPersistenceUnitName == null) {
                scopedPersistenceUnitName = createBeanName(deploymentUnit, pu.getPersistenceUnitName());
            } else {
                ROOT_LOGGER.tracef("persistence unit '%s' specified a custom scoped persistence unit name hint " +
                        "(jboss.as.jpa.scopedname=%s).  The specified name *must* be unique across all application server deployments.",
                        pu.getPersistenceUnitName(),
                        scopedPersistenceUnitName);
                if (scopedPersistenceUnitName.indexOf('/') != -1) {
                    throw JpaLogger.ROOT_LOGGER.invalidScopedName(scopedPersistenceUnitName, '/');
                }
            }

            pu.setScopedPersistenceUnitName(scopedPersistenceUnitName);
        }
    }

Some of this might need to move to the install phase

@param persistence_xml
@param puHolder


public static String validateDescriptor(String descriptor) {
        if (descriptor.length() == 0) {
            throw EeLogger.ROOT_LOGGER.cannotBeEmpty("descriptors");
        }
        if (descriptor.length() > 1) {
            if (descriptor.startsWith("L")) {
                if (!descriptor.endsWith(";")) {
                    throw EeLogger.ROOT_LOGGER.invalidDescriptor(descriptor);
                }
            } else if (descriptor.startsWith("[")) {

            } else {
                    throw EeLogger.ROOT_LOGGER.invalidDescriptor(descriptor);
            }
        } else {
            char type = descriptor.charAt(0);
            switch (type) {
                case 'I':
                case 'Z':
                case 'S':
                case 'B':
                case 'F':
                case 'D':
                case 'V':
                case 'J':
                case 'C':
                    break;
                default:
                    throw EeLogger.ROOT_LOGGER.invalidDescriptor(descriptor);
            }
        }
        return descriptor;
    }

public static String validateDescriptor ( String descriptor ) { if ( descriptor . length ( ) == 0 ) { throw EeLogger . ROOT_LOGGER . cannotBeEmpty ( "descriptors" ) ; } if ( descriptor . length ( ) > 1 ) { if ( descriptor . startsWith ( "L" ) ) { if ( ! descriptor . endsWith ( ";" ) ) { throw EeLogger . ROOT_LOGGER . invalidDescriptor ( descriptor ) ; } } else if ( descriptor . startsWith ( "[" ) ) { } else { throw EeLogger . ROOT_LOGGER . invalidDescriptor ( descriptor ) ; } } else { char type = descriptor . charAt ( 0 ) ; switch ( type ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : break ; default : throw EeLogger . ROOT_LOGGER . invalidDescriptor ( descriptor ) ; } } return descriptor ; }

performs basic validation on a descriptor


void create(final Deployment dep) {
        final DeploymentUnit unit = WSHelper.getRequiredAttachment(dep, DeploymentUnit.class);
        WarMetaData warMD = ASHelper.getOptionalAttachment(unit, WarMetaData.ATTACHMENT_KEY);
        JBossWebMetaData jbossWebMD = warMD != null ? warMD.getMergedJBossWebMetaData() : null;

        if (warMD == null) {
            warMD = new WarMetaData();
        }
        if (jbossWebMD == null) {
            jbossWebMD = new JBossWebMetaData();
            warMD.setMergedJBossWebMetaData(jbossWebMD);
            unit.putAttachment(WarMetaData.ATTACHMENT_KEY, warMD);
        }

        createWebAppDescriptor(dep, jbossWebMD);
        createJBossWebAppDescriptor(dep, jbossWebMD);

        dep.addAttachment(JBossWebMetaData.class, jbossWebMD);
    }

void create ( final Deployment dep ) { final DeploymentUnit unit = WSHelper . getRequiredAttachment ( dep , DeploymentUnit . class ) ; WarMetaData warMD = ASHelper . getOptionalAttachment ( unit , WarMetaData . ATTACHMENT_KEY ) ; JBossWebMetaData jbossWebMD = warMD != null ? warMD . getMergedJBossWebMetaData ( ) : null ; if ( warMD == null ) { warMD = new WarMetaData ( ) ; } if ( jbossWebMD == null ) { jbossWebMD = new JBossWebMetaData ( ) ; warMD . setMergedJBossWebMetaData ( jbossWebMD ) ; unit . putAttachment ( WarMetaData . ATTACHMENT_KEY , warMD ) ; } createWebAppDescriptor ( dep , jbossWebMD ) ; createJBossWebAppDescriptor ( dep , jbossWebMD ) ; dep . addAttachment ( JBossWebMetaData . class , jbossWebMD ) ; }

Creates web meta data for EJB deployments.

@param dep webservice deployment

Creates web meta data for EJB deployments .


private void createWebAppDescriptor(final Deployment dep, final JBossWebMetaData jbossWebMD) {
        WSLogger.ROOT_LOGGER.trace("Creating web.xml descriptor");
        createServlets(dep, jbossWebMD);
        createServletMappings(dep, jbossWebMD);
        createSecurityConstraints(dep, jbossWebMD);
        createLoginConfig(dep, jbossWebMD);
        createSecurityRoles(dep, jbossWebMD);
    }

private
void
createWebAppDescriptor
(
final
Deployment
dep
,
final
JBossWebMetaData
jbossWebMD
)
{
WSLogger
.
ROOT_LOGGER
.
trace
(
"Creating web.xml descriptor"
)
;
createServlets
(
dep
,
jbossWebMD
)
;
createServletMappings
(
dep
,
jbossWebMD
)
;
createSecurityConstraints
(
dep
,
jbossWebMD
)
;
createLoginConfig
(
dep
,
jbossWebMD
)
;
createSecurityRoles
(
dep
,
jbossWebMD
)
;
}

Creates web.xml descriptor meta data.

@param dep        webservice deployment
@param jbossWebMD jboss web meta data

Creates web . xml descriptor meta data .


private String getAuthMethod(final Deployment dep) {
        for (final Endpoint ejbEndpoint : dep.getService().getEndpoints()) {
            final String beanAuthMethod = ejb3SecurityAccessor.getAuthMethod(ejbEndpoint);
            final boolean hasBeanAuthMethod = beanAuthMethod != null;

            if (hasBeanAuthMethod) {
                // First found auth-method defines war
                // login-config/auth-method
                return beanAuthMethod;
            }
        }

        return null;
    }

private
String
getAuthMethod
(
final
Deployment
dep
)
{
for
(
final
Endpoint
ejbEndpoint
:
dep
.
getService
(
)
.
getEndpoints
(
)
)
{
final
String
beanAuthMethod
=
ejb3SecurityAccessor
.
getAuthMethod
(
ejbEndpoint
)
;
final
boolean
hasBeanAuthMethod
=
beanAuthMethod
!=
;
if
(
hasBeanAuthMethod
)
{
// First found auth-method defines war
// login-config/auth-method
return
beanAuthMethod
;
}
}
return
;
}

Returns deployment authentication method.

@param dep webservice deployment
@return deployment authentication method

Returns deployment authentication method .


public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

        final VirtualFile deploymentRoot = phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();

        if(deploymentRoot == null || !deploymentRoot.exists())
            return;

        VirtualFile serviceXmlFile = null;
        if(deploymentRoot.isDirectory()) {
            serviceXmlFile = deploymentRoot.getChild(SERVICE_DESCRIPTOR_PATH);
        } else if(deploymentRoot.getName().toLowerCase(Locale.ENGLISH).endsWith(SERVICE_DESCRIPTOR_SUFFIX)) {
            serviceXmlFile = deploymentRoot;
        }
        if(serviceXmlFile == null || !serviceXmlFile.exists())
            return;

        final XMLMapper xmlMapper = XMLMapper.Factory.create();
        final JBossServiceXmlDescriptorParser jBossServiceXmlDescriptorParser = new JBossServiceXmlDescriptorParser(JBossDescriptorPropertyReplacement.propertyReplacer(phaseContext.getDeploymentUnit()));
        xmlMapper.registerRootElement(new QName("urn:jboss:service:7.0", "server"), jBossServiceXmlDescriptorParser);
        xmlMapper.registerRootElement(new QName(null, "server"), jBossServiceXmlDescriptorParser);

        InputStream xmlStream = null;
        try {
            xmlStream = serviceXmlFile.openStream();
            final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlStream);
            final ParseResult<JBossServiceXmlDescriptor> result = new ParseResult<JBossServiceXmlDescriptor>();
            xmlMapper.parseDocument(result, reader);
            final JBossServiceXmlDescriptor xmlDescriptor = result.getResult();
            if(xmlDescriptor != null)
                phaseContext.getDeploymentUnit().putAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY, xmlDescriptor);
            else
                throw SarLogger.ROOT_LOGGER.failedXmlParsing(serviceXmlFile);
        } catch(Exception e) {
            throw SarLogger.ROOT_LOGGER.failedXmlParsing(e, serviceXmlFile);
        } finally {
            VFSUtils.safeClose(xmlStream);
        }
    }

public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final VirtualFile deploymentRoot = phaseContext . getDeploymentUnit ( ) . getAttachment ( Attachments . DEPLOYMENT_ROOT ) . getRoot ( ) ; if ( deploymentRoot == null || ! deploymentRoot . exists ( ) ) return ; VirtualFile serviceXmlFile = null ; if ( deploymentRoot . isDirectory ( ) ) { serviceXmlFile = deploymentRoot . getChild ( SERVICE_DESCRIPTOR_PATH ) ; } else if ( deploymentRoot . getName ( ) . toLowerCase ( Locale . ENGLISH ) . endsWith ( SERVICE_DESCRIPTOR_SUFFIX ) ) { serviceXmlFile = deploymentRoot ; } if ( serviceXmlFile == null || ! serviceXmlFile . exists ( ) ) return ; final XMLMapper xmlMapper = XMLMapper . Factory . create ( ) ; final JBossServiceXmlDescriptorParser jBossServiceXmlDescriptorParser = new JBossServiceXmlDescriptorParser ( JBossDescriptorPropertyReplacement . propertyReplacer ( phaseContext . getDeploymentUnit ( ) ) ) ; xmlMapper . registerRootElement ( new QName ( "urn:jboss:service:7.0" , "server" ) , jBossServiceXmlDescriptorParser ) ; xmlMapper . registerRootElement ( new QName ( null , "server" ) , jBossServiceXmlDescriptorParser ) ; InputStream xmlStream = null ; try { xmlStream = serviceXmlFile . openStream ( ) ; final XMLStreamReader reader = inputFactory . createXMLStreamReader ( xmlStream ) ; final ParseResult < JBossServiceXmlDescriptor > result = new ParseResult < JBossServiceXmlDescriptor > ( ) ; xmlMapper . parseDocument ( result , reader ) ; final JBossServiceXmlDescriptor xmlDescriptor = result . getResult ( ) ; if ( xmlDescriptor != null ) phaseContext . getDeploymentUnit ( ) . putAttachment ( JBossServiceXmlDescriptor . ATTACHMENT_KEY , xmlDescriptor ) ; else throw SarLogger . ROOT_LOGGER . failedXmlParsing ( serviceXmlFile ) ; } catch ( Exception e ) { throw SarLogger . ROOT_LOGGER . failedXmlParsing ( e , serviceXmlFile ) ; } finally { VFSUtils . safeClose ( xmlStream ) ; } }

Process a deployment for jboss-service.xml files. Will parse the xml file and attach a configuration discovered
during processing.

@param phaseContext the deployment unit context
@throws DeploymentUnitProcessingException

Process a deployment for jboss - service . xml files . Will parse the xml file and attach a configuration discovered during processing .


private void handleStatelessSessionBean(final EJBComponentDescription component, final Module module, final DeploymentReflectionIndex reflectionIndex) throws ClassNotFoundException, DeploymentUnitProcessingException {

        final Class<?> componentClass = ClassLoadingUtils.loadClass(component.getComponentClassName(), module);
        final MethodIdentifier ejbCreateId = MethodIdentifier.getIdentifier(void.class, "ejbCreate");
        final Method ejbCreate = ClassReflectionIndexUtil.findMethod(reflectionIndex, componentClass, ejbCreateId);
        if (ejbCreate != null) {
            final InterceptorClassDescription.Builder builder = InterceptorClassDescription.builder();
            builder.setPostConstruct(ejbCreateId);
            component.addInterceptorMethodOverride(ejbCreate.getDeclaringClass().getName(), builder.build());
        }
        final MethodIdentifier ejbRemoveId = MethodIdentifier.getIdentifier(void.class, "ejbRemove");
        final Method ejbRemove = ClassReflectionIndexUtil.findMethod(reflectionIndex, componentClass, ejbRemoveId);
        if (ejbRemove != null) {
            final InterceptorClassDescription.Builder builder = InterceptorClassDescription.builder();
            builder.setPreDestroy(ejbRemoveId);
            component.addInterceptorMethodOverride(ejbRemove.getDeclaringClass().getName(), builder.build());
        }
    }

private void handleStatelessSessionBean ( final EJBComponentDescription component , final Module module , final DeploymentReflectionIndex reflectionIndex ) throws ClassNotFoundException , DeploymentUnitProcessingException { final Class < ? > componentClass = ClassLoadingUtils . loadClass ( component . getComponentClassName ( ) , module ) ; final MethodIdentifier ejbCreateId = MethodIdentifier . getIdentifier ( void . class , "ejbCreate" ) ; final Method ejbCreate = ClassReflectionIndexUtil . findMethod ( reflectionIndex , componentClass , ejbCreateId ) ; if ( ejbCreate != null ) { final InterceptorClassDescription . Builder builder = InterceptorClassDescription . builder ( ) ; builder . setPostConstruct ( ejbCreateId ) ; component . addInterceptorMethodOverride ( ejbCreate . getDeclaringClass ( ) . getName ( ) , builder . build ( ) ) ; } final MethodIdentifier ejbRemoveId = MethodIdentifier . getIdentifier ( void . class , "ejbRemove" ) ; final Method ejbRemove = ClassReflectionIndexUtil . findMethod ( reflectionIndex , componentClass , ejbRemoveId ) ; if ( ejbRemove != null ) { final InterceptorClassDescription . Builder builder = InterceptorClassDescription . builder ( ) ; builder . setPreDestroy ( ejbRemoveId ) ; component . addInterceptorMethodOverride ( ejbRemove . getDeclaringClass ( ) . getName ( ) , builder . build ( ) ) ; } }

Handles setting up the ejbCreate and ejbRemove methods  for stateless session beans and MDB's

@param component       The component
@param module      The module
@param reflectionIndex The reflection index

Handles setting up the ejbCreate and ejbRemove methods for stateless session beans and MDB s


public static Class<?> makeStubClass(final Class<?> myClass) {
        final String stubClassName = myClass + "_Stub";
        ClassLoader cl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        if (cl == null) {
            cl = myClass.getClassLoader();
        }
        if (cl == null) {
            throw EjbLogger.ROOT_LOGGER.couldNotFindClassLoaderForStub(stubClassName);
        }
        Class<?> theClass;
        try {
            theClass = cl.loadClass(stubClassName);
        } catch (ClassNotFoundException e) {
            try {
                final ClassFile clazz = IIOPStubCompiler.compile(myClass, stubClassName);
                theClass = clazz.define(cl, myClass.getProtectionDomain());
            } catch (Throwable ex) {
                //there is a possibility that another thread may have defined the same class in the meantime
                try {
                    theClass = cl.loadClass(stubClassName);
                } catch (ClassNotFoundException e1) {
                    EjbLogger.ROOT_LOGGER.dynamicStubCreationFailed(stubClassName, ex);
                    throw ex;
                }
            }
        }
        return theClass;
    }

Makes a dynamic stub class, if it does not already exist.
@param myClass The class to create a stub for
@return The dynamic stub class

Makes a dynamic stub class if it does not already exist .


protected byte[] getAnonymousObjectId(long n) {
        String s = anonOidPrefix + Long.toString(n);
        return s.getBytes(StandardCharsets.UTF_8);
    }

protected byte [ ] getAnonymousObjectId ( long n ) { String s = anonOidPrefix + Long . toString ( n ) ; return s . getBytes ( StandardCharsets . UTF_8 ) ; }

Generate the ID of the n-th "anonymous" object created in this IR.

Generate the ID of the n - th anonymous object created in this IR .


@Override
    public List<PersistenceProvider> getPersistenceProviders() {
        List<PersistenceProvider> providersCopy = new ArrayList<>(providers.size());

        /**
         * Add the application specified providers first so they are found before the global providers
         */
        synchronized(persistenceProviderPerClassLoader) {
            if (persistenceProviderPerClassLoader.size() > 0) {
                // get the deployment or subdeployment classloader
                ClassLoader deploymentClassLoader = findParentModuleCl(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
                ROOT_LOGGER.tracef("get application level Persistence Provider for classloader %s" , deploymentClassLoader);
                // collect persistence providers associated with deployment/each sub-deployment
                List<Class<? extends PersistenceProvider>> deploymentSpecificPersistenceProviders = persistenceProviderPerClassLoader.get(deploymentClassLoader);
                ROOT_LOGGER.tracef("got application level Persistence Provider list %s" , deploymentSpecificPersistenceProviders);
                if (deploymentSpecificPersistenceProviders != null) {

                    for (Class<? extends PersistenceProvider> providerClass : deploymentSpecificPersistenceProviders) {
                        try {
                            ROOT_LOGGER.tracef("application has its own Persistence Provider %s", providerClass.getName());
                            providersCopy.add(providerClass.newInstance());
                        } catch (InstantiationException e) {
                            throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
                        } catch (IllegalAccessException e) {
                            throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
                        }
                    }
                }
            }
        }

        // add global persistence providers last (so application packaged providers have priority)
        for (Class<?> providerClass : providers) {
            try {
                providersCopy.add((PersistenceProvider) providerClass.newInstance());
                ROOT_LOGGER.tracef("returning global (module) Persistence Provider %s", providerClass.getName());
            } catch (InstantiationException e) {
                throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
            } catch (IllegalAccessException e) {
                throw JpaLogger.ROOT_LOGGER.couldNotCreateInstanceProvider(e, providerClass.getName());
            }
        }
        return providersCopy;
    }

Return a new instance of each persistence provider class

@return


public void clearCachedDeploymentSpecificProviders(Set<ClassLoader> deploymentClassLoaders) {

        synchronized(persistenceProviderPerClassLoader) {
            for (ClassLoader deploymentClassLoader: deploymentClassLoaders) {
                persistenceProviderPerClassLoader.remove(deploymentClassLoader);
            }
        }
    }

public void clearCachedDeploymentSpecificProviders ( Set < ClassLoader > deploymentClassLoaders ) { synchronized ( persistenceProviderPerClassLoader ) { for ( ClassLoader deploymentClassLoader : deploymentClassLoaders ) { persistenceProviderPerClassLoader . remove ( deploymentClassLoader ) ; } } }

Cleared at application undeployment time to remove any persistence providers that were deployed with the application

@param deploymentClassLoaders


public void addDeploymentSpecificPersistenceProvider(PersistenceProvider persistenceProvider, Set<ClassLoader> deploymentClassLoaders) {

        synchronized(persistenceProviderPerClassLoader) {

            for (ClassLoader deploymentClassLoader: deploymentClassLoaders) {
                List<Class<? extends PersistenceProvider>> list = persistenceProviderPerClassLoader.get(deploymentClassLoader);
                ROOT_LOGGER.tracef("getting persistence provider list (%s) for deployment (%s)", list, deploymentClassLoader );
                if (list == null) {
                    list = new ArrayList<>();
                    persistenceProviderPerClassLoader.put(deploymentClassLoader, list);
                    ROOT_LOGGER.tracef("saving new persistence provider list (%s) for deployment (%s)", list, deploymentClassLoader );
                }
                list.add(persistenceProvider.getClass());
                ROOT_LOGGER.tracef("added new persistence provider (%s) to provider list (%s)", persistenceProvider.getClass().getName(), list);
            }
        }
    }

Set at application deployment time to the persistence providers packaged in the application

@param persistenceProvider
@param deploymentClassLoaders


private ClassLoader findParentModuleCl(ClassLoader classLoader) {
        ClassLoader c = classLoader;
        while (c != null && !(c instanceof ModuleClassLoader)) {
            c = c.getParent();
        }
        return c;
    }

private ClassLoader findParentModuleCl ( ClassLoader classLoader ) { ClassLoader c = classLoader ; while ( c != null && ! ( c instanceof ModuleClassLoader ) ) { c = c . getParent ( ) ; } return c ; }

If a custom CL is in use we want to get the module CL it delegates to
@param classLoader The current CL
@returnThe corresponding module CL


public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
        final JBossServiceXmlDescriptor serviceXmlDescriptor = deploymentUnit.getAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY);
        if(serviceXmlDescriptor == null) {
            return; // Skip deployments with out a service xml descriptor
        }

        moduleSpecification.addSystemDependency(new ModuleDependency(Module.getBootModuleLoader(), JBOSS_MODULES_ID, false, false, false, false));
        moduleSpecification.addSystemDependency(new ModuleDependency(Module.getBootModuleLoader(), JBOSS_AS_SYSTEM_JMX_ID, true, false, false, false));
        // depend on Properties editor module which uses ServiceLoader approach to load the appropriate org.jboss.common.beans.property.finder.PropertyEditorFinder
        moduleSpecification.addSystemDependency(new ModuleDependency(Module.getBootModuleLoader(), PROPERTIES_EDITOR_MODULE_ID, false, false, true, false));

        // All SARs require the ability to register MBeans.
        moduleSpecification.addPermissionFactory(REGISTER_PERMISSION_FACTORY);
    }

Add dependencies for modules required for manged bean deployments, if managed bean configurations are attached
to the deployment.

@param phaseContext the deployment unit context
@throws DeploymentUnitProcessingException

Add dependencies for modules required for manged bean deployments if managed bean configurations are attached to the deployment .


private static void addPuService(final DeploymentPhaseContext phaseContext, final ArrayList<PersistenceUnitMetadataHolder> puList,
                                     final boolean startEarly, final Platform platform)
        throws DeploymentUnitProcessingException {

        if (puList.size() > 0) {
            final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
            final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
            final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
            final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
            final ModuleClassLoader classLoader = module.getClassLoader();

            for (PersistenceUnitMetadataHolder holder : puList) {
                setAnnotationIndexes(holder, deploymentUnit);
                for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {

                    // only start the persistence unit if JPA_CONTAINER_MANAGED is true
                    String jpaContainerManaged = pu.getProperties().getProperty(Configuration.JPA_CONTAINER_MANAGED);
                    boolean deployPU = (jpaContainerManaged == null? true : Boolean.parseBoolean(jpaContainerManaged));

                    if (deployPU) {
                        final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder = getPersistenceProviderDeploymentHolder(deploymentUnit);
                        final PersistenceProvider provider = lookupProvider(pu, persistenceProviderDeploymentHolder, deploymentUnit);
                        final PersistenceProviderAdaptor adaptor = getPersistenceProviderAdaptor(pu, persistenceProviderDeploymentHolder, deploymentUnit, provider, platform);
                        final boolean twoPhaseBootStrapCapable = (adaptor instanceof TwoPhaseBootstrapCapable) && Configuration.allowTwoPhaseBootstrap(pu);

                        if (startEarly) {
                            if (twoPhaseBootStrapCapable) {
                                deployPersistenceUnitPhaseOne(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, adaptor);
                            }
                            else if (false == Configuration.needClassFileTransformer(pu)) {
                                // will start later when startEarly == false
                                ROOT_LOGGER.tracef("persistence unit %s in deployment %s is configured to not need class transformer to be set, no class rewriting will be allowed",
                                    pu.getPersistenceUnitName(), deploymentUnit.getName());
                            }
                            else {
                                // we need class file transformer to work, don't allow cdi bean manager to be access since that
                                // could cause application classes to be loaded (workaround by setting jboss.as.jpa.classtransformer to false).  WFLY-1463
                                final boolean allowCdiBeanManagerAccess = false;
                                deployPersistenceUnit(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor, allowCdiBeanManagerAccess);
                            }
                        }
                        else { // !startEarly
                            if (twoPhaseBootStrapCapable) {
                                deployPersistenceUnitPhaseTwo(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor);
                            } else if (false == Configuration.needClassFileTransformer(pu)) {
                                final boolean allowCdiBeanManagerAccess = true;
                                // PUs that have Configuration.JPA_CONTAINER_CLASS_TRANSFORMER = false will start during INSTALL phase
                                deployPersistenceUnit(deploymentUnit, eeModuleDescription, serviceTarget, classLoader, pu, provider, adaptor, allowCdiBeanManagerAccess);
                            }
                        }

                    }
                    else {
                        ROOT_LOGGER.tracef("persistence unit %s in deployment %s is not container managed (%s is set to false)",
                                pu.getPersistenceUnitName(), deploymentUnit.getName(), Configuration.JPA_CONTAINER_MANAGED);
                    }
                }
            }
        }
    }

Add one PU service per top level deployment that represents

@param phaseContext
@param puList
@param startEarly
@param platform
@throws DeploymentUnitProcessingException


private static void setAnnotationIndexes(
            final PersistenceUnitMetadataHolder puHolder,
            DeploymentUnit deploymentUnit ) {

        final Map<URL, Index> annotationIndexes = new HashMap<>();

        do {
            for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {
                final Index index = root.getAttachment(Attachments.ANNOTATION_INDEX);
                if (index != null) {
                    try {
                        ROOT_LOGGER.tracef("adding '%s' to annotation index map", root.getRoot().toURL());
                        annotationIndexes.put(root.getRoot().toURL(), index);
                    } catch (MalformedURLException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            deploymentUnit = deploymentUnit.getParent(); // get annotation indexes for top level also
        }
        while (deploymentUnit != null);

        for (PersistenceUnitMetadata pu : puHolder.getPersistenceUnits()) {
            pu.setAnnotationIndex(annotationIndexes);   // hold onto the annotation index for Persistence Provider use during deployment
        }
    }

Setup the annotation index map

@param puHolder
@param deploymentUnit


private static PersistenceProviderAdaptor getPersistenceProviderAdaptor(
            final PersistenceUnitMetadata pu,
            final PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder,
            final DeploymentUnit deploymentUnit,
            final PersistenceProvider provider,
            final Platform platform) throws
        DeploymentUnitProcessingException {
        String adapterClass = pu.getProperties().getProperty(Configuration.ADAPTER_CLASS);

        /**
         * use adapter packaged in application deployment.
         */
        if (persistenceProviderDeploymentHolder != null && adapterClass != null) {
            List<PersistenceProviderAdaptor> persistenceProviderAdaptors = persistenceProviderDeploymentHolder.getAdapters();
            for(PersistenceProviderAdaptor persistenceProviderAdaptor:persistenceProviderAdaptors) {
                if(adapterClass.equals(persistenceProviderAdaptor.getClass().getName())) {
                    return persistenceProviderAdaptor;
                }
            }
        }

        String adaptorModule = pu.getProperties().getProperty(Configuration.ADAPTER_MODULE);
        PersistenceProviderAdaptor adaptor;
        adaptor = getPerDeploymentSharedPersistenceProviderAdaptor(deploymentUnit, adaptorModule, provider);
        if (adaptor == null) {
            try {
                // will load the persistence provider adaptor (integration classes).  if adaptorModule is null
                // the noop adaptor is returned (can be used against any provider but the integration classes
                // are handled externally via properties or code in the persistence provider).
                if (adaptorModule != null) { // legacy way of loading adapter module
                    adaptor = PersistenceProviderAdaptorLoader.loadPersistenceAdapterModule(adaptorModule, platform, createManager(deploymentUnit));
                }
                else {
                    adaptor = PersistenceProviderAdaptorLoader.loadPersistenceAdapter(provider, platform, createManager(deploymentUnit));
                }
            } catch (ModuleLoadException e) {
                throw JpaLogger.ROOT_LOGGER.persistenceProviderAdaptorModuleLoadError(e, adaptorModule);
            }
            adaptor = savePerDeploymentSharedPersistenceProviderAdaptor(deploymentUnit, adaptorModule, adaptor, provider);
        }

        if (adaptor == null) {
            throw JpaLogger.ROOT_LOGGER.failedToGetAdapter(pu.getPersistenceProviderClassName());
        }
        return adaptor;
    }

Get the persistence provider adaptor.  Will load the adapter module if needed.

@param pu
@param persistenceProviderDeploymentHolder

@param provider
@param platform
@return
@throws DeploymentUnitProcessingException

Get the persistence provider adaptor . Will load the adapter module if needed .


private static PersistenceProviderAdaptor savePerDeploymentSharedPersistenceProviderAdaptor(DeploymentUnit deploymentUnit, String adaptorModule, PersistenceProviderAdaptor adaptor, PersistenceProvider provider) {
        if (deploymentUnit.getParent() != null) {
            deploymentUnit = deploymentUnit.getParent();
        }
        synchronized (deploymentUnit) {
            Map<String,PersistenceProviderAdaptor> map = deploymentUnit.getAttachment(providerAdaptorMapKey);
            String key;

            if (adaptorModule != null) {
                key = adaptorModule;  // handle legacy adapter module
            }
            else {
                key = provider.getClass().getName();
            }
            PersistenceProviderAdaptor current = map.get(key);

            // saved if not already set by another thread
            if (current == null) {
                map.put(key, adaptor);
                current = adaptor;
            }
            return current;
        }
    }

Will save the PersistenceProviderAdaptor at the top level application deployment unit level for sharing with other persistence units

@param deploymentUnit
@param adaptorModule
@param adaptor
@param provider
@return the application level shared PersistenceProviderAdaptor (which may of been set by a different thread)


private static PersistenceProvider lookupProvider(
            PersistenceUnitMetadata pu,
            PersistenceProviderDeploymentHolder persistenceProviderDeploymentHolder,
            DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException {

        /**
         * check if the deployment is already associated with the specified persistence provider
         */
        Map<String, PersistenceProvider> providerMap = persistenceProviderDeploymentHolder != null ?
                persistenceProviderDeploymentHolder.getProviders() : null;
        if (providerMap != null) {
            synchronized (providerMap) {
                if(providerMap.containsKey(pu.getPersistenceProviderClassName())){
                    ROOT_LOGGER.tracef("deployment %s is using %s", deploymentUnit.getName(), pu.getPersistenceProviderClassName());
                    return providerMap.get(pu.getPersistenceProviderClassName());
                }
            }
        }

        String configuredPersistenceProviderModule = pu.getProperties().getProperty(Configuration.PROVIDER_MODULE);
        String persistenceProviderClassName = pu.getPersistenceProviderClassName();

        if (persistenceProviderClassName == null) {
            persistenceProviderClassName = Configuration.PROVIDER_CLASS_DEFAULT;
        }

        /**
         * locate persistence provider in specified static module
         */
        if (configuredPersistenceProviderModule != null) {
            List<PersistenceProvider> providers;
            if (Configuration.PROVIDER_MODULE_APPLICATION_SUPPLIED.equals(configuredPersistenceProviderModule)) {
                try {
                    // load the persistence provider from the application deployment
                    final ModuleClassLoader classLoader = deploymentUnit.getAttachment(Attachments.MODULE).getClassLoader();
                    PersistenceProvider provider = PersistenceProviderLoader.loadProviderFromDeployment(classLoader, persistenceProviderClassName);
                    providers = new ArrayList<>();
                    providers.add(provider);
                    PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providers, null);
                    return provider;

                } catch (ClassNotFoundException e) {
                    throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, persistenceProviderClassName);
                } catch (InstantiationException e) {
                    throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, persistenceProviderClassName);
                } catch (IllegalAccessException e) {
                    throw JpaLogger.ROOT_LOGGER.cannotDeployApp(e, persistenceProviderClassName);
                }
            } else {
                try {
                    providers = PersistenceProviderLoader.loadProviderModuleByName(configuredPersistenceProviderModule);
                    PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providers, null);
                    PersistenceProvider provider = getProviderByName(pu, providers);
                    if (provider != null) {
                        return provider;
                    }
                } catch (ModuleLoadException e) {
                    throw JpaLogger.ROOT_LOGGER.cannotLoadPersistenceProviderModule(e, configuredPersistenceProviderModule, persistenceProviderClassName);
                }
            }
        }

        // try to determine the static module name based on the persistence provider class name
        String providerNameDerivedFromClassName = Configuration.getProviderModuleNameFromProviderClassName(persistenceProviderClassName);

        // see if the providerNameDerivedFromClassName has been loaded yet
        PersistenceProvider provider = getProviderByName(pu);

        // if we haven't loaded the provider yet, try loading now
        if (provider == null && providerNameDerivedFromClassName != null) {
            try {
                List<PersistenceProvider> providers = PersistenceProviderLoader.loadProviderModuleByName(providerNameDerivedFromClassName);
                PersistenceProviderDeploymentHolder.savePersistenceProviderInDeploymentUnit(deploymentUnit, providers, null);
                provider = getProviderByName(pu, providers);
            } catch (ModuleLoadException e) {
                throw JpaLogger.ROOT_LOGGER.cannotLoadPersistenceProviderModule(e, providerNameDerivedFromClassName, persistenceProviderClassName);
            }
        }

        if (provider == null)
            throw JpaLogger.ROOT_LOGGER.persistenceProviderNotFound(persistenceProviderClassName);

        return provider;
    }

Look up the persistence provider

@param pu
@param deploymentUnit
@return


@Override
    public Map<Class<? extends Annotation>, Set<Class<?>>> getAnnotatedClasses(final Set uris) {
        return annotations; // TODO:  Should this be limited by URI
    }

@
Override
public
Map
<
Class
<
extends
Annotation
>
,
Set
<
Class
<
>
>
>
getAnnotatedClasses
(
final
Set
uris
)
{
return
annotations
;
// TODO:  Should this be limited by URI
}

use a plain Set and it should work for both versions.

use a plain Set and it should work for both versions .


final EJBArchiveMetaData create(final Deployment dep) {
        if (WSLogger.ROOT_LOGGER.isTraceEnabled()) {
            WSLogger.ROOT_LOGGER.tracef("Building JBoss agnostic meta data for EJB webservice deployment: %s", dep.getSimpleName());
        }
        final EJBArchiveMetaData.Builder ejbArchiveMDBuilder = new EJBArchiveMetaData.Builder();

        this.buildEnterpriseBeansMetaData(dep, ejbArchiveMDBuilder);
        this.buildWebservicesMetaData(dep, ejbArchiveMDBuilder);

        return ejbArchiveMDBuilder.build();
    }

Builds universal EJB meta data model that is AS agnostic.

@param dep
webservice deployment
@return universal EJB meta data model

Builds universal EJB meta data model that is AS agnostic .


protected void buildEnterpriseBeanMetaData(final List<EJBMetaData> wsEjbsMD, final EJBEndpoint ejbEndpoint, final JBossWebservicesMetaData jbossWebservicesMD) {
        final SLSBMetaData.Builder wsEjbMDBuilder = new SLSBMetaData.Builder();

        // set EJB name and class
        wsEjbMDBuilder.setEjbName(ejbEndpoint.getName());
        wsEjbMDBuilder.setEjbClass(ejbEndpoint.getClassName());

        final JBossPortComponentMetaData portComponentMD = getPortComponent(ejbEndpoint.getName(), jbossWebservicesMD);
        if (portComponentMD != null) {
            // set port component meta data
            wsEjbMDBuilder.setPortComponentName(portComponentMD.getPortComponentName());
            wsEjbMDBuilder.setPortComponentURI(portComponentMD.getPortComponentURI());
        }
        // set security meta data
        // auth method
        final String authMethod = getAuthMethod(ejbEndpoint, portComponentMD);
        // transport guarantee
        final String transportGuarantee = getTransportGuarantee(ejbEndpoint, portComponentMD);
        // secure wsdl access
        final boolean secureWsdlAccess = isSecureWsdlAccess(ejbEndpoint, portComponentMD);

        final String realmName = getRealmName(ejbEndpoint, portComponentMD);
        // propagate
        wsEjbMDBuilder.setSecurityMetaData(new EJBSecurityMetaData(authMethod, realmName, transportGuarantee, secureWsdlAccess));

        wsEjbsMD.add(wsEjbMDBuilder.build());
    }

protected
void
buildEnterpriseBeanMetaData
(
final
List
<
EJBMetaData
>
wsEjbsMD
,
final
EJBEndpoint
ejbEndpoint
,
final
JBossWebservicesMetaData
jbossWebservicesMD
)
{
final
SLSBMetaData
.
Builder
wsEjbMDBuilder
=
new
SLSBMetaData
.
Builder
(
)
;
// set EJB name and class
wsEjbMDBuilder
.
setEjbName
(
ejbEndpoint
.
getName
(
)
)
;
wsEjbMDBuilder
.
setEjbClass
(
ejbEndpoint
.
getClassName
(
)
)
;
final
JBossPortComponentMetaData
portComponentMD
=
getPortComponent
(
ejbEndpoint
.
getName
(
)
,
jbossWebservicesMD
)
;
if
(
portComponentMD
!=
)
{
// set port component meta data
wsEjbMDBuilder
.
setPortComponentName
(
portComponentMD
.
getPortComponentName
(
)
)
;
wsEjbMDBuilder
.
setPortComponentURI
(
portComponentMD
.
getPortComponentURI
(
)
)
;
}
// set security meta data
// auth method
final
String
authMethod
=
getAuthMethod
(
ejbEndpoint
,
portComponentMD
)
;
// transport guarantee
final
String
transportGuarantee
=
getTransportGuarantee
(
ejbEndpoint
,
portComponentMD
)
;
// secure wsdl access
final
boolean
secureWsdlAccess
=
isSecureWsdlAccess
(
ejbEndpoint
,
portComponentMD
)
;
final
String
realmName
=
getRealmName
(
ejbEndpoint
,
portComponentMD
)
;
// propagate
wsEjbMDBuilder
.
setSecurityMetaData
(
new
EJBSecurityMetaData
(
authMethod
,
realmName
,
transportGuarantee
,
secureWsdlAccess
)
)
;
wsEjbsMD
.
add
(
wsEjbMDBuilder
.
build
(
)
)
;
}

Builds JBoss agnostic EJB meta data.

@param wsEjbsMD
jboss agnostic EJBs meta data


void refreshParticipant(OperationContext context) {
        context.addStep(refreshHandler, OperationContext.Stage.MODEL, true);
    }

void refreshParticipant ( OperationContext context ) { context . addStep ( refreshHandler , OperationContext . Stage . MODEL , true ) ; }

refresh the attributes of this participant (the status attribute should have changed to PREPARED

refresh the attributes of this participant ( the status attribute should have changed to PREPARED


ContainerAnalysis getAnalysis(final Class cls) throws RMIIIOPViolationException {
        ContainerAnalysis ret = null;
        boolean created = false;
        try {
            synchronized (this) {
                ret = lookupDone(cls);
                if (ret != null) {
                    return ret;
                }

                // is it work-in-progress?
                final ContainerAnalysis inProgress = workInProgress.get(new InProgressKey(cls, Thread.currentThread()));
                if (inProgress != null) {
                        return inProgress; // return unfinished

                    // Do not wait for the other thread: We may deadlock
                    // Double work is better that deadlock...
                }

                ret = createWorkInProgress(cls);
            }
            created = true;
            // Do the work
            doTheWork(cls, ret);
        } finally {
            // We did it
            synchronized (this) {
                if(created) {
                    workInProgress.remove(new InProgressKey(cls, Thread.currentThread()));
                    workDone.put(cls, new SoftReference<ContainerAnalysis>(ret));
                    ClassLoader classLoader = cls.getClassLoader();
                    if (classLoader != null) {
                        Set<Class<?>> classes = classesByLoader.get(classLoader);
                        if (classes == null) {
                            classesByLoader.put(classLoader, classes = new HashSet<Class<?>>());
                        }
                        classes.add(cls);
                    }
                }
                notifyAll();
            }
        }
        return ret;
    }

Returns an analysis.
If the calling thread is currently doing an analysis of this
class, an unfinished analysis is returned.

Returns an analysis . If the calling thread is currently doing an analysis of this class an unfinished analysis is returned .


private ContainerAnalysis lookupDone(Class cls) {
        SoftReference ref = (SoftReference) workDone.get(cls);
        if (ref == null)
            return null;
        ContainerAnalysis ret = (ContainerAnalysis) ref.get();
        if (ret == null)
            workDone.remove(cls); // clear map entry if soft ref. was cleared.
        return ret;
    }

Lookup an analysis in the fully done map.

Lookup an analysis in the fully done map .


private ContainerAnalysis createWorkInProgress(final Class cls) {
        final ContainerAnalysis analysis;
        try {
            analysis = (ContainerAnalysis) constructor.newInstance(cls);
        } catch (InstantiationException ex) {
            throw new RuntimeException(ex.toString());
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex.toString());
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(ex.toString());
        }

        workInProgress.put(new InProgressKey(cls, Thread.currentThread()), analysis);

        return analysis;
    }

private ContainerAnalysis createWorkInProgress ( final Class cls ) { final ContainerAnalysis analysis ; try { analysis = ( ContainerAnalysis ) constructor . newInstance ( cls ) ; } catch ( InstantiationException ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } catch ( IllegalAccessException ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } catch ( InvocationTargetException ex ) { throw new RuntimeException ( ex . toString ( ) ) ; } workInProgress . put ( new InProgressKey ( cls , Thread . currentThread ( ) ) , analysis ) ; return analysis ; }


public String getIDLModuleName() {
        if (idlModuleName == null) {
            String pkgName = cls.getPackage().getName();
            StringBuffer b = new StringBuffer();

            while (!"".equals(pkgName)) {
                int idx = pkgName.indexOf('.');
                String n = (idx == -1) ? pkgName : pkgName.substring(0, idx);

                b.append("::").append(Util.javaToIDLName(n));

                pkgName = (idx == -1) ? "" : pkgName.substring(idx + 1);
            }
            idlModuleName = b.toString();
        }
        return idlModuleName;
    }

public String getIDLModuleName ( ) { if ( idlModuleName == null ) { String pkgName = cls . getPackage ( ) . getName ( ) ; StringBuffer b = new StringBuffer ( ) ; while ( ! "" . equals ( pkgName ) ) { int idx = pkgName . indexOf ( ' ' ) ; String n = ( idx == - 1 ) ? pkgName : pkgName . substring ( 0 , idx ) ; b . append ( "::" ) . append ( Util . javaToIDLName ( n ) ) ; pkgName = ( idx == - 1 ) ? "" : pkgName . substring ( idx + 1 ) ; } idlModuleName = b . toString ( ) ; } return idlModuleName ; }

Return the fully qualified IDL module name that this
analysis should be placed in.

Return the fully qualified IDL module name that this analysis should be placed in .


protected String toHexString(int i) {
        String s = Integer.toHexString(i).toUpperCase(Locale.ENGLISH);

        if (s.length() < 8)
            return "00000000".substring(0, 8 - s.length()) + s;
        else
            return s;
    }

protected String toHexString ( int i ) { String s = Integer . toHexString ( i ) . toUpperCase ( Locale . ENGLISH ) ; if ( s . length ( ) < 8 ) return "00000000" . substring ( 0 , 8 - s . length ( ) ) + s ; else return s ; }

Convert an integer to a 16-digit hex string.

Convert an integer to a 16 - digit hex string .


protected String toHexString(long l) {
        String s = Long.toHexString(l).toUpperCase(Locale.ENGLISH);

        if (s.length() < 16)
            return "0000000000000000".substring(0, 16 - s.length()) + s;
        else
            return s;
    }

protected String toHexString ( long l ) { String s = Long . toHexString ( l ) . toUpperCase ( Locale . ENGLISH ) ; if ( s . length ( ) < 16 ) return "0000000000000000" . substring ( 0 , 16 - s . length ( ) ) + s ; else return s ; }

Convert a long to a 16-digit hex string.

Convert a long to a 16 - digit hex string .


protected boolean isAccessor(Method m) {
        Class returnType = m.getReturnType();
        // JBAS-4473, look for get<name>()
        String name = m.getName();
        if (!(name.startsWith("get") && name.length() > "get".length()))
            if (!(name.startsWith("is") && name.length() > "is".length())
                    || !(returnType == Boolean.TYPE))
                return false;
        if (returnType == Void.TYPE)
            return false;
        if (m.getParameterTypes().length != 0)
            return false;

        return hasNonAppExceptions(m);
    }

protected
boolean
isAccessor
(
Method
m
)
{
Class
returnType
=
m
.
getReturnType
(
)
;
// JBAS-4473, look for get<name>()
String
name
=
m
.
getName
(
)
;
if
(
!
(
name
.
startsWith
(
"get"
)
&&
name
.
length
(
)
>
"get"
.
length
(
)
)
)
if
(
!
(
name
.
startsWith
(
"is"
)
&&
name
.
length
(
)
>
"is"
.
length
(
)
)
||
!
(
returnType
==
Boolean
.
TYPE
)
)
return
false
;
if
(
returnType
==
Void
.
TYPE
)
return
false
;
if
(
m
.
getParameterTypes
(
)
.
length
!=
0
)
return
false
;
return
hasNonAppExceptions
(
m
)
;
}


protected boolean isMutator(Method m) {
        // JBAS-4473, look for set<name>()
        String name = m.getName();
        if (!(name.startsWith("set") && name.length() > "set".length()))
            return false;
        if (m.getReturnType() != Void.TYPE)
            return false;
        if (m.getParameterTypes().length != 1)
            return false;
        return hasNonAppExceptions(m);
    }

protected
boolean
isMutator
(
Method
m
)
{
// JBAS-4473, look for set<name>()
String
name
=
m
.
getName
(
)
;
if
(
!
(
name
.
startsWith
(
"set"
)
&&
name
.
length
(
)
>
"set"
.
length
(
)
)
)
return
false
;
if
(
m
.
getReturnType
(
)
!=
Void
.
TYPE
)
return
false
;
if
(
m
.
getParameterTypes
(
)
.
length
!=
1
)
return
false
;
return
hasNonAppExceptions
(
m
)
;
}


protected boolean hasNonAppExceptions(Method m) {
        Class[] ex = m.getExceptionTypes();

        for (int i = 0; i < ex.length; ++i)
            if (!java.rmi.RemoteException.class.isAssignableFrom(ex[i]))
                return false;
        return true;
    }

protected boolean hasNonAppExceptions ( Method m ) { Class [ ] ex = m . getExceptionTypes ( ) ; for ( int i = 0 ; i < ex . length ; ++ i ) if ( ! java . rmi . RemoteException . class . isAssignableFrom ( ex [ i ] ) ) return false ; return true ; }

Check if a method throws anything checked other than
java.rmi.RemoteException and its subclasses.

Check if a method throws anything checked other than java . rmi . RemoteException and its subclasses .


protected String attributeReadName(String name) {
        if (name.startsWith("get"))
            name = name.substring(3);
        else if (name.startsWith("is"))
            name = name.substring(2);
        else
            throw IIOPLogger.ROOT_LOGGER.notAnAccessor(name);

        return name;
    }

protected String attributeReadName ( String name ) { if ( name . startsWith ( "get" ) ) name = name . substring ( 3 ) ; else if ( name . startsWith ( "is" ) ) name = name . substring ( 2 ) ; else throw IIOPLogger . ROOT_LOGGER . notAnAccessor ( name ) ; return name ; }

Convert an attribute read method name in Java format to
an attribute name in Java format.

Convert an attribute read method name in Java format to an attribute name in Java format .


protected String attributeWriteName(String name) {
        if (name.startsWith("set"))
            name = name.substring(3);
        else
            throw IIOPLogger.ROOT_LOGGER.notAnAccessor(name);

        return name;
    }

protected String attributeWriteName ( String name ) { if ( name . startsWith ( "set" ) ) name = name . substring ( 3 ) ; else throw IIOPLogger . ROOT_LOGGER . notAnAccessor ( name ) ; return name ; }

Convert an attribute write method name in Java format to
an attribute name in Java format.

Convert an attribute write method name in Java format to an attribute name in Java format .


protected void fixupOverloadedOperationNames()
            throws RMIIIOPViolationException {
        for (int i = 0; i < methods.length; ++i) {
            if ((m_flags[i] & M_OVERLOADED) == 0)
                continue;

            // Find the operation
            OperationAnalysis oa = null;
            String javaName = methods[i].getName();
            for (int opIdx = 0; oa == null && opIdx < operations.length; ++opIdx)
                if (operations[opIdx].getMethod().equals(methods[i]))
                    oa = operations[opIdx];

            if (oa == null)
                continue; // This method is not mapped.

            // Calculate new IDL name
            ParameterAnalysis[] params = oa.getParameters();
            StringBuffer b = new StringBuffer(oa.getIDLName());
            if (params.length == 0)
                b.append("__");
            for (int j = 0; j < params.length; ++j) {
                String s = params[j].getTypeIDLName();

                if (s.startsWith("::"))
                    s = s.substring(2);

                if (s.startsWith("_")) {
                    // remove leading underscore in IDL escaped identifier
                    s = s.substring(1);
                }

                b.append('_');

                while (!"".equals(s)) {
                    int idx = s.indexOf("::");

                    b.append('_');

                    if (idx == -1) {
                        b.append(s);
                        s = "";
                    } else {
                        b.append(s.substring(0, idx));
                        if (s.length() > idx + 2 && s.charAt(idx + 2) == '_') {
                            // remove leading underscore in IDL escaped identifier
                            s = s.substring(idx + 3);
                        } else {
                            s = s.substring(idx + 2);
                        }
                    }
                }
            }

            // Set new IDL name
            oa.setIDLName(b.toString());
        }
    }

Fixup overloaded operation names.
As specified in section 1.3.2.6.

Fixup overloaded operation names . As specified in section 1 . 3 . 2 . 6 .