Example usage for javax.servlet.http HttpServletRequest getContentType

List of usage examples for javax.servlet.http HttpServletRequest getContentType

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContentType.

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:org.dspace.submit.step.UploadWithEmbargoStep.java

/**
 * Do any processing of the information input by the user, and/or perform
 * step processing (if no user interaction required)
 * <P>//from   w ww .  java  2  s  .  co  m
 * It is this method's job to save any data to the underlying database, as
 * necessary, and return error messages (if any) which can then be processed
 * by the appropriate user interface (JSP-UI or XML-UI)
 * <P>
 * NOTE: If this step is a non-interactive step (i.e. requires no UI), then
 * it should perform *all* of its processing in this method!
 *
 * @param context
 *            current DSpace context
 * @param request
 *            current servlet request object
 * @param response
 *            current servlet response object
 * @param subInfo
 *            submission info object
 * @return Status or error flag which will be processed by
 *         doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned,
 *         no errors occurred!)
 */
public int doProcessing(Context context, HttpServletRequest request, HttpServletResponse response,
        SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException {
    // get button user pressed
    String buttonPressed = Util.getSubmitButton(request, NEXT_BUTTON);

    // get reference to item
    Item item = subInfo.getSubmissionItem().getItem();

    // -----------------------------------
    // Step #0: Upload new files (if any)
    // -----------------------------------
    String contentType = request.getContentType();

    // if multipart form, then we are uploading a file
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        // This is a multipart request, so it's a file upload
        // (return any status messages or errors reported)
        int status = processUploadFile(context, request, response, subInfo);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }
    }

    // if user pressed jump-to button in process bar,
    // return success (so that jump will occur)
    if (buttonPressed.startsWith(PROGRESS_BAR_PREFIX)) {
        // check if a file is required to be uploaded
        if (fileRequired && !item.hasUploadedFiles()) {
            return STATUS_NO_FILES_ERROR;
        } else {
            return STATUS_COMPLETE;
        }
    }

    // POLICIES FORM MANAGEMENT
    int result = editBitstreamPolicies(request, context, subInfo, buttonPressed);
    if (result != -1)
        return result;

    // ---------------------------------------------
    // Step #1: Check if this was just a request to
    // edit file information.
    // (or canceled editing information)
    // ---------------------------------------------
    // check if we're already editing a specific bitstream
    if (request.getParameter("bitstream_id") != null) {
        if (buttonPressed.equals(CANCEL_EDIT_BUTTON)) {
            // canceled an edit bitstream request
            subInfo.setBitstream(null);

            // this flag will just return us to the normal upload screen
            return STATUS_EDIT_COMPLETE;
        } else {
            // load info for bitstream we are editing
            Bitstream b = Bitstream.find(context, Integer.parseInt(request.getParameter("bitstream_id")));

            // save bitstream to submission info
            subInfo.setBitstream(b);
        }
    } else if (buttonPressed.startsWith("submit_edit_")) {
        // get ID of bitstream that was requested for editing
        String bitstreamID = buttonPressed.substring("submit_edit_".length());

        Bitstream b = Bitstream.find(context, Integer.parseInt(bitstreamID));

        // save bitstream to submission info
        subInfo.setBitstream(b);

        // return appropriate status flag to say we are now editing the
        // bitstream
        return STATUS_EDIT_BITSTREAM;
    }

    // ---------------------------------------------
    // Step #2: Process any remove file request(s)
    // ---------------------------------------------
    // Remove-selected requests come from Manakin
    if (buttonPressed.equalsIgnoreCase("submit_remove_selected")) {
        // this is a remove multiple request!

        if (request.getParameter("remove") != null) {
            // get all files to be removed
            String[] removeIDs = request.getParameterValues("remove");

            // remove each file in the list
            for (int i = 0; i < removeIDs.length; i++) {
                int id = Integer.parseInt(removeIDs[i]);

                int status = processRemoveFile(context, item, id);

                // if error occurred, return immediately
                if (status != STATUS_COMPLETE) {
                    return status;
                }
            }

            // remove current bitstream from Submission Info
            subInfo.setBitstream(null);
        }
    } else if (buttonPressed.startsWith("submit_remove_")) {
        // A single file "remove" button must have been pressed

        int id = Integer.parseInt(buttonPressed.substring(14));
        int status = processRemoveFile(context, item, id);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }

        // remove current bitstream from Submission Info
        subInfo.setBitstream(null);
    }

    // -------------------------------------------------
    // Step #3: Check for a change in file description
    // -------------------------------------------------
    String fileDescription = request.getParameter("description");

    if (fileDescription != null && fileDescription.length() > 0) {
        // save this file description
        int status = processSaveFileDescription(context, request, response, subInfo);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }
    }

    // ------------------------------------------
    // Step #4: Check for a file format change
    // (if user had to manually specify format)
    // ------------------------------------------
    int formatTypeID = Util.getIntParameter(request, "format");
    String formatDesc = request.getParameter("format_description");

    // if a format id or description was found, then save this format!
    if (formatTypeID >= 0 || (formatDesc != null && formatDesc.length() > 0)) {
        // save this specified format
        int status = processSaveFileFormat(context, request, response, subInfo);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }
    }

    // execute only if comes from EditBitstreamStep
    if (buttonPressed.equals("submit_save")) {
        processAccessFields(context, request, subInfo, subInfo.getBitstream());
    }

    // ---------------------------------------------------
    // Step #5: Check if primary bitstream has changed
    // -------------------------------------------------
    if (request.getParameter("primary_bitstream_id") != null) {
        Bundle[] bundles = item.getBundles("ORIGINAL");
        if (bundles.length > 0) {
            bundles[0].setPrimaryBitstreamID(
                    Integer.valueOf(request.getParameter("primary_bitstream_id")).intValue());
            bundles[0].update();
        }
    }

    // ---------------------------------------------------
    // Step #6: Determine if there is an error because no
    // files have been uploaded.
    // ---------------------------------------------------
    //check if a file is required to be uploaded
    if (fileRequired && !item.hasUploadedFiles()) {
        return STATUS_NO_FILES_ERROR;
    }
    return STATUS_COMPLETE;
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {/*from w w  w. ja  v  a  2  s  .  c om*/
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}

