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.fao.geonet.services.main.GenericController.java

@RequestMapping(value = "/{lang}/{service}")
@ResponseBody/*from   w ww.  j  a v a2 s. co m*/
public void dispatch(@PathVariable String lang, @PathVariable String service, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession httpSession = request.getSession(false);

    String ip = request.getRemoteAddr();
    // if we do have the optional x-forwarded-for request header then
    // use whatever is in it to record ip address of client
    String forwardedFor = request.getHeader("x-forwarded-for");
    if (forwardedFor != null)
        ip = forwardedFor;

    Log.info(Log.REQUEST, "==========================================================");

    Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + request.getRequestURI());
    if (Log.isDebugEnabled(Log.REQUEST)) {
        Log.debug(Log.REQUEST, "Method       : " + request.getMethod());
        Log.debug(Log.REQUEST, "Content type : " + request.getContentType());
        // Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath());
        // Log.debug(Log.REQUEST, "Char encoding: "+
        // req.getCharacterEncoding());
        Log.debug(Log.REQUEST, "Accept       : " + request.getHeader("Accept"));
        // Log.debug(Log.REQUEST, "Server name  : "+ req.getServerName());
        // Log.debug(Log.REQUEST, "Server port  : "+ req.getServerPort());
    }

    if (Log.isDebugEnabled(Log.REQUEST)) {
        if (httpSession != null) {
            Log.debug(Log.REQUEST, "Session id is " + httpSession.getId());
        } else {
            Log.debug(Log.REQUEST, "No session created");
        }
    }

    UserSession session = null;

    if (httpSession != null) {
        session = (UserSession) httpSession.getAttribute(USER_SESSION_ATTRIBUTE_KEY);

        if (session == null) {
            // --- create session

            session = new UserSession();

            httpSession.setAttribute(USER_SESSION_ATTRIBUTE_KEY, session);
            session.setsHttpSession(httpSession);

            if (Log.isDebugEnabled(Log.REQUEST))
                Log.debug(Log.REQUEST, "Session created for client : " + ip);
        }
    }

    ServiceRequest srvReq = null;

    ApplicationContext jeevesApplicationContext = ApplicationContextHolder.get();
    JeevesEngine jeeves = jeevesApplicationContext.getBean(JeevesEngine.class);
    try {
        final Path uploadDir = jeeves.getUploadDir();
        srvReq = ServiceRequestFactory.create(request, response, uploadDir, jeeves.getMaxUploadSize());
    } catch (FileUploadTooBigEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("File upload too big - exceeds ").append(jeeves.getMaxUploadSize()).append(" Mb\n");
        sb.append("Error : ").append(e.getClass().getName()).append("\n");
        response.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());

    } catch (Exception e) {
        StringBuffer sb = new StringBuffer();

        sb.append("Cannot build ServiceRequest\n");
        sb.append("Cause : ").append(e.getMessage()).append("\n");
        sb.append("Error : ").append(e.getClass().getName()).append("\n");
        response.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
    }

    // --- execute request
    try {
        jeeves.dispatch(srvReq, session);
    } finally {
        // Cleanup uploaded resources
        if (request instanceof MultipartRequest) {
            Map<String, MultipartFile> files = ((MultipartRequest) request).getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> it = files.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, MultipartFile> file = it.next();

                Path uploadedFile = jeeves.getUploadDir().resolve(file.getValue().getOriginalFilename());
                FileUtils.deleteQuietly(uploadedFile.toFile());
            }
        }

    }
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

