public Set<ComponentDescription> getComponents(final String componentName, final VirtualFile deploymentRoot) {
        if (componentName.contains("#")) {
            final String[] parts = componentName.split("#");
            String path = parts[0];
            if (!path.startsWith("../")) {
                path = "../" + path;
            }
            final VirtualFile virtualPath = deploymentRoot.getChild(path);
            final String name = parts[1];
            final List<Description> info = componentsByName.get(name);
            if (info == null) {
                return Collections.emptySet();
            }
            final Set<ComponentDescription> ret = new HashSet<ComponentDescription>();
            for (Description i : info) {
                //now we need to check the path
                if (virtualPath.equals(i.deploymentRoot)) {
                    ret.add(i.componentDescription);
                }
            }
            return ret;
        } else {
            final List<Description> info = componentsByName.get(componentName);
            if (info == null) {
                return Collections.emptySet();
            }
            final Set<ComponentDescription> all = new HashSet<ComponentDescription>();
            final Set<ComponentDescription> thisDeployment = new HashSet<ComponentDescription>();
            for (Description i : info) {
                all.add(i.componentDescription);
                if (i.deploymentRoot.equals(deploymentRoot)) {
                    thisDeployment.add(i.componentDescription);
                }
            }
            //if there are multiple e
            if (all.size() > 1) {
                return thisDeployment;
            }
            return all;
        }
    }

public
Set
<
ComponentDescription
>
getComponents
(
final
String
componentName
,
final
VirtualFile
deploymentRoot
)
{
if
(
componentName
.
contains
(
"#"
)
)
{
final
String
[
]
parts
=
componentName
.
split
(
"#"
)
;
String
path
=
parts
[
0
]
;
if
(
!
path
.
startsWith
(
"../"
)
)
{
path
=
"../"
+
path
;
}
final
VirtualFile
virtualPath
=
deploymentRoot
.
getChild
(
path
)
;
final
String
name
=
parts
[
1
]
;
final
List
<
Description
>
info
=
componentsByName
.
get
(
name
)
;
if
(
info
==
)
{
return
Collections
.
emptySet
(
)
;
}
final
Set
<
ComponentDescription
>
ret
=
new
HashSet
<
ComponentDescription
>
(
)
;
for
(
Description
i
:
info
)
{
//now we need to check the path
if
(
virtualPath
.
equals
(
i
.
deploymentRoot
)
)
{
ret
.
add
(
i
.
componentDescription
)
;
}
}
return
ret
;
}
else
{
final
List
<
Description
>
info
=
componentsByName
.
get
(
componentName
)
;
if
(
info
==
)
{
return
Collections
.
emptySet
(
)
;
}
final
Set
<
ComponentDescription
>
all
=
new
HashSet
<
ComponentDescription
>
(
)
;
final
Set
<
ComponentDescription
>
thisDeployment
=
new
HashSet
<
ComponentDescription
>
(
)
;
for
(
Description
i
:
info
)
{
all
.
add
(
i
.
componentDescription
)
;
if
(
i
.
deploymentRoot
.
equals
(
deploymentRoot
)
)
{
thisDeployment
.
add
(
i
.
componentDescription
)
;
}
}
//if there are multiple e
if
(
all
.
size
(
)
>
1
)
{
return
thisDeployment
;
}
return
all
;
}
}

Get all components in the application that have the given name

@param componentName  The name of the component
@param deploymentRoot The deployment root of the component doing the lookup
@return A set of all views for the given component name and type


public Set<ViewDescription> getComponents(final String componentName, final String viewName, final VirtualFile deploymentRoot) {
        final List<ViewInformation> info = componentsByViewName.get(viewName);
        if (info == null) {
            return Collections.<ViewDescription>emptySet();
        }
        if (componentName.contains("#")) {
            final String[] parts = componentName.split("#");
            String path = parts[0];
            if (!path.startsWith("../")) {
                path = "../" + path;
            }
            final VirtualFile virtualPath = deploymentRoot.getChild(path);
            final String name = parts[1];
            final Set<ViewDescription> ret = new HashSet<ViewDescription>();
            for (ViewInformation i : info) {
                if (i.beanName.equals(name)) {
                    //now we need to check the path
                    if (virtualPath.equals(i.deploymentRoot)) {
                        ret.add(i.viewDescription);
                    }
                }
            }
            return ret;
        } else {
            final Set<ViewDescription> all = new HashSet<ViewDescription>();
            final Set<ViewDescription> thisDeployment = new HashSet<ViewDescription>();
            for (ViewInformation i : info) {
                if (i.beanName.equals(componentName)) {
                    all.add(i.viewDescription);
                    if (i.deploymentRoot.equals(deploymentRoot)) {
                        thisDeployment.add(i.viewDescription);
                    }
                }
            }
            if (all.size() > 1) {
                return thisDeployment;
            }
            return all;
        }
    }

public
Set
<
ViewDescription
>
getComponents
(
final
String
componentName
,
final
String
viewName
,
final
VirtualFile
deploymentRoot
)
{
final
List
<
ViewInformation
>
info
=
componentsByViewName
.
get
(
viewName
)
;
if
(
info
==
)
{
return
Collections
.
<
ViewDescription
>
emptySet
(
)
;
}
if
(
componentName
.
contains
(
"#"
)
)
{
final
String
[
]
parts
=
componentName
.
split
(
"#"
)
;
String
path
=
parts
[
0
]
;
if
(
!
path
.
startsWith
(
"../"
)
)
{
path
=
"../"
+
path
;
}
final
VirtualFile
virtualPath
=
deploymentRoot
.
getChild
(
path
)
;
final
String
name
=
parts
[
1
]
;
final
Set
<
ViewDescription
>
ret
=
new
HashSet
<
ViewDescription
>
(
)
;
for
(
ViewInformation
i
:
info
)
{
if
(
i
.
beanName
.
equals
(
name
)
)
{
//now we need to check the path
if
(
virtualPath
.
equals
(
i
.
deploymentRoot
)
)
{
ret
.
add
(
i
.
viewDescription
)
;
}
}
}
return
ret
;
}
else
{
final
Set
<
ViewDescription
>
all
=
new
HashSet
<
ViewDescription
>
(
)
;
final
Set
<
ViewDescription
>
thisDeployment
=
new
HashSet
<
ViewDescription
>
(
)
;
for
(
ViewInformation
i
:
info
)
{
if
(
i
.
beanName
.
equals
(
componentName
)
)
{
all
.
add
(
i
.
viewDescription
)
;
if
(
i
.
deploymentRoot
.
equals
(
deploymentRoot
)
)
{
thisDeployment
.
add
(
i
.
viewDescription
)
;
}
}
}
if
(
all
.
size
(
)
>
1
)
{
return
thisDeployment
;
}
return
all
;
}
}

Get all views in the application that have the given name and view type

@param componentName  The name of the component
@param viewName       The view type
@param deploymentRoot The deployment root of the component doing the lookup
@return A set of all views for the given component name and type


public Set<String> resolveMessageDestination(final String messageDestName, final VirtualFile deploymentRoot) {

        if (messageDestName.contains("#")) {
            final String[] parts = messageDestName.split("#");
            String path = parts[0];
            if (!path.startsWith("../")) {
                path = "../" + path;
            }
            final VirtualFile virtualPath = deploymentRoot.getChild(path);
            final String name = parts[1];
            final Set<String> ret = new HashSet<String>();
            final List<MessageDestinationMapping> data = messageDestinationJndiMapping.get(name);
            if (data != null) {
                for (final MessageDestinationMapping i : data) {
                    //now we need to check the path
                    if (virtualPath.equals(i.deploymentRoot)) {
                        ret.add(i.jndiName);
                    }
                }
            }
            return ret;
        } else {
            final Set<String> all = new HashSet<String>();
            final Set<String> thisDeployment = new HashSet<String>();
            final List<MessageDestinationMapping> data = messageDestinationJndiMapping.get(messageDestName);
            if (data != null) {
                for (final MessageDestinationMapping i : data) {
                    all.add(i.jndiName);
                    if (i.deploymentRoot.equals(deploymentRoot)) {
                        thisDeployment.add(i.jndiName);
                    }
                }
            }
            if (all.size() > 1) {
                return thisDeployment;
            }
            return all;
        }
    }

public
Set
<
String
>
resolveMessageDestination
(
final
String
messageDestName
,
final
VirtualFile
deploymentRoot
)
{
if
(
messageDestName
.
contains
(
"#"
)
)
{
final
String
[
]
parts
=
messageDestName
.
split
(
"#"
)
;
String
path
=
parts
[
0
]
;
if
(
!
path
.
startsWith
(
"../"
)
)
{
path
=
"../"
+
path
;
}
final
VirtualFile
virtualPath
=
deploymentRoot
.
getChild
(
path
)
;
final
String
name
=
parts
[
1
]
;
final
Set
<
String
>
ret
=
new
HashSet
<
String
>
(
)
;
final
List
<
MessageDestinationMapping
>
data
=
messageDestinationJndiMapping
.
get
(
name
)
;
if
(
data
!=
)
{
for
(
final
MessageDestinationMapping
i
:
data
)
{
//now we need to check the path
if
(
virtualPath
.
equals
(
i
.
deploymentRoot
)
)
{
ret
.
add
(
i
.
jndiName
)
;
}
}
}
return
ret
;
}
else
{
final
Set
<
String
>
all
=
new
HashSet
<
String
>
(
)
;
final
Set
<
String
>
thisDeployment
=
new
HashSet
<
String
>
(
)
;
final
List
<
MessageDestinationMapping
>
data
=
messageDestinationJndiMapping
.
get
(
messageDestName
)
;
if
(
data
!=
)
{
for
(
final
MessageDestinationMapping
i
:
data
)
{
all
.
add
(
i
.
jndiName
)
;
if
(
i
.
deploymentRoot
.
equals
(
deploymentRoot
)
)
{
thisDeployment
.
add
(
i
.
jndiName
)
;
}
}
}
if
(
all
.
size
(
)
>
1
)
{
return
thisDeployment
;
}
return
all
;
}
}

Resolves a message destination name into a JNDI name


private static void buildTransformers2_1_0(ResourceTransformationDescriptionBuilder builder) {
        ResourceTransformationDescriptionBuilder hornetqServer = builder.addChildResource(pathElement(HORNETQ_SERVER));
        ResourceTransformationDescriptionBuilder addressSetting = hornetqServer.addChildResource(AddressSettingDefinition.PATH);
        rejectDefinedAttributeWithDefaultValue(addressSetting, MAX_REDELIVERY_DELAY, REDELIVERY_MULTIPLIER);

        ResourceTransformationDescriptionBuilder bridge = hornetqServer.addChildResource(BridgeDefinition.PATH);
        bridge.getAttributeBuilder().setValueConverter(new DoubleToBigDecimalConverter(), RETRY_INTERVAL_MULTIPLIER);

        ResourceTransformationDescriptionBuilder clusterConnection = hornetqServer.addChildResource(ClusterConnectionDefinition.PATH);
        clusterConnection.getAttributeBuilder().setValueConverter(new DoubleToBigDecimalConverter(), RETRY_INTERVAL_MULTIPLIER);

        ResourceTransformationDescriptionBuilder connectionFactory = hornetqServer.addChildResource(ConnectionFactoryDefinition.PATH);
        connectionFactory.getAttributeBuilder().setValueConverter(new DoubleToBigDecimalConverter(), RETRY_INTERVAL_MULTIPLIER);

        ResourceTransformationDescriptionBuilder pooledConnectionFactory = hornetqServer.addChildResource(PooledConnectionFactoryDefinition.PATH);
        pooledConnectionFactory.getAttributeBuilder().setValueConverter(new DoubleToBigDecimalConverter(), RETRY_INTERVAL_MULTIPLIER);
    }

Transformation for WildFly 8 . 1 . 0 . Final


private static void rejectDefinedAttributeWithDefaultValue(ResourceTransformationDescriptionBuilder builder, AttributeDefinition... attrs) {
        for (AttributeDefinition attr : attrs) {
            builder.getAttributeBuilder()
                    .setDiscard(new DiscardAttributeValueChecker(attr.getDefaultValue()), attr)
                    .addRejectCheck(DEFINED, attr);
        }
    }

