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.red5.server.net.servlet.RTMPTServlet.java

/**
 * Main entry point for the servlet.//from  ww  w . j  av  a  2  s. c  o  m
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    log.info("RTMPT service");

    if (!req.getMethod().equals(REQUEST_METHOD) || req.getContentLength() == 0 || req.getContentType() == null
            || !req.getContentType().equals(CONTENT_TYPE)) {
        // Bad request - return simple error page
        handleBadRequest("Bad request, only RTMPT supported.", resp);
        return;
    }

    // XXX Paul: since the only current difference in the type of request
    // that we are interested in is the 'second' character, we can double
    // the speed of this entry point by using a switch on the second charater.
    char p = req.getServletPath().charAt(1);
    switch (p) {
    case 'o': //OPEN_REQUEST
        handleOpen(req, resp);
        break;
    case 'c': //CLOSE_REQUEST
        handleClose(req, resp);
        break;
    case 's': //SEND_REQUEST
        handleSend(req, resp);
        break;
    case 'i': //IDLE_REQUEST
        handleIdle(req, resp);
        break;
    default:
        handleBadRequest("RTMPT command " + p + " is not supported.", resp);
    }

}

From source file:org.geoserver.importer.rest.ImportTaskController.java

@PostMapping(consumes = { MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public Object taskPost(@PathVariable Long id, @RequestParam(required = false) String expand,
        HttpServletRequest request, HttpServletResponse response) {
    ImportData data = null;//w w w .  j a v a2  s .  c  o m

    LOGGER.info("Handling POST of " + request.getContentType());
    //file posted from form
    MediaType mimeType = MediaType.valueOf(request.getContentType());
    if (request.getContentType().startsWith(MediaType.MULTIPART_FORM_DATA_VALUE)) {
        data = handleMultiPartFormUpload(request, context(id));
    } else if (request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
        try {
            data = handleFormPost(request);
        } catch (IOException | ServletException e) {
            throw new RestException(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    }

    if (data == null) {
        throw new RestException("Unsupported POST", HttpStatus.FORBIDDEN);
    }

    //Construct response
    return acceptData(data, context(id), response, expand);
}

From source file:com.geocent.owf.openlayers.DataRequestProxy.java

/**
 * Gets the data from the provided remote URL.
 * Note that the data will be returned from the method and not automatically
 * populated into the response object./*  w ww .  ja  va  2 s .  com*/
 * 
 * @param request       ServletRequest object containing the request data.
 * @param response      ServletResponse object for the response information.
 * @param url           URL from which the data will be retrieved.
 * @return              Data from the provided remote URL.
 * @throws IOException 
 */
