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.eternity.common.communication.servlet.SyncDispatch.java

protected void doRequest(HttpServletRequest req, HttpServletResponse resp, InputStream data)
        throws ServletException, IOException {
    String contentType = req.getContentType();
    String charset = req.getCharacterEncoding();
    String acceptsHeader = req.getHeader("Accept");
    Encoder encoder = null;// w w  w .ja  va 2  s. c o  m

    if (charset == null) {
        charset = "UTF-8";
    }

    contentType += ";" + charset;

    Decoder decoder = ProtocolHandlers.getHandlers().getDecoder(contentType);

    if (decoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.write("Unacceptable Content-Type!");
        log.warn("Received request with invalid content type of: {} (derived: {})", req.getContentType(),
                contentType);
        return;
    }

    if (acceptsHeader != null) {
        String accepts[] = acceptsHeader.split(",");

        for (String accept : accepts) {
            encoder = ProtocolHandlers.getHandlers().getEncoder(accept.trim() + ";" + charset);
            if (encoder != null)
                break;
        }
    } else {
        encoder = ProtocolHandlers.getHandlers().getEncoder(contentType);
    }

    if (encoder == null) {
        resp.setStatus(400);
        PrintWriter p = resp.getWriter();
        p.println("{\"status\": 400, \"errors\": [\"Unacceptable or missing ACCEPT header!\"]}");
        log.warn(
                "Cannot return data in formats: {}  - if you think this is wrong please check character encodings.",
                acceptsHeader);
        return;
    }

    String jsonMessage = req.getParameter(Parameter.jsonMessage.toString());
    Message message = (Message) decoder.decode(ByteBuffer.wrap(jsonMessage.getBytes(charset)), Message.class);
    message.encoding = contentType;
    if (message.subsystemName == null) {
        message.subsystemName = req.getRequestURL().toString().replaceFirst(".*/([^/?]+).*", "$1");
    }
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (data != null)
        IOUtils.copy(data, bytes);
    message.body = ByteBuffer.wrap(bytes.toByteArray());
    Response result = MessageConsumer.dispatchMessage(message, null, hostName);
    resp.setStatus(result.getStatus());
    resp.getOutputStream().write(result.data.array());
}

