Search in sources :

Example 1 with SecurityRolesMetaData

use of org.jboss.metadata.javaee.spec.SecurityRolesMetaData in project wildfly by wildfly.

the class SimpleSecurityManager method isCallerInRole.

/**
     * @param ejbName              The name of the EJB component where isCallerInRole was invoked.
     * @param incommingMappedRoles The principal vs roles mapping (if any). Can be null.
     * @param roleLinks            The role link map where the key is an alias role name and the value is the collection of
     *                             role names, that alias represents. Can be null.
     * @param roleNames            The role names for which the caller is being checked for
     * @return true if the user is in <b>any</b> one of the <code>roleNames</code>. Else returns false
     */
public boolean isCallerInRole(final String ejbName, final String policyContextID, final Object incommingMappedRoles, final Map<String, Collection<String>> roleLinks, final String... roleNames) {
    final SecurityContext securityContext = doPrivileged(securityContext());
    if (securityContext == null) {
        return false;
    }
    final EJBResource resource = new EJBResource(new HashMap<String, Object>());
    resource.setEjbName(ejbName);
    resource.setPolicyContextID(policyContextID);
    resource.setCallerRunAsIdentity(securityContext.getIncomingRunAs());
    resource.setCallerSubject(securityContext.getUtil().getSubject());
    Principal userPrincipal = securityContext.getUtil().getUserPrincipal();
    resource.setPrincipal(userPrincipal);
    if (roleLinks != null) {
        final Set<SecurityRoleRef> roleRefs = new HashSet<SecurityRoleRef>();
        for (String key : roleLinks.keySet()) {
            Collection<String> values = roleLinks.get(key);
            if (values != null) {
                for (String value : values) roleRefs.add(new SecurityRoleRef(key, value));
            }
        }
        resource.setSecurityRoleReferences(roleRefs);
    }
    Map<String, Set<String>> previousRolesAssociationMap = null;
    try {
        // ensure the security roles association contains the incoming principal x roles map.
        if (incommingMappedRoles != null) {
            SecurityRolesMetaData rolesMetaData = (SecurityRolesMetaData) incommingMappedRoles;
            previousRolesAssociationMap = this.setSecurityRolesAssociation(rolesMetaData.getPrincipalVersusRolesMap());
        }
        AbstractEJBAuthorizationHelper helper = SecurityHelperFactory.getEJBAuthorizationHelper(securityContext);
        for (String roleName : roleNames) {
            if (helper.isCallerInRole(resource, roleName)) {
                return true;
            }
        }
        return false;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        // reset the security roles association state.
        if (incommingMappedRoles != null) {
            this.setSecurityRolesAssociation(previousRolesAssociationMap);
        }
    }
}
Also used : EJBResource(org.jboss.security.authorization.resources.EJBResource) HashSet(java.util.HashSet) Set(java.util.Set) SecurityRolesMetaData(org.jboss.metadata.javaee.spec.SecurityRolesMetaData) SecurityRoleRef(org.jboss.security.javaee.SecurityRoleRef) AbstractEJBAuthorizationHelper(org.jboss.security.javaee.AbstractEJBAuthorizationHelper) SecurityContext(org.jboss.security.SecurityContext) Principal(java.security.Principal) SimplePrincipal(org.jboss.security.SimplePrincipal) HashSet(java.util.HashSet)

Example 2 with SecurityRolesMetaData

use of org.jboss.metadata.javaee.spec.SecurityRolesMetaData in project wildfly by wildfly.

the class WarMetaDataProcessor method deploy.

