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:de.bermuda.arquillian.example.ContentTypeProxyServlet.java

private void copyRequestBody(HttpServletRequest req, PostMethod post) throws IOException {
    BufferedReader contentReader = req.getReader();
    StringBuilder content = new StringBuilder();
    String contentLine = "";
    while (contentLine != null) {
        content.append(contentLine);//w ww.j a  v  a 2s.  c o  m
        contentLine = contentReader.readLine();
    }
    StringRequestEntity requestEntity = new StringRequestEntity(content.toString(), req.getContentType(),
            req.getCharacterEncoding());
    post.setRequestEntity(requestEntity);
    requestLogger.info("RequestBody: " + content);
}

From source file:com.github.matthesrieke.simplebroker.SimpleBrokerServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (verifyRemoteHost(req.getRemoteHost())) {
        final String content;
        final ContentType type;
        final String remoteHost;
        try {/*from  w w w. jav  a 2  s.  co m*/
            content = readContent(req);
            type = ContentType.parse(req.getContentType());
            remoteHost = req.getRemoteHost();
        } catch (IOException e) {
            logger.warn(e.getMessage());
            return;
        }

        this.executor.submit(new Runnable() {

            public void run() {
                for (Consumer c : consumers)
                    try {
                        c.consume(content, type, remoteHost);
                    } catch (RuntimeException e) {
                        logger.warn(e.getMessage());
                    } catch (IOException e) {
                        logger.warn(e.getMessage());
                    }
            }
        });
    } else {
        logger.info("Host {} is not whitelisted. Ignoring request.", req.getRemoteHost());
    }

    resp.setStatus(HttpStatus.SC_NO_CONTENT);
}

From source file:org.kalypso.ogc.core.service.OGCRequest.java

/**
 * This function initializes the body.//  w  w  w  .  j a  v a  2 s. c o  m
 * 
 * @param request
 *          The servlet request.
 * @return The body.
 */
private String initBody(final HttpServletRequest request) {
    /* The reader. */
    BufferedReader reader = null;

    try {
        /* If the request was not sent via the POST method, no body is available. */
        if (!m_post)
            return null;

        /* Only xml bodies may be handled. */
        final String contentType = request.getContentType();
        if (contentType == null || !contentType.contains("text/xml")) //$NON-NLS-1$
            return null;

        /* Memory for the results. */
        final StringBuffer buffer = new StringBuffer();

        /* Get the reader. */
        reader = request.getReader();

        /* Read the body. */
        String line = ""; //$NON-NLS-1$
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append(System.getProperty("line.separator", "\n\r")); //$NON-NLS-1$ //$NON-NLS-2$
        }

        return buffer.toString();
    } catch (final IOException ex) {
        /* Print the exception. */
        ex.printStackTrace();
        return null;
    } finally {
        /* Close the reader. */
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.krawler.esp.servlets.importToDoTask.java

private String doImport(HttpServletRequest request, Connection conn)
        throws SessionExpiredException, ServiceException, IOException, JSONException {
    String contentType = request.getContentType();
    CsvReader csvReader = null;/* w  ww .  j  av a 2s.  c om*/
    String header = "";
    {
        FileInputStream fstream = null;
        try {
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                String fileid = UUID.randomUUID().toString();
                String f1 = uploadDocument(request, fileid);
                if (f1.length() != 0) {
                    String destinationDirectory = StorageHandler.GetDocStorePath()
                            + StorageHandler.GetFileSeparator() + "importplans";
                    File csv = new File(destinationDirectory + StorageHandler.GetFileSeparator() + f1);
                    fstream = new FileInputStream(csv);
                    csvReader = new CsvReader(new InputStreamReader(fstream));
                    csvReader.readRecord();
                    int i = 0;
                    while (!(StringUtil.isNullOrEmpty(csvReader.get(i)))) {
                        header += "{\"header\":\"" + csvReader.get(i) + "\",\"index\":" + i + "},";
                        i++;
                    }
                    header = header.substring(0, header.length() - 1);
                    header = "{\"success\": true,\"FileName\":\"" + f1 + "\",\"Headers\":[" + header + "]}";
                    // e.g. Header= "{'Task Name':0,'Start Date':1,'End Date':2,'Proirity':3,'Percent Completed':4,'Notes':5}";

                }

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ConfigurationException ex) {
            KrawlerLog.op.warn("Problem Storing Data In DB [importProjectPlanCSV.storeInDB()]:" + ex);
            throw ServiceException.FAILURE("importProjectPlanCSV.getfile", ex);
        } finally {
            csvReader.close();
            fstream.close();
        }
    }
    return header;
}

From source file:com.nominanuda.web.http.ServletHelper.java

public HttpRequest copyRequest(HttpServletRequest servletRequest, boolean stripContextPath) throws IOException {
    final InputStream is = getServletRequestBody(servletRequest);
    String method = servletRequest.getMethod();
    String uri = getRequestLineURI(servletRequest, stripContextPath);
    String ct = servletRequest.getContentType();
    @SuppressWarnings("unused")
    String charenc = getCharacterEncoding(servletRequest);
    String cenc = getContentEncoding(servletRequest);
    long contentLength = servletRequest.getContentLength();
    HttpRequest req;// w ww .j  a  v a2 s  .  c  om
    if (is == null) {
        req = new BasicHttpRequest(method, uri);
    } else {
        req = new BasicHttpEntityEnclosingRequest(method, uri);
        HttpEntity entity = buildEntity(servletRequest, is, contentLength, ct, cenc);
        if (entity != null) {
            ((BasicHttpEntityEnclosingRequest) req).setEntity(entity);
        }
    }
    Enumeration<?> names = servletRequest.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration<?> vals = servletRequest.getHeaders(name);
        while (vals.hasMoreElements()) {
            String value = (String) vals.nextElement();
            req.addHeader(name, value);
        }
    }
    return req;
}

