private static List<ServiceName> getServerConfigDependencies(OperationContext context, boolean appclient) {
        final List<ServiceName> serviceNames = new ArrayList<ServiceName>();
        final Resource subsystemResource = context.readResourceFromRoot(PathAddress.pathAddress(WSExtension.SUBSYSTEM_PATH), false);
        readConfigServiceNames(serviceNames, subsystemResource, Constants.CLIENT_CONFIG);
        readConfigServiceNames(serviceNames, subsystemResource, Constants.ENDPOINT_CONFIG);
        if (!appclient) {
            serviceNames.add(CommonWebServer.SERVICE_NAME);
        }
        return serviceNames;
    }

private static List < ServiceName > getServerConfigDependencies ( OperationContext context , boolean appclient ) { final List < ServiceName > serviceNames = new ArrayList < ServiceName > ( ) ; final Resource subsystemResource = context . readResourceFromRoot ( PathAddress . pathAddress ( WSExtension . SUBSYSTEM_PATH ) , false ) ; readConfigServiceNames ( serviceNames , subsystemResource , Constants . CLIENT_CONFIG ) ; readConfigServiceNames ( serviceNames , subsystemResource , Constants . ENDPOINT_CONFIG ) ; if ( ! appclient ) { serviceNames . add ( CommonWebServer . SERVICE_NAME ) ; } return serviceNames ; }

Process the model to figure out the name of the services the server config service has to depend on


private void decReadLockCount() {
        Integer current = readLockCount.get();
        int next;
        assert current != null : "can't decrease, readLockCount is not set";
        next = current.intValue() - 1;
        if (next == 0)
            readLockCount.remove();
        else
            readLockCount.set(new Integer(next));
    }

Decrements the read lock count held by the thread


private void incReadLockCount() {
        Integer current = readLockCount.get();
        int next;
        if (current == null)
            next = 1;
        else
            next = current.intValue() + 1;
        readLockCount.set(new Integer(next));
    }

private void incReadLockCount ( ) { Integer current = readLockCount . get ( ) ; int next ; if ( current == null ) next = 1 ; else next = current . intValue ( ) + 1 ; readLockCount . set ( new Integer ( next ) ) ; }

Increments the read lock count held by the thread


public synchronized <S extends Service> void addService(Class<S> clazz, S service) {
        for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
            bda.getServices().add(clazz,service);
        }
    }

public synchronized < S extends Service > void addService ( Class < S > clazz , S service ) { for ( BeanDeploymentArchiveImpl bda : beanDeploymentArchives ) { bda . getServices ( ) . add ( clazz , service ) ; } }

Adds a service to all bean deployment archives in the module
@param clazz The service type
@param service The service
@param <S> The service type


public void handleRestorationCalculation() {
        if(nextExpiration == null) {
            return;
        }
        //next expiration in the future, we don't care
        if(nextExpiration.getTime() >= System.currentTimeMillis()) {
            return;
        }
        //just set the next expiration to 1ms in the past
        //this means it will run to catch up the missed expiration
        //and then the next calculated expiration will be in the future
        nextExpiration = new Date(System.currentTimeMillis() - 1);
    }

Makes sure that the timer is only run once after being restored.

Makes sure that the timer is only run once after being restored .


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();

        if (JPADeploymentMarker.isJPADeployment(deploymentUnit)) {
            addSearchDependency(moduleSpecification, moduleLoader, deploymentUnit);
        }
    }

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 ( ) ; if ( JPADeploymentMarker . isJPADeployment ( deploymentUnit ) ) { addSearchDependency ( moduleSpecification , moduleLoader , deploymentUnit ) ; } }

if set to `auto`, will behave like not having set the property

if set to auto will behave like not having set the property


private void makeTopLevelBdasVisibleFromStaticModules() {
        for (BeanDeploymentArchiveImpl bda : beanDeploymentArchives) {
            if (bda.getBeanArchiveType().equals(BeanDeploymentArchiveImpl.BeanArchiveType.EXTERNAL) || bda.getBeanArchiveType().equals(BeanDeploymentArchiveImpl.BeanArchiveType.SYNTHETIC)) {
                for (BeanDeploymentArchiveImpl topLevelBda : rootBeanDeploymentModule.getBeanDeploymentArchives()) {
                    bda.addBeanDeploymentArchive(topLevelBda);
                }
            }
        }
    }

Adds additional edges to the accessibility graph that allow static CDI-enabled modules to inject beans from top-level deployment units

Adds additional edges to the accessibility graph that allow static CDI - enabled modules to inject beans from top - level deployment units


JSEArchiveMetaData create(final Deployment dep) {
        if (WSLogger.ROOT_LOGGER.isTraceEnabled()) {
            WSLogger.ROOT_LOGGER.tracef("Creating JBoss agnostic meta data for POJO webservice deployment: %s", dep.getSimpleName());
        }
        final JBossWebMetaData jbossWebMD = WSHelper.getRequiredAttachment(dep, JBossWebMetaData.class);
        final DeploymentUnit unit = WSHelper.getRequiredAttachment(dep, DeploymentUnit.class);
        final List<POJOEndpoint> pojoEndpoints = getPojoEndpoints(unit);
        final JSEArchiveMetaData.Builder builder = new JSEArchiveMetaData.Builder();

        // set context root
        final String contextRoot = getContextRoot(dep, jbossWebMD);
        builder.setContextRoot(contextRoot);
        WSLogger.ROOT_LOGGER.tracef("Setting context root: %s", contextRoot);

        // set servlet url patterns mappings
        final Map<String, String> servletMappings = getServletUrlPatternsMappings(jbossWebMD, pojoEndpoints);
        builder.setServletMappings(servletMappings);

        // set servlet class names mappings
        final Map<String, String> servletClassNamesMappings = getServletClassMappings(jbossWebMD, pojoEndpoints);
        builder.setServletClassNames(servletClassNamesMappings);

        // set security domain
        final String securityDomain = jbossWebMD.getSecurityDomain();
        builder.setSecurityDomain(securityDomain);

        // set wsdl location resolver
        final JBossWebservicesMetaData jbossWebservicesMD = WSHelper.getOptionalAttachment(dep, JBossWebservicesMetaData.class);
        if (jbossWebservicesMD != null) {
            final PublishLocationAdapter resolver = new PublishLocationAdapterImpl(jbossWebservicesMD.getWebserviceDescriptions());
            builder.setPublishLocationAdapter(resolver);
        }

        // set security meta data
        final List<JSESecurityMetaData> jseSecurityMDs = getSecurityMetaData(jbossWebMD.getSecurityConstraints());
        builder.setSecurityMetaData(jseSecurityMDs);

        // set config name and file
        setConfigNameAndFile(builder, jbossWebMD, jbossWebservicesMD);

        return builder.build();
    }

Builds universal JSE meta data model that is AS agnostic.

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

Builds universal JSE meta data model that is AS agnostic .


private void setConfigNameAndFile(final JSEArchiveMetaData.Builder builder, final JBossWebMetaData jbossWebMD, final JBossWebservicesMetaData jbossWebservicesMD) {
        if (jbossWebservicesMD != null) {
           if (jbossWebservicesMD.getConfigName() != null) {
              final String configName = jbossWebservicesMD.getConfigName();
              builder.setConfigName(configName);
              WSLogger.ROOT_LOGGER.tracef("Setting config name: %s", configName);
              final String configFile = jbossWebservicesMD.getConfigFile();
              builder.setConfigFile(configFile);
               WSLogger.ROOT_LOGGER.tracef("Setting config file: %s", configFile);

              // ensure higher priority against web.xml context parameters
              return;
           }
        }

        final List<ParamValueMetaData> contextParams = jbossWebMD.getContextParams();
        if (contextParams != null) {
            for (final ParamValueMetaData contextParam : contextParams) {
                if (WSConstants.JBOSSWS_CONFIG_NAME.equals(contextParam.getParamName())) {
                    final String configName = contextParam.getParamValue();
                    builder.setConfigName(configName);
                    WSLogger.ROOT_LOGGER.tracef("Setting config name: %s", configName);
                }
                if (WSConstants.JBOSSWS_CONFIG_FILE.equals(contextParam.getParamName())) {
                    final String configFile = contextParam.getParamValue();
                    builder.setConfigFile(configFile);
                    WSLogger.ROOT_LOGGER.tracef("Setting config file: %s", configFile);
                }
            }
        }
    }

Sets config name and config file.

@param builder universal JSE meta data model builder
@param jbossWebMD jboss web meta data


private List<JSESecurityMetaData> getSecurityMetaData(final List<SecurityConstraintMetaData> securityConstraintsMD) {
        final List<JSESecurityMetaData> jseSecurityMDs = new LinkedList<JSESecurityMetaData>();

        if (securityConstraintsMD != null) {
            for (final SecurityConstraintMetaData securityConstraintMD : securityConstraintsMD) {
                final JSESecurityMetaData.Builder jseSecurityMDBuilder = new JSESecurityMetaData.Builder();

                // transport guarantee
                jseSecurityMDBuilder.setTransportGuarantee(securityConstraintMD.getTransportGuarantee().name());

                // web resources
                for (final WebResourceCollectionMetaData webResourceMD : securityConstraintMD.getResourceCollections()) {
                    jseSecurityMDBuilder.addWebResource(webResourceMD.getName(), webResourceMD.getUrlPatterns());
                }

                jseSecurityMDs.add(jseSecurityMDBuilder.build());
            }
        }

        return jseSecurityMDs;
    }

private
List
<
JSESecurityMetaData
>
getSecurityMetaData
(
final
List
<
SecurityConstraintMetaData
>
securityConstraintsMD
)
{
final
List
<
JSESecurityMetaData
>
jseSecurityMDs
=
new
LinkedList
<
JSESecurityMetaData
>
(
)
;
if
(
securityConstraintsMD
!=
)
{
for
(
final
SecurityConstraintMetaData
securityConstraintMD
:
securityConstraintsMD
)
{
final
JSESecurityMetaData
.
Builder
jseSecurityMDBuilder
=
new
JSESecurityMetaData
.
Builder
(
)
;
// transport guarantee
jseSecurityMDBuilder
.
setTransportGuarantee
(
securityConstraintMD
.
getTransportGuarantee
(
)
.
name
(
)
)
;
// web resources
for
(
final
WebResourceCollectionMetaData
webResourceMD
:
securityConstraintMD
.
getResourceCollections
(
)
)
{
jseSecurityMDBuilder
.
addWebResource
(
webResourceMD
.
getName
(
)
,
webResourceMD
.
getUrlPatterns
(
)
)
;
}
jseSecurityMDs
.
add
(
jseSecurityMDBuilder
.
build
(
)
)
;
}
}
return
jseSecurityMDs
;
}

Builds security meta data.

@param securityConstraintsMD security constraints meta data
@return universal JSE security meta data model