Reject the attributes if they are defined or discard them if they are undefined or set to their default value.

Reject the attributes if they are defined or discard them if they are undefined or set to their default value .


private static void renameAttribute(ResourceTransformationDescriptionBuilder builder,
                                        AttributeDefinition attribute, AttributeDefinition alias) {
        builder.getAttributeBuilder().addRename(attribute, alias.getName());
    }


public static void popIdentity(final ContextStateCache stateCache) {
        RemotingContext.setConnection(stateCache.getConnection());
        SecurityContextAssociation.setSecurityContext(stateCache.getSecurityContext());
    }

public static void popIdentity ( final ContextStateCache stateCache ) { RemotingContext . setConnection ( stateCache . getConnection ( ) ) ; SecurityContextAssociation . setSecurityContext ( stateCache . getSecurityContext ( ) ) ; }

Pop the identity previously associated and restore internal state to it's previous value.

@param stateCache - The cache containing the state as it was when pushIdentity was called.

Pop the identity previously associated and restore internal state to it s previous value .


private void loadIdsManually() {
        implIds.put("main", ModuleIdentifier.create(IMPL_MODULE));
        apiIds.put("main", ModuleIdentifier.create(API_MODULE));
        injectionIds.put("main", ModuleIdentifier.create(INJECTION_MODULE));

        allVersions.add("main");

        activeVersions.add("main");
    }

private void loadIdsManually ( ) { implIds . put ( "main" , ModuleIdentifier . create ( IMPL_MODULE ) ) ; apiIds . put ( "main" , ModuleIdentifier . create ( API_MODULE ) ) ; injectionIds . put ( "main" , ModuleIdentifier . create ( INJECTION_MODULE ) ) ; allVersions . add ( "main" ) ; activeVersions . add ( "main" ) ; }

just provide the default implementations


private void checkVersionIntegrity() {
        activeVersions.addAll(allVersions);

        for (String version : allVersions) {
            if (!apiIds.containsKey(version)) {
                JSFLogger.ROOT_LOGGER.missingJSFModule(version, API_MODULE);
                activeVersions.remove(version);
            }

            if (!implIds.containsKey(version)) {
                JSFLogger.ROOT_LOGGER.missingJSFModule(version, IMPL_MODULE);
                activeVersions.remove(version);
            }

            if (!injectionIds.containsKey(version)) {
                JSFLogger.ROOT_LOGGER.missingJSFModule(version, INJECTION_MODULE);
                activeVersions.remove(version);
            }
        }
    }

private void checkVersionIntegrity ( ) { activeVersions . addAll ( allVersions ) ; for ( String version : allVersions ) { if ( ! apiIds . containsKey ( version ) ) { JSFLogger . ROOT_LOGGER . missingJSFModule ( version , API_MODULE ) ; activeVersions . remove ( version ) ; } if ( ! implIds . containsKey ( version ) ) { JSFLogger . ROOT_LOGGER . missingJSFModule ( version , IMPL_MODULE ) ; activeVersions . remove ( version ) ; } if ( ! injectionIds . containsKey ( version ) ) { JSFLogger . ROOT_LOGGER . missingJSFModule ( version , INJECTION_MODULE ) ; activeVersions . remove ( version ) ; } } }

make sure that each version has api, impl, and injection

make sure that each version has api impl and injection


String computeSlot(String jsfVersion) {
        if (jsfVersion == null) return defaultSlot;
        if (JsfVersionMarker.JSF_2_0.equals(jsfVersion)) return defaultSlot;
        return jsfVersion;
    }

String computeSlot ( String jsfVersion ) { if ( jsfVersion == null ) return defaultSlot ; if ( JsfVersionMarker . JSF_2_0 . equals ( jsfVersion ) ) return defaultSlot ; return jsfVersion ; }

If needed, convert old JSFVersionMarker values to slot values.

@param jsfVersion The version value from JSFVersionMarker, or null for default slot.
@return The equivalent slot value.

If needed convert old JSFVersionMarker values to slot values .


private TypeCode getConstantTypeCode(Class cls)
            throws IRConstructionException {
        if (cls == null)
            throw IIOPLogger.ROOT_LOGGER.invalidNullClass();

        TypeCode ret = constantTypeCodeMap.get(cls);

        if (ret == null)
            throw IIOPLogger.ROOT_LOGGER.badClassForConstant(cls.getName());
        return ret;
    }

private TypeCode getConstantTypeCode ( Class cls ) throws IRConstructionException { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . invalidNullClass ( ) ; TypeCode ret = constantTypeCodeMap . get ( cls ) ; if ( ret == null ) throw IIOPLogger . ROOT_LOGGER . badClassForConstant ( cls . getName ( ) ) ; return ret ; }

Returns the TypeCode suitable for an IDL constant.

@param cls The Java class denoting the type of the constant.

Returns the TypeCode suitable for an IDL constant .


private void addTypeCode(Class cls, TypeCode typeCode)
            throws IRConstructionException {
        if (cls == null)
            throw IIOPLogger.ROOT_LOGGER.invalidNullClass();

        TypeCode tc = (TypeCode) typeCodeMap.get(cls);

        if (tc != null)
            throw IIOPLogger.ROOT_LOGGER.duplicateTypeCodeForClass(cls.getName());

        typeCodeMap.put(cls, typeCode);
    }

private void addTypeCode ( Class cls , TypeCode typeCode ) throws IRConstructionException { if ( cls == null ) throw IIOPLogger . ROOT_LOGGER . invalidNullClass ( ) ; TypeCode tc = ( TypeCode ) typeCodeMap . get ( cls ) ; if ( tc != null ) throw IIOPLogger . ROOT_LOGGER . duplicateTypeCodeForClass ( cls . getName ( ) ) ; typeCodeMap . put ( cls , typeCode ) ; }

Add a new IDL TypeCode for a mapped class.

@param cls      The Java class denoting the java type.
@param typeCode The IDL type code of the mapped java class.

Add a new IDL TypeCode for a mapped class .


private ModuleDefImpl ensurePackageExists(LocalContainer c,
                                              String previous,
                                              String remainder)
            throws IRConstructionException {
        if ("".equals(remainder))
            return (ModuleDefImpl) c; // done

        int idx = remainder.indexOf('.');
        String base;

        if (idx == -1)
            base = remainder;
        else
            base = remainder.substring(0, idx);
        base = Util.javaToIDLName(base);

        if (previous.equals(""))
            previous = base;
        else
            previous = previous + "/" + base;
        if (idx == -1)
            remainder = "";
        else
            remainder = remainder.substring(idx + 1);

        LocalContainer next = null;
        LocalContained contained = (LocalContained) c._lookup(base);

        if (contained instanceof LocalContainer)
            next = (LocalContainer) contained;
        else if (contained != null)
            throw IIOPLogger.ROOT_LOGGER.collisionWhileCreatingPackage();

        if (next == null) {
            String id = "IDL:" + previous + ":1.0";

            // Create module
            ModuleDefImpl m = new ModuleDefImpl(id, base, "1.0", c, impl);

            c.add(base, m);

            if (idx == -1)
                return m; // done

            next = (LocalContainer) c._lookup(base); // Better be there now...
        } else // Check that next _is_ a module
            if (next.def_kind() != DefinitionKind.dk_Module)
                throw IIOPLogger.ROOT_LOGGER.collisionWhileCreatingPackage();

        return ensurePackageExists(next, previous, remainder);
    }

private
ModuleDefImpl
ensurePackageExists
(
LocalContainer
c
,
String
previous
,
String
remainder
)
throws
IRConstructionException
{
if
(
""
.
equals
(
remainder
)
)
return
(
ModuleDefImpl
)
c
;
// done
int
idx
=
remainder
.
indexOf
(
'
'
)
;
String
base
;
if
(
idx
==
1
)
base
=
remainder
;
else
base
=
remainder
.
substring
(
0
,
idx
)
;
base
=
Util
.
javaToIDLName
(
base
)
;
if
(
previous
.
equals
(
""
)
)
previous
=
base
;
else
previous
=
previous
+
"/"
+
base
;
if
(
idx
==
1
)
remainder
=
""
;
else
remainder
=
remainder
.
substring
(
idx
+
1
)
;
LocalContainer
next
=
;
LocalContained
contained
=
(
LocalContained
)
c
.
_lookup
(
base
)
;
if
(
contained
instanceof
LocalContainer
)
next
=
(
LocalContainer
)
contained
;
else
if
(
contained
!=
)
throw
IIOPLogger
.
ROOT_LOGGER
.
collisionWhileCreatingPackage
(
)
;
if
(
next
==
)
{
String
id
=
"IDL:"
+
previous
+
":1.0"
;
// Create module
ModuleDefImpl
m
=
new
ModuleDefImpl
(
id
,
base
,
"1.0"
,
c
,
impl
)
;
c
.
add
(
base
,
m
)
;
if
(
idx
==
1
)
return
m
;
// done
next
=
(
LocalContainer
)
c
.
_lookup
(
base
)
;
// Better be there now...
}
else
// Check that next _is_ a module
if
(
next
.
def_kind
(
)
!=
DefinitionKind
.
dk_Module
)
throw
IIOPLogger
.
ROOT_LOGGER
.
collisionWhileCreatingPackage
(
)
;
return
ensurePackageExists
(
next
,
previous
,
remainder
)
;
}

Ensure that a package exists in the IR.
This will create modules in the IR as needed.

@param c         The container that the remainder of modules should be defined in.
@param previous  The IDL module name, from root to c.
@param remainder The java package name, relative to c.
@return A reference to the IR module that represents the package.

Ensure that a package exists in the IR . This will create modules in the IR as needed .


private String[] addInterfaces(ContainerAnalysis ca)
            throws RMIIIOPViolationException, IRConstructionException {
        InterfaceAnalysis[] interfaces = ca.getInterfaces();
        List base_interfaces = new ArrayList();
        for (int i = 0; i < interfaces.length; ++i) {
            InterfaceDefImpl idi = addInterface(interfaces[i]);
            base_interfaces.add(idi.id());
        }
        String[] strArr = new String[base_interfaces.size()];
        return (String[]) base_interfaces.toArray(strArr);
    }

