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.bluelotussoftware.apache.commons.fileupload.example.CommonsFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    log("Content-Type: " + request.getContentType());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*/* w  ww . ja va  2s . c  o  m*/
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(10 * 1024 * 1024); //10 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        log("FileItems: " + items.toString());
        Iterator itr = items.iterator();
        while (itr.hasNext()) {

            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                //Handle Uploaded files.
                out.println("<html><head><title>CommonsFileUploadServlet</title></head><body><p>");
                out.println("Field Name = " + item.getFieldName() + "\nFile Name = " + item.getName()
                        + "\nContent type = " + item.getContentType() + "\nFile Size = " + item.getSize());
                out.println("</p>");
                out.println("<img src=\"" + request.getContextPath() + "/files/" + item.getName() + "\"/>");
                out.println("</body></html>");
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, item.getName());
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }
}

From source file:org.red5.server.net.servlet.ZAMFGatewayServlet.java

/** {@inheritDoc} */
@Override//from   www  .j a v  a2  s  . co m
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //Continuation cont = ContinuationSupport.getContinuation(req, this);
    log.info("Service");

    if (req.getContentLength() == 0 || req.getContentType() == null
            || !req.getContentType().equals(APPLICATION_AMF)) {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().write("Gateway");
        resp.flushBuffer();
        return;
    }

    ByteBuffer reqBuffer = null;
    try {

        //req.getSession().getAttribute(REMOTING_CONNECTOR);

        reqBuffer = ByteBuffer.allocate(req.getContentLength());
        ServletUtils.copy(req.getInputStream(), reqBuffer.asOutputStream());
        reqBuffer.flip();

        // Connect to the server.
        VmPipeConnector connector = new VmPipeConnector();
        IoHandler handler = new Handler(req, resp);
        ConnectFuture connectFuture = connector.connect(new VmPipeAddress(5080), handler);
        connectFuture.join();
        IoSession session = connectFuture.getSession();
        session.setAttachment(resp);
        session.write(reqBuffer);

        ContinuationSupport.getContinuation(req, handler).suspend(1000);

    } catch (IOException e) {

        log.error(e);

    }
    log.info("End");
}

From source file:org.apache.hadoop.gateway.dispatch.HttpClientDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;/*from  w w w  .  j  av  a 2  s . c o  m*/
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }

    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {

        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (!delegationTokenPresent && getReplayBufferSize() > 0) {
            entity = new CappedBufferHttpEntity(entity, getReplayBufferSize() * 1024);
        }
    }

    return entity;
}

From source file:org.dataconservancy.ui.api.PersonController.java

/**
 * Handles the posting of a new person, this will add a new person to the
 * system with registration status of pending.
 *
 * @throws org.dataconservancy.model.builder.InvalidXmlException
 * @throws java.io.IOException/*from  w  w w.ja  v a2  s . c  om*/
 */
@RequestMapping(method = { RequestMethod.POST })
public void handlePersonPostRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestBody byte[] content, HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, BizPolicyException, InvalidXmlException, IOException {
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }
    //use businessobjectBuilder to deserialize content into a bop -> set of person
    Set<Person> postedPersonSet = builder.buildBusinessObjectPackage(new ByteArrayInputStream(content))
            .getPersons();
    //currently, only handle request to create 1 person
    //A request is considered BAD if it contains 0 person, or more than 1 person
    if (postedPersonSet.size() != 1) {
        try {
            resp.setStatus(HttpStatus.SC_BAD_REQUEST);
            resp.getWriter()
                    .print("Only one new person can be requested to be created via this API at a time.");
            resp.getWriter().flush();
            resp.getWriter().close();
        } catch (Exception ee) {
            log.debug("Handling exception", ee);
        }
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Person person = postedPersonSet.iterator().next();
        try {
            Person createPerson = userService.create(person);
            //Serialize the created Person to return
            Bop businessObjectPackage = new Bop();
            businessObjectPackage.addPerson(createPerson);

            resp.setStatus(HttpStatus.SC_OK);

            resp.setHeader(LOCATION, createPerson.getId());
            resp.setHeader(LAST_MODIFIED, DateTime.now().toString());
            builder.buildBusinessObjectPackage(businessObjectPackage, baos);
            resp.setHeader(ETAG, ETagCalculator.calculate(Integer.toString(businessObjectPackage.hashCode())));
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/xml");
            resp.setContentLength(baos.size());
            baos.writeTo(resp.getOutputStream());
        } catch (PersonUpdateException re) {
            resp.setStatus(HttpStatus.SC_BAD_REQUEST);
            resp.getOutputStream().println(re.getMessage());
            resp.getWriter().flush();
            resp.getWriter().close();
        }
    }
}