private Map<String, String> getServletUrlPatternsMappings(final JBossWebMetaData jbossWebMD, final List<POJOEndpoint> pojoEndpoints) {
        final Map<String, String> mappings = new HashMap<String, String>();
        final List<ServletMappingMetaData> servletMappings = WebMetaDataHelper.getServletMappings(jbossWebMD);

        for (final POJOEndpoint pojoEndpoint : pojoEndpoints) {
            mappings.put(pojoEndpoint.getName(), pojoEndpoint.getUrlPattern());
            if (!pojoEndpoint.isDeclared()) {
                final String endpointName = pojoEndpoint.getName();
                final List<String> urlPatterns = WebMetaDataHelper.getUrlPatterns(pojoEndpoint.getUrlPattern());
                WebMetaDataHelper.newServletMapping(endpointName, urlPatterns, servletMappings);
            }
        }

        return mappings;
    }

private Map < String , String > getServletUrlPatternsMappings ( final JBossWebMetaData jbossWebMD , final List < POJOEndpoint > pojoEndpoints ) { final Map < String , String > mappings = new HashMap < String , String > ( ) ; final List < ServletMappingMetaData > servletMappings = WebMetaDataHelper . getServletMappings ( jbossWebMD ) ; for ( final POJOEndpoint pojoEndpoint : pojoEndpoints ) { mappings . put ( pojoEndpoint . getName ( ) , pojoEndpoint . getUrlPattern ( ) ) ; if ( ! pojoEndpoint . isDeclared ( ) ) { final String endpointName = pojoEndpoint . getName ( ) ; final List < String > urlPatterns = WebMetaDataHelper . getUrlPatterns ( pojoEndpoint . getUrlPattern ( ) ) ; WebMetaDataHelper . newServletMapping ( endpointName , urlPatterns , servletMappings ) ; } } return mappings ; }

Returns servlet name to url pattern mappings.

@param jbossWebMD jboss web meta data
@return servlet name to url pattern mappings

Returns servlet name to url pattern mappings .


private Map<String, String> getServletClassMappings(final JBossWebMetaData jbossWebMD, final List<POJOEndpoint> pojoEndpoints) {
        final Map<String, String> mappings = new HashMap<String, String>();
        final JBossServletsMetaData servlets = WebMetaDataHelper.getServlets(jbossWebMD);

        for (final POJOEndpoint pojoEndpoint : pojoEndpoints) {
            final String pojoName = pojoEndpoint.getName();
            final String pojoClassName = pojoEndpoint.getClassName();
            mappings.put(pojoName, pojoClassName);
            if (!pojoEndpoint.isDeclared()) {
                final String endpointName = pojoEndpoint.getName();
                final String endpointClassName = pojoEndpoint.getClassName();
                WebMetaDataHelper.newServlet(endpointName, endpointClassName, servlets);
            }
        }

        return mappings;
    }

private Map < String , String > getServletClassMappings ( final JBossWebMetaData jbossWebMD , final List < POJOEndpoint > pojoEndpoints ) { final Map < String , String > mappings = new HashMap < String , String > ( ) ; final JBossServletsMetaData servlets = WebMetaDataHelper . getServlets ( jbossWebMD ) ; for ( final POJOEndpoint pojoEndpoint : pojoEndpoints ) { final String pojoName = pojoEndpoint . getName ( ) ; final String pojoClassName = pojoEndpoint . getClassName ( ) ; mappings . put ( pojoName , pojoClassName ) ; if ( ! pojoEndpoint . isDeclared ( ) ) { final String endpointName = pojoEndpoint . getName ( ) ; final String endpointClassName = pojoEndpoint . getClassName ( ) ; WebMetaDataHelper . newServlet ( endpointName , endpointClassName , servlets ) ; } } return mappings ; }

Returns servlet name to servlet class mappings.

@param jbossWebMD jboss web meta data
@return servlet name to servlet mappings

Returns servlet name to servlet class mappings .


private void resolve() {
        if (!resolved) {
            synchronized (this) {
                if (!resolved) {

                    final Set<ViewDescription> views = getViews();

                    final Set<EJBViewDescription> ejbsForViewName = new HashSet<EJBViewDescription>();
                    for (final ViewDescription view : views) {
                        if (view instanceof EJBViewDescription) {
                            final MethodIntf viewType = ((EJBViewDescription) view).getMethodIntf();
                            // @EJB injection *shouldn't* consider the @WebService endpoint view or MDBs
                            if (viewType == MethodIntf.SERVICE_ENDPOINT || viewType == MethodIntf.MESSAGE_ENDPOINT) {
                                continue;
                            }
                            ejbsForViewName.add((EJBViewDescription) view);
                        }
                    }

                    if (ejbsForViewName.isEmpty()) {
                        if (beanName == null) {
                            error = EjbLogger.ROOT_LOGGER.ejbNotFound(typeName, bindingName);
                        } else {
                            error = EjbLogger.ROOT_LOGGER.ejbNotFound(typeName, beanName, bindingName);
                        }
                    } else if (ejbsForViewName.size() > 1) {
                        if (beanName == null) {
                            error = EjbLogger.ROOT_LOGGER.moreThanOneEjbFound(typeName, bindingName, ejbsForViewName);
                        } else {
                            error = EjbLogger.ROOT_LOGGER.moreThanOneEjbFound(typeName, beanName, bindingName, ejbsForViewName);
                        }
                    } else {
                        final EJBViewDescription description = ejbsForViewName.iterator().next();
                        final EJBViewDescription ejbViewDescription = (EJBViewDescription) description;
                        //for remote interfaces we do not want to use a normal binding
                        //we need to bind the remote proxy factory into JNDI instead to get the correct behaviour

                        if (ejbViewDescription.getMethodIntf() == MethodIntf.REMOTE || ejbViewDescription.getMethodIntf() == MethodIntf.HOME) {
                            final EJBComponentDescription componentDescription = (EJBComponentDescription) description.getComponentDescription();
                            final EEModuleDescription moduleDescription = componentDescription.getModuleDescription();
                            final String earApplicationName = moduleDescription.getEarApplicationName();
                            final Value<ClassLoader> viewClassLoader = new Value<ClassLoader>() {
                                @Override
                                public ClassLoader getValue() throws IllegalStateException, IllegalArgumentException {
                                    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
                                    return module != null ? module.getClassLoader() : null;
                                }
                            };
                            remoteFactory = new RemoteViewManagedReferenceFactory(earApplicationName, moduleDescription.getModuleName(), moduleDescription.getDistinctName(), componentDescription.getComponentName(), description.getViewClassName(), componentDescription.isStateful(), viewClassLoader, appclient);
                        }
                        final ServiceName serviceName = description.getServiceName();
                        resolvedViewName = serviceName;
                    }
                    resolved = true;
                }
            }
        }
    }

Checks if this ejb injection has been resolved yet, and if not resolves it.

Checks if this ejb injection has been resolved yet and if not resolves it .


private static Set<String> getAvailableConnectors(final OperationContext context,final ModelNode operation) throws OperationFailedException{
        PathAddress address = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));
        PathAddress active = MessagingServices.getActiveMQServerPathAddress(address);
        Set<String> availableConnectors = new HashSet<String>();

        Resource subsystemResource = context.readResourceFromRoot(active.getParent(), false);
        availableConnectors.addAll(subsystemResource.getChildrenNames(CommonAttributes.REMOTE_CONNECTOR));

        Resource activeMQServerResource = context.readResourceFromRoot(active, false);
        availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.HTTP_CONNECTOR));
        availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.IN_VM_CONNECTOR));
        availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.REMOTE_CONNECTOR));
        availableConnectors.addAll(activeMQServerResource.getChildrenNames(CommonAttributes.CONNECTOR));
        return availableConnectors;
    }

private static Set < String > getAvailableConnectors ( final OperationContext context , final ModelNode operation ) throws OperationFailedException { PathAddress address = PathAddress . pathAddress ( operation . get ( ModelDescriptionConstants . OP_ADDR ) ) ; PathAddress active = MessagingServices . getActiveMQServerPathAddress ( address ) ; Set < String > availableConnectors = new HashSet < String > ( ) ; Resource subsystemResource = context . readResourceFromRoot ( active . getParent ( ) , false ) ; availableConnectors . addAll ( subsystemResource . getChildrenNames ( CommonAttributes . REMOTE_CONNECTOR ) ) ; Resource activeMQServerResource = context . readResourceFromRoot ( active , false ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . HTTP_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . IN_VM_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . REMOTE_CONNECTOR ) ) ; availableConnectors . addAll ( activeMQServerResource . getChildrenNames ( CommonAttributes . CONNECTOR ) ) ; return availableConnectors ; }


static void parseCoreEnvironmentElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {

        final int count = reader.getAttributeCount();
        for (int i = 0; i < count; i++) {
            requireNoNamespaceAttribute(reader, i);
            final String value = reader.getAttributeValue(i);
            final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
            switch (attribute) {
                case NODE_IDENTIFIER:
                    TransactionSubsystemRootResourceDefinition.NODE_IDENTIFIER.parseAndSetParameter(value, operation, reader);
                    break;
                case PATH:
                case RELATIVE_TO:
                    throw TransactionLogger.ROOT_LOGGER.unsupportedAttribute(attribute.getLocalName(), reader.getLocation());
                default:
                    throw unexpectedAttribute(reader, i);
            }
        }
        // elements
        final EnumSet<Element> required = EnumSet.of(Element.PROCESS_ID);
        final EnumSet<Element> encountered = EnumSet.noneOf(Element.class);
        while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
            final Element element = Element.forName(reader.getLocalName());
            required.remove(element);
            switch (element) {
                case PROCESS_ID: {
                    if (!encountered.add(element)) {
                        throw duplicateNamedElement(reader, reader.getLocalName());
                    }
                    parseProcessIdEnvironmentElement(reader, operation);
                    break;
                }
                default:
                    throw unexpectedElement(reader);
            }
        }
        if (!required.isEmpty()) {
            throw missingRequiredElement(reader, required);
        }
    }

Handle the core-environment element and children

@param reader
@return ModelNode for the core-environment
@throws javax.xml.stream.XMLStreamException

Handle the core - environment element and children


static void parseProcessIdEnvironmentElement(XMLExtendedStreamReader reader, ModelNode coreEnvironmentAdd) throws XMLStreamException {
        // no attributes
        if (reader.getAttributeCount() > 0) {
            throw unexpectedAttribute(reader, 0);
        }

        // elements
        boolean encountered = false;
        while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
            final Element element = Element.forName(reader.getLocalName());
            switch (element) {
                case UUID:
                    if (encountered) {
                        throw unexpectedElement(reader);
                    }
                    encountered = true;
                    if (reader.getAttributeCount() > 0) {
                        throw unexpectedAttribute(reader, 0);
                    }
                    coreEnvironmentAdd.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName()).set(true);
                    requireNoContent(reader);
                    break;
                case SOCKET: {
                    if (encountered) {
                        throw unexpectedElement(reader);
                    }
                    encountered = true;
                    parseSocketProcessIdElement(reader, coreEnvironmentAdd);
                    break;
                }
                default:
                    throw unexpectedElement(reader);
            }
        }

        if (!encountered) {
            throw missingOneOf(reader, EnumSet.of(Element.UUID, Element.SOCKET));
        }
    }

