List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:com.nsano.uat.Imtservlet.java
/** * * @param request/*from ww w . j av a2 s . c o m*/ * @return * @throws IOException */ private String moneytransfer(HttpServletRequest request) throws IOException, JSONException, NoSuchAlgorithmException { // joined json string String join = ""; JsonElement root = null; JsonElement root2 = null; JsonElement root3 = null; String responseobject = ""; //String nickname="KENDYIPL"; // These represent parameters received over the network String tag = "", apikey = "", refID = "", sender = "", sender_country = "", receiver = "", receiver_msisdn = "", receiver_country = "", amount = "", mno = ""; //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative // Get all parameters, the keys of the parameters are specified List<String> lines = IOUtils.readLines(request.getReader()); // used to format/join incoming JSon string join = StringUtils.join(lines.toArray(), ""); //############################################################################### // instantiate the JSon //Note //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping(). //############################################################################### Gson g = new GsonBuilder().disableHtmlEscaping().create(); //Gson g = new Gson(); Map<String, String> expected = new HashMap<>(); try { // parse the JSon string //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative root = new JsonParser().parse(join); tag = root.getAsJsonObject().get("tag").getAsString(); apikey = root.getAsJsonObject().get("apikey").getAsString(); refID = root.getAsJsonObject().get("refID").getAsString(); sender = root.getAsJsonObject().get("sender").getAsString(); sender_country = root.getAsJsonObject().get("sender_country").getAsString(); receiver = root.getAsJsonObject().get("receiver").getAsString(); receiver_msisdn = root.getAsJsonObject().get("receiver_msisdn").getAsString(); receiver_country = root.getAsJsonObject().get("receiver_country").getAsString(); amount = root.getAsJsonObject().get("amount").getAsString(); mno = root.getAsJsonObject().get("mno").getAsString(); } catch (Exception e) { expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS"); String jsonResult = g.toJson(expected); System.out.println(e); return jsonResult; } //check for the presence of all required parameters if (StringUtils.isBlank(tag) || StringUtils.isBlank(apikey) || StringUtils.isBlank(refID) || StringUtils.isBlank(sender) || StringUtils.isBlank(sender_country) || StringUtils.isBlank(receiver) || StringUtils.isBlank(receiver_msisdn) || StringUtils.isBlank(receiver_country) || StringUtils.isBlank(amount) || StringUtils.isBlank(mno)) { //expected.put("username", username); expected.put("status_code", statuscode); expected.put("status_description", Statusdescription); String jsonResult = g.toJson(expected); return jsonResult; } //assign the remit url from properties.config //String processtransaction = airtelbalance.AirtelBalance( nickname, username, password); String processtransaction = cred.sendPOST(); //capture the switch respoinse. System.out.println(processtransaction); //pass the returned json string JsonElement roots = new JsonParser().parse(processtransaction); //JsonElement rootsone = roots.getAsJsonObject(); //exctract a specific json element from the object(status_code) //Double code = roots.getAsJsonObject().get("code").getAsDouble(); Number code = roots.getAsJsonObject().get("code").getAsNumber(); String msg = roots.getAsJsonObject().get("msg").getAsString(); //String data = rootsone.getAsJsonObject().get("error_type").getAsString(); //add //expected.put("username", username); expected.put("code", code.toString()); expected.put("msg", msg.toString()); //expected.put("error_type", data.toString()); String jsonResult = g.toJson(expected); if (code.toString() == "00") { System.out.println("success"); } else { System.out.println("fail"); } return jsonResult; }
From source file:org.openbravo.service.datasource.DataSourceServlet.java
private String getRequestContent(HttpServletRequest request) throws IOException { final BufferedReader reader = request.getReader(); if (reader == null) { return ""; }/*from w w w. ja v a 2s . co m*/ String line; final StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append(line); } log.debug("REQUEST CONTENT>>>>"); for (Enumeration<?> enumeration = request.getParameterNames(); enumeration.hasMoreElements();) { final Object key = enumeration.nextElement(); log.debug(key + ": " + request.getParameter((String) key)); } return sb.toString(); }
From source file:com.nsano.uat.StatusServlet.java
/** * * @param request//from w w w . j ava2 s.c o m * @return * @throws IOException */ private String moneytransfer(HttpServletRequest request) throws IOException, JSONException, NoSuchAlgorithmException { // joined json string String join = ""; JsonElement root = null; JsonElement root2 = null; JsonElement root3 = null; String responseobject = ""; //String nickname="KENDYIPL"; // These represent parameters received over the network String tag = "", apikey = "", refID = "", sender = "", sender_country = "", receiver = "", receiver_msisdn = "", receiver_country = "", amount = "", mno = ""; //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative // Get all parameters, the keys of the parameters are specified List<String> lines = IOUtils.readLines(request.getReader()); // used to format/join incoming JSon string join = StringUtils.join(lines.toArray(), ""); //############################################################################### // instantiate the JSon //Note //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping(). //############################################################################### Gson g = new GsonBuilder().disableHtmlEscaping().create(); //Gson g = new Gson(); Map<String, String> expected = new HashMap<>(); try { // parse the JSon string //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative root = new JsonParser().parse(join); tag = root.getAsJsonObject().get("tag").getAsString(); apikey = root.getAsJsonObject().get("apikey").getAsString(); refID = root.getAsJsonObject().get("refID").getAsString(); sender = root.getAsJsonObject().get("sender").getAsString(); sender_country = root.getAsJsonObject().get("sender_country").getAsString(); receiver = root.getAsJsonObject().get("receiver").getAsString(); receiver_msisdn = root.getAsJsonObject().get("receiver_msisdn").getAsString(); receiver_country = root.getAsJsonObject().get("receiver_country").getAsString(); amount = root.getAsJsonObject().get("amount").getAsString(); mno = root.getAsJsonObject().get("mno").getAsString(); } catch (Exception e) { expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS"); String jsonResult = g.toJson(expected); System.out.println(e); return jsonResult; } //check for the presence of all required parameters if (StringUtils.isBlank(tag) || StringUtils.isBlank(apikey) || StringUtils.isBlank(refID) || StringUtils.isBlank(sender) || StringUtils.isBlank(sender_country) || StringUtils.isBlank(receiver) || StringUtils.isBlank(receiver_msisdn) || StringUtils.isBlank(receiver_country) || StringUtils.isBlank(amount) || StringUtils.isBlank(mno)) { //expected.put("username", username); expected.put("status_code", statuscode); expected.put("status_description", Statusdescription); String jsonResult = g.toJson(expected); return jsonResult; } //assign the remit url from properties.config //String processtransaction = airtelbalance.AirtelBalance( nickname, username, password); String processtransaction = st.sendPOST(); //capture the switch respoinse. System.out.println(processtransaction); //pass the returned json string JsonElement roots = new JsonParser().parse(processtransaction); //JsonElement rootsone = roots.getAsJsonObject(); //exctract a specific json element from the object(status_code) //Double code = roots.getAsJsonObject().get("code").getAsDouble(); Number code = roots.getAsJsonObject().get("code").getAsNumber(); System.out.println("####################################################################"); System.out.println(code); System.out.println("####################################################################"); String msg = roots.getAsJsonObject().get("msg").getAsString(); System.out.println(msg); System.out.println("#####################################################################"); //String d ata = rootsone.getAsJsonObject().get("error_type").getAsString(); // loop array //add //expected.put("username", username); expected.put("code", code.toString()); expected.put("msg", msg.toString()); //expected.put("error_type", data.toString()); String jsonResult = g.toJson(expected); if (code.toString() == "01") { System.out.println("fail"); } else { System.out.println("success"); } return jsonResult; }
From source file:org.academia.servlet.SListarTutor.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from w w w . ja v a 2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String g = request.getParameter("ids"); // // BTutor oBTutor = new BTutor(); // oBTutor.setIdTutor(Integer.parseInt(g)); // oBTutor.setIdTutor(Integer.parseInt(g)); // ArrayList<String> array = new DAOTutor().detalleTutor(oBTutor); // String arraystring = "{\"direccion\":\""+ array.get(0) +"\", \"estado\":" + array.get(1) + ", \"numero\":\"" + array.get(2) + "\", \"denominacion\": \"" + array.get(3) + "\"}"; // String json1 = new Gson().toJson(arraystring); // response.setContentType("application/json"); // response.setCharacterEncoding("utf-8"); // response.getWriter().write(arraystring); StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { jb.append(line); } String datt = String.valueOf(jb.toString()); JSONObject jsonObj = new JSONObject(datt); BTutor oTutor = new BTutor(); String value = (String) jsonObj.get("idTutor"); oTutor.setIdTutor(Integer.parseInt(value)); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java
/** * Get the request body./*from w w w . j ava2 s . c om*/ * * @param request the request. * @return the body as a string. * @throws IOException */ private String getRequestBody(HttpServletRequest request) throws IOException { final String contentEncoding = request.getHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.contains("gzip")) { // then treat the request body as gzip: final GZIPInputStream gzipIn = new GZIPInputStream(request.getInputStream()); final String gunzippedEncodedJson = IOUtils.toString(gzipIn); gzipIn.close(); return gunzippedEncodedJson; } else { // otherwise assume plain-text: return IOUtils.toString(request.getReader()); } }
From source file:org.b3log.solo.processor.CommentProcessorTestCase.java
/** * addPageComment./* w w w . j a v a 2 s. c om*/ * * @throws Exception exception */ @Test(dependsOnMethods = "init") public void addPageComment() throws Exception { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletContext()).thenReturn(mock(ServletContext.class)); when(request.getRequestURI()).thenReturn("/add-page-comment.do"); when(request.getMethod()).thenReturn("POST"); final HttpSession session = mock(HttpSession.class); when(session.getAttribute(CaptchaProcessor.CAPTCHA)).thenReturn("captcha123456"); when(request.getSession(false)).thenReturn(session); final JSONObject requestJSON = new JSONObject(); requestJSON.put("captcha", "captcha123456"); requestJSON.put("oId", addPage()); requestJSON.put("commentName", "88250"); requestJSON.put("commentEmail", "d@hacpai.com"); requestJSON.put("commentURL", "https://hacpai.com"); requestJSON.put("commentContent", ""); final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString())); when(request.getReader()).thenReturn(reader); final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet(); dispatcherServlet.init(); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(printWriter); dispatcherServlet.service(request, response); final String content = stringWriter.toString(); Assert.assertTrue(StringUtils.contains(content, "\"sc\":true")); }
From source file:org.b3log.solo.processor.CommentProcessorTestCase.java
/** * addArticleComment.// ww w . jav a2 s.c o m * * @throws Exception exception */ @Test(dependsOnMethods = "init") public void addArticleComment() throws Exception { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletContext()).thenReturn(mock(ServletContext.class)); when(request.getRequestURI()).thenReturn("/add-article-comment.do"); when(request.getMethod()).thenReturn("POST"); final HttpSession session = mock(HttpSession.class); when(session.getAttribute(CaptchaProcessor.CAPTCHA)).thenReturn("captcha123456"); when(request.getSession(false)).thenReturn(session); final JSONObject requestJSON = new JSONObject(); requestJSON.put("captcha", "captcha123456"); requestJSON.put("oId", addArticle()); requestJSON.put("commentName", "88250"); requestJSON.put("commentEmail", "d@hacpai.com"); requestJSON.put("commentURL", "https://hacpai.com"); requestJSON.put("commentContent", ""); final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString())); when(request.getReader()).thenReturn(reader); final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet(); dispatcherServlet.init(); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); final HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(printWriter); dispatcherServlet.service(request, response); final String content = stringWriter.toString(); Assert.assertTrue(StringUtils.contains(content, "\"sc\":true")); }
From source file:com.controller.schedule.ScheduleSocialPostServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); HttpSession session = request.getSession(); if (session.getAttribute("UID") == null) { Map<String, Object> error = new HashMap<>(); error.put("error", "User is not logged in"); response.getWriter().write(AppConstants.GSON.toJson(error)); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().flush(); response.setContentType("application/json"); return; } Integer userId = Integer.parseInt(session.getAttribute("UID").toString()); List<Map<String, Object>> requestBodyList = AppConstants.GSON .fromJson(new BufferedReader(request.getReader()), List.class); if (requestBodyList == null || requestBodyList.isEmpty()) { Map<String, Object> error = new HashMap<>(); error.put("error", "Request body is missing"); response.getWriter().write(AppConstants.GSON.toJson(error)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().flush(); return; } System.out.println(requestBodyList); List<String> errorMessages = validateRequestBodyList(requestBodyList); if (!errorMessages.isEmpty()) { Map<String, Object> error = new HashMap<>(); error.put("error", errorMessages); response.getWriter().write(AppConstants.GSON.toJson(error)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().flush(); return; } /* If no error messages in the above validation, then next is to validate the JSON structure associated with the keys token_data and metadata */ for (Map<String, Object> requestBodyMap : requestBodyList) { String tokenDataString = requestBodyMap.get("token_data").toString(); String type = requestBodyMap.get("type").toString(); errorMessages.addAll(validateTokenData(tokenDataString, type)); String metadataString = requestBodyMap.get("metadata").toString(); errorMessages.addAll(validateMetadata(metadataString, type)); } if (!errorMessages.isEmpty()) { Map<String, Object> error = new HashMap<>(); error.put("error", errorMessages); response.getWriter().write(AppConstants.GSON.toJson(error)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().flush(); return; } List<Map<String, Integer>> daoResponseList = new ArrayList<>(); try (Connection conn = ConnectionManager.getInstance().getConnection()) { conn.setAutoCommit(false); try { for (Map<String, Object> requestBodyMap : requestBodyList) { Double schedule = (Double) requestBodyMap.get("schedule_time"); Timestamp scheduleTimeStamp = new Timestamp(schedule.longValue()); String tokenDataString = requestBodyMap.get("token_data").toString(); String metadataString = requestBodyMap.get("metadata").toString(); //As of now schedule description is not yet mandatory. String scheduleDesc = requestBodyMap.containsKey("schedule_desc") ? String.valueOf(requestBodyMap.get("schedule_desc")) : null; Map<String, Integer> daoResponse = ScheduleSocialPostDAO.addToScheduleSocialPost(userId, requestBodyMap.get("image_name").toString(), AppConstants.GSON.fromJson(tokenDataString, Map.class), AppConstants.GSON.fromJson(metadataString, Map.class), requestBodyMap.get("type").toString(), requestBodyMap.get("schedule_title").toString(), scheduleDesc, scheduleTimeStamp, TemplateStatus.template_saved.toString(), conn); daoResponseList.add(daoResponse); } conn.commit(); } catch (SQLException ex) { conn.rollback(); throw ex; } response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write(AppConstants.GSON.toJson(daoResponseList)); response.getWriter().flush(); } catch (SQLException ex) { Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java
private void handleSenseiRequest(HttpServletRequest req, HttpServletResponse resp, Broker<SenseiRequest, SenseiResult> broker) throws ServletException, IOException { long time = System.currentTimeMillis(); int numHits = 0, totalDocs = 0; String query = null;//from w w w . ja v a2s. c o m SenseiRequest senseiReq = null; try { JSONObject jsonObj = null; String content = null; if ("post".equalsIgnoreCase(req.getMethod())) { BufferedReader reader = req.getReader(); content = readContent(reader); if (content == null || content.length() == 0) content = "{}"; try { jsonObj = new JSONObject(content); } catch (JSONException jse) { String contentType = req.getHeader("Content-Type"); if (contentType != null && contentType.indexOf("json") >= 0) { logger.error("JSON parsing error", jse); writeEmptyResponse(req, resp, new SenseiError(jse.getMessage(), ErrorType.JsonParsingError)); return; } logger.warn("Old client or json error", jse); // Fall back to the old REST API. In the future, we should // consider reporting JSON exceptions here. senseiReq = DefaultSenseiJSONServlet.convertSenseiRequest( new DataConfiguration(new MapConfiguration(getParameters(content)))); query = content; } } else { content = req.getParameter("json"); if (content != null) { if (content.length() == 0) content = "{}"; try { jsonObj = new JSONObject(content); } catch (JSONException jse) { logger.error("JSON parsing error", jse); writeEmptyResponse(req, resp, new SenseiError(jse.getMessage(), ErrorType.JsonParsingError)); return; } } else { senseiReq = buildSenseiRequest(req); query = URLEncodedUtils.format(HttpRestSenseiServiceImpl.convertRequestToQueryParams(senseiReq), "UTF-8"); } } if (jsonObj != null) { String bqlStmt = jsonObj.optString(BQL_STMT); JSONObject templatesJson = jsonObj.optJSONObject(JsonTemplateProcessor.TEMPLATE_MAPPING_PARAM); JSONObject compiledJson = null; if (bqlStmt.length() > 0) { try { if (jsonObj.length() == 1) query = "bql=" + bqlStmt; else query = "json=" + content; compiledJson = _compiler.compile(bqlStmt); } catch (RecognitionException e) { String errMsg = _compiler.getErrorMessage(e); if (errMsg == null) { errMsg = "Unknown parsing error."; } logger.error("BQL parsing error: " + errMsg + ", BQL: " + bqlStmt); writeEmptyResponse(req, resp, new SenseiError(errMsg, ErrorType.BQLParsingError)); return; } // Handle extra BQL filter if it exists String extraFilter = jsonObj.optString(BQL_EXTRA_FILTER); JSONObject predObj = null; if (extraFilter.length() > 0) { String bql2 = "SELECT * WHERE " + extraFilter; try { predObj = _compiler.compile(bql2); } catch (RecognitionException e) { String errMsg = _compiler.getErrorMessage(e); if (errMsg == null) { errMsg = "Unknown parsing error."; } logger.error("BQL parsing error for additional preds: " + errMsg + ", BQL: " + bql2); writeEmptyResponse(req, resp, new SenseiError( "BQL parsing error for additional preds: " + errMsg + ", BQL: " + bql2, ErrorType.BQLParsingError)); return; } // Combine filters JSONArray filter_list = new JSONArray(); JSONObject currentFilter = compiledJson.optJSONObject("filter"); if (currentFilter != null) { filter_list.put(currentFilter); } JSONArray selections = predObj.optJSONArray("selections"); if (selections != null) { for (int i = 0; i < selections.length(); ++i) { JSONObject pred = selections.getJSONObject(i); if (pred != null) { filter_list.put(pred); } } } JSONObject additionalFilter = predObj.optJSONObject("filter"); if (additionalFilter != null) { filter_list.put(additionalFilter); } if (filter_list.length() > 1) { compiledJson.put("filter", new JSONObject().put("and", filter_list)); } else if (filter_list.length() == 1) { compiledJson.put("filter", filter_list.get(0)); } } JSONObject metaData = compiledJson.optJSONObject("meta"); if (metaData != null) { JSONArray variables = metaData.optJSONArray("variables"); if (variables != null) { for (int i = 0; i < variables.length(); ++i) { String var = variables.getString(i); if (templatesJson == null || templatesJson.opt(var) == null) { writeEmptyResponse(req, resp, new SenseiError("[line:0, col:0] Variable " + var + " is not found.", ErrorType.BQLParsingError)); return; } } } } } else { // This is NOT a BQL statement query = "json=" + content; compiledJson = jsonObj; } if (templatesJson != null) { compiledJson.put(JsonTemplateProcessor.TEMPLATE_MAPPING_PARAM, templatesJson); } senseiReq = SenseiRequest.fromJSON(compiledJson, _facetInfoMap); } SenseiResult res = broker.browse(senseiReq); numHits = res.getNumHits(); totalDocs = res.getTotalDocs(); sendResponse(req, resp, senseiReq, res); } catch (JSONException e) { try { writeEmptyResponse(req, resp, new SenseiError(e.getMessage(), ErrorType.JsonParsingError)); } catch (Exception ex) { throw new ServletException(e); } } catch (Exception e) { try { logger.error(e.getMessage(), e); if (e.getCause() != null && e.getCause() instanceof JSONException) { writeEmptyResponse(req, resp, new SenseiError(e.getMessage(), ErrorType.JsonParsingError)); } else { writeEmptyResponse(req, resp, new SenseiError(e.getMessage(), ErrorType.InternalError)); } } catch (Exception ex) { throw new ServletException(e); } } finally { if (queryLogger.isInfoEnabled() && query != null) { queryLogger.info(String.format("hits(%d/%d) took %dms: %s", numHits, totalDocs, System.currentTimeMillis() - time, query)); } } }