public static void beginSfsbCreation() {
        SFSBCallStackThreadData data = CURRENT.get();
        int no = data.creationBeanNestingLevel;
        if (no == 0) {
            data.creationTimeXPCRegistration = new HashMap<String, ExtendedEntityManager>();
            // create new tracking structure (passing in parent levels tracking structure or null if toplevel)
            data.creationTimeInjectedXPCs = new SFSBInjectedXPCs(data.creationTimeInjectedXPCs, null);
        }
        else {
            // create new tracking structure (passing in parent levels tracking structure or null if toplevel)
            SFSBInjectedXPCs parent = data.creationTimeInjectedXPCs;
            data.creationTimeInjectedXPCs = new SFSBInjectedXPCs(parent, parent.getTopLevel());
        }
        data.creationBeanNestingLevel++;
    }

called from SFSBPreCreateInterceptor, before bean creation

called from SFSBPreCreateInterceptor before bean creation


public static void endSfsbCreation() {
        SFSBCallStackThreadData data = CURRENT.get();
        int no =  data.creationBeanNestingLevel;
        no--;
        data.creationBeanNestingLevel = no;

        if (no == 0) {
            // Completed creating top level bean, remove 'xpc creation tracking' thread local
            data.creationTimeXPCRegistration = null;
            data.creationTimeInjectedXPCs = null;
        }
        else {
            // finished creating a sub-bean, switch to parent level 'xpc creation tracking'
            data.creationTimeInjectedXPCs = data.creationTimeInjectedXPCs.getParent();
        }
    }

called from SFSBPreCreateInterceptor, after bean creation

called from SFSBPreCreateInterceptor after bean creation


public static Map<String, ExtendedEntityManager> currentSFSBCallStackInvocation() {
        ArrayList<Map<String, ExtendedEntityManager>> stack = CURRENT.get().invocationStack;
        if ( stack != null && stack.size() > 0) {
            return stack.get(stack.size() - 1);
        }
        return null;
    }

public static Map < String , ExtendedEntityManager > currentSFSBCallStackInvocation ( ) { ArrayList < Map < String , ExtendedEntityManager > > stack = CURRENT . get ( ) . invocationStack ; if ( stack != null && stack . size ( ) > 0 ) { return stack . get ( stack . size ( ) - 1 ) ; } return null ; }

return for just the current entity manager invocation

@return


public static void pushCall(Map<String, ExtendedEntityManager> entityManagers) {
        currentSFSBCallStack().add(entityManagers);

        if (entityManagers != null) {
            /**
             * JPA 2.0 spec section 7.9.1 Container Responsibilities:
             * "When a business method of the stateful session bean is invoked,
             *  if the stateful session bean uses container managed transaction demarcation,
             *  and the entity manager is not already associated with the current JTA transaction,
             *  the container associates the entity manager with the current JTA transaction and
             *  calls EntityManager.joinTransaction.
             *  "
             */
            for(ExtendedEntityManager extendedEntityManager: entityManagers.values()) {
                extendedEntityManager.internalAssociateWithJtaTx();
            }
        }

    }

Push the passed SFSB context handle onto the invocation call stack

@param entityManagers the entity manager map


public static Map<String, ExtendedEntityManager> popCall() {
        ArrayList<Map<String, ExtendedEntityManager>> stack = currentSFSBCallStack();
        Map<String, ExtendedEntityManager> result = stack.remove(stack.size() - 1);
        stack.trimToSize();
        return result;
    }

public static Map < String , ExtendedEntityManager > popCall ( ) { ArrayList < Map < String , ExtendedEntityManager > > stack = currentSFSBCallStack ( ) ; Map < String , ExtendedEntityManager > result = stack . remove ( stack . size ( ) - 1 ) ; stack . trimToSize ( ) ; return result ; }

Pops the current SFSB invocation off the invocation call stack

@return the entity manager map


static Map<String, ExtendedEntityManager> getCurrentCall() {
        ArrayList<Map<String, ExtendedEntityManager>> stack = currentSFSBCallStack();
        Map<String, ExtendedEntityManager> result = null;
        if (stack != null) {
            result = stack.get(stack.size() - 1);
        }
        return result;
    }

static Map < String , ExtendedEntityManager > getCurrentCall ( ) { ArrayList < Map < String , ExtendedEntityManager > > stack = currentSFSBCallStack ( ) ; Map < String , ExtendedEntityManager > result = null ; if ( stack != null ) { result = stack . get ( stack . size ( ) - 1 ) ; } return result ; }

gets the current SFSB invocation off the invocation call stack

@return the entity manager map


public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);

        final ModuleLoader moduleLoader = Module.getBootModuleLoader();
        addDependency(moduleSpecification, moduleLoader, JAVAX_ENTERPRISE_API);
        addDependency(moduleSpecification, moduleLoader, JAVAX_INJECT_API);

        if (!WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) {
            return; // Skip if there are no beans.xml files in the deployment
        }
        addDependency(moduleSpecification, moduleLoader, JAVAX_PERSISTENCE_API_ID);
        addDependency(moduleSpecification, moduleLoader, WELD_CORE_ID);
        addDependency(moduleSpecification, moduleLoader, WELD_PROBE_ID, true);
        addDependency(moduleSpecification, moduleLoader, WELD_API_ID);
        addDependency(moduleSpecification, moduleLoader, WELD_SPI_ID);

        ModuleDependency weldSubsystemDependency = new ModuleDependency(moduleLoader, JBOSS_AS_WELD_ID, false, false, false, false);
        weldSubsystemDependency.addImportFilter(PathFilters.getMetaInfFilter(), true);
        weldSubsystemDependency.addImportFilter(PathFilters.is("org/jboss/as/weld/injection"), true);
        weldSubsystemDependency.addImportFilter(PathFilters.acceptAll(), false);
        weldSubsystemDependency.addExportFilter(PathFilters.getMetaInfFilter(), true);
        moduleSpecification.addSystemDependency(weldSubsystemDependency);

        // Due to serialization of EJBs
        ModuleDependency weldEjbDependency = new ModuleDependency(moduleLoader, JBOSS_AS_WELD_EJB_ID, true, false, false, false);
        weldEjbDependency.addImportFilter(PathFilters.is("org/jboss/as/weld/ejb"), true);
        weldEjbDependency.addImportFilter(PathFilters.acceptAll(), false);
        moduleSpecification.addSystemDependency(weldEjbDependency);
    }

Add dependencies for modules required for weld deployments, if managed weld configurations are attached to the deployment

Add dependencies for modules required for weld deployments if managed weld configurations are attached to the deployment