Handle the process-id child elements

@param reader
@param coreEnvironmentAdd
@return
@throws javax.xml.stream.XMLStreamException


public static PathAddress getPathAddress(ModelNode operation) {
        return PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
    }

public static PathAddress getPathAddress ( ModelNode operation ) { return PathAddress . pathAddress ( operation . require ( ModelDescriptionConstants . OP_ADDR ) ) ; }

Returns the address of the specified operation
@param operation an operation
@return a path address


public static void setPathAddress(ModelNode operation, PathAddress address) {
        operation.get(ModelDescriptionConstants.OP_ADDR).set(address.toModelNode());
    }

public static void setPathAddress ( ModelNode operation , PathAddress address ) { operation . get ( ModelDescriptionConstants . OP_ADDR ) . set ( address . toModelNode ( ) ) ; }

Sets the address of the specified operation.
@param operation an operation
@param address a path address

Sets the address of the specified operation .


public static ModelNode getAttributeValue(ModelNode operation) {
        return operation.hasDefined(ModelDescriptionConstants.VALUE) ? operation.get(ModelDescriptionConstants.VALUE) : new ModelNode();
    }

public static ModelNode getAttributeValue ( ModelNode operation ) { return operation . hasDefined ( ModelDescriptionConstants . VALUE ) ? operation . get ( ModelDescriptionConstants . VALUE ) : new ModelNode ( ) ; }

Returns the attribute value of the specified operation
@param operation an operation
@return an attribute value


public static boolean isIncludeDefaults(ModelNode operation) {
        return operation.hasDefined(ModelDescriptionConstants.INCLUDE_DEFAULTS) ? operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).asBoolean() : true;
    }

public static boolean isIncludeDefaults ( ModelNode operation ) { return operation . hasDefined ( ModelDescriptionConstants . INCLUDE_DEFAULTS ) ? operation . get ( ModelDescriptionConstants . INCLUDE_DEFAULTS ) . asBoolean ( ) : true ; }

Indicates whether or not this operation expects to include default values.
@param operation an operation
@return true, if default values are expected, false otherwise.

Indicates whether or not this operation expects to include default values .


public static ModelNode createCompositeOperation(List<ModelNode> operations) {
        ModelNode operation = Util.createOperation(ModelDescriptionConstants.COMPOSITE, PathAddress.EMPTY_ADDRESS);
        ModelNode steps = operation.get(ModelDescriptionConstants.STEPS);
        for (ModelNode step: operations) {
            steps.add(step);
        }
        return operation;
    }

public static ModelNode createCompositeOperation ( List < ModelNode > operations ) { ModelNode operation = Util . createOperation ( ModelDescriptionConstants . COMPOSITE , PathAddress . EMPTY_ADDRESS ) ; ModelNode steps = operation . get ( ModelDescriptionConstants . STEPS ) ; for ( ModelNode step : operations ) { steps . add ( step ) ; } return operation ; }

Creates a composite operation using the specified operation steps.
@param operations steps
@return a composite operation

Creates a composite operation using the specified operation steps .


public static ModelNode createAddOperation(PathAddress address, Map<Attribute, ModelNode> parameters) {
        ModelNode operation = Util.createAddOperation(address);
        for (Map.Entry<Attribute, ModelNode> entry : parameters.entrySet()) {
            operation.get(entry.getKey().getName()).set(entry.getValue());
        }
        return operation;
    }

public static ModelNode createAddOperation ( PathAddress address , Map < Attribute , ModelNode > parameters ) { ModelNode operation = Util . createAddOperation ( address ) ; for ( Map . Entry < Attribute , ModelNode > entry : parameters . entrySet ( ) ) { operation . get ( entry . getKey ( ) . getName ( ) ) . set ( entry . getValue ( ) ) ; } return operation ; }

Creates an add operation using the specified address and parameters
@param address a path address
@param parameters a map of values per attribute
@return an add operation


public static ModelNode createAddOperation(PathAddress address, int index) {
        return createAddOperation(address, index, Collections.emptyMap());
    }

public static ModelNode createAddOperation ( PathAddress address , int index ) { return createAddOperation ( address , index , Collections . emptyMap ( ) ) ; }

Creates an indexed add operation using the specified address and index
@param address a path address
@param index
@return an add operation


public static ModelNode createReadAttributeOperation(PathAddress address, Attribute attribute) {
        return createAttributeOperation(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION, address, attribute);
    }

public static ModelNode createReadAttributeOperation ( PathAddress address , Attribute attribute ) { return createAttributeOperation ( ModelDescriptionConstants . READ_ATTRIBUTE_OPERATION , address , attribute ) ; }

Creates a read-attribute operation using the specified address and name.
@param address a resource path
@param attribute an attribute
@return a read-attribute operation

Creates a read - attribute operation using the specified address and name .


public static ModelNode createWriteAttributeOperation(PathAddress address, Attribute attribute, ModelNode value) {
        ModelNode operation = createAttributeOperation(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, address, attribute);
        operation.get(ModelDescriptionConstants.VALUE).set(value);
        return operation;
    }

public static ModelNode createWriteAttributeOperation ( PathAddress address , Attribute attribute , ModelNode value ) { ModelNode operation = createAttributeOperation ( ModelDescriptionConstants . WRITE_ATTRIBUTE_OPERATION , address , attribute ) ; operation . get ( ModelDescriptionConstants . VALUE ) . set ( value ) ; return operation ; }

Creates a write-attribute operation using the specified address, name and value.
@param address a resource path
@param attribute an attribute
@param value an attribute value
@return a write-attribute operation

Creates a write - attribute operation using the specified address name and value .


public static ModelNode createUndefineAttributeOperation(PathAddress address, Attribute attribute) {
        return createAttributeOperation(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, address, attribute);
    }

public static ModelNode createUndefineAttributeOperation ( PathAddress address , Attribute attribute ) { return createAttributeOperation ( ModelDescriptionConstants . UNDEFINE_ATTRIBUTE_OPERATION , address , attribute ) ; }

Creates an undefine-attribute operation using the specified address and name.
@param address a resource path
@param attribute an attribute
@return an undefine-attribute operation

Creates an undefine - attribute operation using the specified address and name .


public T getValue() throws IllegalStateException {
        final Context context = contextValue.getValue();
        try {
            return (T)context.lookup(contextName);
        } catch (NamingException e) {
            throw NamingLogger.ROOT_LOGGER.entryNotRegistered(e, contextName, context);
        }
    }

public T getValue ( ) throws IllegalStateException { final Context context = contextValue . getValue ( ) ; try { return ( T ) context . lookup ( contextName ) ; } catch ( NamingException e ) { throw NamingLogger . ROOT_LOGGER . entryNotRegistered ( e , contextName , context ) ; } }

Lookup the value from the naming context.

@return the injected value if present, the value retrieved from the context if not.
@throws IllegalStateException The name is not found in the context when called

Lookup the value from the naming context .


public static synchronized void addUrlContextFactory(final String scheme, ObjectFactory factory) {
        Map<String, ObjectFactory> factories = new HashMap<String, ObjectFactory>(urlContextFactories);
        factories.put(scheme, factory);
        urlContextFactories = Collections.unmodifiableMap(factories);
    }

public static synchronized void addUrlContextFactory ( final String scheme , ObjectFactory factory ) { Map < String , ObjectFactory > factories = new HashMap < String , ObjectFactory > ( urlContextFactories ) ; factories . put ( scheme , factory ) ; urlContextFactories = Collections . unmodifiableMap ( factories ) ; }

Add an ObjectFactory to handle requests for a specific URL scheme.
@param scheme The URL scheme to handle.
@param factory The ObjectFactory that can handle the requests.

Add an ObjectFactory to handle requests for a specific URL scheme .


public static synchronized void removeUrlContextFactory(final String scheme, ObjectFactory factory) {
        Map<String, ObjectFactory> factories = new HashMap<String, ObjectFactory>(urlContextFactories);

        ObjectFactory f = factories.get(scheme);
        if (f == factory) {
            factories.remove(scheme);
            urlContextFactories = Collections.unmodifiableMap(factories);
            return;
        } else {
            throw new IllegalArgumentException();
        }
    }

public static synchronized void removeUrlContextFactory ( final String scheme , ObjectFactory factory ) { Map < String , ObjectFactory > factories = new HashMap < String , ObjectFactory > ( urlContextFactories ) ; ObjectFactory f = factories . get ( scheme ) ; if ( f == factory ) { factories . remove ( scheme ) ; urlContextFactories = Collections . unmodifiableMap ( factories ) ; return ; } else { throw new IllegalArgumentException ( ) ; } }

Remove an ObjectFactory from the map of registered ones. To make sure that not anybody can remove an
ObjectFactory both the scheme as well as the actual object factory itself need to be supplied. So you
can only remove the factory if you have the factory object.
@param scheme The URL scheme for which the handler is registered.
@param factory The factory object associated with the scheme
@throws IllegalArgumentException if the requested scheme/factory combination is not registered.

Remove an ObjectFactory from the map of registered ones . To make sure that not anybody can remove an ObjectFactory both the scheme as well as the actual object factory itself need to be supplied . So you can only remove the factory if you have the factory object .


private List<ValidationProvider<?>> loadProviders(ClassLoader classLoader) {
        @SuppressWarnings("rawtypes")
        Iterator<ValidationProvider> providerIterator = ServiceLoader.load(ValidationProvider.class, classLoader).iterator();
        LinkedList<ValidationProvider<?>> providers = new LinkedList<ValidationProvider<?>>();

        while (providerIterator.hasNext()) {
            try {
                ValidationProvider<?> provider = providerIterator.next();

                // put Hibernate Validator to the beginning of the list
                if (provider.getClass().getName().equals("org.hibernate.validator.HibernateValidator")) {
                    providers.addFirst(provider);
                } else {
                    providers.add(provider);
                }
            } catch (ServiceConfigurationError e) {
                // ignore, because it can happen when multiple
                // providers are present and some of them are not class loader
                // compatible with our API.
            }
        }

        return providers;
    }

Retrieves the providers from the given loader, using the service loader mechanism.

@param classLoader the class loader to use
@return a list with providers retrieved via the given loader. May be empty but never {@code null}

Retrieves the providers from the given loader using the service loader mechanism .


void modify(final Deployment dep) {
        final JBossWebMetaData jbossWebMD = WSHelper.getOptionalAttachment(dep, JBossWebMetaData.class);

        if (jbossWebMD != null) {
            this.configureEndpoints(dep, jbossWebMD);
            this.modifyContextRoot(dep, jbossWebMD);
        }
    }

