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:org.atricore.idbus.kernel.main.mediation.camel.component.logging.HttpLogMessageBuilder.java

public String buildLogMessage(Message message) {

    HttpExchange httpEx = (HttpExchange) message.getExchange();

    if (message instanceof HttpMessage) {

        HttpServletRequest hreq = httpEx.getRequest();

        StringBuffer logMsg = new StringBuffer(1024);

        logMsg.append("<http-request method=\"").append(hreq.getMethod()).append("\"").append("\n\t url=\"")
                .append(hreq.getRequestURL()).append("\"").append("\n\t content-type=\"")
                .append(hreq.getContentType()).append("\"").append("\n\t content-length=\"")
                .append(hreq.getContentLength()).append("\"").append("\n\t content-encoding=\"")
                .append(hreq.getCharacterEncoding()).append("\"").append(">");

        Enumeration headerNames = hreq.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Enumeration headers = hreq.getHeaders(headerName);

            logMsg.append("\n\t<header name=\"").append(headerName).append("\">");

            while (headers.hasMoreElements()) {
                String headerValue = (String) headers.nextElement();
                logMsg.append("\n\t\t<header-value>").append(headerValue).append("</header-value>");
            }//  w w w . ja va2  s  . c om

            logMsg.append("\n\t</header>");

        }

        Enumeration params = hreq.getParameterNames();
        while (params.hasMoreElements()) {
            String param = (String) params.nextElement();
            logMsg.append("\n\t<parameter name=\"").append(param).append("\">");
            logMsg.append("\n\t\t\t<value>").append(hreq.getParameter(param)).append("</value>");
            logMsg.append("\n\t</parameter>");
        }

        logMsg.append("\n</http-request>");

        return logMsg.toString();
    } else {
        StringBuffer logMsg = new StringBuffer(1024);
        logMsg.append("\t<http-response />");
        return logMsg.toString();
    }
}

From source file:com.dotweblabs.friendscube.rest.resources.gae.GaeFileServerResource.java

@Override
public String upload(Representation entity) throws Exception {
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            Request restletRequest = getRequest();
            HttpServletRequest servletRequest = ServletUtils.getRequest(restletRequest);
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator fileIterator = upload.getItemIterator(servletRequest);
            getLogger().info("content type: " + servletRequest.getContentType());
            getLogger().info("content: " + new ServletRequestContext(servletRequest).getContentLength());

            getLogger().info("iterator: " + fileIterator.hasNext());
            while (fileIterator.hasNext()) {
                FileItemStream item = fileIterator.next();

                String name = item.getName();
                String fileName = getQueryValue("client_token") + "_" + name; // TODO note storing client_token is dangerous
                GcsFilename gcsFilename = new GcsFilename(getBucketName(), fileName);
                getLogger().info("using bucket.. " + getBucketName());
                byte[] byteContent = ByteStreams.toByteArray(item.openStream());
                // TODO byteContent is basicallly the file uploaded

                getLogger().info("contentType: " + item.getContentType());
                GcsOutputChannel outputChannel = gcsService.createOrReplace(gcsFilename,
                        GcsFileOptions.getDefaultInstance());
                outputChannel.write(ByteBuffer.wrap(byteContent));
                outputChannel.close();/*from  w ww. j  av a 2 s.  com*/
                getLogger().info("uploaded");

                BlobKey blobKey = blobstoreService.createGsBlobKey(
                        "/gs/" + gcsFilename.getBucketName() + "/" + gcsFilename.getObjectName());

                ObjectNode result = JsonNodeFactory.instance.objectNode();
                processFile(blobKey, getQueryValue("client_token"), getQueryValue("upload_type"), result);
                return result.toString();
            }
        } else {
            setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        }
    } else {
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
    return null;
}

From source file:org.wso2.carbon.attachment.mgt.ui.fileupload.AttachmentUploadServlet.java