private String [ ] addInterfaces ( ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { InterfaceAnalysis [ ] interfaces = ca . getInterfaces ( ) ; List base_interfaces = new ArrayList ( ) ; for ( int i = 0 ; i < interfaces . length ; ++ i ) { InterfaceDefImpl idi = addInterface ( interfaces [ i ] ) ; base_interfaces . add ( idi . id ( ) ) ; } String [ ] strArr = new String [ base_interfaces . size ( ) ] ; return ( String [ ] ) base_interfaces . toArray ( strArr ) ; }

Add a set of interfaces to the IR.

@return An array of the IR IDs of the interfaces.


private String[] addAbstractBaseValuetypes(ContainerAnalysis ca)
            throws RMIIIOPViolationException, IRConstructionException {
        ValueAnalysis[] abstractValuetypes = ca.getAbstractBaseValuetypes();
        List abstract_base_valuetypes = new ArrayList();
        for (int i = 0; i < abstractValuetypes.length; ++i) {
            ValueDefImpl vdi = addValue(abstractValuetypes[i]);
            abstract_base_valuetypes.add(vdi.id());
        }
        String[] strArr = new String[abstract_base_valuetypes.size()];
        return (String[]) abstract_base_valuetypes.toArray(strArr);
    }

private String [ ] addAbstractBaseValuetypes ( ContainerAnalysis ca ) throws RMIIIOPViolationException , IRConstructionException { ValueAnalysis [ ] abstractValuetypes = ca . getAbstractBaseValuetypes ( ) ; List abstract_base_valuetypes = new ArrayList ( ) ; for ( int i = 0 ; i < abstractValuetypes . length ; ++ i ) { ValueDefImpl vdi = addValue ( abstractValuetypes [ i ] ) ; abstract_base_valuetypes . add ( vdi . id ( ) ) ; } String [ ] strArr = new String [ abstract_base_valuetypes . size ( ) ] ; return ( String [ ] ) abstract_base_valuetypes . toArray ( strArr ) ; }

Add a set of abstract valuetypes to the IR.

@return An array of the IR IDs of the abstract valuetypes.

Add a set of abstract valuetypes to the IR .


private void addClass(Class cls)
            throws RMIIIOPViolationException, IRConstructionException {
        if (cls.isPrimitive())
            return; // No need to add primitives.

        if (cls.isArray()) {
            // Add array mapping
            addArray(cls);
        } else if (cls.isInterface()) {
            if (!RmiIdlUtil.isAbstractValueType(cls)) {
                // Analyse the interface
                InterfaceAnalysis ia = InterfaceAnalysis.getInterfaceAnalysis(cls);

                // Add analyzed interface (which may be abstract)
                addInterface(ia);
            } else {
                // Analyse the value
                ValueAnalysis va = ValueAnalysis.getValueAnalysis(cls);

                // Add analyzed value
                addValue(va);
            }
        } else if (Exception.class.isAssignableFrom(cls)) { // Exception type.
            // Analyse the exception
            ExceptionAnalysis ea = ExceptionAnalysis.getExceptionAnalysis(cls);

            // Add analyzed exception
            addException(ea);
        } else { // Got to be a value type.
            // Analyse the value
            ValueAnalysis va = ValueAnalysis.getValueAnalysis(cls);

            // Add analyzed value
            addValue(va);
        }
    }

Map the class and add its IIOP mapping to the repository.

Map the class and add its IIOP mapping to the repository .


private InterfaceDefImpl addInterface(InterfaceAnalysis ia)
            throws RMIIIOPViolationException, IRConstructionException {
        InterfaceDefImpl iDef;
        Class cls = ia.getCls();

        // Lookup: Has it already been added?
        iDef = (InterfaceDefImpl) interfaceMap.get(cls);
        if (iDef != null)
            return iDef; // Yes, just return it.

        // Get module to add interface to.
        ModuleDefImpl m = ensurePackageExists(cls.getPackage().getName());

        // Add superinterfaces
        String[] base_interfaces = addInterfaces(ia);

        // Create the interface
        String base = cls.getName();
        base = base.substring(base.lastIndexOf('.') + 1);
        base = Util.javaToIDLName(base);

        iDef = new InterfaceDefImpl(ia.getRepositoryId(),
                base, "1.0", m,
                base_interfaces, impl);
        addTypeCode(cls, iDef.type());
        m.add(base, iDef);
        interfaceMap.put(cls, iDef); // Remember we mapped this.

        // Fill in constants
        addConstants(iDef, ia);

        // Add attributes
        addAttributes(iDef, ia);

        // Fill in operations
        addOperations(iDef, ia);

        return iDef;
    }

private
InterfaceDefImpl
addInterface
(
InterfaceAnalysis
ia
)
throws
RMIIIOPViolationException
,
IRConstructionException
{
InterfaceDefImpl
iDef
;
Class
cls
=
ia
.
getCls
(
)
;
// Lookup: Has it already been added?
iDef
=
(
InterfaceDefImpl
)
interfaceMap
.
get
(
cls
)
;
if
(
iDef
!=
)
return
iDef
;
// Yes, just return it.
// Get module to add interface to.
ModuleDefImpl
m
=
ensurePackageExists
(
cls
.
getPackage
(
)
.
getName
(
)
)
;
// Add superinterfaces
String
[
]
base_interfaces
=
addInterfaces
(
ia
)
;
// Create the interface
String
base
=
cls
.
getName
(
)
;
base
=
base
.
substring
(
base
.
lastIndexOf
(
'
'
)
+
1
)
;
base
=
Util
.
javaToIDLName
(
base
)
;
iDef
=
new
InterfaceDefImpl
(
ia
.
getRepositoryId
(
)
,
base
,
"1.0"
,
m
,
base_interfaces
,
impl
)
;
addTypeCode
(
cls
,
iDef
.
type
(
)
)
;
m
.
add
(
base
,
iDef
)
;
interfaceMap
.
put
(
cls
,
iDef
)
;
// Remember we mapped this.
// Fill in constants
addConstants
(
iDef
,
ia
)
;
// Add attributes
addAttributes
(
iDef
,
ia
)
;
// Fill in operations
addOperations
(
iDef
,
ia
)
;
return
iDef
;
}


private ValueDefImpl addValue(ValueAnalysis va)
            throws RMIIIOPViolationException, IRConstructionException {
        ValueDefImpl vDef;
        Class cls = va.getCls();

        // Lookup: Has it already been added?
        vDef = (ValueDefImpl) valueMap.get(cls);
        if (vDef != null)
            return vDef; // Yes, just return it.

        // Get module to add value to.
        ModuleDefImpl m = ensurePackageExists(cls.getPackage().getName());

        // Add implemented interfaces
        String[] supported_interfaces = addInterfaces(va);

        // Add abstract base valuetypes
        String[] abstract_base_valuetypes = addAbstractBaseValuetypes(va);

        // Add superclass
        ValueDefImpl superValue = null;
        ValueAnalysis superAnalysis = va.getSuperAnalysis();
        if (superAnalysis != null)
            superValue = addValue(superAnalysis);

        // Create the value
        String base = cls.getName();
        base = base.substring(base.lastIndexOf('.') + 1);
        base = Util.javaToIDLName(base);

        TypeCode baseTypeCode;
        if (superValue == null)
            baseTypeCode = orb.get_primitive_tc(TCKind.tk_null);
        else
            baseTypeCode = superValue.type();

        vDef = new ValueDefImpl(va.getRepositoryId(), base, "1.0",
                m,
                va.isAbstractValue(),
                va.isCustom(),
                supported_interfaces,
                abstract_base_valuetypes,
                baseTypeCode,
                impl);
        addTypeCode(cls, vDef.type());
        m.add(base, vDef);
        valueMap.put(cls, vDef); // Remember we mapped this.

        // Fill in constants.
        addConstants(vDef, va);

        // Add value members
        ValueMemberAnalysis[] vmas = va.getMembers();
        for (int i = 0; i < vmas.length; ++i) {
            ValueMemberDefImpl vmDef;
            String vmid = va.getMemberRepositoryId(vmas[i].getJavaName());
            String vmName = vmas[i].getIDLName();

            Class vmCls = vmas[i].getCls();
            TypeCode typeCode = getTypeCode(vmCls);

            boolean vmPublic = vmas[i].isPublic();

            vmDef = new ValueMemberDefImpl(vmid, vmName, "1.0",
                    typeCode, vmPublic, vDef, impl);
            vDef.add(vmName, vmDef);
        }

        // Add attributes
        addAttributes(vDef, va);

        // TODO: Fill in operations.

        return vDef;
    }

private
ValueDefImpl
addValue
(
ValueAnalysis
va
)
throws
RMIIIOPViolationException
,
IRConstructionException
{
ValueDefImpl
vDef
;
Class
cls
=
va
.
getCls
(
)
;
// Lookup: Has it already been added?
vDef
=
(
ValueDefImpl
)
valueMap
.
get
(
cls
)
;
if
(
vDef
!=
)
return
vDef
;
// Yes, just return it.
// Get module to add value to.
ModuleDefImpl
m
=
ensurePackageExists
(
cls
.
getPackage
(
)
.
getName
(
)
)
;
// Add implemented interfaces
String
[
]
supported_interfaces
=
addInterfaces
(
va
)
;
// Add abstract base valuetypes
String
[
]
abstract_base_valuetypes
=
addAbstractBaseValuetypes
(
va
)
;
// Add superclass
ValueDefImpl
superValue
=
;
ValueAnalysis
superAnalysis
=
va
.
getSuperAnalysis
(
)
;
if
(
superAnalysis
!=
)
superValue
=
addValue
(
superAnalysis
)
;
// Create the value
String
base
=
cls
.
getName
(
)
;
base
=
base
.
substring
(
base
.
lastIndexOf
(
'
'
)
+
1
)
;
base
=
Util
.
javaToIDLName
(
base
)
;
TypeCode
baseTypeCode
;
if
(
superValue
==
)
baseTypeCode
=
orb
.
get_primitive_tc
(
TCKind
.
tk_null
)
;
else
baseTypeCode
=
superValue
.
type
(
)
;
vDef
=
new
ValueDefImpl
(
va
.
getRepositoryId
(
)
,
base
,
"1.0"
,
m
,
va
.
isAbstractValue
(
)
,
va
.
isCustom
(
)
,
supported_interfaces
,
abstract_base_valuetypes
,
baseTypeCode
,
impl
)
;
addTypeCode
(
cls
,
vDef
.
type
(
)
)
;
m
.
add
(
base
,
vDef
)
;
valueMap
.
put
(
cls
,
vDef
)
;
// Remember we mapped this.
// Fill in constants.
addConstants
(
vDef
,
va
)
;
// Add value members
ValueMemberAnalysis
[
]
vmas
=
va
.
getMembers
(
)
;
for
(
int
i
=
0
;
i
<
vmas
.
length
;
++
i
)
{
ValueMemberDefImpl
vmDef
;
String
vmid
=
va
.
getMemberRepositoryId
(
vmas
[
i
]
.
getJavaName
(
)
)
;
String
vmName
=
vmas
[
i
]
.
getIDLName
(
)
;
Class
vmCls
=
vmas
[
i
]
.
getCls
(
)
;
TypeCode
typeCode
=
getTypeCode
(
vmCls
)
;
boolean
vmPublic
=
vmas
[
i
]
.
isPublic
(
)
;
vmDef
=
new
ValueMemberDefImpl
(
vmid
,
vmName
,
"1.0"
,
typeCode
,
vmPublic
,
vDef
,
impl
)
;
vDef
.
add
(
vmName
,
vmDef
)
;
}
// Add attributes
addAttributes
(
vDef
,
va
)
;
// TODO: Fill in operations.
return
vDef
;
}


private ExceptionDefImpl addException(ExceptionAnalysis ea)
            throws RMIIIOPViolationException, IRConstructionException {
        ExceptionDefImpl eDef;
        Class cls = ea.getCls();

        // Lookup: Has it already been added?
        eDef = (ExceptionDefImpl) exceptionMap.get(cls);
        if (eDef != null)
            return eDef; // Yes, just return it.

        // 1.3.7.1: map to value
        ValueDefImpl vDef = addValue(ea);

        // 1.3.7.2: map to exception
        ModuleDefImpl m = ensurePackageExists(cls.getPackage().getName());
        String base = cls.getName();
        base = base.substring(base.lastIndexOf('.') + 1);
        if (base.endsWith("Exception"))
            base = base.substring(0, base.length() - 9);
        base = Util.javaToIDLName(base + "Ex");

        StructMember[] members = new StructMember[1];
        members[0] = new StructMember("value", vDef.type(), null/*ignored*/);
        TypeCode typeCode
                = orb.create_exception_tc(ea.getExceptionRepositoryId(),
                base, members);

        eDef = new ExceptionDefImpl(ea.getExceptionRepositoryId(), base, "1.0",
                typeCode, vDef, m, impl);
        m.add(base, eDef);
        exceptionMap.put(cls, eDef); // Remember we mapped this.

        return eDef;
    }

private
ExceptionDefImpl
addException
(
ExceptionAnalysis
ea
)
throws
RMIIIOPViolationException
,
IRConstructionException
{
ExceptionDefImpl
eDef
;
Class
cls
=
ea
.
getCls
(
)
;
// Lookup: Has it already been added?
eDef
=
(
ExceptionDefImpl
)
exceptionMap
.
get
(
cls
)
;
if
(
eDef
!=
)
return
eDef
;
// Yes, just return it.
// 1.3.7.1: map to value
ValueDefImpl
vDef
=
addValue
(
ea
)
;
// 1.3.7.2: map to exception
ModuleDefImpl
m
=
ensurePackageExists
(
cls
.
getPackage
(
)
.
getName
(
)
)
;
String
base
=
cls
.
getName
(
)
;
base
=
base
.
substring
(
base
.
lastIndexOf
(
'
'
)
+
1
)
;
if
(
base
.
endsWith
(
"Exception"
)
)
base
=
base
.
substring
(
0
,
base
.
length
(
)
9
)
;
base
=
Util
.
javaToIDLName
(
base
+
"Ex"
)
;
StructMember
[
]
members
=
new
StructMember
[
1
]
;
members
[
0
]
=
new
StructMember
(
"value"
,
vDef
.
type
(
)
,
/*ignored*/
)
;
TypeCode
typeCode
=
orb
.
create_exception_tc
(
ea
.
getExceptionRepositoryId
(
)
,
base
,
members
)
;
eDef
=
new
ExceptionDefImpl
(
ea
.
getExceptionRepositoryId
(
)
,
base
,
"1.0"
,
typeCode
,
vDef
,
m
,
impl
)
;
m
.
add
(
base
,
eDef
)
;
exceptionMap
.
put
(
cls
,
eDef
)
;
// Remember we mapped this.
return
eDef
;
}


private String getClassLevelInjectionType(final AnnotationInstance annotation) {
        boolean isPC = annotation.name().local().equals("PersistenceContext");
        return isPC ? ENTITY_MANAGER_CLASS : ENTITY_MANAGERFACTORY_CLASS;
    }

private String getClassLevelInjectionType ( final AnnotationInstance annotation ) { boolean isPC = annotation . name ( ) . local ( ) . equals ( "PersistenceContext" ) ; return isPC ? ENTITY_MANAGER_CLASS : ENTITY_MANAGERFACTORY_CLASS ; }

Based on the the annotation type, its either entitymanager or entitymanagerfactory

@param annotation
@return

Based on the the annotation type its either entitymanager or entitymanagerfactory


private boolean checkJtsEnabled(final OperationContext context) {
        try {
            final ModelNode jtsNode = context.readResourceFromRoot(PathAddress.pathAddress("subsystem", "transactions"), false)
                    .getModel().get("jts");
            return jtsNode.isDefined() ? jtsNode.asBoolean() : false;
        } catch (NoSuchResourceException ex) {
            return false;
        }
    }

private boolean checkJtsEnabled ( final OperationContext context ) { try { final ModelNode jtsNode = context . readResourceFromRoot ( PathAddress . pathAddress ( "subsystem" , "transactions" ) , false ) . getModel ( ) . get ( "jts" ) ; return jtsNode . isDefined ( ) ? jtsNode . asBoolean ( ) : false ; } catch ( NoSuchResourceException ex ) { return false ; } }


public void start(final StartContext context) throws StartException {
        if(store == null) {
            final ServiceRegistry serviceRegistry = context.getController().getServiceContainer();
            final ServiceName serviceNameBase = context.getController().getName();
            final ServiceTarget serviceTarget = context.getChildTarget();
            store = readOnly ? new ServiceBasedNamingStore(serviceRegistry, serviceNameBase) : new WritableServiceBasedNamingStore(serviceRegistry, serviceNameBase, serviceTarget);
        }
    }

public void start ( final StartContext context ) throws StartException { if ( store == null ) { final ServiceRegistry serviceRegistry = context . getController ( ) . getServiceContainer ( ) ; final ServiceName serviceNameBase = context . getController ( ) . getName ( ) ; final ServiceTarget serviceTarget = context . getChildTarget ( ) ; store = readOnly ? new ServiceBasedNamingStore ( serviceRegistry , serviceNameBase ) : new WritableServiceBasedNamingStore ( serviceRegistry , serviceNameBase , serviceTarget ) ; } }

Creates the naming store if not provided by the constructor.

@param context The start context
@throws StartException If any problems occur creating the context

Creates the naming store if not provided by the constructor .


public void stop(StopContext context) {
        if(store != null) {
            try {
                store.close();
                store = null;
            } catch (NamingException e) {
                throw NamingLogger.ROOT_LOGGER.failedToDestroyRootContext(e);
            }
        }
    }

public void stop ( StopContext context ) { if ( store != null ) { try { store . close ( ) ; store = null ; } catch ( NamingException e ) { throw NamingLogger . ROOT_LOGGER . failedToDestroyRootContext ( e ) ; } } }

Destroys the naming store.

@param context The stop context


public static void checkAllowed(final MethodType methodType) {

        final InterceptorContext context = CurrentInvocationContext.get();
        if (context == null) {
            return;
        }

        final Component component = context.getPrivateData(Component.class);
        if (!(component instanceof EJBComponent)) {
            return;
        }
        final InvocationType invocationType = context.getPrivateData(InvocationType.class);

        ((EJBComponent) component).getAllowedMethodsInformation().realCheckPermission(methodType, invocationType);

    }

public static void checkAllowed ( final MethodType methodType ) { final InterceptorContext context = CurrentInvocationContext . get ( ) ; if ( context == null ) { return ; } final Component component = context . getPrivateData ( Component . class ) ; if ( ! ( component instanceof EJBComponent ) ) { return ; } final InvocationType invocationType = context . getPrivateData ( InvocationType . class ) ; ( ( EJBComponent ) component ) . getAllowedMethodsInformation ( ) . realCheckPermission ( methodType , invocationType ) ; }


private void checkTransactionSync(MethodType methodType) {
        //first we have to check the synchronization status
        //as the sync is not affected by the current invocation
        final CurrentSynchronizationCallback.CallbackType currentSync = CurrentSynchronizationCallback.get();
        if (currentSync != null) {
            if (deniedSyncMethods.contains(new DeniedSyncMethodKey(currentSync, methodType))) {
                throwException(methodType, currentSync);
            }
        }
    }

transaction sync is not affected by the current invocation, as multiple ejb methods may be invoked from afterCompletion

transaction sync is not affected by the current invocation as multiple ejb methods may be invoked from afterCompletion


private Set<String> getAllComponentClasses(DeploymentUnit deploymentUnit, CompositeIndex index, WarMetaData metaData, TldsMetaData tldsMetaData) {
        final Set<String> classes = new HashSet<String>();
        getAllComponentClasses(metaData.getMergedJBossWebMetaData(), classes);
        if (tldsMetaData == null)
            return classes;
        if (tldsMetaData.getSharedTlds(deploymentUnit) != null)
            for (TldMetaData tldMetaData : tldsMetaData.getSharedTlds(deploymentUnit)) {
                getAllComponentClasses(tldMetaData, classes);
            }
        if (tldsMetaData.getTlds() != null)
            for (Map.Entry<String, TldMetaData> tldMetaData : tldsMetaData.getTlds().entrySet()) {
                getAllComponentClasses(tldMetaData.getValue(), classes);
            }
        getAllAsyncListenerClasses(index, classes);
        return classes;
    }

private Set < String > getAllComponentClasses ( DeploymentUnit deploymentUnit , CompositeIndex index , WarMetaData metaData , TldsMetaData tldsMetaData ) { final Set < String > classes = new HashSet < String > ( ) ; getAllComponentClasses ( metaData . getMergedJBossWebMetaData ( ) , classes ) ; if ( tldsMetaData == null ) return classes ; if ( tldsMetaData . getSharedTlds ( deploymentUnit ) != null ) for ( TldMetaData tldMetaData : tldsMetaData . getSharedTlds ( deploymentUnit ) ) { getAllComponentClasses ( tldMetaData , classes ) ; } if ( tldsMetaData . getTlds ( ) != null ) for ( Map . Entry < String , TldMetaData > tldMetaData : tldsMetaData . getTlds ( ) . entrySet ( ) ) { getAllComponentClasses ( tldMetaData . getValue ( ) , classes ) ; } getAllAsyncListenerClasses ( index , classes ) ; return classes ; }

Gets all classes that are eligible for injection etc

@param metaData
@return


private Map<String, TimerImpl> getWaitingOnTxCompletionTimers() {
        Map<String, TimerImpl> timers = null;
        if (getTransaction() != null) {
            timers = (Map<String, TimerImpl>) tsr.getResource(waitingOnTxCompletionKey);
        }
        return timers == null ? Collections.<String, TimerImpl>emptyMap() : timers;
    }

private Map < String , TimerImpl > getWaitingOnTxCompletionTimers ( ) { Map < String , TimerImpl > timers = null ; if ( getTransaction ( ) != null ) { timers = ( Map < String , TimerImpl > ) tsr . getResource ( waitingOnTxCompletionKey ) ; } return timers == null ? Collections . < String , TimerImpl > emptyMap ( ) : timers ; }

Returns an unmodifiable view of timers in the current transaction that are waiting for the transaction
to finish


private static Map<String, Object> getExtraParameters(final Set<String> allowedKeys, final Map<String, Object> parameters) {
        Map<String, Object> extraParameters = new HashMap<>();
        for(Map.Entry<String, Object> parameter : parameters.entrySet()) {
            if(!allowedKeys.contains(parameter.getKey())) {
                extraParameters.put(parameter.getKey(), parameter.getValue());
            }
        }
        for (String extraParam : extraParameters.keySet()) {
            parameters.remove(extraParam);
        }
        return extraParameters;
    }

private static Map < String , Object > getExtraParameters ( final Set < String > allowedKeys , final Map < String , Object > parameters ) { Map < String , Object > extraParameters = new HashMap <> ( ) ; for ( Map . Entry < String , Object > parameter : parameters . entrySet ( ) ) { if ( ! allowedKeys . contains ( parameter . getKey ( ) ) ) { extraParameters . put ( parameter . getKey ( ) , parameter . getValue ( ) ) ; } } for ( String extraParam : extraParameters . keySet ( ) ) { parameters . remove ( extraParam ) ; } return extraParameters ; }

Extract extra parameters from the map of parameters.
@param allowedKeys: the keys for allowed parameters.
@param parameters all the parameters (allowed and extra).
@return a Map of extra parameters (those that are not allowed).

Extract extra parameters from the map of parameters .


public static Map<String, Object> getParameters(final OperationContext context, final ModelNode config, final Map<String, String> mapping) throws OperationFailedException {
        Map<String, String> fromModel = CommonAttributes.PARAMS.unwrap(context, config);
        Map<String, Object> parameters = new HashMap<>();
        for (Map.Entry<String, String> entry : fromModel.entrySet()) {
            parameters.put(mapping.getOrDefault(entry.getKey(), entry.getKey()), entry.getValue());
        }
        return parameters;
    }

public static Map < String , Object > getParameters ( final OperationContext context , final ModelNode config , final Map < String , String > mapping ) throws OperationFailedException { Map < String , String > fromModel = CommonAttributes . PARAMS . unwrap ( context , config ) ; Map < String , Object > parameters = new HashMap <> ( ) ; for ( Map . Entry < String , String > entry : fromModel . entrySet ( ) ) { parameters . put ( mapping . getOrDefault ( entry . getKey ( ) , entry . getKey ( ) ) , entry . getValue ( ) ) ; } return parameters ; }

Get the parameters.

@param context the operation context
@param config the transport configuration
@param mapping Mapping betwen WildFly parameters (keys) and Artemis constants (values)
@return the extracted parameters
@throws OperationFailedException if an expression can not be resolved


public static Class<?> toClass(Type type) {
        if (type instanceof Class) {
            return (Class) type;
        } else if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            return toClass(pt.getRawType());
        } else {
            throw PojoLogger.ROOT_LOGGER.unknownType(type);
        }
    }