void modify ( final Deployment dep ) { final JBossWebMetaData jbossWebMD = WSHelper . getOptionalAttachment ( dep , JBossWebMetaData . class ) ; if ( jbossWebMD != null ) { this . configureEndpoints ( dep , jbossWebMD ) ; this . modifyContextRoot ( dep , jbossWebMD ) ; } }

Modifies web meta data to configure webservice stack transport and properties.

@param dep webservice deployment

Modifies web meta data to configure webservice stack transport and properties .


private void configureEndpoints(final Deployment dep, final JBossWebMetaData jbossWebMD) {
        final String transportClassName = this.getTransportClassName(dep);
        WSLogger.ROOT_LOGGER.trace("Modifying servlets");

        // get a list of the endpoint bean class names
        final Set<String> epNames = new HashSet<String>();
        for (Endpoint ep : dep.getService().getEndpoints()) {
            epNames.add(ep.getTargetBeanName());
        }

        // fix servlet class names for endpoints
        for (final ServletMetaData servletMD : jbossWebMD.getServlets()) {
            final String endpointClassName = ASHelper.getEndpointClassName(servletMD);
            if (endpointClassName != null && endpointClassName.length() > 0) { // exclude JSP
                if (epNames.contains(endpointClassName)) {
                    // set transport servlet
                    servletMD.setServletClass(WSFServlet.class.getName());
                    WSLogger.ROOT_LOGGER.tracef("Setting transport class: %s for endpoint: %s", transportClassName, endpointClassName);
                    final List<ParamValueMetaData> initParams = WebMetaDataHelper.getServletInitParams(servletMD);
                    // configure transport class name
                    WebMetaDataHelper.newParamValue(WSFServlet.STACK_SERVLET_DELEGATE_CLASS, transportClassName, initParams);
                    // configure webservice endpoint
                    WebMetaDataHelper.newParamValue(Endpoint.SEPID_DOMAIN_ENDPOINT, endpointClassName, initParams);
                } else if (endpointClassName.startsWith("org.apache.cxf")) {
                    throw WSLogger.ROOT_LOGGER.invalidWSServlet(endpointClassName);
                }
            }
        }
    }

Configures transport servlet class for every found webservice endpoint.

@param dep webservice deployment
@param jbossWebMD web meta data

Configures transport servlet class for every found webservice endpoint .


private void modifyContextRoot(final Deployment dep, final JBossWebMetaData jbossWebMD) {
        final String contextRoot = dep.getService().getContextRoot();
        if (WSLogger.ROOT_LOGGER.isTraceEnabled()) {
            WSLogger.ROOT_LOGGER.tracef("Setting context root: %s for deployment: %s", contextRoot, dep.getSimpleName());
        }
        jbossWebMD.setContextRoot(contextRoot);
    }

Modifies context root.

@param dep webservice deployment
@param jbossWebMD web meta data


private String getTransportClassName(final Deployment dep) {
        String transportClassName = (String) dep.getProperty(WSConstants.STACK_TRANSPORT_CLASS);
        if (transportClassName == null) throw WSLogger.ROOT_LOGGER.missingDeploymentProperty(WSConstants.STACK_TRANSPORT_CLASS);
        return transportClassName;
    }

private String getTransportClassName ( final Deployment dep ) { String transportClassName = ( String ) dep . getProperty ( WSConstants . STACK_TRANSPORT_CLASS ) ; if ( transportClassName == null ) throw WSLogger . ROOT_LOGGER . missingDeploymentProperty ( WSConstants . STACK_TRANSPORT_CLASS ) ; return transportClassName ; }

Returns stack specific transport class name.

@param dep webservice deployment
@return stack specific transport class name
@throws IllegalStateException if transport class name is not found in deployment properties map

Returns stack specific transport class name .


static RunAs setRunAsIdentity(final RunAs principal, final SecurityContext sc) {
        if (WildFlySecurityManager.isChecking()) {
            return WildFlySecurityManager.doUnchecked(new PrivilegedAction<RunAs>() {

                @Override
                public RunAs run() {
                    if (sc == null) {
                        throw UndertowLogger.ROOT_LOGGER.noSecurityContext();
                    }
                    RunAs old = sc.getOutgoingRunAs();
                    sc.setOutgoingRunAs(principal);
                    return old;
                }
            });
        } else {
            if (sc == null) {
                throw UndertowLogger.ROOT_LOGGER.noSecurityContext();
            }
            RunAs old = sc.getOutgoingRunAs();
            sc.setOutgoingRunAs(principal);
            return old;
        }
    }

static RunAs setRunAsIdentity ( final RunAs principal , final SecurityContext sc ) { if ( WildFlySecurityManager . isChecking ( ) ) { return WildFlySecurityManager . doUnchecked ( new PrivilegedAction < RunAs > ( ) { @ Override public RunAs run ( ) { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs old = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( principal ) ; return old ; } } ) ; } else { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs old = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( principal ) ; return old ; } }

Sets the run as identity

@param principal the identity


static RunAs popRunAsIdentity(final SecurityContext sc) {
        if (WildFlySecurityManager.isChecking()) {
            return AccessController.doPrivileged(new PrivilegedAction<RunAs>() {
                @Override
                public RunAs run() {
                    if (sc == null) {
                        throw UndertowLogger.ROOT_LOGGER.noSecurityContext();
                    }
                    RunAs principal = sc.getOutgoingRunAs();
                    sc.setOutgoingRunAs(null);
                    return principal;
                }
            });
        } else {
            if (sc == null) {
                throw UndertowLogger.ROOT_LOGGER.noSecurityContext();
            }
            RunAs principal = sc.getOutgoingRunAs();
            sc.setOutgoingRunAs(null);
            return principal;
        }
    }

static RunAs popRunAsIdentity ( final SecurityContext sc ) { if ( WildFlySecurityManager . isChecking ( ) ) { return AccessController . doPrivileged ( new PrivilegedAction < RunAs > ( ) { @ Override public RunAs run ( ) { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs principal = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( null ) ; return principal ; } } ) ; } else { if ( sc == null ) { throw UndertowLogger . ROOT_LOGGER . noSecurityContext ( ) ; } RunAs principal = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( null ) ; return principal ; } }

Removes the run as identity

@return the identity removed


void processManagement(final DeploymentUnit unit, JBossWebMetaData metaData) {
        final DeploymentResourceSupport deploymentResourceSupport = unit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
        for (final JBossServletMetaData servlet : metaData.getServlets()) {
            try {
                final String name = servlet.getName();
                final ModelNode node = deploymentResourceSupport.getDeploymentSubModel(UndertowExtension.SUBSYSTEM_NAME, PathElement.pathElement("servlet", name));
                node.get("servlet-class").set(servlet.getServletClass());
                node.get("servlet-name").set(servlet.getServletName());
            } catch (Exception e) {
                // Should a failure in creating the mgmt view also make to the deployment to fail?
                continue;
            }
        }

    }

todo move to UndertowDeploymentService and use all registered servlets from Deployment instead of just one found by metadata


@SuppressWarnings("unchecked")
    public void inject(Object object, String propertyName, Object propertyValue)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        inject(object, propertyName, propertyValue, null, false);
    }

@ SuppressWarnings ( "unchecked" ) public void inject ( Object object , String propertyName , Object propertyValue ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { inject ( object , propertyName , propertyValue , null , false ) ; }

Inject a value into an object property

@param object        The object
@param propertyName  The property name
@param propertyValue The property value
@throws NoSuchMethodException     If the property method cannot be found
@throws IllegalAccessException    If the property method cannot be accessed
@throws InvocationTargetException If the property method cannot be executed


private boolean argumentMatches(String classType, String propertyType) {
        return (classType.equals(propertyType))
                || (classType.equals("java.lang.Byte") && propertyType.equals("byte"))
                || (classType.equals("java.lang.Short") && propertyType.equals("short"))
                || (classType.equals("java.lang.Integer") && propertyType.equals("int"))
                || (classType.equals("java.lang.Long") && propertyType.equals("long"))
                || (classType.equals("java.lang.Float") && propertyType.equals("float"))
                || (classType.equals("java.lang.Double") && propertyType.equals("double"))
                || (classType.equals("java.lang.Boolean") && propertyType.equals("boolean"))
                || (classType.equals("java.lang.Character") && propertyType.equals("char"));
    }

private boolean argumentMatches ( String classType , String propertyType ) { return ( classType . equals ( propertyType ) ) || ( classType . equals ( "java.lang.Byte" ) && propertyType . equals ( "byte" ) ) || ( classType . equals ( "java.lang.Short" ) && propertyType . equals ( "short" ) ) || ( classType . equals ( "java.lang.Integer" ) && propertyType . equals ( "int" ) ) || ( classType . equals ( "java.lang.Long" ) && propertyType . equals ( "long" ) ) || ( classType . equals ( "java.lang.Float" ) && propertyType . equals ( "float" ) ) || ( classType . equals ( "java.lang.Double" ) && propertyType . equals ( "double" ) ) || ( classType . equals ( "java.lang.Boolean" ) && propertyType . equals ( "boolean" ) ) || ( classType . equals ( "java.lang.Character" ) && propertyType . equals ( "char" ) ) ; }

Compare the type of a class with the actual value

@param classType    The class type
@param propertyType The property type
@return True if they match, or if there is a primitive mapping


protected Method findMethod(Class<?> clz, String methodName, String propertyType) {
        while (!clz.equals(Object.class)) {
            List<Method> hits = null;
            Method[] methods = SecurityActions.getDeclaredMethods(clz);
            for (int i = 0; i < methods.length; i++) {
                final Method method = methods[i];
                if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) {
                    if (propertyType == null || argumentMatches(propertyType, method.getParameterTypes()[0].getName())) {
                        if (hits == null)
                            hits = new ArrayList<Method>(1);

                        SecurityActions.setAccessible(method);

                        hits.add(method);
                    }
                }
            }

            if (hits != null) {
                if (hits.size() == 1) {
                    return hits.get(0);
                } else {
                    Collections.sort(hits, new MethodSorter());
                    if (propertyType != null) {
                        for (Method m : hits) {
                            if (propertyType.equals(m.getParameterTypes()[0].getName()))
                                return m;
                        }
                    }

                    return hits.get(0);
                }
            }

            clz = clz.getSuperclass();
        }

        return null;
    }

