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:info.magnolia.test.fixture.JcrPropertyServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String path = request.getParameter("path");
    final String workspace = StringUtils.defaultString(request.getParameter("workspace"),
            RepositoryConstants.CONFIG);
    final String value = request.getParameter("value");
    final boolean delete = Boolean.valueOf(request.getParameter("delete"));
    final String nodePath = StringUtils.substringBeforeLast(path, "/");
    final String propertyName = StringUtils.substringAfterLast(path, "/");
    try {/*  w ww .  j av  a2 s. c  om*/
        final Node node = SessionUtil.getNode(workspace, nodePath);
        if (node == null) {
            throw new ServletException("Node does not exist [" + nodePath + "]");
        }

        final String returnValue = PropertyUtil.getString(node, propertyName);

        if (value != null) {
            node.setProperty(propertyName, value);
            node.getSession().save();
            log.info("Changing value of '{}' from [{}] to [{}]", path, returnValue, value);
        } else if (delete) {
            if (node.hasProperty(propertyName)) {
                Property property = node.getProperty(propertyName);
                property.remove();
                node.getSession().save();
                log.info("Removed property '{}' from [{}].", propertyName, path);
            } else {
                log.info("No property '{}' found at [{}].", propertyName, path);
            }
        }

        response.getWriter().write(String.valueOf(returnValue));
    } catch (RepositoryException e) {
        log.warn("Could not handle property [{}] from workspace [{}]", new Object[] { path, workspace });
        throw new ServletException("Could not read property [" + path + "]");
    }
}

From source file:EmailBean.java

private void handleMessages(HttpServletRequest request, PrintWriter out) throws IOException, ServletException {

    HttpSession httpSession = request.getSession();
    String user = (String) httpSession.getAttribute("user");
    String password = (String) httpSession.getAttribute("pass");
    String popAddr = (String) httpSession.getAttribute("pop");

    Store popStore = null;/* w w w.  j  a v a2s .  co  m*/
    Folder folder = null;

    if (!check(popAddr))
        popAddr = EmailBean.DEFAULT_SERVER;

    try {

        if ((!check(user)) || (!check(password)))
            throw new ServletException("A valid username and password is required to check email.");

        Properties properties = System.getProperties();

        Session session = Session.getDefaultInstance(properties);

        popStore = session.getStore("pop3");

        popStore.connect(popAddr, user, password);

        folder = popStore.getFolder("INBOX");

        if (!folder.exists())
            throw new ServletException("An 'INBOX' folder does not exist for the user.");

        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        int msgLen = messages.length;

        if (msgLen == 0)
            out.println("<h2>The INBOX folder does not yet contain any email messages.</h2>");

        for (int i = 0; i < msgLen; i++) {
            displayMessage(messages[i], out);
            out.println("<br /><br />");
        }

    } catch (Exception exc) {

        out.println("<h2>Sorry, an error occurred while accessing the email messages.</h2>");
        out.println(exc.toString());

    } finally {
        try {
            if (folder != null)
                folder.close(false);

            if (popStore != null)
                popStore.close();
        } catch (Exception e) {
        }
    }
}

From source file:edu.sc.seis.receiverFunction.web.MyDisplayChart.java

/**
 * Service method.// ww  w .j a  v  a  2s.c om
 *
 * @param request  the request.
 * @param response  the response.
 *
 * @throws ServletException ??.
 * @throws IOException ??.
 */
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String filename = request.getParameter("filename");

    if (filename == null) {
        throw new ServletException("Parameter 'filename' must be supplied");
    }
    logger.debug("service :" + filename);
    //  Replace ".." with ""
    //  This is to prevent access to the rest of the file system
    filename = ServletUtilities.searchReplace(filename, "..", "");

    //  Check the file exists
    File file = new File(System.getProperty("java.io.tmpdir"), filename);
    if (!file.exists()) {
        throw new ServletException("File '" + file.getAbsolutePath() + "' does not exist");
    }

    //  Check that the graph being served was created by the current user
    //  or that it begins with "public"
    boolean isChartInUserList = false;
    ChartDeleter chartDeleter = (ChartDeleter) session.getAttribute("JFreeChart_Deleter");
    if (chartDeleter != null) {
        isChartInUserList = chartDeleter.isChartAvailable(filename);
    }

    boolean isChartPublic = false;
    if (filename.length() >= 6) {
        if (filename.substring(0, 6).equals("public")) {
            isChartPublic = true;
        }
    }

    boolean isOneTimeChart = false;
    if (filename.startsWith(ServletUtilities.getTempOneTimeFilePrefix())) {
        isOneTimeChart = true;
    }
    //
    // WARNING: HACK AHEAD!!!!!
    //
    // this is dumb, but since all ears charts are public and one time, just serve it
    // I think the upgrade to jetty8 caused the http to no longer have sessions, so
    // the default DisplayChart servlet had all three of 
    // isChartInUserList || isChartPublic || isOneTimeChart false, and
    // so no image was served. Progress! :(
    isOneTimeChart = true;

    if (isChartInUserList || isChartPublic || isOneTimeChart) {
        //  Serve it up
        logger.debug("sending " + file);
        ServletUtilities.sendTempFile(file, response);
        if (isOneTimeChart) {
            logger.debug("delelte " + file);
            file.delete();
        }
    } else {
        logger.error("chart image not found " + filename);
        throw new ServletException("Chart image not found");
    }
    return;
}

