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:com.meltmedia.cadmium.servlets.RedirectFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    Redirect redir = null;/* w  w w  . ja v a2s .  co m*/
    try {
        if (redirect != null && req instanceof HttpServletRequest && resp instanceof HttpServletResponse) {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            String path = request.getRequestURI();
            String queryString = request.getQueryString();
            log.trace("Checking for existing redirect [{}?{}]", path, queryString);
            redir = redirect.requestMatches(path, queryString);
            if (redir != null) {
                String redirectTo = redir.getUrlSubstituted();
                if (StringUtils.isNotBlank(queryString) && !redirectTo.contains("?")) {

                    redirectTo += "?" + queryString;
                    log.debug("adding query string to redirect path: {}", redirectTo);
                }
                response.setHeader("Location", redirectTo);
                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                log.debug("Location response header: {}", redirectTo);
                return;
            }
        } else {
            log.trace("Redirect and/or req and resp are not http");
        }
        try {
            chain.doFilter(req, resp);
        } catch (IOException ioe) {
            log.trace("Failed down stream from redirect filter.", ioe);
            throw ioe;
        } catch (ServletException se) {
            log.trace("Failed down stream from redirect filter.", se);
            throw se;
        } catch (Throwable t) {
            StringWriter str = new StringWriter();
            t.printStackTrace(new PrintWriter(str));
            log.trace("Failed down stream from redirect filter: " + str.toString(), t);
            ServletException se = new ServletException(t);
            throw se;

        }
    } catch (Throwable t) {
        StringWriter str = new StringWriter();
        t.printStackTrace(new PrintWriter(str));
        log.debug("Failed in redirect filter: " + str.toString(), t);
        ServletException se = new ServletException(t);
        throw se;
    }
}

From source file:de.micromata.genome.gwiki.web.GWikiServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    servletPath = config.getInitParameter("servletPath");
    contextPath = config.getInitParameter("contextPath");
    if (contextPath == null) {
        contextPath = config.getServletContext().getContextPath();
    }//from w  w w.ja v  a 2s.c  o  m
    if (daoContext == null) {
        String className = config.getInitParameter(
                "de.micromata.genome.gwiki.model.config.GWikiBootstrapConfigLoader.className");
        if (StringUtils.isBlank(className) == true) {
            throw new ServletException(
                    "de.micromata.genome.gwiki.model.config.GWikiBootstrapConfigLoader.className is not set in ServletConfig for GWikiServlet");
        }
        GWikiBootstrapConfigLoader loader = ClassUtils.createDefaultInstance(className,
                GWikiBootstrapConfigLoader.class);
        daoContext = loader.loadConfig(config);
    }
}

From source file:com.sun.socialsite.web.rest.servlets.ImageServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    if ((defaultImage = config.getInitParameter("default-image")) == null) {
        throw new ServletException("Missing required parameter: default-image");
    }//w w w .  ja  v a2s  .  co  m

    String s;

    s = config.getInitParameter("handle-conditional-get");
    if (s != null)
        handleConditionalGets = Boolean.parseBoolean(s);

    s = config.getInitParameter("image-width");
    if (s != null)
        imageWidth = Integer.parseInt(s);

    s = config.getInitParameter("image-height");
    if (s != null)
        imageHeight = Integer.parseInt(s);
}

From source file:org.dspace.app.webui.cris.controller.json.MyRPJSONController.java

private ResearcherPage getMyResearcherPage(HttpServletRequest request) throws SQLException, ServletException {
    EPerson currUser = getCurrentUser(request);
    if (currUser == null) {
        throw new ServletException(
                "Wrong data or configuration: access to the my rp servlet without a valid user: there is no user logged in");
    }/*from w  w w .jav a  2  s.  com*/

    int id = currUser.getID();
    ResearcherPage rp = applicationService.getResearcherPageByEPersonId(id);
    return rp;
}

