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.mirth.connect.server.servlets.WebStartServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    try {//w  ww.  ja v a 2s .c om
        response.setContentType("application/x-java-jnlp-file");
        response.setHeader("Pragma", "no-cache");
        PrintWriter out = response.getWriter();
        Document jnlpDocument = null;

        if (request.getServletPath().equals("/webstart.jnlp") || request.getServletPath().equals("/webstart")) {
            jnlpDocument = getAdministratorJnlp(request);
        } else if (request.getServletPath().equals("/webstart/extensions")) {
            String extensionPath = StringUtils.removeEnd(StringUtils.removeStart(request.getPathInfo(), "/"),
                    ".jnlp");
            jnlpDocument = getExtensionJnlp(extensionPath);
        }

        DocumentSerializer docSerializer = new DocumentSerializer(true);
        docSerializer.toXML(jnlpDocument, out);
    } catch (RuntimeIOException rio) {
        logger.debug(rio);
    } catch (Throwable t) {
        logger.error(ExceptionUtils.getStackTrace(t));
        throw new ServletException(t);
    }
}

From source file:cc.vidr.servlet.DatumImportServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    try {//from w  w  w. j a  v a  2s. c  o  m
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(req);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField())
                continue;
            String filename = item.getName();
            if (filename.isEmpty())
                continue;
            InputStream stream = item.openStream();
            resp.getWriter().println("<p>");
            try {
                resp.getWriter().println("Loading '" + filename + "'... ");
                Program program = new Program(stream);
                program.parse();
                program.assertFacts(Server.factDatabase);
                program.assertRules(Server.ruleDatabase);
                resp.getWriter().println("OK");
            } catch (RecognitionException e) {
                resp.getWriter().println("Malformed input: " + e.getMessage());
            } catch (UnsafeException e) {
                resp.getWriter().println("Unsafe rule or non-ground fact encountered: " + e.getMessage());
            } catch (IOException e) {
                resp.getWriter().println("Error opening file: " + e.getMessage());
            }
            resp.getWriter().println("</p>");
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    doGet(req, resp);
}

From source file:cpabe.controladores.UploadDownloadFileServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from w  ww .  j  a v  a 2  s .c  om

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/formularios/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:com.lti.system.MyLogoutFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }/*w  w w  . j a  v a 2s .c  om*/

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (requiresLogout(httpRequest, httpResponse)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (logger.isDebugEnabled()) {
            logger.debug("Logging out user '" + auth + "' and redirecting to logout page");
        }

        for (int i = 0; i < handlers.length; i++) {
            handlers[i].logout(httpRequest, httpResponse, auth);
        }

        Cookie cookie = new Cookie("jforumSSOCookie", null);
        cookie.setMaxAge(0);
        cookie.setPath("/jforum");
        httpResponse.addCookie(cookie);

        cookie = new Cookie("jforumSSOGroupCookie", null);
        cookie.setMaxAge(0);
        cookie.setPath("/jforum");
        httpResponse.addCookie(cookie);

        request.removeAttribute("legalDate");

        sendRedirect(httpRequest, httpResponse, logoutSuccessUrl);

        return;
    }

    chain.doFilter(request, response);
}

From source file:com.bluexml.xforms.actions.SubmitAction.java

@Override
protected void afterSubmit() throws ServletException {
    String url = StringUtils.trimToNull(initParams.get(MsgId.PARAM_NEXT_PAGE_SUBMIT.getText()));

    if (url == null) { // #1656
        // there may be something specified in the Xtension property of this form
        url = controller.getXtensionNextPageSubmit(currentPage.getFormName(), currentPage.getFormType());
    }//from w ww .  ja v a2  s.c  o  m

    // if in search mode, a specific processing applies
    if (isSearching()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting after search mode or search form");
            logger.debug(" --> targetURL:'" + url + "'");
            logger.debug(" --> search string:'" + transactionId + "'");
        }
        if (StringUtils.trimToNull(url) == null) {
            throw new ServletException("No next page was provided for this search.");
        }
        String nextPageURL = url;
        nextPageURL += (url.indexOf('?') == -1) ? "?" : "&";
        nextPageURL += "search=" + transactionId;
        super.redirectClient(nextPageURL);
        return;
    }

    String elementId = transaction.getIds().get(transactionId);
    String extActionResultURL = null;

    // persist data id
    Page currentPage = navigationPath.peekCurrentPage();
    currentPage.setDataId(elementId);
    currentPage.setNode(null);

    // call external action if any
    if (initParams != null) {
        String className = StringUtils.trimToNull(initParams.get(MsgId.PARAM_ACTION_NAME.getText()));
        if ((className != null) && !(className.equals("null"))) {
            extActionResultURL = callExternalAction(className);
        }
    }
    if (StringUtils.trimToNull(extActionResultURL) != null) {
        super.redirectClient(extActionResultURL);
    } else {
        if (StringUtils.trimToNull(url) != null) {
            url = buildRedirectionUrlWithParams(url, currentPage);
            super.redirectClient(url);
        } else {
            // go to previous page
            restorePrevPage(navigationPath, elementId);
            setSubmissionDefaultLocation(getServletURL(), result);
        }
    }
}

