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.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Performs an HTTP POST request// w  w  w . j  ava2s  . c  o  m
 *
 * @param httpServletRequest  The {@link javax.servlet.http.HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link javax.servlet.http.HttpServletResponse} object by which
 *                            we can send a proxied response to the client
 */
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    // Create a standard POST request
    String contentType = httpServletRequest.getContentType();
    String destinationUrl = this.getProxyURL(httpServletRequest);
    debug("POST Request URL: " + httpServletRequest.getRequestURL(), "    Content Type: " + contentType,
            " Destination URL: " + destinationUrl);
    PostMethod postMethodProxyRequest = new PostMethod(destinationUrl);
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
    setProxyRequestCookies(httpServletRequest, postMethodProxyRequest);
    // Check if this is a mulitpart (file upload) POST
    if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
        this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
    } else {
        if (contentType == null || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equals(contentType)) {
            this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
        } else {
            this.handleContentPost(postMethodProxyRequest, httpServletRequest);
        }
    }
    // Execute the proxy request
    this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
}

From source file:com.att.nsa.cambria.service.impl.MMServiceImpl.java

@Override
public void pushEvents(DMaaPContext ctx, final String topic, InputStream msg, final String defaultPartition,
        final String requestTime) throws ConfigDbException, AccessDeniedException, TopicExistsException,
        CambriaApiException, IOException, missingReqdSetting {

    //final NsaApiKey user = DMaaPAuthenticatorImpl.getAuthenticatedUser(ctx);
    //final Topic metatopic = ctx.getConfigReader().getfMetaBroker().getTopic(topic);

    final String remoteAddr = Utils.getRemoteAddress(ctx);

    if (ctx.getConfigReader().getfIpBlackList().contains(remoteAddr)) {

        ErrorResponse errRes = new ErrorResponse(HttpStatus.SC_FORBIDDEN,
                DMaaPResponseCode.ACCESS_NOT_PERMITTED.getResponseCode(),
                "Source address [" + remoteAddr
                        + "] is blacklisted. Please contact the cluster management team.",
                null, Utils.getFormattedDate(new Date()), topic, Utils.getUserApiKey(ctx.getRequest()),
                ctx.getRequest().getRemoteHost(), null, null);
        LOG.info(errRes.toString());//from ww w  .  j  a  v  a  2s .  c om
        throw new CambriaApiException(errRes);
    }

    String topicNameStd = null;

    topicNameStd = com.att.ajsc.beans.PropertiesMapBean.getProperty(CambriaConstants.msgRtr_prop,
            "enforced.topic.name.AAF");
    String metricTopicname = com.att.ajsc.filemonitor.AJSCPropertiesMap
            .getProperty(CambriaConstants.msgRtr_prop, "metrics.send.cambria.topic");
    if (null == metricTopicname)
        metricTopicname = "msgrtr.apinode.metrics.dmaap";
    boolean topicNameEnforced = false;
    if (null != topicNameStd && topic.startsWith(topicNameStd)) {
        topicNameEnforced = true;
    }

    final HttpServletRequest req = ctx.getRequest();

    boolean chunked = false;
    if (null != req.getHeader(TRANSFER_ENCODING)) {
        chunked = req.getHeader(TRANSFER_ENCODING).contains("chunked");
    }

    String mediaType = req.getContentType();
    if (mediaType == null || mediaType.length() == 0) {
        mediaType = MimeTypes.kAppGenericBinary;
    }

    if (mediaType.contains("charset=UTF-8")) {
        mediaType = mediaType.replace("; charset=UTF-8", "").trim();
    }

    if (!topic.equalsIgnoreCase(metricTopicname)) {
        pushEventsWithTransaction(ctx, msg, topic, defaultPartition, requestTime, chunked, mediaType);
    } else {
        pushEvents(ctx, topic, msg, defaultPartition, chunked, mediaType);
    }
}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  ww  .  j a  va  2s .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    String filePath;
    String file_name = null, field_name, upload_path;
    RequestDispatcher request_dispatcher;
    String font_name = "", look_id;
    String font_family_name = "";
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;

    try {

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("fontname")) {
                        font_name = fi.getString();
                    }
                    if (field_name.equals("fontstylecss")) {
                        font_family_name = fi.getString();
                    }

                } else {

                    //                        check = fonts.checkAvailability(font_name);
                    //                        if (check == false){

                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                    fonts.addFont(font_name, file_name, font_family_name);
                    response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");

                    //                            }else {
                    //                                response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist");
                    //                            }
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception while uploading fonts", e);
    }
}

From source file:com.glaf.mail.web.rest.MailReceiveReource.java