public static Class < ? > toClass ( Type type ) { if ( type instanceof Class ) { return ( Class ) type ; } else if ( type instanceof ParameterizedType ) { ParameterizedType pt = ( ParameterizedType ) type ; return toClass ( pt . getRawType ( ) ) ; } else { throw PojoLogger . ROOT_LOGGER . unknownType ( type ) ; } }

Turn type into class.

@param type the type
@return class


@SuppressWarnings("unchecked")
    public static Object convertValue(Class<?> clazz, Object value, boolean replaceProperties, boolean trim) throws Throwable {
        if (clazz == null)
            return value;
        if (value == null)
            return null;

        Class<?> valueClass = value.getClass();

        // If we have a string, trim and replace any system properties when requested
        if (valueClass == String.class) {
            String string = (String) value;
            if (trim)
                string = string.trim();
            if (replaceProperties)
                value = PropertiesValueResolver.replaceProperties(string);
        }

        if (clazz.isAssignableFrom(valueClass))
            return value;

        // First see if this is an Enum
        if (clazz.isEnum()) {
            Class<? extends Enum> eclazz = clazz.asSubclass(Enum.class);
            return Enum.valueOf(eclazz, value.toString());
        }

        // Next look for a property editor
        if (valueClass == String.class) {
            PropertyEditor editor = PropertyEditorManager.findEditor(clazz);
            if (editor != null) {
                editor.setAsText((String) value);
                return editor.getValue();
            }
        }

        // Try a static clazz.valueOf(value)
        try {
            Method method = clazz.getMethod("valueOf", valueClass);
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                    && clazz.isAssignableFrom(method.getReturnType()))
                return method.invoke(null, value);
        } catch (Exception ignored) {
        }

        if (valueClass == String.class) {
            try {
                Constructor constructor = clazz.getConstructor(valueClass);
                if (Modifier.isPublic(constructor.getModifiers()))
                    return constructor.newInstance(value);
            } catch (Exception ignored) {
            }
        }

        return value;
    }

