Example usage for javax.servlet.http HttpServletResponse isCommitted

List of usage examples for javax.servlet.http HttpServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:org.nuxeo.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    Throwable unwrappedException = unwrapException(t);

    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;//  w w  w.j av a  2s  .c om
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);

            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

From source file:org.ecside.filter.ECSideFilter.java

 public void handleExport(HttpServletRequest request,
      HttpServletResponse response, WebContext context) {
   try {//from  ww w  .  jav  a  2 s.  c om
      Object viewData = request.getAttribute(TableConstants.VIEW_DATA);
      if (viewData != null) {
         Preferences preferences = new TableProperties();
         preferences.init(null, TableModelUtils
               .getPreferencesLocation(context));
         String viewResolver = (String) request
               .getAttribute(TableConstants.VIEW_RESOLVER);
         Class classDefinition = Class.forName(viewResolver);
         ViewResolver handleExportViewResolver = (ViewResolver) classDefinition
               .newInstance();
         request.setAttribute(TableConstants.SERVLET_REAL_PATH,
               servletRealPath);
         handleExportViewResolver.resolveView(request, response,
               preferences, viewData);
         // response.flushBuffer();
         if (!response.isCommitted()) {
            response.getOutputStream().flush();
            response.getOutputStream().close();
         }
      }
   } catch (Exception e) {
      LogHandler.errorLog(logger, e);
   }
}

From source file:com.alfaariss.oa.sso.web.WebSSOServlet.java

/**
 * Process the WebSSO HTTP requests./*from   w  w  w .j  a v  a  2 s .c om*/
 * @throws IOException 
 * 
 * @see javax.servlet.http.HttpServlet#service(
 *  javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 *  
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        if (_defaultSSOProfile == null)
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, oRequest.getRequestURI());

        String sTarget = resolveTarget(oRequest);
        if (sTarget == null)
            _defaultSSOProfile.service(oRequest, oResponse);
        else {
            ISSOProfile ssoProfile = _mapSSOProfiles.get(sTarget);
            if (ssoProfile != null & (ssoProfile instanceof IService)) {
                ((IService) ssoProfile).service(oRequest, oResponse);
            } else {//if profile not found by target, then use default profile
                _defaultSSOProfile.service(oRequest, oResponse);
            }
        }

        //send okay if no response is sent yet
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Could not process request", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Could not process request due to internal error", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.openbravo.service.datasource.DataSourceServlet.java

private void handleException(Exception e, HttpServletResponse response) throws IOException {
    log4j.error(e.getMessage(), e);// w w  w  .ja  va  2 s  . c om
    if (e instanceof SQLGrammarException) {
        log.error(((SQLGrammarException) e).getSQL());
    }
    if (!response.isCommitted()) {
        final JSONObject jsonResult = new JSONObject();
        final JSONObject jsonResponse = new JSONObject();
        String result = "";
        try {
            jsonResponse.put(JsonConstants.RESPONSE_STATUS, JsonConstants.RPCREQUEST_STATUS_VALIDATION_ERROR);
            jsonResponse.put("error", KernelUtils.getInstance().createErrorJSON(e));
            jsonResult.put(JsonConstants.RESPONSE_RESPONSE, jsonResponse);
            result = jsonResult.toString();
        } catch (JSONException e1) {
            log.error("Error genearating JSON error", e1);
        }
        writeResult(response, result);
    }
}

From source file:org.nema.medical.mint.server.controller.StudySummaryController.java

@RequestMapping("/studies/{uuid}/{type}/summary")
public void studiesSummary(@PathVariable("uuid") final String uuid, @PathVariable("type") final String type,
        final HttpServletResponse res) throws IOException {
    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;//from  www.  ja  v a 2  s .c  om
    }

    final File studyDir = new File(studiesRoot, uuid);
    final File typeDir = new File(studyDir, type);
    if (!typeDir.exists() || !typeDir.canRead()) {
        LOG.error("Unable to locate directory for study: " + studyDir);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid study requested: Not found");
        return;
    }

    try {
        final File file = new File(typeDir, "/summary.xml");
        if (!file.exists()) {
            StudyMetadata study = StudyIO.loadStudy(typeDir);
            StudyIO.writeSummaryToXML(study, file);
        }

        res.setContentType("text/xml");
        res.setContentLength(Long.valueOf(file.length()).intValue());
        res.setBufferSize(fileResponseBufferSize);
        Utils.streamFile(file, res.getOutputStream(), fileStreamBufferSize);
    } catch (final IOException e) {
        if (!res.isCommitted()) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Unable to provide study summary. See server logs.");
            return;
        }
    }
}

From source file:com.almende.eve.transport.http.DebugServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    // If this is a handshake request, handle it.
    if (handleHandShake(req, resp)) {
        return;/* w  ww.j  a  va 2s.co m*/
    }

    final String url = req.getRequestURI();
    final String id = getId(url);
    if (id == null || id.equals("") || id.equals(myUrl.toASCIIString())) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Couldn't parse URL, missing 'id'");
        resp.flushBuffer();
        return;
    }
    if (myUrl != null) {
        final HttpTransport transport = HttpService.get(myUrl, id);
        if (transport != null) {
            // get the resource name from the end of the url

            String resource = getResource(url);
            if (resource == null || resource.equals("")) {
                if (!url.endsWith("/") && !resp.isCommitted()) {
                    final String redirect = url + "/";
                    resp.sendRedirect(redirect);
                    return;
                }
                resource = "index.html";
            }
            final String extension = resource.substring(resource.lastIndexOf('.') + 1);
            // load the resource
            final String mimetype = StreamingUtil.getMimeType(extension);

            final String filename = RESOURCES + resource;
            final InputStream is = this.getClass().getResourceAsStream(filename);
            if (is != null) {
                StreamingUtil.streamBinaryData(is, mimetype, resp);
            } else {
                throw new ServletException(
                        "Resource '" + resource + "' not found. (filename:'" + filename + "')");
            }
            resp.flushBuffer();
        } else {
            resp.setContentType("text/plain");
            resp.getWriter().println("Agent:" + id + " is unknown!");
            resp.getWriter().close();
            resp.flushBuffer();
        }
    } else {
        resp.setContentType("text/plain");
        resp.getWriter().println("You've found the servlet for agent:" + id);
        resp.getWriter().close();
        resp.flushBuffer();
    }
}