private void processXmlManagedBeans(final DeploymentUnit deploymentUnit, final Set<String> managedBeanClasses) {
        for (final VirtualFile facesConfig : getConfigurationFiles(deploymentUnit)) {
            InputStream is = null;
            try {
                is = facesConfig.openStream();
                final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
                inputFactory.setXMLResolver(NoopXMLResolver.create());
                XMLStreamReader parser = inputFactory.createXMLStreamReader(is);
                StringBuilder className = null;
                int indent = 0;
                boolean managedBean = false;
                boolean managedBeanClass = false;
                while (true) {
                    int event = parser.next();
                    if (event == XMLStreamConstants.END_DOCUMENT) {
                        parser.close();
                        break;
                    }
                    if (event == XMLStreamConstants.START_ELEMENT) {
                        indent++;
                        if (indent == 2) {
                            if (parser.getLocalName().equals(MANAGED_BEAN)) {
                                managedBean = true;
                            }
                        } else if (indent == 3 && managedBean) {
                            if (parser.getLocalName().equals(MANAGED_BEAN_CLASS)) {
                                managedBeanClass = true;
                                className = new StringBuilder();
                            }
                        }

                    } else if (event == XMLStreamConstants.END_ELEMENT) {
                        indent--;
                        managedBeanClass = false;
                        if (indent == 1) {
                            managedBean = false;
                        }
                        if (className != null) {
                            managedBeanClasses.add(className.toString().trim());
                            className = null;
                        }
                    } else if (managedBeanClass && event == XMLStreamConstants.CHARACTERS) {
                        className.append(parser.getText());
                    }
                }
            } catch (Exception e) {
                JSFLogger.ROOT_LOGGER.managedBeansConfigParseFailed(facesConfig);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    }

private
void
processXmlManagedBeans
(
final
DeploymentUnit
deploymentUnit
,
final
Set
<
String
>
managedBeanClasses
)
{
for
(
final
VirtualFile
facesConfig
:
getConfigurationFiles
(
deploymentUnit
)
)
{
InputStream
is
=
;
try
{
is
=
facesConfig
.
openStream
(
)
;
final
XMLInputFactory
inputFactory
=
XMLInputFactory
.
newInstance
(
)
;
inputFactory
.
setXMLResolver
(
NoopXMLResolver
.
create
(
)
)
;
XMLStreamReader
parser
=
inputFactory
.
createXMLStreamReader
(
is
)
;
StringBuilder
className
=
;
int
indent
=
0
;
boolean
managedBean
=
false
;
boolean
managedBeanClass
=
false
;
while
(
true
)
{
int
event
=
parser
.
next
(
)
;
if
(
event
==
XMLStreamConstants
.
END_DOCUMENT
)
{
parser
.
close
(
)
;
break
;
}
if
(
event
==
XMLStreamConstants
.
START_ELEMENT
)
{
indent
++
;
if
(
indent
==
2
)
{
if
(
parser
.
getLocalName
(
)
.
equals
(
MANAGED_BEAN
)
)
{
managedBean
=
true
;
}
}
else
if
(
indent
==
3
&&
managedBean
)
{
if
(
parser
.
getLocalName
(
)
.
equals
(
MANAGED_BEAN_CLASS
)
)
{
managedBeanClass
=
true
;
className
=
new
StringBuilder
(
)
;
}
}
}
else
if
(
event
==
XMLStreamConstants
.
END_ELEMENT
)
{
indent
;
managedBeanClass
=
false
;
if
(
indent
==
1
)
{
managedBean
=
false
;
}
if
(
className
!=
)
{
managedBeanClasses
.
add
(
className
.
toString
(
)
.
trim
(
)
)
;
className
=
;
}
}
else
if
(
managedBeanClass
&&
event
==
XMLStreamConstants
.
CHARACTERS
)
{
className
.
append
(
parser
.
getText
(
)
)
;
}
}
}
catch
(
Exception
e
)
{
JSFLogger
.
ROOT_LOGGER
.
managedBeansConfigParseFailed
(
facesConfig
)
;
}
finally
{
try
{
if
(
is
!=
)
{
is
.
close
(
)
;
}
}
catch
(
IOException
e
)
{
// Ignore
}
}
}
}

Parse the faces config files looking for managed bean classes. The parser is quite
simplistic as the only information we need is the managed-bean-class element

Parse the faces config files looking for managed bean classes . The parser is quite simplistic as the only information we need is the managed - bean - class element


private void processPhaseListeners(final DeploymentUnit deploymentUnit, final Set<String> managedBeanClasses) {
        for (final VirtualFile facesConfig : getConfigurationFiles(deploymentUnit)) {
            InputStream is = null;
            try {
                is = facesConfig.openStream();
                final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
                inputFactory.setXMLResolver(NoopXMLResolver.create());
                XMLStreamReader parser = inputFactory.createXMLStreamReader(is);
                StringBuilder phaseListenerName = null;
                int indent = 0;
                boolean lifecycle = false;
                boolean phaseListener = false;
                while (true) {
                    int event = parser.next();
                    if (event == XMLStreamConstants.END_DOCUMENT) {
                        parser.close();
                        break;
                    }
                    if (event == XMLStreamConstants.START_ELEMENT) {
                        indent++;
                        if (indent == 2) {
                            if(parser.getLocalName().equals(LIFECYCLE)){
                                lifecycle = true;
                            }
                        } else if (indent == 3 && lifecycle) {
                            if(parser.getLocalName().equals(PHASE_LISTENER)){
                                phaseListener = true;
                                phaseListenerName = new StringBuilder();
                            }
                        }
                    } else if (event == XMLStreamConstants.END_ELEMENT) {
                        indent--;
                        phaseListener = false;
                        if (indent == 1) {
                            lifecycle = false;
                        }
                        if(phaseListenerName != null){
                            managedBeanClasses.add(phaseListenerName.toString().trim());
                            phaseListenerName = null;
                        }
                    } else if (phaseListener && event == XMLStreamConstants.CHARACTERS) {
                        phaseListenerName.append(parser.getText());
                    }
                }
            } catch (Exception e) {
                JSFLogger.ROOT_LOGGER.phaseListenersConfigParseFailed(facesConfig);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    }

private
void
processPhaseListeners
(
final
DeploymentUnit
deploymentUnit
,
final
Set
<
String
>
managedBeanClasses
)
{
for
(
final
VirtualFile
facesConfig
:
getConfigurationFiles
(
deploymentUnit
)
)
{
InputStream
is
=
;
try
{
is
=
facesConfig
.
openStream
(
)
;
final
XMLInputFactory
inputFactory
=
XMLInputFactory
.
newInstance
(
)
;
inputFactory
.
setXMLResolver
(
NoopXMLResolver
.
create
(
)
)
;
XMLStreamReader
parser
=
inputFactory
.
createXMLStreamReader
(
is
)
;
StringBuilder
phaseListenerName
=
;
int
indent
=
0
;
boolean
lifecycle
=
false
;
boolean
phaseListener
=
false
;
while
(
true
)
{
int
event
=
parser
.
next
(
)
;
if
(
event
==
XMLStreamConstants
.
END_DOCUMENT
)
{
parser
.
close
(
)
;
break
;
}
if
(
event
==
XMLStreamConstants
.
START_ELEMENT
)
{
indent
++
;
if
(
indent
==
2
)
{
if
(
parser
.
getLocalName
(
)
.
equals
(
LIFECYCLE
)
)
{
lifecycle
=
true
;
}
}
else
if
(
indent
==
3
&&
lifecycle
)
{
if
(
parser
.
getLocalName
(
)
.
equals
(
PHASE_LISTENER
)
)
{
phaseListener
=
true
;
phaseListenerName
=
new
StringBuilder
(
)
;
}
}
}
else
if
(
event
==
XMLStreamConstants
.
END_ELEMENT
)
{
indent
;
phaseListener
=
false
;
if
(
indent
==
1
)
{
lifecycle
=
false
;
}
if
(
phaseListenerName
!=
)
{
managedBeanClasses
.
add
(
phaseListenerName
.
toString
(
)
.
trim
(
)
)
;
phaseListenerName
=
;
}
}
else
if
(
phaseListener
&&
event
==
XMLStreamConstants
.
CHARACTERS
)
{
phaseListenerName
.
append
(
parser
.
getText
(
)
)
;
}
}
}
catch
(
Exception
e
)
{
JSFLogger
.
ROOT_LOGGER
.
phaseListenersConfigParseFailed
(
facesConfig
)
;
}
finally
{
try
{
if
(
is
!=
)
{
is
.
close
(
)
;
}
}
catch
(
IOException
e
)
{
// Ignore
}
}
}
}

WFLY-6617
According to  JSF 2.2 spec, it should be possible to inject beans using @EJB annotation into
PhaseListeners.

WFLY - 6617 According to JSF 2 . 2 spec it should be possible to inject beans using


public static String getTypeIDLName(Class cls)
            throws RMIIIOPViolationException {

        if (cls.isPrimitive())
            return PrimitiveAnalysis.getPrimitiveAnalysis(cls).getIDLName();

        if (cls.isArray()) {
            // boxedRMI 1.3.6
            Class componentClass = cls;
            int sequence = 0;
            while (componentClass.isArray()) {
                componentClass = componentClass.getComponentType();
                ++sequence;
            }

            String idlName = getTypeIDLName(componentClass);
            int idx = idlName.lastIndexOf("::");
            String idlModule = idlName.substring(0, idx + 2);
            String baseName = idlName.substring(idx + 2);
            return "::org::omg::boxedRMI" + idlModule + "seq" + sequence + "_" + baseName;
        }

        // special classes
        if (cls == java.lang.String.class)
            return "::CORBA::WStringValue";
        if (cls == java.lang.Object.class)
            return "::java::lang::_Object";
        if (cls == java.lang.Class.class)
            return "::javax::rmi::CORBA::ClassDesc";
        if (cls == java.io.Serializable.class)
            return "::java::io::Serializable";
        if (cls == java.io.Externalizable.class)
            return "::java::io::Externalizable";
        if (cls == java.rmi.Remote.class)
            return "::java::rmi::Remote";
        if (cls == org.omg.CORBA.Object.class)
            return "::CORBA::Object";

        // remote interface?
        if (cls.isInterface() && java.rmi.Remote.class.isAssignableFrom(cls)) {
            InterfaceAnalysis ia = InterfaceAnalysis.getInterfaceAnalysis(cls);

            return ia.getIDLModuleName() + "::" + ia.getIDLName();
        }

        // IDL interface?
        if (cls.isInterface() &&
                org.omg.CORBA.Object.class.isAssignableFrom(cls) &&
                org.omg.CORBA.portable.IDLEntity.class.isAssignableFrom(cls)) {
            InterfaceAnalysis ia = InterfaceAnalysis.getInterfaceAnalysis(cls);

            return ia.getIDLModuleName() + "::" + ia.getIDLName();
        }

        // exception?
        if (Throwable.class.isAssignableFrom(cls)) {
            if (Exception.class.isAssignableFrom(cls) &&
                    !RuntimeException.class.isAssignableFrom(cls)) {
                ExceptionAnalysis ea = ExceptionAnalysis.getExceptionAnalysis(cls);

                return ea.getIDLModuleName() + "::" + ea.getIDLName();
            }
        }

        // got to be value
        ValueAnalysis va = ValueAnalysis.getValueAnalysis(cls);

        return va.getIDLModuleName() + "::" + va.getIDLName();
    }

public
static
String
getTypeIDLName
(
Class
cls
)
throws
RMIIIOPViolationException
{
if
(
cls
.
isPrimitive
(
)
)
return
PrimitiveAnalysis
.
getPrimitiveAnalysis
(
cls
)
.
getIDLName
(
)
;
if
(
cls
.
isArray
(
)
)
{
// boxedRMI 1.3.6
Class
componentClass
=
cls
;
int
sequence
=
0
;
while
(
componentClass
.
isArray
(
)
)
{
componentClass
=
componentClass
.
getComponentType
(
)
;
++
sequence
;
}
String
idlName
=
getTypeIDLName
(
componentClass
)
;
int
idx
=
idlName
.
lastIndexOf
(
"::"
)
;
String
idlModule
=
idlName
.
substring
(
0
,
idx
+
2
)
;
String
baseName
=
idlName
.
substring
(
idx
+
2
)
;
return
"::org::omg::boxedRMI"
+
idlModule
+
"seq"
+
sequence
+
"_"
+
baseName
;
}
// special classes
if
(
cls
==
java
.
lang
.
String
.
class
)
return
"::CORBA::WStringValue"
;
if
(
cls
==
java
.
lang
.
Object
.
class
)
return
"::java::lang::_Object"
;
if
(
cls
==
java
.
lang
.
Class
.
class
)
return
"::javax::rmi::CORBA::ClassDesc"
;
if
(
cls
==
java
.
io
.
Serializable
.
class
)
return
"::java::io::Serializable"
;
if
(
cls
==
java
.
io
.
Externalizable
.
class
)
return
"::java::io::Externalizable"
;
if
(
cls
==
java
.
rmi
.
Remote
.
class
)
return
"::java::rmi::Remote"
;
if
(
cls
==
org
.
omg
.
CORBA
.
Object
.
class
)
return
"::CORBA::Object"
;
// remote interface?
if
(
cls
.
isInterface
(
)
&&
java
.
rmi
.
Remote
.
class
.
isAssignableFrom
(
cls
)
)
{
InterfaceAnalysis
ia
=
InterfaceAnalysis
.
getInterfaceAnalysis
(
cls
)
;
return
ia
.
getIDLModuleName
(
)
+
"::"
+
ia
.
getIDLName
(
)
;
}
// IDL interface?
if
(
cls
.
isInterface
(
)
&&
org
.
omg
.
CORBA
.
Object
.
class
.
isAssignableFrom
(
cls
)
&&
org
.
omg
.
CORBA
.
portable
.
IDLEntity
.
class
.
isAssignableFrom
(
cls
)
)
{
InterfaceAnalysis
ia
=
InterfaceAnalysis
.
getInterfaceAnalysis
(
cls
)
;
return
ia
.
getIDLModuleName
(
)
+
"::"
+
ia
.
getIDLName
(
)
;
}
// exception?
if
(
Throwable
.
class
.
isAssignableFrom
(
cls
)
)
{
if
(
Exception
.
class
.
isAssignableFrom
(
cls
)
&&
!
RuntimeException
.
class
.
isAssignableFrom
(
cls
)
)
{
ExceptionAnalysis
ea
=
ExceptionAnalysis
.
getExceptionAnalysis
(
cls
)
;
return
ea
.
getIDLModuleName
(
)
+
"::"
+
ea
.
getIDLName
(
)
;
}
}
// got to be value
ValueAnalysis
va
=
ValueAnalysis
.
getValueAnalysis
(
cls
)
;
return
va
.
getIDLModuleName
(
)
+
"::"
+
va
.
getIDLName
(
)
;
}

Return the IDL type name for the given class.
Here we use the mapping for parameter types and return values.

Return the IDL type name for the given class . Here we use the mapping for parameter types and return values .


public static void insertAnyPrimitive(Any any, Object primitive) {
        Class type = primitive.getClass();

        if (type == Boolean.class)
            any.insert_boolean(((Boolean) primitive).booleanValue());
        else if (type == Character.class)
            any.insert_wchar(((Character) primitive).charValue());
        else if (type == Byte.class)
            any.insert_octet(((Byte) primitive).byteValue());
        else if (type == Short.class)
            any.insert_short(((Short) primitive).shortValue());
        else if (type == Integer.class)
            any.insert_long(((Integer) primitive).intValue());
        else if (type == Long.class)
            any.insert_longlong(((Long) primitive).longValue());
        else if (type == Float.class)
            any.insert_float(((Float) primitive).floatValue());
        else if (type == Double.class)
            any.insert_double(((Double) primitive).doubleValue());
        else
            throw IIOPLogger.ROOT_LOGGER.notAPrimitive(type.getName());
    }

public static void insertAnyPrimitive ( Any any , Object primitive ) { Class type = primitive . getClass ( ) ; if ( type == Boolean . class ) any . insert_boolean ( ( ( Boolean ) primitive ) . booleanValue ( ) ) ; else if ( type == Character . class ) any . insert_wchar ( ( ( Character ) primitive ) . charValue ( ) ) ; else if ( type == Byte . class ) any . insert_octet ( ( ( Byte ) primitive ) . byteValue ( ) ) ; else if ( type == Short . class ) any . insert_short ( ( ( Short ) primitive ) . shortValue ( ) ) ; else if ( type == Integer . class ) any . insert_long ( ( ( Integer ) primitive ) . intValue ( ) ) ; else if ( type == Long . class ) any . insert_longlong ( ( ( Long ) primitive ) . longValue ( ) ) ; else if ( type == Float . class ) any . insert_float ( ( ( Float ) primitive ) . floatValue ( ) ) ; else if ( type == Double . class ) any . insert_double ( ( ( Double ) primitive ) . doubleValue ( ) ) ; else throw IIOPLogger . ROOT_LOGGER . notAPrimitive ( type . getName ( ) ) ; }

Insert a java primitive into an Any.
The primitive is assumed to be wrapped in one of the primitive
wrapper classes.

Insert a java primitive into an Any . The primitive is assumed to be wrapped in one of the primitive wrapper classes .


public static String javaToIDLName(String name) {
        if (name == null || "".equals(name) || name.indexOf('.') != -1)
            throw IIOPLogger.ROOT_LOGGER.nameCannotBeNullEmptyOrQualified();

        StringBuffer res = new StringBuffer(name.length());

        if (name.charAt(0) == '_')
            res.append('J'); // 1.3.2.3

        for (int i = 0; i < name.length(); ++i) {
            char c = name.charAt(i);

            if (isLegalIDLIdentifierChar(c))
                res.append(c);
            else // 1.3.2.4
                res.append('U').append(toHexString((int) c));
        }

        String s = res.toString();

        if (isReservedIDLKeyword(s))
            return "_" + s;
        else
            return s;
    }

public
static
String
javaToIDLName
(
String
name
)
{
if
(
name
==
||
""
.
equals
(
name
)
||
name
.
indexOf
(
'
'
)
!=
1
)
throw
IIOPLogger
.
ROOT_LOGGER
.
nameCannotBeNullEmptyOrQualified
(
)
;
StringBuffer
res
=
new
StringBuffer
(
name
.
length
(
)
)
;
if
(
name
.
charAt
(
0
)
==
'
'
)
res
.
append
(
'
'
)
;
// 1.3.2.3
for
(
int
i
=
0
;
i
<
name
.
length
(
)
;
++
i
)
{
char
c
=
name
.
charAt
(
i
)
;
if
(
isLegalIDLIdentifierChar
(
c
)
)
res
.
append
(
c
)
;
else
// 1.3.2.4
res
.
append
(
'
'
)
.
append
(
toHexString
(
(
int
)
c
)
)
;
}
String
s
=
res
.
toString
(
)
;
if
(
isReservedIDLKeyword
(
s
)
)
return
"_"
+
s
;
else
return
s
;
}

Map Java name to IDL name, as per sections 1.3.2.3, 1.3.2.4 and
1.3.2.2.
This only works for a single name component, without a qualifying
dot.

Map Java name to IDL name as per sections 1 . 3 . 2 . 3 1 . 3 . 2 . 4 and 1 . 3 . 2 . 2 . This only works for a single name component without a qualifying dot .


private static boolean isReservedIDLKeyword(String s) {
        // TODO: faster lookup
        for (int i = 0; i < reservedIDLKeywords.length; ++i)
            if (reservedIDLKeywords[i].equals(s))
                return true;
        return false;
    }

private
static
boolean
isReservedIDLKeyword
(
String
s
)
{
// TODO: faster lookup
for
(
int
i
=
0
;
i
<
reservedIDLKeywords
.
length
;
++
i
)
if
(
reservedIDLKeywords
[
i
]
.
equals
(
s
)
)
return
true
;
return
false
;
}

Determine if the argument is a reserved IDL keyword.

Determine if the argument is a reserved IDL keyword .


private static String getSignature(Class cls) {
        if (cls.isArray())
            return "[" + cls.getComponentType();

        if (cls.isPrimitive()) {
            if (cls == Byte.TYPE)
                return "B";
            if (cls == Character.TYPE)
                return "C";
            if (cls == Double.TYPE)
                return "D";
            if (cls == Float.TYPE)
                return "F";
            if (cls == Integer.TYPE)
                return "I";
            if (cls == Long.TYPE)
                return "J";
            if (cls == Short.TYPE)
                return "S";
            if (cls == Boolean.TYPE)
                return "Z";
            throw IIOPLogger.ROOT_LOGGER.unknownPrimitiveType(cls.getName());
        }

        return "L" + cls.getName().replace('.', '/') + ";";
    }

private static String getSignature ( Class cls ) { if ( cls . isArray ( ) ) return "[" + cls . getComponentType ( ) ; if ( cls . isPrimitive ( ) ) { if ( cls == Byte . TYPE ) return "B" ; if ( cls == Character . TYPE ) return "C" ; if ( cls == Double . TYPE ) return "D" ; if ( cls == Float . TYPE ) return "F" ; if ( cls == Integer . TYPE ) return "I" ; if ( cls == Long . TYPE ) return "J" ; if ( cls == Short . TYPE ) return "S" ; if ( cls == Boolean . TYPE ) return "Z" ; throw IIOPLogger . ROOT_LOGGER . unknownPrimitiveType ( cls . getName ( ) ) ; } return "L" + cls . getName ( ) . replace ( ' ' , ' ' ) + ";" ; }

Calculate the signature of a class, according to the Java VM
specification, section 4.3.2.

Calculate the signature of a class according to the Java VM specification section 4 . 3 . 2 .


private static String getSignature(Method method) {
        StringBuffer b = new StringBuffer("(");
        Class[] parameterTypes = method.getParameterTypes();

        for (int i = 0; i < parameterTypes.length; ++i)
            b.append(getSignature(parameterTypes[i]));

        b.append(')').append(getSignature(method.getReturnType()));

        return b.toString();
    }

private static String getSignature ( Method method ) { StringBuffer b = new StringBuffer ( "(" ) ; Class [ ] parameterTypes = method . getParameterTypes ( ) ; for ( int i = 0 ; i < parameterTypes . length ; ++ i ) b . append ( getSignature ( parameterTypes [ i ] ) ) ; b . append ( ' ' ) . append ( getSignature ( method . getReturnType ( ) ) ) ; return b . toString ( ) ; }

Calculate the signature of a method, according to the Java VM
specification, section 4.3.3.

Calculate the signature of a method according to the Java VM specification section 4 . 3 . 3 .


static String primitiveTypeIDLName(Class type) {
        if (type == Void.TYPE)
            return "void";
        if (type == Boolean.TYPE)
            return "boolean";
        if (type == Character.TYPE)
            return "wchar";
        if (type == Byte.TYPE)
            return "octet";
        if (type == Short.TYPE)
            return "short";
        if (type == Integer.TYPE)
            return "long";
        if (type == Long.TYPE)
            return "long long";
        if (type == Float.TYPE)
            return "float";
        if (type == Double.TYPE)
            return "double";
        throw IIOPLogger.ROOT_LOGGER.notAPrimitive(type.getName());
    }

static
String
primitiveTypeIDLName
(
Class
type
)
{
if
(
type
==
Void
.
TYPE
)
return
"void"
;
if
(
type
==
Boolean
.
TYPE
)
return
"boolean"
;
if
(
type
==
Character
.
TYPE
)
return
"wchar"
;
if
(
type
==
Byte
.
TYPE
)
return
"octet"
;
if
(
type
==
Short
.
TYPE
)
return
"short"
;
if
(
type
==
Integer
.
TYPE
)
return
"long"
;
if
(
type
==
Long
.
TYPE
)
return
"long long"
;
if
(
type
==
Float
.
TYPE
)
return
"float"
;
if
(
type
==
Double
.
TYPE
)
return
"double"
;
throw
IIOPLogger
.
ROOT_LOGGER
.
notAPrimitive
(
type
.
getName
(
)
)
;
}

Handle mappings for primitive types, as per section 1.3.3.

Handle mappings for primitive types as per section 1 . 3 . 3 .


public static BatchPermission forName(final String name) {
        Assert.checkNotNullParam("name", name);
        return "*".equals(name) ? allPermission : mapping.getItemByString(name);
    }

public static BatchPermission forName ( final String name ) { Assert . checkNotNullParam ( "name" , name ) ; return "*" . equals ( name ) ? allPermission : mapping . getItemByString ( name ) ; }

Get the permission with the given name.

@param name the name (must not be {@code null})

@return the permission (not {@code null})

@throws IllegalArgumentException if the name is not valid

Get the permission with the given name .


private EntityManager getOrCreateTransactionScopedEntityManager(
            final EntityManagerFactory emf,
            final String scopedPuName,
            final Map properties,
            final SynchronizationType synchronizationType) {
        EntityManager entityManager = TransactionUtil.getTransactionScopedEntityManager(puScopedName, transactionSynchronizationRegistry);
        if (entityManager == null) {
            entityManager = createEntityManager(emf, properties, synchronizationType);
            if (ROOT_LOGGER.isDebugEnabled()) {
                ROOT_LOGGER.debugf("%s: created entity manager session %s", TransactionUtil.getEntityManagerDetails(entityManager, scopedPuName),
                        TransactionUtil.getTransaction(transactionManager).toString());
            }
            TransactionUtil.registerSynchronization(entityManager, scopedPuName, transactionSynchronizationRegistry, transactionManager);
            TransactionUtil.putEntityManagerInTransactionRegistry(scopedPuName, entityManager, transactionSynchronizationRegistry);
        }
        else {
            testForMixedSynchronizationTypes(emf, entityManager, puScopedName, synchronizationType, properties);
            if (ROOT_LOGGER.isDebugEnabled()) {
                ROOT_LOGGER.debugf("%s: reuse entity manager session already in tx %s", TransactionUtil.getEntityManagerDetails(entityManager, scopedPuName),
                        TransactionUtil.getTransaction(transactionManager).toString());
            }
        }
        return entityManager;
    }

get or create a Transactional entity manager.
Only call while a transaction is active in the current thread.

@param emf
@param scopedPuName
@param properties
@param synchronizationType
@return

get or create a Transactional entity manager . Only call while a transaction is active in the current thread .


public V put(K key, V value) {
        if (value == null)
            throw new NullPointerException();
        int hash = hashOf(key);
        return segmentFor(hash).put(key, hash, value, false);
    }

public V put ( K key , V value ) { if ( value == null ) throw new NullPointerException ( ) ; int hash = hashOf ( key ) ; return segmentFor ( hash ) . put ( key , hash , value , false ) ; }

Maps the specified key to the specified value in this table.
Neither the key nor the value can be null.

<p> The value can be retrieved by calling the <tt>get</tt> method
with a key that is equal to the original key.

@param key key with which the specified value is to be associated
@param value value to be associated with the specified key
@return the previous value associated with <tt>key</tt>, or
<tt>null</tt> if there was no mapping for <tt>key</tt>
@throws NullPointerException if the specified key or value is null

Maps the specified key to the specified value in this table . Neither the key nor the value can be null .


static ModelNode convertSecurityRole(final ModelNode camelCase) {
        final ModelNode result = new ModelNode();
        result.setEmptyList();
        if (camelCase.isDefined()) {
            for (ModelNode role : camelCase.asList()) {
                final ModelNode roleNode = result.add();
                for (Property prop : role.asPropertyList()) {
                    String key = prop.getName();
                    if ("createDurableQueue".equals(key)) {
                        key = SecurityRoleDefinition.CREATE_DURABLE_QUEUE.getName();
                    } else if ("deleteDurableQueue".equals(key)) {
                        key = SecurityRoleDefinition.DELETE_DURABLE_QUEUE.getName();
                    } else if ("createNonDurableQueue".equals(key)) {
                        key = SecurityRoleDefinition.CREATE_NON_DURABLE_QUEUE.getName();
                    } else if ("deleteNonDurableQueue".equals(key)) {
                        key = SecurityRoleDefinition.DELETE_NON_DURABLE_QUEUE.getName();
                    }

                    roleNode.get(key).set(prop.getValue());
                }
            }
        }

        return result;
    }

static ModelNode convertSecurityRole ( final ModelNode camelCase ) { final ModelNode result = new ModelNode ( ) ; result . setEmptyList ( ) ; if ( camelCase . isDefined ( ) ) { for ( ModelNode role : camelCase . asList ( ) ) { final ModelNode roleNode = result . add ( ) ; for ( Property prop : role . asPropertyList ( ) ) { String key = prop . getName ( ) ; if ( "createDurableQueue" . equals ( key ) ) { key = SecurityRoleDefinition . CREATE_DURABLE_QUEUE . getName ( ) ; } else if ( "deleteDurableQueue" . equals ( key ) ) { key = SecurityRoleDefinition . DELETE_DURABLE_QUEUE . getName ( ) ; } else if ( "createNonDurableQueue" . equals ( key ) ) { key = SecurityRoleDefinition . CREATE_NON_DURABLE_QUEUE . getName ( ) ; } else if ( "deleteNonDurableQueue" . equals ( key ) ) { key = SecurityRoleDefinition . DELETE_NON_DURABLE_QUEUE . getName ( ) ; } roleNode . get ( key ) . set ( prop . getValue ( ) ) ; } } } return result ; }

Utility for converting camel case based ActiveMQ formats to WildFly standards.

Utility for converting camel case based ActiveMQ formats to WildFly standards .


private TimerImpl mostRecentEntityVersion(final TimerImpl timerImpl) {
        try {
            final int status = ContextTransactionManager.getInstance().getStatus();
            if (status == Status.STATUS_UNKNOWN ||
                    status == Status.STATUS_NO_TRANSACTION) {
                return timerImpl;
            }
            final String key = timerTransactionKey(timerImpl);
            TimerImpl existing = (TimerImpl) transactionSynchronizationRegistry.getValue().getResource(key);
            return existing != null ? existing : timerImpl;
        } catch (SystemException e) {
            throw new RuntimeException(e);
        }
    }

private TimerImpl mostRecentEntityVersion ( final TimerImpl timerImpl ) { try { final int status = ContextTransactionManager . getInstance ( ) . getStatus ( ) ; if ( status == Status . STATUS_UNKNOWN || status == Status . STATUS_NO_TRANSACTION ) { return timerImpl ; } final String key = timerTransactionKey ( timerImpl ) ; TimerImpl existing = ( TimerImpl ) transactionSynchronizationRegistry . getValue ( ) . getResource ( key ) ; return existing != null ? existing : timerImpl ; } catch ( SystemException e ) { throw new RuntimeException ( e ) ; } }

Returns either the loaded entity or the most recent version of the entity that has
been persisted in this transaction.

Returns either the loaded entity or the most recent version of the entity that has been persisted in this transaction .


private Map<String, TimerImpl> getTimers(final String timedObjectId, final TimerServiceImpl timerService) {
        return loadTimersFromFile(timedObjectId, timerService);
    }

private Map < String , TimerImpl > getTimers ( final String timedObjectId , final TimerServiceImpl timerService ) { return loadTimersFromFile ( timedObjectId , timerService ) ; }

Gets the timer map, loading from the persistent store if necessary. Should be called under lock

@param timedObjectId The timed object id
@return The timers for the object

Gets the timer map loading from the persistent store if necessary . Should be called under lock


private String getDirectory(String timedObjectId) {
        String dirName = directories.get(timedObjectId);
        if (dirName == null) {
            dirName = baseDir.getAbsolutePath() + File.separator + timedObjectId.replace(File.separator, "-");
            File file = new File(dirName);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    EJB3_TIMER_LOGGER.failToCreateDirectoryForPersistTimers(file);
                }
            }
            directories.put(timedObjectId, dirName);
        }
        return dirName;
    }

private String getDirectory ( String timedObjectId ) { String dirName = directories . get ( timedObjectId ) ; if ( dirName == null ) { dirName = baseDir . getAbsolutePath ( ) + File . separator + timedObjectId . replace ( File . separator , "-" ) ; File file = new File ( dirName ) ; if ( ! file . exists ( ) ) { if ( ! file . mkdirs ( ) ) { EJB3_TIMER_LOGGER . failToCreateDirectoryForPersistTimers ( file ) ; } } directories . put ( timedObjectId , dirName ) ; } return dirName ; }

Gets the directory for a given timed object, making sure it exists.

@param timedObjectId The timed object
@return The directory

Gets the directory for a given timed object making sure it exists .


synchronized void addListener(final String target, final int scope, final NamingListener namingListener) {
        final TargetScope targetScope = new TargetScope(target, scope);
        // Do we have a holder for this listener
        ListenerHolder holder = holdersByListener.get(namingListener);
        if (holder == null) {
            holder = new ListenerHolder(namingListener, targetScope);
            final Map<NamingListener, ListenerHolder> byListenerCopy = new FastCopyHashMap<NamingListener, ListenerHolder>(holdersByListener);
            byListenerCopy.put(namingListener, holder);
            holdersByListener = byListenerCopy;
        } else {
            holder.addTarget(targetScope);
        }

        List<ListenerHolder> holdersForTarget = holdersByTarget.get(targetScope);
        if (holdersForTarget == null) {
            holdersForTarget = new CopyOnWriteArrayList<ListenerHolder>();
            final Map<TargetScope, List<ListenerHolder>> byTargetCopy = new FastCopyHashMap<TargetScope, List<ListenerHolder>>(holdersByTarget);
            byTargetCopy.put(targetScope, holdersForTarget);
            holdersByTarget = byTargetCopy;
        }
        holdersForTarget.add(holder);
    }

Add a listener to the coordinator with a given target name and event scope.  This information is used when an
event is fired to determine whether or not to fire this listener.

@param target The target name to lister
@param scope The event scope
@param namingListener The listener

Add a listener to the coordinator with a given target name and event scope . This information is used when an event is fired to determine whether or not to fire this listener .


synchronized void removeListener(final NamingListener namingListener) {
        // Do we have a holder for this listener
        final ListenerHolder holder = holdersByListener.get(namingListener);
        if (holder == null) {
            return;
        }

        final Map<NamingListener, ListenerHolder> byListenerCopy = new FastCopyHashMap<NamingListener, ListenerHolder>(holdersByListener);
        byListenerCopy.remove(namingListener);
        holdersByListener = byListenerCopy;

        final Map<TargetScope, List<ListenerHolder>> byTargetCopy = new FastCopyHashMap<TargetScope, List<ListenerHolder>>(holdersByTarget);
        for (TargetScope targetScope : holder.targets) {
            final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
            holders.remove(holder);
            if (holders.isEmpty()) {
                byTargetCopy.remove(targetScope);
            }
        }
        holdersByTarget = byTargetCopy;
    }

Remove a listener.  Will remove it from all target mappings.  Once this method returns, the listener will no longer
receive any events.

@param namingListener The listener

Remove a listener . Will remove it from all target mappings . Once this method returns the listener will no longer receive any events .


void fireEvent(final EventContext context, final Name name, final Binding existingBinding, final Binding newBinding, int type, final String changeInfo, final Integer... scopes) {
        final String target = name.toString();
        final Set<Integer> scopeSet = new HashSet<Integer>(Arrays.asList(scopes));
        final NamingEvent event = new NamingEvent(context, type, newBinding, existingBinding, changeInfo);

        final Set<ListenerHolder> holdersToFire = new HashSet<ListenerHolder>();

        // Check for OBJECT_SCOPE based listeners
        if (scopeSet.contains(EventContext.OBJECT_SCOPE)) {
            final TargetScope targetScope = new TargetScope(target, EventContext.OBJECT_SCOPE);
            final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
            if (holders != null) {
                for (ListenerHolder holder : holders) {
                    holdersToFire.add(holder);
                }
            }
        }

        // Check for ONELEVEL_SCOPE based listeners
        if (scopeSet.contains(EventContext.ONELEVEL_SCOPE) && !name.isEmpty()) {
            final TargetScope targetScope = new TargetScope(name.getPrefix(name.size() - 1).toString(), EventContext.ONELEVEL_SCOPE);
            final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
            if (holders != null) {
                for (ListenerHolder holder : holders) {
                    holdersToFire.add(holder);
                }
            }
        }

        // Check for SUBTREE_SCOPE based listeners
        if (scopeSet.contains(EventContext.SUBTREE_SCOPE) && !name.isEmpty()) {
            for (int i = 1; i < name.size(); i++) {
                final Name parentName = name.getPrefix(i);
                final TargetScope targetScope = new TargetScope(parentName.toString(), EventContext.SUBTREE_SCOPE);
                final List<ListenerHolder> holders = holdersByTarget.get(targetScope);
                if (holders != null) {
                    for (ListenerHolder holder : holders) {
                        holdersToFire.add(holder);
                    }
                }
            }
        }

        executor.execute(new FireEventTask(holdersToFire, event));
    }

Fire a naming event.  An event will be created with the provided information and sent to each listener that matches
the target and scope information.

@param context The event context generating the event.
@param name The target name the event represents
@param existingBinding The existing binding at the provided name
@param newBinding The new binding at the provided name
@param type The event type
@param changeInfo The change info for the event
@param scopes The scopes this event should be fired against

Fire a naming event . An event will be created with the provided information and sent to each listener that matches the target and scope information .


public static <T extends AutoCloseable> Consumer<T> close() {
        return value -> {
            try {
                value.close();
            } catch (Throwable e) {
                ClusteringLogger.ROOT_LOGGER.failedToClose(e, value);
            }
        };
    }

public static < T extends AutoCloseable > Consumer < T > close ( ) { return value -> { try { value . close ( ) ; } catch ( Throwable e ) { ClusteringLogger . ROOT_LOGGER . failedToClose ( e , value ) ; } } ; }

Returns a consumer that closes its input.
@return a consumer that closes its input.

Returns a consumer that closes its input .


private void addPrivateCredential(final Subject subject, final Object credential) {
        if (!WildFlySecurityManager.isChecking()) {
            subject.getPrivateCredentials().add(credential);
        }
        else {
            AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
                subject.getPrivateCredentials().add(credential);
                return null;
            });
        }
    }