Convert a value

@param clazz             the class
@param value             the value
@param replaceProperties whether to replace system properties
@param trim              whether to trim string value
@return the value or null if there is no editor
@throws Throwable for any error


public static String[] getTypes(ValueConfig[] values) {
        if (values == null || values.length == 0)
            return NO_PARAMS_TYPES;

        String[] types = new String[values.length];
        for (int i =0; i < types.length; i++)
            types[i] = values[i].getType();
        return types;
    }

public static String [ ] getTypes ( ValueConfig [ ] values ) { if ( values == null || values . length == 0 ) return NO_PARAMS_TYPES ; String [ ] types = new String [ values . length ] ; for ( int i = 0 ; i < types . length ; i ++ ) types [ i ] = values [ i ] . getType ( ) ; return types ; }

Get types from values.

@param values the values
@return the values' types


protected static boolean simpleCheck(String[] typeNames, Class<?>[] typeInfos) {
        return typeNames != null && typeInfos != null && typeNames.length == typeInfos.length;
    }

protected static boolean simpleCheck ( String [ ] typeNames , Class < ? > [ ] typeInfos ) { return typeNames != null && typeInfos != null && typeNames . length == typeInfos . length ; }

A simple null and length check.

@param typeNames the type names
@param typeInfos the type infos
@return false if either argument is null or lengths differ, else true


public java.lang.Object next() throws NamingException {
        if (more && counter >= _bindingList.value.length) {
            getMore();
        }
        if (more && counter < _bindingList.value.length) {
            org.omg.CosNaming.Binding bndg = _bindingList.value[counter];
            counter++;
            return mapBinding(bndg);
        } else {
            throw new NoSuchElementException();
        }
    }

public java . lang . Object next ( ) throws NamingException { if ( more && counter >= _bindingList . value . length ) { getMore ( ) ; } if ( more && counter < _bindingList . value . length ) { org . omg . CosNaming . Binding bndg = _bindingList . value [ counter ] ; counter ++ ; return mapBinding ( bndg ) ; } else { throw new NoSuchElementException ( ) ; } }

Returns the next binding in the list.

@throws NamingException any naming exception.


private boolean getMore() throws NamingException {
        try {
            more = _bindingIter.next_n(batchsize, _bindingList);
            counter = 0; // reset
        } catch (Exception e) {
            more = false;
            NamingException ne = IIOPLogger.ROOT_LOGGER.errorGettingBindingList();
            ne.setRootCause(e);
            throw ne;
        }
        return more;
    }

private
boolean
getMore
(
)
throws
NamingException
{
try
{
more
=
_bindingIter
.
next_n
(
batchsize
,
_bindingList
)
;
counter
=
0
;
// reset
}
catch
(
Exception
e
)
{
more
=
false
;
NamingException
ne
=
IIOPLogger
.
ROOT_LOGGER
.
errorGettingBindingList
(
)
;
ne
.
setRootCause
(
e
)
;
throw
ne
;
}
return
more
;
}

Get the next batch using _bindingIter. Update the 'more' field.

Get the next batch using _bindingIter . Update the more field .


private javax.naming.Binding mapBinding(org.omg.CosNaming.Binding bndg)
            throws NamingException {
        java.lang.Object obj = _ctx.callResolve(bndg.binding_name);

        Name cname = org.wildfly.iiop.openjdk.naming.jndi.CNNameParser.cosNameToName(bndg.binding_name);

        try {
            obj = NamingManager.getObjectInstance(obj, cname, _ctx, _env);
        } catch (NamingException e) {
            throw e;
        } catch (Exception e) {
            NamingException ne = IIOPLogger.ROOT_LOGGER.errorGeneratingObjectViaFactory();
            ne.setRootCause(e);
            throw ne;
        }

        // Use cname.toString() instead of bindingName because the name
        // in the binding should be a composite name
        String cnameStr = cname.toString();
        javax.naming.Binding jbndg = new javax.naming.Binding(cnameStr, obj);

        NameComponent[] comps = _ctx.makeFullName(bndg.binding_name);
        String fullName = org.wildfly.iiop.openjdk.naming.jndi.CNNameParser.cosNameToInsString(comps);
        jbndg.setNameInNamespace(fullName);
        return jbndg;
    }

Constructs a JNDI Binding object from the COS Naming binding
object.

@throws org.omg.CosNaming.NamingContextPackage.CannotProceed   Unable to obtain a continuation context
@throws org.omg.CosNaming.NamingContextPackage.InvalidNameCNCtx     Name not understood.
@throws NamingException One of the above.

Constructs a JNDI Binding object from the COS Naming binding object .


public void observeResources(@Observes @WithAnnotations({Health.class})  ProcessAnnotatedType<? extends HealthCheck> event) {
        AnnotatedType<? extends HealthCheck> annotatedType = event.getAnnotatedType();
        Class<? extends HealthCheck> javaClass = annotatedType.getJavaClass();
        MicroProfileHealthLogger.LOGGER.infof("Discovered health check procedure %s", javaClass);
        delegates.add(annotatedType);
    }

public
void
observeResources
(
@
Observes
@
WithAnnotations
(
{
Health
.
class
}
)
ProcessAnnotatedType
<
extends
HealthCheck
>
event
)
{
AnnotatedType
<
extends
HealthCheck
>
annotatedType
=
event
.
getAnnotatedType
(
)
;
Class
<
extends
HealthCheck
>
javaClass
=
annotatedType
.
getJavaClass
(
)
;
MicroProfileHealthLogger
.
LOGGER
.
infof
(
"Discovered health check procedure %s"
,
javaClass
)
;
delegates
.
add
(
annotatedType
)
;
}

Discover all classes that implements HealthCheckProcedure


public void close(@Observes final BeforeShutdown bs) {
        healthCheckInstances.forEach(healthCheck -> {
            healthReporter.removeHealthCheck(healthCheck.get());
            healthCheck.preDestroy().dispose();
        });
        healthCheckInstances.clear();
    }

public void close ( @ Observes final BeforeShutdown bs ) { healthCheckInstances . forEach ( healthCheck -> { healthReporter . removeHealthCheck ( healthCheck . get ( ) ) ; healthCheck . preDestroy ( ) . dispose ( ) ; } ) ; healthCheckInstances . clear ( ) ; }

Called when the deployment is undeployed.

Remove all the instances of {@link HealthCheck} from the {@link SmallRyeHealthReporter}.
Handle manually their CDI destroy lifecycle.

Called when the deployment is undeployed .


public org.omg.CORBA.Object referenceForLocator(final EJBLocator<?> locator) {
        final EJBComponent ejbComponent = ejbComponentInjectedValue.getValue();
        try {
            final String earApplicationName = ejbComponent.getEarApplicationName() == null ? "" : ejbComponent.getEarApplicationName();
            if (locator.getBeanName().equals(ejbComponent.getComponentName()) &&
                    locator.getAppName().equals(earApplicationName) &&
                    locator.getModuleName().equals(ejbComponent.getModuleName()) &&
                    locator.getDistinctName().equals(ejbComponent.getDistinctName())) {
                if (locator instanceof EJBHomeLocator) {
                    return (org.omg.CORBA.Object) ejbHome;
                } else if (locator instanceof StatelessEJBLocator) {
                    return beanReferenceFactory.createReference(beanRepositoryIds[0]);
                } else if (locator instanceof StatefulEJBLocator) {
                    final Marshaller marshaller = factory.createMarshaller(configuration);
                    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    marshaller.start(new OutputStreamByteOutput(stream));
                    marshaller.writeObject(((StatefulEJBLocator<?>) locator).getSessionId());
                    marshaller.finish();
                    return beanReferenceFactory.createReferenceWithId(stream.toByteArray(), beanRepositoryIds[0]);
                } else if (locator instanceof EntityEJBLocator) {
                    final Marshaller marshaller = factory.createMarshaller(configuration);
                    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    marshaller.start(new OutputStreamByteOutput(stream));
                    marshaller.writeObject(((EntityEJBLocator<?>) locator).getPrimaryKey());
                    marshaller.finish();
                    return beanReferenceFactory.createReferenceWithId(stream.toByteArray(), beanRepositoryIds[0]);
                }
                throw EjbLogger.ROOT_LOGGER.unknownEJBLocatorType(locator);
            } else {
                throw EjbLogger.ROOT_LOGGER.incorrectEJBLocatorForBean(locator, ejbComponent.getComponentName());
            }
        } catch (Exception e) {
            throw EjbLogger.ROOT_LOGGER.couldNotCreateCorbaObject(e, locator);
        }
    }

public org . omg . CORBA . Object referenceForLocator ( final EJBLocator < ? > locator ) { final EJBComponent ejbComponent = ejbComponentInjectedValue . getValue ( ) ; try { final String earApplicationName = ejbComponent . getEarApplicationName ( ) == null ? "" : ejbComponent . getEarApplicationName ( ) ; if ( locator . getBeanName ( ) . equals ( ejbComponent . getComponentName ( ) ) && locator . getAppName ( ) . equals ( earApplicationName ) && locator . getModuleName ( ) . equals ( ejbComponent . getModuleName ( ) ) && locator . getDistinctName ( ) . equals ( ejbComponent . getDistinctName ( ) ) ) { if ( locator instanceof EJBHomeLocator ) { return ( org . omg . CORBA . Object ) ejbHome ; } else if ( locator instanceof StatelessEJBLocator ) { return beanReferenceFactory . createReference ( beanRepositoryIds [ 0 ] ) ; } else if ( locator instanceof StatefulEJBLocator ) { final Marshaller marshaller = factory . createMarshaller ( configuration ) ; final ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; marshaller . start ( new OutputStreamByteOutput ( stream ) ) ; marshaller . writeObject ( ( ( StatefulEJBLocator < ? > ) locator ) . getSessionId ( ) ) ; marshaller . finish ( ) ; return beanReferenceFactory . createReferenceWithId ( stream . toByteArray ( ) , beanRepositoryIds [ 0 ] ) ; } else if ( locator instanceof EntityEJBLocator ) { final Marshaller marshaller = factory . createMarshaller ( configuration ) ; final ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; marshaller . start ( new OutputStreamByteOutput ( stream ) ) ; marshaller . writeObject ( ( ( EntityEJBLocator < ? > ) locator ) . getPrimaryKey ( ) ) ; marshaller . finish ( ) ; return beanReferenceFactory . createReferenceWithId ( stream . toByteArray ( ) , beanRepositoryIds [ 0 ] ) ; } throw EjbLogger . ROOT_LOGGER . unknownEJBLocatorType ( locator ) ; } else { throw EjbLogger . ROOT_LOGGER . incorrectEJBLocatorForBean ( locator , ejbComponent . getComponentName ( ) ) ; } } catch ( Exception e ) { throw EjbLogger . ROOT_LOGGER . couldNotCreateCorbaObject ( e , locator ) ; } }

Returns a corba reference for the given locator

@param locator The locator
@return The corba reference


public Object handleForLocator(final EJBLocator<?> locator) {
        final org.omg.CORBA.Object reference = referenceForLocator(locator);
        if(locator instanceof EJBHomeLocator) {
            return new HomeHandleImplIIOP(orb.getValue().object_to_string(reference));
        }
        return new HandleImplIIOP(orb.getValue().object_to_string(reference));
    }

public Object handleForLocator ( final EJBLocator < ? > locator ) { final org . omg . CORBA . Object reference = referenceForLocator ( locator ) ; if ( locator instanceof EJBHomeLocator ) { return new HomeHandleImplIIOP ( orb . getValue ( ) . object_to_string ( reference ) ) ; } return new HandleImplIIOP ( orb . getValue ( ) . object_to_string ( reference ) ) ; }