From source file:org.opendatakit.aggregate.odktables.impl.api.InstanceFileServiceImpl.java

@Override
public Response putFile(@Context HttpServletRequest req, @PathParam("filePath") List<PathSegment> segments,
        byte[] content) throws IOException, ODKTaskLockException {

    if (segments.size() < 1) {
        return Response.status(Status.BAD_REQUEST).entity(InstanceFileService.ERROR_MSG_INSUFFICIENT_PATH)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();/*ww  w.  ja  va 2  s  .  c  o m*/
    }
    // The appId and tableId are from the surrounding TableService.
    // The rowId is already pulled out.
    // The segments are just rest/of/path in the full app-centric
    // path of:
    // appid/data/attachments/tableid/instances/instanceId/rest/of/path
    String partialPath = constructPathFromSegments(segments);
    String contentType = req.getContentType();
    String md5Hash = PersistenceUtils.newMD5HashUri(content);
    try {
        userPermissions.checkPermission(appId, tableId, TablePermission.WRITE_ROW);

        UriBuilder ub = info.getBaseUriBuilder();
        ub.path(OdkTables.class, "getTablesService");

        URI getFile = ub.clone().path(TableService.class, "getRealizedTable")
                .path(RealizedTableService.class, "getInstanceFiles").path(InstanceFileService.class, "getFile")
                .build(appId, tableId, schemaETag, rowId, partialPath);

        String locationUrl = getFile.toURL().toExternalForm();

        // we are adding a file -- delete any cached ETag value for this row's attachments manifest
        try {
            DbTableInstanceManifestETagEntity entity = DbTableInstanceManifestETags.getRowIdEntry(tableId,
                    rowId, cc);
            entity.delete(cc);
        } catch (ODKEntityNotFoundException e) {
            // ignore...
        }

        DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc);
        BlobEntitySet instance = blobStore.newBlobEntitySet(rowId, cc);
        int count = instance.getAttachmentCount(cc);
        for (int i = 1; i <= count; ++i) {
            String path = instance.getUnrootedFilename(i, cc);
            if (path != null && path.equals(partialPath)) {
                // we already have this in our store -- check that it is identical.
                // if not, we have a problem!!!
                if (md5Hash.equals(instance.getContentHash(i, cc))) {
                    return Response.status(Status.CREATED).header("Location", locationUrl)
                            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                    ApiConstants.OPEN_DATA_KIT_VERSION)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Credentials", "true").build();
                } else {
                    return Response.status(Status.BAD_REQUEST)
                            .entity(ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath)
                            .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER,
                                    ApiConstants.OPEN_DATA_KIT_VERSION)
                            .header("Access-Control-Allow-Origin", "*")
                            .header("Access-Control-Allow-Credentials", "true").build();
                }
            }
        }
        BlobSubmissionOutcome outcome = instance.addBlob(content, contentType, partialPath, false, cc);
        if (outcome == BlobSubmissionOutcome.NEW_FILE_VERSION) {
            return Response.status(Status.BAD_REQUEST).entity(ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath)
                    .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true").build();
        }
        return Response.status(Status.CREATED).header("Location", locationUrl)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    } catch (ODKDatastoreException e) {
        LOGGER.error(("ODKTables file upload persistence error: " + e.getMessage()));
        return Response.status(Status.INTERNAL_SERVER_ERROR)
                .entity(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.getMessage())
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    } catch (PermissionDeniedException e) {
        String msg = e.getMessage();
        if (msg == null) {
            msg = e.toString();
        }
        LOGGER.error(("ODKTables file upload permissions error: " + msg));
        return Response.status(Status.FORBIDDEN).entity(new Error(ErrorType.PERMISSION_DENIED, msg))
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();
    }
}