@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
        // Skip non web deployments
        return;
    }
    WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    assert warMetaData != null;
    boolean isComplete = false;
    WebMetaData specMetaData = warMetaData.getWebMetaData();
    if (specMetaData != null) {
        if (specMetaData instanceof Web25MetaData) {
            isComplete |= ((Web25MetaData) specMetaData).isMetadataComplete();
        } else if (specMetaData instanceof Web30MetaData) {
            isComplete |= ((Web30MetaData) specMetaData).isMetadataComplete();
        } else {
            // As per Servlet 3.0 spec, metadata is not completed unless it's set to true in web.xml.
            // Hence, any web.xml 2.4 or earlier deployment is not metadata completed.
            isComplete = false;
        }
    }
    // Find all fragments that have been processed by deployers, and place
    // them in a map keyed by location
    LinkedList<String> order = new LinkedList<String>();
    List<WebOrdering> orderings = new ArrayList<WebOrdering>();
    HashSet<String> jarsSet = new HashSet<String>();
    Set<VirtualFile> overlays = new HashSet<VirtualFile>();
    Map<String, VirtualFile> scis = new HashMap<String, VirtualFile>();
    boolean fragmentFound = false;
    Map<String, WebFragmentMetaData> webFragments = warMetaData.getWebFragmentsMetaData();
    List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
    for (ResourceRoot resourceRoot : resourceRoots) {
        if (resourceRoot.getRoot().getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) {
            jarsSet.add(resourceRoot.getRootName());
            // Find overlays
            VirtualFile overlay = resourceRoot.getRoot().getChild("META-INF/resources");
            if (overlay.exists()) {
                overlays.add(overlay);
            }
            // Find ServletContainerInitializer services
            VirtualFile sci = resourceRoot.getRoot().getChild("META-INF/services/javax.servlet.ServletContainerInitializer");
            if (sci.exists()) {
                scis.put(resourceRoot.getRootName(), sci);
            }
        }
    }
    if (!isComplete) {
        HashSet<String> jarsWithoutFragmentsSet = new HashSet<String>();
        jarsWithoutFragmentsSet.addAll(jarsSet);
        for (String jarName : webFragments.keySet()) {
            fragmentFound = true;
            WebFragmentMetaData fragmentMetaData = webFragments.get(jarName);
            webFragments.put(jarName, fragmentMetaData);
            WebOrdering webOrdering = new WebOrdering();
            webOrdering.setName(fragmentMetaData.getName());
            webOrdering.setJar(jarName);
            jarsWithoutFragmentsSet.remove(jarName);
            if (fragmentMetaData.getOrdering() != null) {
                if (fragmentMetaData.getOrdering().getAfter() != null) {
                    for (OrderingElementMetaData orderingElementMetaData : fragmentMetaData.getOrdering().getAfter().getOrdering()) {
                        if (orderingElementMetaData.isOthers()) {
                            webOrdering.setAfterOthers(true);
                        } else {
                            webOrdering.addAfter(orderingElementMetaData.getName());
                        }
                    }
                }
                if (fragmentMetaData.getOrdering().getBefore() != null) {
                    for (OrderingElementMetaData orderingElementMetaData : fragmentMetaData.getOrdering().getBefore().getOrdering()) {
                        if (orderingElementMetaData.isOthers()) {
                            webOrdering.setBeforeOthers(true);
                        } else {
                            webOrdering.addBefore(orderingElementMetaData.getName());
                        }
                    }
                }
            }
            orderings.add(webOrdering);
        }
        // fragment specifying no name and no order
        for (String jarName : jarsWithoutFragmentsSet) {
            WebOrdering ordering = new WebOrdering();
            ordering.setJar(jarName);
            orderings.add(ordering);
        }
    }
    if (!fragmentFound) {
        // Drop the order as there is no fragment in the webapp
        orderings.clear();
    }
    // Generate web fragments parsing order
    AbsoluteOrderingMetaData absoluteOrderingMetaData = null;
    if (!isComplete && specMetaData instanceof Web30MetaData) {
        absoluteOrderingMetaData = ((Web30MetaData) specMetaData).getAbsoluteOrdering();
    }
    if (absoluteOrderingMetaData != null) {
        // Absolute ordering from web.xml, any relative fragment ordering is ignored
        int otherPos = -1;
        int i = 0;
        for (OrderingElementMetaData orderingElementMetaData : absoluteOrderingMetaData.getOrdering()) {
            if (orderingElementMetaData.isOthers()) {
                if (otherPos >= 0) {
                    throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidMultipleOthers());
                }
                otherPos = i;
            } else {
                boolean found = false;
                for (WebOrdering ordering : orderings) {
                    if (orderingElementMetaData.getName().equals(ordering.getName())) {
                        order.add(ordering.getJar());
                        jarsSet.remove(ordering.getJar());
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    UndertowLogger.ROOT_LOGGER.invalidAbsoluteOrdering(orderingElementMetaData.getName());
                } else {
                    i++;
                }
            }
        }
        if (otherPos >= 0) {
            order.addAll(otherPos, jarsSet);
            jarsSet.clear();
        }
    } else if (orderings.size() > 0) {
        // Resolve relative ordering
        try {
            resolveOrder(orderings, order);
        } catch (IllegalStateException e) {
            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidRelativeOrdering(), e);
        }
        jarsSet.clear();
    } else {
        // No order specified
        order.addAll(jarsSet);
        jarsSet.clear();
        warMetaData.setNoOrder(true);
    }
    if (UndertowLogger.ROOT_LOGGER.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder();
        builder.append("Resolved order: [ ");
        for (String jar : order) {
            builder.append(jar).append(' ');
        }
        builder.append(']');
        UndertowLogger.ROOT_LOGGER.debug(builder.toString());
    }
    warMetaData.setOrder(order);
    warMetaData.setOverlays(overlays);
    warMetaData.setScis(scis);
    Map<String, WebMetaData> annotationsMetaData = warMetaData.getAnnotationsMetaData();
    // The fragments and corresponding annotations will need to be merged in order
    // For each JAR in the order:
    // - Merge the annotation metadata into the fragment meta data (unless the fragment exists and is meta data complete)
    // - Merge the fragment metadata into merged fragment meta data
    WebCommonMetaData mergedFragmentMetaData = new WebCommonMetaData();
    if (specMetaData == null) {
        // If there is no web.xml, it has to be considered to be the latest version
        specMetaData = new Web31MetaData();
        specMetaData.setVersion("3.1");
    }
    // Augment with meta data from annotations in /WEB-INF/classes
    WebMetaData annotatedMetaData = annotationsMetaData.get("classes");
    if (annotatedMetaData == null && deploymentUnit.hasAttachment(Attachments.OSGI_MANIFEST)) {
        annotatedMetaData = annotationsMetaData.get(deploymentUnit.getName());
    }
    if (annotatedMetaData != null) {
        if (isComplete) {
            // Discard @WebFilter, @WebListener and @WebServlet
            annotatedMetaData.setFilters(null);
            annotatedMetaData.setFilterMappings(null);
            annotatedMetaData.setListeners(null);
            annotatedMetaData.setServlets(null);
            annotatedMetaData.setServletMappings(null);
        }
        WebCommonMetaDataMerger.augment(specMetaData, annotatedMetaData, null, true);
    }
    // Augment with meta data from fragments and annotations from the corresponding JAR
    for (String jar : order) {
        WebFragmentMetaData webFragmentMetaData = webFragments.get(jar);
        if (webFragmentMetaData == null || isComplete) {
            webFragmentMetaData = new WebFragmentMetaData();
            // Add non overriding default distributable flag
            webFragmentMetaData.setDistributable(new EmptyMetaData());
        }
        WebMetaData jarAnnotatedMetaData = annotationsMetaData.get(jar);
        if ((isComplete || webFragmentMetaData.isMetadataComplete()) && jarAnnotatedMetaData != null) {
            // Discard @WebFilter, @WebListener and @WebServlet
            jarAnnotatedMetaData.setFilters(null);
            jarAnnotatedMetaData.setFilterMappings(null);
            jarAnnotatedMetaData.setListeners(null);
            jarAnnotatedMetaData.setServlets(null);
            jarAnnotatedMetaData.setServletMappings(null);
        }
        if (jarAnnotatedMetaData != null) {
            // Merge annotations corresponding to the JAR
            WebCommonMetaDataMerger.augment(webFragmentMetaData, jarAnnotatedMetaData, null, true);
        }
        // Merge fragment meta data according to the conflict rules
        try {
            WebCommonMetaDataMerger.augment(mergedFragmentMetaData, webFragmentMetaData, specMetaData, false);
        } catch (Exception e) {
            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFragment(jar), e);
        }
    }
    // Augment with meta data from annotations from JARs excluded from the order
    for (String jar : jarsSet) {
        WebFragmentMetaData webFragmentMetaData = new WebFragmentMetaData();
        // Add non overriding default distributable flag
        webFragmentMetaData.setDistributable(new EmptyMetaData());
        WebMetaData jarAnnotatedMetaData = annotationsMetaData.get(jar);
        if (jarAnnotatedMetaData != null) {
            // Discard @WebFilter, @WebListener and @WebServlet
            jarAnnotatedMetaData.setFilters(null);
            jarAnnotatedMetaData.setFilterMappings(null);
            jarAnnotatedMetaData.setListeners(null);
            jarAnnotatedMetaData.setServlets(null);
            jarAnnotatedMetaData.setServletMappings(null);
        }
        if (jarAnnotatedMetaData != null) {
            // Merge annotations corresponding to the JAR
            WebCommonMetaDataMerger.augment(webFragmentMetaData, jarAnnotatedMetaData, null, true);
        }
        // Merge fragment meta data according to the conflict rules
        try {
            WebCommonMetaDataMerger.augment(mergedFragmentMetaData, webFragmentMetaData, specMetaData, false);
        } catch (Exception e) {
            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFragment(jar), e);
        }
    }
    WebCommonMetaDataMerger.augment(specMetaData, mergedFragmentMetaData, null, true);
    List<WebMetaData> additional = warMetaData.getAdditionalModuleAnnotationsMetadata();
    if (additional != null && !isComplete) {
        //augument with annotations from additional modules
        for (WebMetaData annotations : additional) {
            // Merge annotations corresponding to the JAR
            WebCommonMetaDataMerger.augment(specMetaData, annotations, null, true);
        }
    }
    // Override with meta data (JBossWebMetaData) Create a merged view
    JBossWebMetaData mergedMetaData = new JBossWebMetaData();
    JBossWebMetaData metaData = warMetaData.getJBossWebMetaData();
    JBossWebMetaDataMerger.merge(mergedMetaData, metaData, specMetaData);
    // FIXME: Incorporate any ear level overrides
    // Use the OSGi Web-ContextPath if not given otherwise
    String contextRoot = mergedMetaData.getContextRoot();
    Manifest manifest = deploymentUnit.getAttachment(Attachments.OSGI_MANIFEST);
    if (contextRoot == null && manifest != null) {
        contextRoot = manifest.getMainAttributes().getValue("Web-ContextPath");
        mergedMetaData.setContextRoot(contextRoot);
    }
    warMetaData.setMergedJBossWebMetaData(mergedMetaData);
    if (mergedMetaData.isMetadataComplete()) {
        MetadataCompleteMarker.setMetadataComplete(deploymentUnit, true);
    }
    //now attach any JNDI binding related information to the deployment
    if (mergedMetaData.getJndiEnvironmentRefsGroup() != null) {
        final DeploymentDescriptorEnvironment bindings = new DeploymentDescriptorEnvironment("java:module/env/", mergedMetaData.getJndiEnvironmentRefsGroup());
        deploymentUnit.putAttachment(org.jboss.as.ee.component.Attachments.MODULE_DEPLOYMENT_DESCRIPTOR_ENVIRONMENT, bindings);
    }
    //override module name if applicable
    if (mergedMetaData.getModuleName() != null && !mergedMetaData.getModuleName().isEmpty()) {
        final EEModuleDescription description = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
        description.setModuleName(mergedMetaData.getModuleName());
    }
    //WFLY-3102 EJB in WAR should inherit WAR's security domain
    if (mergedMetaData.getSecurityDomain() != null) {
        final EEModuleDescription description = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
        description.setDefaultSecurityDomain(mergedMetaData.getSecurityDomain());
    }
    //merge security roles from the ear
    DeploymentUnit parent = deploymentUnit.getParent();
    if (parent != null) {
        final EarMetaData earMetaData = parent.getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA);
        if (earMetaData != null) {
            SecurityRolesMetaData earSecurityRolesMetaData = earMetaData.getSecurityRoles();
            if (earSecurityRolesMetaData != null) {
                if (mergedMetaData.getSecurityRoles() == null) {
                    mergedMetaData.setSecurityRoles(new SecurityRolesMetaData());
                }
                SecurityRolesMetaDataMerger.merge(mergedMetaData.getSecurityRoles(), mergedMetaData.getSecurityRoles(), earSecurityRolesMetaData);
            }
        }
    }
}
Also used : Web25MetaData(org.jboss.metadata.web.spec.Web25MetaData) VirtualFile(org.jboss.vfs.VirtualFile) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) HashMap(java.util.HashMap) EmptyMetaData(org.jboss.metadata.javaee.spec.EmptyMetaData) WarMetaData(org.jboss.as.web.common.WarMetaData) ArrayList(java.util.ArrayList) SecurityRolesMetaData(org.jboss.metadata.javaee.spec.SecurityRolesMetaData) EarMetaData(org.jboss.metadata.ear.spec.EarMetaData) ResourceRoot(org.jboss.as.server.deployment.module.ResourceRoot) EEModuleDescription(org.jboss.as.ee.component.EEModuleDescription) DeploymentDescriptorEnvironment(org.jboss.as.ee.component.DeploymentDescriptorEnvironment) Web30MetaData(org.jboss.metadata.web.spec.Web30MetaData) Web31MetaData(org.jboss.metadata.web.spec.Web31MetaData) HashSet(java.util.HashSet) AbsoluteOrderingMetaData(org.jboss.metadata.web.spec.AbsoluteOrderingMetaData) Manifest(java.util.jar.Manifest) LinkedList(java.util.LinkedList) WebFragmentMetaData(org.jboss.metadata.web.spec.WebFragmentMetaData) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) OrderingElementMetaData(org.jboss.metadata.web.spec.OrderingElementMetaData) WebCommonMetaData(org.jboss.metadata.web.spec.WebCommonMetaData) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) WebMetaData(org.jboss.metadata.web.spec.WebMetaData)