protected Method findMethod ( Class < ? > clz , String methodName , String propertyType ) { while ( ! clz . equals ( Object . class ) ) { List < Method > hits = null ; Method [ ] methods = SecurityActions . getDeclaredMethods ( clz ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { final Method method = methods [ i ] ; if ( methodName . equals ( method . getName ( ) ) && method . getParameterTypes ( ) . length == 1 ) { if ( propertyType == null || argumentMatches ( propertyType , method . getParameterTypes ( ) [ 0 ] . getName ( ) ) ) { if ( hits == null ) hits = new ArrayList < Method > ( 1 ) ; SecurityActions . setAccessible ( method ) ; hits . add ( method ) ; } } } if ( hits != null ) { if ( hits . size ( ) == 1 ) { return hits . get ( 0 ) ; } else { Collections . sort ( hits , new MethodSorter ( ) ) ; if ( propertyType != null ) { for ( Method m : hits ) { if ( propertyType . equals ( m . getParameterTypes ( ) [ 0 ] . getName ( ) ) ) return m ; } } return hits . get ( 0 ) ; } } clz = clz . getSuperclass ( ) ; } return null ; }

Find a method

@param clz          The class
@param methodName   The method name
@param propertyType The property type; can be null
@return The method; null if not found


protected Field findField(Class<?> clz, String fieldName, String fieldType) {
        while (!clz.equals(Object.class)) {
            List<Field> hits = null;
            Field[] fields = SecurityActions.getDeclaredFields(clz);
            for (int i = 0; i < fields.length; i++) {
                final Field field = fields[i];
                if (fieldName.equals(field.getName())) {
                    if (fieldType == null || argumentMatches(fieldType, field.getType().getName())) {
                        if (hits == null)
                            hits = new ArrayList<Field>(1);

                        SecurityActions.setAccessible(field);

                        hits.add(field);
                    }
                }
            }

            if (hits != null) {
                if (hits.size() == 1) {
                    return hits.get(0);
                } else {
                    Collections.sort(hits, new FieldSorter());
                    if (fieldType != null) {
                        for (Field f : hits) {
                            if (fieldType.equals(f.getType().getName()))
                                return f;
                        }
                    }

                    return hits.get(0);
                }
            }

            clz = clz.getSuperclass();
        }

        return null;
    }

protected Field findField ( Class < ? > clz , String fieldName , String fieldType ) { while ( ! clz . equals ( Object . class ) ) { List < Field > hits = null ; Field [ ] fields = SecurityActions . getDeclaredFields ( clz ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { final Field field = fields [ i ] ; if ( fieldName . equals ( field . getName ( ) ) ) { if ( fieldType == null || argumentMatches ( fieldType , field . getType ( ) . getName ( ) ) ) { if ( hits == null ) hits = new ArrayList < Field > ( 1 ) ; SecurityActions . setAccessible ( field ) ; hits . add ( field ) ; } } } if ( hits != null ) { if ( hits . size ( ) == 1 ) { return hits . get ( 0 ) ; } else { Collections . sort ( hits , new FieldSorter ( ) ) ; if ( fieldType != null ) { for ( Field f : hits ) { if ( fieldType . equals ( f . getType ( ) . getName ( ) ) ) return f ; } } return hits . get ( 0 ) ; } } clz = clz . getSuperclass ( ) ; } return null ; }

Find a field

@param clz       The class
@param fieldName The field name
@param fieldType The field type; can be null
@return The field; null if not found


private void initOptions() {
        options = new Options();
        options.addOption("k", KEYSTORE_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineKeyStoreURL());
        options.addOption("p", KEYSTORE_PASSWORD_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineKeyStorePassword());
        options.addOption("e", ENC_DIR_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineEncryptionDirectory());
        options.addOption("s", SALT_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineSalt());
        options.addOption("i", ITERATION_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineIterationCount());
        options.addOption("v", ALIAS_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineVaultKeyStoreAlias());
        options.addOption("b", VAULT_BLOCK_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineVaultBlock());
        options.addOption("a", ATTRIBUTE_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineAttributeName());
        options.addOption("t", CREATE_KEYSTORE_PARAM, false, SecurityLogger.ROOT_LOGGER.cmdLineAutomaticallyCreateKeystore());

        OptionGroup og = new OptionGroup();
        Option x = new Option("x", SEC_ATTR_VALUE_PARAM, true, SecurityLogger.ROOT_LOGGER.cmdLineSecuredAttribute());
        Option c = new Option("c", CHECK_SEC_ATTR_EXISTS_PARAM, false, SecurityLogger.ROOT_LOGGER.cmdLineCheckAttribute());
        Option r = new Option("r", REMOVE_SEC_ATTR_PARAM, false, SecurityLogger.ROOT_LOGGER.cmdLineRemoveSecuredAttribute());
        Option h = new Option("h", HELP_PARAM, false, SecurityLogger.ROOT_LOGGER.cmdLineHelp());
        og.addOption(x);
        og.addOption(c);
        og.addOption(r);
        og.addOption(h);
        og.setRequired(true);
        options.addOptionGroup(og);
    }

private void initOptions ( ) { options = new Options ( ) ; options . addOption ( "k" , KEYSTORE_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineKeyStoreURL ( ) ) ; options . addOption ( "p" , KEYSTORE_PASSWORD_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineKeyStorePassword ( ) ) ; options . addOption ( "e" , ENC_DIR_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineEncryptionDirectory ( ) ) ; options . addOption ( "s" , SALT_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineSalt ( ) ) ; options . addOption ( "i" , ITERATION_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineIterationCount ( ) ) ; options . addOption ( "v" , ALIAS_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineVaultKeyStoreAlias ( ) ) ; options . addOption ( "b" , VAULT_BLOCK_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineVaultBlock ( ) ) ; options . addOption ( "a" , ATTRIBUTE_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineAttributeName ( ) ) ; options . addOption ( "t" , CREATE_KEYSTORE_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineAutomaticallyCreateKeystore ( ) ) ; OptionGroup og = new OptionGroup ( ) ; Option x = new Option ( "x" , SEC_ATTR_VALUE_PARAM , true , SecurityLogger . ROOT_LOGGER . cmdLineSecuredAttribute ( ) ) ; Option c = new Option ( "c" , CHECK_SEC_ATTR_EXISTS_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineCheckAttribute ( ) ) ; Option r = new Option ( "r" , REMOVE_SEC_ATTR_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineRemoveSecuredAttribute ( ) ) ; Option h = new Option ( "h" , HELP_PARAM , false , SecurityLogger . ROOT_LOGGER . cmdLineHelp ( ) ) ; og . addOption ( x ) ; og . addOption ( c ) ; og . addOption ( r ) ; og . addOption ( h ) ; og . setRequired ( true ) ; options . addOptionGroup ( og ) ; }

Build options for non-interactive VaultTool usage scenario.

@return

Build options for non - interactive VaultTool usage scenario .


private static String deriveUsefulInfo(HttpServletRequest httpRequest) {
        StringBuilder sb = new StringBuilder();
        sb.append("[").append(httpRequest.getContextPath());
        sb.append(":cookies=").append(Arrays.toString(httpRequest.getCookies())).append(":headers=");
        // Append Header information
        Enumeration<?> en = httpRequest.getHeaderNames();
        while (en.hasMoreElements()) {
            String headerName = (String) en.nextElement();
            sb.append(headerName).append("=");
            // Ensure HTTP Basic Password is not logged
            if (!headerName.contains("authorization")) { sb.append(httpRequest.getHeader(headerName)).append(","); }
        }
        sb.append("]");
        // Append Request parameter information
        sb.append("[parameters=");
        Enumeration<?> enparam = httpRequest.getParameterNames();
        while (enparam.hasMoreElements()) {
            String paramName = (String) enparam.nextElement();
            String[] paramValues = httpRequest.getParameterValues(paramName);
            int len = paramValues != null ? paramValues.length : 0;
            for (int i = 0; i < len; i++) { sb.append(paramValues[i]).append("::"); }
            sb.append(",");
        }
        sb.append("][attributes=");
        // Append Request attribute information
        Enumeration<?> enu = httpRequest.getAttributeNames();
        while (enu.hasMoreElements()) {
            String attrName = (String) enu.nextElement();
            sb.append(attrName).append("=");
            sb.append(httpRequest.getAttribute(attrName)).append(",");
        }
        sb.append("]");
        return sb.toString();
    }

Obtain debug information from the servlet request object

@param httpRequest
@return


public JdrReport standaloneCollect(CLI cli, String protocol, String host, int port) throws OperationFailedException {
        return new JdrRunner(cli, protocol, host, port, null, null).collect();
    }

public JdrReport standaloneCollect ( CLI cli , String protocol , String host , int port ) throws OperationFailedException { return new JdrRunner ( cli , protocol , host , port , null , null ) . collect ( ) ; }

Collect a JDR report when run outside the Application Server.
@param cli

Collect a JDR report when run outside the Application Server .


public JdrReport collect() throws OperationFailedException {
        JdrRunner runner = new JdrRunner(true);
        serverEnvironment = serverEnvironmentValue.getValue();
        runner.setJbossHomeDir(serverEnvironment.getHomeDir().getAbsolutePath());
        runner.setReportLocationDir(serverEnvironment.getServerTempDir().getAbsolutePath());
        runner.setControllerClient(controllerClient);
        runner.setHostControllerName(serverEnvironment.getHostControllerName());
        runner.setServerName(serverEnvironment.getServerName());
        return runner.collect();
    }

public JdrReport collect ( ) throws OperationFailedException { JdrRunner runner = new JdrRunner ( true ) ; serverEnvironment = serverEnvironmentValue . getValue ( ) ; runner . setJbossHomeDir ( serverEnvironment . getHomeDir ( ) . getAbsolutePath ( ) ) ; runner . setReportLocationDir ( serverEnvironment . getServerTempDir ( ) . getAbsolutePath ( ) ) ; runner . setControllerClient ( controllerClient ) ; runner . setHostControllerName ( serverEnvironment . getHostControllerName ( ) ) ; runner . setServerName ( serverEnvironment . getServerName ( ) ) ; return runner . collect ( ) ; }


public void registerResourceAdapterDeployment(ResourceAdapterDeployment deployment) {
        if (deployment == null)
            throw new IllegalArgumentException(ConnectorLogger.ROOT_LOGGER.nullVar("Deployment"));

        DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.tracef("Adding deployment: %s", deployment);

        deployments.add(deployment);
    }

public
void
registerResourceAdapterDeployment
(
ResourceAdapterDeployment
deployment
)
{
if
(
deployment
==
)
throw
new
IllegalArgumentException
(
ConnectorLogger
.
ROOT_LOGGER
.
nullVar
(
"Deployment"
)
)
;
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER
.
tracef
(
"Adding deployment: %s"
,
deployment
)
;
deployments
.
add
(
deployment
)
;
}

Register a resource adapter deployment
@param deployment The deployment


public void unregisterResourceAdapterDeployment(ResourceAdapterDeployment deployment) {
        if (deployment == null)
            throw new IllegalArgumentException(ConnectorLogger.ROOT_LOGGER.nullVar("Deployment"));

        DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER.tracef("Removing deployment: %s", deployment);

        deployments.remove(deployment);
    }

public
void
unregisterResourceAdapterDeployment
(
ResourceAdapterDeployment
deployment
)
{
if
(
deployment
==
)
throw
new
IllegalArgumentException
(
ConnectorLogger
.
ROOT_LOGGER
.
nullVar
(
"Deployment"
)
)
;
DEPLOYMENT_CONNECTOR_REGISTRY_LOGGER
.
tracef
(
"Removing deployment: %s"
,
deployment
)
;
deployments
.
remove
(
deployment
)
;
}

Unregister a resource adapter deployment
@param deployment The deployment


protected static void registerTransformers(final SubsystemRegistration subsystem) {
        ChainedTransformationDescriptionBuilder chained = ResourceTransformationDescriptionBuilder.Factory.createChainedSubystemInstance(CURRENT_MODEL_VERSION);
        ModelVersion MODEL_VERSION_EAP64 = ModelVersion.create(1, 4, 0);
        ModelVersion MODEL_VERSION_EAP63 = ModelVersion.create(1, 3, 0);//also EAP6.2

        ResourceTransformationDescriptionBuilder builder64 = chained.createBuilder(CURRENT_MODEL_VERSION, MODEL_VERSION_EAP64);
        builder64.getAttributeBuilder()
                .addRejectCheck(RejectAttributeChecker.DEFINED, JacORBSubsystemDefinitions.PERSISTENT_SERVER_ID)
                .setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(JacORBSubsystemDefinitions.PERSISTENT_SERVER_ID.getDefaultValue()), JacORBSubsystemDefinitions.PERSISTENT_SERVER_ID)
                .setValueConverter(new AttributeConverter.DefaultValueAttributeConverter(JacORBSubsystemDefinitions.INTEROP_CHUNK_RMI_VALUETYPES),JacORBSubsystemDefinitions.INTEROP_CHUNK_RMI_VALUETYPES);

        ResourceTransformationDescriptionBuilder builder63 = chained.createBuilder(MODEL_VERSION_EAP64, MODEL_VERSION_EAP63);
        builder63.getAttributeBuilder()
                .addRejectCheck(RejectAttributeChecker.DEFINED, IORTransportConfigDefinition.ATTRIBUTES.toArray(new AttributeDefinition[0]))
                .addRejectCheck(RejectAttributeChecker.DEFINED, IORASContextDefinition.ATTRIBUTES.toArray(new AttributeDefinition[0]))
                .addRejectCheck(RejectAttributeChecker.DEFINED, IORSASContextDefinition.ATTRIBUTES.toArray(new AttributeDefinition[0]))
                .end()
                .rejectChildResource(IORSettingsDefinition.INSTANCE.getPathElement());

        chained.buildAndRegister(subsystem, new ModelVersion[]{
                MODEL_VERSION_EAP64,
                MODEL_VERSION_EAP63
        });
    }

Register the transformers for the 1.3.0 version.

@param subsystem the subsystems registration

Register the transformers for the 1 . 3 . 0 version .


public void writeParams(OutputStream out, Object[] params) {
        int len = params.length;

        if (len != paramWriters.length) {
            throw IIOPLogger.ROOT_LOGGER.errorMashalingParams();
        }
        for (int i = 0; i < len; i++) {
            Object param = params[i];
            if (param instanceof PortableRemoteObject) {
                try {
                    param = PortableRemoteObject.toStub((Remote) param);
                } catch (NoSuchObjectException e) {
                    throw new RuntimeException(e);
                }
            }
            paramWriters[i].write(out, RemoteObjectSubstitutionManager.writeReplaceRemote(param));
        }
    }

public void writeParams ( OutputStream out , Object [ ] params ) { int len = params . length ; if ( len != paramWriters . length ) { throw IIOPLogger . ROOT_LOGGER . errorMashalingParams ( ) ; } for ( int i = 0 ; i < len ; i ++ ) { Object param = params [ i ] ; if ( param instanceof PortableRemoteObject ) { try { param = PortableRemoteObject . toStub ( ( Remote ) param ) ; } catch ( NoSuchObjectException e ) { throw new RuntimeException ( e ) ; } } paramWriters [ i ] . write ( out , RemoteObjectSubstitutionManager . writeReplaceRemote ( param ) ) ; } }

Marshals the sequence of method parameters into an output stream.

@param out    a CDR output stream
@param params an object array with the parameters.

Marshals the sequence of method parameters into an output stream .


public Exception readException(String id, InputStream in) {
        ExceptionReader exceptionReader = (ExceptionReader) exceptionMap.get(id);
        if (exceptionReader == null) {
            return new UnexpectedException(id);
        } else {
            return exceptionReader.read(in);
        }
    }

public Exception readException ( String id , InputStream in ) { ExceptionReader exceptionReader = ( ExceptionReader ) exceptionMap . get ( id ) ; if ( exceptionReader == null ) { return new UnexpectedException ( id ) ; } else { return exceptionReader . read ( in ) ; } }

Unmarshals from an input stream an exception thrown by the method.

@param id the repository id of the exception to unmarshal
@param in a CDR input stream
@return an exception unmarshaled from the stream.

Unmarshals from an input stream an exception thrown by the method .


private static Object getLockOwner(final TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
        Object owner = transactionSynchronizationRegistry.getTransactionKey();
        return owner != null ? owner : Thread.currentThread();
    }

private static Object getLockOwner ( final TransactionSynchronizationRegistry transactionSynchronizationRegistry ) { Object owner = transactionSynchronizationRegistry . getTransactionKey ( ) ; return owner != null ? owner : Thread . currentThread ( ) ; }

Use either the active transaction or the current thread as the lock owner

@return The lock owner


static void releaseLock(final StatefulSessionComponentInstance instance) {
        instance.getLock().unlock(getLockOwner(instance.getComponent().getTransactionSynchronizationRegistry()));
        ROOT_LOGGER.tracef("Released lock: %s", instance.getLock());
    }

static
void
releaseLock
(
final
StatefulSessionComponentInstance
instance
)
{
instance
.
getLock
(
)
.
unlock
(
getLockOwner
(
instance
.
getComponent
(
)
.
getTransactionSynchronizationRegistry
(
)
)
)
;
ROOT_LOGGER
.
tracef
(
"Released lock: %s"
,
instance
.
getLock
(
)
)
;
}

Releases the lock, held by this thread, on the stateful component instance.

Releases the lock held by this thread on the stateful component instance .


public void addLog(String content, String logName) throws Exception {
        String name = "sos_logs/" + logName;
        this.add(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), name);
    }