From source file:com.qut.middleware.spep.filter.SPEPFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!(servletRequest instanceof HttpServletRequest)) {
        throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$
    }//w  w w  .  j  ava2  s. c  om
    if (!(servletResponse instanceof HttpServletResponse)) {
        throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String resource, decodedResource, requested, redirectURL;
    URL serviceHost;

    ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName);

    // Get servlet context.
    if (spepContext == null) {
        throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Establish SPEPProxy object.
    SPEPProxy spep;
    try {
        spep = Initializer.init(spepContext);
    } catch (Exception e) {
        this.logger.error(
                "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n"
                        + e.getLocalizedMessage());
        throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$
    }

    // Ensure SPEP startup.
    if (!spep.isStarted()) {
        // Don't allow anything to occur if SPEP hasn't started correctly.
        this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty ");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$
    }

    // Get SPEP cookie.
    Cookie spepCookie = null;
    Cookie globalESOECookie = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(spep.getTokenName())) {
                spepCookie = cookie;
                this.logger.debug("Located spep cookie with value of " + spepCookie.getValue());
            }
            if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) {
                globalESOECookie = cookie;
                this.logger
                        .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue());
            }
        }
    }

    // value for re-determining session status after Authz request
    boolean validSession = false;

    // Check SPEP session is valid.
    if (spepCookie != null) {
        String sessionID = spepCookie.getValue();

        this.logger.info("Attempting to retrieve data for session with ID of " + sessionID);
        PrincipalSession PrincipalSession = spep.verifySession(sessionID);

        if (PrincipalSession != null) {
            this.logger.info("Located session with ID of " + sessionID);

            if (request.getSession().getAttribute(ATTRIBUTES) == null) {
                // over write with new data if it exists
                WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>();
                attributeMap.putAll(PrincipalSession.getAttributes());
                attributeMap.close();

                request.getSession().setAttribute(ATTRIBUTES, attributeMap);
                request.getSession().setAttribute(SPEP_SESSIONID, sessionID);
            }

            /*
             * This section of code is critical, we must pass the PEP an exact representation of what the user is
             * attempting to access additionally the PEP expects that the string is not in encoded form as it will
             * do exact matching, so we decode before passing our request to it.
             */
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource);

            // the authz processor may destroy the session if the PDP determines that the client
            // session is no longer valid, so we have to check it again
            if ((PrincipalSession = spep.verifySession(sessionID)) != null)
                validSession = true;

            if (validSession) {
                if (authzDecision == SPEPProxy.decision.permit) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was permissable");
                    chain.doFilter(request, response);
                    return;
                } else if (authzDecision == SPEPProxy.decision.deny) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was denied, forcing response of"
                            + HttpServletResponse.SC_FORBIDDEN);
                    response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN);
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else if (authzDecision == SPEPProxy.decision.error) {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was in error, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$
                } else {
                    this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource "
                            + decodedResource + " was undetermined, forcing response of"
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$
                }
            }
        }

        /* Clear the local session object the supplied request is invalid */
        this.logger.debug("Invalidating session for ID of " + sessionID);
        request.getSession().invalidate();
    }

    /*
     * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the
     * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have
     * come back to the SPEP since logging out.
     */
    List<Cookie> clearCookies = new Vector<Cookie>();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (spep.getLogoutClearCookies() != null) {
                for (Cookie clearCookie : spep.getLogoutClearCookies()) {
                    if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) {
                        Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone();
                        clearCookieCloneInsecure.setMaxAge(0);
                        clearCookieCloneInsecure.setSecure(false);

                        clearCookies.add(clearCookieCloneInsecure);

                        // Don't need to process the inner loop again for this cookie.
                        break;
                    }
                }
            }
        }
    }

    /* Add the cookies to be cleared into the response object. */
    for (Cookie c : clearCookies)
        response.addCookie(c);

    /*
     * Remove any principal object details which may be in the session, this state can occur if the user has removed
     * their spepSession cookie but retained their jsessionid cookie
     */
    request.getSession().removeAttribute(ATTRIBUTES);

    /*
     * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered
     * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the
     * logical reasons below they will be forced to authenticate.
     */
    if (spep.isLazyInit()) {
        this.logger.info(
                "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP");

        /*
         * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the
         * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out
         * if user is accessing something that has been configured to force a session to be established before it is
         * accessible
         */
        if (globalESOECookie == null) {
            this.logger.debug("globalESOECookie was not set for this request");

            boolean matchedLazyInitResource = false;
            resource = request.getRequestURI();
            if (request.getQueryString() != null)
                resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$

            decodedResource = decode(resource);

            for (String lazyInitResource : spep.getLazyInitResources()) {
                if (decodedResource.matches(lazyInitResource)) {
                    matchedLazyInitResource = true;
                    this.logger.info("Lazy session init attempt matched initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
                } else
                    this.logger.debug("Lazy session init attempt failed to match initialization query of "
                            + lazyInitResource + " from request of " + decodedResource);
            }

            // If we still have no reason to engage spep functionality for this request let the request pass
            if (matchedLazyInitResource) {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            } else {
                if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) {
                    this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource
                            + " could be determined due to lazyInit, forwarding request to application");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }
    }

    /*
     * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment
     * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically
     */
    this.logger.debug("Failed all avenues to provide access to content");
    if (request.getQueryString() != null)
        requested = request.getRequestURI() + "?" + request.getQueryString();
    else
        requested = request.getRequestURI();

    /*
     * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to
     * the local node.
     */
    serviceHost = new URL(spep.getServiceHost());

    String ssoRedirect = spep.getSsoRedirect();
    String timestampParameter;
    if (ssoRedirect.indexOf('?') > -1) {
        timestampParameter = "&ts=" + System.currentTimeMillis();
    } else {
        timestampParameter = "?ts=" + System.currentTimeMillis();
    }

    if (request.getServerName().equals(serviceHost.getHost())) {
        /* Ensures that SSL offloading in Layer 7 environments is correctly handled */
        requested = spep.getServiceHost() + requested;
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    } else {
        String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes()));
        redirectURL = MessageFormat.format(spep.getSsoRedirect(),
                new Object[] { base64RequestURI + timestampParameter });
    }

    this.logger.debug("Redirecting to " + redirectURL + " to establish secure session");
    response.sendRedirect(redirectURL);
}