From source file:cpabe.controladores.UploadDecriptacaoServlet.java

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

    List<CaminhoArquivo> lista = new ArrayList<CaminhoArquivo>();
    List<File> lista2 = new ArrayList<File>();

    CaminhoArquivo c = new CaminhoArquivo();

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/*w  w  w. java  2s.c o m*/

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            c.setNome(nome);
            c.setWay(caminho);

            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            lista2.add(file);
            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
    //lendo a lista dos arquivos adicionados e pegando os caminhos do arquivo e da chave
    c.setWay(lista2.get(0).getAbsolutePath());
    c.setNome(lista2.get(0).getName());
    System.out.println("arquivo=" + lista2.get(0).getAbsolutePath());
    c.setChave(lista2.get(1).getAbsolutePath());
    System.out.println("chave=" + lista2.get(1).getAbsolutePath());

    request.setAttribute("caminho", c);

    request.getRequestDispatcher("/formularios/decriptar/decriptar2.jsp").forward(request, response);

}

From source file:com.appeligo.search.entity.SetPermissionsInViewFilter.java

/**
 * // w  w  w . j  a  va  2 s  .  c  o m
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    User user = null;

    if (request instanceof HttpServletRequest) {
        String username = ((HttpServletRequest) request).getRemoteUser();
        if (username != null) {
            user = User.findByUsername(username);
        }
    }
    Permissions.setCurrentUser(user);
    try {
        chain.doFilter(request, response);
    } catch (ServletException se) {
        String message = se.toString();
        if (se.getRootCause() != null) {
            message = se.getRootCause().toString();
        }
        if (message != null && ((message.indexOf("ClientAbortException") >= 0)
                || (message.indexOf("Connection reset by peer") >= 0))) {
            log.warn(message);
        } else {
            if (printFullExceptions) {
                log.error("Caught servlet exception:");
                if (se.getRootCause() != null) {
                    log.error(message, se.getRootCause());
                } else {
                    log.error(message, se);
                }
            } else {
                log.error(message);
            }
            throw se;
        }
    } catch (Throwable t) {
        if (printFullExceptions) {
            log.error(t.getMessage(), t);
        } else {
            log.error(t.toString());
        }
        throw new ServletException(t);
    } finally {
        Permissions.setCurrentUser(null);
    }
}

From source file:com.bluexml.xforms.servlets.ReadServlet.java

/**
 * Read./*  w  w w.j a  v a  2 s  . com*/
 * 
 * @param req
 *            the req
 * @param resp
 *            the resp
 * 
 * @throws ServletException
 *             the servlet exception
 */
