Example usage for javax.servlet ServletException ServletException

List of usage examples for javax.servlet ServletException ServletException

Introduction

In this page you can find the example usage for javax.servlet ServletException ServletException.

Prototype


public ServletException(Throwable rootCause) 

Source Link

Document

Constructs a new servlet exception when the servlet needs to throw an exception and include a message about the "root cause" exception that interfered with its normal operation.

Usage

From source file:be.fedict.eid.idp.sp.protocol.saml2.AuthenticationRequestUtil.java

/**
 * Generates a SAML v2.0 Authentication Request and performs a browser POST
 * to the specified idpDestination.//from  w  ww  .ja  va 2  s  . c o  m
 * 
 * @param issuerName
 *            issuer of the SAML v2.0 AuthnRequest
 * @param idpDestination
 *            required eID IdP destination
 * @param spDestination
 *            Service Provider landing URL where the IdP will post the SAML2
 *            Response to.
 * @param relayState
 *            optional relay state
 * @param spIdentity
 *            optional Service Provider Identity. If specified the
 *            authentication request will be signed.
 * @param response
 *            response used for posting the request to the IdP
 * @param language
 *            optional language hint
 * @return the SAML v2.0 AuthnRequest just sent over.
 * @throws ServletException
 *             something went wrong.
 */
@SuppressWarnings("unchecked")
public static AuthnRequest sendRequest(String issuerName, String idpDestination, String spDestination,
        String relayState, KeyStore.PrivateKeyEntry spIdentity, HttpServletResponse response, String language)
        throws ServletException {

    if (null == idpDestination) {
        throw new ServletException("No IdP Destination specified");
    }
    if (null == spDestination) {
        throw new ServletException("No SP Destination specified");
    }

    LOG.debug("Issuer: " + issuerName);
    LOG.debug("IdP destination: " + idpDestination);
    LOG.debug("SP destination: " + spDestination);
    LOG.debug("relay state: " + relayState);
    LOG.debug("SP identity: " + spIdentity);

    String idpEndpoint = idpDestination;
    if (null != language) {
        idpEndpoint += "?language=" + language;
    }

    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SAMLObjectBuilder<AuthnRequest> requestBuilder = (SAMLObjectBuilder<AuthnRequest>) builderFactory
            .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    AuthnRequest authnRequest = requestBuilder.buildObject();
    authnRequest.setID("authn-request-" + UUID.randomUUID().toString());
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setDestination(idpDestination);
    authnRequest.setAssertionConsumerServiceURL(spDestination);
    authnRequest.setForceAuthn(true);
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);

    SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) builderFactory
            .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerName);
    authnRequest.setIssuer(issuer);

    SAMLObjectBuilder<Endpoint> endpointBuilder = (SAMLObjectBuilder<Endpoint>) builderFactory
            .getBuilder(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    Endpoint samlEndpoint = endpointBuilder.buildObject();
    samlEndpoint.setLocation(idpEndpoint);
    samlEndpoint.setResponseLocation(spDestination);

    OutTransport outTransport = new HttpServletResponseAdapter(response, true);

    BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext();
    messageContext.setOutboundMessageTransport(outTransport);
    messageContext.setPeerEntityEndpoint(samlEndpoint);
    messageContext.setOutboundSAMLMessage(authnRequest);
    messageContext.setRelayState(relayState);

    // sign request if a SP identity is specified
    if (null != spIdentity) {

        List<X509Certificate> certChain = new LinkedList<X509Certificate>();
        for (Certificate certificate : spIdentity.getCertificateChain()) {
            certChain.add((X509Certificate) certificate);
        }

        BasicX509Credential credential = new BasicX509Credential();
        credential.setPrivateKey(spIdentity.getPrivateKey());
        credential.setEntityCertificateChain(certChain);

        // enable adding the cert.chain as KeyInfo
        X509KeyInfoGeneratorFactory factory = (X509KeyInfoGeneratorFactory) org.opensaml.xml.Configuration
                .getGlobalSecurityConfiguration().getKeyInfoGeneratorManager().getDefaultManager()
                .getFactory(credential);
        factory.setEmitEntityCertificateChain(true);

        messageContext.setOutboundSAMLMessageSigningCredential(credential);
    }

    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, Log4JLogChute.class.getName());
    try {
        velocityEngine.init();
    } catch (Exception e) {
        throw new ServletException("velocity engine init error: " + e.getMessage(), e);
    }
    HTTPPostEncoder encoder = new HTTPPostEncoder(velocityEngine, "/templates/saml2-post-binding.vm");
    try {
        encoder.encode(messageContext);
    } catch (MessageEncodingException e) {
        throw new ServletException("SAML encoding error: " + e.getMessage(), e);
    }

    return authnRequest;
}