@GET
@POST/*  w ww  .j a  v  a  2s  . c o  m*/
@Path("/view")
public void view(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    String messageId = request.getParameter("messageId");
    if (messageId != null) {
        messageId = RequestUtils.decodeString(messageId);
        Map<String, Object> dataMap = JsonUtils.decode(messageId);
        String taskId = (String) dataMap.get("taskId");
        String itemId = (String) dataMap.get("itemId");
        if (taskId != null && itemId != null) {
            MailItem mailItem = mailDataFacede.getMailItem(taskId, itemId);
            if (mailItem != null) {
                mailItem.setReceiveStatus(1);
                mailItem.setReceiveDate(new Date());
                mailItem.setReceiveIP(RequestUtils.getIPAddress(request));
                String contentType = request.getContentType();
                mailItem.setContentType(contentType);
                logger.debug("contentType:" + contentType);
                java.util.Enumeration<String> e = request.getHeaderNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    logger.debug(name + "=" + request.getHeader(name));
                }
                String userAgent = request.getHeader("user-agent");
                if (userAgent != null) {
                    if (userAgent.indexOf("Chrome") != -1) {
                        mailItem.setBrowser("Chrome");
                    } else if (userAgent.indexOf("MSIE") != -1) {
                        mailItem.setBrowser("IE");
                    } else if (userAgent.indexOf("Firefox") != -1) {
                        mailItem.setBrowser("Firefox");
                    }
                    if (userAgent.indexOf("Windows") != -1) {
                        mailItem.setClientOS("Windows");
                    }
                }
                mailDataFacede.updateMail(taskId, mailItem);
            }
        }
    }
}

From source file:OpenProdocServ.Oper.java

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request/* w w  w.j a  v  a 2s. c  o  m*/
 * @param response servlet response
 * @throws ServletException
 * @throws IOException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    try {
        if (!FWStartted) {
            StartFW();
            FWStartted = true;
        }
        if (PDLog.isDebug())
            PDLog.Debug("##########################################################################");
        if (Connected(request) && request.getContentType().contains("multipart")) {
            InsFile(request, response);
            return;
        }
        if (request.getParameter(DriverRemote.ORDER) == null) {
            PrintWriter out = response.getWriter();
            Answer(request, out, "<OPD><Result>KO</Result><Msg>Disconnected</Msg></OPD>");
            out.close();
            return;
        }
        String Order = request.getParameter(DriverRemote.ORDER);
        if (Connected(request) && Order.equals(DriverGeneric.S_RETRIEVEFILE)) {
            SendFile(request, response);
            return;
        }
        if (Connected(request) || Order.equals(DriverGeneric.S_LOGIN)) {
            PrintWriter out = response.getWriter();
            ProcessPage(request, out);
            out.close();
        } else {
            PrintWriter out = response.getWriter();
            Answer(request, out, false, "<OPD><Result>KO</Result><Msg>Disconnected</Msg></OPD>", null);
            out.close();
        }
    } catch (Exception e) {
        PrintWriter out = response.getWriter();
        AddLog(e.getMessage());
        Answer(request, out, false, e.getMessage(), null);
        out.close();
    }
}

From source file:com.esri.gpt.catalog.gxe.GxeServlet.java

/**
 * Reads a posted XML document.//w w w.jav  a  2  s. c  om
 * @param request the HTTP servlet request
 * @param response the HTTP servlet response
 * @param context the request context
 * @throws Exception if a processing exception occurs
 */
private String readPostedXml(HttpServletRequest request, HttpServletResponse response, RequestContext context)
        throws Exception {
    String sXml = "";
    String sContentType = Val.chkStr(request.getContentType());
    if (sContentType.toLowerCase().startsWith("multipart/form-data;")) {
        String sMultipartAttribute = "uploadedfiles[]";
        Object oFile = request.getAttribute(sMultipartAttribute);
        if (oFile == null) {
            sMultipartAttribute = "uploadedfile";
            oFile = request.getAttribute(sMultipartAttribute);
        }
        if ((oFile != null) && (oFile instanceof FileItem)) {
            FileItem item = (FileItem) oFile;
            sXml = Val.chkStr(Val.removeBOM(item.getString("UTF-8")));
        }
    } else if (sContentType.toLowerCase().startsWith("application/x-www-form-urlencoded")) {
        String sFormUrlParamater = "xml";
        sXml = Val.chkStr(Val.removeBOM(request.getParameter(sFormUrlParamater)));
    } else {
        sXml = Val.chkStr(Val.removeBOM(this.readInputCharacters(request)));
    }

    /*
    // check for multipart/form-data
    String sMultipartAttribute = "uploadedfiles[]";
    Object oFile = request.getAttribute(sMultipartAttribute);
    if ((oFile != null) && (oFile instanceof FileItem)) {
      FileItem item = (FileItem)oFile;
      sXml = Val.chkStr(Val.removeBOM(item.getString("UTF-8")));
    } else {
              
      // check for application/x-www-form-urlencoded
      String sFormUrlParamater = "xml";
      sXml = Val.chkStr(request.getParameter(sFormUrlParamater));
      if (sXml == null) {
                
        // check the raw post body
        sXml = this.readInputCharacters(request);
      }
    }
    */
    return sXml;
}