From source file:org.createnet.raptor.auth.service.jwt.JsonUsernamePasswordFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    if (!request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }//  w  w w. java 2s  .c  o  m

    if (!request.getContentType().equals(MediaType.APPLICATION_JSON)) {
        throw new AuthenticationServiceException("Only Content-Type " + MediaType.APPLICATION_JSON
                + " is supported. Provided is " + request.getContentType());
    }

    LoginForm loginForm;
    try {
        InputStream body = request.getInputStream();
        loginForm = jacksonObjectMapper.readValue(body, LoginForm.class);
    } catch (IOException ex) {
        throw new AuthenticationServiceException("Error reading body", ex);
    }

    if (loginForm.username == null) {
        loginForm.username = "";
    }

    if (loginForm.password == null) {
        loginForm.password = "";
    }

    loginForm.username = loginForm.username.trim();

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
            loginForm.username, loginForm.password);
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}

From source file:com.google.ratel.util.RatelUtils.java

public static boolean isJsonContentType(HttpServletRequest request) {

    String contentType = request.getContentType();
    if (StringUtils.isBlank(contentType)) {
        return false;
    }//from   w  ww.java 2s . c  o m

    if (contentType.indexOf(Constants.JSON) >= 0) {
        return true;
    }

    return false;
}

From source file:org.esigate.servlet.impl.HttpServletRequestEntity.java

HttpServletRequestEntity(HttpServletRequest request) {
    this.request = request;
    String contentLengthHeader = request.getHeader(HttpHeaders.CONTENT_LENGTH);
    if (contentLengthHeader != null) {
        length = Long.parseLong(contentLengthHeader);
    } else {//from w ww.j av  a  2  s .c  o m
        length = -1;
    }
    String contentTypeHeader = request.getContentType();
    if (contentTypeHeader != null) {
        this.setContentType(contentTypeHeader);
    }
    String contentEncodingHeader = request.getCharacterEncoding();
    if (contentEncodingHeader != null) {
        this.setContentEncoding(contentEncodingHeader);
    }

}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;//  www . ja  v a  2s . c  o  m
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }
    GatewayConfig config = (GatewayConfig) request.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (config != null && config.isHadoopKerberosSecured()) {
        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (replayBufferSize < 0) {
            replayBufferSize = config.getHttpServerRequestBuffer();
        }
        if (!delegationTokenPresent && replayBufferSize > 0) {
            entity = new PartiallyRepeatableHttpEntity(entity, replayBufferSize);
        }
    }

    return entity;
}

From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java

/**
 * Determines format of request. Returns null if the format is not suitable
 * for eInternationalization Filter.//from   w ww .j av  a  2  s.  co  m
 *
 * @param req
 * @return
 */
public String getInformat(HttpServletRequest req) {
    String informat = req.getParameter("informat");
    if (informat == null && req.getContentType() != null) {
        informat = req.getContentType();
        String[] parts = informat.split(";");
        if (parts.length > 1) {
            informat = parts[0].trim();
        }
    }
    if (informat == null) {
        return informat;
    }
    informat = informat.toLowerCase();
    if (contentTypes.contains(informat)) {
        return informat;
    } else {
        return null;
    }
}

From source file:org.openehealth.ipf.platform.camel.lbs.http.process.HttpResourceHandler.java

private ResourceList extractFromSingle(String subUnit, HttpServletRequest request) throws Exception {
    ResourceList resources = new ResourceList();
    handleResource(subUnit, resources, request.getContentType(), request.getPathTranslated(), null,
            request.getInputStream());//from   w w  w .  ja v a 2  s. c  om
    return resources;
}