From source file:eionet.gdem.web.struts.remoteapi.ConvertJson2XmlAction.java

/**
 * The purpose of this action is to execute <code>Json</code> static methods to convert json string or URL to XML format. The
 * method expects either url or json parameters.
 *//*from   w  w w .ja va2  s.  com*/
@Override
public ActionForward execute(ActionMapping map, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse httpServletResponse) throws ServletException {

    String jsonParam = null;

    Map params = request.getParameterMap();
    try {
        // parse request parameters
        if (params.containsKey(JSON_PARAM_NAME)) {
            jsonParam = ((String[]) params.get(JSON_PARAM_NAME))[0];
        }
        if (Utils.isNullStr(jsonParam)) {
            throw new GDEMException("Missing request parameter: " + JSON_PARAM_NAME);
        }
        String xml = "";
        if (jsonParam.startsWith("http:")) {
            // append other parameters to service Url
            if (params.size() > 1) {
                jsonParam = getJsonServiceUrl(jsonParam, params);
            }
            xml = Json.jsonRequest2xmlString(jsonParam);
        } else {
            xml = Json.jsonString2xml(jsonParam);
        }
        // set response properties
        httpServletResponse.setContentType("text/xml");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentLength(xml.length());

        // write data into response
        httpServletResponse.getOutputStream().write(xml.getBytes());
    } catch (GDEMException ge) {
        ge.printStackTrace();
        LOGGER.error("Unable to convert JSON to XML. " + ge.toString());
        throw new ServletException(ge);
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Unable to convert JSON to XML. ");
        throw new ServletException(e);
    } finally {
        try {
            httpServletResponse.getOutputStream().close();
            httpServletResponse.getOutputStream().flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw new ServletException(ioe);
        }
    }

    // Do nothing, then response is already sent.
    return null;
}