/**
 * Get the inputstream from the request and generate a file from t at the tmp directory.
 *///w w  w  .  j ava 2s. co m
private File generateTemporaryFile(HttpServletRequest request) throws ServletException, IOException {
    log.warn(
            "This code can be improved if reviewed thoroughly. Here we get the file from input stream and create"
                    + " a temp file at \"tmp\" directory. May be we can avoid this file creation.");
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream inputStream = new DataInputStream(request.getInputStream());
        //we are taking the length of Content type data
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        //this loop converting the uploaded file into byte code
        while (totalBytesRead < formDataLength) {
            byteRead = inputStream.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
        }
        String file = new String(dataBytes);
        //for saving the file name
        String saveFile = file.substring(file.indexOf("filename=\"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1, contentType.length());
        int pos;
        //extracting the index of file
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

        //TODO log.warn("Hard-coded directory path:" + "\"tmp/\"");
        File tmpFile = new File("tmp" + File.separator + saveFile);
        FileOutputStream fileOut = new FileOutputStream(tmpFile);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        IOUtils.closeQuietly(fileOut);
        IOUtils.closeQuietly(inputStream);

        return tmpFile;
    } else {
        throw new ServletException("Content type of the request is not multipart/form-data");
    }
}

From source file:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req) throws IOException {
    String contentType = StringUtils.substringBefore(req.getContentType(), ";");
    if ("application/json".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        LwM2mNode node;//from w w  w . j a va2 s.com
        try {
            node = gson.fromJson(content, LwM2mNode.class);
        } catch (JsonSyntaxException e) {
            throw new InvalidRequestException("unable to parse json to tlv:" + e.getMessage(), e);
        }
        return node;
    } else if ("text/plain".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1));
        return LwM2mSingleResource.newStringResource(rscId, content);
    }
    throw new InvalidRequestException("content type " + req.getContentType() + " not supported");
}

From source file:org.intalio.tempo.workflow.wds.servlets.WDSServlet.java

@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("doPut request={} contentType={} contentLength={}",
                new Object[] { request, request.getContentType(), request.getContentLength() });
    }//w  w w. j a  va2s.c  o  m
    String resourceUri = getResourceUri(request);
    String contentType = request.getContentType();
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    String participantToken = getParticipantToken(request);
    InputStream payloadStream = request.getInputStream();
    try {
        WDSService service = _wdsFactory.getWDSService();
        try {
            byte[] payload = IOUtils.toByteArray(payloadStream);
            Item item = new Item(resourceUri, contentType, payload);

            LOG.debug("Storing the item: {}", resourceUri);
            try {
                service.deleteItem(item.getURI(), participantToken);
            } catch (UnavailableItemException except) {
                // ignore
            }
            service.storeItem(item, participantToken);
            LOG.debug("Item {} stored OK.", resourceUri);
        } catch (UnavailableItemException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            LOG.warn("Item not found: '" + resourceUri + "'");
        } finally {
            service.close();
        }
    } finally {
        payloadStream.close();
    }
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void singleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-single-file.txt"));

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>());
    EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2);
    EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8");
    EasyMock.expect(request.getContentLength()).andReturn(body.length());
    final Capture<Map<String, List<FileInfo>>> capture = new Capture<>();
    request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture));
    EasyMock.replay(request);//from   w w  w.j ava2  s . c  o  m

    final AtomicBoolean run = new AtomicBoolean(false);
    MockWorkflowChain chain = new MockWorkflowChain(() -> {
        Map<String, List<FileInfo>> files = capture.getValue();
        assertEquals(files.size(), 1);
        try {
            assertEquals(FileUtils.readFileToString(files.get("userfile").get(0).file), "test");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        run.set(true);
    });

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);
    assertTrue(run.get());

    assertEquals(wrapper.getParameter("field1"), "value1");
    assertEquals(wrapper.getParameter("field2"), "value2");

    EasyMock.verify(request);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void multipleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-multiple-files.txt"));

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>());
    EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2);
    EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8");
    EasyMock.expect(request.getContentLength()).andReturn(body.length());
    final Capture<Map<String, List<FileInfo>>> capture = new Capture<>();
    request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture));
    EasyMock.replay(request);/*from   w  w w.java 2  s. c  o m*/

    final AtomicBoolean run = new AtomicBoolean(false);
    MockWorkflowChain chain = new MockWorkflowChain(() -> {
        Map<String, List<FileInfo>> files = capture.getValue();
        assertEquals(files.size(), 1);
        try {
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(0).file), "test");
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(1).file), "test2");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        run.set(true);
    });

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);
    assertTrue(run.get());

    assertEquals(wrapper.getParameter("field1"), "value1");
    assertEquals(wrapper.getParameter("field2"), "value2");

    EasyMock.verify(request);
}