From source file:org.emergent.plumber.StorageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //    int length = req.getContentLength();
    String ctype = req.getContentType();
    String cenc = req.getCharacterEncoding();
    //    this.log("CLEN: " + length);
    this.log("CTYPE: " + ctype);
    this.log("CENC : " + cenc);
    String body = MiscUtil.readBody(req);
    this.log("BODY:\n" + body);
    long tsmillis = getServerTimestamp(req);

    String rspMsg = null;/*  ww w.j a  v  a2s .  c o m*/
    try {
        JSONObject retval = new JSONObject();
        double serverTimestamp = MiscUtil.toWeaveTimestampDouble(tsmillis);
        retval.put("modified", serverTimestamp);
        JSONArray successArray = new JSONArray();
        JSONArray failedArray = new JSONArray();
        JSONArray clientsArray = new JSONArray(body);
        for (int ii = 0; ii < clientsArray.length(); ii++) {
            // todo catch exceptions in loop
            JSONObject clientObj = clientsArray.getJSONObject(ii);
            String nodeId = clientObj.getString("id");
            updateClient(req, tsmillis, clientObj);
            successArray.put(nodeId);
        }
        //      failedArray.put(nodeId);
        retval.put("success", successArray);
        retval.put("failed", failedArray);
        rspMsg = retval.toString();
    } catch (SQLException e) {
        log(e.getMessage(), e);
    } catch (JSONException e) {
        log(e.getMessage(), e);
    }

    log("RESPONSE: " + rspMsg);
    if (rspMsg != null) {
        resp.setContentType("application/json");
        PrintWriter writer2 = resp.getWriter();
        writer2.append(rspMsg);
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.apache.struts.util.RequestUtils.java

/**
 * <p>Populate the properties of the specified JavaBean from the specified
 * HTTP request, based on matching each parameter name (plus an optional
 * prefix and/or suffix) against the corresponding JavaBeans "property
 * setter" methods in the bean's class. Suitable conversion is done for
 * argument types as described under <code>setProperties</code>.</p>
 * <p/>//from w  w  w .  j  ava  2 s  . c o m
 * <p>If you specify a non-null <code>prefix</code> and a non-null
 * <code>suffix</code>, the parameter name must match
 * <strong>both</strong> conditions for its value(s) to be used in
 * populating bean properties. If the request's content type is
 * "multipart/form-data" and the method is "POST", the
 * <code>HttpServletRequest</code> object will be wrapped in a
 * <code>MultipartRequestWrapper</code object.</p>
 *
 * @param bean    The JavaBean whose properties are to be set
 * @param prefix  The prefix (if any) to be prepend to bean property names
 *                when looking for matching parameters
 * @param suffix  The suffix (if any) to be appended to bean property
 *                names when looking for matching parameters
 * @param request The HTTP request whose parameters are to be used to
 *                populate bean properties
 * @throws ServletException if an exception is thrown while setting
 *                          property values
 */
public static void populate(Object bean, String prefix, String suffix, HttpServletRequest request)
        throws ServletException {
    // Build a list of relevant request parameters from this request
    HashMap properties = new HashMap();

    // Iterator of parameter names
    Enumeration names = null;

    // Map for multipart parameters
    Map multipartParameters = null;

    String contentType = request.getContentType();
    String method = request.getMethod();
    boolean isMultipart = false;

    if (bean instanceof ActionForm) {
        ((ActionForm) bean).setMultipartRequestHandler(null);
    }

    MultipartRequestHandler multipartHandler = null;
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (method.equalsIgnoreCase("POST"))) {
        // Get the ActionServletWrapper from the form bean
        ActionServletWrapper servlet;

        if (bean instanceof ActionForm) {
            servlet = ((ActionForm) bean).getServletWrapper();
        } else {
            throw new ServletException(
                    "bean that's supposed to be " + "populated from a multipart request is not of type "
                            + "\"org.apache.struts.action.ActionForm\", but type " + "\""
                            + bean.getClass().getName() + "\"");
        }

        // Obtain a MultipartRequestHandler
        multipartHandler = getMultipartHandler(request);

        if (multipartHandler != null) {
            isMultipart = true;

            // Set servlet and mapping info
            servlet.setServletFor(multipartHandler);
            multipartHandler.setMapping((ActionMapping) request.getAttribute(Globals.MAPPING_KEY));

            // Initialize multipart request class handler
            multipartHandler.handleRequest(request);

            //stop here if the maximum length has been exceeded
            Boolean maxLengthExceeded = (Boolean) request
                    .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);

            if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
                ((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
                return;
            }

            //retrieve form values and put into properties
            multipartParameters = getAllParametersForMultipartRequest(request, multipartHandler);
            names = Collections.enumeration(multipartParameters.keySet());
        }
    }

    if (!isMultipart) {
        names = request.getParameterNames();
    }

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        String stripped = name;

        if (prefix != null) {
            if (!stripped.startsWith(prefix)) {
                continue;
            }

            stripped = stripped.substring(prefix.length());
        }

        if (suffix != null) {
            if (!stripped.endsWith(suffix)) {
                continue;
            }

            stripped = stripped.substring(0, stripped.length() - suffix.length());
        }

        Object parameterValue = null;

        if (isMultipart) {
            parameterValue = multipartParameters.get(name);
            parameterValue = rationalizeMultipleFileProperty(bean, name, parameterValue);
        } else {
            parameterValue = request.getParameterValues(name);
        }

        // Populate parameters, except "standard" struts attributes
        // such as 'org.apache.struts.action.CANCEL'
        if (!(stripped.startsWith("org.apache.struts."))) {
            properties.put(stripped, parameterValue);
        }
    }

    // Set the corresponding properties of our bean
    try {
        BeanUtils.populate(bean, properties);
    } catch (Exception e) {
        throw new ServletException("BeanUtils.populate", e);
    } finally {
        if (multipartHandler != null) {
            // Set the multipart request handler for our ActionForm.
            // If the bean isn't an ActionForm, an exception would have been
            // thrown earlier, so it's safe to assume that our bean is
            // in fact an ActionForm.
            ((ActionForm) bean).setMultipartRequestHandler(multipartHandler);
        }
    }
}