private String readPayloadAsUtf8(HttpServletRequest request) throws IOException, ServletException {
    int contentLength = request.getContentLength();
    if (contentLength == -1) {
        // Content length must be known.
        throw new ServletException("Content-Length must be specified");
    }/*  w ww  .  j a v  a2s. co  m*/

    String contentType = request.getContentType();
    boolean contentTypeIsOkay = false;
    // Content-Type must be specified.
    if (contentType != null) {
        // The type must be plain text.
        if (contentType.startsWith("text/plain")) {
            // And it must be UTF-8 encoded (or unspecified, in which case
            // we assume
            // that it's either UTF-8 or ASCII).
            if (contentType.indexOf("charset=") == -1)
                contentTypeIsOkay = true;
            else if (contentType.indexOf("charset=utf-8") != -1)
                contentTypeIsOkay = true;
        }
    }
    if (!contentTypeIsOkay)
        throw new ServletException(
                "Content-Type must be 'text/plain' with 'charset=utf-8' (or unspecified charset)");

    InputStream in = request.getInputStream();
    try {
        byte[] payload = new byte[contentLength];
        int offset = 0;
        int len = contentLength;
        int byteCount;
        while (offset < contentLength) {
            byteCount = in.read(payload, offset, len);
            if (byteCount == -1)
                throw new ServletException("Client did not send " + contentLength + " bytes as expected");
            offset += byteCount;
            len -= byteCount;
        }
        return new String(payload, "UTF-8");
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:admin.controller.ServletChangeLooks.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods.//from   w w  w. ja  v  a 2  s. 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
  */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = "";
    String fileName, fieldName, uploadPath, deletePath, file_name_to_delete = "", uploadPath1;
    Looks look;
    RequestDispatcher request_dispatcher;
    String lookname = "", lookid = "";
    Integer organization = 0;
    look = new Looks();
    boolean check = false;

    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();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("lookname")) {
                        lookname = fi.getString();
                    }
                    if (fieldName.equals("lookid")) {
                        lookid = fi.getString();
                    }
                    if (fieldName.equals("organization")) {
                        organization = Integer.parseInt(fi.getString());
                    }
                    file_name_to_delete = look.getFileName(Integer.parseInt(lookid));
                } else {

                    check = look.checkAvailabilities(Integer.parseInt(lookid), lookname, organization);

                    if (check == false) {

                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(AppConstants.LOOK_IMAGES_HOME);

                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = lookname + "_" + Str + ".png";
                        fileName = lookname + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = AppConstants.LOOK_IMAGES_HOME + File.separator + fileName;
                        String delete_path = AppConstants.LOOK_IMAGES_HOME + File.separator
                                + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                        look.changeLooks(Integer.parseInt(lookid), lookname, fileName, organization);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/editlook.jsp?exist=exist&look_id=" + lookid
                                        + "&look_name=" + lookname + "&organization_id=" + organization
                                        + "&image_file_name=" + file_name_to_delete);
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing the looks", ex);
    } finally {
        out.close();
    }

}

From source file:controller.FacebookServlet.java

public boolean doFilePost64(HttpServletRequest request) throws FacebookDAOException {
    System.out.println("Do file post 45");
    if (request.getContentType() == null) {
        System.out.println("Content type null");
        return false;
    }/*from   ww w.  j  av a 2  s .  co  m*/

    String s = null;
    try {
        ServletInputStream input = request.getInputStream();
        s = IOUtils.toString(input);
        Pattern regex = Pattern
                .compile("name=(.*)&email=(.*)&password=(.*)&birthday=(.*)&profile=(.*)&cover=(.*)");
        Matcher m = regex.matcher(s);
        if (m.find() && m.groupCount() > 0) {
            String name = m.group(1);
            String email = m.group(2);
            String password = m.group(3);
            String birthday = m.group(4);
            String profile = m.group(5);
            String cover = m.group(6);
            System.out.println(name + " - " + email + " - " + password + " - " + birthday);//+" - "+profile);//+" - "+cover);
            System.out.println(profile.length());
            //
            //
            System.out.println("CALENDAR");
            Calendar birth = Calendar.getInstance();
            System.out.println("DATE");
            String date[] = (birthday.split("-"));
            System.out.println("BIRTH" + birthday);
            birth.set(Integer.valueOf(date[0]), Integer.valueOf(date[1]), Integer.valueOf(date[2]));
            //System.out.println(birth);
            System.out.println("USER");
            User u = new User(name, email, birth);
            //System.out.println(u);
            String pathFile = "C:/Users/BBEIRIGO/Documents/NetBeansProjects/WebServiceFacebook/src/main/webapp/";
            FacebookDAO dao = new FacebookDAO(pathFile);
            User cadastrado = dao.saveUser(u, password);
            new File(pathFile + "/photos/" + cadastrado.getId() + "/Cover").mkdirs();
            new File(pathFile + "/photos/" + cadastrado.getId() + "/Profile").mkdirs();
            System.out.println(cadastrado);
            System.out.println("cover:" + cadastrado.getCoverPhoto().getPath());
            ///
            String coverPath = cadastrado.getCoverPhoto().getPath();
            String profilePath = cadastrado.getProfilePhoto().getPath();
            System.out.println(coverPath);
            //                if (saveFileEconded(URLDecoder.decode(cover, "UTF-8"), coverPath)) {
            //                    System.out.println("ENCODE COVER!!!");
            //                } else {
            //                    System.out.println("NO ENCODE COVER!!!");
            //                }
            //                if (saveFileEconded(URLDecoder.decode(profile, "UTF-8"), profilePath)) {
            //                    System.out.println("ENCODE PROFILE!!!");
            //                } else {
            //                    System.out.println("NO ENCODE PROFILE!!!");
            //                }
        } else {
            System.out.println("No achou!");
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    return true;
}

From source file:eu.impact_project.iif.t2.client.HelperTest.java

/**
 * Test of parseRequest method, of class Helper.
 *///from w ww . j a v a2 s  .c  om
@Test
public void testParseRequest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    URL url = this.getClass().getResource("/prueba.txt");
    File testFile = new File(url.getFile());
    Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile),
            new FilePart("comon_file", testFile) };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    Helper.parseRequest(request);

}