private void addPrivateCredential ( final Subject subject , final Object credential ) { if ( ! WildFlySecurityManager . isChecking ( ) ) { subject . getPrivateCredentials ( ) . add ( credential ) ; } else { AccessController . doPrivileged ( ( PrivilegedAction < Void > ) ( ) -> { subject . getPrivateCredentials ( ) . add ( credential ) ; return null ; } ) ; } }

Add the specified credential to the subject's private credentials set.

@param subject the {@link Subject} to add the credential to.
@param credential a reference to the credential.

Add the specified credential to the subject s private credentials set .


public Object getObjectInstance(final Object ref, final Name name, final Context nameCtx, final Hashtable<?, ?> environment) throws Exception {
        final ClassLoader classLoader = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        if (classLoader == null) {
            return ref;
        }
        final String factoriesProp = (String) environment.get(Context.OBJECT_FACTORIES);
        if (factoriesProp != null) {
            final String[] classes = factoriesProp.split(":");
            for (String className : classes) {
                try {
                    final Class<?> factoryClass = classLoader.loadClass(className);
                    final ObjectFactory objectFactory = ObjectFactory.class.cast(factoryClass.newInstance());
                    final Object result = objectFactory.getObjectInstance(ref, name, nameCtx, environment);
                    if (result != null) {
                        return result;
                    }
                } catch (Throwable ignored) {
                }
            }
        }
        return ref;
    }

