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:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java

@Override
public void init(FilterConfig config) throws ServletException {
    String s = config.getInitParameter("max-size");
    maxSize = toInt(s, maxSize);/*from  w  ww .ja va  2  s .  c om*/

    s = config.getInitParameter("threshold-size");
    thresholdSize = toInt(s, thresholdSize);

    // ????MB???
    // DEFAULT_MAX_SIZE???.
    s = SystemConfig.getValue(Constants.KEY_FILE_MAX_SIZE);
    maxFileSize = toInt(s, maxFileSize) * DEFAULT_MAX_SIZE;

    s = SystemConfig.getValue(Constants.KEY_FILE_DIR_PATH);
    if (!StringUtils.isEmpty(s)) {
        File f = new File(s);
        if (!f.exists() || !f.isDirectory()) {
            throw new ServletException("temporary directory is missing ;" + f.getAbsolutePath());
        }
        temporaryDirectory = f;
    } else {
        throw new ServletException("temporary directory parameter is missing");
    }

    s = SystemConfig.getValue(Constants.KEY_FILENAME_MAX_LENGTH);
    maxFilenameLength = toInt(s, maxFilenameLength);
}

From source file:com.mirth.connect.server.servlets.EngineServlet.java

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

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*w ww  . j  a v  a2s .  co  m*/
        try {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            ServerEventContext context = new ServerEventContext();
            context.setUserId(getCurrentUserId(request));

            if (operation.equals(Operations.CHANNEL_REDEPLOY)) {
                if (!isUserAuthorized(request, null) || doesUserHaveChannelRestrictions(request)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    engineController.redeployAllChannels(context);
                }
            } else if (operation.equals(Operations.CHANNEL_DEPLOY)) {
                List<String> channelIds = (List<String>) serializer.fromXML(request.getParameter("channelIds"));
                parameterMap.put("channelIds", channelIds);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    engineController.deployChannels(channelIds, context);
                }
            } else if (operation.equals(Operations.CHANNEL_UNDEPLOY)) {
                List<String> channelIds = (List<String>) serializer.fromXML(request.getParameter("channelIds"));
                parameterMap.put("channelIds", channelIds);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    engineController.undeployChannels(channelIds, context);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:org.apache.lucene.replicator.http.ReplicationService.java

private static String extractRequestParam(HttpServletRequest req, String paramName) throws ServletException {
    String param = req.getParameter(paramName);
    if (param == null) {
        throw new ServletException("Missing mandatory parameter: " + paramName);
    }/*from   w  ww. j  av a 2  s. c  o m*/
    return param;
}

From source file:demo.wseventing.CreateSubscriptionServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from  w  w  w  . jav  a  2 s. c o  m*/
        resp.getWriter().append("<html><body>");

        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(EventSourceEndpoint.class);
        factory.setAddress("http://localhost:8080/ws_eventing/services/EventSource");
        EventSourceEndpoint requestorClient = (EventSourceEndpoint) factory.create();

        String expires = null;
        if (req.getParameter("expires-set") == null) {
            expires = req.getParameter("expires");
        } else {
            if (!req.getParameter("expires-set").equals("false")) {
                expires = req.getParameter("expires");
            }
        }

        Subscribe sub = createSubscribeMessage(req.getParameter("targeturl"),
                req.getParameter("filter-set") == null ? req.getParameter("filter") : null, expires);

        resp.getWriter().append("<h3>Subscription request</h3>");
        resp.getWriter().append(convertJAXBElementToStringAndEscapeHTML(sub));

        SubscribeResponse subscribeResponse = requestorClient.subscribeOp(sub);

        resp.getWriter().append("<h3>Response from Event Source</h3>");
        resp.getWriter().append(convertJAXBElementToStringAndEscapeHTML(subscribeResponse));

        resp.getWriter().append("<br/><a href=\"index.jsp\">Back to main page</a>");
        resp.getWriter().append("</body></html>");
    } catch (Exception e) {
        throw new ServletException(e);
    }

}

From source file:nijhof2axon.ui.AutowiringApplicationServlet.java

/**
 * Get the containing Spring {@link WebApplicationContext}.
 * This only works after the servlet has been initialized (via {@link #init init()}).
 *
 * @throws ServletException if the operation fails
 *///from w  w  w . j av a  2  s  . c o  m
protected final WebApplicationContext getWebApplicationContext() throws ServletException {
    if (this.webApplicationContext == null)
        throw new ServletException("can't retrieve WebApplicationContext before init() is invoked");
    return this.webApplicationContext;
}

