javax.servlet.annotation.ServletSecurity Java Examples

The following examples show how to use javax.servlet.annotation.ServletSecurity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServletSecurityElement.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Create from an annotation.
 * @param annotation
 * @throws IllegalArgumentException if a method name is specified more than
 */
public ServletSecurityElement(ServletSecurity annotation) {
    this(new HttpConstraintElement(annotation.value().value(),
            annotation.value().transportGuarantee(),
            annotation.value().rolesAllowed()));
    
    List<HttpMethodConstraintElement> l =
        new ArrayList<HttpMethodConstraintElement>();
    HttpMethodConstraint[] constraints = annotation.httpMethodConstraints();
    if (constraints != null) {
        for (int i = 0; i < constraints.length; i++) {
            HttpMethodConstraintElement e =
                new HttpMethodConstraintElement(constraints[i].value(),
                        new HttpConstraintElement(
                                constraints[i].emptyRoleSemantic(),
                                constraints[i].transportGuarantee(),
                                constraints[i].rolesAllowed()));
            l.add(e);
        }
    }
    addHttpMethodConstraints(l);
}
 
Example #2
Source File: ServletSecurityElement.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Create from an annotation.
 * @param annotation Annotation to use as the basis for the new instance
 * @throws IllegalArgumentException if a method name is specified more than
 */
public ServletSecurityElement(ServletSecurity annotation) {
    this(new HttpConstraintElement(annotation.value().value(),
            annotation.value().transportGuarantee(),
            annotation.value().rolesAllowed()));

    List<HttpMethodConstraintElement> l = new ArrayList<>();
    HttpMethodConstraint[] constraints = annotation.httpMethodConstraints();
    if (constraints != null) {
        for (int i = 0; i < constraints.length; i++) {
            HttpMethodConstraintElement e =
                new HttpMethodConstraintElement(constraints[i].value(),
                        new HttpConstraintElement(
                                constraints[i].emptyRoleSemantic(),
                                constraints[i].transportGuarantee(),
                                constraints[i].rolesAllowed()));
            l.add(e);
        }
    }
    addHttpMethodConstraints(l);
}
 
Example #3
Source File: StandardWrapper.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void processServletSecurityAnnotation(Class<?> clazz) {
    // Calling this twice isn't harmful so no syncs
    servletSecurityAnnotationScanRequired = false;

    Context ctxt = (Context) getParent();
    
    if (ctxt.getIgnoreAnnotations()) {
        return;
    }

    ServletSecurity secAnnotation =
        clazz.getAnnotation(ServletSecurity.class);
    if (secAnnotation != null) {
        ctxt.addServletSecurity(
                new ApplicationServletRegistration(this, ctxt),
                new ServletSecurityElement(secAnnotation));
    }
}
 
Example #4
Source File: AuthorizationPreInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public List<SecurityConstraint> getConstraintsFromSecurityAnnotations(ServletContext servletContext, AuthorizationService authorizationService) throws ServletException {
    List<Entry<List<String>, ServletSecurity>> elements = getOptionalAttribute(servletContext, SECURITY_ANNOTATIONS);
    if (elements == null) {
        return null;
    }

    List<SecurityConstraint> constraints = new ArrayList<>();

    for (Entry<List<String>, ServletSecurity> elementEntry : elements) {
        constraints.addAll(ElementsToConstraintsTransformer.createConstraints(
                new HashSet<>(elementEntry.getKey()),
                elementEntry.getValue()));
    }

    return constraints;
}
 
Example #5
Source File: ServletSecurityElement.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an instance from a {@link ServletSecurity} annotation value.
 *
 * @param annotation the annotation value
 *
 * @throws IllegalArgumentException if duplicate method names are
 * detected
 */
public ServletSecurityElement(ServletSecurity annotation) {
    super(annotation.value().value(),
            annotation.value().transportGuarantee(),
            annotation.value().rolesAllowed());
    this.methodConstraints = new HashSet<HttpMethodConstraintElement>();
    for (HttpMethodConstraint constraint :
            annotation.httpMethodConstraints()) {
        this.methodConstraints.add(
            new HttpMethodConstraintElement(
                constraint.value(),
                new HttpConstraintElement(constraint.emptyRoleSemantic(),
                    constraint.transportGuarantee(),
                    constraint.rolesAllowed())));
    }
    methodNames = checkMethodNames(this.methodConstraints);
}
 