public void addLog ( String content , String logName ) throws Exception { String name = "sos_logs/" + logName ; this . add ( new ByteArrayInputStream ( content . getBytes ( StandardCharsets . UTF_8 ) ) , name ) ; }

Adds content to the zipfile in a file named logName

path is prepended with the directory reserved for JDR log files

@param content
@param logName
@throws Exception


private void addCDIFlag(WarMetaData warMetaData, DeploymentUnit deploymentUnit) {
        JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
        if (webMetaData == null) {
            webMetaData = new JBossWebMetaData();
            warMetaData.setMergedJBossWebMetaData(webMetaData);
        }

        List<ParamValueMetaData> contextParams = webMetaData.getContextParams();
        if (contextParams == null) {
            contextParams = new ArrayList<ParamValueMetaData>();
        }

        boolean isCDI = false;
        final CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
        if (support.hasCapability(WELD_CAPABILITY_NAME)) {
            isCDI = support.getOptionalCapabilityRuntimeAPI(WELD_CAPABILITY_NAME, WeldCapability.class).get()
                    .isPartOfWeldDeployment(deploymentUnit);
        }

        ParamValueMetaData param = new ParamValueMetaData();
        param.setParamName(IS_CDI_PARAM);
        param.setParamValue(Boolean.toString(isCDI));
        contextParams.add(param);

        webMetaData.setContextParams(contextParams);
    }

private void addCDIFlag ( WarMetaData warMetaData , DeploymentUnit deploymentUnit ) { JBossWebMetaData webMetaData = warMetaData . getMergedJBossWebMetaData ( ) ; if ( webMetaData == null ) { webMetaData = new JBossWebMetaData ( ) ; warMetaData . setMergedJBossWebMetaData ( webMetaData ) ; } List < ParamValueMetaData > contextParams = webMetaData . getContextParams ( ) ; if ( contextParams == null ) { contextParams = new ArrayList < ParamValueMetaData > ( ) ; } boolean isCDI = false ; final CapabilityServiceSupport support = deploymentUnit . getAttachment ( Attachments . CAPABILITY_SERVICE_SUPPORT ) ; if ( support . hasCapability ( WELD_CAPABILITY_NAME ) ) { isCDI = support . getOptionalCapabilityRuntimeAPI ( WELD_CAPABILITY_NAME , WeldCapability . class ) . get ( ) . isPartOfWeldDeployment ( deploymentUnit ) ; } ParamValueMetaData param = new ParamValueMetaData ( ) ; param . setParamName ( IS_CDI_PARAM ) ; param . setParamValue ( Boolean . toString ( isCDI ) ) ; contextParams . add ( param ) ; webMetaData . setContextParams ( contextParams ) ; }