public Object getObjectInstance ( final Object ref , final Name name , final Context nameCtx , final Hashtable < ? , ? > environment ) throws Exception { final ClassLoader classLoader = WildFlySecurityManager . getCurrentContextClassLoaderPrivileged ( ) ; if ( classLoader == null ) { return ref ; } final String factoriesProp = ( String ) environment . get ( Context . OBJECT_FACTORIES ) ; if ( factoriesProp != null ) { final String [ ] classes = factoriesProp . split ( ":" ) ; for ( String className : classes ) { try { final Class < ? > factoryClass = classLoader . loadClass ( className ) ; final ObjectFactory objectFactory = ObjectFactory . class . cast ( factoryClass . newInstance ( ) ) ; final Object result = objectFactory . getObjectInstance ( ref , name , nameCtx , environment ) ; if ( result != null ) { return result ; } } catch ( Throwable ignored ) { } } } return ref ; }

Create an object instance.

@param ref         Object containing reference information
@param name        The name relative to nameCtx
@param nameCtx     The naming context
@param environment The environment information
@return The object
@throws Exception If any error occur


protected static void addTxManagementInterceptorForView(ViewDescription view) {
        // add a Tx configurator
        view.getConfigurators().add(new ViewConfigurator() {
            @Override
            public void configure(DeploymentPhaseContext context, ComponentConfiguration componentConfiguration, ViewDescription description, ViewConfiguration configuration) throws DeploymentUnitProcessingException {
                EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) componentConfiguration.getComponentDescription();
                // Add CMT interceptor factory
                if (TransactionManagementType.CONTAINER.equals(ejbComponentDescription.getTransactionManagementType())) {
                    configuration.addViewInterceptor(CMTTxInterceptor.FACTORY, InterceptorOrder.View.CMT_TRANSACTION_INTERCEPTOR);
                }
            }
        });
    }

