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:com.threewks.thundr.bind.http.MultipartHttpBinder.java

@Override
public void bindAll(Map<ParameterDescription, Object> bindings, HttpServletRequest req,
        HttpServletResponse resp, Map<String, String> pathVariables) {
    if (ContentType.matchesAny(req.getContentType(), supportedContentTypes) && shouldTryToBind(bindings)) {
        Map<String, List<String>> formFields = new HashMap<String, List<String>>();
        Map<String, MultipartFile> fileFields = new HashMap<String, MultipartFile>();
        extractParameters(req, formFields, fileFields);
        Map<String, String[]> parameterMap = ParameterBinderRegistry.convertListMapToArrayMap(formFields);
        parameterBinderRegistry.bind(bindings, parameterMap, fileFields);
    }/*from   w ww. j  av  a2 s .  co  m*/
}

From source file:egovframework.com.utl.wed.filter.CkFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (request.getContentType() == null || request.getContentType().indexOf("multipart") == -1) {
        // contentType ? multipart  ? .
        chain.doFilter(request, response);
    } else {//from   w ww.j av a 2s.c om
        ckImageSaver.saveAndReturnUrlToClient(request, response);

    }
}

From source file:eu.city4ageproject.delivery.HTTPService.java

/**{@inheritDoc} */
@Override/*from w  w w  . j  a v  a 2  s  .  c om*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getContentType() != null && req.getContentType().toLowerCase().contains("application/json")
    //            && req.getCharacterEncoding() != null
    //            && req.getCharacterEncoding().toLowerCase().contains("utf")
    //            && req.getCharacterEncoding().toLowerCase().contains("8")
    ) {
        ServletInputStream is = req.getInputStream();
        String request = IOUtils.toString(is, "UTF-8");
        try {
            DeliveryRequest drequest = gsonBuilder.create().fromJson(request, DeliveryRequest.class);
            if (drequest.getPilotID() != null && !drequest.getPilotID().isEmpty()
                    && drequest.getUserID() != null && !drequest.getUserID().isEmpty()
                    && drequest.getIntervention() != null) {
                //connect to uAAL
                if (delivery.sendIntervention(drequest))
                    resp.setStatus(HttpServletResponse.SC_ACCEPTED);
                else
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            //TODO get parameters into the Actual delivery
        } catch (JsonSyntaxException e) {
            e.printStackTrace();

        }
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.\n cotnent is not compliant to schema.");
    } else {
        resp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintStream ps = new PrintStream(resp.getOutputStream());
        ps.print("Request not acceptable.<br> " + "Content-Type: application/json <br>"
        //               +" Content-Encoding: UTF-8"
        );
    }
}

From source file:com.dreambox.web.logger.LoggingFilter.java

private boolean isMultipart(HttpServletRequest request) {
    return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
}

From source file:jp.opencollector.guacamole.auth.delegated.DelegatedAuthenticationProvider.java

private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req)
        throws GuacamoleException {
    try {/*from w w w.  j a v a 2  s.co  m*/
        if (req.getClass().getName().equals("org.glyptodon.guacamole.net.basic.rest.APIRequest")) {
            final GuacamoleConfiguration config = new GuacamoleConfiguration();
            final String protocol = req.getParameter("protocol");
            if (protocol == null)
                throw new GuacamoleException("required parameter \"protocol\" is missing");
            config.setProtocol(protocol);
            for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
                String[] values = param.getValue();
                if (values.length > 0)
                    config.setParameter(param.getKey(), values[0]);
            }
            return Optional.of(config);
        } else {
            final ServletInputStream is = req.getInputStream();
            if (!is.isReady()) {
                MediaType contentType = MediaType.parse(req.getContentType());
                boolean invalidContentType = true;
                if (contentType.type().equals("application")) {
                    if (contentType.subtype().equals("json")) {
                        invalidContentType = false;
                    } else if (contentType.subtype().equals("x-www-form-urlencoded")
                            && req.getParameter("token") != null) {
                        return Optional.<GuacamoleConfiguration>absent();
                    }
                }
                if (invalidContentType)
                    throw new GuacamoleException(String.format("expecting application/json, got %s",
                            contentType.withoutParameters()));
                final GuacamoleConfiguration config = new GuacamoleConfiguration();
                try {
                    final ObjectMapper mapper = new ObjectMapper();
                    JsonNode root = (JsonNode) mapper.readTree(
                            createJsonParser(req.getInputStream(), contentType.charset().or(UTF_8), mapper));
                    {
                        final JsonNode protocol = root.get("protocol");
                        if (protocol == null)
                            throw new GuacamoleException("required parameter \"protocol\" is missing");
                        final JsonNode parameters = root.get("parameters");
                        if (parameters == null)
                            throw new GuacamoleException("required parameter \"parameters\" is missing");
                        config.setProtocol(protocol.asText());
                        {
                            for (Iterator<Entry<String, JsonNode>> i = parameters.fields(); i.hasNext();) {
                                Entry<String, JsonNode> member = i.next();
                                config.setParameter(member.getKey(), member.getValue().asText());
                            }
                        }
                    }
                } catch (ClassCastException e) {
                    throw new GuacamoleException("error occurred during parsing configuration", e);
                }
                return Optional.of(config);
            } else {
                return Optional.<GuacamoleConfiguration>absent();
            }
        }
    } catch (IOException e) {
        throw new GuacamoleException("error occurred during retrieving configuration from the request body", e);
    }
}