Example 3 with SecurityRolesMetaData

use of org.jboss.metadata.javaee.spec.SecurityRolesMetaData in project wildfly by wildfly.

the class AbstractSecurityMetaDataAccessorEJB method getSecurityRoles.

public SecurityRolesMetaData getSecurityRoles(final Deployment dep) {
    final SecurityRolesMetaData securityRolesMD = new SecurityRolesMetaData();
    Set<String> firstEndpointDeclaredSecurityRoles = null;
    for (final EJBEndpoint ejbEndpoint : getEjbEndpoints(dep)) {
        final Set<String> declaredSecurityRoles = ejbEndpoint.getDeclaredSecurityRoles();
        if (firstEndpointDeclaredSecurityRoles == null) {
            firstEndpointDeclaredSecurityRoles = declaredSecurityRoles;
        } else if (!firstEndpointDeclaredSecurityRoles.equals(declaredSecurityRoles)) {
            WSLogger.ROOT_LOGGER.multipleEndpointsWithDifferentDeclaredSecurityRoles();
        }
        //union of declared security roles from all endpoints...
        for (final String roleName : declaredSecurityRoles) {
            final SecurityRoleMetaData securityRoleMD = new SecurityRoleMetaData();
            securityRoleMD.setRoleName(roleName);
            securityRolesMD.add(securityRoleMD);
        }
    }
    return securityRolesMD;
}
Also used : SecurityRoleMetaData(org.jboss.metadata.javaee.spec.SecurityRoleMetaData) EJBEndpoint(org.jboss.as.webservices.metadata.model.EJBEndpoint) SecurityRolesMetaData(org.jboss.metadata.javaee.spec.SecurityRolesMetaData)