From source file:org.openecomp.sdcrests.action.rest.services.ActionsImpl.java

public Response updateArtifactInternal(String actionInvariantUuId, String artifactUuId, String artifactName,
        String artifactLabel, String artifactCategory, String artifactDescription, String artifactProtection,
        String checksum, Attachment artifactToUpdate, HttpServletRequest servletRequest) {
    byte[] payload = null;
    Map<String, String> errorMap = validateRequestHeaders(servletRequest);
    //Content-Type Header Validation
    String contentType = servletRequest.getContentType();
    if (StringUtils.isEmpty(contentType)) {
        errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
    }/*from ww w  .j  a v  a  2  s  . c  o  m*/

    if (artifactToUpdate != null) {
        InputStream artifactInputStream = null;
        try {
            artifactInputStream = artifactToUpdate.getDataHandler().getInputStream();
        } catch (IOException e) {
            throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
        }

        payload = FileUtils.toByteArray(artifactInputStream);
        //Validate Artifact size
        if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
            throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR);
        }

        //Validate Checksum
        if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
            errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
        }
    }

    if (artifactProtection != null && (artifactProtection.isEmpty()
            || (!artifactProtection.equals(ActionArtifactProtection.readOnly.name())
                    && !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) {
        errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
    }

    ActionArtifact updateArtifact = new ActionArtifact();
    if (errorMap.isEmpty()) {
        String user = servletRequest.getRemoteUser();
        ActionArtifact update = new ActionArtifact();
        update.setArtifactUuId(artifactUuId);
        update.setArtifactName(artifactName);
        update.setArtifactLabel(artifactLabel);
        update.setArtifactDescription(artifactDescription);
        update.setArtifact(payload);
        update.setArtifactCategory(artifactCategory);
        update.setArtifactProtection(artifactProtection);
        actionManager.updateArtifact(update, actionInvariantUuId, user);
    } else {
        checkAndThrowError(errorMap);
    }
    return Response.ok().build();
    //return Response.status(Response.Status.OK).entity("Artifact successfully updated").build();
}

From source file:org.osaf.cosmo.cmp.CmpServlet.java

private boolean checkPutPreconditions(HttpServletRequest req, HttpServletResponse resp) {
    if (req.getContentLength() <= 0) {
        resp.setStatus(HttpServletResponse.SC_LENGTH_REQUIRED);
        return false;
    }/*  ww w .j  ava  2s.com*/
    if (req.getContentType() == null || !req.getContentType().startsWith("text/xml")) {
        resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        return false;
    }
    if (req.getHeader("Content-Transfer-Encoding") != null || req.getHeader("Content-Encoding") != null
            || req.getHeader("Content-Base") != null || req.getHeader("Content-Location") != null
            || req.getHeader("Content-MD5") != null || req.getHeader("Content-Range") != null) {
        resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return false;
    }
    return true;
}

From source file:com.castlemock.web.mock.soap.web.soap.controller.AbstractSoapServiceController.java

/**
 * The method prepares an request//from  w  ww  . j a va 2  s.c  o  m
 * @param projectId The id of the project that the incoming request belongs to
 * @param httpServletRequest The incoming request
 * @return A new created project
 */
protected SoapRequestDto prepareRequest(final String projectId, final HttpServletRequest httpServletRequest) {
    final SoapRequestDto request = new SoapRequestDto();
    final String body = HttpMessageSupport.getBody(httpServletRequest);
    final String identifier = HttpMessageSupport.extractSoapRequestName(body);
    final String serviceUri = httpServletRequest.getRequestURI().replace(
            getContext() + SLASH + MOCK + SLASH + SOAP + SLASH + PROJECT + SLASH + projectId + SLASH, EMPTY);
    final List<HttpHeaderDto> httpHeaders = HttpMessageSupport.extractHttpHeaders(httpServletRequest);

    SoapVersion type = SoapVersion.SOAP11;
    if (SoapVersion.SOAP12.getContextPath().equalsIgnoreCase(httpServletRequest.getContextPath())) {
        type = SoapVersion.SOAP12;
    }

    request.setSoapVersion(type);
    request.setHttpHeaders(httpHeaders);
    request.setUri(serviceUri);
    request.setHttpMethod(HttpMethod.valueOf(httpServletRequest.getMethod()));
    request.setBody(body);
    request.setOperationIdentifier(identifier);
    request.setContentType(httpServletRequest.getContentType());
    return request;
}

From source file:com.github.restdriver.clientdriver.HttpRealRequest.java

public HttpRealRequest(HttpServletRequest request) {
    this.path = request.getPathInfo();
    this.method = Method.custom(request.getMethod().toUpperCase());
    this.params = HashMultimap.create();

    if (request.getQueryString() != null) {
        MultiMap<String> parameterMap = new MultiMap<String>();
        UrlEncoded.decodeTo(request.getQueryString(), parameterMap, "UTF-8", 0);
        for (Entry<String, String[]> paramEntry : parameterMap.toStringArrayMap().entrySet()) {
            String[] values = paramEntry.getValue();
            for (String value : values) {
                this.params.put(paramEntry.getKey(), value);
            }/* w  ww  . j  a  v  a  2 s . c o  m*/
        }
    }

    headers = new HashMap<String, Object>();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName.toLowerCase(), request.getHeader(headerName));
        }
    }

    try {
        this.bodyContent = IOUtils.toByteArray(request.getInputStream());
    } catch (IOException e) {
        throw new RuntimeException("Failed to read body of request", e);
    }

    this.bodyContentType = request.getContentType();
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