protected
static
void
addTxManagementInterceptorForView
(
ViewDescription
view
)
{
// add a Tx configurator
view
.
getConfigurators
(
)
.
add
(
new
ViewConfigurator
(
)
{
@
Override
public
void
configure
(
DeploymentPhaseContext
context
,
ComponentConfiguration
componentConfiguration
,
ViewDescription
description
,
ViewConfiguration
configuration
)
throws
DeploymentUnitProcessingException
{
EJBComponentDescription
ejbComponentDescription
=
(
EJBComponentDescription
)
componentConfiguration
.
getComponentDescription
(
)
;
// Add CMT interceptor factory
if
(
TransactionManagementType
.
CONTAINER
.
equals
(
ejbComponentDescription
.
getTransactionManagementType
(
)
)
)
{
configuration
.
addViewInterceptor
(
CMTTxInterceptor
.
FACTORY
,
InterceptorOrder
.
View
.
CMT_TRANSACTION_INTERCEPTOR
)
;
}
}
}
)
;
}

Sets up the transaction management interceptor for all methods of the passed view.

@param view The EJB bean view

Sets up the transaction management interceptor for all methods of the passed view .


private static void subst(final StringBuilder stringBuilder, final String from, final String to) {
        int begin = 0, end = 0;

        while ((end = stringBuilder.indexOf(from, end)) != -1) {
            stringBuilder.delete(end, end + from.length());
            stringBuilder.insert(end, to);

            // update positions
            begin = end + to.length();
            end = begin;
        }
    }

private
static
void
subst
(
final
StringBuilder
stringBuilder
,
final
String
from
,
final
String
to
)
{
int
begin
=
0
,
end
=
0
;
while
(
(
end
=
stringBuilder
.
indexOf
(
from
,
end
)
)
!=
1
)
{
stringBuilder
.
delete
(
end
,
end
+
from
.
length
(
)
)
;
stringBuilder
.
insert
(
end
,
to
)
;
// update positions
begin
=
end
+
to
.
length
(
)
;
end
=
begin
;
}
}

Substitute sub-strings inside of a string.

@param stringBuilder String buffer to use for substitution (buffer is not reset)
@param from String to substitute from
@param to   String to substitute to

Substitute sub - strings inside of a string .


private TransportConfiguration createInVMTransportConfiguration(OperationContext context) throws OperationFailedException {
        final Resource serverResource = context.readResource(EMPTY_ADDRESS, false);
        Set<Resource.ResourceEntry> invmConnectors = serverResource.getChildren(CommonAttributes.IN_VM_CONNECTOR);
        if (invmConnectors.isEmpty()) {
            throw MessagingLogger.ROOT_LOGGER.noInVMConnector();
        }
        Resource.ResourceEntry connectorEntry = invmConnectors.iterator().next();

        Resource connectorResource = context.readResource(PathAddress.pathAddress(connectorEntry.getPathElement()), false);
        ModelNode model = connectorResource.getModel();

        Map<String, Object> params = new HashMap<>(CommonAttributes.PARAMS.unwrap(context, model));
        params.put(InVMTransportDefinition.SERVER_ID.getName(), InVMTransportDefinition.SERVER_ID.resolveModelAttribute(context, model).asInt());
        TransportConfiguration transportConfiguration = new TransportConfiguration(InVMConnectorFactory.class.getName(), params);
        return transportConfiguration;
    }

private TransportConfiguration createInVMTransportConfiguration ( OperationContext context ) throws OperationFailedException { final Resource serverResource = context . readResource ( EMPTY_ADDRESS , false ) ; Set < Resource . ResourceEntry > invmConnectors = serverResource . getChildren ( CommonAttributes . IN_VM_CONNECTOR ) ; if ( invmConnectors . isEmpty ( ) ) { throw MessagingLogger . ROOT_LOGGER . noInVMConnector ( ) ; } Resource . ResourceEntry connectorEntry = invmConnectors . iterator ( ) . next ( ) ; Resource connectorResource = context . readResource ( PathAddress . pathAddress ( connectorEntry . getPathElement ( ) ) , false ) ; ModelNode model = connectorResource . getModel ( ) ; Map < String , Object > params = new HashMap <> ( CommonAttributes . PARAMS . unwrap ( context , model ) ) ; params . put ( InVMTransportDefinition . SERVER_ID . getName ( ) , InVMTransportDefinition . SERVER_ID . resolveModelAttribute ( context , model ) . asInt ( ) ) ; TransportConfiguration transportConfiguration = new TransportConfiguration ( InVMConnectorFactory . class . getName ( ) , params ) ; return transportConfiguration ; }

The XmlDataImporter requires a connector to connect to the artemis broker.

We require to use a in-vm one so that importing a journal is not subject to any network connection problem.

The XmlDataImporter requires a connector to connect to the artemis broker .


private String addEarPrefixIfRelativeName(final String configuredName, final DeploymentUnit deploymentUnit,
            final Class<?> componentClass) throws DeploymentUnitProcessingException {
        if (!configuredName.startsWith("#")) {
            return configuredName;
        }
        final DeploymentUnit parent = deploymentUnit.getParent();
        if (parent == null) {
            throw EjbLogger.ROOT_LOGGER.relativeResourceAdapterNameInStandaloneModule(deploymentUnit.getName(),
                    componentClass.getName(), configuredName);
        }
        return new StringBuilder().append(parent.getName()).append(configuredName).toString();
    }

adds ear prefix to configured adapter name if it is specified in relative form


public static DeploymentUnit getRootDeploymentUnit(DeploymentUnit deploymentUnit) {
        if (deploymentUnit.getParent() == null) {
            return deploymentUnit;
        }
        return deploymentUnit.getParent();
    }

public static DeploymentUnit getRootDeploymentUnit ( DeploymentUnit deploymentUnit ) { if ( deploymentUnit . getParent ( ) == null ) { return deploymentUnit ; } return deploymentUnit . getParent ( ) ; }

Returns the parent of the given deployment unit if such a parent exists. If the given deployment unit is the parent
deployment unit, it is returned.

Returns the parent of the given deployment unit if such a parent exists . If the given deployment unit is the parent deployment unit it is returned .


public ServiceName getServiceName() {
        //TODO: need to set viewNameParts somewhere
        if (!viewNameParts.isEmpty()) {
            return componentDescription.getServiceName().append("VIEW").append(viewNameParts.toArray(new String[viewNameParts.size()]));
        } else {
            return componentDescription.getServiceName().append("VIEW").append(viewClassName);
        }
    }

Get the service name for this view.

@return the service name


public ViewConfiguration createViewConfiguration(final Class<?> viewClass, final ComponentConfiguration componentConfiguration, final ProxyFactory<?> proxyFactory) {
        return new ViewConfiguration(viewClass, componentConfiguration, getServiceName(), proxyFactory);
    }

public ViewConfiguration createViewConfiguration ( final Class < ? > viewClass , final ComponentConfiguration componentConfiguration , final ProxyFactory < ? > proxyFactory ) { return new ViewConfiguration ( viewClass , componentConfiguration , getServiceName ( ) , proxyFactory ) ; }

Creates view configuration. Allows for extensibility in EE sub components.

@param viewClass              view class
@param componentConfiguration component config
@param proxyFactory           proxy factory
@return new view configuration

Creates view configuration . Allows for extensibility in EE sub components .


protected InjectionSource createInjectionSource(final ServiceName serviceName, Value<ClassLoader> viewClassLoader, boolean appclient) {
        return new ViewBindingInjectionSource(serviceName);
    }

protected InjectionSource createInjectionSource ( final ServiceName serviceName , Value < ClassLoader > viewClassLoader , boolean appclient ) { return new ViewBindingInjectionSource ( serviceName ) ; }

Create the injection source

@param serviceName     The view service name
@param viewClassLoader


public List<InterceptorFactory> getViewInterceptors(Method method) {
        OrderedItemContainer<InterceptorFactory> container = viewInterceptors.get(method);
        if (container == null) {
            return Collections.emptyList();
        }
        return container.getSortedItems();
    }

public List < InterceptorFactory > getViewInterceptors ( Method method ) { OrderedItemContainer < InterceptorFactory > container = viewInterceptors . get ( method ) ; if ( container == null ) { return Collections . emptyList ( ) ; } return container . getSortedItems ( ) ; }

Get the view interceptors for a method.  These interceptors are run sequentially on the "server side" of an
invocation.  The interceptor factories are used every time a new view instance is constructed, called with a
new factory context each time.  The factory may return the same interceptor instance or a new interceptor
instance as appropriate.

@param method the method to look up
@return the interceptors for this method

Get the view interceptors for a method . These interceptors are run sequentially on the server side of an invocation . The interceptor factories are used every time a new view instance is constructed called with a new factory context each time . The factory may return the same interceptor instance or a new interceptor instance as appropriate .


public void addViewInterceptor(InterceptorFactory interceptorFactory, int priority) {
        for (Method method : proxyFactory.getCachedMethods()) {
            addViewInterceptor(method, interceptorFactory, priority);
        }
    }

public void addViewInterceptor ( InterceptorFactory interceptorFactory , int priority ) { for ( Method method : proxyFactory . getCachedMethods ( ) ) { addViewInterceptor ( method , interceptorFactory , priority ) ; } }

Adds an interceptor factory to all methods of a view

@param interceptorFactory The factory to add
@param priority           The interceptor order


public void addViewInterceptor(Method method, InterceptorFactory interceptorFactory, int priority) {
        OrderedItemContainer<InterceptorFactory> container = viewInterceptors.get(method);
        if (container == null) {
            viewInterceptors.put(method, container = new OrderedItemContainer<InterceptorFactory>());
        }
        container.add(interceptorFactory, priority);
    }

public void addViewInterceptor ( Method method , InterceptorFactory interceptorFactory , int priority ) { OrderedItemContainer < InterceptorFactory > container = viewInterceptors . get ( method ) ; if ( container == null ) { viewInterceptors . put ( method , container = new OrderedItemContainer < InterceptorFactory > ( ) ) ; } container . add ( interceptorFactory , priority ) ; }

Adds a view interceptor to the given method

@param method             The method to add
@param interceptorFactory The interceptor factory
@param priority           The priority


public List<InterceptorFactory> getClientInterceptors(Method method) {
        OrderedItemContainer<InterceptorFactory> container = clientInterceptors.get(method);
        if (container == null) {
            return Collections.emptyList();
        }
        return container.getSortedItems();
    }

public List < InterceptorFactory > getClientInterceptors ( Method method ) { OrderedItemContainer < InterceptorFactory > container = clientInterceptors . get ( method ) ; if ( container == null ) { return Collections . emptyList ( ) ; } return container . getSortedItems ( ) ; }