public String getData(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {

    if (!allowUrl(url)) {
        throw new UnknownHostException("Request to invalid host not allowed.");
    }

    HttpURLConnection connection = (HttpURLConnection) (new URL(url).openConnection());
    connection.setRequestMethod(request.getMethod());

    // Detects a request with a payload inside the message body
    if (request.getContentLength() > 0) {
        connection.setRequestProperty("Content-Type", request.getContentType());
        connection.setDoOutput(true);
        connection.setDoInput(true);
        byte[] requestPayload = IOUtils.toByteArray(request.getInputStream());
        connection.getOutputStream().write(requestPayload);
        connection.getOutputStream().flush();
    }

    // Create handler for the given content type and proxy the extracted information
    Handler contentHandler = HandlerFactory.getHandler(connection.getContentType());
    return contentHandler.handleContent(response, connection.getInputStream());
}

From source file:org.mule.module.http.functional.proxy.HttpProxyTemplateTestCase.java

@Test
public void proxyStreaming() throws Exception {
    final Latch latch = new Latch();
    consumeAllRequest = false;//from  w w  w . j av a2  s  . c om
    handlerExtender = new RequestHandlerExtender() {
        @Override
        public void handleRequest(org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException {
            extractHeadersFromBaseRequest(baseRequest);

            latch.release();
            IOUtils.toString(baseRequest.getInputStream());

            response.setContentType(request.getContentType());
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print("OK");
        }
    };

    AsyncHttpClientConfig.Builder configBuilder = new AsyncHttpClientConfig.Builder();
    AsyncHttpClientConfig config = configBuilder.build();
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient(new GrizzlyAsyncHttpProvider(config), config);

    AsyncHttpClient.BoundRequestBuilder boundRequestBuilder = asyncHttpClient
            .preparePost(getProxyUrl("test?parameterName=parameterValue"));
    boundRequestBuilder.setBody(new InputStreamBodyGenerator(new TestInputStream(latch)));
    ListenableFuture<com.ning.http.client.Response> future = boundRequestBuilder.execute();

    com.ning.http.client.Response response = future.get();
    assertThat(response.getStatusCode(), is(200));
    response.getHeaders();

    assertThat(getFirstReceivedHeader(HttpHeaders.Names.TRANSFER_ENCODING), is(HttpHeaders.Values.CHUNKED));
    assertThat(response.getResponseBody(), is("OK"));

    asyncHttpClient.close();
}

From source file:org.infoscoop.gadgets.servlet.JsonRpcServlet.java

protected String getPostContent(HttpServletRequest request, Map<String, FormDataItem> formItems)
        throws ContentTypes.InvalidContentTypeException, IOException {
    String content = null;// w  w  w. j ava2s . com

    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 (!Strings.isNullOrEmpty(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:controllers.LinguagemController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    this.request = request;
    this.response = response;

    if (request.getParameter("btn_editar") != null) {
        getEditarLinguagemView();//ww w. j  a  v  a2s .  c o  m
        return;
    }

    if (request.getParameter("btn_excluir") != null) {
        excluirLinguagem();
        return;
    }

    if (request.getContentType().contains("multipart/form-data")) {
        adicionarOuEditarLinguagem();
    }
}

From source file:lc.kra.servlet.FileManagerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///from   w w w.  ja va 2  s  . c  om
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Files files = null;
    File file = null, parent;
    String path = request.getParameter("path"), type = request.getContentType(),
            search = request.getParameter("search"), mode;

    if (path == null || !(file = new File(path)).exists())
        files = new Roots();
    else if (request.getParameter("zip") != null) {
        File zipFile = File.createTempFile(file.getName() + "-", ".zip");
        if (file.isFile())
            ZipUtil.addEntry(zipFile, file.getName(), file);
        else if (file.isDirectory())
            ZipUtil.pack(file, zipFile);
        downloadFile(response, zipFile, permamentName(zipFile.getName()), "application/zip");
    } else if (request.getParameter("delete") != null) {
        if (file.isFile())
            file.delete();
        else if (file.isDirectory()) {
            java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    java.nio.file.Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    java.nio.file.Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } else if ((mode = request.getParameter("mode")) != null) {
        boolean add = mode.startsWith("+");
        if (mode.indexOf('r') > -1)
            file.setReadable(add);
        if (mode.indexOf('w') > -1)
            file.setWritable(add);
        if (mode.indexOf('x') > -1)
            file.setExecutable(add);
    } else if (file.isFile())
        downloadFile(response, file);
    else if (file.isDirectory()) {
        if (search != null && !search.isEmpty())
            files = new Search(file.toPath(), search);
        else if (type != null && type.startsWith("multipart/form-data")) {
            for (Part part : request.getParts()) {
                String name;
                if ((name = partFileName(part)) == null) //retrieves <input type="file" name="...">, no other (e.g. input) form fields
                    continue;
                if (request.getParameter("unzip") == null)
                    try (OutputStream output = new FileOutputStream(new File(file, name))) {
                        copyStream(part.getInputStream(), output);
                    }
                else
                    ZipUtil.unpack(part.getInputStream(), file);
            }
        } else
            files = new Directory(file);
    } else
        throw new ServletException("Unknown type of file or folder.");

    if (files != null) {
        final PrintWriter writer = response.getWriter();
        writer.println(
                "<!DOCTYPE html><html><head><style>*,input[type=\"file\"]::-webkit-file-upload-button{font-family:monospace}</style></head><body>");
        writer.println("<p>Current directory: " + files + "</p><pre>");
        if (!(files instanceof Roots)) {
            writer.print(
                    "<form method=\"post\"><label for=\"search\">Search Files:</label> <input type=\"text\" name=\"search\" id=\"search\" value=\""
                            + (search != null ? search : "")
                            + "\"> <button type=\"submit\">Search</button></form>");
            writer.print(
                    "<form method=\"post\" enctype=\"multipart/form-data\"><label for=\"upload\">Upload Files:</label> <button type=\"submit\">Upload</button> <button type=\"submit\" name=\"unzip\">Upload & Unzip</button> <input type=\"file\" name=\"upload[]\" id=\"upload\" multiple></form>");
            writer.println();
        }
        if (files instanceof Directory) {
            writer.println("+ <a href=\"?path=" + URLEncoder.encode(path, ENCODING) + "\">.</a>");
            if ((parent = file.getParentFile()) != null)
                writer.println("+ <a href=\"?path=" + URLEncoder.encode(parent.getAbsolutePath(), ENCODING)
                        + "\">..</a>");
            else
                writer.println("+ <a href=\"?path=\">..</a>");
        }

        for (File child : files.listFiles()) {
            writer.print(child.isDirectory() ? "+ " : "  ");
            writer.print("<a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                    + "\" title=\"" + child.getAbsolutePath() + "\">" + child.getName() + "</a>");
            if (child.isDirectory())
                writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING)
                        + "&zip\" title=\"download\">&#8681;</a>");
            if (search != null && !search.isEmpty())
                writer.print(" <a href=\"?path="
                        + URLEncoder.encode(child.getParentFile().getAbsolutePath(), ENCODING)
                        + "\" title=\"go to parent folder\">&#128449;</a>");
            writer.println();
        }
        writer.print("</pre></body></html>");
        writer.flush();
    }
}

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

/**
 * Handles the posting of a new project, this will add a new project to the
 * system. Note: Dates should be in the format dd mm yyyy
 *
 * @throws InvalidXmlException/*from  ww w. j a v  a 2 s.  c  o m*/
 * @throws IOException
 */
@RequestMapping(method = { RequestMethod.POST })
public void handleProjectPostRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestBody byte[] content, HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, BizPolicyException, InvalidXmlException, IOException {

    // TODO Why doesn't spring do this?
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }

    Project project = objectBuilder.buildProject(new ByteArrayInputStream(content));
    Person user = getAuthenticatedUser();

    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else if (authorizationService.canCreateProject(user)) {
        projectBizService.updateProject(project, user);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/xml");
        resp.setStatus(HttpStatus.SC_CREATED);

        Bop bop = new Bop();
        bop.addProject(project);
        objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
}

From source file:org.apache.solr.servlet.SolrRequestParsers.java

public SolrParams parseParamsAndFillStreams(final HttpServletRequest req, ArrayList<ContentStream> streams)
        throws Exception {
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                "Not multipart content! " + req.getContentType());
    }//from  w ww .  j a  va 2 s  .  c  om

    MultiMapSolrParams params = SolrRequestParsers.parseQueryString(req.getQueryString());

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    // TODO - configure factory.setSizeThreshold(yourMaxMemorySize);
    // TODO - configure factory.setRepository(yourTempDirectory);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(uploadLimitKB * 1024);

    // Parse the request
    List items = upload.parseRequest(req);
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        // If its a form field, put it in our parameter map
        if (item.isFormField()) {
            MultiMapSolrParams.addParam(item.getFieldName(), item.getString(), params.getMap());
        }
        // Add the stream
        else {
            System.out.println(item.getFieldName() + "===" + item.getSize());
            streams.add(new FileItemContentStream(item));
        }
    }
    return params;
}

