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:com.googlecode.jsfFlex.phaseListener.ObjectServiceRequestDataRetrieverFlusher.java

@Override
void retrieveFlushData(FacesContext context, String componentId, String methodToInvoke)
        throws ServletException, IOException {

    JSONObject methodResult = null;/* w  w w. j a v a  2s . co m*/

    try {
        methodResult = JSONObject.class
                .cast(invokeResourceMethod(context, componentId, methodToInvoke, null, null));
    } catch (Exception methodInvocationException) {
        throw new ServletException(methodInvocationException);
    }

    HttpServletResponse response = HttpServletResponse.class.cast(context.getExternalContext().getResponse());
    response.setContentType(XML_CONTENT_TYPE);

    StringBuilder responseContent = new StringBuilder();
    responseContent.append(XML_HEAD);

    try {
        responseContent.append(JSONConverter.convertJSONObjectToXMLString(methodResult));
    } catch (JSONException jsonException) {
        throw new ServletException(ERROR_CONVERTING_JSON_OBJECT_TO_XML, jsonException.getCause());
    }

    _log.info("Flushing content : " + responseContent.toString());

    Writer writer = response.getWriter();
    writer.write(responseContent.toString());
    writer.flush();

}

From source file:de.berlios.jedi.presentation.admin.LoginFilter.java

