Example usage for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR

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

Introduction

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

Prototype

int SC_INTERNAL_SERVER_ERROR

To view the source code for javax.servlet.http HttpServletResponse SC_INTERNAL_SERVER_ERROR.

Click Source Link

Document

Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.

Usage

From source file:org.openrepose.commons.utils.http.ServiceClient.java

private ServiceClientResponse execute(HttpRequestBase base, String... queryParameters) {
    try {/*from w  ww .  j a v a 2s  .  c  o  m*/

        HttpClient client = getClientWithBasicAuth();

        for (int index = 0; index < queryParameters.length; index = index + 2) {
            client.getParams().setParameter(queryParameters[index], queryParameters[index + 1]);
        }

        HttpResponse httpResponse = client.execute(base);
        HttpEntity entity = httpResponse.getEntity();

        InputStream stream = null;
        if (entity != null) {
            stream = new ByteArrayInputStream(RawInputStreamReader.instance().readFully(entity.getContent()));
            EntityUtils.consume(entity);
        }

        return new ServiceClientResponse(httpResponse.getStatusLine().getStatusCode(),
                httpResponse.getAllHeaders(), stream);
    } catch (ServiceClientException ex) {
        LOG.error("Failed to obtain an HTTP default client connection", ex);
    } catch (IOException ex) {
        LOG.error("Error executing request", ex);
    } finally {
        base.releaseConnection();

    }

    return new ServiceClientResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
}

From source file:org.ngrinder.script.controller.SvnDavController.java

/**
 * Request Handler.//from   w w  w .ja va 2  s  .c o  m
 *
 * @param request  request
 * @param response response
 * @throws ServletException occurs when servlet has a problem.
 * @throws IOException      occurs when file system has a problem.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (LOGGER.isTraceEnabled()) {
        logRequest(request);
    }
    try {
        // To make it understand Asian Language..
        request = new MyHttpServletRequestWrapper(request);
        DAVRepositoryManager repositoryManager = new DAVRepositoryManager(getDAVConfig(), request);
        ServletDAVHandler handler = DAVHandlerFactory.createHandler(repositoryManager, request, response);
        handler.execute();
    } catch (DAVException de) {
        response.setContentType(XML_CONTENT_TYPE);
        handleError(de, response);
    } catch (SVNException svne) {
        StringWriter sw = new StringWriter();
        svne.printStackTrace(new PrintWriter(sw));

        /**
         * truncate status line if it is to long
         */
        String msg = sw.getBuffer().toString();
        if (msg.length() > 128) {
            msg = msg.substring(0, 128);
        }
        SVNErrorCode errorCode = svne.getErrorMessage().getErrorCode();
        if (errorCode == SVNErrorCode.FS_NOT_DIRECTORY || errorCode == SVNErrorCode.FS_NOT_FOUND
                || errorCode == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        } else if (errorCode == SVNErrorCode.NO_AUTH_FILE_PATH) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        } else if (errorCode == SVNErrorCode.RA_NOT_AUTHORIZED) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, msg);
        } else {
            String errorBody = generateStandardizedErrorBody(errorCode.getCode(), null, null,
                    svne.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType(XML_CONTENT_TYPE);
            response.getWriter().print(errorBody);
        }
    } catch (Throwable th) {
        StringWriter sw = new StringWriter();
        th.printStackTrace(new PrintWriter(sw));
        String msg = sw.getBuffer().toString();
        LOGGER.debug("Error in DavSVN Controller", th);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    } finally {
        response.flushBuffer();
    }
}

From source file:org.dataconservancy.ui.api.FileController.java