From source file:com.globalsight.everest.webapp.pagehandler.qachecks.DitaQaReportsHandler.java

@ActionHandler(action = ACTION_UPLOAD, formClass = "")
public void uploadReport(HttpServletRequest p_request, HttpServletResponse p_response, Object form)
        throws Exception {
    // For DITA report, only store one copy for every task. The uploaded
    // file will replace old one if old one exsits.
    String taskIdStr = p_request.getParameter("taskId");
    long taskId = Long.parseLong(taskIdStr);

    String msg = "The selected file has been uploaded successfully";
    File reportFile = null;/*from w ww.  j av  a  2s.  c o  m*/
    File tmpFile = null;
    String fileName = null;
    long taskIdFromReport = -1;
    String contentType = p_request.getContentType();
    if (contentType != null && contentType.toLowerCase().startsWith("multipart/form-data")) {
        MultipartFormDataReader reader = new MultipartFormDataReader();
        tmpFile = reader.uploadToTempFile(p_request);
        fileName = reader.getFilename();
        if (fileName != null && fileName.toLowerCase().endsWith(".xlsx")) {
            taskIdFromReport = getTaskIdFromReportFile(tmpFile);
            if (taskIdFromReport == -1) {
                msg = "The uploading file is not a DITA QA checks report file";
            }
        } else {
            msg = "The uploading file is not an xlsx file";
        }
    }

    if (taskId == taskIdFromReport) {
        Task task = TaskHelper.getTask(taskId);
        File taskFolder = DITAQACheckerHelper.getReportFileDir(task);
        // As we only store one copy for one task, delete previous copy.
        FileUtil.deleteFile(taskFolder);
        taskFolder.mkdirs();
        reportFile = new File(taskFolder, fileName);
        FileUtils.copyFile(tmpFile, reportFile);
    } else if (taskIdFromReport != -1) {
        msg = "The uploading file is not for current task";
    }

    // Redirect to "Upload DITA QA Report" UI.
    if (msg != null) {
        HttpSession httpSession = p_request.getSession();
        SessionManager sessionMgr = (SessionManager) httpSession.getAttribute(SESSION_MANAGER);
        sessionMgr.setAttribute("ditaUploadMsg", msg + ": " + fileName);
    }
    p_response.sendRedirect(
            "/globalsight/ControlServlet?linkName=uploadDitaReport&pageName=QA_downloadDitaReport&taskId="
                    + taskId);

    pageReturn();
}

From source file:org.openrdf.http.server.repository.transaction.TransactionController.java

/**
 * Evaluates a query on the given connection and returns the resulting
 * {@link QueryResultView}. The {@link QueryResultView} will take care of
 * correctly releasing the connection back to the
 * {@link ActiveTransactionRegistry}, after fully rendering the query result
 * for sending over the wire./*w ww.java  2 s . c  o m*/
 */