/**
 * This method performs the proxying of the request to the target address.
 *
 * @param target     The target address. Has to be a fully qualified address. The request is send as-is to this address.
 * @param hsRequest  The request data which should be send to the
 * @param hsResponse The response data which will contain the data returned by the proxied request to target.
 * @throws java.io.IOException Passed on from the connection logic.
 *///from   www  .  java 2  s. c  o m
public static void execute(final String target, final HttpServletRequest hsRequest,
        final HttpServletResponse hsResponse) throws IOException {
    if (log.isInfoEnabled()) {
        log.info("execute, target is " + target);
        log.info("response commit state: " + hsResponse.isCommitted());
    }

    if (StringUtils.isBlank(target)) {
        log.error("The target address is not given. Please provide a target address.");
        return;
    }

    log.info("checking url");
    final URL url;
    try {
        url = new URL(target);
    } catch (MalformedURLException e) {
        log.error("The provided target url is not valid.", e);
        return;
    }

    log.info("seting up the host configuration");

    final HostConfiguration config = new HostConfiguration();

    ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy"));
    if (proxyHost != null)
        config.setProxyHost(proxyHost);

    final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
    config.setHost(url.getHost(), port, url.getProtocol());

    if (log.isInfoEnabled())
        log.info("config is " + config.toString());

    final HttpMethod targetRequest = setupProxyRequest(hsRequest, url);
    if (targetRequest == null) {
        log.error("Unsupported request method found: " + hsRequest.getMethod());
        return;
    }

    //perform the reqeust to the target server
    final HttpClient client = new HttpClient(new SimpleHttpConnectionManager());
    if (log.isInfoEnabled()) {
        log.info("client state" + client.getState());
        log.info("client params" + client.getParams().toString());
        log.info("executeMethod / fetching data ...");
    }

    final int result;
    if (targetRequest instanceof EntityEnclosingMethod) {
        final RequestProxyCustomRequestEntity requestEntity = new RequestProxyCustomRequestEntity(
                hsRequest.getInputStream(), hsRequest.getContentLength(), hsRequest.getContentType());
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) targetRequest;
        entityEnclosingMethod.setRequestEntity(requestEntity);
        result = client.executeMethod(config, entityEnclosingMethod);

    } else {
        result = client.executeMethod(config, targetRequest);
    }

    //copy the target response headers to our response
    setupResponseHeaders(targetRequest, hsResponse);

    InputStream originalResponseStream = targetRequest.getResponseBodyAsStream();
    //the body might be null, i.e. for responses with cache-headers which leave out the body
    if (originalResponseStream != null) {
        OutputStream responseStream = hsResponse.getOutputStream();
        copyStream(originalResponseStream, responseStream);
    }

    log.info("set up response, result code was " + result);
}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);/*from   w w  w .j av a 2s .  co  m*/
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:com.github.vatbub.vatbubgitreports.Main.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    PrintWriter writer;/*  ww w.ja  va 2s  . co  m*/
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    StringBuilder requestBody = new StringBuilder();
    String line;

    try {
        writer = response.getWriter();
    } catch (IOException e) {
        Internet.sendErrorMail("getWriter", "Unable not read request", e, gMailUsername, gMailPassword);
        e.printStackTrace();
        response.setStatus(500);
        return;
    }

    try {
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
    } catch (IOException e) {
        Error error = new Error(e.getClass().getName() + " occurred while reading the request",
                ExceptionUtils.getFullStackTrace(e));
        writer.write(gson.toJson(error));
        response.setStatus(500);
        Internet.sendErrorMail("ReadRequestBody", requestBody.toString(), e, gMailUsername, gMailPassword);
        return;
    }

    // parse the request
    if (!request.getContentType().equals("application/json")) {
        // bad content type
        Error error = new Error("content type must be application/json");
        writer.write(gson.toJson(error));
    }

    GitHubIssue gitHubIssue;

    try {
        System.out.println("Received request:");
        System.out.println(requestBody.toString());
        System.out.println("Request encoding is: " + request.getCharacterEncoding());
        gitHubIssue = gson.fromJson(requestBody.toString(), GitHubIssue.class);
    } catch (Exception e) {
        Internet.sendErrorMail("ParseJSON", requestBody.toString(), e, gMailUsername, gMailPassword);
        Error error = new Error(e.getClass().getName() + " occurred while parsing the request",
                ExceptionUtils.getFullStackTrace(e));
        writer.write(gson.toJson(error));
        response.setStatus(500);
        return;
    }

    // Authenticate on GitHub
    GitHubClient client = new GitHubClient();
    client.setOAuth2Token(System.getenv("GITHUB_ACCESS_TOKEN"));

    // Convert the issue object
    Issue issue = new Issue();
    issue.setTitle(gitHubIssue.getTitle());
    String body = "";
    boolean metadataGiven = false;
    if (!gitHubIssue.getReporterName().equals("")) {
        body = "Reporter name: " + gitHubIssue.getReporterName() + "\n";
        metadataGiven = true;
    }
    if (!gitHubIssue.getReporterEmail().equals("")) {
        body = body + "Reporter email: " + gitHubIssue.getReporterEmail() + "\n";
        metadataGiven = true;
    }
    if (gitHubIssue.getLogLocation() != null) {
        body = body + "Log location: " + gitHubIssue.getLogLocation() + "\n";
        metadataGiven = true;
    }
    if (gitHubIssue.getScreenshotLocation() != null) {
        body = body + "Screenshot location: " + gitHubIssue.getScreenshotLocation() + "\n";
        metadataGiven = true;
    }
    if (gitHubIssue.getThrowable() != null) {
        body = body + "Exception stacktrace:\n" + ExceptionUtils.getFullStackTrace(gitHubIssue.getThrowable())
                + "\n";
        metadataGiven = true;
    }
    if (metadataGiven) {
        body = body + "----------------------------------" + "\n\nDESCRIPTION:\n";
    }
    body = body + gitHubIssue.getBody();

    issue.setBody(body);

    // send the issue to GitHub
    try {
        new IssueService(client).createIssue(gitHubIssue.getToRepo_Owner(), gitHubIssue.getToRepo_RepoName(),
                issue);
    } catch (IOException e) {
        e.printStackTrace();
        Error error = new Error(e.getClass().getName() + " occurred while parsing the request",
                ExceptionUtils.getFullStackTrace(e));
        writer.write(gson.toJson(error));
        response.setStatus(500);
        Internet.sendErrorMail("ForwardToGitHub", requestBody.toString(), e, gMailUsername, gMailPassword);
        return;
    }

    writer.write(gson.toJson(issue));
}