Example #6
Source File: ServletSecurityElement.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Create from an annotation.
 * @param annotation
 * @throws IllegalArgumentException if a method name is specified more than
 */
public ServletSecurityElement(ServletSecurity annotation) {
    this(new HttpConstraintElement(annotation.value().value(),
            annotation.value().transportGuarantee(),
            annotation.value().rolesAllowed()));
    
    List<HttpMethodConstraintElement> l =
        new ArrayList<HttpMethodConstraintElement>();
    HttpMethodConstraint[] constraints = annotation.httpMethodConstraints();
    if (constraints != null) {
        for (int i = 0; i < constraints.length; i++) {
            HttpMethodConstraintElement e =
                new HttpMethodConstraintElement(constraints[i].value(),
                        new HttpConstraintElement(
                                constraints[i].emptyRoleSemantic(),
                                constraints[i].transportGuarantee(),
                                constraints[i].rolesAllowed()));
            l.add(e);
        }
    }
    addHttpMethodConstraints(l);
}
 
Example #7
Source File: StandardWrapper.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void processServletSecurityAnnotation(Class<?> clazz) {
    // Calling this twice isn't harmful so no syncs
    servletSecurityAnnotationScanRequired = false;

    Context ctxt = (Context) getParent();
    
    if (ctxt.getIgnoreAnnotations()) {
        return;
    }

    ServletSecurity secAnnotation =
        clazz.getAnnotation(ServletSecurity.class);
    if (secAnnotation != null) {
        ctxt.addServletSecurity(
                new ApplicationServletRegistration(this, ctxt),
                new ServletSecurityElement(secAnnotation));
    }
}
 
Example #8
Source File: ServletSecurityElementTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test constructor.
 */
@Test
public void testConstructor3() {
    HttpConstraintElement httpConstraintElement = new HttpConstraintElement(ServletSecurity.EmptyRoleSemantic.PERMIT);
    ArrayList<HttpMethodConstraintElement> methodConstraints = new ArrayList<>();
    methodConstraints.add(new HttpMethodConstraintElement("HEAD"));
    methodConstraints.add(new HttpMethodConstraintElement("HEAD"));
    assertThrows(IllegalArgumentException.class, () -> new ServletSecurityElement(httpConstraintElement, methodConstraints));
}
 
Example #9
Source File: ServletManager.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static ServletSecurity.TransportGuarantee getTransportGuarantee(String propertyName) {
	AppConstants appConstants = AppConstants.getInstance();
	String constraintType = appConstants.getString(propertyName, null);
	if (StringUtils.isNotEmpty(constraintType))
		return ServletSecurity.TransportGuarantee.valueOf(constraintType);

	String stage = appConstants.getString("dtap.stage", null);
	if (StringUtils.isNotEmpty(stage) && stage.equalsIgnoreCase("LOC")) {
		return ServletSecurity.TransportGuarantee.NONE;
	}
	return ServletSecurity.TransportGuarantee.CONFIDENTIAL;

}
 
Example #10
Source File: SecurityConstraint.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private static SecurityConstraint createConstraint(
        HttpConstraintElement element, String urlPattern, boolean alwaysCreate) {

    SecurityConstraint constraint = new SecurityConstraint();
    SecurityCollection collection = new SecurityCollection();
    boolean create = alwaysCreate;
    
    if (element.getTransportGuarantee() !=
            ServletSecurity.TransportGuarantee.NONE) {
        constraint.setUserConstraint(element.getTransportGuarantee().name());
        create = true;
    }
    if (element.getRolesAllowed().length > 0) {
        String[] roles = element.getRolesAllowed();
        for (String role : roles) {
            constraint.addAuthRole(role);
        }
        create = true;
    }
    if (element.getEmptyRoleSemantic() != EmptyRoleSemantic.PERMIT) {
        constraint.setAuthConstraint(true);
        create = true;
    }
    
    if (create) {
        collection.addPattern(urlPattern);
        constraint.addCollection(collection);
        return constraint;
    }
    
    return null;
}
 