Gets a handle for the given ejb locator.

@param locator The locator to get the handle for
@return The {@link org.jboss.ejb.client.EJBHandle} or {@link org.jboss.ejb.client.EJBHomeHandle}

Gets a handle for the given ejb locator .


public static <E extends Enum<E>> E asEnum(ModelNode value, Class<E> targetClass) {
        return Enum.valueOf(targetClass, value.asString());
    }

public static < E extends Enum < E > > E asEnum ( ModelNode value , Class < E > targetClass ) { return Enum . valueOf ( targetClass , value . asString ( ) ) ; }

Returns the value of the node as an Enum value.
@param value a model node
@return the value of the node as an Enum.

Returns the value of the node as an Enum value .


public static void skip(InputStream is, long amount) throws IOException {
        long leftToSkip = amount;
        long amountSkipped = 0;
        while(leftToSkip > 0 && amountSkipped >= 0){
            amountSkipped = is.skip(leftToSkip);
            leftToSkip -= amountSkipped;
        }
    }

public static void skip ( InputStream is , long amount ) throws IOException { long leftToSkip = amount ; long amountSkipped = 0 ; while ( leftToSkip > 0 && amountSkipped >= 0 ) { amountSkipped = is . skip ( leftToSkip ) ; leftToSkip -= amountSkipped ; } }

Ensure InputStream actually skips ahead the required number of bytes
@param is
@param amount
@throws IOException


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

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

Check that not both elements have been defined


public void addComponent(ComponentDescription description) {
        final String componentName = description.getComponentName();
        final String componentClassName = description.getComponentClassName();
        if (componentName == null) {
            throw EeLogger.ROOT_LOGGER.nullVar("componentName", "module", moduleName);
        }
        if (componentClassName == null) {
            throw EeLogger.ROOT_LOGGER.nullVar("componentClassName","module", moduleName);
        }
        if (componentsByName.containsKey(componentName)) {
            throw EeLogger.ROOT_LOGGER.componentAlreadyDefined(componentName);
        }
        componentsByName.put(componentName, description);
        List<ComponentDescription> list = componentsByClassName.get(componentClassName);
        if (list == null) {
            componentsByClassName.put(componentClassName, list = new ArrayList<ComponentDescription>(1));
        }
        list.add(description);
    }

public void addComponent ( ComponentDescription description ) { final String componentName = description . getComponentName ( ) ; final String componentClassName = description . getComponentClassName ( ) ; if ( componentName == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( "componentName" , "module" , moduleName ) ; } if ( componentClassName == null ) { throw EeLogger . ROOT_LOGGER . nullVar ( "componentClassName" , "module" , moduleName ) ; } if ( componentsByName . containsKey ( componentName ) ) { throw EeLogger . ROOT_LOGGER . componentAlreadyDefined ( componentName ) ; } componentsByName . put ( componentName , description ) ; List < ComponentDescription > list = componentsByClassName . get ( componentClassName ) ; if ( list == null ) { componentsByClassName . put ( componentClassName , list = new ArrayList < ComponentDescription > ( 1 ) ) ; } list . add ( description ) ; }

Add a component to this module.

@param description the component description


public static void addClassLoaders(ClassLoader topLevel, Set<ClassLoader> allClassLoaders) {
        deploymentClassLoaders.put(topLevel, allClassLoaders);
    }

public static void addClassLoaders ( ClassLoader topLevel , Set < ClassLoader > allClassLoaders ) { deploymentClassLoaders . put ( topLevel , allClassLoaders ) ; }

Maps a top level class loader to all CL's in the deployment

Maps a top level class loader to all CL s in the deployment


public void unbind(final Name name) throws NamingException {
        if (isLastComponentEmpty(name)) {
            throw emptyNameException();
        }

        writeLock.lock();
        try {
            root.accept(new UnbindVisitor(name));
        } finally {
            writeLock.unlock();
        }
    }

public void unbind ( final Name name ) throws NamingException { if ( isLastComponentEmpty ( name ) ) { throw emptyNameException ( ) ; } writeLock . lock ( ) ; try { root . accept ( new UnbindVisitor ( name ) ) ; } finally { writeLock . unlock ( ) ; } }

Unbind the entry in the provided location.  This will remove the node in the tree and no longer manage it.

@param name The entry name
@throws NamingException

Unbind the entry in the provided location . This will remove the node in the tree and no longer manage it .


public Object lookup(final Name name) throws NamingException {
        if (isEmpty(name)) {
            final Name emptyName = new CompositeName("");
            return new NamingContext(emptyName, this, new Hashtable<String, Object>());
        }
        return root.accept(new LookupVisitor(name));
    }

public Object lookup ( final Name name ) throws NamingException { if ( isEmpty ( name ) ) { final Name emptyName = new CompositeName ( "" ) ; return new NamingContext ( emptyName , this , new Hashtable < String , Object > ( ) ) ; } return root . accept ( new LookupVisitor ( name ) ) ; }

Lookup the object value of a binding node in the tree.

@param name The entry name
@return The object value of the binding
@throws NamingException

Lookup the object value of a binding node in the tree .


public List<NameClassPair> list(final Name name) throws NamingException {
        final Name nodeName = name.isEmpty() ? new CompositeName("") : name;
        return root.accept(new ListVisitor(nodeName));
    }

public List < NameClassPair > list ( final Name name ) throws NamingException { final Name nodeName = name . isEmpty ( ) ? new CompositeName ( "" ) : name ; return root . accept ( new ListVisitor ( nodeName ) ) ; }

List all NameClassPair instances at a given location in the tree.

@param name The entry name
@return The NameClassPair instances
@throws NamingException

List all NameClassPair instances at a given location in the tree .


public List<Binding> listBindings(final Name name) throws NamingException {
        final Name nodeName = name.isEmpty() ? new CompositeName("") : name;
        return root.accept(new ListBindingsVisitor(nodeName));
    }

public List < Binding > listBindings ( final Name name ) throws NamingException { final Name nodeName = name . isEmpty ( ) ? new CompositeName ( "" ) : name ; return root . accept ( new ListBindingsVisitor ( nodeName ) ) ; }

List all the Binding instances at a given location in the tree.

@param name The entry name
@return The Binding instances
@throws NamingException

List all the Binding instances at a given location in the tree .


public synchronized void addFactory(ContextHandleFactory factory) {
        final String factoryName = factory.getName();
        if(factoryMap.containsKey(factoryName)) {
            throw EeLogger.ROOT_LOGGER.factoryAlreadyExists(this, factoryName);
        }
        factoryMap.put(factoryName, factory);
        final Comparator<ContextHandleFactory> comparator = new Comparator<ContextHandleFactory>() {
            @Override
            public int compare(ContextHandleFactory o1, ContextHandleFactory o2) {
                return Integer.compare(o1.getChainPriority(),o2.getChainPriority());
            }
        };
        SortedSet<ContextHandleFactory> sortedSet = new TreeSet<>(comparator);
        sortedSet.addAll(factoryMap.values());
        factoryOrderedList = new ArrayList<>(sortedSet);
    }

public synchronized void addFactory ( ContextHandleFactory factory ) { final String factoryName = factory . getName ( ) ; if ( factoryMap . containsKey ( factoryName ) ) { throw EeLogger . ROOT_LOGGER . factoryAlreadyExists ( this , factoryName ) ; } factoryMap . put ( factoryName , factory ) ; final Comparator < ContextHandleFactory > comparator = new Comparator < ContextHandleFactory > ( ) { @ Override public int compare ( ContextHandleFactory o1 , ContextHandleFactory o2 ) { return Integer . compare ( o1 . getChainPriority ( ) , o2 . getChainPriority ( ) ) ; } } ; SortedSet < ContextHandleFactory > sortedSet = new TreeSet <> ( comparator ) ; sortedSet . addAll ( factoryMap . values ( ) ) ; factoryOrderedList = new ArrayList <> ( sortedSet ) ; }


public SetupContextHandle saveContext(ContextService contextService, Map<String, String> contextObjectProperties) {
        final List<SetupContextHandle> handles = new ArrayList<>(factoryOrderedList.size());
        for (ContextHandleFactory factory : factoryOrderedList) {
            handles.add(factory.saveContext(contextService, contextObjectProperties));
        }
        return new ChainedSetupContextHandle(this, handles);
    }

public SetupContextHandle saveContext ( ContextService contextService , Map < String , String > contextObjectProperties ) { final List < SetupContextHandle > handles = new ArrayList <> ( factoryOrderedList . size ( ) ) ; for ( ContextHandleFactory factory : factoryOrderedList ) { handles . add ( factory . saveContext ( contextService , contextObjectProperties ) ) ; } return new ChainedSetupContextHandle ( this , handles ) ; }

Saves the current invocation context on a chained context handle.
@param contextService
@param contextObjectProperties
@return

Saves the current invocation context on a chained context handle .


private void createIoSubsystem(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, PathAddress baseAddress) {
        Resource root = context.readResourceFromRoot(baseAddress, false);
        if (root.getChildrenNames(SUBSYSTEM).contains(IOExtension.SUBSYSTEM_NAME)) {
            // subsystem is already added, do nothing
            return;
        }

        //these addresses will be fixed later, no need to use the base address
        PathAddress address = pathAddress(pathElement(SUBSYSTEM, IOExtension.SUBSYSTEM_NAME));
        migrationOperations.put(address, createAddOperation(address));
        address = pathAddress(pathElement(SUBSYSTEM, IOExtension.SUBSYSTEM_NAME), pathElement("worker", "default"));
        migrationOperations.put(address, createAddOperation(address));
        address = pathAddress(pathElement(SUBSYSTEM, IOExtension.SUBSYSTEM_NAME), pathElement("buffer-pool", "default"));
        migrationOperations.put(address, createAddOperation(address));

    }

We need to create the IO subsystem, if it does not already exist

We need to create the IO subsystem if it does not already exist


private void createWelcomeContentHandler(Map<PathAddress, ModelNode> migrationOperations) {

        PathAddress address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.CONFIGURATION, Constants.HANDLER));
        migrationOperations.put(address, createAddOperation(address));

        address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.CONFIGURATION, Constants.HANDLER), pathElement(Constants.FILE, "welcome-content"));
        final ModelNode add = createAddOperation(address);
        add.get(Constants.PATH).set(new ModelNode(new ValueExpression("${jboss.home.dir}/welcome-content")));
        migrationOperations.put(address, add);
    }

private void createWelcomeContentHandler ( Map < PathAddress , ModelNode > migrationOperations ) { PathAddress address = pathAddress ( pathElement ( SUBSYSTEM , UndertowExtension . SUBSYSTEM_NAME ) , pathElement ( Constants . CONFIGURATION , Constants . HANDLER ) ) ; migrationOperations . put ( address , createAddOperation ( address ) ) ; address = pathAddress ( pathElement ( SUBSYSTEM , UndertowExtension . SUBSYSTEM_NAME ) , pathElement ( Constants . CONFIGURATION , Constants . HANDLER ) , pathElement ( Constants . FILE , "welcome-content" ) ) ; final ModelNode add = createAddOperation ( address ) ; add . get ( Constants . PATH ) . set ( new ModelNode ( new ValueExpression ( "${jboss.home.dir}/welcome-content" ) ) ) ; migrationOperations . put ( address , add ) ; }

create a handler for serving welcome content


public T get() {
        try {
            boolean acquired = semaphore.tryAcquire(timeout, timeUnit);
            if (!acquired)
                throw EjbLogger.ROOT_LOGGER.failedToAcquirePermit(timeout, timeUnit);
        } catch (InterruptedException e) {
            throw EjbLogger.ROOT_LOGGER.acquireSemaphoreInterrupted();
        }

        T bean = pool.poll();

        if( bean !=null) {
            //we found a bean instance in the pool, return it
            return bean;
        }

        try {
            // Pool is empty, create an instance
            bean = create();
        } finally {
            if (bean == null) {
                semaphore.release();
            }
        }
        return bean;
    }

Get an instance without identity.
Can be used by finders,create-methods, and activation

