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:net.sf.j2ep.RewriteFilter.java

/**
 * Initialize.//from   w  ww .j a  va 2 s  .c o  m
 * 
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 */
public void init(FilterConfig filterConfig) throws ServletException {
    log = LogFactory.getLog(RewriteFilter.class);

    String data = filterConfig.getInitParameter("dataUrl");
    if (data == null) {
        throw new ServletException("dataUrl is required.");
    } else {
        try {
            File dataFile = new File(filterConfig.getServletContext().getRealPath(data));
            ConfigParser parser = new ConfigParser(dataFile);
            serverChain = parser.getServerChain();
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = RequestMethod.POST)
public void exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response,
        HttpServletRequest request) throws ServletException, IOException, InterruptedException,
        SVGConverterException, NoSuchElementException, PoolException, TimeoutException {

    long start1 = System.currentTimeMillis();

    MimeType mime = getMime(type);
    filename = getFilename(filename);//from w  ww.  j a  va  2 s.  co m
    Float parsedWidth = widthToFloat(width);
    Float parsedScale = scaleToFloat(scale);
    options = sanitize(options);
    String input;

    boolean convertSvg = false;

    if (options != null) {
        // create a svg file out of the options
        input = options;
        callback = sanitize(callback);
    } else {
        // assume SVG conversion
        if (svg == null) {
            throw new ServletException("The manadatory svg POST parameter is undefined.");
        } else {
            svg = sanitize(svg);
            if (svg == null) {
                throw new ServletException("The manadatory svg POST parameter is undefined.");
            }
            convertSvg = true;
            input = svg;
        }
    }

    ByteArrayOutputStream stream = null;
    if (convertSvg && mime.equals(MimeType.SVG)) {
        // send this to the client, without converting.
        stream = new ByteArrayOutputStream();
        stream.write(input.getBytes());
    } else {
        //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale);
        stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale);
    }

    if (stream == null) {
        throw new ServletException("Error while converting");
    }

    logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1));

    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentLength(stream.size());
    response.setStatus(HttpStatus.OK.value());
    response.setHeader("Content-disposition",
            "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\"");

    IOUtils.write(stream.toByteArray(), response.getOutputStream());
    response.flushBuffer();
}

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

/**
 * Used when performing searches on lists. Invoked via ModelElementListUpdater.
 *//*from w  w  w.  j a  v  a2  s . c  om*/
@SuppressWarnings("deprecation")
@Override
public void submit() throws ServletException {
    // update list using search
    Document doc = (Document) node;
    String query = "";
    String maxResults = "";
    Element queryElement = doc.getDocumentElement();
    NodeList childNodes = queryElement.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node child = childNodes.item(i);
        if (child instanceof Element) {
            Element element = (Element) child;
            if (StringUtils.equals(element.getTagName(), "query")) {
                query = element.getTextContent();
            }
            if (StringUtils.equals(element.getTagName(), "maxResults")) {
                maxResults = element.getTextContent();
            }
        }
    }

    requestParameters.put(MsgId.INT_ACT_PARAM_LIST_QUERY.getText(), query);
    requestParameters.put(MsgId.INT_ACT_PARAM_LIST_SIZE.getText(), maxResults);

    // retrieves elements
    Node list = list();

    // convert to string
    Source xmlSource = new DOMSource(list);
    ByteArrayOutputStream pos = new ByteArrayOutputStream();
    Result outputTarget = new StreamResult(pos);
    try {
        documentTransformer.transform(xmlSource, outputTarget);
    } catch (TransformerException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Failed to convert the list document into a string", e);
        }
        throw new ServletException(MsgId.MSG_ERROR_DEFAULT_MSG.getText());
    }

    ByteArrayInputStream pis = new ByteArrayInputStream(pos.toByteArray());

    result.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, pis);
}

From source file:org.wso2.carbon.mediation.transport.handlers.NHttpGetProcessor.java