From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java

public static void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/*from  ww  w  .ja  v a2 s .  c o  m*/

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream())).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:com.bennavetta.appsite.webapi.ContentController.java

@RequestMapping(value = "/upload/**", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)/*from w  ww .j  av a  2s . c  o  m*/
public void uploadFile(HttpServletRequest request) throws IOException {
    MediaType type = MediaType.parse(request.getContentType());
    String path = extractPathFromPattern(request);
    log.trace("Uploading resource {} with type {}", path, type);

    Resource old = Resource.get(path);
    if (old != null) {
        log.trace("Deleting prior resource: {}", old);
        old.delete();
    }

    try (InputStream in = request.getInputStream()) {
        ReadableByteChannel channel = Channels.newChannel(in);
        resources.create(path, type, channel);
    }
}

From source file:io.robusta.rra.controller.SpringController.java

/**
 * set the entity to a request attribut//from www  .  ja  v a 2  s  . com
 * 
 * @param request
 * @return
 * @throws IOException
 */
@ModelAttribute("representation")
String representation(HttpServletRequest request) throws IOException {
    String contentType = request.getContentType();

    if (contentType != null && contentType.contains("application/json")) {
        InputStream in = request.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        int d;
        while ((d = in.read()) != -1) {
            stringBuffer.append((char) d);
        }
        System.out.println(stringBuffer.toString());
        System.out.println(Rra.defaultRepresentation instanceof GsonRepresentation);
        request.setAttribute("representation", stringBuffer.toString());
    }
    return "representation";
}

From source file:org.geowebcache.rest.controller.MassTruncateController.java

/**
 * Issue a mass truncate request.//ww w  . j  av  a2s  . c  om
 */
@RequestMapping(value = "/masstruncate", method = RequestMethod.POST)
public ResponseEntity<?> doPost(HttpServletRequest req) throws IOException {
    String contentType = req.getContentType();

    XStream xs = configXStream(new GeoWebCacheXStream(new DomDriver()));
    StringWriter writer = new StringWriter();
    IOUtils.copy(req.getInputStream(), writer, null);
    String reqData = writer.toString();

    Object obj = null;

    if (contentType == null || contentType.equalsIgnoreCase("text/xml")) {

        obj = xs.fromXML(reqData);
    } else if (contentType.equalsIgnoreCase("json")) {
        obj = xs.fromXML(convertJson(reqData));
    } else {
        throw new RestException("Format extension unknown or not specified: " + contentType,
                HttpStatus.BAD_REQUEST);
    }

    MassTruncateRequest mtr = (MassTruncateRequest) obj;
    try {
        if (!mtr.doTruncate(broker, breeder)) {
            throw new RestException("Truncation failed", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (IllegalArgumentException e) {
        throw new RestException(e.getMessage(), HttpStatus.BAD_REQUEST);
    } catch (StorageException e) {
        throw new RestException(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (GeoWebCacheException e) {
        throw new RestException(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<String>(HttpStatus.OK);
}

From source file:org.springframework.web.multipart.cos.CosMultipartResolver.java

public boolean isMultipart(HttpServletRequest request) {
    return request.getContentType() != null && request.getContentType().startsWith(MULTIPART_CONTENT_TYPE);
}