Get the client interceptors for a method.  These interceptors are run sequentially on the "client side" of an
invocation.  The interceptor factories are used every time a new client proxy instance is constructed, called with a
new factory context each time.  The factory may return the same interceptor instance or a new interceptor
instance as appropriate.

@param method the method to look up
@return the interceptors for this method

Get the client interceptors for a method . These interceptors are run sequentially on the client side of an invocation . The interceptor factories are used every time a new client proxy instance is constructed called with a new factory context each time . The factory may return the same interceptor instance or a new interceptor instance as appropriate .


public void addClientInterceptor(InterceptorFactory interceptorFactory, int priority) {
        for (Method method : proxyFactory.getCachedMethods()) {
            addClientInterceptor(method, interceptorFactory, priority);
        }
    }

public void addClientInterceptor ( InterceptorFactory interceptorFactory , int priority ) { for ( Method method : proxyFactory . getCachedMethods ( ) ) { addClientInterceptor ( method , interceptorFactory , priority ) ; } }

Adds a client interceptor factory to all methods of a view

@param interceptorFactory The factory to add
@param priority           The interceptor order


public void addClientInterceptor(Method method, InterceptorFactory interceptorFactory, int priority) {
        OrderedItemContainer<InterceptorFactory> container = clientInterceptors.get(method);
        if (container == null) {
            clientInterceptors.put(method, container = new OrderedItemContainer<InterceptorFactory>());
        }
        container.add(interceptorFactory, priority);
    }

public void addClientInterceptor ( Method method , InterceptorFactory interceptorFactory , int priority ) { OrderedItemContainer < InterceptorFactory > container = clientInterceptors . get ( method ) ; if ( container == null ) { clientInterceptors . put ( method , container = new OrderedItemContainer < InterceptorFactory > ( ) ) ; } container . add ( interceptorFactory , priority ) ; }

Adds a client interceptor to the given method

@param method             The method to add
@param interceptorFactory The interceptor factory
@param priority           The priority


public <T> void putPrivateData(final Class<T> type, T data ) {
        privateData.put(type, data);
    }

public < T > void putPrivateData ( final Class < T > type , T data ) { privateData . put ( type , data ) ; }

Attaches arbitrary private data to this view instance

@param type The type of data
@param data The data


protected static void unexpectedElement(final XMLExtendedStreamReader reader) throws XMLStreamException {
        throw EeLogger.ROOT_LOGGER.unexpectedElement(reader.getName(), reader.getLocation());
    }

protected static void unexpectedElement ( final XMLExtendedStreamReader reader ) throws XMLStreamException { throw EeLogger . ROOT_LOGGER . unexpectedElement ( reader . getName ( ) , reader . getLocation ( ) ) ; }

Throws a XMLStreamException for the unexpected element that was encountered during the parse

@param reader the stream reader
@throws XMLStreamException


public static List<EJBEndpoint> getJaxwsEjbs(final DeploymentUnit unit) {
        final JAXWSDeployment jaxwsDeployment = getOptionalAttachment(unit, WSAttachmentKeys.JAXWS_ENDPOINTS_KEY);
        return jaxwsDeployment != null ? jaxwsDeployment.getEjbEndpoints() : Collections.<EJBEndpoint>emptyList();
    }

public static List < EJBEndpoint > getJaxwsEjbs ( final DeploymentUnit unit ) { final JAXWSDeployment jaxwsDeployment = getOptionalAttachment ( unit , WSAttachmentKeys . JAXWS_ENDPOINTS_KEY ) ; return jaxwsDeployment != null ? jaxwsDeployment . getEjbEndpoints ( ) : Collections . < EJBEndpoint > emptyList ( ) ; }

Gets list of JAXWS EJBs meta data.

@param unit deployment unit
@return list of JAXWS EJBs meta data


public static List<POJOEndpoint> getJaxwsPojos(final DeploymentUnit unit) {
        final JAXWSDeployment jaxwsDeployment = unit.getAttachment(WSAttachmentKeys.JAXWS_ENDPOINTS_KEY);
        return jaxwsDeployment != null ? jaxwsDeployment.getPojoEndpoints() : Collections.<POJOEndpoint>emptyList();
    }

public static List < POJOEndpoint > getJaxwsPojos ( final DeploymentUnit unit ) { final JAXWSDeployment jaxwsDeployment = unit . getAttachment ( WSAttachmentKeys . JAXWS_ENDPOINTS_KEY ) ; return jaxwsDeployment != null ? jaxwsDeployment . getPojoEndpoints ( ) : Collections . < POJOEndpoint > emptyList ( ) ; }

Gets list of JAXWS POJOs meta data.

@param unit deployment unit
@return list of JAXWS POJOs meta data


public static String getEndpointName(final ServletMetaData servletMD) {
        final String endpointName = servletMD.getName();
        return endpointName != null ? endpointName.trim() : null;
    }

public static String getEndpointName ( final ServletMetaData servletMD ) { final String endpointName = servletMD . getName ( ) ; return endpointName != null ? endpointName . trim ( ) : null ; }

Returns endpoint name.

@param servletMD servlet meta data
@return endpoint name


public static String getEndpointClassName(final ServletMetaData servletMD) {
        final String endpointClass = servletMD.getServletClass();
        return endpointClass != null ? endpointClass.trim() : null;
    }

public static String getEndpointClassName ( final ServletMetaData servletMD ) { final String endpointClass = servletMD . getServletClass ( ) ; return endpointClass != null ? endpointClass . trim ( ) : null ; }

Returns endpoint class name.

@param servletMD servlet meta data
@return endpoint class name


public static ServletMetaData getServletForName(final JBossWebMetaData jbossWebMD, final String servletName) {
        for (JBossServletMetaData servlet : jbossWebMD.getServlets()) {
            if (servlet.getName().equals(servletName)) {
                return servlet;
            }
        }

        return null;
    }

public static ServletMetaData getServletForName ( final JBossWebMetaData jbossWebMD , final String servletName ) { for ( JBossServletMetaData servlet : jbossWebMD . getServlets ( ) ) { if ( servlet . getName ( ) . equals ( servletName ) ) { return servlet ; } } return null ; }

Returns servlet meta data for requested servlet name.

@param jbossWebMD jboss web meta data
@param servletName servlet name
@return servlet meta data

Returns servlet meta data for requested servlet name .


public static <A> A getRequiredAttachment(final DeploymentUnit unit, final AttachmentKey<A> key) {
        final A value = unit.getAttachment(key);
        if (value == null) {
            throw new IllegalStateException();
        }

        return value;
    }

public static < A > A getRequiredAttachment ( final DeploymentUnit unit , final AttachmentKey < A > key ) { final A value = unit . getAttachment ( key ) ; if ( value == null ) { throw new IllegalStateException ( ) ; } return value ; }

Returns required attachment value from deployment unit.

@param <A> expected value
@param unit deployment unit
@param key attachment key
@return required attachment
@throws IllegalStateException if attachment value is null

Returns required attachment value from deployment unit .


public static <A> A getOptionalAttachment(final DeploymentUnit unit, final AttachmentKey<A> key) {
        return unit.getAttachment(key);
    }

public static < A > A getOptionalAttachment ( final DeploymentUnit unit , final AttachmentKey < A > key ) { return unit . getAttachment ( key ) ; }

Returns optional attachment value from deployment unit or null if not bound.

@param <A> expected value
@param unit deployment unit
@param key attachment key
@return optional attachment value or null

Returns optional attachment value from deployment unit or null if not bound .


public static JBossWebMetaData getJBossWebMetaData(final DeploymentUnit unit) {
        final WarMetaData warMetaData = getOptionalAttachment(unit, WarMetaData.ATTACHMENT_KEY);
        JBossWebMetaData result = null;
        if (warMetaData != null) {
            result = warMetaData.getMergedJBossWebMetaData();
            if (result == null) {
                result = warMetaData.getJBossWebMetaData();
            }
        } else {
            result = getOptionalAttachment(unit, WSAttachmentKeys.JBOSSWEB_METADATA_KEY);
        }
        return result;
    }

public static JBossWebMetaData getJBossWebMetaData ( final DeploymentUnit unit ) { final WarMetaData warMetaData = getOptionalAttachment ( unit , WarMetaData . ATTACHMENT_KEY ) ; JBossWebMetaData result = null ; if ( warMetaData != null ) { result = warMetaData . getMergedJBossWebMetaData ( ) ; if ( result == null ) { result = warMetaData . getJBossWebMetaData ( ) ; } } else { result = getOptionalAttachment ( unit , WSAttachmentKeys . JBOSSWEB_METADATA_KEY ) ; } return result ; }

Gets the JBossWebMetaData from the WarMetaData attached to the provided deployment unit, if any.

@param unit
@return the JBossWebMetaData or null if either that or the parent WarMetaData are not found.

Gets the JBossWebMetaData from the WarMetaData attached to the provided deployment unit if any .


public static JBossPortComponentMetaData getJBossWebserviceMetaDataPortComponent(
        final DeploymentUnit unit, final String name) {

        if (name != null) {
            final JBossWebservicesMetaData jbossWebserviceMetaData = unit.getAttachment(JBOSS_WEBSERVICES_METADATA_KEY);

            if (jbossWebserviceMetaData != null) {
                JBossPortComponentMetaData[] portComponent = jbossWebserviceMetaData.getPortComponents();

                if (portComponent != null) {
                    for (JBossPortComponentMetaData component : portComponent) {
                        if (name.equals(component.getEjbName())) {
                            return component;
                        }
                    }
                }
            }
        }
        return null;
    }

public static JBossPortComponentMetaData getJBossWebserviceMetaDataPortComponent ( final DeploymentUnit unit , final String name ) { if ( name != null ) { final JBossWebservicesMetaData jbossWebserviceMetaData = unit . getAttachment ( JBOSS_WEBSERVICES_METADATA_KEY ) ; if ( jbossWebserviceMetaData != null ) { JBossPortComponentMetaData [ ] portComponent = jbossWebserviceMetaData . getPortComponents ( ) ; if ( portComponent != null ) { for ( JBossPortComponentMetaData component : portComponent ) { if ( name . equals ( component . getEjbName ( ) ) ) { return component ; } } } } } return null ; }

Return a named port-component from the jboss-webservices.xml
@param unit
@param name
@return

Return a named port - component from the jboss - webservices . xml


public static EJBEndpoint getWebserviceMetadataEJBEndpoint(final JAXWSDeployment jaxwsDeployment,
                                                               final String className) {

        java.util.List<EJBEndpoint> ejbEndpointList = jaxwsDeployment.getEjbEndpoints();
        for (EJBEndpoint ejbEndpoint : ejbEndpointList) {
            if (className.equals(ejbEndpoint.getClassName())) {
                return ejbEndpoint;
            }
        }
        return null;
    }

public static EJBEndpoint getWebserviceMetadataEJBEndpoint ( final JAXWSDeployment jaxwsDeployment , final String className ) { java . util . List < EJBEndpoint > ejbEndpointList = jaxwsDeployment . getEjbEndpoints ( ) ; for ( EJBEndpoint ejbEndpoint : ejbEndpointList ) { if ( className . equals ( ejbEndpoint . getClassName ( ) ) ) { return ejbEndpoint ; } } return null ; }

Returns an EJBEndpoint based upon fully qualified classname.
@param jaxwsDeployment
@param className
@return

Returns an EJBEndpoint based upon fully qualified classname .


