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:nl.surfnet.coin.teams.interceptor.LoginInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    HttpSession session = request.getSession();

    String remoteUser = getRemoteUser(request);

    // Check session first:
    Person person = (Person) session.getAttribute(PERSON_SESSION_KEY);
    if (person == null || !person.getId().equals(remoteUser)) {

        if (StringUtils.hasText(remoteUser)) {
            person = apiClient.getPerson(remoteUser, null);
            // Add person to session:
            session.setAttribute(PERSON_SESSION_KEY, person);

            if (person == null) {
                String errorMessage = "Cannot find user: " + remoteUser;
                throw new ServletException(errorMessage);
            }/*ww  w  .  j a va 2  s. c om*/
            AuditLog.log("Login by user {}", person.getId());
            handleGuestStatus(session, person);

        } else {
            // User is not logged in, and REMOTE_USER header is empty.
            // Check whether the user is requesting the landing page, if not
            // redirect him to the landing page.
            String url = getRequestedPart(request);
            String[] urlSplit = url.split("/");

            String view = request.getParameter("view");

            // Unprotect the items in bypass
            String urlPart = urlSplit[2];

            logger.trace("Request for '{}'", request.getRequestURI());
            logger.trace("urlPart: '{}'", urlPart);
            logger.trace("view '{}'", view);

            String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : "";

            if (LOGIN_BYPASS.contains(urlPart)) {
                logger.trace("Bypassing {}", urlPart);
                return super.preHandle(request, response, handler);
            } else if (GADGET.equals(view) || "acceptInvitation.shtml".equals(urlPart)
                    || "detailteam.shtml".equals(urlPart)) {
                logger.trace("Going to shibboleth");
                response.sendRedirect("/Shibboleth.sso/Login?target=" + request.getRequestURL()
                        + URLEncoder.encode(queryString, "utf-8"));
                return false;
                // If user is requesting SURFteams for a VO redirect to Federation Login
            } else {
                if (getTeamsCookie(request).contains("skipLanding")) {
                    response.sendRedirect("/Shibboleth.sso/Login?target=" + request.getRequestURL()
                            + URLEncoder.encode(queryString, "utf-8"));
                    return false;
                } else {
                    // Send redirect to landingpage if gadget is not requested in app view.
                    logger.trace("Redirect to landingpage");
                    response.sendRedirect(teamEnvironment.getTeamsURL() + "/landingpage.shtml");
                    return false;
                }
            }
        }
    }
    return super.preHandle(request, response, handler);
}

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

