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:annis.gui.servlets.BinaryServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    Map<String, String[]> binaryParameter = request.getParameterMap();
    String toplevelCorpusName = binaryParameter.get("toplevelCorpusName")[0];
    String documentName = binaryParameter.get("documentName")[0];
    String mimeType = binaryParameter.get("mime")[0];

    try {/*from w w  w .  ja  v a  2  s  .c  o m*/
        ServletOutputStream out = response.getOutputStream();

        String range = request.getHeader("Range");

        HttpSession session = request.getSession();
        Object annisServiceURLObject = session.getAttribute(AnnisBaseUI.WEBSERVICEURL_KEY);

        if (annisServiceURLObject == null || !(annisServiceURLObject instanceof String)) {
            throw new ServletException("AnnisWebService.URL was not set as init parameter in web.xml");
        }

        String annisServiceURL = (String) annisServiceURLObject;

        WebResource annisRes = Helper.getAnnisWebResource(annisServiceURL,
                (AnnisUser) session.getAttribute(AnnisBaseUI.USER_KEY));

        WebResource binaryRes = annisRes.path("query").path("corpora")
                .path(URLEncoder.encode(toplevelCorpusName, "UTF-8"))
                .path(URLEncoder.encode(documentName, "UTF-8")).path("binary").queryParam("mime", mimeType);

        if (range != null) {
            responseStatus206(binaryRes, mimeType, out, response, range);
        } else {
            responseStatus200(binaryRes, mimeType, out, response);
        }

        out.flush();
    } catch (IOException ex) {
        log.debug("IOException in BinaryServlet", ex);
    } catch (ClientHandlerException ex) {
        log.error(null, ex);
        response.setStatus(500);
    } catch (UniformInterfaceException ex) {
        log.error(null, ex);
        response.setStatus(500);
    }
}

From source file:eionet.gdem.web.filters.SetCharacterEncodingFilter.java

/**
 * Select and set (if specified) the character encoding to be used to interpret request parameters for this request.
 *
 * @param request/*w w  w.ja  v a2 s .  co  m*/
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param chain
 *            The filter chain we are processing
 *
 * @exception IOException
 *                if an input/output error occurs
 * @exception ServletException
 *                if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
        String encoding = selectEncoding(request);
        if (encoding != null)
            request.setCharacterEncoding(encoding);
    }

    // Pass control on to the next filter
    try {
        chain.doFilter(request, response);
    } catch (Exception e) {
        // Logging unhandled exception
        LOGGER.error("Unhandled exception caught", e);
        throw new ServletException(e);
    }

}

From source file:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

@Override
protected void initTarget() throws ServletException {
    targetUriTemplate = getConfigParam(P_TARGET_URI);
    if (targetUriTemplate == null)
        throw new ServletException(P_TARGET_URI + " is required.");

    //leave this.target* null to prevent accidental mis-use
}

From source file:com.autentia.wuija.web.DownloadServlet.java