public static String getContextRoot(final Deployment dep, final JBossWebMetaData jbossWebMD) {
        final DeploymentUnit unit = WSHelper.getRequiredAttachment(dep, DeploymentUnit.class);
        final JBossAppMetaData jbossAppMD = unit.getParent() == null ? null : ASHelper.getOptionalAttachment(unit.getParent(),
                WSAttachmentKeys.JBOSS_APP_METADATA_KEY);

        String contextRoot = null;

        // prefer context root defined in application.xml over one defined in jboss-web.xml
        if (jbossAppMD != null) {
            final ModuleMetaData moduleMD = jbossAppMD.getModules().get(dep.getSimpleName());
            if (moduleMD != null) {
                final WebModuleMetaData webModuleMD = (WebModuleMetaData) moduleMD.getValue();
                contextRoot = webModuleMD.getContextRoot();
            }
        }

        if (contextRoot == null) {
            contextRoot = jbossWebMD != null ? jbossWebMD.getContextRoot() : null;
        }

        return contextRoot;
    }

Returns context root associated with webservice deployment.

If there's application.xml descriptor provided defining nested web module, then context root defined there will be
returned. Otherwise context root defined in jboss-web.xml will be returned.

@param dep webservice deployment
@param jbossWebMD jboss web meta data
@return context root

Returns context root associated with webservice deployment .


@Override
    public Class<?> classForName(String name) {
        try {
            if (classes.containsKey(name)) {
                return classes.get(name);
            }
            final Class<?> clazz = module.getClassLoader().loadClass(name);
            classes.put(name, clazz);
            return clazz;
        } catch (ClassNotFoundException | LinkageError e) {
            throw new ResourceLoadingException(e);
        }
    }

@ Override public Class < ? > classForName ( String name ) { try { if ( classes . containsKey ( name ) ) { return classes . get ( name ) ; } final Class < ? > clazz = module . getClassLoader ( ) . loadClass ( name ) ; classes . put ( name , clazz ) ; return clazz ; } catch ( ClassNotFoundException | LinkageError e ) { throw new ResourceLoadingException ( e ) ; } }

If the class name is found in additionalClasses then return it.

Otherwise the class will be loaded from the module ClassLoader

If the class name is found in additionalClasses then return it .


@Override
    public URL getResource(String name) {
        try {
            return module.getClassLoader().getResource(name);
        } catch (Exception e) {
            throw new ResourceLoadingException(e);
        }
    }

@ Override public URL getResource ( String name ) { try { return module . getClassLoader ( ) . getResource ( name ) ; } catch ( Exception e ) { throw new ResourceLoadingException ( e ) ; } }

Loads a resource from the module class loader


@Override
    public Collection<URL> getResources(String name) {
        try {
            final HashSet<URL> resources = new HashSet<URL>();
            Enumeration<URL> urls = module.getClassLoader().getResources(name);
            while (urls.hasMoreElements()) {
                resources.add(urls.nextElement());
            }
            return resources;
        } catch (Exception e) {
            throw new ResourceLoadingException(e);
        }

    }

@ Override public Collection < URL > getResources ( String name ) { try { final HashSet < URL > resources = new HashSet < URL > ( ) ; Enumeration < URL > urls = module . getClassLoader ( ) . getResources ( name ) ; while ( urls . hasMoreElements ( ) ) { resources . add ( urls . nextElement ( ) ) ; } return resources ; } catch ( Exception e ) { throw new ResourceLoadingException ( e ) ; } }

Loads resources from the module class loader


public List<Resource> list(String path) {
        try {
            final List<Resource> ret = new ArrayList<>();

            Resource res = deploymentResourceManager.getResource(path);
            if (res != null) {
                for (Resource child : res.list()) {
                    ret.add(new ServletResource(this, child));
                }
            }
            String p = path;
            if (p.startsWith("/")) {
                p = p.substring(1);
            }
            if (overlays != null) {
                for (VirtualFile overlay : overlays) {
                    VirtualFile child = overlay.getChild(p);
                    if (child.exists()) {
                        VirtualFileResource vfsResource = new VirtualFileResource(overlay.getPhysicalFile(), child, path);
                        for (Resource c : vfsResource.list()) {
                            ret.add(new ServletResource(this, c));
                        }
                    }
                }
            }
            return ret;
        } catch (IOException e) {
            throw new RuntimeException(e); //this method really should have thrown IOException
        }
    }

Lists all children of a particular path, taking overlays into account

@param path The path
@return The list of children

Lists all children of a particular path taking overlays into account


public static void popCall() {
        Map<String, EntityManager> emStack = nonTxStack.pop();
        if (emStack != null) {
            for (EntityManager entityManager : emStack.values()) {
                try {
                    if (entityManager.isOpen()) {
                        entityManager.close();
                    }
                } catch (RuntimeException safeToIgnore) {
                    if (ROOT_LOGGER.isTraceEnabled()) {
                        ROOT_LOGGER.trace("Could not close (non-transactional) container managed entity manager." +
                            "  This shouldn't impact application functionality (only read " +
                            "operations occur in non-transactional mode)", safeToIgnore);
                    }
                }
            }
        }
    }

current session bean invocation is ending, close any transactional entity managers created without a JTA
transaction.

current session bean invocation is ending close any transactional entity managers created without a JTA transaction .


public static EntityManager get(String puScopedName) {
        Map<String, EntityManager> map = nonTxStack.peek();
        if (map != null) {
            return map.get(puScopedName);
        }
        return null;
    }

public static EntityManager get ( String puScopedName ) { Map < String , EntityManager > map = nonTxStack . peek ( ) ; if ( map != null ) { return map . get ( puScopedName ) ; } return null ; }

Return the transactional entity manager for the specified scoped persistence unit name

@param puScopedName
@return


void registerCleanUpListener(TransactionSynchronizationRegistry transactionSynchronizationRegistry, JMSContext contextInstance) {
        //to avoid registration of more listeners for one context, flag in transaction is used.
        Object alreadyRegistered = transactionSynchronizationRegistry.getResource(contextInstance);
        if (alreadyRegistered == null) {
            transactionSynchronizationRegistry.registerInterposedSynchronization(new AfterCompletionSynchronization(contextInstance));
            transactionSynchronizationRegistry.putResource(contextInstance, AfterCompletionSynchronization.class.getName());
        }
    }

Closing of transaction scoped JMSContext is executed through Synchronization listener.
This method registers listener, which takes care of closing JMSContext.

@param transactionSynchronizationRegistry
@param contextInstance

Closing of transaction scoped JMSContext is executed through Synchronization listener . This method registers listener which takes care of closing JMSContext .


public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
            return; // Skip non web deployments
        }

        WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
        assert warMetaData != null;
        Map<String, WebMetaData> annotationsMetaData = warMetaData.getAnnotationsMetaData();
        if (annotationsMetaData == null) {
            annotationsMetaData = new HashMap<String, WebMetaData>();
            warMetaData.setAnnotationsMetaData(annotationsMetaData);
        }
        Map<ResourceRoot, Index> indexes = AnnotationIndexUtils.getAnnotationIndexes(deploymentUnit);

        // Process lib/*.jar
        for (final Entry<ResourceRoot, Index> entry : indexes.entrySet()) {
            final Index jarIndex = entry.getValue();
            annotationsMetaData.put(entry.getKey().getRootName(), processAnnotations(jarIndex));
        }

        Map<ModuleIdentifier, CompositeIndex> additionalModelAnnotations = deploymentUnit.getAttachment(Attachments.ADDITIONAL_ANNOTATION_INDEXES_BY_MODULE);
        if (additionalModelAnnotations != null) {
            final List<WebMetaData> additional = new ArrayList<WebMetaData>();
            for (Entry<ModuleIdentifier, CompositeIndex> entry : additionalModelAnnotations.entrySet()) {
                for(Index index : entry.getValue().getIndexes()) {
                    additional.add(processAnnotations(index));
                }
            }
            warMetaData.setAdditionalModuleAnnotationsMetadata(additional);
        }
    }

public
void
deploy
(
final
DeploymentPhaseContext
phaseContext
)
throws
DeploymentUnitProcessingException
{
final
DeploymentUnit
deploymentUnit
=
phaseContext
.
getDeploymentUnit
(
)
;
if
(
!
DeploymentTypeMarker
.
isType
(
DeploymentType
.
WAR
,
deploymentUnit
)
)
{
return
;
// Skip non web deployments
}
WarMetaData
warMetaData
=
deploymentUnit
.
getAttachment
(
WarMetaData
.
ATTACHMENT_KEY
)
;
assert
warMetaData
!=
;
Map
<
String
,
WebMetaData
>
annotationsMetaData
=
warMetaData
.
getAnnotationsMetaData
(
)
;
if
(
annotationsMetaData
==
)
{
annotationsMetaData
=
new
HashMap
<
String
,
WebMetaData
>
(
)
;
warMetaData
.
setAnnotationsMetaData
(
annotationsMetaData
)
;
}
Map
<
ResourceRoot
,
Index
>
indexes
=
AnnotationIndexUtils
.
getAnnotationIndexes
(
deploymentUnit
)
;
// Process lib/*.jar
for
(
final
Entry
<
ResourceRoot
,
Index
>
entry
:
indexes
.
entrySet
(
)
)
{
final
Index
jarIndex
=
entry
.
getValue
(
)
;
annotationsMetaData
.
put
(
entry
.
getKey
(
)
.
getRootName
(
)
,
processAnnotations
(
jarIndex
)
)
;
}
Map
<
ModuleIdentifier
,
CompositeIndex
>
additionalModelAnnotations
=
deploymentUnit
.
getAttachment
(
Attachments
.
ADDITIONAL_ANNOTATION_INDEXES_BY_MODULE
)
;
if
(
additionalModelAnnotations
!=
)
{
final
List
<
WebMetaData
>
additional
=
new
ArrayList
<
WebMetaData
>
(
)
;
for
(
Entry
<
ModuleIdentifier
,
CompositeIndex
>
entry
:
additionalModelAnnotations
.
entrySet
(
)
)
{
for
(
Index
index
:
entry
.
getValue
(
)
.
getIndexes
(
)
)
{
additional
.
add
(
processAnnotations
(
index
)
)
;
}
}
warMetaData
.
setAdditionalModuleAnnotationsMetadata
(
additional
)
;
}
}


private boolean updateServerConfig(String attributeName, String value, boolean isRevert) throws OperationFailedException, DisabledOperationException {
        final ServerConfigImpl config = (ServerConfigImpl) ServerConfigFactoryImpl.getConfig();
        try {
            if (MODIFY_WSDL_ADDRESS.equals(attributeName)) {
                final boolean modifyWSDLAddress = value != null && Boolean.parseBoolean(value);
                config.setModifySOAPAddress(modifyWSDLAddress, isRevert);
            } else if (WSDL_HOST.equals(attributeName)) {
                final String host = value != null ? value : null;
                try {
                    config.setWebServiceHost(host, isRevert);
                } catch (final UnknownHostException e) {
                    throw new OperationFailedException(e.getMessage(), e);
                }
            } else if (WSDL_PORT.equals(attributeName)) {
                final int port = value != null ? Integer.parseInt(value) : -1;
                config.setWebServicePort(port, isRevert);
            } else if (WSDL_SECURE_PORT.equals(attributeName)) {
                final int securePort = value != null ? Integer.parseInt(value) : -1;
                config.setWebServiceSecurePort(securePort, isRevert);
            } else if (WSDL_PATH_REWRITE_RULE.equals(attributeName)) {
                final String path = value != null ? value : null;
                config.setWebServicePathRewriteRule(path, isRevert);
            } else if (WSDL_URI_SCHEME.equals(attributeName)) {
                if (value == null || value.equals("http") || value.equals("https")) {
                    config.setWebServiceUriScheme(value, isRevert);
                } else {
                    throw new IllegalArgumentException(attributeName + " = " + value);
                }
            } else if (STATISTICS_ENABLED.equals(attributeName)) {
                final boolean enabled = value != null ? Boolean.parseBoolean(value) : false;
                config.setStatisticsEnabled(enabled);
            } else {
                throw new IllegalArgumentException(attributeName);
            }
        } catch (DisabledOperationException doe) {
            // the WS stack rejected the runtime update
            if (!isRevert) {
                return false;
            } else {
                throw doe;
            }
        }
        return true;
    }

