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.jooreports.web.spring.controller.AbstractDocumentGenerator.java

private void renderDocument(Object model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    DocumentConverter converter = (DocumentConverter) getApplicationContext().getBean("documentConverter");
    DocumentFormatRegistry formatRegistry = (DocumentFormatRegistry) getApplicationContext()
            .getBean("documentFormatRegistry");
    String outputExtension = FilenameUtils.getExtension(request.getRequestURI());
    DocumentFormat outputFormat = formatRegistry.getFormatByFileExtension(outputExtension);
    if (outputFormat == null) {
        throw new ServletException("unsupported output format: " + outputExtension);
    }/*w w w.  ja v  a2s .c  om*/
    File templateFile = null;
    String documentName = FilenameUtils.getBaseName(request.getRequestURI());
    Resource templateDirectory = getTemplateDirectory(documentName);
    if (templateDirectory.exists()) {
        templateFile = templateDirectory.getFile();
    } else {
        templateFile = getTemplateFile(documentName).getFile();
        if (!templateFile.exists()) {
            throw new ServletException("template not found: " + documentName);
        }
    }

    DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
    DocumentTemplate template = documentTemplateFactory.getTemplate(templateFile);

    ByteArrayOutputStream odtOutputStream = new ByteArrayOutputStream();
    try {
        template.createDocument(model, odtOutputStream);
    } catch (DocumentTemplateException exception) {
        throw new ServletException(exception);
    }
    response.setContentType(outputFormat.getMimeType());
    response.setHeader("Content-Disposition",
            "inline; filename=" + documentName + "." + outputFormat.getFileExtension());

    if ("odt".equals(outputFormat.getFileExtension())) {
        // no need to convert
        response.getOutputStream().write(odtOutputStream.toByteArray());
    } else {
        ByteArrayInputStream odtInputStream = new ByteArrayInputStream(odtOutputStream.toByteArray());
        DocumentFormat inputFormat = formatRegistry.getFormatByFileExtension("odt");
        converter.convert(odtInputStream, inputFormat, response.getOutputStream(), outputFormat);
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   ww  w  .  j  a  va2 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 {

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

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

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

        int incomeAcctNum = Integer.parseInt(up.getFieldMap().get("incomeAcct"));
        int feeAcctNum = Integer.parseInt(up.getFieldMap().get("feeAcct"));
        int depositAcctNum = Integer.parseInt(up.getFieldMap().get("depositAcct"));

        QbAccount incomeAcct = getAccount(incomeAcctNum);
        QbAccount feeAcct = getAccount(feeAcctNum);
        QbAccount depositAcct = getAccount(depositAcctNum);

        SquareParser sp = new SquareParser(file);
        List<SquareTxn> txns;

        try {
            txns = sp.parse();
        } catch (SquareException ex) {
            throw new ServletException(ex);
        }

        SquareToIif squareToIif = new SquareToIif(txns, incomeAcct, feeAcct, depositAcct);
        File iifFile = squareToIif.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();

        //       PrintWriter out = response.getWriter();
        //       for (SquareTxn txn : txns) {
        //      out.println(txn.toString());
        //       }
    }
}

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

/**
 * Handles the following activities for <code>TwistInfo</code>
 * /*from   w ww.  j  av  a  2 s.c o m*/
 */
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String responseType = req.getParameter("response-type");
    // If type is JSON, then respond with JSON
    // Otherwise, direct to JSP

    Long twistInfoId = null;
    TwistInfo twistInfo = null;
    try {
        twistInfoId = new Long(req.getParameter(PARAMETER_KEY_TWIST_ID));
        twistInfo = store.getTwistInfoById(twistInfoId);
        store.deleteTwistInfo(twistInfo);
    } catch (Exception e) {
        // Do nothing. If the value doesn't exist, oh well. 
    }

    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 = new JSONObject();
            jsonObject.put("success", "Deleted");
            jsonResponseObject.put("result", jsonObject);
            out.println(jsonResponseObject.toString());

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

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

    } else {
        List<TwistInfo> twistInfoList = store.getTwistInfoList();
        Util.saveSuccessMessage("Deleted", req);
        req.setAttribute("twistInfoList", twistInfoList);
        req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId());

        RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp");
        dispatch.forward(req, resp);
        return;
    }

}

From source file:edu.umn.msi.tropix.transfer.http.server.HttpTransferControllerImpl.java