From source file:nijhof2axon.ui.AutowiringApplicationServlet.java

/**
 * Initialize this servlet./*from  w w  w . j  a  v a2s.c  om*/
 *
 * @throws ServletException if there is no {@link WebApplicationContext} associated with this servlet's context
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    log.debug("finding containing WebApplicationContext");
    try {
        this.webApplicationContext = WebApplicationContextUtils
                .getRequiredWebApplicationContext(config.getServletContext());
    } catch (IllegalStateException e) {
        throw new ServletException("could not locate containing WebApplicationContext");
    }
}

From source file:com.jada.browser.YuiImageBrowser.java

public void init() throws ServletException {
    try {/*ww  w.  j  av  a 2 s.  c om*/
        if (!externalInit) {
            YuiImageBrowser.baseDir = getInitParameter("baseDir");
            String smClassName = getInitParameter("securityMangerClassName");
            if (smClassName != null && smClassName.trim().length() > 0) {
                YuiImageBrowser.securityManager = (SecurityManager) Class.forName(smClassName).newInstance();
            }
            String s = getInitParameter("maxsize");
            if (s != null && s.length() > 0) {
                maxsize = Integer.parseInt(s);
            }
        }
    } catch (InstantiationException e) {
        e.printStackTrace();
        throw new ServletException(e);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        throw new ServletException(e);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new ServletException(e);
    }
}

From source file:de.betterform.agent.web.resources.ResourceServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    if ("false".equals(config.getInitParameter("caching"))) {
        caching = false;//from  w w  w  .ja v  a2 s.c  om
        if (LOG.isTraceEnabled()) {
            LOG.trace("Caching of Resources is disabled");
        }
    } else {
        caching = true;

        if (LOG.isTraceEnabled()) {
            LOG.trace("Caching of Resources is enabled - resources are loaded from classpath");
        }
    }
    this.lastModified = getLastModifiedValue();
    String path = null;
    try {
        path = WebFactory.getRealPath("WEB-INF/classes/META-INF/resources", config.getServletContext());
    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
    if (path != null && new File(path).exists()) {
        exploded = true;
    }

    initMimeTypes();
    initResourceStreamers();
}

From source file:com.liferay.portal.spring.servlet.RemotingServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {/*  w w w  .  j  a  v  a2 s. c om*/
        PortalInstances.getCompanyId(request);

        String remoteUser = request.getRemoteUser();

        if (_log.isDebugEnabled()) {
            _log.debug("Remote user " + remoteUser);
        }

        if (remoteUser != null) {
            PrincipalThreadLocal.setName(remoteUser);

            long userId = GetterUtil.getLong(remoteUser);

            User user = UserLocalServiceUtil.getUserById(userId);

            PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, true);

            PermissionThreadLocal.setPermissionChecker(permissionChecker);
        } else {
            if (_log.isWarnEnabled()) {
                _log.warn("User id is not provided. An exception will be "
                        + "thrown  if a protected method is accessed.");
            }
        }

        super.service(request, response);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.idega.servlet.filter.CacheFilter.java

