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:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }/*  ww w  .  j a v a  2s .com*/
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:com.github.thesmartenergy.sparql.generate.api.Take.java

@GET
public Response doGet(@Context Request r, @Context HttpServletRequest request,
        @DefaultValue("") @QueryParam("accept") String accept) throws IOException {

    String message = IOUtils.toString(request.getInputStream());
    // if content encoding is not text-based, then use base64 encoding
    // use con.getContentEncoding() for this
    String dturi = "http://www.w3.org/2001/XMLSchema#string";
    String ct = request.getContentType();
    if (ct != null) {
        dturi = "urn:iana:mime:" + ct;
    }//from  ww  w  .ja v  a2  s.c o  m

    String queryuri = request.getHeader("SPARGL-Query");
    String var = request.getHeader("SPARGL-Variable");
    HttpURLConnection con;
    String query = null;
    try {
        URL obj = new URL(queryuri);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", "application/sparql-generate");
        con.setInstanceFollowRedirects(true);
        System.out.println("GET to " + queryuri + " returned " + con.getResponseCode());
        InputStream in = con.getInputStream();
        query = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access query at URI <" + queryuri + ">: " + e.getMessage())
                .build();
    }
    System.out.println("got query " + query);

    // parse the SPARQL-Generate query and create plan
    PlanFactory factory = new PlanFactory();

    Syntax syntax = SPARQLGenerate.SYNTAX;
    SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, syntax);
    if (q.getBaseURI() == null) {
        q.setBaseURI("http://example.org/");
    }
    RootPlan plan = factory.create(q);

    // create the initial model
    Model model = ModelFactory.createDefaultModel();

    QuerySolutionMap initialBinding = new QuerySolutionMap();
    TypeMapper typeMapper = TypeMapper.getInstance();
    RDFDatatype dt = typeMapper.getSafeTypeByName(dturi);
    Node arqLiteral = NodeFactory.createLiteral(message, dt);
    RDFNode jenaLiteral = model.asRDFNode(arqLiteral);
    initialBinding.add(var, jenaLiteral);

    // execute the plan
    plan.exec(initialBinding, model);

    System.out.println(accept);
    if (!accept.equals("text/turtle") && !accept.equals("application/rdf+xml")) {
        List<Variant> vs = Variant
                .mediaTypes(new MediaType("application", "rdf+xml"), new MediaType("text", "turtle")).build();
        Variant v = r.selectVariant(vs);
        accept = v.getMediaType().toString();
    }

    System.out.println(accept);
    StringWriter sw = new StringWriter();
    Response.ResponseBuilder res;
    if (accept.equals("application/rdf+xml")) {
        model.write(sw, "RDF/XML", "http://example.org/");
        res = Response.ok(sw.toString(), "application/rdf+xml");
        res.header("Content-Disposition", "filename= message.rdf;");
        return res.build();
    } else {
        model.write(sw, "TTL", "http://example.org/");
        res = Response.ok(sw.toString(), "text/turtle");
        res.header("Content-Disposition", "filename= message.ttl;");
        return res.build();
    }
}

From source file:org.openmrs.module.sensorreading.web.controller.SensorReadingManageController.java

public void logger(String post, HttpServletRequest request, HttpServletResponse response) {
    System.out.println("request: " + request);
    System.out.println("request getContentType : " + request.getContentType());
    System.out.println("response : " + response);
    System.out.println("String post: " + post);
}

From source file:org.bibsonomy.rest.util.MultiPartRequestParser.java

/**
 * @param request/*  w  w  w .  j  a  v  a 2s .co  m*/
 * @throws FileUploadException
 */
public MultiPartRequestParser(final HttpServletRequest request) throws FileUploadException {
    // the factory to hold the file
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload upload = new ServletFileUpload(factory);

    /*
     * need to check if the request content-type isn't null because the
     * apache.commons.fileupload doesn't to that so the junit tests will
     * fail with a nullpointer exception
     */
    boolean isMultipart = false;
    if (request.getContentType() != null) {
        isMultipart = ServletFileUpload.isMultipartContent(request);
    }

    // online parse the items if the content-type is multipart
    if (isMultipart) {
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // parse the items
        @SuppressWarnings("unchecked") // ServletFileUpload.parseRequest specified to return a list of FileItems
        final List<FileItem> parseRequest = upload.parseRequest(request);
        this.items = parseRequest;
    }
}