From source file:org.imsglobal.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];/*from w  w w.j  a v  a  2s.com*/
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = TEST_KEY;
    String profile = PERSIST.get("profile");
    JSONObject providerProfile = (JSONObject) JSONValue.parse(profile);
    JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT);
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    LtiVerificationResult result = BasicLTIUtil.validateMessage(request, URL, oauth_secret);
    if (!result.getSuccess()) {
        response.setStatus(HttpStatus.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, result.getMessage(), null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:org.tsugi.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts)
        throws java.io.IOException {

    String URL = request.getRequestURL().toString();
    System.out.println("URL=" + URL);
    String scope = parts[4];/*w  w w .  j  a  v a2  s. com*/
    System.out.println("scope=" + scope);

    String acceptHdr = request.getHeader("Accept");
    String contentHdr = request.getContentType();
    boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0;

    System.out.println("accept=" + acceptHdr + " ac=" + acceptComplex);

    // Check the JSON on PUT and check the oauth_body_hash
    IMSJSONRequest jsonRequest = null;
    JSONObject requestData = null;
    if ("PUT".equals(request.getMethod())) {
        try {
            jsonRequest = new IMSJSONRequest(request);
            requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e);
            return;
        }
    }

    String consumer_key = TEST_KEY;
    String profile = PERSIST.get("profile");
    ToolProxy toolProxy = new ToolProxy(profile);
    JSONObject security_contract = toolProxy.getSecurityContract();
    String oauth_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET);

    // Validate the incoming message
    Object retval = BasicLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key);
    if (retval instanceof String) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        doErrorJSON(request, response, jsonRequest, (String) retval, null);
        return;
    }

    // The URLs for the various settings resources
    String settingsUrl = getServiceURL(request) + SVC_Settings;
    String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key;
    String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + "TBD";
    String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + "TBD";

    // Load and parse the old settings...
    JSONObject link_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_LtiLink));
    JSONObject binding_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxyBinding));
    JSONObject proxy_settings = LTI2Util.parseSettings(PERSIST.get(LTI2Util.SCOPE_ToolProxy));

    // For a GET request we depend on LTI2Util to do the GET logic
    if ("GET".equals(request.getMethod())) {
        Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings,
                link_url, binding_url, proxy_url);

        if (obj instanceof String) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            doErrorJSON(request, response, jsonRequest, (String) obj, null);
            return;
        }

        if (acceptComplex) {
            response.setContentType(StandardServices.TOOLSETTINGS_FORMAT);
        } else {
            response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT);
        }

        JSONObject jsonResponse = (JSONObject) obj;
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter out = response.getWriter();
        System.out.println("jsonResponse=" + jsonResponse);
        out.println(jsonResponse.toString());
        return;
    } else if ("PUT".equals(request.getMethod())) {
        // This is assuming the rule that a PUT of the complex settings
        // format that there is only one entry in the graph and it is
        // the same as our current URL.  We parse without much checking.
        String settings = null;
        try {
            JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH);
            if (graph.size() != 1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null);
                return;
            }
            JSONObject firstChild = (JSONObject) graph.get(0);
            JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM);
            settings = custom.toString();
        } catch (Exception e) {
            settings = jsonRequest.getPostBody();
        }
        PERSIST.put(scope, settings);
        System.out.println("Stored settings scope=" + scope);
        System.out.println("settings=" + settings);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null);
    }
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Sets up the given {@link PostMethod} to send the same content POST data (JSON, XML, etc.) as was sent in the
 * given {@link HttpServletRequest}./* w ww. j a v  a 2s  .c om*/
 *
 * @param postMethodProxyRequest    The {@link PostMethod} that we are configuring to send a standard POST request
 * @param httpServletRequest        The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod}
 */
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    // Hack to trickle main server gwt rpc servlet
    // this avoids warnings like the following :
    // "ERROR: The module path requested, /testmodule/, is not in the same web application as this servlet"
    // or
    // "WARNING: Failed to get the SerializationPolicy '29F4EA1240F157649C12466F01F46F60' for module 'http://localhost:8888/testmodule/'"
    //
    // Actually it avoids a NullPointerException in server logging :
    // See http://code.google.com/p/google-web-toolkit/issues/detail?id=3624
    if (contentType.startsWith(this.stringMimeType)) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1") || clientHost.equals("0:0:0:0:0:0:0:1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = targetHost + ((targetPort != 80) ? ":" + targetPort : "") + stringPrefixPath;

        // Replace more completely if destination server is https :
        if (targetSsl) {
            clientUrl = "http://" + clientUrl;
            serverUrl = "https://" + serverUrl;
        }
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    LOGGER.trace("POST Content Type: {} Encoding: {} Content: {}",
            new Object[] { contentType, encoding, postContent });
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:org.kuali.rice.kns.web.struts.form.pojo.PojoFormBase.java