@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
        throws ServletException {
    HttpServletRequest request = (HttpServletRequest) sRequest;
    HttpServletResponse response = (HttpServletResponse) sResponse;

    if (cacheRequest(request, response)) {
        super.doFilter(sRequest, sResponse, chain);
    } else {//from w w  w. j  av a 2  s  .  c  o m
        try {
            chain.doFilter(sRequest, sResponse);
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }
}

From source file:com.expressui.core.util.SpringApplicationServlet.java

protected final WebApplicationContext getWebApplicationContext() throws ServletException {
    if (webApplicationContext == null) {
        throw new ServletException("init() must be invoked before WebApplicationContext can be retrieved");
    }/*from  w w  w.  ja  v a 2s  .co m*/
    return webApplicationContext;
}

From source file:mitm.djigzo.web.services.security.InvalidateUserSpringSecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("HttpServletRequest expected.");
    }/*from  ww  w  .  j a v a 2s.  c o  m*/

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("HttpServletResponse expected.");
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    String loggedInUserName = null;

    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();

    if (loggedInUser != null) {
        loggedInUserName = loggedInUser.getName();
    }

    if (loggedInUserName != null) {
        String email = StringUtils.trimToNull(request.getParameter(usernameRequestParameter));

        if (email != null) {
            email = EmailAddressUtils.canonicalize(email);

            if (!email.equals(loggedInUserName)) {
                /*
                 * The user has changed, so invalidate session
                 */
                HttpSession session = httpServletRequest.getSession(false);

                if (session != null) {
                    session.invalidate();
                }

                SecurityContextHolder.clearContext();

                /*
                 * We need to 'reload' the complete request to make sure the user need to login
                 */
                StringBuffer redirectURL = httpServletRequest.getRequestURL();

                if (httpServletRequest.getQueryString() != null) {
                    redirectURL.append("?").append(httpServletRequest.getQueryString());
                }

                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(redirectURL.toString()));

                return;
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:io.wcm.wcm.ui.extjs.provider.AbstractPageProvider.java

@Override
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    // determine root resource
    Resource rootResource = getRootResource(request);
    if (rootResource == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from   w  w  w.ja v  a2 s. c  o  m
    }

    response.setContentType(ContentType.JSON);

    try {
        PageFilter pageFilter = getPageFilter(request);
        JSONArray jsonContent = getJsonContent(rootResource, pageFilter);
        response.getWriter().write(jsonContent.toString());
    } catch (Throwable ex) {
        log.error("Unexpected error, rethrow as servlet exception.", ex);
        throw new ServletException(ex);
    }
}

From source file:com.aurel.track.util.PropertiesConfigurationHelper.java

/**
 * Gets the PropertiesConfiguration for a property file from servlet context
 * @param servletContext// w w  w . j  a  v  a 2s  .  c om
 * @param pathWithinContext
 * @param propFile
 * @return
 * @throws ServletException
 */
public static PropertiesConfiguration loadServletContextPropFile(ServletContext servletContext,
        String pathWithinContext, String propFile) throws ServletException {
    PropertiesConfiguration propertiesConfiguration = null;
    InputStream in = null;
    URL propFileURL = null;
    try {
        if (servletContext != null && pathWithinContext != null) {
            if (!pathWithinContext.startsWith("/")) {
                pathWithinContext = "/" + pathWithinContext;
            }
            if (!pathWithinContext.endsWith("/")) {
                pathWithinContext = pathWithinContext + "/";
            }
            propFileURL = servletContext.getResource(pathWithinContext + propFile);
            in = propFileURL.openStream();
            propertiesConfiguration = new PropertiesConfiguration();
            propertiesConfiguration.load(in);
            in.close();
        }
    } catch (Exception e) {
        LOGGER.error("Could not read " + propFile + " from servlet context " + propFileURL == null ? ""
                : propFileURL.toExternalForm() + ". Exiting. " + e.getMessage());
        throw new ServletException(e);
    }
    return propertiesConfiguration;
}