protected void read(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    AlfrescoController controller = AlfrescoController.getInstance();
    String dataType = StringUtils.trimToNull(req.getParameter(DATA_TYPE));
    if (dataType != null) {
        dataType = dataType.replace('_', '.');
    }
    String dataId = StringUtils.trimToNull(req.getParameter(DATA_ID));
    dataId = controller.patchDataId(dataId);

    String skipIdStr = StringUtils.trimToNull(req.getParameter(ID_AS_SERVLET));
    boolean idAsServlet = !StringUtils.equals(skipIdStr, "false");

    try {
        String userName = req.getParameter(MsgId.PARAM_USER_NAME.getText());
        AlfrescoTransaction transaction = createTransaction(controller, userName);
        Document node = controller.getMappingAgent().getInstanceClass(transaction, dataType, dataId, false,
                idAsServlet);
        Source xmlSource = new DOMSource(node);
        Result outputTarget = new StreamResult(resp.getOutputStream());
        documentTransformer.transform(xmlSource, outputTarget);
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.alfaariss.oa.OAServlet.java

/**
 * Starts requestor profiles and helpers.
 * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
 *//*from w w  w .  jav a  2  s  .  c  o  m*/
public void init(ServletConfig oServletConfig) throws ServletException {
    try {
        _context = oServletConfig.getServletContext();

        //Retrieve configuration manager            
        IConfigurationManager config = _engine.getConfigurationManager();

        //Start profiles and helpers
        start(config, null);

        //Add as listener           
        _engine.addComponent(this);
    } catch (OAException e) {
        _logger.fatal("Error starting Asimba Server", e);
        stop(); //Stop started profiles and helpers
        throw new ServletException(SystemErrors.toHexString(e.getCode()));
    } catch (Exception e) {
        _logger.fatal("Error starting Asimba Server", e);
        stop(); //Stop started profiles and helpers
        throw new ServletException(SystemErrors.toHexString(SystemErrors.ERROR_INTERNAL));
    }

}

From source file:at.molindo.notify.servlet.NotifyFilterBean.java

@Override
public void initFilterBean() throws ServletException {
    {//from   www.j a  v  a  2s .  c o  m
        if (!StringUtils.empty(_baseUrlProperty)) {
            String baseUrl = System.getProperty(_baseUrlProperty);
            if (!StringUtils.empty(baseUrl)) {
                _baseUrl = baseUrl;
            }
        }

        if (StringUtils.empty(_baseUrl)) {
            throw new ServletException(String.format("parameter %s is required", PARAMTER_BASE_URL));
        }

        try {
            _baseUrl = StringUtils.stripTrailing(new URL(_baseUrl).toString(), "/");
        } catch (MalformedURLException e) {
            throw new ServletException(
                    String.format("illegal value for parameter %s: '%s'", PARAMTER_BASE_URL, _baseUrl), e);
        }
    }

    {
        if (StringUtils.empty(_mountPath)) {
            _mountPath = DEFAULT_MOUNT_PATH;
        }
        _mountPath = StringUtils.stripTrailing(StringUtils.startWith(_mountPath, "/"), "/");
    }

    {
        if (StringUtils.empty(_pullPrefix)) {
            _pullPrefix = DEFAULT_PULL_PREFIX;
        }
        _pullPrefix = StringUtils.endWith(StringUtils.startWith(_pullPrefix, "/"), "/");
        _pullPattern = Pattern.compile("^" + Pattern.quote(_pullPrefix) + "([^/?]+)/([^/?]+).*$");
    }

    {
        if (StringUtils.empty(_confirmPrefix)) {
            _confirmPrefix = DEFAULT_CONFIRM_PREFIX;
        }
        _confirmPrefix = StringUtils.endWith(StringUtils.startWith(_confirmPrefix, "/"), "/");
        _confirmPattern = Pattern.compile("^" + Pattern.quote(_confirmPrefix) + "([^/?]+)/?$");
    }
}

From source file:io.hops.hopsworks.api.jupyter.URITemplateProxyServlet.java

protected void initTarget() throws ServletException {
    targetUriTemplate = getConfigParam(P_TARGET_URI);
    if (targetUriTemplate == null) {
        throw new ServletException(P_TARGET_URI + " is required.");
    }//from ww  w .j a  v  a2 s. co  m

    targetUri = getConfigParam(P_TARGET_URI);
    if (targetUri == null) {
        throw new ServletException(P_TARGET_URI + " is required.");
    }
    //test it's valid
    try {
        targetUriObj = new URI(targetUri);
    } catch (Exception e) {
        throw new ServletException("Trying to process targetUri init parameter: " + e, e);
    }
    targetHost = URIUtils.extractHost(targetUriObj);

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

From source file:br.bireme.prvtrm.PreviousTermServlet.java

/**
 * Processes requests for both HTTP//from w  ww .j  a  va  2 s  .  co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @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("application/json; charset=UTF-8");
    final PrintWriter out = response.getWriter();

    try {
        final String init = request.getParameter("init");
        if (init == null) {
            throw new ServletException("missing 'init' parameter");
        }

        int maxSize = previous.getMaxSize();
        String maxTerms = request.getParameter("maxTerms");
        if (maxTerms != null) {
            maxSize = Integer.parseInt(maxTerms);
        }

        List<String> fields = previous.getFields();
        String fldsParam = request.getParameter("fields");
        if (fldsParam != null) {
            fields = Arrays.asList(fldsParam.split("[,;\\-]"));
        }

        final List<String> terms;
        String direction = request.getParameter("direction");
        if ((direction == null) || (direction.compareToIgnoreCase("next") == 0)) {
            terms = previous.getNextTerms(init, fields, maxSize);
            direction = "next";
        } else {
            terms = previous.getPreviousTerms(init, fields, maxSize);
            direction = "previous";
        }

        final JSONObject jobj = new JSONObject();
        final JSONArray jlistTerms = new JSONArray();
        final JSONArray jlistFields = new JSONArray();

        jlistTerms.addAll(terms);
        jlistFields.addAll(fields);
        jobj.put("init", init);
        jobj.put("direction", direction);
        jobj.put("maxTerms", maxSize);
        jobj.put("fields", jlistFields);
        jobj.put("terms", jlistTerms);

        out.println(jobj.toJSONString());
    } finally {
        out.close();
    }
}