From source file:com.autentia.tnt.filter.HibernateSessionRequestFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {//w w w .  j  a  v  a  2 s.  c  om
        log.debug("Starting a database transaction");
        sf.openSession();
        sf.getCurrentSession().beginTransaction();

        // Call the next filter (continue request processing)
        chain.doFilter(request, response);

        // Commit and cleanup
        log.debug("Committing the database transaction");
        if (sf.getCurrentSession().getTransaction().isActive()) {
            sf.getCurrentSession().getTransaction().commit();
        }
        sf.getCurrentSession().close();

    } catch (StaleObjectStateException staleEx) {
        log.error("This interceptor does not implement optimistic concurrency control!");
        log.error("Your application will not work until you add compensation actions!");
        // Rollback, close everything, possibly compensate for any permanent changes
        // during the conversation, and finally restart business conversation. Maybe
        // give the user of the application a chance to merge some of his work with
        // fresh data... what you do here depends on your applications design.
        throw staleEx;
    } catch (Exception ex) {
        // Rollback only
        log.error("Error en doFilter ", ex);
        try {
            if (sf.getCurrentSession().getTransaction().isActive()) {
                log.debug("Trying to rollback database transaction after exception");
                sf.getCurrentSession().getTransaction().rollback();
            }
        } catch (Exception rbEx) {
            log.error("Could not rollback transaction after exception!", rbEx);
        }

        // Let others handle it... maybe another interceptor for exceptions?
        throw new ServletException(ex);
    }
}

From source file:com.vmware.identity.HealthStatusController.java

/**
 * Handle GET request for the health status
 *//*from www. ja v  a  2  s. c o m*/
@RequestMapping(value = "/HealthStatus", method = RequestMethod.GET)
public void getHealthStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    Validate.notNull(request, "HttpServletRequest should not be null.");
    Validate.notNull(response, "HttpServletResponse should not be null.");

    // we are going to be very simple in this request processing for now
    // and just report if we are "reachable"
    // we also do not worry about the sender's identity
    // (in reality CM will include the SAML token in the header,
    // and so generally it means they successfully obtained it through sso ...)
    logger.debug("Handling getHealthStatus HTTP request; method:{} url:{}", request.getMethod(),
            request.getRequestURL());

    try {
        response.setHeader("Content-Type", "application/xml; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8);
        try {
            osw.write(healthStatusXml);
        } finally {
            osw.close();
        }

        logger.debug("Handled getHealthStatus HTTP request; method:{} url:{}", request.getMethod(),
                request.getRequestURL());
    } catch (Exception e) {
        logger.error("Failed to return Health Status with [%s]." + e.toString(), e);
        throw new ServletException(e); // let the exception bubble up and show in the response since this is not user-facing
    }
}

From source file:cpabe.controladores.UploadDownloadFileAdvancedServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*from  w  w w.  j  a v  a2 s  . c om*/

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/avancado/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    this.tmpDir = FileUtils.getTempDirectory();
    if (!this.tmpDir.isDirectory()) {
        throw new ServletException(this.tmpDir.getAbsolutePath() + " is not a directory");
    }/*from   w  w  w . j  ava 2 s. c o  m*/
}

From source file:com.tremolosecurity.proxy.auth.persistentCookie.PersistentCookie.java