Example 4 with SecurityRolesMetaData

use of org.jboss.metadata.javaee.spec.SecurityRolesMetaData in project wildfly by wildfly.

the class SecurityRolesMergingProcessor method handleDeploymentDescriptor.

@Override
protected void handleDeploymentDescriptor(DeploymentUnit deploymentUnit, DeploymentReflectionIndex deploymentReflectionIndex, Class<?> componentClass, EJBComponentDescription ejbComponentDescription) throws DeploymentUnitProcessingException {
    final SecurityRolesMetaData roleMappings = new SecurityRolesMetaData();
    final EjbJarMetaData ejbJarMetaData = deploymentUnit.getAttachment(EjbDeploymentAttachmentKeys.EJB_JAR_METADATA);
    if (ejbJarMetaData != null) {
        final AssemblyDescriptorMetaData assemblyDescriptorMetaData = ejbJarMetaData.getAssemblyDescriptor();
        if (assemblyDescriptorMetaData != null) {
            // get the mapping between principal to rolename, defined in the assembly descriptor
            final List<SecurityRoleMetaData> securityRoleMetaDatas = assemblyDescriptorMetaData.getAny(SecurityRoleMetaData.class);
            if (securityRoleMetaDatas != null) {
                for (SecurityRoleMetaData securityRoleMetaData : securityRoleMetaDatas) {
                    roleMappings.add(securityRoleMetaData);
                }
            }
        }
    }
    //Let us look at the ear metadata also
    DeploymentUnit parent = deploymentUnit.getParent();
    if (parent != null) {
        final EarMetaData earMetaData = parent.getAttachment(Attachments.EAR_METADATA);
        if (earMetaData != null) {
            SecurityRolesMetaData earSecurityRolesMetaData = earMetaData.getSecurityRoles();
            SecurityRolesMetaDataMerger.merge(roleMappings, roleMappings, earSecurityRolesMetaData);
        }
    }
    // add it to the EJB component description
    ejbComponentDescription.setSecurityRoles(roleMappings);
}
Also used : SecurityRoleMetaData(org.jboss.metadata.javaee.spec.SecurityRoleMetaData) EjbJarMetaData(org.jboss.metadata.ejb.spec.EjbJarMetaData) SecurityRolesMetaData(org.jboss.metadata.javaee.spec.SecurityRolesMetaData) AssemblyDescriptorMetaData(org.jboss.metadata.ejb.spec.AssemblyDescriptorMetaData) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) EarMetaData(org.jboss.metadata.ear.spec.EarMetaData)