/**
 * Accepts the parameters as specified below and returns the content of the file with matching id and qualifies the
 * criteria specified in the request header.
 * @param idpart id string that uniquely identify requested.
 * @param mimeType specifies the acceptable type of the response's content. The matching file's mime type is
 *        determined using the {@link javax.activation.MimetypesFileTypeMap}'s default map.
 * @param modifiedSince specifies that the request is only for file with matching id that has been modified
 *        since the {@code modifiedSince} date. Files with matching ids that has not been modified since
 *        {@code modifiedSince} date will be disqualified and not returned.
 * @param request http request//from w  ww .j  a  va 2s. co m
 * @throws {@link IOException} when an exception occurs when writing to the {@link HttpServletResponse} object.
 *
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.GET })
public void handleFileGetRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp) throws IOException {

    // this impl does not require authz at the moment, but need a user for the fileBizService getFile method
    // ok if null
    Person user = getAuthenticatedUser();

    // Get file id from the request
    String id = requestUtil.buildRequestUrl(request);

    // Resolve the Request URL to the ID of the file (in this case URL == ID)
    if (id == null || id.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    try {

        archiveService.pollArchive();

        // Get file's last modified date via the fileBizService if it is a DataFile, or
        // via the metadataFileBizService if it is a MetadataFile

        DateTime lastModifiedDate = (fileBizService.getLastModifiedDate(id) != null)
                ? fileBizService.getLastModifiedDate(id)
                : metadataFileBizService.getLastModifiedDate(id);

        // Handle if-modified-since header
        if (failIfModifiedSinceHeader(request, resp, modifiedSince, lastModifiedDate)) {
            return;
        }

        // Get file via fileBizService if it is a DataFile, or
        // via the metadataFileBizService if it is a MetadataFile
        DataFile file = null;
        if (fileBizService.getFile(id, user) != null) {
            file = fileBizService.getFile(id, user);
        } else {
            file = metadataFileBizService.retrieveMetadataFile(id);
        }

        //If file is not found
        if (file == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No file matching this id " + id + " was found.");
        } else { //if file is found

            String fileMimeType = file.getFormat();

            if (fileMimeType == null) {
                fileMimeType = "application/octet-stream";
            }

            //Handling mimeType header
            if (failAcceptHeader(request, resp, mimeType, fileMimeType)) {
                return;
            }

            //Set the Content-Length
            resp.setContentLength((int) file.getSize());
            resp.setStatus(HttpStatus.SC_OK);
            //Calculate ETAG
            resp.setHeader(ETAG, ETagCalculator.calculate(Integer.toString(file.hashCode())));
            DateTimeFormatter fmt = new DateTimeFormatterBuilder().appendPattern("EEE, dd MMM yyyy HH:mm:ss Z")
                    .toFormatter();
            String rfcDate = fmt.print(lastModifiedDate);
            resp.setHeader(LAST_MODIFIED, rfcDate);
            //Set Content-Disposition
            resp.setHeader(CONTENT_DISPOSITION,
                    getResponseContentDispositionString("\"" + file.getName() + "\"", file.getSize()));
            //Set Content-Type
            resp.setContentType(fileMimeType);

            InputStream is = new URL(file.getSource()).openStream();
            IOUtils.copy(is, resp.getOutputStream());
            is.close();
        }
    } catch (BizPolicyException be) {
        handleException(be, request, resp);
    } catch (ArchiveServiceException ae) {
        handleException(ae, request, resp);
    } catch (RelationshipConstraintException re) {
        handleException(re, request, resp);
    }
}

From source file:com.xpn.xwiki.web.DeleteAttachmentAction.java

/**
 * {@inheritDoc}//www. j a v a  2  s .c  om
 * 
 * @see com.xpn.xwiki.web.XWikiAction#action(com.xpn.xwiki.XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    XWikiAttachment attachment = null;
    XWiki xwiki = context.getWiki();
    String filename;

    // Delete from the trash
    if (request.getParameter("trashId") != null) {
        long trashId = NumberUtils.toLong(request.getParameter("trashId"));
        DeletedAttachment da = xwiki.getAttachmentRecycleBinStore().getDeletedAttachment(trashId, context,
                true);
        // If the attachment hasn't been previously deleted (i.e. it's not in the deleted attachment store) then
        // don't try to delete it and instead redirect to the attachment list.
        if (da != null) {
            com.xpn.xwiki.api.DeletedAttachment daapi = new com.xpn.xwiki.api.DeletedAttachment(da, context);
            if (!daapi.canDelete()) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS,
                        XWikiException.ERROR_XWIKI_ACCESS_DENIED,
                        "You are not allowed to delete an attachment from the trash "
                                + "immediately after it has been deleted from the wiki");
            }
            if (!da.getDocName().equals(doc.getFullName())) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
                        XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
                        "The specified trash entry does not match the current document");
            }
            // TODO: Add a confirmation check
            xwiki.getAttachmentRecycleBinStore().deleteFromRecycleBin(trashId, context, true);
        }
        sendRedirect(response, Utils.getRedirect("attach", context));
        return false;
    }

    if (context.getMode() == XWikiContext.MODE_PORTLET) {
        filename = request.getParameter("filename");
    } else {
        // Note: We use getRequestURI() because the spec says the server doesn't decode it, as
        // we want to use our own decoding.
        String requestUri = request.getRequestURI();
        filename = Util.decodeURI(requestUri.substring(requestUri.lastIndexOf("/") + 1), context);
    }

    XWikiDocument newdoc = doc.clone();

    // An attachment can be indicated either using an id, or using the filename.
    if (request.getParameter("id") != null) {
        int id = NumberUtils.toInt(request.getParameter("id"));
        if (newdoc.getAttachmentList().size() > id) {
            attachment = newdoc.getAttachmentList().get(id);
        }
    } else {
        attachment = newdoc.getAttachment(filename);
    }

    // No such attachment
    if (attachment == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        if (vcontext != null) {
            vcontext.put("message",
                    context.getMessageTool().get("core.action.deleteAttachment.failed", filename));
            vcontext.put("details",
                    context.getMessageTool().get("platform.core.action.deleteAttachment.noAttachment"));
        }
        return true;
    }

    newdoc.setAuthor(context.getUser());

    // Set "deleted attachment" as the version comment.
    ArrayList<String> params = new ArrayList<String>();
    params.add(filename);
    if (attachment.isImage(context)) {
        newdoc.setComment(context.getMessageTool().get("core.comment.deleteImageComment", params));
    } else {
        newdoc.setComment(context.getMessageTool().get("core.comment.deleteAttachmentComment", params));
    }

    try {
        newdoc.deleteAttachment(attachment, context);

        // Needed to counter a side effect: the attachment is deleted from the newdoc.originalDoc as well
        newdoc.setOriginalDocument(doc);

        // Also save the document and attachment metadata
        context.getWiki().saveDocument(newdoc, context);
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        if (vcontext != null) {
            vcontext.put("message",
                    context.getMessageTool().get("core.action.deleteAttachment.failed", filename));
            vcontext.put("details", ExceptionUtils.getRootCauseMessage(ex));
        }
        return true;
    }

    // forward to attach page
    String redirect = Utils.getRedirect("attach", context);
    sendRedirect(response, redirect);

    return false;
}

From source file:com.kurento.kmf.content.internal.base.AbstractContentHandlerServlet.java

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

    if (useControlProtocol) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_NOT_IMPLEMENTED,
                "Only POST request are supported for this service. You can enable GET requests "
                        + " by setting useControlProtocol to false on the appropriate handler annotation");
        return;//from w  w w. ja  va 2  s .co  m
    }

    getLogger().info("GET request received: " + req.getRequestURI());

    if (!req.isAsyncSupported()) {
        // Async context could not be created. It is not necessary to
        // complete it. Just send error message to
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "AsyncContext could not be started. The application should add \"asyncSupported = true\" in all "
                        + this.getClass().getName() + " instances and in all filters in the associated chain");
        return;
    }
    if (handler == null) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                handler.getClass().getSimpleName() + " is null. This error means that you "
                        + "need to provide a valid implementation of interface "
                        + handler.getClass().getSimpleName());
        return;
    }

    String contentId = req.getPathInfo();
    if (contentId != null) {
        contentId = contentId.substring(1);
    }

    AsyncContext asyncCtx = req.startAsync();

    // Add listener for managing error conditions
    asyncCtx.addListener(new ContentAsyncListener());

    doRequest4SimpleHttpProtocol(asyncCtx, contentId, resp);

}

From source file:com.homesnap.webserver.AbstractRestApi.java

protected JSONObject putRequestJSONObject(String urn, String body, int returnCodeExpected) {
    Client client = Client.create();//from w w  w .  jav a  2 s .  c o  m
    WebResource webResource = client.resource("http://" + server + ":" + port + urn);

    String json = null;
    try {
        ClientResponse response = webResource.accept("application/json").put(ClientResponse.class, body);
        Assert.assertEquals(returnCodeExpected, response.getStatus());
        if (returnCodeExpected == HttpServletResponse.SC_NOT_IMPLEMENTED
                || returnCodeExpected == HttpServletResponse.SC_NOT_ACCEPTABLE
                || returnCodeExpected == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            return null;
        }
        json = response.getEntity(String.class);
        return JSonTools.fromJson(json);
    } catch (JSONException e) {
        e.printStackTrace();
        Assert.fail("Problem with JSON [" + json + "] :" + e.getMessage());
    }
    Assert.fail("Problem when call [" + urn + "].");
    return null;
}

From source file:edu.ucsd.library.dams.api.FileStoreServlet.java

/**
 * Process the actual request./*from ww w .  ja v  a  2 s  . com*/
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not
 *  (HEAD).
 * @throws IOException If something fails at I/O level.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException {
    // Validate the requested file -------------------------------------

    // Get requested file by path info.
    /* start ucsd changes */

    // get object and file ids from path
    String objid = null;
    String cmpid = null;
    String fileid = null;
    try {
        // /bb1234567x/1.tif
        // /bb1234567x/1/2.tif
        String[] path = request.getPathInfo().split("/");
        if (path.length == 3) {
            objid = path[1];
            fileid = path[2];
        } else if (path.length == 4) {
            objid = path[1];
            cmpid = path[2];
            fileid = path[3];
        }
    } catch (Exception e) {
        String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo();
        log.error(errorMessage, e);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage);
        return;
    }

    // make sure required parameters are populated
    if (objid == null || objid.trim().length() == 0 || fileid == null || fileid.trim().length() == 0) {
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Subject and file must be specified in the request URI");
        return;
    }
    String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid;

    // first load the FileStore (no point if this doesn't work)
    FileStore fs = null;
    long fsTime = 0;
    try {
        long start = System.currentTimeMillis();
        fs = FileStoreUtil.getFileStore(props, fsDefault);
        fsTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        response.setContentType("text/plain");
        response.sendError(response.SC_INTERNAL_SERVER_ERROR, "Error initializing FileStore");
        ex.printStackTrace();
        return;
    }

    // check authorization attribute
    String restricted = null;
    String authorized = (String) request.getAttribute("edu.ucsd.library.dams.api.DAMSAPIServlet.authorized");
    if (authorized == null || !authorized.equals("true")) {
        log.warn("Illegal Access from IP " + request.getRemoteAddr() + " for file " + fullFilename);
        response.setContentType("text/plain");
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access without authorization.");
        return;
    } else {
        log.info("DAMS Access authorized for IP " + request.getRemoteAddr() + " for file " + fullFilename);
        restricted = (String) request.getAttribute("pas.restricted");
        //Disable browser caching for restricted objects.
        if (restricted != null && restricted.equals("1")) {
            String browser = request.getHeader("User-Agent");
            if (browser != null && browser.indexOf("MSIE") != -1) {
                response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            } else {
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            }
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
        }
    }
    /* end ucsd changes */

    // load file metadata
    Map<String, String> meta = null;
    long metaTime = 0;
    try {
        long start = System.currentTimeMillis();
        meta = fs.meta(objid, cmpid, fileid);
        metaTime = System.currentTimeMillis() - start;
    } catch (Exception ex) {
        log.error("File " + fullFilename + " doesn't exist.", ex);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file
    String length = meta.get("Content-Length");
    String lastModStr = meta.get("Last-Modified");
    long lastModified = 0L;
    try {
        lastModified = df.parse(lastModStr).getTime();
    } catch (Exception ex) {
        // error parsing lastmod date... set to now
        lastModified = System.currentTimeMillis();
    }
    String eTag = meta.get("ETag");
    if (eTag == null) {
        eTag = fullFilename + "_" + length + "_" + lastModified;
    }

    // Validate request headers for caching -----------------------------

    // If-None-Match header should contain "*" or ETag. If so, return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified.
    // If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Prepare and initialize response ----------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fullFilename);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.  For all
    // content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    //If UCSD download
    boolean download = request.getParameter("download") != null;
    if (download) {
        disposition = "attachment";
        contentType = "application/x-download";
    }
    // Else if content type is text, then determine whether GZIP content
    // encoding is supported by the browser and expand content type with
    // the one and right character encoding.
    else if (contentType.startsWith("text")) {
        //String acceptEncoding = request.getHeader("Accept-Encoding");
        //acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by the browser, then set to inline, else
    // attachment which will pop a 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    String sFileName = request.getParameter("name");
    if (sFileName == null || (sFileName = sFileName.trim()).length() == 0)
        sFileName = fullFilename;

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + sFileName + "\"");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    /* begin ucsd changes */
    if (restricted == null || !restricted.equals("1")) {
        response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
    }
    /* end ucsd changes */

    // Send requested file to client ------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;
    long fileTime = 0;
    if (content) {
        try {
            long start = System.currentTimeMillis();
            // Open streams.
            input = fs.getInputStream(objid, cmpid, fileid);
            output = response.getOutputStream();
            response.setContentType(contentType);
            if (acceptsGzip) {
                // The browser accepts GZIP, so GZIP the content.
                response.setHeader("Content-Encoding", "gzip");
                output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
            } else {
                // Content length is not directly predictable in case of
                // GZIP. So only add it if there is no means of GZIP, else
                // browser will hang.
                response.setHeader("Content-Length", length);
            }

            // Copy full range.
            /* begin ucsd changes */
            FileStoreUtil.copy(input, output);
            fileTime = System.currentTimeMillis() - start;
            /* begin ucsd changes */
        } catch (Exception ex) {
            log.error("Error reading " + fullFilename, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            /* begin ucsd changes */
            log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)"
                    + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime
                    + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]");
            /* begin ucsd changes */
            // Gently close streams.
            close(output);
            close(input);
        }
    }
}