protected ComponentView getComponentView() {
        ComponentView cv = componentView;
        // we need to check both, otherwise it is possible for
        // componentView to be initialized before reference
        if (cv == null) {
            synchronized (this) {
                cv = componentView;
                if (cv == null) {
                    cv = getMSCService(componentViewName, ComponentView.class);
                    if (cv == null) {
                        throw WSLogger.ROOT_LOGGER.cannotFindComponentView(componentViewName);
                    }
                    if (reference == null) {
                        try {
                            reference = cv.createInstance();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                    componentView = cv;
                }
            }
        }
        return cv;
    }

Gets endpoint container lazily.

@return endpoint container


public void invoke(final Endpoint endpoint, final Invocation wsInvocation) throws Exception {
        try {
            if (!EndpointState.STARTED.equals(endpoint.getState())) {
                throw WSLogger.ROOT_LOGGER.endpointAlreadyStopped(endpoint.getShortName());
            }
            SecurityDomainContext securityDomainContext = endpoint.getSecurityDomainContext();
            securityDomainContext.runAs((Callable<Void>) () -> {
                invokeInternal(endpoint, wsInvocation);
                return null;
            });
        } catch (Throwable t) {
            handleInvocationException(t);
        } finally {
            onAfterInvocation(wsInvocation);
        }
    }

public void invoke ( final Endpoint endpoint , final Invocation wsInvocation ) throws Exception { try { if ( ! EndpointState . STARTED . equals ( endpoint . getState ( ) ) ) { throw WSLogger . ROOT_LOGGER . endpointAlreadyStopped ( endpoint . getShortName ( ) ) ; } SecurityDomainContext securityDomainContext = endpoint . getSecurityDomainContext ( ) ; securityDomainContext . runAs ( ( Callable < Void > ) ( ) -> { invokeInternal ( endpoint , wsInvocation ) ; return null ; } ) ; } catch ( Throwable t ) { handleInvocationException ( t ) ; } finally { onAfterInvocation ( wsInvocation ) ; } }

Invokes WS endpoint.

@param endpoint WS endpoint
@param wsInvocation web service invocation
@throws Exception if any error occurs


protected Method getComponentViewMethod(final Method seiMethod, final Collection<Method> viewMethods) {
       for (final Method viewMethod : viewMethods) {
           if (matches(seiMethod, viewMethod)) {
               return viewMethod;
           }
       }
       throw new IllegalStateException();
   }

protected Method getComponentViewMethod ( final Method seiMethod , final Collection < Method > viewMethods ) { for ( final Method viewMethod : viewMethods ) { if ( matches ( seiMethod , viewMethod ) ) { return viewMethod ; } } throw new IllegalStateException ( ) ; }

Translates SEI method to component view method.

@param seiMethod SEI method
@param viewMethods component view methods
@return matching component view method

Translates SEI method to component view method .


private boolean matches(final Method seiMethod, final Method viewMethod) {
       if (!seiMethod.getName().equals(viewMethod.getName())) return false;
       final Class<?>[] sourceParams = seiMethod.getParameterTypes();
       final Class<?>[] targetParams = viewMethod.getParameterTypes();
       if (sourceParams.length != targetParams.length) return false;
       for (int i = 0; i < sourceParams.length; i++) {
           if (!sourceParams[i].equals(targetParams[i])) return false;
       }
       return true;
   }

private boolean matches ( final Method seiMethod , final Method viewMethod ) { if ( ! seiMethod . getName ( ) . equals ( viewMethod . getName ( ) ) ) return false ; final Class < ? > [ ] sourceParams = seiMethod . getParameterTypes ( ) ; final Class < ? > [ ] targetParams = viewMethod . getParameterTypes ( ) ; if ( sourceParams . length != targetParams . length ) return false ; for ( int i = 0 ; i < sourceParams . length ; i ++ ) { if ( ! sourceParams [ i ] . equals ( targetParams [ i ] ) ) return false ; } return true ; }

Compares two methods if they are identical.

@param seiMethod reference method
@param viewMethod target method
@return true if they match, false otherwise

Compares two methods if they are identical .


public static Resource createManagementStatisticsResource(
            final ManagementAdaptor managementAdaptor,
            final String scopedPersistenceUnitName,
            final DeploymentUnit deploymentUnit) {

        synchronized (existingResourceDescriptionResolver) {
            final EntityManagerFactoryLookup entityManagerFactoryLookup = new EntityManagerFactoryLookup();
            final Statistics statistics = managementAdaptor.getStatistics();

            if (false == existingResourceDescriptionResolver.contains(managementAdaptor.getVersion())) {

                // setup statistics (this used to be part of JPA subsystem startup)
                ResourceDescriptionResolver resourceDescriptionResolver = new StandardResourceDescriptionResolver(
                        statistics.getResourceBundleKeyPrefix(), statistics.getResourceBundleName(), statistics.getClass().getClassLoader()){
                    private ResourceDescriptionResolver fallback = JPAExtension.getResourceDescriptionResolver();
                    //add a fallback in case provider doesn't have all properties properly defined
                    @Override
                    public String getResourceAttributeDescription(String attributeName, Locale locale, ResourceBundle bundle) {
                        if (bundle.containsKey(getBundleKey(attributeName))) {
                            return super.getResourceAttributeDescription(attributeName, locale, bundle);
                        }else{
                            return fallback.getResourceAttributeDescription(attributeName, locale, fallback.getResourceBundle(locale));
                        }
                    }
                };

                PathElement subsystemPE = PathElement.pathElement(ModelDescriptionConstants.SUBSYSTEM, JPAExtension.SUBSYSTEM_NAME);
                ManagementResourceRegistration deploymentResourceRegistration = deploymentUnit.getAttachment(DeploymentModelUtils.MUTABLE_REGISTRATION_ATTACHMENT);
                ManagementResourceRegistration deploymentSubsystemRegistration =
                        deploymentResourceRegistration.getSubModel(PathAddress.pathAddress(subsystemPE));
                ManagementResourceRegistration subdeploymentSubsystemRegistration =
                        deploymentResourceRegistration.getSubModel(PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.SUBDEPLOYMENT), subsystemPE));

                ManagementResourceRegistration providerResource = deploymentSubsystemRegistration.registerSubModel(
                        new ManagementResourceDefinition(PathElement.pathElement(managementAdaptor.getIdentificationLabel()), resourceDescriptionResolver, statistics, entityManagerFactoryLookup));
                providerResource.registerReadOnlyAttribute(PersistenceUnitServiceHandler.SCOPED_UNIT_NAME, null);

                providerResource = subdeploymentSubsystemRegistration.registerSubModel(
                        new ManagementResourceDefinition(PathElement.pathElement(managementAdaptor.getIdentificationLabel()), resourceDescriptionResolver, statistics, entityManagerFactoryLookup));
                providerResource.registerReadOnlyAttribute(PersistenceUnitServiceHandler.SCOPED_UNIT_NAME, null);

                existingResourceDescriptionResolver.add(managementAdaptor.getVersion());
            }
            // create (per deployment) dynamic Resource implementation that can reflect the deployment specific names (e.g. jpa entity classname/Hibernate region name)
            return new DynamicManagementStatisticsResource(statistics, scopedPersistenceUnitName, managementAdaptor.getIdentificationLabel(), entityManagerFactoryLookup);
        }
    }

Create single instance of management statistics resource per managementAdaptor version.

ManagementAccess

The persistence provider and jipijapa adapters will be in the same classloader,
either a static module or included directly in the application.  Those are the two supported use
cases for management of deployment persistence units also.

From a management point of view, the requirements are:
1.  show management statistics for static persistence provider modules and applications that have
their own persistence provider module.

2.  persistence provider adapters will provide a unique key that identifies the management version of supported
management statistics/operations.  For example, Hibernate 3.x might be 1.0, Hibernate 4.1/4.2 might
be version 2.0 and Hibernate 4.3 could be 2.0 also as long as its compatible (same stats) with 4.1/4.2.
Eventually, a Hibernate (later version) change in statistics is likely to happen, the management version
will be incremented.

@param managementAdaptor the management adaptor that will provide statistics
@param scopedPersistenceUnitName name of the persistence unit
@param deploymentUnit deployment unit for the deployment requesting a resource
@return the management resource

Create single instance of management statistics resource per managementAdaptor version .


private EJBSecurityMetaData getEjbSecurityMetaData(final Endpoint endpoint) {
        final String ejbName = endpoint.getShortName();
        final Deployment dep = endpoint.getService().getDeployment();
        final EJBArchiveMetaData ejbArchiveMD = WSHelper.getOptionalAttachment(dep, EJBArchiveMetaData.class);
        final EJBMetaData ejbMD = ejbArchiveMD != null ? ejbArchiveMD.getBeanByEjbName(ejbName) : null;

        return ejbMD != null ? ejbMD.getSecurityMetaData() : null;
    }

private EJBSecurityMetaData getEjbSecurityMetaData ( final Endpoint endpoint ) { final String ejbName = endpoint . getShortName ( ) ; final Deployment dep = endpoint . getService ( ) . getDeployment ( ) ; final EJBArchiveMetaData ejbArchiveMD = WSHelper . getOptionalAttachment ( dep , EJBArchiveMetaData . class ) ; final EJBMetaData ejbMD = ejbArchiveMD != null ? ejbArchiveMD . getBeanByEjbName ( ejbName ) : null ; return ejbMD != null ? ejbMD . getSecurityMetaData ( ) : null ; }

Gets EJB security meta data if associated with EJB endpoint.

@param endpoint EJB webservice endpoint
@return EJB security meta data or null

Gets EJB security meta data if associated with EJB endpoint .


private String getDomain(final String oldSecurityDomain, final String nextSecurityDomain) {
        if (nextSecurityDomain == null) {
            return oldSecurityDomain;
        }

        if (oldSecurityDomain == null) {
            return nextSecurityDomain;
        }

        ensureSameDomains(oldSecurityDomain, nextSecurityDomain);

        return oldSecurityDomain;
    }

private String getDomain ( final String oldSecurityDomain , final String nextSecurityDomain ) { if ( nextSecurityDomain == null ) { return oldSecurityDomain ; } if ( oldSecurityDomain == null ) { return nextSecurityDomain ; } ensureSameDomains ( oldSecurityDomain , nextSecurityDomain ) ; return oldSecurityDomain ; }

Returns security domain value. This method checks domain is the same for every EJB 3 endpoint.

@param oldSecurityDomain our security domain
@param nextSecurityDomain next security domain
@return security domain value
@throws IllegalStateException if domains have different values

Returns security domain value . This method checks domain is the same for every EJB 3 endpoint .


private void ensureSameDomains(final String oldSecurityDomain, final String newSecurityDomain) {
        final boolean domainsDiffer = !oldSecurityDomain.equals(newSecurityDomain);
        if (domainsDiffer)
            throw WSLogger.ROOT_LOGGER.multipleSecurityDomainsDetected(oldSecurityDomain, newSecurityDomain);
    }

private void ensureSameDomains ( final String oldSecurityDomain , final String newSecurityDomain ) { final boolean domainsDiffer = ! oldSecurityDomain . equals ( newSecurityDomain ) ; if ( domainsDiffer ) throw WSLogger . ROOT_LOGGER . multipleSecurityDomainsDetected ( oldSecurityDomain , newSecurityDomain ) ; }

This method ensures both passed domains contain the same value.

@param oldSecurityDomain our security domain
@param newSecurityDomain next security domain
@throws IllegalStateException if domains have different values

This method ensures both passed domains contain the same value .


void setIDLName(String idlName) {
        super.setIDLName(idlName);

        // If the first char is an uppercase letter and the second char is not
        // an uppercase letter, then convert the first char to lowercase.
        if (idlName.charAt(0) >= 0x41 && idlName.charAt(0) <= 0x5a
                && (idlName.length() <= 1
                || idlName.charAt(1) < 0x41 || idlName.charAt(1) > 0x5a)) {
            idlName =
                    idlName.substring(0, 1).toLowerCase(Locale.ENGLISH) + idlName.substring(1);
        }

        if (accessorAnalysis != null)
            accessorAnalysis.setIDLName("_get_" + idlName);
        if (mutatorAnalysis != null)
            mutatorAnalysis.setIDLName("_set_" + idlName);
    }

Set my unqualified IDL name.
This also sets the names of the associated operations.

Set my unqualified IDL name . This also sets the names of the associated operations .


public String getAbsoluteName() {
        final StringBuilder absolute = new StringBuilder();
        if (parent != null) {
            absolute.append(parent).append(ENTRY_SEPARATOR);
        }
        absolute.append(local);
        return absolute.toString();
    }

public String getAbsoluteName ( ) { final StringBuilder absolute = new StringBuilder ( ) ; if ( parent != null ) { absolute . append ( parent ) . append ( ENTRY_SEPARATOR ) ; } absolute . append ( local ) ; return absolute . toString ( ) ; }

Get the absolute JNDI name as a string.

@return The absolute JNDI name as a string

Get the absolute JNDI name as a string .