From source file:DbServletTrans.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Connection conn = null;//from   ww w.j  a v  a  2 s .c om
    Statement stmt = null;

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Using transactions</title></head><body>");
    out.println("<h2>These SQL statements are part of a transaction</h2>");
    out.println("CallableStatement.executeUpdate()");
    out.println("<br><br>");
    out.println("Statement.executeUpdate()");
    out.println("<br><br>");

    try {

        conn = pool.getConnection();

        out.println("AutoCommit before setAutoCommit(): " + conn.getAutoCommit() + "<br><br>");

        out.println("Transaction isolation level: ");

        switch (conn.getTransactionIsolation()) {

        case 0:
            out.println("TRANSACTION_NONE<br><br>");
            break;
        case 1:
            out.println("TRANSACTION_READ_UNCOMMITTED<br><br>");
            break;
        case 2:
            out.println("TRANSACTION_READ_COMMITTED<br><br>");
            break;
        case 4:
            out.println("TRANSACTION_REPEATABLE_READ<br><br>");
            break;
        case 8:
            out.println("TRANSACTION_SERIALIZABLE<br><br>");
            break;
        default:
            out.println("UNKNOWN<br><br>");

        }
        conn.setAutoCommit(false);

        CallableStatement cs = null;

        //Create an instance of the CallableStatement
        cs = conn.prepareCall("{call addEvent (?,?,?)}");

        cs.setString(1, "Salisbury Beach 5-Miler");
        cs.setString(2, "Salisbury MA");
        cs.setString(3, "14-Aug-2003");

        //Call the inherited PreparedStatement.executeUpdate() method
        cs.executeUpdate();

        String sql = "update raceevent set racedate='13-Aug-2003' " + "where name='Salisbury Beach 5-Miler'";

        int res = 0;

        stmt = conn.createStatement();

        res = stmt.executeUpdate(sql);

        //commit the two SQL statements
        conn.commit();

    } catch (Exception e) {

        try {
            //rollback the transaction in case of a problem
            conn.rollback();

        } catch (SQLException sqle) {
        }

        throw new ServletException(e.getMessage());

    } finally {

        try {

            if (stmt != null)
                stmt.close();

            if (conn != null)
                conn.close();//this returns the Connection to the
                             // Connection pool

        } catch (SQLException sqle) {
        }

    }
    out.println("</table></body></html>");
    out.close();

}

From source file:info.joseluismartin.gtc.mvc.CacheController.java

/**
 * Parse request and create a new Tile./*from  w w  w  .j a va  2s .  com*/
 * Try to find tile in memory cache first, if not found, try to read from disk, if not found,
 * download tile from server and write it to cache.
 * @throws ServletException 
 */
@RequestMapping("/**")
protected void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    UrlPathHelper pathHelper = new UrlPathHelper();
    String requestString = pathHelper.getPathWithinApplication(req);

    if (requestString == null)
        throw new ServletException("The request must include a cache path");

    if (req.getQueryString() != null)
        requestString += "?" + req.getQueryString();

    String cachePath = null;
    String query = null;
    Matcher m = URI_PATTERN.matcher(requestString);

    if (m.find()) {
        cachePath = m.group(1);
        query = pathHelper.decodeRequestString(req, m.group(2));
        if (log.isDebugEnabled()) {
            log.debug("received request: cachePath [" + cachePath + "] query [" + query + "]");
        }
    }

    TileCache cache = cacheService.findCache(cachePath);

    if (cache == null) {
        throw new ServletException("There is not tile cache configured for path [" + cachePath + "]");
    }

    // Have a cache to handle request, now test the tile
    Tile tile = cache.getTile(query);

    String remoteUrlString = cache.getServerUrl(query) + (query.startsWith("?") ? query : "/" + query);
    URL remoteUrl = new URL(remoteUrlString);

    if (tile == null) {
        proxyConnection(req, resp, requestString, cache, remoteUrlString, remoteUrl);
    } else {
        if (tile.isEmpty()) {
            // try three times...
            for (int i = 0; i < 3; i++) {
                try {
                    downloadTile(tile, remoteUrl);
                    break;
                } catch (IOException ioe) {
                    log.error("Error downloading the tile, try: " + i, ioe);
                }
            }
            cache.storeTile(tile);
        }
        // may be still empty
        if (!tile.isEmpty()) {
            resp.setContentType(tile.getMimeType());
            resp.getOutputStream().write(tile.getImage());
        } else {
            throw new ServletException("Cannot download tile: " + tile.toString());
        }
    }
}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Determine if the request has multipart content and if so parse it into a <code>MultipartForm</code> and store
 * it as a request attribute.//from  w  w w  .j  a  v  a2  s  .c o  m
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        boolean isMultipartContent = FileUploadBase.isMultipartContent((HttpServletRequest) request);
        if (isMultipartContent) {
            try {
                parseRequest((HttpServletRequest) request);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw new ServletException(e);
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:net.naijatek.myalumni.framework.spring.MyAlumniStartupServlet.java

protected void initSystem() throws ServletException {
    // Initialize the persistence service

    try {/*from w w  w .  j a v a 2  s.c om*/
        //sched = new MyJobScheduler();

        // Starting the schedular jobs
        //sched.run();

        setupCache();

    } catch (Exception e) {
        logger.fatal("ERROR - in initSystem(), exception is thrown - " + e.toString());
        e.printStackTrace();
        throw new ServletException(e.toString());
    }
}