private void populateGetRequestProcessors() throws AxisFault {
    try {/*from w ww . j  a  v a 2 s.c o m*/
        OMElement docEle = XMLUtils.toOM(ServerConfiguration.getInstance().getDocumentElement());
        if (docEle != null) {
            SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
            nsCtx.addNamespace("wsas", ServerConstants.CARBON_SERVER_XML_NAMESPACE);
            XPath xp = new AXIOMXPath("//wsas:HttpGetRequestProcessors/wsas:Processor");
            xp.setNamespaceContext(nsCtx);
            List nodeList = xp.selectNodes(docEle);
            for (Object aNodeList : nodeList) {
                OMElement processorEle = (OMElement) aNodeList;
                OMElement itemEle = processorEle.getFirstChildWithName(ITEM_QN);
                if (itemEle == null) {
                    throw new ServletException("Required element, 'Item' not found!");
                }
                OMElement classEle = processorEle.getFirstChildWithName(CLASS_QN);
                org.wso2.carbon.core.transports.HttpGetRequestProcessor processor;
                if (classEle == null) {
                    throw new ServletException("Required element, 'Class' not found!");
                } else {
                    processor = (org.wso2.carbon.core.transports.HttpGetRequestProcessor) Class
                            .forName(classEle.getText().trim()).newInstance();
                }
                getRequestProcessors.put(itemEle.getText().trim(), processor);
            }
        }
    } catch (Exception e) {
        handleException("Error populating GetRequestProcessors", e);
    }
}

From source file:com.ibm.sbt.service.basic.ProxyEndpointService.java

@Override
protected void checkRequestAllowed(HttpServletRequest request) throws ServletException {
    if (!isRefererAllowed(request)) {
        throw new ServletException("Invalid request referer");
    }//  ww w.  j  a va 2  s  .c  om
    super.checkRequestAllowed(request);
}

From source file:com.mirth.connect.server.servlets.ChannelStatisticsServlet.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  www.  ja va 2 s.c o m*/
        try {
            ChannelStatisticsController statisticsController = ControllerFactory.getFactory()
                    .createChannelStatisticsController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            PrintWriter out = response.getWriter();
            Operation operation = Operations.getOperation(request.getParameter("op"));
            String channelId = request.getParameter("id");
            Map<String, Object> parameterMap = new HashMap<String, Object>();
            parameterMap.put("channelId", channelId);

            if (operation.equals(Operations.CHANNEL_STATS_GET)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(statisticsController.getStatistics(channelId), out);
                }
            } else if (operation.equals(Operations.CHANNEL_STATS_CLEAR)) {
                if (!isUserAuthorized(request, parameterMap)) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                } else {
                    boolean deleteReceived = Boolean.valueOf(request.getParameter("deleteReceived"));
                    boolean deleteFiltered = Boolean.valueOf(request.getParameter("deleteFiltered"));
                    boolean deleteQueued = Boolean.valueOf(request.getParameter("deleteQueued"));
                    boolean deleteSent = Boolean.valueOf(request.getParameter("deleteSent"));
                    boolean deleteErrored = Boolean.valueOf(request.getParameter("deleteErrored"));
                    boolean deleteAlerted = Boolean.valueOf(request.getParameter("deleteAlerted"));
                    statisticsController.clearStatistics(channelId, deleteReceived, deleteFiltered,
                            deleteQueued, deleteSent, deleteErrored, deleteAlerted);
                }
            }
        } catch (RuntimeIOException rio) {
            logger.debug(rio);
        } catch (Throwable t) {
            logger.error(ExceptionUtils.getStackTrace(t));
            throw new ServletException(t);
        }
    }
}

From source file:com.softwareaggov.messaging.simplesoapjms.client.web.SendSoapCall.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    out.write("<h1>" + req.getContextPath() + " - Sending SOAP Call</h1>");
    try {//from  ww w .ja v a2  s.c  o m
        String callType = req.getParameter("calltype");
        SoapClientLocal soapJmsService = null;
        if (null != callType) {
            if ("oneway".equals(callType.toLowerCase()))
                soapJmsService = soapHttpClientOneWayService;
            else if ("twoway".equals(callType.toLowerCase()))
                soapJmsService = soapHttpClientTwoWayService;
            else
                throw new IllegalArgumentException("call type [" + callType + "] not supported.");
        } else {
            throw new IllegalArgumentException("call type [null] not supported.");
        }

        if (null == soapJmsService)
            throw new IllegalArgumentException(
                    "soapJmsService is null...should not be...check code or configs");

        String response = soapJmsService.callWS();

        String responseToDisplay = "";
        if (null != response) {
            if (response.toLowerCase().startsWith("<?xml")) {
                responseToDisplay = StringEscapeUtils.escapeXml10(response);
            } else {
                responseToDisplay = response;
            }
        } else {
            responseToDisplay = "null";
        }

        out.write("<p><b>messages sent successfully</b></p>");
        out.write(String.format("<div><p>Response:</p><p>%s</p></div>", responseToDisplay));

        out.close();
    } catch (Throwable exc) {
        log.error("Error Occurred", exc);
        throw new ServletException(exc);
    }
}

