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:org.jamwiki.authentication.JAMWikiExceptionMessageFilter.java

/**
 *
 *//*from   w w w  . j a  v a 2  s  .c om*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("HttpServletRequest required");
    }
    try {
        chain.doFilter(request, response);
    } catch (AcegiSecurityException ex) {
        handleException(request, ex);
        throw ex;
    } catch (ServletException ex) {
        if (ex.getRootCause() instanceof AcegiSecurityException) {
            handleException(request, (AcegiSecurityException) ex.getRootCause());
        }
        throw ex;
    }
}

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

public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    this.spepContextName = filterConfig.getInitParameter(SPEP_CONTEXT_PARAM_NAME);

    if (this.spepContextName == null)
        throw new ServletException(Messages.getString("SPEPFilter.8") + SPEP_CONTEXT_PARAM_NAME); //$NON-NLS-1$
}

From source file:com.sun.identity.provider.springsecurity.OpenSSOAuthenticationEntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        request = HttpUtil.unwrapOriginalHttpServletRequest(httpRequest);
        redirectToLoginUrl(httpRequest, httpResponse);
    } else {/* w w w . j a va 2s  .  c o  m*/
        debug.error("Request: " + request.getClass() + " Response: " + response.getClass());
        throw new ServletException("Handles only HttpServletRequest/Response");
    }
}

From source file:com.earldouglas.filtre.Filtre.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    boolean accessGranted = false;
    try {/*  w  w  w .j a v  a 2 s  .co m*/
        accessGranted = addressManager.isAccessPermitted(servletRequest.getRemoteAddr());
    } catch (AddressFormatException addressFormatException) {
        throw new ServletException(addressFormatException);
    } finally {
        logResult(servletRequest, accessGranted);
        if (accessGranted) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}

From source file:edu.morgan.server.UploadFileServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    RequestDispatcher rd;//  w w w.  j  a  v  a2 s  .  c o m
    response.setContentType("text/html");

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        rd = request.getRequestDispatcher("fail.jsp");
        rd.forward(request, response);
    }

    try {
        ServletFileUpload upload = new ServletFileUpload();
        response.setContentType("text/plain");

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            this.read(stream);
        }

        rd = request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);

    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:org.soulwing.cas.filter.FilterToBeanProxy.java

private Filter getTargetBean(ApplicationContext appContext, String beanName) throws ServletException {
    if (appContext.containsBean(beanName)) {
        Object bean = appContext.getBean(beanName);
        if (bean instanceof Filter) {
            return (Filter) bean;
        } else {//from  w  w  w  .jav  a2  s  . c om
            throw new ServletException(bean.getClass().getCanonicalName() + MUST_IMPLEMENT_FILTER);
        }
    } else {
        throw new ServletException(beanName + BEAN_NOT_FOUND);
    }
}