From source file:com.ultrapower.eoms.common.plugin.ecside.filter.ECSideFilter.java

    public void handleExport(HttpServletRequest request, HttpServletResponse response, WebContext context) {
        try {/*w ww.jav  a  2  s .  co m*/
            Object viewData = request.getAttribute(TableConstants.VIEW_DATA);
            if (viewData != null) {
                Preferences preferences = new TableProperties();
                preferences.init(null, TableModelUtils.getPreferencesLocation(context));
                String viewResolver = (String) request.getAttribute(TableConstants.VIEW_RESOLVER);
                Class classDefinition = Class.forName(viewResolver);
                ViewResolver handleExportViewResolver = (ViewResolver) classDefinition.newInstance();
                request.setAttribute(TableConstants.SERVLET_REAL_PATH, servletRealPath);
                handleExportViewResolver.resolveView(request, response, preferences, viewData);
//            response.flushBuffer();
                if (!response.isCommitted()){
                   response.getOutputStream().flush();
                   response.getOutputStream().close();
                }
            }
        } catch (Exception e) {
           LogHandler.errorLog(logger, e);
        }
    }

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Send a JSON-RPC message to an agent Usage: POST /servlet/{agentId} With a
 * JSON-RPC request as body. Response will be a JSON-RPC response.
 * //from www .  ja v a2  s .co m
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ServletException
 *             the servlet exception
 */
@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, ServletException {

    // retrieve the agent url and the request body
    final String body = StringUtil.streamToString(req.getInputStream());

    final String agentUrl = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(agentUrl));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    if (agentId == null || agentId.equals("")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No agentId found in url.");
        resp.flushBuffer();
        return;
    }

    if (host.hasPrivate(agentId) && !handleSession(req, resp)) {
        if (!resp.isCommitted()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
        resp.flushBuffer();
        return;
    }

    // Attach the claimed senderId, or null if not given.
    String senderUrl = req.getHeader("X-Eve-SenderUrl");
    if (senderUrl == null || senderUrl.equals("")) {
        senderUrl = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr();
    }
    final String tag = new UUID().toString();

    final SyncCallback<String> callback = new SyncCallback<String>();

    final AsyncCallbackQueue<String> callbacks = host.getCallbackQueue("HttpTransport", String.class);
    callbacks.push(tag, "", callback);
    //TODO: check if it's base64 encoded data, decode to byte[] and call receive byte[].
    host.receive(agentId, body, URI.create(senderUrl), tag);

    try {
        final Object message = callback.get();
        // return response
        resp.addHeader("Content-Type", "application/json");
        resp.getWriter().println(message.toString());
        resp.getWriter().close();
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "Http Sync receive raised exception.", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Receiver raised exception:" + e.getMessage());
    }
    resp.flushBuffer();
}

From source file:com.fluidops.iwb.server.SparqlServlet.java

/**
 * Send the specified error message to the client (if the connection is
 * still open)./*  w  w  w  . j  a  va2s.  co  m*/
 * 
 * @param resp
 * @param errorCode
 * @param message
 */
protected void error(HttpServletResponse resp, int errorCode, String message) {

    try {
        log.info("Error (" + errorCode + "): " + message);
        if (!resp.isCommitted())
            resp.sendError(errorCode, message);
    } catch (IllegalStateException e) {
        // should never occur
        log.warn("Error message could not be send. Stream is committed: " + message);
    } catch (IOException e) {
        log.error("Error message could not be sent", e);
    }
}

From source file:org.alfresco.web.app.servlet.AdminAuthenticationFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///from   w  ww.  j  av  a  2s.c  om
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) req;
    HttpServletResponse httpResponse = (HttpServletResponse) res;

    // The fact that this filter is being called means a request for a protected
    // resource has taken place, check that the current user is in fact an
    // administrator.

    if (logger.isDebugEnabled())
        logger.debug("Authorising request for protected resource: " + httpRequest.getRequestURI());

    // there should be a user at this point so retrieve it
    User user = AuthenticationHelper.getUser(this.config.getServletContext(), httpRequest, httpResponse);

    // if the user is present check to see whether it is an admin user
    boolean isAdmin = (user != null && user.isAdmin());

    if (isAdmin) {
        if (logger.isDebugEnabled())
            logger.debug("Current user has admin authority, allowing access.");

        // continue filter chaining if current user is admin user
        chain.doFilter(req, res);
    } else {
        // return the 401 Forbidden error as the current user is not an administrator
        // if the response has already been committed there's nothing we can do but
        // print out a warning
        if (httpResponse.isCommitted() == false) {
            if (logger.isDebugEnabled())
                logger.debug("Current user does not have admin authority, returning 401 Forbidden error...");

            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else {
            if (logger.isWarnEnabled())
                logger.warn("Access denied to '" + httpRequest.getRequestURI()
                        + "'. The response has already been committed so a 401 Forbidden error could not be sent!");
        }
    }
}