@return Context /w instance

Get an instance without identity . Can be used by finders create - methods and activation


protected void calculateOperationAnalysisMap() {
        operationAnalysisMap = new HashMap();
        OperationAnalysis oa;

        // Map the operations
        for (int i = 0; i < operations.length; ++i) {
            oa = operations[i];
            operationAnalysisMap.put(oa.getIDLName(), oa);
        }

        // Map the attributes
        for (int i = 0; i < attributes.length; ++i) {
            AttributeAnalysis attr = attributes[i];

            oa = attr.getAccessorAnalysis();

            // Not having an accessor analysis means that
            // the attribute is not in a remote interface
            if (oa != null) {
                operationAnalysisMap.put(oa.getIDLName(), oa);

                oa = attr.getMutatorAnalysis();
                if (oa != null)
                    operationAnalysisMap.put(oa.getIDLName(), oa);
            }
        }
    }

Calculate the map that maps IDL operation names to operation analyses.
Besides mapped operations, this map also contains the attribute
accessor and mutator operations.

Calculate the map that maps IDL operation names to operation analyses . Besides mapped operations this map also contains the attribute accessor and mutator operations .


public MetricRegistration collectResourceMetrics(final Resource resource,
                                              ImmutableManagementResourceRegistration managementResourceRegistration,
                                              Function<PathAddress, PathAddress> resourceAddressResolver) {
        MetricRegistration registration = new MetricRegistration();
        collectResourceMetrics0(resource, managementResourceRegistration, EMPTY_ADDRESS, resourceAddressResolver, registration);
        return registration;
    }

public MetricRegistration collectResourceMetrics ( final Resource resource , ImmutableManagementResourceRegistration managementResourceRegistration , Function < PathAddress , PathAddress > resourceAddressResolver ) { MetricRegistration registration = new MetricRegistration ( ) ; collectResourceMetrics0 ( resource , managementResourceRegistration , EMPTY_ADDRESS , resourceAddressResolver , registration ) ; return registration ; }


protected DeploymentUnit doPrepare(String context, ClassLoader loader,
            Map<String, String> urlPatternToClassNameMap, JBossWebMetaData jbwmd, WebservicesMetaData metadata, JBossWebservicesMetaData jbwsMetadata) {
        ClassLoader origClassLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        WSEndpointDeploymentUnit unit = new WSEndpointDeploymentUnit(loader, context, urlPatternToClassNameMap, jbwmd, metadata, jbwsMetadata);
        try {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader());
            WSDeploymentBuilder.getInstance().build(unit);
            return unit;
        } finally {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(origClassLoader);
        }
    }

protected DeploymentUnit doPrepare ( String context , ClassLoader loader , Map < String , String > urlPatternToClassNameMap , JBossWebMetaData jbwmd , WebservicesMetaData metadata , JBossWebservicesMetaData jbwsMetadata ) { ClassLoader origClassLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; WSEndpointDeploymentUnit unit = new WSEndpointDeploymentUnit ( loader , context , urlPatternToClassNameMap , jbwmd , metadata , jbwsMetadata ) ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ) ; WSDeploymentBuilder . getInstance ( ) . build ( unit ) ; return unit ; } finally { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( origClassLoader ) ; } }

Prepare the ws Deployment and return a DeploymentUnit containing it

@param context
@param loader
@param urlPatternToClassNameMap
@param jbwmd
@param metadata
@param jbwsMetadata
@return


protected void doDeploy(ServiceTarget target, DeploymentUnit unit) {
        List<DeploymentAspect> aspects = getDeploymentAspects();
        ClassLoader origClassLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        Deployment dep = null;
        try {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(ClassLoaderProvider.getDefaultProvider().getServerIntegrationClassLoader());
            dep = unit.getAttachment(WSAttachmentKeys.DEPLOYMENT_KEY);
            dep.addAttachment(ServiceTarget.class, target);
            DeploymentAspectManager dam = new DeploymentAspectManagerImpl();
            dam.setDeploymentAspects(aspects);
            dam.deploy(dep);
        } finally {
            if (dep != null) {
                dep.removeAttachment(ServiceTarget.class);
            }
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(origClassLoader);
        }
    }

protected void doDeploy ( ServiceTarget target , DeploymentUnit unit ) { List < DeploymentAspect > aspects = getDeploymentAspects ( ) ; ClassLoader origClassLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; Deployment dep = null ; try { WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( ClassLoaderProvider . getDefaultProvider ( ) . getServerIntegrationClassLoader ( ) ) ; dep = unit . getAttachment ( WSAttachmentKeys . DEPLOYMENT_KEY ) ; dep . addAttachment ( ServiceTarget . class , target ) ; DeploymentAspectManager dam = new DeploymentAspectManagerImpl ( ) ; dam . setDeploymentAspects ( aspects ) ; dam . deploy ( dep ) ; } finally { if ( dep != null ) { dep . removeAttachment ( ServiceTarget . class ) ; } WildFlySecurityManager . setCurrentContextClassLoaderPrivileged ( origClassLoader ) ; } }

Triggers the WS deployment aspects, which process the deployment and
install the endpoint services.

@param target
@param unit

Triggers the WS deployment aspects which process the deployment and install the endpoint services .


protected Context doPublish(ServiceTarget target, DeploymentUnit unit) throws Exception {
        Deployment deployment = unit.getAttachment(WSAttachmentKeys.DEPLOYMENT_KEY);
        List<Endpoint> endpoints = deployment.getService().getEndpoints();
        //If we're running in a Service, that will already have proper dependencies set on the installed endpoint services,
        //otherwise we need to explicitly wait for the endpoint services to be started before creating the webapp.
        if (!runningInService) {
            final ServiceRegistry registry = unit.getServiceRegistry();
            final StabilityMonitor monitor = new StabilityMonitor();
            for (Endpoint ep : endpoints) {
                final ServiceName serviceName = EndpointService.getServiceName(unit, ep.getShortName());
                monitor.addController(registry.getRequiredService(serviceName));
            }
            try {
                monitor.awaitStability();
            } finally {
                monitor.clear();
            }
        }
        deployment.addAttachment(WebDeploymentController.class, startWebApp(host, unit)); //TODO simplify and use findChild later in destroy()/stopWebApp()
        return new Context(unit.getAttachment(WSAttachmentKeys.JBOSSWEB_METADATA_KEY).getContextRoot(), endpoints);
    }

Publish the webapp for the WS deployment unit

@param target
@param unit
@return
@throws Exception


protected void stopWebApp(Deployment deployment) throws Exception {
        WebDeploymentController context;
        try {
            context = deployment.getAttachment(WebDeploymentController.class);
            context.stop();
        } catch (Exception e) {
            throw WSLogger.ROOT_LOGGER.stopContextPhaseFailed(e);
        }
        try {
            context.destroy();
        } catch (Exception e) {
            throw WSLogger.ROOT_LOGGER.destroyContextPhaseFailed(e);
        }
    }

protected void stopWebApp ( Deployment deployment ) throws Exception { WebDeploymentController context ; try { context = deployment . getAttachment ( WebDeploymentController . class ) ; context . stop ( ) ; } catch ( Exception e ) { throw WSLogger . ROOT_LOGGER . stopContextPhaseFailed ( e ) ; } try { context . destroy ( ) ; } catch ( Exception e ) { throw WSLogger . ROOT_LOGGER . destroyContextPhaseFailed ( e ) ; } }

Stops the webapp serving the provided ws deployment

@param deployment
@throws Exception


public synchronized void start(final StartContext context) {
        if (started) {
            throw WeldLogger.ROOT_LOGGER.alreadyRunning("WeldContainer");
        }
        started = true;

        WeldLogger.DEPLOYMENT_LOGGER.startingWeldService(deploymentName);
        // set up injected services
        addWeldService(SecurityServices.class, securityServicesSupplier.get());

        TransactionServices transactionServices = weldTransactionServicesSupplier != null ? weldTransactionServicesSupplier.get() : null;
        if (transactionServices != null) {
            addWeldService(TransactionServices.class, transactionServices);
        }

        if (!deployment.getServices().contains(ExecutorServices.class)) {
            addWeldService(ExecutorServices.class, executorServicesSupplier.get());
        }

        ModuleGroupSingletonProvider.addClassLoaders(deployment.getModule().getClassLoader(),
                deployment.getSubDeploymentClassLoaders());

        ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        try {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(deployment.getModule().getClassLoader());
            bootstrap.startContainer(deploymentName, environment, deployment);
            WeldProvider.containerInitialized(Container.instance(deploymentName), getBeanManager(), deployment);
        } finally {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
        }
        weldBootstrapServiceConsumer.accept(this);
    }

public
synchronized
void
start
(
final
StartContext
context
)
{
if
(
started
)
{
throw
WeldLogger
.
ROOT_LOGGER
.
alreadyRunning
(
"WeldContainer"
)
;
}
started
=
true
;
WeldLogger
.
DEPLOYMENT_LOGGER
.
startingWeldService
(
deploymentName
)
;
// set up injected services
addWeldService
(
SecurityServices
.
class
,
securityServicesSupplier
.
get
(
)
)
;
TransactionServices
transactionServices
=
weldTransactionServicesSupplier
!=
weldTransactionServicesSupplier
.
get
(
)
:
;
if
(
transactionServices
!=
)
{
addWeldService
(
TransactionServices
.
class
,
transactionServices
)
;
}
if
(
!
deployment
.
getServices
(
)
.
contains
(
ExecutorServices
.
class
)
)
{
addWeldService
(
ExecutorServices
.
class
,
executorServicesSupplier
.
get
(
)
)
;
}
ModuleGroupSingletonProvider
.
addClassLoaders
(
deployment
.
getModule
(
)
.
getClassLoader
(
)
,
deployment
.
getSubDeploymentClassLoaders
(
)
)
;
ClassLoader
oldTccl
=
WildFlySecurityManager
.
getCurrentContextClassLoaderPrivileged
(
)
;
try
{
WildFlySecurityManager
.
setCurrentContextClassLoaderPrivileged
(
deployment
.
getModule
(
)
.
getClassLoader
(
)
)
;
bootstrap
.
startContainer
(
deploymentName
,
environment
,
deployment
)
;
WeldProvider
.
containerInitialized
(
Container
.
instance
(
deploymentName
)
,
getBeanManager
(
)
,
deployment
)
;
}
finally
{
WildFlySecurityManager
.
setCurrentContextClassLoaderPrivileged
(
oldTccl
)
;
}
weldBootstrapServiceConsumer
.
accept
(
this
)
;
}

Starts the weld container

@throws IllegalStateException if the container is already running


public void registerEndpointConfig(final String endpointClass, final EndpointConfig config) {
        if ((endpointClass == null) || (config == null)) {
            throw new IllegalArgumentException();
        }
        endpointConfigMap.put(endpointClass, config);
    }

public void registerEndpointConfig ( final String endpointClass , final EndpointConfig config ) { if ( ( endpointClass == null ) || ( config == null ) ) { throw new IllegalArgumentException ( ) ; } endpointConfigMap . put ( endpointClass , config ) ; }

Registers endpoint and its config.

@param endpointClass WS endpoint
@param config Config with endpoint


protected void retryTimeout(TimerImpl timer) throws Exception {
        boolean callTimeout = false;

        timer.lock();
        try {
            if (timer.isActive()) {
                EJB3_TIMER_LOGGER.retryingTimeout(timer);
                timer.setTimerState(TimerState.RETRY_TIMEOUT, Thread.currentThread());
                timerService.persistTimer(timer, false);
                callTimeout = true;
            } else {
                EJB3_TIMER_LOGGER.timerNotActive(timer);
            }
        } finally {
            timer.unlock();
        }
        if(callTimeout) {
            this.callTimeout(timer);
        }
    }

protected void retryTimeout ( TimerImpl timer ) throws Exception { boolean callTimeout = false ; timer . lock ( ) ; try { if ( timer . isActive ( ) ) { EJB3_TIMER_LOGGER . retryingTimeout ( timer ) ; timer . setTimerState ( TimerState . RETRY_TIMEOUT , Thread . currentThread ( ) ) ; timerService . persistTimer ( timer , false ) ; callTimeout = true ; } else { EJB3_TIMER_LOGGER . timerNotActive ( timer ) ; } } finally { timer . unlock ( ) ; } if ( callTimeout ) { this . callTimeout ( timer ) ; } }