From source file:com.softwareaggov.messaging.simplesoapjms.client.web.SendSoapJmsCall.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    out.write("<h1>" + req.getContextPath() + " - Sending SOAP Call</h1>");
    try {/*from w  w w. j  av  a2s . c o m*/
        String callType = req.getParameter("calltype");
        SoapClientLocal soapJmsService = null;
        if (null != callType) {
            if ("oneway".equals(callType.toLowerCase()))
                soapJmsService = soapJmsClientOneWayService;
            else if ("twoway".equals(callType.toLowerCase()))
                soapJmsService = soapJmsClientTwoWayService;
            else
                throw new IllegalArgumentException("call type [" + callType + "] not supported.");
        } else {
            throw new IllegalArgumentException("call type [null] not supported.");
        }

        if (null == soapJmsService)
            throw new IllegalArgumentException(
                    "soapJmsService is null...should not be...check code or configs");

        String response = soapJmsService.callWS();

        String responseToDisplay = "";
        if (null != response) {
            if (response.toLowerCase().startsWith("<?xml")) {
                responseToDisplay = StringEscapeUtils.escapeXml10(response);
            } else {
                responseToDisplay = response;
            }
        } else {
            responseToDisplay = "null";
        }

        out.write("<p><b>messages sent successfully</b></p>");
        out.write(String.format("<div><p>Response:</p><p>%s</p></div>", responseToDisplay));

        out.close();
    } catch (Throwable exc) {
        log.error("Error Occurred", exc);
        throw new ServletException(exc);
    }
}

From source file:com.mockey.ui.TwistInfoSetupServlet.java

/**
 * Handles the following activities for <code>TwistInfo</code>
 * /*from   w ww .  ja v a  2s .  com*/
 */
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    List<TwistInfo> twistInfoList = store.getTwistInfoList();
    String responseType = req.getParameter("response-type");
    // If type is JSON, then respond with JSON
    // Otherwise, direct to JSP

    if (PARAMETER_KEY_RESPONSE_TYPE_VALUE_JSON.equalsIgnoreCase(responseType)) {
        // ***********************
        // BEGIN - JSON response
        // ***********************
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        try {
            JSONObject jsonResponseObject = new JSONObject();
            JSONObject jsonObject = null; // new JSONObject();
            for (TwistInfo twistInfo : twistInfoList) {
                jsonObject = new JSONObject();
                jsonObject.put("id", "" + twistInfo.getId());
                jsonObject.put("name", twistInfo.getName());
                for (PatternPair patternPair : twistInfo.getPatternPairList()) {
                    JSONObject ppObj = new JSONObject();
                    ppObj.put("origination", patternPair.getOrigination());
                    ppObj.put("destination", patternPair.getDestination());
                    jsonObject.append("pattern-pair-list", ppObj);
                }
            }

            jsonResponseObject.put("result", jsonObject);
            out.println(jsonResponseObject.toString());

        } catch (JSONException jsonException) {
            throw new ServletException(jsonException);
        }

        out.flush();
        out.close();
        return;
        // ***********************
        // END - JSON response
        // ***********************

    } else {
        req.setAttribute("twistInfoList", twistInfoList);
        req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId());
        RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp");
        dispatch.forward(req, resp);
        return;
    }

}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from ww  w. ja  v a 2s.c om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Integer mrnCount = ServletRequestUtils.getRequiredIntParameter(request, "mrn_count");
    Integer templateId = ServletRequestUtils.getIntParameter(request, "templateId", 1);
    String generatedMRNs = ServletRequestUtils.getStringParameter(request, "generated_mrns", "none");
    String password = ServletRequestUtils.getStringParameter(request, "pdf_password");
    if (!StringUtils.hasLength(password))
        throw new ServletException("A non-empty password is required.");

    IdcardsTemplate card = getIdcardsService().getIdcardsTemplate(templateId);

    StringBuffer requestURL = request.getRequestURL();
    String baseURL = requestURL.substring(0, requestURL.indexOf("/moduleServlet"));

    List<Integer> identifiers = null;

    if ("none".equals(generatedMRNs)) {
        identifiers = Collections.nCopies(mrnCount, 0);
    } else if ("pregenerated".equals(generatedMRNs)) {
        identifiers = getIdcardsService().printGeneratedIdentifiers(mrnCount, card);
    } else if ("generateNew".equals(generatedMRNs)) {
        Integer min = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMin"));
        Integer max = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMax"));
        identifiers = getIdcardsService().generateAndPrintIdentifiers(mrnCount, min, max, card);
    } else
        throw new ServletException("Invalid choice for 'generatedMRNs' parameter");

    generateOutput(card, baseURL, response, identifiers, password);

}