/**
 * Populates the form with values from the current request. Uses instances of Formatter to convert strings to the Java types of
 * the properties to which they are bound. Values that can't be converted are cached in a map of unconverted values. Returns an
 * ActionErrors containing ActionMessage instances for each conversion error that occured, if any.
 *//* ww w.ja  va 2s.c  o m*/
@Override
public void populate(HttpServletRequest request) {

    StopWatch watch = null;
    if (LOG.isDebugEnabled()) {
        watch = new StopWatch();
        watch.start();
        LOG.debug(WATCH_NAME + ": started");
    }
    unconvertedValues.clear();
    unknownKeys = new ArrayList();
    addRequiredNonEditableProperties();
    Map params = request.getParameterMap();

    String contentType = request.getContentType();
    String method = request.getMethod();

    if ("POST".equalsIgnoreCase(method) && contentType != null
            && contentType.startsWith("multipart/form-data")) {
        Map fileElements = (HashMap) request.getAttribute(KRADConstants.UPLOADED_FILE_REQUEST_ATTRIBUTE_KEY);
        Enumeration names = Collections.enumeration(fileElements.keySet());
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            params.put(name, fileElements.get(name));
        }
    }

    postprocessRequestParameters(params);

    /**
     * Iterate through request parameters, if parameter matches a form variable, get the property type, formatter and convert,
     * if not add to the unknowKeys map.
     */
    Comparator<String> nestedPathComparator = new Comparator<String>() {
        public int compare(String prop1, String prop2) {
            Integer i1 = new Integer(prop1.split("\\.").length);
            Integer i2 = new Integer(prop2.split("\\.").length);
            return (i1.compareTo(i2));
        }
    };

    List<String> pathKeyList = new ArrayList<String>(params.keySet());
    Collections.sort(pathKeyList, nestedPathComparator);

    for (String keypath : pathKeyList) {
        if (shouldPropertyBePopulatedInForm(keypath, request)) {
            Object param = params.get(keypath);
            //LOG.debug("(keypath,paramType)=(" + keypath + "," + param.getClass().getName() + ")");

            populateForProperty(keypath, param, params);
        }
    }
    this.registerIsNewForm(false);
    if (LOG.isDebugEnabled()) {
        watch.stop();
        LOG.debug(WATCH_NAME + ": " + watch.toString());
    }
}