From source file:bijian.util.upload.MyMultiPartRequest.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 *
 * @param req  the request./*w w w  . j  av  a 2 s .  c  om*/
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

        public String getContentType() {
            return req.getContentType();
        }

        public int getContentLength() {
            return req.getContentLength();
        }

        public InputStream getInputStream() throws IOException {
            InputStream in = req.getInputStream();
            if (in == null) {
                throw new IOException("Missing content in the request");
            }
            return req.getInputStream();
        }
    };
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private HttpUriRequest prepareRequest(HttpServletRequest req, String target) throws IOException {
    String method = req.getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        return new HttpGet(target);
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        HttpPost post = new HttpPost(target);
        post.setEntity(new ByteArrayEntity(readInputStream(req.getInputStream(), req.getContentLength()),
                ContentType.parse(req.getContentType())));
        return post;
    }//from  w  w  w  .jav a 2 s  . co m
    throw new UnsupportedOperationException("Only GET and POST are supported by this proxy.");
}

From source file:org.apache.axis2.transport.http.util.SOAPUtil.java

/**
 * Handle SOAP Messages/*w w  w .ja v  a2 s . c  o m*/
 *
 * @param msgContext
 * @param request
 * @param response
 * @throws AxisFault
 */
public boolean processPostRequest(MessageContext msgContext, HttpServletRequest request,
        HttpServletResponse response) throws AxisFault {
    try {
        response.setHeader("Content-Type", "text/html");

        if (server(msgContext) != null) {
            response.setHeader("Server", server(msgContext));
        }
        String soapAction = request.getHeader(HTTPConstants.HEADER_SOAP_ACTION);
        msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, request.getContentType());
        InvocationResponse ir = HTTPTransportUtils.processHTTPPostRequest(msgContext, request.getInputStream(),
                response.getOutputStream(), request.getContentType(), soapAction,
                request.getRequestURL().toString());

        response.setContentType(
                "text/xml; charset=" + msgContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));

        if (!TransportUtils.isResponseWritten(msgContext)) {
            Integer statusCode = (Integer) msgContext.getProperty(Constants.RESPONSE_CODE);
            if (statusCode != null) {
                response.setStatus(statusCode.intValue());
            } else {
                response.setStatus(HttpServletResponse.SC_ACCEPTED);
            }
        }

        boolean closeReader = true;
        Parameter parameter = msgContext.getConfigurationContext().getAxisConfiguration()
                .getParameter("axis2.close.reader");
        if (parameter != null) {
            closeReader = JavaUtils.isTrueExplicitly(parameter.getValue());
        }
        if (closeReader && !InvocationResponse.SUSPEND.equals(ir)) {
            try {
                ((StAXBuilder) msgContext.getEnvelope().getBuilder()).close();
            } catch (Exception e) {
                log.debug(e);
            }
        }
        return true;
    } catch (AxisFault axisFault) {
        throw axisFault;
    } catch (IOException ioException) {
        throw AxisFault.makeFault(ioException);
    }
}