/**
 * Checks if the admin is logged in<br>
 * If admin isn't logged in, a forward to the login view is made.<br>
 * If admin is already logged in, the next element in the chain is invoked.
 * // w  w w.  jav  a2  s.c  o m
 * @throws IOException
 *             If an IOException occurs when filtering.
 * @throws ServletException
 *             If a ServletException occurs when filtering.
 * 
 * @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 {

    if (!(request instanceof HttpServletRequest)) {
        LogFactory.getLog(LoginFilter.class)
                .error("Unexpected error: request in LoginFilter" + "isn't a HttpServletRequest");
        throw new ServletException("Unexpected error: request in LoginFilter" + "isn't a HttpServletRequest");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Boolean isLoggedIn = (Boolean) httpRequest.getSession().getAttribute(AdminKeys.IS_LOGGED_IN);

    try {
        if (isLoggedIn == null || !isLoggedIn.booleanValue()) {
            httpRequest.getSession().getServletContext().getRequestDispatcher("/Admin/LoginView.do")
                    .forward(request, response);
            return;
        }

        chain.doFilter(request, response);
    } catch (IOException e) {
        LogFactory.getLog(LoginFilter.class).error("IOException in LoginFilter", e);
        throw e;
    } catch (ServletException e) {
        LogFactory.getLog(LoginFilter.class).error("ServletException in LoginFilter", e);
        throw e;
    }
}

From source file:UploadDownloadFile.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);//from   w ww  . j a  v a2s .c  om
    System.out.println("--> doGet -->");
    String filePath;

    String fileName = request.getParameter("fileName");
    if (fileName == null || fileName.equals("")) {
        throw new ServletException("File Name can't be null or empty");
    }
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    File file = new File(filePath + File.separator + fileName);

    System.out.println("download file = " + file);
    if (!file.exists()) {
        throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::" + file.getAbsolutePath());
    ServletContext ctx = getServletContext();
    InputStream fis = new FileInputStream(file);
    String mimeType = ctx.getMimeType(file.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) file.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while ((read = fis.read(bufferData)) != -1) {
        os.write(bufferData, 0, read);
    }
    os.flush();
    os.close();
    fis.close();
    System.out.println("File downloaded at client successfully");
}

From source file:by.creepid.jsf.fileupload.UploadFilter.java

@SuppressWarnings("unchecked")
@Override// w  w w.j  av  a 2 s.co m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((request instanceof HttpServletRequest)) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        if (ServletFileUpload.isMultipartContent(httpRequest)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(new File(repositoryPath));

            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

                List<FileItem> items = (List<FileItem>) upload.parseRequest(httpRequest);
                final Map<String, String[]> map = new HashMap<String, String[]>();

                for (FileItem item : items) {
                    if (item.isFormField()) {
                        processFormField(item, map);
                    } else {
                        processFileField(item, httpRequest);
                    }
                }

                request = UploadFilter.wrapRequest(httpRequest, map);

            } catch (FileUploadException ex) {
                throw new ServletException(ex);
            }
        }
    }
    chain.doFilter(request, response);
}

From source file:com.googlecode.jsfFlex.phaseListener.ArrayServiceRequestDataRetrieverFlusher.java

@Override
void retrieveFlushData(FacesContext context, String componentId, String methodToInvoke)
        throws ServletException, IOException {

    JSONArray methodResult = null;//from w w w .  j  a va 2  s .  c  om

    try {
        methodResult = JSONArray.class
                .cast(invokeResourceMethod(context, componentId, methodToInvoke, null, null));
    } catch (Exception methodInvocationException) {
        throw new ServletException(methodInvocationException);
    }

    HttpServletResponse response = HttpServletResponse.class.cast(context.getExternalContext().getResponse());
    response.setContentType(XML_CONTENT_TYPE);

    StringBuilder responseContent = new StringBuilder();
    responseContent.append(XML_HEAD);
    responseContent.append(XML_RESULT_ROOT_START_TAG);

    try {
        responseContent.append(JSONConverter.convertJSONArrayToXMLString(methodResult));
    } catch (JSONException jsonException) {
        throw new ServletException(ERROR_CONVERTING_JSON_ARRAY_TO_XML, jsonException.getCause());
    }

    responseContent.append(XML_RESULT_ROOT_END_TAG);

    _log.info("Flushing content : " + responseContent.toString());

    Writer writer = response.getWriter();
    writer.write(responseContent.toString());
    writer.flush();

}

From source file:edu.umd.cs.submitServer.servlets.UploadTestSetup.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO sanity checks on the format of the test setup
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    Connection conn = null;//from  w w  w  .  ja  v a  2  s  .  c  o m
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        fileItem = multipartRequest.getFileItem();
        if (fileItem == null)
            throw new ServletException("fileItem is null; this is not good");

        Project project = (Project) request.getAttribute(PROJECT);
        // could be null
        String comment = multipartRequest.getOptionalCheckedParameter("comment");

        // get size in bytes
        long sizeInBytes = fileItem.getSize();
        if (sizeInBytes == 0) {
            throw new ServletException("Trying upload file of size 0");
        }

        // copy the fileItem into a byte array
        InputStream is = fileItem.getInputStream();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes);
        IO.copyStream(is, bytes);

        byte[] byteArray = bytes.toByteArray();

        FormatDescription desc = FormatIdentification.identify(byteArray);
        if (desc == null || !desc.getMimeType().equals("application/zip")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You MUST submit test-setups that are either zipped or jarred");
            return;
        }
        Submission canonicalSubmission = Submission
                .lookupMostRecent(project.getCanonicalStudentRegistrationPK(), project.getProjectPK(), conn);
        // start transaction here
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        TestSetup.submit(byteArray, project, comment, conn);
        conn.commit();
        transactionSuccess = true;
        if (canonicalSubmission != null
                && canonicalSubmission.getBuildStatus() != Submission.BuildStatus.BROKEN) {
            WaitingBuildServer.offerSubmission(project, canonicalSubmission);
        }

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
        releaseConnection(conn);
        if (fileItem != null)
            fileItem.delete();
    }
}

From source file:fi.jyu.student.jatahama.onlineinquirytool.server.LoadSaveServlet.java

@Override
public final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//ww  w  . ja va  2s.c  o  m
        // Always server same page. Used to check if Servlet exists.
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader(Utils.httpHeaderNameHello, "Hello!");
        //         response.setStatus(307);
        //         response.setHeader("Location", "../");
        ServletOutputStream out = response.getOutputStream();
        out.print("<html><head><META HTTP-EQUIV=REFRESH CONTENT=\"0; URL=../\"><!-- "
                + Utils.httpHeaderNameHello + ": Hello! --></head><body><a href=\"../\">App</a></body></html>");
        out.flush();
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:org.araneaframework.ioc.spring.SimpleAraneaSpringDispatcherServlet.java

public void init() throws ServletException {
    beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

    rootConf = new XmlBeanFactory(
            new ClassPathResource("spring-property-conf/property-custom-webapp-aranea-conf.xml"), beanFactory);
    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setLocation(new ClassPathResource("spring-property-conf/default-aranea-conf.properties"));

    Properties localConf = new Properties();
    try {// w  ww. j a v a 2s . co  m
        if (getServletContext().getResource("/WEB-INF/aranea-conf.properties") != null)
            localConf.load(getServletContext().getResourceAsStream("/WEB-INF/aranea-conf.properties"));
    } catch (IOException e) {
        throw new ServletException(e);
    }
    cfg.setProperties(localConf);
    cfg.setLocalOverride(true);

    cfg.postProcessBeanFactory(rootConf);

    super.init();
}

From source file:com.vilt.spring.context.response.OncePerRequestContextFilter.java

/**
 * This <code>doFilter</code> implementation stores a request attribute for
 * "already filtered", proceeding without filtering again if the attribute
 * is already there./*  ww w . j av a  2 s . co m*/
 * 
 * @see #getAlreadyFilteredAttributeName
 * @see #doFilterInternal
 */
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        throw new ServletException("OncePerRequestContextFilter just supports HTTP requests");
    }
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    if (request.getAttribute(alreadyFilteredAttributeName) != null) {
        // Proceed without invoking this filter...
        filterChain.doFilter(request, response);
        return;
    }
    // Do invoke this filter...
    request.setAttribute(alreadyFilteredAttributeName, TRUE);
    try {
        doFilterInternal(httpRequest, httpResponse, filterChain);
    } finally {
        // Remove the "already filtered" request attribute for this
        // request.
        request.removeAttribute(alreadyFilteredAttributeName);
    }
}