private void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    LOG.info("doPost called");
    final String uploadKey = request.getParameter(ServerConstants.KEY_PARAMETER_NAME);
    LOG.info("Key is " + uploadKey);
    try {/*w  w w . j a  va2 s  .  c  o m*/
        fileKeyResolver.handleUpload(uploadKey, request.getInputStream());
        response.flushBuffer();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (final Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.controlj.green.modstat.servlets.LongRunning.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*w w  w.j a v  a  2 s  . c  o m*/
        String actionString = req.getParameter(PARAM_ACTION);
        if (actionString == null || actionString.isEmpty()) {
            throw new ServletException("Missing parameter: action");
        }
        if (actionString.equals(ACTION_START)) {
            String processString = req.getParameter(PARAM_PROCESS);
            if (processString == null || processString.isEmpty()) {
                throw new ServletException("Missing parameter: process");
            }

            RunnableProgress oldWork = (RunnableProgress) req.getSession().getAttribute(ATTRIB_WORK);
            if (oldWork != null) {
                oldWork.interrupt();
            }
            /*
            if (processString.equals(PROCESS_TIMER)) {
                    
            TestWork work = new TestWork();
            req.getSession().setAttribute(ATTRIB_WORK, work);
            work.start();
            } else
            */
            if (processString.equals(PROCESS_MODSTAT)) {
                String idString = req.getParameter(PARAM_ID);
                if (idString == null || idString.isEmpty()) {
                    throw new ServletException("Missing parameter: id");
                }

                SystemConnection connection = null;
                try {
                    connection = DirectAccess.getDirectAccess().getUserSystemConnection(req);
                } catch (InvalidConnectionRequestException e) {
                    throw new ServletException("Error getting connection:" + e.getMessage());
                }
                RunnableProgress work;
                if (test) {
                    work = new TestWork(getFileInWebApp(TEST_SOURCE));
                } else {
                    work = new ModstatWork(connection, idString);
                }
                req.getSession().setAttribute(ATTRIB_WORK, work);
                work.start();
            } else {
                throw new ServletException("Unknown process:" + processString);
            }
        } else if (actionString.equals(ACTION_STATUS)) {
            RunnableProgress work = (RunnableProgress) req.getSession().getAttribute("work");
            JSONObject result = new JSONObject();
            resp.setContentType("application/json");
            String errorMessage = null;
            int percent = 0;
            boolean stopped = false;

            if (work == null) {
                throw new ServletException("Can't get status, nothing started");
            } else if (work.hasError()) {
                throw new ServletException(work.getError().getMessage());
            } else {
                if (work.isAlive()) {
                    percent = work.getProgress();
                } else {
                    percent = 100;
                    stopped = true;
                }
            }
            try {
                result.put("percent", percent);
                result.put("stopped", stopped);
                if (errorMessage != null) {
                    result.put("error", errorMessage);
                }

                result.write(resp.getWriter());
            } catch (JSONException e) {
                throw new ServletException("Error writing result:" + e.getMessage());
            }
        }
    } catch (ServletException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        System.err.println("Add-On Error in " + AddOnInfo.getAddOnInfo().getName() + ":" + e.getMessage());
        e.printStackTrace(new PrintWriter(System.err));
    }
}

From source file:com.adobe.communities.ugc.migration.importer.ForumImportServlet.java

protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    final ResourceResolver resolver = request.getResourceResolver();

    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    final UGCImportHelper importHelper = new UGCImportHelper();
    importHelper.setForumOperations(forumOperations);
    importHelper.setTallyService(tallyOperationsService);
    // get the forum we'll be adding new topics to
    final String path = request.getRequestParameter("path").getString();
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for import");
    }//from w w w  .  j  ava2s  .  co  m

    // finally get the uploaded file
    final RequestParameter[] fileRequestParameters = request.getRequestParameters("file");
    if (fileRequestParameters != null && fileRequestParameters.length > 0
            && !fileRequestParameters[0].isFormField()) {

        InputStream inputStream = fileRequestParameters[0].getInputStream();
        JsonParser jsonParser = new JsonFactory().createParser(inputStream);
        jsonParser.nextToken(); // get the first token

        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            jsonParser.nextToken();
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
                jsonParser.nextToken();
                final String contentType = jsonParser.getValueAsString();
                if (contentType.equals(getContentType())) {
                    jsonParser.nextToken(); // content
                    if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                        jsonParser.nextToken(); // startObject
                        if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
                            JsonToken token = jsonParser.nextToken(); // social:key
                            try {
                                while (!token.equals(JsonToken.END_OBJECT)) {
                                    importHelper.extractTopic(jsonParser, resource,
                                            resource.getResourceResolver(), getOperationsService());
                                    token = jsonParser.nextToken();
                                }
                            } catch (final IOException e) {
                                throw new ServletException("Encountered an IOException", e);
                            }
                        } else {
                            throw new ServletException("Start object token not found for content");
                        }
                    } else {
                        throw new ServletException("Content not found");
                    }
                } else {
                    throw new ServletException("Expected forum data");
                }
            } else {
                throw new ServletException("Content Type not specified");
            }
        } else {
            throw new ServletException("Invalid Json format");
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.config.FenixNotAuthorizedExceptionHandler.java

/**
 * Handle the exception. Return the <code>ActionForward</code> instance (if
 * any) returned by the called <code>ExceptionHandler</code>.
 * /*from ww  w.  jav  a 2  s . c  o m*/
 * @param ex
 *            The exception to handle
 * @param ae
 *            The ExceptionConfig corresponding to the exception
 * @param mapping
 *            The ActionMapping we are processing
 * @param formInstance
 *            The ActionForm we are processing
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * 
 * @exception ServletException
 *                if a servlet exception occurs
 * 
 * @since Struts 1.1
 */
@Override
public ActionForward execute(Exception ex, ExceptionConfig exceptionConfig, ActionMapping mapping,
        ActionForm actionForm, HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    try {
        ActionForward forward = mapping.getInputForward();

        ActionForward newForward = new ActionForward();
        PropertyUtils.copyProperties(newForward, forward);
        StringBuilder path = new StringBuilder();
        path.append("/teacherAdministrationViewer.do?method=instructions").append("&objectCode=")
                .append(request.getParameter("executionCourseId"));
        newForward.setPath(path.toString());
        // Store the exception
        ActionError actionError = new ActionError(exceptionConfig.getKey());
        super.storeException(request, exceptionConfig.getKey(), actionError, newForward,
                exceptionConfig.getScope());
        return newForward;
    } catch (Exception e) {
        throw new ServletException(e.getMessage());
    }
}

From source file:com.jk.web.filters.JKDefaultFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {
    try {//from www .  jav a  2s .  c om
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        this.logger.info("@doFilter : ".concat(request.getRequestURI()));
        JKWebContextUtil.sync(request);
        final boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (!multipart) {
            final boolean toPdf = request.getParameter(JKWebConstants.PARAMTER_CONVERT_TO_PDF) != null;
            if (toPdf) {
                this.logger.info("toPDF request");
                final HttpServletRequestWrapper rq = new HttpServletRequestWrapper(request);
                final CharResponseWrapper rs = new CharResponseWrapper(response);
                chain.doFilter(rq, rs);
                JKWebUtil.toPDF(request, response, rs.toString());
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    } catch (final Exception e) {
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        throw new ServletException(e);
    } finally {
        JKThreadLocal.remove();
        this.logger.info("@End of doFilter");
    }
}

From source file:org.dspace.app.webui.cris.controller.json.EPersonController.java

private boolean isAdmin(Context context, HttpServletRequest request) throws SQLException, ServletException {
    EPerson currUser = getCurrentUser(request);
    if (currUser == null) {
        throw new ServletException(
                "Wrong data or configuration: access to the my rp servlet without a valid user: there is no user logged in");
    }/*from  w w  w .ja  v a 2 s  .co m*/

    return AuthorizeManager.isAdmin(context);
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@Override
public void init(FilterConfig conf) throws ServletException {
    proxyHost = conf.getInitParameter(PROXY_HOST);
    tokenManager = new StramDelegationTokenManager(DELEGATION_KEY_UPDATE_INTERVAL,
            DELEGATION_TOKEN_MAX_LIFETIME, DELEGATION_TOKEN_RENEW_INTERVAL,
            DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL);
    sequenceNumber = new AtomicInteger(0);
    try {//ww  w .  j  av  a  2  s .  c o m
        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
        if (ugi != null) {
            loginUser = ugi.getUserName();
        }
        tokenManager.startThreads();
    } catch (IOException e) {
        throw new ServletException(e);
    }
}