private void doWork(HttpServletRequest request, HttpServletResponse response, AuthStep as)
        throws IOException, ServletException {

    as.setExecuted(true);/*from   w  w  w  .ja v  a2s.c o  m*/

    MyVDConnection myvd = cfgMgr.getMyVD();
    //HttpSession session = (HttpSession) req.getAttribute(ConfigFilter.AUTOIDM_SESSION);//((HttpServletRequest) req).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    HttpSession session = ((HttpServletRequest) request).getSession(); //SharedSession.getSharedSession().getSession(req.getSession().getId());
    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    if (holder == null) {
        throw new ServletException("Holder is null");
    }

    RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

    String urlChain = holder.getUrl().getAuthChain();
    AuthChainType act = holder.getConfig().getAuthChains().get(reqHolder.getAuthChainName());

    HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
            .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);

    Attribute attr = authParams.get("cookieName");
    if (attr == null) {
        throw new ServletException("No cookie name specified");
    }

    String cookieName = attr.getValues().get(0);

    boolean useSSLSessionID;
    attr = authParams.get("useSSLSessionID");
    if (attr == null) {
        useSSLSessionID = false;
    } else {
        useSSLSessionID = attr.getValues().get(0).equalsIgnoreCase("true");
    }

    attr = authParams.get("millisToLive");
    if (attr == null) {
        throw new ServletException("No milliseconds to live specified");
    }

    long millisToLive = Long.parseLong(attr.getValues().get(0));

    attr = authParams.get("keyAlias");
    if (attr == null) {
        throw new ServletException("No key name specified");
    }
    String keyAlias = attr.getValues().get(0);

    Cookie authCookie = null;

    if (request.getCookies() == null) {
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equalsIgnoreCase(cookieName)) {
            authCookie = cookie;
            break;
        }
    }

    if (authCookie == null) {
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    com.tremolosecurity.lastmile.LastMile lastmile = new com.tremolosecurity.lastmile.LastMile();

    SecretKey key = this.cfgMgr.getSecretKey(keyAlias);
    if (key == null) {
        throw new ServletException("Secret key '" + keyAlias + "' does not exist");
    }

    try {
        String cookieVal = authCookie.getValue();
        if (cookieVal.startsWith("\"")) {
            cookieVal = cookieVal.substring(1, cookieVal.length() - 1);
        }
        lastmile.loadLastMielToken(cookieVal, key);
    } catch (Exception e) {
        logger.warn("Could not decrypt cookie", e);
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    if (!lastmile.isValid()) {
        logger.warn("Cookie no longer valid");
        as.setSuccess(false);
        holder.getConfig().getAuthManager().nextAuth(request, response, session, false);
        return;
    }

    boolean found = false;
    boolean validip = false;
    boolean validSslSessionId = !useSSLSessionID;
    String dn = null;

    for (Attribute attrib : lastmile.getAttributes()) {
        if (attrib.getName().equalsIgnoreCase("CLIENT_IP")) {
            validip = attrib.getValues().get(0).equals(request.getRemoteAddr());
        } else if (attrib.getName().equalsIgnoreCase("DN")) {
            dn = attrib.getValues().get(0);

        } else if (attrib.getName().equalsIgnoreCase("SSL_SESSION_ID")) {

            Object sessionID = request.getAttribute("javax.servlet.request.ssl_session_id");
            if (sessionID instanceof byte[]) {
                sessionID = new String(Base64.encodeBase64((byte[]) sessionID));
            }

            validSslSessionId = attrib.getValues().get(0).equals(sessionID);

        }
    }

    if (dn != null && validip && validSslSessionId) {
        try {
            LDAPSearchResults res = myvd.search(dn, 0, "(objectClass=*)", new ArrayList<String>());

            if (res.hasMore()) {
                LDAPEntry entry = res.next();

                Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator();
                AuthInfo authInfo = new AuthInfo(entry.getDN(),
                        (String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME), act.getName(),
                        act.getLevel());
                ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo);

                while (it.hasNext()) {
                    LDAPAttribute ldapattr = it.next();
                    attr = new Attribute(ldapattr.getName());
                    String[] vals = ldapattr.getStringValueArray();
                    for (int i = 0; i < vals.length; i++) {
                        attr.getValues().add(vals[i]);
                    }
                    authInfo.getAttribs().put(attr.getName(), attr);
                }

                as.setSuccess(true);

            } else {

                as.setSuccess(false);
            }

        } catch (LDAPException e) {
            if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) {
                logger.error("Could not authenticate user", e);
            }

            as.setSuccess(false);
        }
    } else {
        as.setSuccess(false);
    }

    holder.getConfig().getAuthManager().nextAuth(request, response, session, false);

}