From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java

/**
 * //from w  w  w.ja  v  a2s .  c  o  m
 * This is the default root authorize method that manages the whole 
 * authorization lifecycle when accessing the backend repositories.
 * <p>
 * Based on the information included in the config file, it uses that 
 * information to manage the authorization process. If there is any URL 
 * pattern defined in the config file that matches with the url sent to 
 * the authorize() method, a new authorization class of that kind is created.
 * <p>
 * At the end, it collects the error message coming from the specific 
 * authorization class' authorize() method. If there is any problem during 
 * the processing, it's returned as well.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param id the default credential id
 * 
 * @return the HTTP error code
 * 
 * @throws HttpException
 * @throws IOException
 */
public int authorize(HttpServletRequest request, HttpServletResponse response, Cookie[] authCookies, String url,
        String id) throws HttpException, IOException, nonValidSessionException {

    logger.debug("Authorize");

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;
    boolean patternMatch = false;
    boolean rootIDExists = false;

    //UserSession
    UserSession userSession = null;

    //GSA cookie
    Cookie gsaAuthCookie = null;

    //Encoding support
    String newURL = null;

    //Try to avoid the double encoding problem
    try {
        newURL = URLDecoder.decode(url, ENCODING);
    } catch (IllegalArgumentException e) {
        logger.error("Illegal Argument when decoding/encoding URL");
        newURL = url;
    }
    URLUTF8Encoder encoder = new URLUTF8Encoder();
    url = encoder.encodeURL(new URL(newURL));

    //read vars
    if (valveConf != null) {
        //Set config vars
        setValveConf();

    } else {
        logger.error("Configuration error: Config file is not present");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Configuration error - Kerberos is not set properly");
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    //set auth Cookie                                
    Cookie[] cookies = request.getCookies();

    //SAML
    if (cookies == null) {
        cookies = authCookies;
    }

    if (cookies != null) {
        logger.debug("authCookieName is: " + authCookieName);
        for (int i = 0; i < cookies.length; i++) {
            logger.debug("Cookie found: " + cookies[i].getName() + "; value=" + cookies[i].getValue());
            if (cookies[i].getName().equals(authCookieName)) {
                gsaAuthCookie = cookies[i];
                logger.debug("Auth Cookie found!");
                break;
            }
        }
    }

    //manage Sessions                
    if (isSessionEnabled) {
        logger.debug("Session is enabled. Getting session instance");
        try {

            //Session Support. Get Sessions instance            
            sessions = Sessions.getInstance();

            //Get user session
            userSession = manageSessions(gsaAuthCookie);

        } catch (nonValidSessionException nVS) {
            //throw Exception
            throw nVS;
        } catch (Exception e) {
            logger.error("Error when geting session: " + e.getMessage(), e);
        }

    }

    //setting auth cookies
    if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies) && (!isSAML))) {
        //send auth cookies as those coming straight from the browser
        authCookies = request.getCookies();
    } else {
        //auth cookies are those that are in the session
        authCookies = userSession.getCookies();
    }

    logger.debug("Authz authorizing [" + url + "]");

    //protection
    if (repositoryConfigurations == null) {
        logger.error("Authorization Repository Vector has not been initialized");
        return HttpServletResponse.SC_UNAUTHORIZED;
    }

    //Pattern of the host that has been confiogured that needs to be macthed to the URL that is being authorized.
    RE authZHost = null;

    //The host of the GSA, need to detect a request from this host and skip past it
    RE queryHostRE = null;
    try {
        queryHostRE = new RE("/search", RE.MATCH_CASEINDEPENDENT);
    } catch (RESyntaxException reSynTaxExp) {
        logger.error("Failed to created queryHost RE: " + reSynTaxExp.getMessage());
    }

    ValveRepositoryConfiguration repository = null;

    logger.debug("Repository length: " + repositoryConfigurations.size());

    for (int i = 0; i < repositoryConfigurations.size(); i++) {

        repository = repositoryConfigurations.elementAt(i);

        logger.debug("Repository ID: " + repository.getId());

        //Pattern for this repository that needs to be macthed
        try {
            authZHost = new RE(repository.getPattern(), RE.MATCH_CASEINDEPENDENT);
        } catch (RESyntaxException reSynTaxExp) {
            logger.error("Failed to created authZHost RE: " + reSynTaxExp.getMessage());
            logger.error("Pattern trying to use: " + repository.getPattern());
        }

        if (queryHostRE.match(url)) {
            logger.debug("Query AuthZ");
            statusCode = HttpServletResponse.SC_OK;
            patternMatch = true;
        } else {
            if (authZHost.match(url)) {

                //Need the correct authZProcess implementation for this repository ID
                AuthorizationProcessImpl authZProcess = getAuthorizationProcess(repository);

                if (authZProcess != null) {
                    //URL matches a pattern
                    if (repository.getId().equals("root")) {
                        //If this is a match for the root id then it's the internal host used to test valve/test.html, so should just return valid
                        logger.debug("Internal AuthZ");
                        statusCode = HttpServletResponse.SC_OK;
                        patternMatch = true;
                        rootIDExists = true;
                    } else {
                        logger.info("Authorizing with " + repository.getId());
                        patternMatch = true;

                        //Add credentials
                        try {
                            addCredentials(authZProcess, userSession);
                        } catch (Exception e) {
                            logger.error("Error during Kerberos authZ treatment : " + e.getMessage(), e);
                        }

                        try {
                            String repoID = repository.getId();
                            statusCode = authZProcess.authorize(request, response, authCookies, url, repoID);
                            //If statusCode is UNAUTHORIZED, then the process has to stop here
                            if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
                                break;
                            }
                        } catch (Exception e) {
                            logger.error("Error during authorization: " + e.getMessage(), e);
                        }
                    }
                } else {
                    logger.debug("The URL matches with the pattern defined for repository " + "["
                            + repository.getId() + "] but could not instantiate the class");
                }
            }

        }

    }
    if (!patternMatch) {
        //check if "root" repository was created in the config file
        //if not: check if the URL is a Valve one. If so, return SC_OK
        if (!rootIDExists) {
            RE internalRE = new RE(new URL(internalURL).getHost(), RE.MATCH_CASEINDEPENDENT);
            boolean samePorts = (((new URL(internalURL)).getPort()) == ((new URL(url)).getPort()));
            if ((internalRE.match(url)) && (samePorts)) {
                logger.debug("This is an internal URL");
                statusCode = HttpServletResponse.SC_OK;
            } else {
                logger.debug("No pattern has been defined at any repository for this URL");
                //Set Status Code equal to "-1", so we do know there was no pattern found
                statusCode = -1;
            }
        } else {
            logger.debug("No pattern has been defined at any repository for this URL");
            //Set Status Code equal to "-1", so we do know there was no pattern found
            statusCode = -1;
        }
    }

    //protection
    userSession = null;

    return statusCode;
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.POST, value = "/plansinglejourney")
public @ResponseBody List<Itinerary> planSingleJourney(HttpServletResponse response,
        @RequestBody(required = false) SingleJourney journeyRequest,
        @RequestParam(required = false, defaultValue = "default") String policyId,
        @RequestHeader(required = false, value = "UserID") String userId,
        @RequestHeader(required = false, value = "AppName") String appName) throws Exception {
    try {/*w  ww . j  a  v a 2s.c o  m*/
        domainStorage.savePlanRequest(journeyRequest, userId, appName);

        String userFromToken = getUserId();
        statLogger.log(journeyRequest, userFromToken);
        logger.info("-" + userId + "~AppConsume~plan");

        List<Itinerary> results = smartPlannerHelper.planSingleJourney(journeyRequest, policyId);
        for (Itinerary itinerary : results) {
            gamificationHelper.computeEstimatedGameScore(itinerary, false);
        }
        return results;
    } catch (Exception e) {
        e.printStackTrace();
        response.addHeader("error_msg", e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}