Example #11
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void run() {
    final ServletSecurity security = servletInfo.getServletClass().getAnnotation(ServletSecurity.class);
    if (security != null) {

        ServletSecurityInfo servletSecurityInfo = new ServletSecurityInfo()
                .setEmptyRoleSemantic(security.value().value() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
                .setTransportGuaranteeType(security.value().transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
                .addRolesAllowed(security.value().rolesAllowed());
        for (HttpMethodConstraint constraint : security.httpMethodConstraints()) {
            servletSecurityInfo.addHttpMethodSecurityInfo(new HttpMethodSecurityInfo()
                    .setMethod(constraint.value()))
                    .setEmptyRoleSemantic(constraint.emptyRoleSemantic() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
                    .setTransportGuaranteeType(constraint.transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
                    .addRolesAllowed(constraint.rolesAllowed());
        }
        servletInfo.setServletSecurityInfo(servletSecurityInfo);
    }
    final MultipartConfig multipartConfig = servletInfo.getServletClass().getAnnotation(MultipartConfig.class);
    if (multipartConfig != null) {
        servletInfo.setMultipartConfig(new MultipartConfigElement(multipartConfig.location(), multipartConfig.maxFileSize(), multipartConfig.maxRequestSize(), multipartConfig.fileSizeThreshold()));
    }
    final RunAs runAs = servletInfo.getServletClass().getAnnotation(RunAs.class);
    if (runAs != null) {
        servletInfo.setRunAs(runAs.value());
    }
    final DeclareRoles declareRoles = servletInfo.getServletClass().getAnnotation(DeclareRoles.class);
    if (declareRoles != null) {
        deploymentInfo.addSecurityRoles(declareRoles.value());
    }
    return null;
}
 
Example #12
Source File: SecurityConstraint.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private static SecurityConstraint createConstraint(
        HttpConstraintElement element, String urlPattern, boolean alwaysCreate) {

    SecurityConstraint constraint = new SecurityConstraint();
    SecurityCollection collection = new SecurityCollection();
    boolean create = alwaysCreate;
    
    if (element.getTransportGuarantee() !=
            ServletSecurity.TransportGuarantee.NONE) {
        constraint.setUserConstraint(element.getTransportGuarantee().name());
        create = true;
    }
    if (element.getRolesAllowed().length > 0) {
        String[] roles = element.getRolesAllowed();
        for (String role : roles) {
            constraint.addAuthRole(role);
        }
        create = true;
    }
    if (element.getEmptyRoleSemantic() != EmptyRoleSemantic.PERMIT) {
        constraint.setAuthConstraint(true);
        create = true;
    }
    
    if (create) {
        collection.addPattern(urlPattern);
        constraint.addCollection(collection);
        return constraint;
    }
    
    return null;
}
 
Example #13
Source File: WebAnnotationSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Process the annotations for the servlets.
 *
 * @param context The context which will have its annotations processed
 */
protected static void loadApplicationServletAnnotations(Context context) {

    Container[] children = context.findChildren();
    for (Container child : children) {
        if (child instanceof Wrapper) {

            Wrapper wrapper = (Wrapper) child;
            if (wrapper.getServletClass() == null) {
                continue;
            }

            Class<?> clazz = Introspection.loadClass(context, wrapper.getServletClass());
            if (clazz == null) {
                continue;
            }

            loadClassAnnotation(context, clazz);
            loadFieldsAnnotation(context, clazz);
            loadMethodsAnnotation(context, clazz);

            /* Process RunAs annotation which can be only on servlets.
             * Ref JSR 250, equivalent to the run-as element in
             * the deployment descriptor
             */
            RunAs runAs = clazz.getAnnotation(RunAs.class);
            if (runAs != null) {
                wrapper.setRunAs(runAs.value());
            }

            // Process ServletSecurity annotation
            ServletSecurity servletSecurity = clazz.getAnnotation(ServletSecurity.class);
            if (servletSecurity != null) {
                context.addServletSecurity(
                        new ApplicationServletRegistration(wrapper, context),
                        new ServletSecurityElement(servletSecurity));
            }
        }
    }
}
 
Example #14
Source File: ServletSecurityElementTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test constructor.
 */
@Test
public void testConstructor2() {
    HttpConstraintElement httpConstraintElement = new HttpConstraintElement(ServletSecurity.EmptyRoleSemantic.PERMIT);
    ArrayList<HttpMethodConstraintElement> methodConstraints = new ArrayList<>();
    methodConstraints.add(new HttpMethodConstraintElement("HEAD"));
    ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement, methodConstraints);
    assertEquals(element.getEmptyRoleSemantic(), ServletSecurity.EmptyRoleSemantic.PERMIT);
    assertNotNull(element.getHttpMethodConstraints());
    assertEquals(element.getHttpMethodConstraints().iterator().next().getMethodName(), "HEAD");
}
 
Example #15
Source File: ServletSecurityElementTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test constructor.
 */
@Test
public void testConstructor() {
    HttpConstraintElement httpConstraintElement = new HttpConstraintElement(ServletSecurity.EmptyRoleSemantic.PERMIT);
    ServletSecurityElement element = new ServletSecurityElement(httpConstraintElement);
    assertEquals(element.getEmptyRoleSemantic(), ServletSecurity.EmptyRoleSemantic.PERMIT);
    assertNotNull(element.getHttpMethodConstraints());
}
 
Example #16
Source File: HttpConstraintElementTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test constructor.
 */
@Test
public void testConstructor() {
    HttpConstraintElement element = new HttpConstraintElement(
            ServletSecurity.TransportGuarantee.NONE, "developer");
    assertEquals(element.getEmptyRoleSemantic(), ServletSecurity.EmptyRoleSemantic.PERMIT);
    assertEquals(element.getTransportGuarantee(), ServletSecurity.TransportGuarantee.NONE);
    assertEquals(element.getRolesAllowed()[0], "developer");
}
 
Example #17
Source File: ServletSecurityElement.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param annotation the annotation.
 */
public ServletSecurityElement(ServletSecurity annotation) {
    super(annotation.value().value(), annotation.value().transportGuarantee(), annotation.value().rolesAllowed());
    this.methodConstraints = new HashSet<>();
    for (HttpMethodConstraint constraint : annotation.httpMethodConstraints()) {
        this.methodConstraints.add(new HttpMethodConstraintElement(constraint.value(),
                new HttpConstraintElement(constraint.emptyRoleSemantic(),
                        constraint.transportGuarantee(),
                        constraint.rolesAllowed())));
    }
    methodNames = collectMethodNames(methodConstraints);
}
 
Example #18
Source File: AnnotationScanInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Is this a web annotation.
 *
 * @param annotation the annotation.
 * @return true if it is, false otherwise.
 */
private boolean isWebAnnotation(Annotation annotation) {
    return annotation instanceof WebServlet
            || annotation instanceof WebListener
            || annotation instanceof WebInitParam
            || annotation instanceof WebFilter
            || annotation instanceof ServletSecurity
            || annotation instanceof MultipartConfig;
}
 
Example #19
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public Void run() {
    final ServletSecurity security = servletInfo.getServletClass().getAnnotation(ServletSecurity.class);
    if (security != null) {

        ServletSecurityInfo servletSecurityInfo = new ServletSecurityInfo()
                .setEmptyRoleSemantic(security.value().value() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
                .setTransportGuaranteeType(security.value().transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
                .addRolesAllowed(security.value().rolesAllowed());
        for (HttpMethodConstraint constraint : security.httpMethodConstraints()) {
            servletSecurityInfo.addHttpMethodSecurityInfo(new HttpMethodSecurityInfo()
                    .setMethod(constraint.value()))
                    .setEmptyRoleSemantic(constraint.emptyRoleSemantic() == ServletSecurity.EmptyRoleSemantic.DENY ? SecurityInfo.EmptyRoleSemantic.DENY : SecurityInfo.EmptyRoleSemantic.PERMIT)
                    .setTransportGuaranteeType(constraint.transportGuarantee() == ServletSecurity.TransportGuarantee.CONFIDENTIAL ? TransportGuaranteeType.CONFIDENTIAL : TransportGuaranteeType.NONE)
                    .addRolesAllowed(constraint.rolesAllowed());
        }
        servletInfo.setServletSecurityInfo(servletSecurityInfo);
    }
    final MultipartConfig multipartConfig = servletInfo.getServletClass().getAnnotation(MultipartConfig.class);
    if (multipartConfig != null) {
        servletInfo.setMultipartConfig(new MultipartConfigElement(multipartConfig.location(), multipartConfig.maxFileSize(), multipartConfig.maxRequestSize(), multipartConfig.fileSizeThreshold()));
    }
    final RunAs runAs = servletInfo.getServletClass().getAnnotation(RunAs.class);
    if (runAs != null) {
        servletInfo.setRunAs(runAs.value());
    }
    final DeclareRoles declareRoles = servletInfo.getServletClass().getAnnotation(DeclareRoles.class);
    if (declareRoles != null) {
        deploymentInfo.addSecurityRoles(declareRoles.value());
    }
    return null;
}
 
Example #20
Source File: SecurityConstraint.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private static SecurityConstraint createConstraint(
        HttpConstraintElement element, String urlPattern, boolean alwaysCreate) {

    SecurityConstraint constraint = new SecurityConstraint();
    SecurityCollection collection = new SecurityCollection();
    boolean create = alwaysCreate;

    if (element.getTransportGuarantee() !=
            ServletSecurity.TransportGuarantee.NONE) {
        constraint.setUserConstraint(element.getTransportGuarantee().name());
        create = true;
    }
    if (element.getRolesAllowed().length > 0) {
        String[] roles = element.getRolesAllowed();
        for (String role : roles) {
            constraint.addAuthRole(role);
        }
        create = true;
    }
    if (element.getEmptyRoleSemantic() != EmptyRoleSemantic.PERMIT) {
        constraint.setAuthConstraint(true);
        create = true;
    }

    if (create) {
        collection.addPattern(urlPattern);
        constraint.addCollection(collection);
        return constraint;
    }

    return null;
}
 
Example #21
Source File: ServletSecurityElementTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Test constructor.
 */
@Test
public void testConstructor4() {
    ServletSecurity servletSecurity = new ServletSecurity() {
        @Override
        public HttpMethodConstraint[] httpMethodConstraints() {
            return new HttpMethodConstraint[]{
                new HttpMethodConstraint() {
                    @Override
                    public ServletSecurity.EmptyRoleSemantic emptyRoleSemantic() {
                        return ServletSecurity.EmptyRoleSemantic.PERMIT;
                    }

                    @Override
                    public String[] rolesAllowed() {
                        return new String[]{};
                    }

                    @Override
                    public ServletSecurity.TransportGuarantee transportGuarantee() {
                        return ServletSecurity.TransportGuarantee.NONE;
                    }

                    @Override
                    public String value() {
                        return "HEAD";
                    }

                    @Override
                    public Class<? extends Annotation> annotationType() {
                        throw new UnsupportedOperationException("Not supported yet.");
                    }
                }
            };
        }

        @Override
        public HttpConstraint value() {
            return new HttpConstraint() {
                @Override
                public String[] rolesAllowed() {
                    return new String[]{};
                }

                @Override
                public ServletSecurity.TransportGuarantee transportGuarantee() {
                    return ServletSecurity.TransportGuarantee.NONE;
                }

                @Override
                public ServletSecurity.EmptyRoleSemantic value() {
                    return ServletSecurity.EmptyRoleSemantic.PERMIT;
                }

                @Override
                public Class<? extends Annotation> annotationType() {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            };
        }

        @Override
        public Class<? extends Annotation> annotationType() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };
    ServletSecurityElement servletSecurityElement = new ServletSecurityElement(servletSecurity);
    assertNotNull(servletSecurityElement);
}
 
Example #22
Source File: WebAnnotationInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Class<? extends HttpServlet> getTargetServlet(AnnotationInfo<ServletSecurity> annotationInfo) {
    return (Class<? extends HttpServlet>) annotationInfo.getTargetType();
}
 
Example #23
Source File: ServletManager.java    From iaf with Apache License 2.0 4 votes vote down vote up
public void registerServlet(String servletName, Servlet servletClass, String urlMapping, String[] roles, int loadOnStartup, Map<String, String> initParameters) {
	log.info("instantiating IbisInitializer servlet name ["+servletName+"] servletClass ["+servletClass+"] loadOnStartup ["+loadOnStartup+"]");
	getServletContext().log("instantiating IbisInitializer servlet ["+servletName+"]");


	AppConstants appConstants = AppConstants.getInstance();
	String propertyPrefix = "servlet."+servletName+".";

	if(!appConstants.getBoolean(propertyPrefix+"enabled", true))
		return;

	ServletRegistration.Dynamic serv = getServletContext().addServlet(servletName, servletClass);
	ServletSecurity.TransportGuarantee transportGuarantee = getTransportGuarantee(propertyPrefix+"transportGuarantee");

	String stage = appConstants.getString("dtap.stage", null);
	String[] rolesCopy = new String[0];
	if(roles != null && !stage.equalsIgnoreCase("LOC"))
		rolesCopy = roles;
	String roleNames = appConstants.getString(propertyPrefix+"securityroles", null);
	if(StringUtils.isNotEmpty(roleNames))
		rolesCopy = roleNames.split(",");
	declareRoles(rolesCopy);

	HttpConstraintElement httpConstraintElement = new HttpConstraintElement(transportGuarantee, rolesCopy);
	ServletSecurityElement constraint = new ServletSecurityElement(httpConstraintElement);

	String urlMappingCopy = appConstants.getString(propertyPrefix+"urlMapping", urlMapping);
	if(!urlMappingCopy.startsWith("/") && !urlMappingCopy.startsWith("*")) {
		urlMappingCopy = "/"+urlMappingCopy;
	}
	serv.addMapping(urlMappingCopy);

	int loadOnStartupCopy = appConstants.getInt(propertyPrefix+"loadOnStartup", loadOnStartup);
	serv.setLoadOnStartup(loadOnStartupCopy);
	serv.setServletSecurity(constraint);

	if(initParameters != null && !initParameters.isEmpty()) {
		//Manually loop through the map as serv.setInitParameters will fail all parameters even if only 1 fails...
		for (String key : initParameters.keySet()) {
			String value = initParameters.get(key);
			if(!serv.setInitParameter(key, value)) {
				log("unable to set init-parameter ["+key+"] with value ["+value+"] for servlet ["+servletName+"]", Level.ERROR);
			}
		}
	}

	if(log.isDebugEnabled()) log.debug("registered servlet ["+servletName+"] class ["+servletClass+"] url ["+urlMapping+"] loadOnStartup ["+loadOnStartup+"]");
}
 
Example #24
Source File: ApplicationContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass,
        Servlet servlet, Map<String,String> initParams) throws IllegalStateException {

    if (servletName == null || servletName.equals("")) {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.invalidServletName", servletName));
    }

    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        //TODO Spec breaking enhancement to ignore this restriction
        throw new IllegalStateException(
                sm.getString("applicationContext.addServlet.ise",
                        getContextPath()));
    }

    Wrapper wrapper = (Wrapper) context.findChild(servletName);

    // Assume a 'complete' ServletRegistration is one that has a class and
    // a name
    if (wrapper == null) {
        wrapper = context.createWrapper();
        wrapper.setName(servletName);
        context.addChild(wrapper);
    } else {
        if (wrapper.getName() != null &&
                wrapper.getServletClass() != null) {
            if (wrapper.isOverridable()) {
                wrapper.setOverridable(false);
            } else {
                return null;
            }
        }
    }

    ServletSecurity annotation = null;
    if (servlet == null) {
        wrapper.setServletClass(servletClass);
        Class<?> clazz = Introspection.loadClass(context, servletClass);
        if (clazz != null) {
            annotation = clazz.getAnnotation(ServletSecurity.class);
        }
    } else {
        wrapper.setServletClass(servlet.getClass().getName());
        wrapper.setServlet(servlet);
        if (context.wasCreatedDynamicServlet(servlet)) {
            annotation = servlet.getClass().getAnnotation(ServletSecurity.class);
        }
    }

    if (initParams != null) {
        for (Map.Entry<String, String> initParam: initParams.entrySet()) {
            wrapper.addInitParameter(initParam.getKey(), initParam.getValue());
        }
    }

    ServletRegistration.Dynamic registration =
            new ApplicationServletRegistration(wrapper, context);
    if (annotation != null) {
        registration.setServletSecurity(new ServletSecurityElement(annotation));
    }
    return registration;
}