From source file:com.squarecash4glass.servlet.OAuth2AuthorizationServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    String provider = getProvider(req);
    LOG.info("in oauth flow for: " + provider);
    Configuration oauthConfiguration;
    try {/* w  w  w . j  a v a2s  .  c  o m*/
        oauthConfiguration = Oauth2Factory.getOauth2Configuration(provider, "sandbox");
    } catch (ConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        throw new ServletException(e1);
    }
    OAuth2Util oAuth2Util = Oauth2Factory.getOauth2Util(oauthConfiguration);
    if (req.getParameter("error") != null) {
        LOG.severe("Something went wrong during auth: " + req.getParameter("error"));
        res.setContentType("text/plain");
        res.getWriter().write("Something went wrong during auth. Please check your log for details");
        return;
    }

    // If we have a code, finish the OAuth 2.0 dance
    if (req.getParameter("code") != null) {
        LOG.info("Got a code. Attempting to exchange for access token.");

        TokenResponse tokenResponse = null;
        AuthorizationCodeFlow flow = oAuth2Util.newAuthorizationCodeFlow();

        try {

            tokenResponse = flow.newTokenRequest(req.getParameter("code"))
                    .setRedirectUri(WebUtil.buildUrl(req, oauthConfiguration.getString("oauthcallback")))
                    .execute();

        } catch (TokenResponseException e) {
            LOG.severe("exception getting token: " + e.getMessage());
            throw e;
        }

        LOG.info("tokenResponse: " + tokenResponse);

        if ("google".equals(provider)) {
            // Extract the Google User ID from the ID token in the auth response
            Payload googlePayload = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload();
            String userId = googlePayload.getSubject();
            String email = googlePayload.getEmail();
            req.getSession().setAttribute("userId", userId);
            User user = new User(userId, email);
            ofy().save().entities(user).now();
            LOG.info("Code exchange worked. User " + userId + " logged in.");
        }

        String userid = OAuth2Util.getUserId(req);
        flow.createAndStoreCredential(tokenResponse, userid + oauthConfiguration.getString("useridPostfix"));

        // Redirect back to index
        res.sendRedirect(WebUtil.buildUrl(req, "/main"));
        return;
    }

    // Else, we have a new flow. Initiate a new flow.
    LOG.info("No auth context found. Kicking off a new dwolla auth flow.");

    AuthorizationCodeFlow flow = oAuth2Util.newAuthorizationCodeFlow();
    GenericUrl url = flow.newAuthorizationUrl()
            .setRedirectUri(WebUtil.buildUrl(req, oauthConfiguration.getString("oauthcallback")));
    adjustURL(provider, url);
    LOG.info("redirecting to URL: " + url.build());
    res.sendRedirect(url.build());
}