From source file:be.fedict.trust.service.ocsp.OCSPResponderServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getContentType();
    if (false == OCSP_REQUEST_CONTENT_TYPE.equals(contentType)) {
        LOG.error("incorrect content type: " + contentType);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;//from w  w w . ja  va 2  s .co m
    }

    InputStream ocspRequestInputStream = request.getInputStream();
    OCSPReq ocspReq = new OCSPReq(ocspRequestInputStream);

    Req[] requestList = ocspReq.getRequestList();
    if (1 != requestList.length) {
        LOG.error("OCSP request list size not 1: " + requestList.length);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    Req ocspRequest = requestList[0];

    CertificateID certificateID = ocspRequest.getCertID();
    LOG.debug("certificate Id hash algo OID: " + certificateID.getHashAlgOID());
    if (false == CertificateID.HASH_SHA1.equals(certificateID.getHashAlgOID())) {
        LOG.debug("only supporting SHA1 hash algo");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    BigInteger serialNumber = certificateID.getSerialNumber();
    byte[] issuerNameHash = certificateID.getIssuerNameHash();
    byte[] issuerKeyHash = certificateID.getIssuerKeyHash();
    LOG.debug("serial number: " + serialNumber);
    LOG.debug("issuer name hash: " + new String(Hex.encodeHex(issuerNameHash)));
    LOG.debug("issuer key hash: " + new String(Hex.encodeHex(issuerKeyHash)));

    Date revocationDate = this.validationService.validate(serialNumber, issuerNameHash, issuerKeyHash);

    PrivateKeyEntry privateKeyEntry = this.validationService.getPrivateKeyEntry();
    if (null == privateKeyEntry) {
        LOG.debug("missing service identity");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PublicKey publicKey = certificate.getPublicKey();
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    try {
        BasicOCSPRespGenerator basicOCSPRespGenerator = new BasicOCSPRespGenerator(publicKey);
        CertificateStatus certificateStatus;
        if (null == revocationDate) {
            certificateStatus = CertificateStatus.GOOD;
        } else {
            certificateStatus = new RevokedStatus(revocationDate, CRLReason.unspecified);
        }
        basicOCSPRespGenerator.addResponse(certificateID, certificateStatus);
        BasicOCSPResp basicOCSPResp = basicOCSPRespGenerator.generate("SHA1WITHRSA", privateKey, null,
                new Date(), BouncyCastleProvider.PROVIDER_NAME);
        OCSPRespGenerator ocspRespGenerator = new OCSPRespGenerator();
        OCSPResp ocspResp = ocspRespGenerator.generate(OCSPRespGenerator.SUCCESSFUL, basicOCSPResp);
        response.setContentType("application/ocsp-response");
        response.getOutputStream().write(ocspResp.getEncoded());
    } catch (Exception e) {
        LOG.error("OCSP generator error: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
}

From source file:com.kazuki43zoo.apistub.api.key.FixedLengthKeyExtractor.java

@Override
public List<Object> extract(HttpServletRequest request, byte[] requestBody, String... expressions) {
    if (requestBody == null || requestBody.length == 0) {
        return Collections.emptyList();
    }// w w  w. jav  a 2 s  .com

    Charset defaultCharset = Optional.ofNullable(request.getContentType()).map(MediaType::parseMediaType)
            .map(MediaType::getCharset).orElse(StandardCharsets.UTF_8);

    return Stream.of(expressions).map(expression -> {
        String[] defines = StringUtils.splitByWholeSeparatorPreserveAllTokens(expression, ",");
        if (defines.length <= 2) {
            return null;
        }
        int offset = Integer.parseInt(defines[0].trim());
        int length = Integer.parseInt(defines[1].trim());
        String type = defines[2].trim().toLowerCase();
        final Charset charset;
        if (defines.length >= 4) {
            charset = Charset.forName(defines[3].trim());
        } else {
            charset = defaultCharset;
        }
        if (!(requestBody.length >= offset && requestBody.length >= offset + length)) {
            return null;
        }
        return Optional.ofNullable(FUNCTIONS.get(type)).orElseThrow(() -> new IllegalArgumentException(
                "A bad expression is detected. The specified type does not support. expression: '" + expression
                        + "', specified type: '" + type + "', allowing types: " + FUNCTIONS.keySet()))
                .apply(Arrays.copyOfRange(requestBody, offset, offset + length), charset);
    }).filter(Objects::nonNull).collect(Collectors.toList());
}

From source file:eu.freme.broker.tools.loggingfilter.LoggingFilter.java

/**
 * Created by Jonathan Sauder (jonathan.sauder@student.hpi.de) on 11.12.15.
 */// www.  j a v a  2  s  .c  o m

/*
 * Checks if the Content-Type of the given request/response is in the whitelisted
 * Mime-Types for logging. These are specified in the loggingfilter.whitelist parameter
 * in application.properties
 */
public boolean checkAgainstWhitelist(HttpServletRequest request) {
    String compare = request.getParameter("informat");
    if (compare == null) {
        compare = request.getContentType();
    }
    return checkAgainstWhitelist(compare);
}

From source file:org.opennms.protocols.http.TestServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    LOG.info("JUnit Test Request: {}", req.getRequestURI());
    LOG.info("JUnit Test Content Type: {}", req.getContentType());
    String requestContent = IOUtils.toString(req.getReader());
    if (req.getRequestURI().equals("/junit/test/sample")) {
        resp.getWriter().write("OK!");
    }//from www .j  a  v  a2 s.c om
    if (req.getRequestURI().equals("/junit/test/post")) {
        if (req.getContentType().startsWith("application/xml")) {
            resp.setContentType("application/xml");
            Person p = JaxbUtils.unmarshal(Person.class, requestContent);
            SampleData data = new SampleData();
            data.addParameter("firstName", p.getFirstName());
            data.addParameter("lastName", p.getLastName());
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else if (req.getContentType().startsWith("application/json")) {
            resp.setContentType("application/json");
            JSONObject object = JSONObject.fromObject(requestContent);
            SampleData data = new SampleData();
            data.addParameter("firstName", object.getJSONObject("person").getString("firstName"));
            data.addParameter("lastName", object.getJSONObject("person").getString("lastName"));
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else if (req.getContentType().startsWith("application/x-www-form-urlencoded")) {
            resp.setContentType("application/xml");
            StringTokenizer st = new StringTokenizer(requestContent, "&");
            SampleData data = new SampleData();
            while (st.hasMoreTokens()) {
                String[] pair = ((String) st.nextToken()).split("=");
                data.addParameter(pair[0], pair[1]);
            }
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else {
            resp.setContentType("text/plain");
            resp.getWriter().write("ERROR!");
        }
    }
    if (req.getRequestURI().equals("/junit/test/post-data")) {
        Person p = JaxbUtils.unmarshal(Person.class, requestContent);
        if ("Alejandro".equals(p.getFirstName()) && "Galue".equals(p.getLastName())) {
            SampleData data = new SampleData();
            data.addParameter("contributions", "500");
            data.addParameter("applications", "2");
            data.addParameter("frameworks", "25");
            resp.setContentType("application/xml");
            resp.getWriter().write(JaxbUtils.marshal(data));
        } else {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid request");
        }
    }
}

From source file:org.sc.probro.servlets.RequestListServlet.java

public Request parseRequest(Broker broker, UserCredentials user, HttpServletRequest httpReq)
        throws BrokerException {
    String contentType = httpReq.getContentType();
    Log.info(String.format("Parsing request from content-type %s", contentType));

    if (contentType == null || contentType.equals(CONTENT_TYPE_JSON)) {
        return parseRequestFromJSONString(broker, user, httpReq);

    } else if (contentType.equals(CONTENT_TYPE_FORM)) {
        return parseRequestFromForm(broker, user, httpReq);

    } else {//from   w w  w.j av  a2  s. c o m
        throw new BadRequestException(
                String.format("Unrecognized Content-Type: %s", String.valueOf(contentType)));
    }
}

From source file:org.opendaylight.sloth.filter.SlothSecurityFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest) {
        long startTime = System.nanoTime();
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletRequest multiReadHttpServletRequest = httpServletRequest.getContentType() != null
                && Objects.equals(httpServletRequest.getContentType(), JSON_CONTENT_TYPE)
                        ? new MultiHttpServletRequest(httpServletRequest)
                        : httpServletRequest;

        Principal principal = getPrincipal((ODLPrincipal) SecurityUtils.getSubject().getPrincipal());
        final Future<RpcResult<CheckPermissionOutput>> rpcResultFuture = slothPermissionService
                .checkPermission(new CheckPermissionInputBuilder().setPrincipal(principal)
                        .setRequest(getRequest(multiReadHttpServletRequest, null)).build());
        try {//from  www.  j  a v  a  2  s  .c  o  m
            RpcResult<CheckPermissionOutput> rpcResult = rpcResultFuture.get();
            if (rpcResult.isSuccessful()) {
                long endTime = System.nanoTime();
                LOG.info("Permission Checking Time: " + (endTime - startTime) + " nano seconds");
                LOG.info("SlothSecurityFilter, check permission successful");
                if (rpcResult.getResult().getStatusCode() / 100 == 2) {
                    if (multiReadHttpServletRequest.getMethod().equals("GET")) {
                        LOG.info("response content type: " + multiReadHttpServletRequest.getContentType());
                        GenericResponseWrapper genericResponseWrapper = new GenericResponseWrapper(
                                (HttpServletResponse) response);
                        chain.doFilter(multiReadHttpServletRequest, genericResponseWrapper);
                        final Future<RpcResult<CheckPermissionOutput>> resultFuture = slothPermissionService
                                .checkPermission(new CheckPermissionInputBuilder().setPrincipal(principal)
                                        .setRequest(getRequest(multiReadHttpServletRequest,
                                                new String(genericResponseWrapper.getData())))
                                        .build());
                        RpcResult<CheckPermissionOutput> result = resultFuture.get();
                        if (result.isSuccessful()) {
                            if (result.getResult().getStatusCode() / 100 == 2) {
                                response.getOutputStream().write(genericResponseWrapper.getData());
                            } else {
                                response.getWriter().write(String.format("status code: %s, response: %s",
                                        result.getResult().getStatusCode(), result.getResult().getResponse()));
                            }
                        } else {
                            LOG.warn(
                                    "SlothSecurityFilter, unknown exception during permission checking, GET check");
                            response.getWriter()
                                    .write("unknown exception during permission checking, GET check");
                        }
                    } else {
                        chain.doFilter(multiReadHttpServletRequest, response);
                    }
                } else {
                    response.getWriter().write(String.format("status code: %s, response: %s",
                            rpcResult.getResult().getStatusCode(), rpcResult.getResult().getResponse()));
                }
            } else {
                LOG.warn("SlothSecurityFilter, unknown exception during permission checking");
                response.getWriter().write("unknown exception during permission checking");
            }
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("SlothSecurityFilter, check permission exception: " + e.getMessage());
            response.getWriter().write("exception during check permission: " + e.getMessage());
        }
    } else {
        LOG.warn("not http servletRequest, no permission check");
        chain.doFilter(servletRequest, response);
    }
}

From source file:org.apache.struts.chain.legacy.ComposableRequestProcessor.java

/**
 * If this is a multipart request, wrap it with a special wrapper.
 * Otherwise, return the request unchanged.
 *
 * @param request The HttpServletRequest we are processing
 *//*  ww w  .j av a2s.co m*/
protected HttpServletRequest processMultipart(HttpServletRequest request) {

    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        return (request);
    }

    String contentType = request.getContentType();
    if ((contentType != null) && contentType.startsWith("multipart/form-data")) {
        return (new MultipartRequestWrapper(request));
    } else {
        return (request);
    }

}

From source file:ar.com.zauber.commons.spring.exceptions.HeaderBasedStatusSimpleMappingExceptionHandler.java

/**
 * @see SimpleMappingExceptionResolver#doResolveException(HttpServletRequest,
 *      HttpServletResponse, Object, Exception)
 *//*from   w ww.ja v  a  2 s .  c  o m*/
@Override
protected final ModelAndView doResolveException(final HttpServletRequest request,
        final HttpServletResponse response, final Object handler, final Exception ex) {
    if (StringUtils.contains(request.getHeader("Accept"), accept)
            || StringUtils.contains(request.getContentType(), contentType)) {
        LOGGER.debug("Header match! Accept: {}, ContentType: {}", accept, contentType);

        response.setStatus(determineStatusCode(request, determineViewName(ex, request)));
        final ModelAndView mav = new ModelAndView(view);
        mav.addObject(messageKey, ex.getMessage());
        return mav;
    }
    return super.doResolveException(request, response, handler, ex);
}

From source file:com.ibm.util.merge.web.rest.servlet.RequestData.java

public RequestData(HttpServletRequest request) {
    method = request.getMethod();//from ww w .j  a v  a  2 s .  co m
    byte[] bytes = readRequestBody(request);
    requestBody = bytes;
    contentType = request.getContentType();
    preferredLocale = request.getLocale();
    List<Locale> tlocales = getAllRequestLocales(request);
    locales = new ArrayList<>(tlocales);
    params = request.getParameterMap();
    pathInfo = request.getPathInfo();
    queryString = request.getQueryString();
    Map<String, List<String>> headerValues = readHeaderValues(request);
    headers = headerValues;
    requestUrl = request.getRequestURL().toString();
}