List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:org.guanxi.idp.service.shibboleth.AttributeAuthority.java
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { // Load up the config file IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG); String nameIdentifier = null; RequestType samlRequest = null;//from ww w .j av a2 s .c o m RequestDocument samlRequestDoc = null; try { /* Parse the SOAP message that contains the SAML Request... * XMLBeans 2.2.0 has problems parsing from an InputStream though */ BufferedReader buffer = request.getReader(); StringBuffer stringBuffer = new StringBuffer(); String line = null; while ((line = buffer.readLine()) != null) { stringBuffer.append(line); } buffer.close(); logger.debug( "Parsing attribute query : " + stringBuffer.length() + " bytes " + stringBuffer.toString()); EnvelopeDocument soapEnvelopeDoc = EnvelopeDocument.Factory.parse(stringBuffer.toString()); Body soapBody = soapEnvelopeDoc.getEnvelope().getBody(); // ...and extract the SAML Request samlRequestDoc = RequestDocument.Factory.parse(soapBody.getDomNode().getFirstChild()); samlRequest = samlRequestDoc.getRequest(); } catch (UnsupportedEncodingException uee) { logger.error("Can't parse input text", uee); } catch (IOException ioe) { logger.error("Can't read the input", ioe); } catch (IllegalStateException ise) { logger.error("Can't read input - already read", ise); } catch (XmlException xe) { logger.error("Can't parse SOAP AttributeQuery", xe); } // The first thing we need to do is find out what Principal is being referred to by the requesting SP // Get the SP's providerId from the attribute query String spProviderId = samlRequest.getAttributeQuery().getResource(); // Get the NameIdentifier of the query... nameIdentifier = samlRequest.getAttributeQuery().getSubject().getNameIdentifier().getStringValue(); // ...and retrieve their SP specific details from the session GuanxiPrincipal principal = (GuanxiPrincipal) servletContext.getAttribute(nameIdentifier); HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put(Shibboleth.NS_SAML_10_PROTOCOL, Shibboleth.NS_PREFIX_SAML_10_PROTOCOL); namespaces.put(Shibboleth.NS_SAML_10_ASSERTION, Shibboleth.NS_PREFIX_SAML_10_ASSERTION); XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setSavePrettyPrint(); xmlOptions.setSavePrettyPrintIndent(2); xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveAggressiveNamespaces(); xmlOptions.setSaveSuggestedPrefixes(namespaces); xmlOptions.setSaveNamespacesFirst(); // Build a SAML Response to send to the SP ResponseDocument samlResponseDoc = ResponseDocument.Factory.newInstance(xmlOptions); ResponseType samlResponse = samlResponseDoc.addNewResponse(); samlResponse.setResponseID(Utils.createNCNameID()); samlResponse.setMajorVersion(new BigInteger("1")); samlResponse.setMinorVersion(new BigInteger("1")); samlResponse.setIssueInstant(Calendar.getInstance()); samlResponse.setInResponseTo(samlRequest.getRequestID()); Utils.zuluXmlObject(samlResponse, 0); // Get a SAML Status ready StatusDocument statusDoc = StatusDocument.Factory.newInstance(); StatusType status = statusDoc.addNewStatus(); StatusCodeType topLevelStatusCode = status.addNewStatusCode(); // From now on, any exceptions will be propagated to the SP using <Status> // Is this a locally registered SP? String spID = null; ServiceProvider[] spList = idpConfig.getServiceProviderArray(); for (int c = 0; c < spList.length; c++) { if (spList[c].getName().equals(spProviderId)) { // We trust locally registered SPs spID = spProviderId; } } /* Not a locally registered SP, so full validation rules. * * The client's X509Certificate chain will only be available if the server is configured to ask for it. * In Tomcat's case, this means configuring client authentication: * clientAuth="want" * If you use clientAuth="true" you'll need to put the AA on a different port from the SSO as the SSO * doesn't use certificates as it's accessed by a browser. The AA is only accessed by a machine (SP). */ if (spID == null) { EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM); EntityManager manager = farm.getEntityManagerForID(spProviderId); if (manager != null) { if (manager.getMetadata(spProviderId) != null) { if (manager.getTrustEngine() != null) { if (!manager.getTrustEngine().trustEntity(manager.getMetadata(spProviderId), (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"))) { logger.error("Failed to trust SP '" + spProviderId); topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_ERROR)); samlResponse.setStatus(status); samlResponseDoc.save(response.getOutputStream()); return false; } } else { logger.error("Manager could not find trust engine for SP '" + spProviderId); topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_ERROR)); samlResponse.setStatus(status); samlResponseDoc.save(response.getOutputStream()); return false; } } else { logger.error("Manager could not find metadata for SP '" + spProviderId); topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_ERROR)); samlResponse.setStatus(status); samlResponseDoc.save(response.getOutputStream()); return false; } } else { logger.error("Could not find manager for SP '" + spProviderId); topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_ERROR)); samlResponse.setStatus(status); samlResponseDoc.save(response.getOutputStream()); return false; } } // Did we get the principal from the request? if (principal == null) { // If not, there's nothing we can do about attributes. topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_ERROR)); samlResponse.setStatus(status); samlResponseDoc.save(response.getOutputStream()); return false; } // Get their attributes UserAttributesDocument attributesDoc = UserAttributesDocument.Factory.newInstance(); UserAttributesDocument.UserAttributes attributes = attributesDoc.addNewUserAttributes(); for (org.guanxi.idp.farm.attributors.Attributor attr : attributor) { attr.getAttributes(principal, spProviderId, arpEngine, mapper, attributes); } // Set the Status for the SAML Response topLevelStatusCode.setValue(new QName("", Shibboleth.SAMLP_SUCCESS)); samlResponse.setStatus(status); // Get a new Assertion ready for the AttributeStatement nodes AssertionDocument assertionDoc = AssertionDocument.Factory.newInstance(); AssertionType assertion = assertionDoc.addNewAssertion(); assertion.setAssertionID(Utils.createNCNameID()); assertion.setMajorVersion(new BigInteger("1")); assertion.setMinorVersion(new BigInteger("1")); assertion.setIssuer(principal.getIssuerFor(spProviderId)); assertion.setIssueInstant(Calendar.getInstance()); Utils.zuluXmlObject(assertion, 0); // Conditions for the assertions ConditionsDocument conditionsDoc = ConditionsDocument.Factory.newInstance(); ConditionsType conditions = conditionsDoc.addNewConditions(); conditions.setNotBefore(Calendar.getInstance()); conditions.setNotOnOrAfter(Calendar.getInstance()); Utils.zuluXmlObject(conditions, 5); assertion.setConditions(conditions); // Add the attributes if there are any AttributeStatementDocument attrStatementDoc = addAttributesFromFarm(attributesDoc, samlRequest.getAttributeQuery().getSubject().getNameIdentifier().getNameQualifier(), spProviderId); // If a user has no attributes we shouldn't add an Assertion or Subject if (attrStatementDoc != null) { SubjectType subject = attrStatementDoc.getAttributeStatement().addNewSubject(); NameIdentifierType nameID = subject.addNewNameIdentifier(); nameID.setFormat(samlRequest.getAttributeQuery().getSubject().getNameIdentifier().getFormat()); nameID.setNameQualifier( samlRequest.getAttributeQuery().getSubject().getNameIdentifier().getNameQualifier()); nameID.setStringValue( samlRequest.getAttributeQuery().getSubject().getNameIdentifier().getStringValue()); assertion.setAttributeStatementArray( new AttributeStatementType[] { attrStatementDoc.getAttributeStatement() }); samlResponse.setAssertionArray(new AssertionType[] { assertion }); } // Get the config ready for signing SecUtilsConfig secUtilsConfig = new SecUtilsConfig(); secUtilsConfig.setKeystoreFile(principal.getSigningCredsFor(spProviderId).getKeystoreFile()); secUtilsConfig.setKeystorePass(principal.getSigningCredsFor(spProviderId).getKeystorePassword()); secUtilsConfig.setKeystoreType(principal.getSigningCredsFor(spProviderId).getKeystoreType()); secUtilsConfig.setPrivateKeyAlias(principal.getSigningCredsFor(spProviderId).getPrivateKeyAlias()); secUtilsConfig.setPrivateKeyPass(principal.getSigningCredsFor(spProviderId).getPrivateKeyPassword()); secUtilsConfig.setCertificateAlias(principal.getSigningCredsFor(spProviderId).getCertificateAlias()); secUtilsConfig.setKeyType(principal.getSigningCredsFor(spProviderId).getKeyType()); response.setContentType("text/xml"); // SOAP message to hold the SAML Response EnvelopeDocument soapResponseDoc = EnvelopeDocument.Factory.newInstance(); Envelope soapEnvelope = soapResponseDoc.addNewEnvelope(); Body soapBody = soapEnvelope.addNewBody(); // Do we need to sign the assertion? boolean samlAddedToResponse = false; String resource = request.getParameter(samlRequest.getAttributeQuery().getResource()); if (resource != null) { EntityDescriptorType sp = (EntityDescriptorType) servletContext.getAttribute(resource); if (sp != null) { if (sp.getSPSSODescriptorArray(0) != null) { if (sp.getSPSSODescriptorArray(0).getWantAssertionsSigned()) { // Break out to DOM land to get the SAML Response signed... Document signedDoc = null; try { // Add a signed assertion to the response samlAddedToResponse = true; // Need to use newDomNode to preserve namespace information signedDoc = SecUtils.getInstance().sign(secUtilsConfig, (Document) samlResponseDoc.newDomNode(xmlOptions), ""); // Add the SAML Response to the SOAP message soapBody.getDomNode().appendChild(soapBody.getDomNode().getOwnerDocument() .importNode(signedDoc.getDocumentElement(), true)); } catch (GuanxiException ge) { logger.error(ge); } } // if (sp.getSPSSODescriptorArray(0).getWantAssertionsSigned()) } // if (sp.getSPSSODescriptorArray(0) != null) } } if (!samlAddedToResponse) { // Add the unsigned SAML Response to the SOAP message soapBody.getDomNode().appendChild( soapBody.getDomNode().getOwnerDocument().importNode(samlResponse.newDomNode(xmlOptions), true)); } // Debug syphoning? if (idpConfig.getDebug() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions() != null) { if (idpConfig.getDebug().getSypthonAttributeAssertions().equals("yes")) { logger.info("======================================================="); logger.info("Response to AttributeQuery by " + spProviderId); logger.info(""); StringWriter sw = new StringWriter(); soapResponseDoc.save(sw, xmlOptions); logger.info(sw.toString()); logger.info(""); logger.info("======================================================="); } } } soapResponseDoc.save(response.getOutputStream(), xmlOptions); return false; }
From source file:com.softwarementors.extjs.djn.servlet.DirectJNgineServlet.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Missing a 'default' branch is not a problem with enums, given the appropriate compiler settings") private void processRequest(HttpServletRequest request, HttpServletResponse response, RequestType type) throws IOException { final String JSON_CONTENT_TYPE = "application/json"; final String JAVASCRIPT_CONTENT_TYPE = "text/javascript"; // *YES*, shoul be "application/javascript", but then there is IE, and the fact that this is really cross-browser (sigh!) final String HTML_CONTENT_TYPE = "text/html"; RequestRouter processor = getProcessor(); switch (type) { case FORM_SIMPLE_POST: response.setContentType(JSON_CONTENT_TYPE); processor.processSimpleFormPostRequest(request.getReader(), response.getWriter()); break;//w w w. ja v a 2s . c o m case FORM_UPLOAD_POST: response.setContentType(HTML_CONTENT_TYPE); // MUST be "text/html" for uploads to work! processUploadFormPost(request, response); break; case JSON: response.setContentType(JSON_CONTENT_TYPE); processor.processJsonRequest(request.getReader(), response.getWriter()); break; case POLL: response.setContentType(JSON_CONTENT_TYPE); processor.processPollRequest(request.getReader(), response.getWriter(), request.getPathInfo()); break; case SOURCE: response.setContentType(JAVASCRIPT_CONTENT_TYPE); processor.processSourceRequest(request.getReader(), response.getWriter(), request.getPathInfo()); break; } }
From source file:net.bull.javamelody.TestMonitoringFilter.java
/** Test. * @throws ServletException e/*from ww w.java 2s .c om*/ * @throws IOException e */ @Test public void testDoFilterWithGWT() throws ServletException, IOException { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); final String textGwtRpc = "text/x-gwt-rpc"; expect(request.getContentType()).andReturn(textGwtRpc).anyTimes(); expect(request.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes(); doFilter(request); final HttpServletRequest request2a = createNiceMock(HttpServletRequest.class); expect(request2a.getContentType()).andReturn("not/x-gwt-rpc").anyTimes(); expect(request2a.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes(); doFilter(request2a); final HttpServletRequest request2b = createNiceMock(HttpServletRequest.class); expect(request2b.getContentType()).andReturn(textGwtRpc).anyTimes(); expect(request2b.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6")).anyTimes(); expect(request2b.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes(); replay(request2b); final PayloadNameRequestWrapper wrapper2b = new PayloadNameRequestWrapper(request2b); wrapper2b.getInputStream().read(); wrapper2b.getReader().read(); verify(request2b); final HttpServletRequest request2 = createNiceMock(HttpServletRequest.class); expect(request2.getContentType()).andReturn(textGwtRpc).anyTimes(); expect(request2.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes(); expect(request2.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes(); replay(request2); final PayloadNameRequestWrapper wrapper2 = new PayloadNameRequestWrapper(request2); wrapper2.getInputStream().read(); wrapper2.getReader().read(); verify(request2); final HttpServletRequest request3 = createNiceMock(HttpServletRequest.class); expect(request3.getContentType()).andReturn(textGwtRpc).anyTimes(); expect(request3.getCharacterEncoding()).andReturn("utf-8").anyTimes(); expect(request3.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes(); expect(request3.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes(); replay(request3); final PayloadNameRequestWrapper wrapper3 = new PayloadNameRequestWrapper(request3); wrapper3.getInputStream().read(); wrapper3.getInputStream().read(); wrapper3.getReader().read(); wrapper3.getReader().read(); verify(request3); }
From source file:com.controller.schedule.ScheduleSocialPostActionsServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w . j a va2 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("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { 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; } 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; } 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) { String tokenDataString = requestBodyMap.get("token_data").toString(); String metadataString = requestBodyMap.get("metadata").toString(); String schedule_id = (String) requestBodyMap.get("schedule_id"); Map<String, Integer> daoResponse = ScheduleSocialPostDAO.updateActionsToScheduleSocialPost( userId, Integer.parseInt(schedule_id), requestBodyMap.get("image_name").toString(), AppConstants.GSON.fromJson(tokenDataString, Map.class), AppConstants.GSON.fromJson(metadataString, Map.class), requestBodyMap.get("type").toString(), 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); } } catch (Exception e) { Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, e); out.println(e); } }
From source file:com.impala.paga.all.QueryBanks.java
/** * //w w w. j av a2s . com * @param request * @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 remiturlss = ""; Properties prop = new Properties(); String hashkey = prop.getProperty("hashkey"); String principal = prop.getProperty("principal"); String credentials = prop.getProperty("credentials"); // String hashkey ="372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66"; // String principal="02A10715-0E53-4A8C-982E-2B7BFC7CF550"; //String credentials ="QE3@u=jd*2b+"; // These represent parameters received over the network String referenceNumber = ""; // 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 root = new JsonParser().parse(join); referenceNumber = root.getAsJsonObject().get("referenceNumber").getAsString(); remiturlss = root.getAsJsonObject().get("remiturlss").getAsString(); } catch (Exception e) { expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS"); String jsonResult = g.toJson(expected); System.out.println(e); return jsonResult; } /*String referenceNumber = "", amount = "",currency="",destinationBankUUID="", destinationBankAccountNumber= "", recipientPhoneNumber = "" , credentials = "";*/ // check for the presence of all required parameters if (StringUtils.isBlank(referenceNumber)) { expected.put("am_referenceid", referenceNumber); expected.put("am_timestamp", "tombwa"); expected.put("status_code", statuscode); expected.put("status_description", Statusdescription); String jsonResult = g.toJson(expected); return jsonResult; } MessageDigest md = null; String saltedToken = referenceNumber + hashkey; md = MessageDigest.getInstance("SHA-512"); md.update(saltedToken.getBytes()); byte byteData[] = md.digest(); //convert the byte to hex format method 1 StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } System.out.println("Hex format : " + sb.toString()); String hash = sb.toString(); /*{ referenceNumber": "", "amount": "", "currency": "", "destinationBankUUID": "","destinationBankAccountNumber": "", "recipientPhoneNumber": ""} */ toPaga.put("referenceNumber", referenceNumber); //toVitesse.put("source","IMPALAPAY"); System.out.println(toPaga.toString()); //assign the remit url from properties.config CLIENT_URL = remiturlss; //principal = "" , credentials = "", hash = "" PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials, hash); //capture the switch respoinse. responseobject = PostWithIgnoreSSLPaga.doPost(); System.out.println(responseobject); //pass the returned json string JsonElement roots = new JsonParser().parse(responseobject); //exctract a specific json element from the object(status_code) //exctract a specific json element from the object(status_code) int switchresponse = roots.getAsJsonObject().get("responseCode").getAsInt(); expected.put("am_referenceid", ""); expected.put("am_timestamp", ""); expected.put("status_code", switchresponse + ""); expected.put("banks", responseobject.toString()); ; String jsonResult = g.toJson(expected); return jsonResult; }
From source file:com.impala.paga.all.QueryMobileOperators.java
/** * // ww w .ja v a2s.co m * @param request * @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 = ""; Properties prop = new Properties(); String hashkey = prop.getProperty("hashkey"); String principal = prop.getProperty("principal"); String credentials = prop.getProperty("credentials"); String remiturlss = ""; // String hashkey ="372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66"; // String principal="02A10715-0E53-4A8C-982E-2B7BFC7CF550"; // String credentials ="QE3@u=jd*2b+"; // These represent parameters received over the network String referenceNumber = ""; // 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 root = new JsonParser().parse(join); remiturlss = root.getAsJsonObject().get("remiturlss").getAsString(); referenceNumber = root.getAsJsonObject().get("referenceNumber").getAsString(); } catch (Exception e) { expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS"); String jsonResult = g.toJson(expected); System.out.println(e); return jsonResult; } /*String referenceNumber = "", amount = "",currency="",destinationBankUUID="", destinationBankAccountNumber= "", recipientPhoneNumber = "" , credentials = "";*/ // check for the presence of all required parameters if (StringUtils.isBlank(referenceNumber)) { expected.put("am_referenceid", referenceNumber); expected.put("am_timestamp", "tombwa"); expected.put("status_code", statuscode); expected.put("status_description", Statusdescription); String jsonResult = g.toJson(expected); return jsonResult; } MessageDigest md = null; String saltedToken = referenceNumber + hashkey; md = MessageDigest.getInstance("SHA-512"); md.update(saltedToken.getBytes()); byte byteData[] = md.digest(); //convert the byte to hex format method 1 StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } System.out.println("Hex format : " + sb.toString()); String hash = sb.toString(); /*{ referenceNumber": "", "amount": "", "currency": "", "destinationBankUUID": "","destinationBankAccountNumber": "", "recipientPhoneNumber": ""} */ toPaga.put("referenceNumber", referenceNumber); //toVitesse.put("source","IMPALAPAY"); System.out.println(toPaga.toString()); //assign the remit url from properties.config CLIENT_URL = remiturlss; //principal = "" , credentials = "", hash = "" PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials, hash); //capture the switch respoinse. responseobject = PostWithIgnoreSSLPaga.doPost(); System.out.println(responseobject); //pass the returned json string JsonElement roots = new JsonParser().parse(responseobject); //exctract a specific json element from the object(status_code) int switchresponse = roots.getAsJsonObject().get("responseCode").getAsInt(); //exctract a specific json element from the object(status_code) String statusdescription = roots.getAsJsonObject().get("message").getAsString(); expected.put("am_referenceid", ""); expected.put("am_timestamp", ""); expected.put("status_code", switchresponse + ""); expected.put("status_description", statusdescription); String jsonResult = g.toJson(expected); return jsonResult; }
From source file:org.jitsi.videobridge.rest.HandlerImpl.java
private void doPostShutdownJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { Videobridge videobridge = getVideobridge(); if (videobridge == null) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;/*w w w . ja va 2s. c o m*/ } if (!RESTUtil.isJSONContentType(request.getContentType())) { response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); return; } Object requestJSONObject; int status; try { requestJSONObject = new JSONParser().parse(request.getReader()); if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } } catch (ParseException pe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } ShutdownIQ requestShutdownIQ = JSONDeserializer.deserializeShutdownIQ((JSONObject) requestJSONObject); if ((requestShutdownIQ == null)) { status = HttpServletResponse.SC_BAD_REQUEST; } else { // Fill source address String ipAddress = request.getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } requestShutdownIQ.setFrom(ipAddress); try { IQ responseIQ = videobridge.handleShutdownIQ(requestShutdownIQ); if (IQ.Type.RESULT.equals(responseIQ.getType())) { status = HttpServletResponse.SC_OK; } else { status = getHttpStatusCodeForResultIq(responseIQ); } } catch (Exception e) { logger.error("Error while trying to handle shutdown request", e); status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } response.setStatus(status); }
From source file:com.easyjf.web.core.FrameworkEngine.java
/** * ?requestform/*from www. jav a 2 s . c o m*/ * * @param request * @param formName * @return ??Form */ public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) { Map textElement = new HashMap(); Map fileElement = new HashMap(); String contentType = request.getContentType(); String reMethod = request.getMethod(); if ((contentType != null) && (contentType.startsWith("multipart/form-data")) && (reMethod.equalsIgnoreCase("post"))) { // multipart/form-data File file = new File(request.getSession().getServletContext().getRealPath("/temp")); if (!file.exists()) { file.getParentFile().mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(webConfig.getUploadSizeThreshold()); factory.setRepository(file); ServletFileUpload sf = new ServletFileUpload(factory); sf.setSizeMax(webConfig.getMaxUploadFileSize()); sf.setHeaderEncoding(request.getCharacterEncoding()); List reqPars = null; try { reqPars = sf.parseRequest(request); for (int i = 0; i < reqPars.size(); i++) { FileItem it = (FileItem) reqPars.get(i); if (it.isFormField()) { textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ?? } else { fileElement.put(it.getFieldName(), it);// ??? } } } catch (Exception e) { logger.error(e); } } else if ((contentType != null) && contentType.equals("text/xml")) { StringBuffer buffer = new StringBuffer(); try { String s = request.getReader().readLine(); while (s != null) { buffer.append(s + "\n"); s = request.getReader().readLine(); } } catch (Exception e) { logger.error(e); } textElement.put("xml", buffer.toString()); } else { textElement = request2map(request); } // logger.debug("????"); WebForm wf = findForm(formName); wf.setValidate(module.isValidate());// ?validate?Form if (wf != null) { wf.setFileElement(fileElement); wf.setTextElement(textElement); } return wf; }
From source file:org.apache.struts2.json.JSONInterceptor.java
@SuppressWarnings("unchecked") public String intercept(ActionInvocation invocation) throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String requestContentType = readContentType(request); String requestContentTypeEncoding = readContentTypeEncoding(request); Object rootObject = null;// w w w . jav a 2s. co m final ValueStack stack = invocation.getStack(); if (this.root != null) { rootObject = stack.findValue(this.root); if (rootObject == null) { throw new RuntimeException("Invalid root expression: '" + this.root + "'."); } } if (jsonContentType.equalsIgnoreCase(requestContentType)) { // load JSON object Object obj = JSONUtil.deserialize(request.getReader()); // JSON array (this.root cannot be null in this case) if (obj instanceof List && this.root != null) { String mapKey = this.root; rootObject = null; if (this.root.indexOf('.') != -1) { mapKey = this.root.substring(this.root.lastIndexOf('.') + 1); rootObject = stack.findValue(this.root.substring(0, this.root.lastIndexOf('.'))); if (rootObject == null) { throw new RuntimeException("JSON array: Invalid root expression: '" + this.root + "'."); } } // create a map with a list inside Map m = new HashMap(); m.put(mapKey, new ArrayList((List) obj)); obj = m; } if (obj instanceof Map) { Map json = (Map) obj; // clean up the values if (dataCleaner != null) dataCleaner.clean("", json); if (rootObject == null) // model overrides action rootObject = invocation.getStack().peek(); // populate fields populator.populateObject(rootObject, json); } else { LOG.error("Unable to deserialize JSON object from request"); throw new JSONException("Unable to deserialize JSON object from request"); } } else if (jsonRpcContentType.equalsIgnoreCase(requestContentType)) { Object result; if (this.enableSMD) { // load JSON object Object obj = JSONUtil.deserialize(request.getReader()); if (obj instanceof Map) { Map smd = (Map) obj; if (rootObject == null) { // model makes no sense when using RPC rootObject = invocation.getAction(); } // invoke method try { result = this.invoke(rootObject, smd); } catch (Exception e) { RPCResponse rpcResponse = new RPCResponse(); rpcResponse.setId(smd.get("id").toString()); rpcResponse.setError(new RPCError(e, RPCErrorCode.EXCEPTION, getDebug())); result = rpcResponse; } } else { String message = "SMD request was not in the right format. See http://json-rpc.org"; RPCResponse rpcResponse = new RPCResponse(); rpcResponse.setError(new RPCError(message, RPCErrorCode.INVALID_PROCEDURE_CALL)); result = rpcResponse; } } else { String message = "Request with content type of 'application/json-rpc' was received but SMD is " + "not enabled for this interceptor. Set 'enableSMD' to true to enable it"; RPCResponse rpcResponse = new RPCResponse(); rpcResponse.setError(new RPCError(message, RPCErrorCode.SMD_DISABLED)); result = rpcResponse; } String json = JSONUtil.serialize(result, excludeProperties, getIncludeProperties(), ignoreHierarchy, excludeNullProperties); json = addCallbackIfApplicable(request, json); boolean writeGzip = enableGZIP && JSONUtil.isGzipInRequest(request); JSONUtil.writeJSONToResponse(new SerializationParams(response, requestContentTypeEncoding, this.wrapWithComments, json, true, writeGzip, noCache, -1, -1, prefix, "application/json")); return Action.NONE; } else { LOG.debug("Accept header parameter must be '{}' or '{}'. Ignoring request with Content Type '{}'", jsonContentType, jsonRpcContentType, requestContentType); } return invocation.invoke(); }
From source file:org.openhab.io.neeo.internal.servletservices.NeeoBrainService.java
/** * Handle a directory request/*w w w .j av a 2 s .com*/ * * @param req the non-null request to use * @param resp the non-null response to write to * @param pathInfo the non-null path information * @throws IOException Signals that an I/O exception has occurred. */ private void handleDirectory(HttpServletRequest req, HttpServletResponse resp, PathInfo pathInfo) throws IOException { Objects.requireNonNull(req, "req cannot be null"); Objects.requireNonNull(resp, "resp cannot be null"); Objects.requireNonNull(pathInfo, "pathInfo cannot be null"); logger.debug("handleDirectory {}", pathInfo); final NeeoDevice device = context.getDefinitions().getDevice(pathInfo.getThingUid()); if (device != null) { final NeeoDeviceChannel channel = device.getChannel(pathInfo.getItemName(), pathInfo.getSubType(), pathInfo.getChannelNbr()); if (StringUtils.equalsIgnoreCase("action", pathInfo.getActionValue())) { final NeeoDirectoryRequestAction discoveryAction = gson.fromJson(req.getReader(), NeeoDirectoryRequestAction.class); try { final Item item = context.getItemRegistry().getItem(pathInfo.getItemName()); final Command cmd = NeeoItemValueConverter.convert(item, pathInfo, discoveryAction.getActionIdentifier()); if (cmd != null) { final ItemCommandEvent event = ItemEventFactory.createCommandEvent(item.getName(), cmd); logger.debug("Posting item event: {}", event); context.getEventPublisher().post(event); } else { logger.debug("Cannot set value (directory) - no command for path: {}", pathInfo); } } catch (ItemNotFoundException e) { logger.debug("Cannot set value(directory) - no linked items: {}", pathInfo); } } else { if (channel instanceof NeeoDeviceChannelDirectory) { final NeeoDirectoryRequest discoveryRequest = gson.fromJson(req.getReader(), NeeoDirectoryRequest.class); final NeeoDeviceChannelDirectory directoryChannel = (NeeoDeviceChannelDirectory) channel; NeeoUtil.write(resp, gson.toJson(new NeeoDirectoryResult(discoveryRequest, directoryChannel))); } else { logger.debug("Channel definition for '{}' not found to directory set value ({})", pathInfo.getItemName(), pathInfo); } } } else { logger.debug("Device definition for '{}' not found to directory set value ({})", pathInfo.getItemName(), pathInfo); } }