Example 5 with SecurityRolesMetaData

use of org.jboss.metadata.javaee.spec.SecurityRolesMetaData in project wildfly by wildfly.

the class WarAnnotationDeploymentProcessor method processAnnotations.

/**
     * Process a single index.
     *
     * @param index the annotation index
     *
     * @throws DeploymentUnitProcessingException
     */
protected WebMetaData processAnnotations(Index index) throws DeploymentUnitProcessingException {
    Web30MetaData metaData = new Web30MetaData();
    // @WebServlet
    final List<AnnotationInstance> webServletAnnotations = index.getAnnotations(webServlet);
    if (webServletAnnotations != null && webServletAnnotations.size() > 0) {
        ServletsMetaData servlets = new ServletsMetaData();
        List<ServletMappingMetaData> servletMappings = new ArrayList<ServletMappingMetaData>();
        for (final AnnotationInstance annotation : webServletAnnotations) {
            ServletMetaData servlet = new ServletMetaData();
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebServletAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            servlet.setServletClass(classInfo.toString());
            AnnotationValue nameValue = annotation.value("name");
            if (nameValue == null || nameValue.asString().isEmpty()) {
                servlet.setName(classInfo.toString());
            } else {
                servlet.setName(nameValue.asString());
            }
            AnnotationValue loadOnStartup = annotation.value("loadOnStartup");
            if (loadOnStartup != null && loadOnStartup.asInt() >= 0) {
                servlet.setLoadOnStartupInt(loadOnStartup.asInt());
            }
            AnnotationValue asyncSupported = annotation.value("asyncSupported");
            if (asyncSupported != null) {
                servlet.setAsyncSupported(asyncSupported.asBoolean());
            }
            AnnotationValue initParamsValue = annotation.value("initParams");
            if (initParamsValue != null) {
                AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray();
                if (initParamsAnnotations != null && initParamsAnnotations.length > 0) {
                    List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>();
                    for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) {
                        ParamValueMetaData initParam = new ParamValueMetaData();
                        AnnotationValue initParamName = initParamsAnnotation.value("name");
                        AnnotationValue initParamValue = initParamsAnnotation.value();
                        if (initParamName == null || initParamValue == null) {
                            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebInitParamAnnotation(target));
                        }
                        AnnotationValue initParamDescription = initParamsAnnotation.value("description");
                        initParam.setParamName(initParamName.asString());
                        initParam.setParamValue(initParamValue.asString());
                        if (initParamDescription != null) {
                            Descriptions descriptions = getDescription(initParamDescription.asString());
                            if (descriptions != null) {
                                initParam.setDescriptions(descriptions);
                            }
                        }
                        initParams.add(initParam);
                    }
                    servlet.setInitParam(initParams);
                }
            }
            AnnotationValue descriptionValue = annotation.value("description");
            AnnotationValue displayNameValue = annotation.value("displayName");
            AnnotationValue smallIconValue = annotation.value("smallIcon");
            AnnotationValue largeIconValue = annotation.value("largeIcon");
            DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString());
            if (descriptionGroup != null) {
                servlet.setDescriptionGroup(descriptionGroup);
            }
            ServletMappingMetaData servletMapping = new ServletMappingMetaData();
            servletMapping.setServletName(servlet.getName());
            List<String> urlPatterns = new ArrayList<String>();
            AnnotationValue urlPatternsValue = annotation.value("urlPatterns");
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            urlPatternsValue = annotation.value();
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            if (urlPatterns.size() > 0) {
                servletMapping.setUrlPatterns(urlPatterns);
                servletMappings.add(servletMapping);
            }
            servlets.add(servlet);
        }
        metaData.setServlets(servlets);
        metaData.setServletMappings(servletMappings);
    }
    // @WebFilter
    final List<AnnotationInstance> webFilterAnnotations = index.getAnnotations(webFilter);
    if (webFilterAnnotations != null && webFilterAnnotations.size() > 0) {
        FiltersMetaData filters = new FiltersMetaData();
        List<FilterMappingMetaData> filterMappings = new ArrayList<FilterMappingMetaData>();
        for (final AnnotationInstance annotation : webFilterAnnotations) {
            FilterMetaData filter = new FilterMetaData();
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFilterAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            filter.setFilterClass(classInfo.toString());
            AnnotationValue nameValue = annotation.value("filterName");
            if (nameValue == null || nameValue.asString().isEmpty()) {
                filter.setName(classInfo.toString());
            } else {
                filter.setName(nameValue.asString());
            }
            AnnotationValue asyncSupported = annotation.value("asyncSupported");
            if (asyncSupported != null) {
                filter.setAsyncSupported(asyncSupported.asBoolean());
            }
            AnnotationValue initParamsValue = annotation.value("initParams");
            if (initParamsValue != null) {
                AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray();
                if (initParamsAnnotations != null && initParamsAnnotations.length > 0) {
                    List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>();
                    for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) {
                        ParamValueMetaData initParam = new ParamValueMetaData();
                        AnnotationValue initParamName = initParamsAnnotation.value("name");
                        AnnotationValue initParamValue = initParamsAnnotation.value();
                        if (initParamName == null || initParamValue == null) {
                            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebInitParamAnnotation(target));
                        }
                        AnnotationValue initParamDescription = initParamsAnnotation.value("description");
                        initParam.setParamName(initParamName.asString());
                        initParam.setParamValue(initParamValue.asString());
                        if (initParamDescription != null) {
                            Descriptions descriptions = getDescription(initParamDescription.asString());
                            if (descriptions != null) {
                                initParam.setDescriptions(descriptions);
                            }
                        }
                        initParams.add(initParam);
                    }
                    filter.setInitParam(initParams);
                }
            }
            AnnotationValue descriptionValue = annotation.value("description");
            AnnotationValue displayNameValue = annotation.value("displayName");
            AnnotationValue smallIconValue = annotation.value("smallIcon");
            AnnotationValue largeIconValue = annotation.value("largeIcon");
            DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString());
            if (descriptionGroup != null) {
                filter.setDescriptionGroup(descriptionGroup);
            }
            filters.add(filter);
            FilterMappingMetaData filterMapping = new FilterMappingMetaData();
            filterMapping.setFilterName(filter.getName());
            List<String> urlPatterns = new ArrayList<String>();
            List<String> servletNames = new ArrayList<String>();
            List<DispatcherType> dispatchers = new ArrayList<DispatcherType>();
            AnnotationValue urlPatternsValue = annotation.value("urlPatterns");
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            urlPatternsValue = annotation.value();
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            if (urlPatterns.size() > 0) {
                filterMapping.setUrlPatterns(urlPatterns);
            }
            AnnotationValue servletNamesValue = annotation.value("servletNames");
            if (servletNamesValue != null) {
                for (String servletName : servletNamesValue.asStringArray()) {
                    servletNames.add(servletName);
                }
            }
            if (servletNames.size() > 0) {
                filterMapping.setServletNames(servletNames);
            }
            AnnotationValue dispatcherTypesValue = annotation.value("dispatcherTypes");
            if (dispatcherTypesValue != null) {
                for (String dispatcherValue : dispatcherTypesValue.asEnumArray()) {
                    dispatchers.add(DispatcherType.valueOf(dispatcherValue));
                }
            }
            if (dispatchers.size() > 0) {
                filterMapping.setDispatchers(dispatchers);
            }
            if (urlPatterns.size() > 0 || servletNames.size() > 0) {
                filterMappings.add(filterMapping);
            }
        }
        metaData.setFilters(filters);
        metaData.setFilterMappings(filterMappings);
    }
    // @WebListener
    final List<AnnotationInstance> webListenerAnnotations = index.getAnnotations(webListener);
    if (webListenerAnnotations != null && webListenerAnnotations.size() > 0) {
        List<ListenerMetaData> listeners = new ArrayList<ListenerMetaData>();
        for (final AnnotationInstance annotation : webListenerAnnotations) {
            ListenerMetaData listener = new ListenerMetaData();
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebListenerAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            listener.setListenerClass(classInfo.toString());
            AnnotationValue descriptionValue = annotation.value();
            if (descriptionValue != null) {
                DescriptionGroupMetaData descriptionGroup = getDescriptionGroup(descriptionValue.asString());
                if (descriptionGroup != null) {
                    listener.setDescriptionGroup(descriptionGroup);
                }
            }
            listeners.add(listener);
        }
        metaData.setListeners(listeners);
    }
    // @RunAs
    final List<AnnotationInstance> runAsAnnotations = index.getAnnotations(runAs);
    if (runAsAnnotations != null && runAsAnnotations.size() > 0) {
        AnnotationsMetaData annotations = metaData.getAnnotations();
        if (annotations == null) {
            annotations = new AnnotationsMetaData();
            metaData.setAnnotations(annotations);
        }
        for (final AnnotationInstance annotation : runAsAnnotations) {
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                continue;
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            AnnotationMetaData annotationMD = annotations.get(classInfo.toString());
            if (annotationMD == null) {
                annotationMD = new AnnotationMetaData();
                annotationMD.setClassName(classInfo.toString());
                annotations.add(annotationMD);
            }
            if (annotation.value() == null) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidRunAsAnnotation(target));
            }
            RunAsMetaData runAs = new RunAsMetaData();
            runAs.setRoleName(annotation.value().asString());
            annotationMD.setRunAs(runAs);
        }
    }
    // @DeclareRoles
    final List<AnnotationInstance> declareRolesAnnotations = index.getAnnotations(declareRoles);
    if (declareRolesAnnotations != null && declareRolesAnnotations.size() > 0) {
        SecurityRolesMetaData securityRoles = metaData.getSecurityRoles();
        if (securityRoles == null) {
            securityRoles = new SecurityRolesMetaData();
            metaData.setSecurityRoles(securityRoles);
        }
        for (final AnnotationInstance annotation : declareRolesAnnotations) {
            if (annotation.value() == null) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidDeclareRolesAnnotation(annotation.target()));
            }
            for (String role : annotation.value().asStringArray()) {
                SecurityRoleMetaData sr = new SecurityRoleMetaData();
                sr.setRoleName(role);
                securityRoles.add(sr);
            }
        }
    }
    // @MultipartConfig
    final List<AnnotationInstance> multipartConfigAnnotations = index.getAnnotations(multipartConfig);
    if (multipartConfigAnnotations != null && multipartConfigAnnotations.size() > 0) {
        AnnotationsMetaData annotations = metaData.getAnnotations();
        if (annotations == null) {
            annotations = new AnnotationsMetaData();
            metaData.setAnnotations(annotations);
        }
        for (final AnnotationInstance annotation : multipartConfigAnnotations) {
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidMultipartConfigAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            AnnotationMetaData annotationMD = annotations.get(classInfo.toString());
            if (annotationMD == null) {
                annotationMD = new AnnotationMetaData();
                annotationMD.setClassName(classInfo.toString());
                annotations.add(annotationMD);
            }
            MultipartConfigMetaData multipartConfig = new MultipartConfigMetaData();
            AnnotationValue locationValue = annotation.value("location");
            if (locationValue != null && locationValue.asString().length() > 0) {
                multipartConfig.setLocation(locationValue.asString());
            }
            AnnotationValue maxFileSizeValue = annotation.value("maxFileSize");
            if (maxFileSizeValue != null && maxFileSizeValue.asLong() != -1L) {
                multipartConfig.setMaxFileSize(maxFileSizeValue.asLong());
            }
            AnnotationValue maxRequestSizeValue = annotation.value("maxRequestSize");
            if (maxRequestSizeValue != null && maxRequestSizeValue.asLong() != -1L) {
                multipartConfig.setMaxRequestSize(maxRequestSizeValue.asLong());
            }
            AnnotationValue fileSizeThresholdValue = annotation.value("fileSizeThreshold");
            if (fileSizeThresholdValue != null && fileSizeThresholdValue.asInt() != 0) {
                multipartConfig.setFileSizeThreshold(fileSizeThresholdValue.asInt());
            }
            annotationMD.setMultipartConfig(multipartConfig);
        }
    }
    // @ServletSecurity
    final List<AnnotationInstance> servletSecurityAnnotations = index.getAnnotations(servletSecurity);
    if (servletSecurityAnnotations != null && servletSecurityAnnotations.size() > 0) {
        AnnotationsMetaData annotations = metaData.getAnnotations();
        if (annotations == null) {
            annotations = new AnnotationsMetaData();
            metaData.setAnnotations(annotations);
        }
        for (final AnnotationInstance annotation : servletSecurityAnnotations) {
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidServletSecurityAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            AnnotationMetaData annotationMD = annotations.get(classInfo.toString());
            if (annotationMD == null) {
                annotationMD = new AnnotationMetaData();
                annotationMD.setClassName(classInfo.toString());
                annotations.add(annotationMD);
            }
            ServletSecurityMetaData servletSecurity = new ServletSecurityMetaData();
            AnnotationValue httpConstraintValue = annotation.value();
            List<String> rolesAllowed = new ArrayList<String>();
            if (httpConstraintValue != null) {
                AnnotationInstance httpConstraint = httpConstraintValue.asNested();
                AnnotationValue httpConstraintERSValue = httpConstraint.value();
                if (httpConstraintERSValue != null) {
                    servletSecurity.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpConstraintERSValue.asEnum()));
                }
                AnnotationValue httpConstraintTGValue = httpConstraint.value("transportGuarantee");
                if (httpConstraintTGValue != null) {
                    servletSecurity.setTransportGuarantee(TransportGuaranteeType.valueOf(httpConstraintTGValue.asEnum()));
                }
                AnnotationValue rolesAllowedValue = httpConstraint.value("rolesAllowed");
                if (rolesAllowedValue != null) {
                    for (String role : rolesAllowedValue.asStringArray()) {
                        rolesAllowed.add(role);
                    }
                }
            }
            servletSecurity.setRolesAllowed(rolesAllowed);
            AnnotationValue httpMethodConstraintsValue = annotation.value("httpMethodConstraints");
            if (httpMethodConstraintsValue != null) {
                AnnotationInstance[] httpMethodConstraints = httpMethodConstraintsValue.asNestedArray();
                if (httpMethodConstraints.length > 0) {
                    List<HttpMethodConstraintMetaData> methodConstraints = new ArrayList<HttpMethodConstraintMetaData>();
                    for (AnnotationInstance httpMethodConstraint : httpMethodConstraints) {
                        HttpMethodConstraintMetaData methodConstraint = new HttpMethodConstraintMetaData();
                        AnnotationValue httpMethodConstraintValue = httpMethodConstraint.value();
                        if (httpMethodConstraintValue != null) {
                            methodConstraint.setMethod(httpMethodConstraintValue.asString());
                        }
                        AnnotationValue httpMethodConstraintERSValue = httpMethodConstraint.value("emptyRoleSemantic");
                        if (httpMethodConstraintERSValue != null) {
                            methodConstraint.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpMethodConstraintERSValue.asEnum()));
                        }
                        AnnotationValue httpMethodConstraintTGValue = httpMethodConstraint.value("transportGuarantee");
                        if (httpMethodConstraintTGValue != null) {
                            methodConstraint.setTransportGuarantee(TransportGuaranteeType.valueOf(httpMethodConstraintTGValue.asEnum()));
                        }
                        AnnotationValue rolesAllowedValue = httpMethodConstraint.value("rolesAllowed");
                        rolesAllowed = new ArrayList<String>();
                        if (rolesAllowedValue != null) {
                            for (String role : rolesAllowedValue.asStringArray()) {
                                rolesAllowed.add(role);
                            }
                        }
                        methodConstraint.setRolesAllowed(rolesAllowed);
                        methodConstraints.add(methodConstraint);
                    }
                    servletSecurity.setHttpMethodConstraints(methodConstraints);
                }
            }
            annotationMD.setServletSecurity(servletSecurity);
        }
    }
    return metaData;
}
Also used : DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) SecurityRoleMetaData(org.jboss.metadata.javaee.spec.SecurityRoleMetaData) ArrayList(java.util.ArrayList) SecurityRolesMetaData(org.jboss.metadata.javaee.spec.SecurityRolesMetaData) ServletSecurityMetaData(org.jboss.metadata.web.spec.ServletSecurityMetaData) Descriptions(org.jboss.annotation.javaee.Descriptions) ListenerMetaData(org.jboss.metadata.web.spec.ListenerMetaData) MultipartConfigMetaData(org.jboss.metadata.web.spec.MultipartConfigMetaData) Web30MetaData(org.jboss.metadata.web.spec.Web30MetaData) ServletMetaData(org.jboss.metadata.web.spec.ServletMetaData) DispatcherType(org.jboss.metadata.web.spec.DispatcherType) FilterMappingMetaData(org.jboss.metadata.web.spec.FilterMappingMetaData) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) FilterMetaData(org.jboss.metadata.web.spec.FilterMetaData) RunAsMetaData(org.jboss.metadata.javaee.spec.RunAsMetaData) HttpMethodConstraintMetaData(org.jboss.metadata.web.spec.HttpMethodConstraintMetaData) FiltersMetaData(org.jboss.metadata.web.spec.FiltersMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) ServletsMetaData(org.jboss.metadata.web.spec.ServletsMetaData) AnnotationValue(org.jboss.jandex.AnnotationValue) DescriptionGroupMetaData(org.jboss.metadata.javaee.spec.DescriptionGroupMetaData) AnnotationsMetaData(org.jboss.metadata.web.spec.AnnotationsMetaData) AnnotationMetaData(org.jboss.metadata.web.spec.AnnotationMetaData) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ClassInfo(org.jboss.jandex.ClassInfo)

Aggregations

SecurityRolesMetaData (org.jboss.metadata.javaee.spec.SecurityRolesMetaData)9 SecurityRoleMetaData (org.jboss.metadata.javaee.spec.SecurityRoleMetaData)5 HashSet (java.util.HashSet)4 DeploymentUnit (org.jboss.as.server.deployment.DeploymentUnit)4 EarMetaData (org.jboss.metadata.ear.spec.EarMetaData)3 ArrayList (java.util.ArrayList)2 Set (java.util.Set)2 DeploymentUnitProcessingException (org.jboss.as.server.deployment.DeploymentUnitProcessingException)2 AnnotationInstance (org.jboss.jandex.AnnotationInstance)2 EjbJarMetaData (org.jboss.metadata.ejb.spec.EjbJarMetaData)2 Method (java.lang.reflect.Method)1 Permission (java.security.Permission)1 Principal (java.security.Principal)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Manifest (java.util.jar.Manifest)1 EJBMethodPermission (javax.security.jacc.EJBMethodPermission)1 EJBRoleRefPermission (javax.security.jacc.EJBRoleRefPermission)1