After a timeout failed the timer need to retried.
The method must lock the timer for state check and update but not during callTimeout run.

@param timer timer to retry and state updates
@throws Exception

After a timeout failed the timer need to retried . The method must lock the timer for state check and update but not during callTimeout run .


protected void postTimeoutProcessing(TimerImpl timer) throws InterruptedException {
        timer.lock();
        try {
            TimerState timerState = timer.getState();
            if (timerState != TimerState.CANCELED
                    && timerState != TimerState.EXPIRED) {
                if (timer.getInterval() == 0) {
                    timerService.expireTimer(timer);
                } else {
                    timer.setTimerState(TimerState.ACTIVE, null);
                }
                timerService.persistTimer(timer, false);
            }
        } finally {
            timer.unlock();
        }
    }

protected void postTimeoutProcessing ( TimerImpl timer ) throws InterruptedException { timer . lock ( ) ; try { TimerState timerState = timer . getState ( ) ; if ( timerState != TimerState . CANCELED && timerState != TimerState . EXPIRED ) { if ( timer . getInterval ( ) == 0 ) { timerService . expireTimer ( timer ) ; } else { timer . setTimerState ( TimerState . ACTIVE , null ) ; } timerService . persistTimer ( timer , false ) ; } } finally { timer . unlock ( ) ; } }

After running the timer calculate the new state or expire the timer and persist it if changed.
The method must lock the timer for state check and updates if overridden.

@param timer timer to post processing and persist

After running the timer calculate the new state or expire the timer and persist it if changed . The method must lock the timer for state check and updates if overridden .


static Method[] getDeclaredMethods(final Class<?> c) {
        if (System.getSecurityManager() == null)
            return c.getDeclaredMethods();

        return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
            public Method[] run() {
                return c.getDeclaredMethods();
            }
        });
    }

static Method [ ] getDeclaredMethods ( final Class < ? > c ) { if ( System . getSecurityManager ( ) == null ) return c . getDeclaredMethods ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < Method [ ] > ( ) { public Method [ ] run ( ) { return c . getDeclaredMethods ( ) ; } } ) ; }

Get the declared methods

@param c The class
@return The methods


static Field[] getDeclaredFields(final Class<?> c) {
        if (System.getSecurityManager() == null)
            return c.getDeclaredFields();

        return AccessController.doPrivileged(new PrivilegedAction<Field[]>() {
            public Field[] run() {
                return c.getDeclaredFields();
            }
        });
    }

static Field [ ] getDeclaredFields ( final Class < ? > c ) { if ( System . getSecurityManager ( ) == null ) return c . getDeclaredFields ( ) ; return AccessController . doPrivileged ( new PrivilegedAction < Field [ ] > ( ) { public Field [ ] run ( ) { return c . getDeclaredFields ( ) ; } } ) ; }

Get the declared fields

@param c The class
@return The fields


static Constructor<?> getConstructor(final Class<?> c, final Class<?>... params)
            throws NoSuchMethodException {
        if (System.getSecurityManager() == null)
            return c.getConstructor(params);

        Constructor<?> result = AccessController.doPrivileged(new PrivilegedAction<Constructor<?>>() {
            public Constructor<?> run() {
                try {
                    return c.getConstructor(params);
                } catch (NoSuchMethodException e) {
                    return null;
                }
            }
        });

        if (result != null)
            return result;

        throw new NoSuchMethodException();
    }

static Constructor < ? > getConstructor ( final Class < ? > c , final Class < ? > ... params ) throws NoSuchMethodException { if ( System . getSecurityManager ( ) == null ) return c . getConstructor ( params ) ; Constructor < ? > result = AccessController . doPrivileged ( new PrivilegedAction < Constructor < ? > > ( ) { public Constructor < ? > run ( ) { try { return c . getConstructor ( params ) ; } catch ( NoSuchMethodException e ) { return null ; } } } ) ; if ( result != null ) return result ; throw new NoSuchMethodException ( ) ; }

Get the constructor

@param c      The class
@param params The parameters
@return The constructor
@throws NoSuchMethodException If a matching method is not found.


static Method getMethod(final Class<?> c, final String name, final Class<?>... params)
            throws NoSuchMethodException {
        if (System.getSecurityManager() == null)
            return c.getMethod(name, params);

        Method result = AccessController.doPrivileged(new PrivilegedAction<Method>() {
            public Method run() {
                try {
                    return c.getMethod(name, params);
                } catch (NoSuchMethodException e) {
                    return null;
                }
            }
        });

        if (result != null)
            return result;

        throw new NoSuchMethodException();
    }

static Method getMethod ( final Class < ? > c , final String name , final Class < ? > ... params ) throws NoSuchMethodException { if ( System . getSecurityManager ( ) == null ) return c . getMethod ( name , params ) ; Method result = AccessController . doPrivileged ( new PrivilegedAction < Method > ( ) { public Method run ( ) { try { return c . getMethod ( name , params ) ; } catch ( NoSuchMethodException e ) { return null ; } } } ) ; if ( result != null ) return result ; throw new NoSuchMethodException ( ) ; }

Get the method

@param c      The class
@param name   The name
@param params The parameters
@return The method
@throws NoSuchMethodException If a matching method is not found.


private void addMessagingActiveMQExtension(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, boolean describe) {
        Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false);
        if (root.getChildrenNames(EXTENSION).contains(MESSAGING_ACTIVEMQ_EXTENSION)) {
            // extension is already added, do nothing
            return;
        }
        PathAddress extensionAddress = pathAddress(EXTENSION, MESSAGING_ACTIVEMQ_EXTENSION);
        OperationEntry addEntry = context.getRootResourceRegistration().getOperationEntry(extensionAddress, ADD);
        ModelNode addOperation = createAddOperation(extensionAddress);
        addOperation.get(MODULE).set(MESSAGING_ACTIVEMQ_MODULE);
        if (describe) {
            migrationOperations.put(extensionAddress, addOperation);
        } else {
            context.addStep(context.getResult().get(extensionAddress.toString()), addOperation, addEntry.getOperationHandler(), MODEL);
        }
    }

It's possible that the extension is already present. In that case, this method does nothing.

It s possible that the extension is already present . In that case this method does nothing .


private boolean parameterIsAllowed(String name, String resourceType) {
        switch (resourceType) {
            case REMOTE_ACCEPTOR:
            case HTTP_ACCEPTOR:
            case REMOTE_CONNECTOR:
            case HTTP_CONNECTOR:
                // WFLY-5667 - for now remove only use-nio. Revisit this code when Artemis offers an API
                // to know which parameters are ignored.
                if ("use-nio".equals(name)) {
                    return false;
                } else {
                    return true;
                }
            default:
                // accept any parameter for other resources.
                return true;
        }
    }

Check if the name of the parameter is allowed for the given resourceType.

Check if the name of the parameter is allowed for the given resourceType .


private void migrateGenericTransport(ModelNode addOperation) {
        String factoryClass = addOperation.get(FACTORY_CLASS.getName()).asString();
        final String newFactoryClass;
        switch (factoryClass) {
            case HORNETQ_NETTY_ACCEPTOR_FACTORY:
                newFactoryClass = ARTEMIS_NETTY_ACCEPTOR_FACTORY;
                break;
            case HORNETQ_NETTY_CONNECTOR_FACTORY:
                newFactoryClass = ARTEMIS_NETTY_CONNECTOR_FACTORY;
                break;
            default:
                newFactoryClass = factoryClass;
        }
        addOperation.get(FACTORY_CLASS.getName()).set(newFactoryClass);
    }

private void migrateGenericTransport ( ModelNode addOperation ) { String factoryClass = addOperation . get ( FACTORY_CLASS . getName ( ) ) . asString ( ) ; final String newFactoryClass ; switch ( factoryClass ) { case HORNETQ_NETTY_ACCEPTOR_FACTORY : newFactoryClass = ARTEMIS_NETTY_ACCEPTOR_FACTORY ; break ; case HORNETQ_NETTY_CONNECTOR_FACTORY : newFactoryClass = ARTEMIS_NETTY_CONNECTOR_FACTORY ; break ; default : newFactoryClass = factoryClass ; } addOperation . get ( FACTORY_CLASS . getName ( ) ) . set ( newFactoryClass ) ; }

For generic acceptor and connectors, migrate their factory-class attribute
if they are using the default Netty ones.

For generic acceptor and connectors migrate their factory - class attribute if they are using the default Netty ones .


public boolean cancel(boolean setFlag) {
        final AtomicInteger stateRef = this.stateRef;
        int oldVal, newVal;
        do {
            oldVal = stateRef.get();
            if (oldVal == ST_WAITING) {
                newVal = ST_CANCELLED;
            } else if (oldVal == ST_CANCELLED) {
                if (! setFlag) {
                    return true;
                }
                newVal = ST_CANCELLED_FLAG_SET;
            } else if (oldVal == ST_CANCELLED_FLAG_SET) {
                // do nothing
                return true;
            } else if (oldVal == ST_STARTED) {
                if (! setFlag) {
                    return false;
                }
                newVal = ST_STARTED_FLAG_SET;
            } else {
                assert oldVal == ST_STARTED_FLAG_SET;
                return false;
            }
        } while (! stateRef.compareAndSet(oldVal, newVal));
        return newVal == ST_CANCELLED || newVal == ST_CANCELLED_FLAG_SET;
    }

public
boolean
cancel
(
boolean
setFlag
)
{
final
AtomicInteger
stateRef
=
this
.
stateRef
;
int
oldVal
,
newVal
;
do
{
oldVal
=
stateRef
.
get
(
)
;
if
(
oldVal
==
ST_WAITING
)
{
newVal
=
ST_CANCELLED
;
}
else
if
(
oldVal
==
ST_CANCELLED
)
{
if
(
!
setFlag
)
{
return
true
;
}
newVal
=
ST_CANCELLED_FLAG_SET
;
}
else
if
(
oldVal
==
ST_CANCELLED_FLAG_SET
)
{
// do nothing
return
true
;
}
else
if
(
oldVal
==
ST_STARTED
)
{
if
(
!
setFlag
)
{
return
false
;
}
newVal
=
ST_STARTED_FLAG_SET
;
}
else
{
assert
oldVal
==
ST_STARTED_FLAG_SET
;
return
false
;
}
}
while
(
!
stateRef
.
compareAndSet
(
oldVal
,
newVal
)
)
;
return
newVal
==
ST_CANCELLED
||
newVal
==
ST_CANCELLED_FLAG_SET
;
}

Attempt to cancel the corresponding invocation.

@param setFlag {@code true} to set the EJB context cancellation flag (or equivalent), {@code false} otherwise
@return {@code true} if the invocation was definitely cancelled, or {@code false} if it was not cancelled or it could not be determined if it was cancelled

Attempt to cancel the corresponding invocation .


public boolean runIfNotCancelled() {
        final AtomicInteger stateRef = this.stateRef;
        int oldVal;
        do {
            oldVal = stateRef.get();
            if (oldVal == ST_CANCELLED || oldVal == ST_CANCELLED_FLAG_SET) {
                return false;
            } else if (oldVal != ST_WAITING) {
                throw Assert.unreachableCode();
            }
        } while (! stateRef.compareAndSet(oldVal, ST_STARTED));
        return true;
    }

public boolean runIfNotCancelled ( ) { final AtomicInteger stateRef = this . stateRef ; int oldVal ; do { oldVal = stateRef . get ( ) ; if ( oldVal == ST_CANCELLED || oldVal == ST_CANCELLED_FLAG_SET ) { return false ; } else if ( oldVal != ST_WAITING ) { throw Assert . unreachableCode ( ) ; } } while ( ! stateRef . compareAndSet ( oldVal , ST_STARTED ) ) ; return true ; }

Attempt to determine whether the invocation should proceed or whether it should be cancelled.  This method should only
be called once per flag instance.

@return {@code true} if the invocation should proceed, or {@code false} if it was cancelled

Attempt to determine whether the invocation should proceed or whether it should be cancelled . This method should only be called once per flag instance .