From source file:com.adobe.acs.commons.mcp.impl.ProcessErrorReportExcelServlet.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    ManagedProcess report = request.getResource().adaptTo(ManagedProcess.class);
    if (report != null) {
        String title = report.getName();
        String fileName = JcrUtil.createValidName(title) + ".xlsx";

        Workbook workbook = createSpreadsheet(report);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        try (ServletOutputStream out = response.getOutputStream()) {
            workbook.write(out);/*from w  w w  .  j a v a  2s .  co m*/
            out.flush();
        } catch (Exception ex) {
            LOG.error("Error generating excel export for " + request.getResource().getPath(), ex);
            throw ex;
        }
    } else {
        LOG.error("Unable to process report stored at " + request.getResource().getPath());
        throw new ServletException("Unable to process report stored at " + request.getResource().getPath());
    }
}

From source file:com.adobe.acs.commons.wcm.impl.QrCodeServlet.java

@Override
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    if (externalizer == null) {
        log.warn("Externalizer is not configured. This is required for QR Code servlet to work.");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    } else if (request.getResource().getValueMap().get(PN_ENABLED, false)) {
        final JSONObject json = new JSONObject();
        final String publishUrl = externalizer.publishLink(request.getResourceResolver(),
                request.getRequestPathInfo().getSuffix());

        log.debug("Externalized path [ {} ] for QR Code generation to [ {} ]",
                request.getRequestPathInfo().getSuffix(), publishUrl);

        if (StringUtils.isNotBlank(publishUrl)) {
            try {
                json.put(JSON_KEY_ENABLED, true);
                json.put(JSON_KEY_PUBLISH_URL, publishUrl);
            } catch (JSONException e) {
                log.error("Could not construct the QR Code Servlet JSON response", e);
                throw new ServletException(e);
            }/*from   ww  w .  j a  v a 2 s .c  o  m*/

            response.getWriter().write(json.toString());
            response.getWriter().flush();
        } else {
            log.warn("Externalizer configuration for AEM Publish did not yield a valid URL");
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        log.warn("Externalizer configuration for AEM Publish did not yield a valid URL");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.adobe.communities.ugc.migration.legacyProfileExport.MessagesExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    final String headerKey = "Content-Disposition";
    final String headerValue = "attachment; filename=\"export.zip\"";
    response.setHeader(headerKey, headerValue);
    File outFile = null;/*w  w  w .j ava 2 s.  c o m*/
    exportedIds = new HashMap<String, Boolean>();
    messagesForExport = new HashMap<String, JSONObject>();
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        responseWriter = new OutputStreamWriter(zip);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {

            int start = 0;
            int increment = 100;
            try {
                do {
                    Iterable<Message> messages = messagingService.search(request.getResourceResolver(),
                            new MessageFilter(), start, start + increment);
                    if (messages.iterator().hasNext()) {
                        exportMessagesBatch(messages);
                    } else {
                        break;
                    }
                    start += increment;
                } while (true);
            } catch (final RepositoryException e) {
                // do nothing for now
            }
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}

From source file:org.ambraproject.user.action.AdminUserAlertsAction.java

/**
 * save the user search alerts/*from   w  w w. j  a  v  a  2 s .  c o m*/
 * @return webwork status
 * @throws Exception
 */
public String saveSearchAlerts() throws Exception {
    final String authId = getUserAuthId();
    if (authId == null) {
        throw new ServletException("Unable to resolve ambra user");
    }
    userService.setSavedSearchAlerts(authId, Arrays.asList(monthlyAlerts), Arrays.asList(weeklyAlerts),
            Arrays.asList(deleteAlerts));
    return SUCCESS;
}

From source file:com.mirth.connect.server.servlets.AlertServlet.java

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

    if (!isUserLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } else {/*from  w  w w.  ja  v a  2  s .  c om*/
        try {
            AlertController alertController = ControllerFactory.getFactory().createAlertController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (operation.equals(Operations.ALERT_GET)) {
                Alert alert = (Alert) serializer.fromXML(request.getParameter("alert"));
                parameterMap.put("alert", alert);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(alertController.getAlert(alert), out);
                }
            } else if (operation.equals(Operations.ALERT_UPDATE)) {
                List<Alert> alerts = (List<Alert>) serializer.fromXML(request.getParameter("alerts"));
                parameterMap.put("alerts", alerts);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    alertController.updateAlerts(alerts);
                }
            } else if (operation.equals(Operations.ALERT_REMOVE)) {
                Alert alert = (Alert) serializer.fromXML(request.getParameter("alert"));
                parameterMap.put("alert", alert);

                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    alertController.removeAlert(alert);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}