From source file:dk.clarin.tools.rest.upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    response.setStatus(200);/*from w w w .  j av a2 s  .  c  om*/
    if (!BracMat.loaded()) {
        response.setStatus(500);
        throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason());
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
    *Set the size threshold, above which content will be stored on disk.
    */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    String arg = "(method.POST)"; // bj 20120801 "(action.POST)";

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
        * Parse the request
        */
        @SuppressWarnings("unchecked")
        List<FileItem> items = (List<FileItem>) uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        FileItem theFile = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
            * Handle Form Fields.
            */
            if (item.isFormField()) {
                // We need the job parameter that indirectly tells us what local file name to give to the uploaded file.
                arg = arg + " (\"" + workflow.escape(item.getFieldName()) + "\".\""
                        + workflow.escape(item.getString()) + "\")";
            } else if (item.getName() != "") {
                //Handle Uploaded file.
                if (theFile != null) {
                    response.setStatus(400);
                    /**
                     * getStatusCode$
                     *
                     * Given a HTTP status code and an informatory text, return an HTML-file
                     * with a heading containing the status code and the official short description
                     * of the status code, a paragraph containing the informatory text and a 
                     * paragraph displaying a longer text explaining the code (From wikipedia).
                     * 
                     * This function could just as well have been written in Java.
                     */
                    String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"Too many files uploaded\")");
                    out.println(messagetext);
                    return;
                }
                theFile = item;
            }
        }
        if (theFile != null) {
            /*
            * Write file to the ultimate location.
            */
            /**
             * upload$
             *
             * Make a waiting job non-waiting upon receipt of a result from an 
             * asynchronous tool.
             *
             * Analyze the job parameter. It tells to which job the sent file belongs.
             * The jobs table knows the file name and location for the uploaded file.
             *              (Last field)
             * Input:
             *      List of HTTP request parameters.
             *      One of the parameters must be (job.<jobNr>-<jobID>)
             *
             * Output:
             *      The file name that must be given to the received file when saved in
             *      the staging area.
             *
             * Status codes:
             *      200     ok
             *      400     'job' parameter does not contain hyphen '-' or
             *              'job' parameter missing altogether.
             *      404     Job is not expecting a result (job is not waiting)
             *              Job is unknown
             *      500     Job list could not be read
             *
             * Affected tables:
             *      jobs.table
             */
            String LocalFileName = BracMat.Eval("upload$(" + arg + ")");
            if (LocalFileName == null) {
                response.setStatus(404);
                String messagetext = BracMat
                        .Eval("getStatusCode$(\"404\".\"doPost:" + workflow.escape(LocalFileName) + "\")");
                out.println(messagetext);
            } else if (LocalFileName.startsWith("HTTP-status-code")) {
                /**
                 * parseStatusCode$
                 *
                 * Find the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String statusCode = BracMat
                        .Eval("parseStatusCode$(\"" + workflow.escape(LocalFileName) + "\")");
                response.setStatus(Integer.parseInt(statusCode));
                /**
                 * parsemessage$
                 *
                 * Find the text following the number greater than 100 immediately following the string 
                 * 'HTTP-status-code'
                 */
                String messagetext = BracMat.Eval("parsemessage$(\"" + workflow.escape(LocalFileName) + "\")");
                messagetext = BracMat.Eval("getStatusCode$(\"" + workflow.escape(statusCode) + "\".\""
                        + workflow.escape(messagetext) + "\")");
                out.println(messagetext);
            } else {
                File file = new File(destinationDir, LocalFileName);
                try {
                    theFile.write(file);
                } catch (Exception ex) {
                    response.setStatus(500);
                    String messagetext = BracMat
                            .Eval("getStatusCode$(\"500\".\"Tools cannot save uploaded file to "
                                    + workflow.escape(destinationDir + LocalFileName) + "\")");
                    out.println(messagetext);
                    return;
                }
                /**
                 * uploadJobNr$
                 *
                 * Return the string preceding the hyphen in the input.
                 *
                 * Input: <jobNr>-<jobID>
                 */
                String JobNr = BracMat.Eval("uploadJobNr$(" + arg + ")");
                Runnable runnable = new workflow(JobNr, destinationDir);
                Thread thread = new Thread(runnable);
                thread.start();
                response.setStatus(201);
                String messagetext = BracMat.Eval("getStatusCode$(\"201\".\"\")");
                out.println(messagetext);
            }
        } else {
            response.setStatus(400);
            String messagetext = BracMat.Eval("getStatusCode$(\"400\".\"No file uploaded\")");
            out.println(messagetext);
        }
    } catch (FileUploadException ex) {
        response.setStatus(500);
        String messagetext = BracMat.Eval("getStatusCode$(\"500\".\"doPost: FileUploadException "
                + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    } catch (Exception ex) {
        response.setStatus(500);
        String messagetext = BracMat
                .Eval("getStatusCode$(\"500\".\"doPost: Exception " + workflow.escape(ex.toString()) + "\")");
        out.println(messagetext);
    }
}

From source file:org.fusesource.restygwt.server.complex.DTOTypeResolverInsideServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    DTOCustom1 one = new DTOCustom1();
    one.name = "Fred Flintstone";
    one.size = 1024;//w  w w  . j a v  a2s . c  om

    DTOCustom2 two = new DTOCustom2();
    two.name = "Barney Rubble";
    two.foo = "schmaltzy";

    DTOCustom2 three = new DTOCustom2();
    three.name = "BamBam Rubble";
    three.foo = "dorky";

    resp.setContentType("application/json");
    ObjectMapper om = new ObjectMapper();
    try {
        AbstractCustomDtoList list = new AbstractCustomDtoList(Lists.newArrayList(one, two, three));
        om.writeValue(resp.getOutputStream(), list);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.viewer.servlets.ViewDocument.java

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

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {//from w  w  w .j av a  2s .  co  m
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        try {
            result.setDocumentDescription(
                    (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
        } catch (ParseException x) {
            throw new ServletException(x);
        }
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages;
        try {
            htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
            cssList = tempRef_cssList.argValue;

            ArrayList<String> pagesContent = new ArrayList<String>();
            for (PageHtml page : htmlPages) {
                pagesContent.add(page.getHtmlContent());
            }
            String[] htmlContent = pagesContent.toArray(new String[0]);
            result.setPageHtml(htmlContent);
            result.setPageCss(new String[] { String.join(" ", temp_cssList) });

            for (int i = 0; i < result.getPageHtml().length; i++) {
                String html = result.getPageHtml()[i];
                int indexOfScript = html.indexOf("script");
                if (indexOfScript > 0) {
                    result.getPageHtml()[i] = html.substring(0, indexOfScript);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:com.jaspersoft.jasperserver.war.OlapGetChart.java

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request/*from ww w .ja  va2 s.  co  m*/
 * @param response servlet response
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getParameter("filename");
    logger.debug("GetChart called: filename=" + filename);
    if (filename == null) {
        throw new ServletException("Parameter 'filename' must be supplied");
    }

    //  Replace ".." with ""
    //  This is to prevent access to the rest of the file system
    filename = searchReplace(filename, "..", "");

    //  Check the file exists
    File file = new File(System.getProperty("java.io.tmpdir"), filename);
    if (!file.exists()) {
        logger.error("File '" + file.getAbsolutePath() + "' does not exist");
        URL url = this.getClass().getResource(fileNotFound);

        URI uri;
        try {
            uri = new URI(url.toString());
        } catch (URISyntaxException e) {
            throw new ServletException(e);
        }
        file = new File(uri.getPath());
    } else {
        //  Serve it up
        sendTempFile(file, response);
    }

    return;

}