public static JndiName of(final String name) {
        if(name == null || name.isEmpty()) throw NamingLogger.ROOT_LOGGER.invalidJndiName(name);
        final String[] parts = name.split(ENTRY_SEPARATOR);
        JndiName current = null;
        for(String part : parts) {
            current = new JndiName(current, part);
        }
        return current;
    }

public static JndiName of ( final String name ) { if ( name == null || name . isEmpty ( ) ) throw NamingLogger . ROOT_LOGGER . invalidJndiName ( name ) ; final String [ ] parts = name . split ( ENTRY_SEPARATOR ) ; JndiName current = null ; for ( String part : parts ) { current = new JndiName ( current , part ) ; } return current ; }

Create a new instance of the JndiName by breaking the provided string format into a JndiName parts.

@param name The string representation of a JNDI name.
@return The JndiName representation

Create a new instance of the JndiName by breaking the provided string format into a JndiName parts .


@Override
    public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final ResourceRoot resourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
        final VirtualFile deploymentRoot = resourceRoot.getRoot();
        final boolean resolveProperties = Util.shouldResolveJBoss(deploymentUnit);

        IronJacamarXmlDescriptor xmlDescriptor = process(deploymentRoot, resolveProperties);
        if (xmlDescriptor != null) {
            deploymentUnit.putAttachment(IronJacamarXmlDescriptor.ATTACHMENT_KEY, xmlDescriptor);
        }
    }

@ Override public void deploy ( DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; final ResourceRoot resourceRoot = deploymentUnit . getAttachment ( Attachments . DEPLOYMENT_ROOT ) ; final VirtualFile deploymentRoot = resourceRoot . getRoot ( ) ; final boolean resolveProperties = Util . shouldResolveJBoss ( deploymentUnit ) ; IronJacamarXmlDescriptor xmlDescriptor = process ( deploymentRoot , resolveProperties ) ; if ( xmlDescriptor != null ) { deploymentUnit . putAttachment ( IronJacamarXmlDescriptor . ATTACHMENT_KEY , xmlDescriptor ) ; } }

Process a deployment for iron-jacamar.xml files. Will parse the xml file
and attach metadata discovered during processing.

@param phaseContext the deployment unit context
@throws DeploymentUnitProcessingException

Process a deployment for iron - jacamar . xml files . Will parse the xml file and attach metadata discovered during processing .


@Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        runningCount.increment();

        exchange.addExchangeCompleteListener(new ExchangeCompletionListener() {
            @Override
            public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
                runningCount.decrement();

                // Proceed to next listener must be called!
                nextListener.proceed();
            }
        });

        wrappedHandler.handleRequest(exchange);
    }

Increments the counter and registers a listener to decrement the counter upon exchange complete event.

Increments the counter and registers a listener to decrement the counter upon exchange complete event .


private boolean isInTransaction() {
        TransactionSynchronizationRegistry tsr = getTransactionSynchronizationRegistry();
        boolean inTx = tsr.getTransactionStatus() == Status.STATUS_ACTIVE;
        return inTx;
    }

private boolean isInTransaction ( ) { TransactionSynchronizationRegistry tsr = getTransactionSynchronizationRegistry ( ) ; boolean inTx = tsr . getTransactionStatus ( ) == Status . STATUS_ACTIVE ; return inTx ; }

check whether there is an active transaction.

check whether there is an active transaction .


private TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
        TransactionSynchronizationRegistry cachedTSR = transactionSynchronizationRegistry;
        if (cachedTSR == null) {
            cachedTSR = (TransactionSynchronizationRegistry) lookup(TRANSACTION_SYNCHRONIZATION_REGISTRY_LOOKUP);
            transactionSynchronizationRegistry = cachedTSR;
        }
        return cachedTSR;
    }

lookup the transactionSynchronizationRegistry and cache it.

lookup the transactionSynchronizationRegistry and cache it .


private ConnectionFactory getConnectionFactory() {
        ConnectionFactory cachedCF = connectionFactory;

        if (cachedCF == null) {
            cachedCF = (ConnectionFactory)lookup(info.getConnectionFactoryLookup());
            connectionFactory = cachedCF;
        }
        return cachedCF;
    }

private ConnectionFactory getConnectionFactory ( ) { ConnectionFactory cachedCF = connectionFactory ; if ( cachedCF == null ) { cachedCF = ( ConnectionFactory ) lookup ( info . getConnectionFactoryLookup ( ) ) ; connectionFactory = cachedCF ; } return cachedCF ; }

lookup the connectionFactory and cache it.

lookup the connectionFactory and cache it .


public static String getLastComponent(final Name name) {
        if(name.size() > 0)
            return name.get(name.size() - 1);
        return "";
    }

public static String getLastComponent ( final Name name ) { if ( name . size ( ) > 0 ) return name . get ( name . size ( ) - 1 ) ; return "" ; }

Get the last component of a name.

@param name the name
@return the last component


public static boolean isEmpty(final Name name) {
        return name.isEmpty() || (name.size() == 1 && "".equals(name.get(0)));
    }

public static boolean isEmpty ( final Name name ) { return name . isEmpty ( ) || ( name . size ( ) == 1 && "" . equals ( name . get ( 0 ) ) ) ; }

Determine if a name is empty, or if ot contains only one component which is the empty string.

@param name the name
@return {@code true} if the name is empty or contains one empty component

Determine if a name is empty or if ot contains only one component which is the empty string .


public static NameNotFoundException nameNotFoundException(final String name, final Name contextName) {
        return NamingLogger.ROOT_LOGGER.nameNotFoundInContext(name, contextName);
    }

public static NameNotFoundException nameNotFoundException ( final String name , final Name contextName ) { return NamingLogger . ROOT_LOGGER . nameNotFoundInContext ( name , contextName ) ; }

Create a name-not-found exception.

@param name the name
@param contextName the context name
@return the exception


public static NamingException namingException(final String message, final Throwable cause) {
        final NamingException exception = new NamingException(message);
        if (cause != null) exception.initCause(cause);
        return exception;
    }

public static NamingException namingException ( final String message , final Throwable cause ) { final NamingException exception = new NamingException ( message ) ; if ( cause != null ) exception . initCause ( cause ) ; return exception ; }

Return a general naming exception with a root cause.

@param message the message
@param cause the exception cause, or {@code null} for none
@return the exception

Return a general naming exception with a root cause .


public static NamingException namingException(final String message, final Throwable cause, final Name remainingName) {
        final NamingException exception = namingException(message, cause);
        exception.setRemainingName(remainingName);
        return exception;
    }

public static NamingException namingException ( final String message , final Throwable cause , final Name remainingName ) { final NamingException exception = namingException ( message , cause ) ; exception . setRemainingName ( remainingName ) ; return exception ; }

Return a general naming exception with a root cause and a remaining name field.

@param message the message
@param cause the exception cause, or {@code null} for none
@param remainingName the remaining name
@return the exception

Return a general naming exception with a root cause and a remaining name field .


public static CannotProceedException cannotProceedException(final Object resolvedObject, final Name remainingName) {
        final CannotProceedException cpe = new CannotProceedException();
        cpe.setResolvedObj(resolvedObject);
        cpe.setRemainingName(remainingName);
        return cpe;
    }

public static CannotProceedException cannotProceedException ( final Object resolvedObject , final Name remainingName ) { final CannotProceedException cpe = new CannotProceedException ( ) ; cpe . setResolvedObj ( resolvedObject ) ; cpe . setRemainingName ( remainingName ) ; return cpe ; }

Return a cannot-proceed exception.

@param resolvedObject the resolved object
@param remainingName the remaining name
@return the exception


public static <T> NamingEnumeration<T> namingEnumeration(final Collection<T> collection) {
        final Iterator<T> iterator = collection.iterator();
        return new NamingEnumeration<T>() {
            public T next() {
                return nextElement();
            }

            public boolean hasMore() {
                return hasMoreElements();
            }

            public void close() {
            }

            public boolean hasMoreElements() {
                return iterator.hasNext();
            }

            public T nextElement() {
                return iterator.next();
            }
        };
    }

public static < T > NamingEnumeration < T > namingEnumeration ( final Collection < T > collection ) { final Iterator < T > iterator = collection . iterator ( ) ; return new NamingEnumeration < T > ( ) { public T next ( ) { return nextElement ( ) ; } public boolean hasMore ( ) { return hasMoreElements ( ) ; } public void close ( ) { } public boolean hasMoreElements ( ) { return iterator . hasNext ( ) ; } public T nextElement ( ) { return iterator . next ( ) ; } } ; }

Return a naming enumeration over a collection.

@param collection the collection
@param <T> the member type
@return the enumeration

Return a naming enumeration over a collection .


public static void rebind(final Context ctx, final String name, final Object value) throws NamingException {
       final Name n = ctx.getNameParser("").parse(name);
       rebind(ctx, n, value);
    }

public static void rebind ( final Context ctx , final String name , final Object value ) throws NamingException { final Name n = ctx . getNameParser ( "" ) . parse ( name ) ; rebind ( ctx , n , value ) ; }

Rebind val to name in ctx, and make sure that all intermediate contexts exist

@param ctx the parent JNDI Context under which value will be bound
@param name the name relative to ctx where value will be bound
@param value the value to bind.
@throws NamingException for any error

Rebind val to name in ctx and make sure that all intermediate contexts exist


protected final T getActiveMQComponentControl(final OperationContext context, final ModelNode operation, final boolean forWrite) throws OperationFailedException {
        final ServiceName artemisServiceName = MessagingServices.getActiveMQServiceName(PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
        ServiceController<?> artemisService = context.getServiceRegistry(forWrite).getService(artemisServiceName);
        ActiveMQServer server = ActiveMQServer.class.cast(artemisService.getValue());
        PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
         T control = getActiveMQComponentControl(server, address);
         if (control == null) {
             throw ControllerLogger.ROOT_LOGGER.managementResourceNotFound(address);
         }
         return control;

    }

protected final T getActiveMQComponentControl ( final OperationContext context , final ModelNode operation , final boolean forWrite ) throws OperationFailedException { final ServiceName artemisServiceName = MessagingServices . getActiveMQServiceName ( PathAddress . pathAddress ( operation . get ( ModelDescriptionConstants . OP_ADDR ) ) ) ; ServiceController < ? > artemisService = context . getServiceRegistry ( forWrite ) . getService ( artemisServiceName ) ; ActiveMQServer server = ActiveMQServer . class . cast ( artemisService . getValue ( ) ) ; PathAddress address = PathAddress . pathAddress ( operation . require ( OP_ADDR ) ) ; T control = getActiveMQComponentControl ( server , address ) ; if ( control == null ) { throw ControllerLogger . ROOT_LOGGER . managementResourceNotFound ( address ) ; } return control ; }

Gets the runtime ActiveMQ control object that can help service this request.

@param context  the operation context
@param operation the operation
@param forWrite {@code true} if this operation will modify the runtime; {@code false} if not.
@return the control object
@throws OperationFailedException

Gets the runtime ActiveMQ control object that can help service this request .