From source file:cn.bc.web.util.DebugUtils.java

public static StringBuffer getDebugInfo(HttpServletRequest request, HttpServletResponse response) {
    @SuppressWarnings("rawtypes")
    Enumeration e;//from  w ww.j  a v  a 2s .  co  m
    String name;
    StringBuffer html = new StringBuffer();

    //session
    HttpSession session = request.getSession();
    html.append("<div><b>session:</b></div><ul>");
    html.append(createLI("Id", session.getId()));
    html.append(createLI("CreationTime", new Date(session.getCreationTime()).toString()));
    html.append(createLI("LastAccessedTime", new Date(session.getLastAccessedTime()).toString()));

    //session:attributes
    e = session.getAttributeNames();
    html.append("<li>attributes:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, String.valueOf(session.getAttribute(name))));
    }
    html.append("</ul></li>\r\n");
    html.append("</ul>\r\n");

    //request
    html.append("<div><b>request:</b></div><ul>");
    html.append(createLI("URL", request.getRequestURL().toString()));
    html.append(createLI("QueryString", request.getQueryString()));
    html.append(createLI("Method", request.getMethod()));
    html.append(createLI("CharacterEncoding", request.getCharacterEncoding()));
    html.append(createLI("ContentType", request.getContentType()));
    html.append(createLI("Protocol", request.getProtocol()));
    html.append(createLI("RemoteAddr", request.getRemoteAddr()));
    html.append(createLI("RemoteHost", request.getRemoteHost()));
    html.append(createLI("RemotePort", request.getRemotePort() + ""));
    html.append(createLI("RemoteUser", request.getRemoteUser()));
    html.append(createLI("ServerName", request.getServerName()));
    html.append(createLI("ServletPath", request.getServletPath()));
    html.append(createLI("ServerPort", request.getServerPort() + ""));
    html.append(createLI("Scheme", request.getScheme()));
    html.append(createLI("LocalAddr", request.getLocalAddr()));
    html.append(createLI("LocalName", request.getLocalName()));
    html.append(createLI("LocalPort", request.getLocalPort() + ""));
    html.append(createLI("Locale", request.getLocale().toString()));

    //request:headers
    e = request.getHeaderNames();
    html.append("<li>Headers:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getHeader(name)));
    }
    html.append("</ul></li>\r\n");

    //request:parameters
    e = request.getParameterNames();
    html.append("<li>Parameters:<ul>\r\n");
    while (e.hasMoreElements()) {
        name = (String) e.nextElement();
        html.append(createLI(name, request.getParameter(name)));
    }
    html.append("</ul></li>\r\n");

    html.append("</ul>\r\n");

    //response
    html.append("<div><b>response:</b></div><ul>");
    html.append(createLI("CharacterEncoding", response.getCharacterEncoding()));
    html.append(createLI("ContentType", response.getContentType()));
    html.append(createLI("BufferSize", response.getBufferSize() + ""));
    html.append(createLI("Locale", response.getLocale().toString()));
    html.append("<ul>\r\n");
    return html;
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }/*from  w  ww. j  a va2  s  .co m*/
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength(),
            ContentType.create(contentType));
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.MultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from  w  ww  .jav  a  2  s.c om*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        chain.doFilter(request, response);
        return;
    }
    LineInput in = new LineInput(request.getInputStream());
    String content_type = srequest.getContentType();
    String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary=")));
    byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1);
    MultiMap params = new MultiMap();

    // Get first boundary
    String line = in.readLine();
    if (!line.equals(boundary)) {
        log.warn(line);
        throw new IOException("Missing initial multi part boundary");
    }

    // Read each part
    boolean lastPart = false;
    String content_disposition = null;
    while (!lastPart) {
        while ((line = in.readLine()) != null) {
            // If blank line, end of part headers
            if (line.length() == 0)
                break;
            // place part header key and value in map
            int c = line.indexOf(':', 0);
            if (c > 0) {
                String key = line.substring(0, c).trim().toLowerCase();
                String value = line.substring(c + 1, line.length()).trim();
                if (key.equals("content-disposition"))
                    content_disposition = value;
            }
        }
        // Extract content-disposition
        boolean form_data = false;
        if (content_disposition == null) {
            throw new IOException("Missing content-disposition");
        }

        StringTokenizer tok = new StringTokenizer(content_disposition, ";");
        String name = null;
        String filename = null;
        while (tok.hasMoreTokens()) {
            String t = tok.nextToken().trim();
            String tl = t.toLowerCase();
            if (t.startsWith("form-data"))
                form_data = true;
            else if (tl.startsWith("name="))
                name = value(t);
            else if (tl.startsWith("filename="))
                filename = value(t);
        }

        // Check disposition
        if (!form_data) {
            log.warn("Non form-data part in multipart/form-data");
            continue;
        }
        if (name == null || name.length() == 0) {
            log.warn("Part with no name in multipart/form-data");
            continue;
        }

        OutputStream out = null;
        File file = null;
        try {
            if (filename != null && filename.length() > 0) {
                file = File.createTempFile("MultiPart", "", tempdir);
                out = new FileOutputStream(file);
                request.setAttribute(name, file);
                params.put(name, filename);
            } else
                out = new ByteArrayOutputStream();

            int state = -2;
            int c;
            boolean cr = false;
            boolean lf = false;

            // loop for all lines`
            while (true) {
                int b = 0;
                while ((c = (state != -2) ? state : in.read()) != -1) {
                    state = -2;
                    // look for CR and/or LF
                    if (c == 13 || c == 10) {
                        if (c == 13)
                            state = in.read();
                        break;
                    }
                    // look for boundary
                    if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b])
                        b++;
                    else {
                        // this is not a boundary
                        if (cr)
                            out.write(13);
                        if (lf)
                            out.write(10);
                        cr = lf = false;
                        if (b > 0)
                            out.write(byteBoundary, 0, b);
                        b = -1;
                        out.write(c);
                    }
                }
                // check partial boundary
                if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) {
                    if (cr)
                        out.write(13);
                    if (lf)
                        out.write(10);
                    cr = lf = false;
                    out.write(byteBoundary, 0, b);
                    b = -1;
                }
                // boundary match
                if (b > 0 || c == -1) {
                    if (b == byteBoundary.length)
                        lastPart = true;
                    if (state == 10)
                        state = -2;
                    break;
                }
                // handle CR LF
                if (cr)
                    out.write(13);
                if (lf)
                    out.write(10);
                cr = (c == 13);
                lf = (c == 10 || state == 10);
                if (state == 10)
                    state = -2;
            }
        } finally {
            IO.close(out);
        }

        if (file == null) {
            byte[] bytes = ((ByteArrayOutputStream) out).toByteArray();
            params.add(name, bytes);
        }
    }

    chain.doFilter(new Wrapper(srequest, params), response);

    // TODO delete the files if they still exist.
}