Returns true if the update operation succeeds in modifying the runtime, false otherwise.

@param attributeName
@param value
@return
@throws OperationFailedException
@throws DisabledOperationException

Returns true if the update operation succeeds in modifying the runtime false otherwise .


public static boolean isAllFieldsPublic(Class c) {
        try {
            final Field[] list = c.getFields();
            for (int i = 0; i < list.length; i++)
                if (!Modifier.isPublic(list[i].getModifiers()))
                    return false;
        } catch (Exception e) {
            return false;
        }
        return true;
    }

public static boolean isAllFieldsPublic ( Class c ) { try { final Field [ ] list = c . getFields ( ) ; for ( int i = 0 ; i < list . length ; i ++ ) if ( ! Modifier . isPublic ( list [ i ] . getModifiers ( ) ) ) return false ; } catch ( Exception e ) { return false ; } return true ; }

Checks whether all the fields in the class are declared as public.

Checks whether all the fields in the class are declared as public .


protected final Endpoint newHttpEndpoint(final String endpointClass, final String endpointName, final Deployment dep) {
        if (endpointName == null) throw WSLogger.ROOT_LOGGER.nullEndpointName();
        if (endpointClass == null) throw WSLogger.ROOT_LOGGER.nullEndpointClass();

        final Endpoint endpoint = this.deploymentModelFactory.newHttpEndpoint(endpointClass);
        endpoint.setShortName(endpointName);
        endpoint.setType(endpointType);
        dep.getService().addEndpoint(endpoint);

        return endpoint;
    }

protected final Endpoint newHttpEndpoint ( final String endpointClass , final String endpointName , final Deployment dep ) { if ( endpointName == null ) throw WSLogger . ROOT_LOGGER . nullEndpointName ( ) ; if ( endpointClass == null ) throw WSLogger . ROOT_LOGGER . nullEndpointClass ( ) ; final Endpoint endpoint = this . deploymentModelFactory . newHttpEndpoint ( endpointClass ) ; endpoint . setShortName ( endpointName ) ; endpoint . setType ( endpointType ) ; dep . getService ( ) . addEndpoint ( endpoint ) ; return endpoint ; }

Creates new Http Web Service endpoint.

@param endpointClass endpoint class name
@param endpointName endpoint name
@param dep deployment
@return WS endpoint


private ArchiveDeployment newDeployment(final DeploymentUnit unit) {
        WSLogger.ROOT_LOGGER.tracef("Creating new unified WS deployment model for %s", unit);
        final ResourceRoot deploymentRoot = unit.getAttachment(Attachments.DEPLOYMENT_ROOT);
        final VirtualFile root = deploymentRoot != null ? deploymentRoot.getRoot() : null;
        final ClassLoader classLoader;
        final Module module = unit.getAttachment(Attachments.MODULE);
        if (module == null) {
            classLoader = unit.getAttachment(CLASSLOADER_KEY);
            if (classLoader == null) {
                throw WSLogger.ROOT_LOGGER.classLoaderResolutionFailed(unit);
            }
        } else {
            classLoader = module.getClassLoader();
        }

        ArchiveDeployment parentDep = null;
        if (unit.getParent() != null) {
            final Module parentModule = unit.getParent().getAttachment(Attachments.MODULE);
            if (parentModule == null) {
                throw WSLogger.ROOT_LOGGER.classLoaderResolutionFailed(deploymentRoot);
            }
            WSLogger.ROOT_LOGGER.tracef("Creating new unified WS deployment model for %s", unit.getParent());
            parentDep = this.newDeployment(null, unit.getParent().getName(), parentModule.getClassLoader(), null);
        }

        final UnifiedVirtualFile uvf = root != null ? new VirtualFileAdaptor(root) : new ResourceLoaderAdapter(classLoader);
        final ArchiveDeployment dep = this.newDeployment(parentDep, unit.getName(), classLoader, uvf);

        //add an AnnotationInfo attachment that uses composite jandex index
        dep.addAttachment(AnnotationsInfo.class, new JandexAnnotationsInfo(unit));

        return dep;
    }

Creates new Web Service deployment.

@param unit deployment unit
@return archive deployment


public static boolean isJaxrsDeployment(DeploymentUnit deploymentUnit) {
        DeploymentUnit deployment = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
        Boolean val = deployment.getAttachment(ATTACHMENT_KEY);
        return val != null && val;
    }

public static boolean isJaxrsDeployment ( DeploymentUnit deploymentUnit ) { DeploymentUnit deployment = deploymentUnit . getParent ( ) == null ? deploymentUnit : deploymentUnit . getParent ( ) ; Boolean val = deployment . getAttachment ( ATTACHMENT_KEY ) ; return val != null && val ; }

JAX-RS annotations are found in the deployment, especially if it's an EAR one)

JAX - RS annotations are found in the deployment especially if it s an EAR one )


public void setNextTimeout(Date next) {
        if(next == null) {
            setTimerState(TimerState.EXPIRED, null);
        }
        this.nextExpiration = next;
    }

public void setNextTimeout ( Date next ) { if ( next == null ) { setTimerState ( TimerState . EXPIRED , null ) ; } this . nextExpiration = next ; }

Sets the next timeout of this timer

@param next The next scheduled timeout of this timer


protected void setTimerState(TimerState state, Thread thread) {
        assert ((state == TimerState.IN_TIMEOUT || state == TimerState.RETRY_TIMEOUT) && thread != null) || thread == null : "Invalid to set timer state " + state + " with executing Thread " + thread;
        this.timerState = state;
        this.executingThread = thread;
    }

protected
void
setTimerState
(
TimerState
state
,
Thread
thread
)
{
assert
(
(
state
==
TimerState
.
IN_TIMEOUT
||
state
==
TimerState
.
RETRY_TIMEOUT
)
&&
thread
!=
)
||
thread
==
:
"Invalid to set timer state "
+
state
+
" with executing Thread "
+
thread
;
this
.
timerState
=
state
;
this
.
executingThread
=
thread
;
}

Sets the state and timer task executing thread of this timer

@param state The state of this timer
@param thread The executing thread which is processing the timeout task


public void merge(final List<ResteasyDeploymentData> deploymentData) throws DeploymentUnitProcessingException {
        for (ResteasyDeploymentData data : deploymentData) {
            scannedApplicationClasses.addAll(data.getScannedApplicationClasses());
            if (scanResources) {
                scannedResourceClasses.addAll(data.getScannedResourceClasses());
                scannedJndiComponentResources.addAll(data.getScannedJndiComponentResources());
            }
            if (scanProviders) {
                scannedProviderClasses.addAll(data.getScannedProviderClasses());
            }
        }
    }

public void merge ( final List < ResteasyDeploymentData > deploymentData ) throws DeploymentUnitProcessingException { for ( ResteasyDeploymentData data : deploymentData ) { scannedApplicationClasses . addAll ( data . getScannedApplicationClasses ( ) ) ; if ( scanResources ) { scannedResourceClasses . addAll ( data . getScannedResourceClasses ( ) ) ; scannedJndiComponentResources . addAll ( data . getScannedJndiComponentResources ( ) ) ; } if ( scanProviders ) { scannedProviderClasses . addAll ( data . getScannedProviderClasses ( ) ) ; } } }

Merges a list of additional JAX-RS deployment data with this lot of deployment data.

@param deploymentData

Merges a list of additional JAX - RS deployment data with this lot of deployment data .


public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);

        final ModuleLoader moduleLoader = Module.getBootModuleLoader();

        //add jboss-invocation classes needed by the proxies
        ModuleDependency invocation = new ModuleDependency(moduleLoader, JBOSS_INVOCATION_ID, false, false, false, false);
        invocation.addImportFilter(PathFilters.is("org/jboss/invocation/proxy/classloading"), true);
        invocation.addImportFilter(PathFilters.acceptAll(), false);
        moduleSpecification.addSystemDependency(invocation);

        ModuleDependency ee = new ModuleDependency(moduleLoader, JBOSS_AS_EE, false, false, false, false);
        ee.addImportFilter(PathFilters.is("org/jboss/as/ee/component/serialization"), true);
        ee.addImportFilter(PathFilters.is("org/jboss/as/ee/concurrent"), true);
        ee.addImportFilter(PathFilters.is("org/jboss/as/ee/concurrent/handle"), true);
        ee.addImportFilter(PathFilters.acceptAll(), false);
        moduleSpecification.addSystemDependency(ee);

        // add dep for naming permission
        moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, ModuleIdentifier.create(WILDFLY_NAMING), false, false, false, false));

        //we always add all Java EE API modules, as the platform spec requires them to always be available
        //we do not just add the javaee.api module, as this breaks excludes

        for (final ModuleIdentifier moduleIdentifier : JAVA_EE_API_MODULES) {
            moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, moduleIdentifier, true, false, true, false));
        }
    }

Add the EE APIs as a dependency to all deployments

@param phaseContext the deployment unit context
@throws DeploymentUnitProcessingException


protected void addRemoteTransactionsDependency() {
        this.getConfigurators().add(new ComponentConfigurator() {
            @Override
            public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration componentConfiguration) throws DeploymentUnitProcessingException {
                if (this.hasRemoteView((EJBComponentDescription) description)) {
                    // add a dependency on local transaction service
                    componentConfiguration.getCreateDependencies().add((sb, cs) -> sb.requires(TxnServices.JBOSS_TXN_REMOTE_TRANSACTION_SERVICE));
                }
            }

            /**
             * Returns true if the passed EJB component description has at least one remote view
             * @param ejbComponentDescription
             * @return
             */
            private boolean hasRemoteView(final EJBComponentDescription ejbComponentDescription) {
                final Set<ViewDescription> views = ejbComponentDescription.getViews();
                for (final ViewDescription view : views) {
                    if (!(view instanceof EJBViewDescription)) {
                        continue;
                    }
                    final MethodIntf viewType = ((EJBViewDescription) view).getMethodIntf();
                    if (viewType == MethodIntf.REMOTE || viewType == MethodIntf.HOME) {
                        return true;
                    }
                }
                return false;
            }
        });
    }

Adds a dependency for the ComponentConfiguration on the remote transaction service if the EJB exposes at least one remote view


public Set<InterceptorDescription> getAllContainerInterceptors() {
        if (this.allContainerInterceptors == null) {
            this.allContainerInterceptors = new HashSet<InterceptorDescription>();
            this.allContainerInterceptors.addAll(this.classLevelContainerInterceptors);
            if (!this.excludeDefaultContainerInterceptors) {
                this.allContainerInterceptors.addAll(this.defaultContainerInterceptors);
            }
            for (List<InterceptorDescription> interceptors : this.methodLevelContainerInterceptors.values()) {
                this.allContainerInterceptors.addAll(interceptors);
            }
        }
        return this.allContainerInterceptors;
    }

public Set < InterceptorDescription > getAllContainerInterceptors ( ) { if ( this . allContainerInterceptors == null ) { this . allContainerInterceptors = new HashSet < InterceptorDescription > ( ) ; this . allContainerInterceptors . addAll ( this . classLevelContainerInterceptors ) ; if ( ! this . excludeDefaultContainerInterceptors ) { this . allContainerInterceptors . addAll ( this . defaultContainerInterceptors ) ; } for ( List < InterceptorDescription > interceptors : this . methodLevelContainerInterceptors . values ( ) ) { this . allContainerInterceptors . addAll ( interceptors ) ; } } return this . allContainerInterceptors ; }

Returns a combined map of class and method level container interceptors