private ModelAndView processQuery(RepositoryConnection conn, UUID txnId, HttpServletRequest request,
        HttpServletResponse response) throws IOException, HTTPException {
    String queryStr = null;
    final String contentType = request.getContentType();
    if (contentType != null && contentType.contains(Protocol.SPARQL_QUERY_MIME_TYPE)) {
        final String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                : "UTF-8";
        queryStr = IOUtils.toString(request.getInputStream(), encoding);
    } else {
        queryStr = request.getParameter(QUERY_PARAM_NAME);
    }

    Query query = getQuery(conn, queryStr, request, response);

    View view;
    Object queryResult;
    FileFormatServiceRegistry<? extends FileFormat, ?> registry;

    try {
        if (query instanceof TupleQuery) {
            TupleQuery tQuery = (TupleQuery) query;

            queryResult = tQuery.evaluate();
            registry = TupleQueryResultWriterRegistry.getInstance();
            view = TupleQueryResultView.getInstance();
        } else if (query instanceof GraphQuery) {
            GraphQuery gQuery = (GraphQuery) query;

            queryResult = gQuery.evaluate();
            registry = RDFWriterRegistry.getInstance();
            view = GraphQueryResultView.getInstance();
        } else if (query instanceof BooleanQuery) {
            BooleanQuery bQuery = (BooleanQuery) query;

            queryResult = bQuery.evaluate();
            registry = BooleanQueryResultWriterRegistry.getInstance();
            view = BooleanQueryResultView.getInstance();
        } else {
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "Unsupported query type: " + query.getClass().getName());
        }
    } catch (QueryInterruptedException e) {
        logger.info("Query interrupted", e);
        ActiveTransactionRegistry.INSTANCE.returnTransactionConnection(txnId);
        throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "Query evaluation took too long");
    } catch (QueryEvaluationException e) {
        logger.info("Query evaluation error", e);
        ActiveTransactionRegistry.INSTANCE.returnTransactionConnection(txnId);
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException
            // directly (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Query evaluation error: " + e.getMessage());
        }
    }
    Object factory = ProtocolUtil.getAcceptableService(request, response, registry);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(QueryResultView.FILENAME_HINT_KEY, "query-result");
    model.put(QueryResultView.QUERY_RESULT_KEY, queryResult);
    model.put(QueryResultView.FACTORY_KEY, factory);
    model.put(QueryResultView.HEADERS_ONLY, false); // TODO needed for HEAD
                                                    // requests.
    model.put(QueryResultView.TRANSACTION_ID_KEY, txnId);
    return new ModelAndView(view, model);
}

From source file:PrintCGI.java

/**
     * Prints CGI Environment Variables in a table
     * // w  w  w. ja  va  2s.c  o m
     * @param request
     * @param response
     * @throws IOException
     */

    public void printCGIValues(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String headers = null;
        String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>";
        String htmlFooter = "</BODY></HTML>";

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println(htmlHeader);
        out.println("<TABLE ALIGN=CENTER BORDER=1>");
        out.println("<tr><th> CGI Variable </th><th> Value </th>");

        out.println("<tr><td align=center>Authentication Type</td>");
        out.println("<td align=center>" + request.getAuthType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type</td>");
        out.println("<td align=center>" + request.getContentType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type Length</td>");
        out.println("<td align=center>" + request.getContentLength() + "</td></tr>");

        out.println("<tr><td align=center>Query String</td>");
        out.println("<td align=center>" + request.getMethod() + "</td></tr>");

        out.println("<tr><td align=center>IP Address</td>");
        out.println("<td align=center>" + request.getRemoteAddr() + "</td></tr>");

        out.println("<tr><td align=center>Host Name</td>");
        out.println("<td align=center>" + request.getRemoteHost() + "</td></tr>");

        out.println("<tr><td align=center>Request URL</td>");
        out.println("<td align=center>" + request.getRequestURI() + "</td></tr>");

        out.println("<tr><td align=center>Servlet Path</td>");
        out.println("<td align=center>" + request.getServletPath() + "</td></tr>");

        out.println("<tr><td align=center>Server's Name</td>");
        out.println("<td align=center>" + request.getServerName() + "</td></tr>");

        out.println("<tr><td align=center>Server's Port</td>");
        out.println("<td align=center>" + request.getServerPort() + "</td></tr>");

        out.println("</TABLE><BR>");
        out.println(htmlFooter);

    }

From source file:com.github.restdriver.clientdriver.unit.HttpRealRequestTest.java

@Test
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException {

    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    String expectedPathInfo = "someUrlPath";
    String expectedMethod = "GET";
    Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1"));

    String bodyContent = "bodyContent";
    String expectedContentType = "contentType";

    when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo);
    when(mockRequest.getMethod()).thenReturn(expectedMethod);
    when(mockRequest.getQueryString()).thenReturn("hello=world");
    when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames);
    when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1");
    when(mockRequest.getInputStream())/*from w w w.  j  av a  2 s .c o m*/
            .thenReturn(new DummyServletInputStream(IOUtils.toInputStream(bodyContent)));
    when(mockRequest.getContentType()).thenReturn(expectedContentType);

    RealRequest realRequest = new HttpRealRequest(mockRequest);

    assertThat((String) realRequest.getPath(), is(expectedPathInfo));
    assertThat(realRequest.getMethod(), is(Method.GET));
    assertThat(realRequest.getParams().size(), is(1));
    assertThat((String) realRequest.getParams().get("hello").iterator().next(), is("world"));
    assertThat((String) realRequest.getHeaders().get("header1"), is("thisIsHeader1"));
    assertThat((String) realRequest.getBodyContentType(), is(expectedContentType));

}