From source file:com.streamsets.pipeline.lib.sdcipc.TestSdcIpcRequestFragmenter.java

@Test
public void testValidate() throws IOException {
    HttpRequestFragmenter fragmenter = new SdcIpcRequestFragmenter();
    fragmenter.init(null);//from   w w  w . j  a va  2  s. co m
    HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse res = Mockito.mock(HttpServletResponse.class);

    Assert.assertFalse(fragmenter.validate(req, res));
    Mockito.verify(res).sendError(Mockito.eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
            Mockito.anyString());

    Mockito.reset(res);
    Mockito.when(req.getContentType()).thenReturn("foo");
    Assert.assertFalse(fragmenter.validate(req, res));
    Mockito.verify(res).sendError(Mockito.eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
            Mockito.anyString());

    Mockito.reset(res);
    Mockito.when(req.getContentType()).thenReturn("APPLICATION/BINARY");
    Assert.assertFalse(fragmenter.validate(req, res));
    Mockito.verify(res).sendError(Mockito.eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
            Mockito.anyString());

    Mockito.reset(res);
    Mockito.when(req.getHeader(Mockito.eq("X-SDC-JSON1-FRAGMENTABLE"))).thenReturn("TRUE");
    Assert.assertTrue(fragmenter.validate(req, res));

    fragmenter.destroy();
}