From source file:org.apache.shindig.protocol.JsonRpcServlet.java

protected String getPostContent(HttpServletRequest request, Map<String, FormDataItem> formItems)
        throws ContentTypes.InvalidContentTypeException, IOException {
    String content = null;/*from www  . j a va2  s  .  c  o m*/

    ContentTypes.checkContentTypes(ALLOWED_CONTENT_TYPES, request.getContentType());

    if (formParser.isMultipartContent(request)) {
        for (FormDataItem item : formParser.parse(request)) {
            if (item.isFormField() && REQUEST_PARAM.equals(item.getFieldName()) && content == null) {
                // As per spec, in case of a multipart/form-data content, there will be one form field
                // with field name as "request". It will contain the json request. Any further form
                // field or file item will not be parsed out, but will be exposed via getFormItem
                // method of RequestItem.
                if (!StringUtils.isEmpty(item.getContentType())) {
                    ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES,
                            item.getContentType());
                }
                content = item.getAsString();
            } else {
                formItems.put(item.getFieldName(), item);
            }
        }
    } else {
        content = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
    }
    return content;
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
private void doPost(HttpPost method, HttpServletRequest req) throws IOException {
    copyHeaders(req, method);//  w ww .  j av  a2  s  .  c  om
    if (CONTENT_TYPE_FORM.equalsIgnoreCase(req.getContentType())) {
        Map<String, String[]> params = (Map<String, String[]>) req.getParameterMap();
        List<NameValuePair> pairs = new LinkedList<NameValuePair>();

        for (String name : params.keySet()) {
            String[] values = params.get(name);

            for (String value : values) {
                NameValuePair pair = new BasicNameValuePair(name, value);
                pairs.add(pair);
            }
        }

        method.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
    } else {
        method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength()));
    }
}

From source file:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * /*  ww  w .ja  v  a2 s.  com*/
 * @param req the HTTP request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        @Override
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

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

        @Override
        @Deprecated
        public int getContentLength() {
            return req.getContentLength();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:org.eclipse.leshan.standalone.servlet.ClientServlet.java

private LwM2mResponse createRequest(Client client, String target, HttpServletRequest req,
        HttpServletResponse resp) throws IOException {
    Map<String, String> parameters = new HashMap<String, String>();
    String contentType = HttpFields.valueParameters(req.getContentType(), parameters);
    if ("application/json".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), parameters.get("charset"));
        LwM2mNode node;/*from  w  w w . j a v  a 2 s.  com*/
        try {
            node = gson.fromJson(content, LwM2mNode.class);
        } catch (JsonSyntaxException e) {
            throw new IllegalArgumentException("unable to parse json to tlv:" + e.getMessage(), e);
        }
        if (!(node instanceof LwM2mObjectInstance)) {
            throw new IllegalArgumentException("payload must contain an object instance");
        }
        return server.send(client,
                new CreateRequest(target,
                        ((LwM2mObjectInstance) node).getResources().values().toArray(new LwM2mResource[0]),
                        ContentFormat.TLV),
                TIMEOUT);
    } else {
        throw new IllegalArgumentException(
                "content type " + req.getContentType() + " not supported for write requests");
    }
}

From source file:com.amazon.dtasdk.v2.signature.Request.java

/**
 * Creates a Request from an HttpServletRequest. Useful for verifying the signature of a request.
 * /*from ww w.  ja v  a 2 s .c o  m*/
 * NOTE: This consumes the body of the request which can cause issues when you try and read it again.
 * 
 * @param httpServletRequest
 *            the HttpServletRequest to copy
 * @throws IOException
 *             on invalid url or body copying
 */
public Request(HttpServletRequest httpServletRequest) throws IOException {
    url = getFullURL(httpServletRequest);
    method = Method.valueOf(httpServletRequest.getMethod());

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        headers.put(name, httpServletRequest.getHeader(name));
    }
    headers.put(CONTENT_TYPE_HEADER, httpServletRequest.getContentType());
    body = IOUtils.toString(httpServletRequest.getInputStream());
}