@Override
protected void doGet(@Nonnull final SlingHttpServletRequest request,
        @Nonnull 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;//ww  w .  j ava2  s .  co 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.terasoluna.gfw.web.logging.mdc.MDCClearFilterTest.java

/**
 * [doFilterInternal] Case of occur exception.
 * <p>/*from   w  w  w . ja v a  2  s  .  c  om*/
 * [Expected Result]
 * <ol>
 * <li>remove all values from MDC on after chain.</li>
 * </ol>
 * </p>
 * @throws ServletException
 * @throws IOException
 */
@Test
public void testDoFilterInternal_occur_exception() throws ServletException, IOException {
    // do setup.
    ServletException occurException = new ServletException("test");
    doThrow(occurException).when(mockFilterChain).doFilter(mockRequest, mockResponse);
    MDC.put("key0", "value0");

    // do test.
    try {
        testTarget.doFilterInternal(mockRequest, mockResponse, mockFilterChain);
        fail("don't occur ServletException.");
    } catch (ServletException e) {
        // do assert.
        // throws original exception.
        assertThat(e, is(occurException));
    }

    // do assert.
    // remove all values from MDC on after chain.
    assertThat(MDC.getCopyOfContextMap(), is(nullValue()));

}

From source file:com.google.publicalerts.cap.validator.CapValidatorServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String input = null;//  w w w.  j  a  v a  2 s .co  m
    String fileInput = null;
    String example = null;
    Set<CapProfile> profiles = Sets.newHashSet();

    try {
        FileItemIterator itemItr = upload.getItemIterator(req);
        while (itemItr.hasNext()) {
            FileItemStream item = itemItr.next();
            if ("input".equals(item.getFieldName())) {
                input = ValidatorUtil.readFully(item.openStream());
            } else if (item.getFieldName().startsWith("inputfile")) {
                fileInput = ValidatorUtil.readFully(item.openStream());
            } else if ("example".equals(item.getFieldName())) {
                example = ValidatorUtil.readFully(item.openStream());
            } else if ("profile".equals(item.getFieldName())) {
                String profileCode = ValidatorUtil.readFully(item.openStream());
                profiles.addAll(ValidatorUtil.parseProfiles(profileCode));
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    if (!CapUtil.isEmptyOrWhitespace(example)) {
        log.info("ExampleRequest: " + example);
        input = loadExample(example);
        profiles = ImmutableSet.of();
    } else if (!CapUtil.isEmptyOrWhitespace(fileInput)) {
        log.info("FileInput");
        input = fileInput;
    }

    input = (input == null) ? "" : input.trim();
    if ("".equals(input)) {
        log.info("EmptyRequest");
        doGet(req, resp);
        return;
    }

    ValidationResult result = capValidator.validate(input, profiles);

    req.setAttribute("input", input);
    req.setAttribute("profiles", ValidatorUtil.getProfilesJsp(profiles));
    req.setAttribute("validationResult", result);
    req.setAttribute("lines", Arrays.asList(result.getInput().split("\n")));
    req.setAttribute("timing", result.getTiming());
    JSONArray alertsJs = new MapVisualizer(result.getValidAlerts()).getAlertsJs();
    if (alertsJs != null) {
        req.setAttribute("alertsJs", alertsJs.toString());
    }
    render(req, resp);
}

From source file:com.stratelia.webactiv.servlets.RestOnlineFileServer.java

@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RestRequest restRequest = new RestRequest(req, "");
    SilverTrace.info("peasUtil", "RestOnlineFileServer.doPost", "root.MSG_GEN_ENTER_METHOD");
    try {/*  www.  ja  va 2 s.  c  o  m*/
        OnlineFile file = getWantedFile(restRequest);
        if (file != null) {
            display(res, file);
            return;
        }
    } catch (IllegalAccessException ex) {
        res.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    displayWarningHtmlCode(res);
}

From source file:org.openmeetings.servlet.outputhandler.UploadController.java

@RequestMapping(value = "/file.upload", method = RequestMethod.POST)
public void handleFileUpload(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws ServletException {
    UploadInfo info = validate(request, false);
    try {/*from   w  w w .j a  va 2s  .c  om*/
        LinkedHashMap<String, Object> hs = prepareMessage(info);
        String room_idAsString = request.getParameter("room_id");
        if (room_idAsString == null) {
            throw new ServletException("Missing Room ID");
        }

        Long room_id_to_Store = Long.parseLong(room_idAsString);

        String isOwnerAsString = request.getParameter("isOwner");
        if (isOwnerAsString == null) {
            throw new ServletException("Missing isOwnerAsString");
        }
        boolean isOwner = false;
        if (isOwnerAsString.equals("1")) {
            isOwner = true;
        }

        String parentFolderIdAsString = request.getParameter("parentFolderId");
        if (parentFolderIdAsString == null) {
            throw new ServletException("Missing parentFolderId ID");
        }
        Long parentFolderId = Long.parseLong(parentFolderIdAsString);

        String current_dir = context.getRealPath("/");

        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        log.debug("fileSystemName: " + info.filename);

        HashMap<String, HashMap<String, String>> returnError = fileProcessor.processFile(info.userId,
                room_id_to_Store, isOwner, is, parentFolderId, info.filename, current_dir, hs, 0L, ""); // externalFilesId,
        // externalType

        HashMap<String, String> returnAttributes = returnError.get("returnAttributes");

        // Flash cannot read the response of an upload
        // httpServletResponse.getWriter().print(returnError);
        hs.put("message", "library");
        hs.put("action", "newFile");
        hs.put("fileExplorerItem", fileExplorerItemDao.getFileExplorerItemsById(
                Long.parseLong(returnAttributes.get("fileExplorerItemId").toString())));
        hs.put("error", returnError);
        hs.put("fileName", returnAttributes.get("completeName"));
        sendMessage(info, hs);
    } catch (ServletException e) {
        throw e;
    } catch (Exception e) {
        log.error("Exception during upload: ", e);
        throw new ServletException(e);
    }
}

From source file:org.openmrs.module.personalhr.web.controller.PatientDashboardController.java

/**
 * This is called prior to displaying a form for the first time. It tells Spring the
 * form/command object to load into the request
 * //from  w w w  .  j  ava  2  s.c om
 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
 */
@Override
protected Object formBackingObject(final HttpServletRequest request) throws ServletException {
    this.log.debug("Entering PatientDashboardController.formBackingObject");

    if (!Context.isAuthenticated()) {
        return new Patient();
    }

    Patient patient = null;
    try {
        String patientId = request.getParameter("patientId");
        this.log.debug("patientId: " + patientId);
        if (patientId == null) {
            patientId = getPatientId(Context.getAuthenticatedUser());
            if (patientId == null) {
                //throw new ServletException("Integer 'patientId' is a required parameter");
                this.log.error("Integer 'patientId' is a required parameter");
                return new Patient();
            }
        }
        request.setAttribute("patientId", patientId);

        //Add temporary privilege
        //PersonalhrUtil.addTemporayPrivileges();

        final PatientService ps = Context.getPatientService();
        Integer id = null;

        try {
            id = Integer.valueOf(patientId);
            patient = ps.getPatient(id);
        } catch (final NumberFormatException numberError) {
            this.log.warn("Invalid patientId supplied: '" + patientId + "'", numberError);
        } catch (final ObjectRetrievalFailureException noPatientEx) {
            this.log.warn("There is no patient with id: '" + patientId + "'", noPatientEx);
        }

        if (patient == null) {
            throw new ServletException("There is no patient with id: '" + patientId + "'");
        }
    } finally {
        //PersonalhrUtil.removeTemporayPrivileges();
    }

    return patient;
}

From source file:jsst.server.FrontController.java

private void makeResponse(HttpServletResponse response, TestResult testResult)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    try {//from  www.  jav  a2 s.c  o m
        JSONObject jsonObject = convertToJSON(testResult);
        jsonObject.write(writer);
    } catch (JSONException e) {
        throw new ServletException(e);
    } finally {
        writer.close();
    }
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    random = new SecureRandom();
    String str_cfg = servletConfig.getInitParameter("cfg");
    Class c = null;/*from  w w w . ja va 2s.  co  m*/
    try {
        c = Class.forName(str_cfg);
        cfg = (DragDropServletConfig) c.newInstance();
        logger = cfg.getLogger();

        //used in 500.jsp for error logging
        servletConfig.getServletContext().setAttribute("mycfg", cfg);

    } catch (Exception e) {
        System.err.println(e.getMessage());
        throw new ServletException(e);
    }
    utils = new DragDropServletUtils(cfg.getFolder(), cfg.checkHash(), logger);
    logger.logDebug(".....................................Init drag drop servlet ok:" + str_cfg + ":"
            + cfg.getHandler() + ":" + cfg.getFolder());
}

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

/**
 * Gets the static enum.//from   w  ww .  j  av a  2  s  .  c om
 * 
 * @param type
 *            the type
 * 
 * @return the static enum
 * 
 * @throws ServletException
 *             the servlet exception
 */
private static synchronized Document getStaticEnum(String type, Map<String, String> initParams)
        throws ServletException {
    Document result;
    result = enums.get(type);
    if (result == null) {
        try {
            String baseFolderPath = AlfrescoController.getInstance().getParamBaseFolder(initParams)
                    + File.separator + "forms";

            String filename = baseFolderPath + File.separator + MsgId.INT_DIRECTORY_ENUMS + File.separator
                    + type + ".enum.xml";
            InputStream xformsStream = new FileInputStream(filename);
            // InputStream xformsStream =
            // NavigationSessionListener.getContext().getResourceAsStream(
            // "/forms/" + MsgId.INT_DIRECTORY_ENUMS + "/" + type + ".enum.xml");
            result = DOMUtil.getDocumentFromStream(xformsStream);
            fillValues(type, result);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        enums.put(type, result);
    }
    return result;
}