/**
 * Process GET request//from   w  w w.ja v a2  s  . c  o m
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @throws javax.servlet.ServletException
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    final String requestUri = request.getRequestURI();
    final String fileName = requestUri.substring(requestUri.lastIndexOf('/') + 1, requestUri.length());

    if (log.isTraceEnabled()) {
        log.trace("fileName='" + fileName + "'.");
    }

    if (fileName == null) {
        final String msg = "Filename not found in the requested URL.";
        log.error(msg);
        throw new ServletException(msg);
    }

    final StringBuilder tempFilePath = new StringBuilder(System.getProperty("java.io.tmpdir"));

    if (log.isTraceEnabled()) {
        log.trace("tempdir = " + tempFilePath);
    }

    if (tempFilePath.charAt(tempFilePath.length() - 1) != File.separatorChar) {
        tempFilePath.append(File.separatorChar);
    }

    tempFilePath.append(fileName);

    if (log.isTraceEnabled()) {
        log.trace("filePath = " + tempFilePath);
    }

    final File file = new File(tempFilePath.toString());
    file.deleteOnExit();

    String clientFileName = request.getHeader(FILE_NAME);
    if (clientFileName == null) {
        clientFileName = file.getName();
    }
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Content-disposition", "attachment; filename=" + clientFileName);

    // XXX [wuija]: reemplazar por una librera de mimetypes
    if (clientFileName.toLowerCase().endsWith(".csv")) {
        response.setContentType("application/vnd.ms-excel");
    } else if (clientFileName.toLowerCase().endsWith(".zip")) {
        response.setContentType("application/zip");
    } else if (clientFileName.toLowerCase().endsWith(".pdf")) {
        response.setContentType("application/pdf");
    }
    response.setContentLength((int) file.length());

    try {
        int read = 0;
        final byte[] bytes = new byte[1024];
        final FileInputStream in = new FileInputStream(file);

        while ((read = in.read(bytes)) != -1) {
            response.getOutputStream().write(bytes, 0, read);
        }
        in.close();

        log.trace("The contents of the file have been written.");

        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (IOException e) {
        final String msg = "Error writting the contents of the file.";
        log.error(msg);
        throw new ServletException(msg, e);
    }

    file.delete();
    log.trace("File='" + file + "' deleted.");

}

From source file:com.collective.celos.servlet.RegisterServlet.java

protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    BucketID bucket = getRequestBucketID(req);
    try {/*from w  w  w  .  j  a v a2s .co m*/
        try (StateDatabaseConnection connection = getStateDatabase().openConnection()) {
            if (req.getParameter(CelosClient.KEY_PARAM) != null) {
                connection.deleteRegister(bucket, getRequestKey(req));
            } else if (req.getParameter(CelosClient.PREFIX_PARAM) != null) {
                connection.deleteRegistersWithPrefix(bucket, req.getParameter(CelosClient.PREFIX_PARAM));
            } else {
                throw new IllegalArgumentException("Either " + CelosClient.KEY_PARAM + " or "
                        + CelosClient.PREFIX_PARAM + " should be specified");
            }
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.sap.dirigible.runtime.content.ContentInitializerServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    logger.info("Content Servlet Init"); //$NON-NLS-1$
    initRepository();/*  w ww.  j  a  v  a 2s .  c  o  m*/
    try {
        // 1. Import pre-delivered content
        checkAndImportRegistry(config, SYSTEM_USER);
        // 2. Post import actions
        ContentPostImportUpdater contentPostImportUpdater = new ContentPostImportUpdater(
                getRepository(SYSTEM_USER));
        contentPostImportUpdater.update();
    } catch (IOException e) {
        throw new ServletException(e);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.github.buildnum.servlet.VersionServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from w  ww.  j  a v  a  2s . c om*/
        final String action = getParameter(req, "action");
        final String format = getParameter(req, "format");
        final String ignoreSnapshotStr = getParameter(req, "ignoreSnapshot");

        final VersionRequest versionRequest = new VersionRequest();
        versionRequest.setGroupId(getParameter(req, "groupId"));
        versionRequest.setArtifactId(getParameter(req, "artifactId"));
        versionRequest.setArtifactClassifier(getParameter(req, "artifactClassifier"));
        versionRequest.setArtifactVersion(getParameter(req, "artifactVersion"));
        versionRequest.setActionType(ActionType.fromValue(action));
        versionRequest.setFormatType(FormatType.fromValue(format));
        versionRequest.setIgnoreSnapshot("1".equals(ignoreSnapshotStr));
        versionRequest.setBuildNumber(getParameterAsInt(req, "buildNumber")); // for SET action
        versionRequest.setPrefix(getParameter(req, "prefix"));

        VersionResponse versionResponse = null;

        if (versionRequest.getGroupId() != null && versionRequest.getArtifactId() != null
                && versionRequest.getArtifactVersion() != null) {
            // call service
            versionResponse = VersionManager.getInstance().getVersion(versionRequest);
        }

        final String output = getOutput(versionRequest, versionResponse);
        // write to output stream
        writeOutput(output, resp);
    } catch (Exception e) {
        log.error("Error in VersionServlet", e);
        throw new ServletException(e);
    }
}

From source file:com.mkmeier.quickerbooks.ProcessUwcu.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//  w  w w. ja  v a2 s  .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    if (!ServletFileUpload.isMultipartContent(request)) {
        showForm(request, response);
    } else {

        ServletFileUploader up = new ServletFileUploader();
        up.parseRequest(request);

        File file = up.getFileMap().get("uwcuTxn");

        int depositAcctNum = Integer.parseInt(up.getFieldMap().get("depositAcct"));
        int creditCardAcctNum = Integer.parseInt(up.getFieldMap().get("ccAcct"));

        QbAccount depositAcct = getAccount(depositAcctNum);
        QbAccount creditCardAcct = getAccount(creditCardAcctNum);

        UwcuParser uwcuParser = new UwcuParser(file);
        List<UwcuTxn> txns;

        try {
            txns = uwcuParser.parse();
        } catch (UwcuException ex) {
            throw new ServletException(ex);
        }

        UwcuToIif uwcuToIif = new UwcuToIif(txns, depositAcct, creditCardAcct);
        File iifFile = uwcuToIif.getIifFile();

        response.setHeader("Content-Disposition", "attachement; filename=\"iifFile.iif\"");
        ServletOutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(iifFile);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
}

From source file:de.betterform.agent.web.filter.XFormsFilter.java

/**
 * Filter initialisation//w  w w. j av a2 s.  c  o  m
 *
 * @see http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/Filter.html#init(javax.servlet.FilterConfig)
 */
public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;

    webFactory = new WebFactory();
    webFactory.setServletContext(filterConfig.getServletContext());
    try {
        webFactory.initConfiguration(XFormsFilter.USERAGENT);
        defaultRequestEncoding = webFactory.getConfig().getProperty("defaultRequestEncoding",
                defaultRequestEncoding);
        webFactory.initLogging(this.getClass());
        String realPath = WebFactory.getRealPath(".", this.filterConfig.getServletContext());
        webFactory.initTransformerService(realPath);
        // webFactory.initXFormsSessionCache(); // todo: still needed????

    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
}

From source file:com.liferay.arquillian.DeployerServlet.java

@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    BundleContext bundleContext = _bundle.getBundleContext();

    try {/*  w  ww . j a va2s  .c  om*/
        Bundle bundle = bundleContext.getBundle(DEPLOYER_SERVLET_LOCATION);

        bundle.stop();

        bundle.uninstall();
    } catch (BundleException e) {
        throw new ServletException(e);
    }
}