List of usage examples for javax.servlet.http HttpServletRequest getReader
public BufferedReader getReader() throws IOException;
BufferedReader
. From source file:servlets.User_servlets.java
private void user_sign_up_handler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w. j av a 2 s.c om*/ DAO dao_instance = null; User user = null; boolean ROLLBACK_NEEDED = false; String error = ""; try { /** * ******************************************************* * STEP 1 Check if the user exists in the DB. IF ERROR --> * throws MySQL exception, GO TO STEP 2b throws * NoSuchAlgorithmException, GO TO STEP 2b ELSE --> GO TO STEP 2 * ******************************************************* */ JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); String email = requestData.get("email").getAsString(); String user_id = requestData.get("user_id").getAsString(); String password = requestData.get("password").getAsString(); password = SHA1.getHash(password); dao_instance = DAOProvider.getDAOByName("User"); Object[] params = { null, false, true }; user = (User) ((User_JDBCDAO) dao_instance).findByID(email, params); if (user != null) { throw new AccessControlException("Email already registered."); } user = (User) ((User_JDBCDAO) dao_instance).findByID(user_id, null); if (user != null) { throw new AccessControlException( "There is another user with that name. Try with another name."); } /** * ******************************************************* * STEP 2 Create the new user instance. * ******************************************************* */ user = new User(user_id, email); user.setPassword(password); user.setRandomAPICode(); /** * ******************************************************* * STEP 3 INSERT IN DATABASE. IF ERROR --> throws exception if * not valid session, GO TO STEP 4b ELSE --> GO TO STEP 4 * ******************************************************* */ dao_instance = DAOProvider.getDAOByName("User"); dao_instance.disableAutocommit(); ROLLBACK_NEEDED = true; dao_instance.insert(user); /** * ******************************************************* * STEP 4 COMMIT CHANGES IN DB. IF ERROR --> throws exception if * not valid session, GO TO STEP 4b ELSE --> GO TO STEP 5 * ******************************************************* */ dao_instance.doCommit(); } catch (AccessControlException e) { error = e.getMessage(); } catch (Exception e) { ServerErrorManager.handleException(e, User_servlets.class.getName(), "userLoginPostHandler", e.getMessage()); } finally { /** * ******************************************************* * STEP 3b CATCH ERROR. GO TO STEP 4 * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { dao_instance.doRollback(); } } else { /** * ******************************************************* * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4 * ******************************************************* */ if (error.length() > 0) { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(false)); obj.add("reason", new JsonPrimitive(error)); response.getWriter().print(obj.toString()); } else { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(true)); response.getWriter().print(obj.toString()); } } /** * ******************************************************* * STEP 4 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, User_servlets.class.getName(), "userSignUpPostHandler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:org.dtls.fairifier.PostFairDataToFairDataPoint.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { f = SimpleValueFactory.getInstance(); ArrayList<IRI> datasetThemes = new ArrayList<IRI>(); ArrayList<IRI> catalogThemes = new ArrayList<IRI>(); String uuid_catalog = UUID.randomUUID().toString(); String uuid_dataset = UUID.randomUUID().toString(); String uuid_distribution = UUID.randomUUID().toString(); ArrayList<Literal> keyWords = new ArrayList<Literal>(); Identifier identifier = new Identifier(); Agent agent = new Agent(); Date date = new Date(); String catalogString = null;/* w w w.j a va 2s.c o m*/ String datasetString = null; String distributionString = null; Resource r = null; CatalogMetadata catalogMetadata = new CatalogMetadata(); DatasetMetadata datasetMetadata = new DatasetMetadata(); DistributionMetadata distributionMetadata = new DistributionMetadata(); try { StringBuffer jb = new StringBuffer(); String line = null; BufferedReader reader = req.getReader(); while ((line = reader.readLine()) != null) jb.append(line); JSONObject fdp = new JSONObject(jb.toString()).getJSONObject("metadata"); JSONObject catalog = fdp.getJSONObject("catalog"); JSONObject dataset = fdp.getJSONObject("dataset"); JSONObject distribution = fdp.getJSONObject("distribution"); JSONObject uploadConfiguration = fdp.getJSONObject("uploadConfiguration"); if (!catalog.getBoolean("_exists")) { // optional try { catalogMetadata .setHomepage(f.createIRI(catalog.getString("http://xmlns.com/foaf/0.1/homepage"))); } catch (Exception ex) { } catalogThemes.add(f.createIRI(catalog.getString("http://www.w3.org/ns/dcat#themeTaxonomy"))); catalogMetadata.setThemeTaxonomys(catalogThemes); catalogMetadata.setTitle(f.createLiteral(catalog.getString("http://purl.org/dc/terms/title"))); identifier.setIdentifier(f.createLiteral(fdp.getString("baseUri") + "/catalog/" + catalog.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + catalog.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_catalog + "/identifier")); identifier.setUri(f.createIRI(fdp.getString("baseUri") + "/catalog/" + catalog.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + catalog.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_catalog + "/identifier")); catalogMetadata.setIdentifier(identifier); agent.setUri(f.createIRI(fdp.getString("baseUri"))); agent.setName(f.createLiteral( catalog.getJSONObject("http://purl.org/dc/terms/publisher").getString("url"))); catalogMetadata.setPublisher(agent); try { catalogMetadata.setRights(f.createIRI(catalog.getString("http://purl.org/dc/terms/rights"))); } catch (Exception ex) { } catalogMetadata .setVersion(f.createLiteral(catalog.getString("http://purl.org/dc/terms/hasVersion"))); catalogMetadata.setUri(f.createIRI(fdp.getString("baseUri"))); catalogMetadata.setIssued(f.createLiteral(date)); catalogMetadata.setModified(f.createLiteral(date)); catalogString = MetadataUtils.getString(catalogMetadata, RDFFormat.TURTLE) .replaceAll("\\<" + catalogMetadata.getUri() + "\\>", "<>"); } if (!dataset.getBoolean("_exists")) { // optional try { datasetMetadata.setLandingPage( f.createIRI(dataset.getString("http://www.w3.org/ns/dcat#landingPage"))); } catch (Exception ex) { } for (int i = 0; i < dataset.getJSONArray("http://www.w3.org/ns/dcat#theme").length(); i++) { datasetThemes .add(f.createIRI(dataset.getJSONArray("http://www.w3.org/ns/dcat#theme").getString(i))); } datasetMetadata.setThemes(datasetThemes); // optional try { for (int i = 0; i < dataset.getJSONArray("http://www.w3.org/ns/dcat#keyword").length(); i++) { keyWords.add(f.createLiteral( dataset.getJSONArray("http://www.w3.org/ns/dcat#keyword").getString(i))); } datasetMetadata.setKeywords(keyWords); } catch (Exception ex) { } //optional try { datasetMetadata.setContactPoint( f.createIRI(dataset.getString("http://www.w3.org/ns/dcat#contactPoint"))); } catch (Exception ex) { } datasetMetadata.setTitle(f.createLiteral(dataset.getString("http://purl.org/dc/terms/title"))); identifier = new Identifier(); identifier.setIdentifier(f.createLiteral(fdp.getString("baseUri") + "/dataset/" + dataset.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + dataset.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_dataset + "/identifier")); identifier.setUri(f.createIRI(fdp.getString("baseUri") + "/dataset/" + dataset.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + dataset.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_dataset + "/identifier")); datasetMetadata.setIdentifier(identifier); datasetMetadata.setIssued(f.createLiteral(date)); datasetMetadata.setModified(f.createLiteral(date)); datasetMetadata .setVersion(f.createLiteral(dataset.getString("http://purl.org/dc/terms/hasVersion"))); try { datasetMetadata.setLanguage( f.createIRI(dataset.getJSONArray("http://purl.org/dc/terms/language").getString(0))); } catch (Exception ex) { } try { datasetMetadata.setRights(f.createIRI(dataset.getString("http://purl.org/dc/terms/rights"))); } catch (Exception ex) { } // optional try { datasetMetadata.setDescription( f.createLiteral(dataset.getString("http://purl.org/dc/terms/description"))); } catch (Exception ex) { } datasetMetadata.setParentURI(f.createIRI(fdp.getString("baseUri") + "/catalog/" + catalog.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + catalog.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_catalog)); agent = new Agent(); agent.setUri(f.createIRI(fdp.getString("baseUri") + "/datasetAgent/" + dataset.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + dataset.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_"))); agent.setName(f.createLiteral( dataset.getJSONObject("http://purl.org/dc/terms/publisher").getString("url"))); datasetMetadata.setPublisher(agent); datasetMetadata.setUri(f.createIRI("http://base/catalog/dataset")); datasetString = MetadataUtils.getString(datasetMetadata, RDFFormat.TURTLE) .replaceAll("\\<" + datasetMetadata.getUri() + "\\>", "<>"); } if (fdp.getString("uploadtype").equals("ftp")) { distributionMetadata.setAccessURL(f.createIRI("ftp://" + uploadConfiguration.getString("host") + uploadConfiguration.getString("directory") + "FAIRdistribution_" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + ".ttl")); // optional try { distributionMetadata.setMediaType(f.createLiteral("text/turtle")); } catch (Exception ex) { } distributionMetadata.setByteSize(f.createLiteral(datasetString.getBytes("UTF-8").length)); } else if (fdp.getString("uploadtype").equals("virtuoso")) { try { distributionMetadata.setMediaType(f.createLiteral("text/turtle")); } catch (Exception ex) { } distributionMetadata.setAccessURL(f.createIRI("http://" + uploadConfiguration.getString("host") + uploadConfiguration.getString("directory") + "FAIRdistribution_" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + ".ttl")); } distributionMetadata .setTitle(f.createLiteral(distribution.getString("http://purl.org/dc/terms/title"))); distributionMetadata.setParentURI(f.createIRI(fdp.getString("baseUri") + "/dataset/" + dataset.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + dataset.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_dataset)); identifier = new Identifier(); identifier.setIdentifier(f.createLiteral(fdp.getString("baseUri") + "/distribution/" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_distribution + "/identifier")); identifier.setUri(f.createIRI(fdp.getString("baseUri") + "/distribution/" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_distribution + "/identifier")); distributionMetadata.setIdentifier(identifier); distributionMetadata .setVersion(f.createLiteral(distribution.getString("http://purl.org/dc/terms/hasVersion"))); // optional try { distributionMetadata .setLicense(f.createIRI(distribution.getString("http://purl.org/dc/terms/license"))); } catch (Exception ex) { } distributionMetadata.setUri(f.createIRI("http://base/catalog/dataset/distribution")); distributionMetadata.setIssued(f.createLiteral(date)); distributionMetadata.setModified(f.createLiteral(date)); // optional try { distributionMetadata.setDescription( f.createLiteral(distribution.getString("http://purl.org/dc/terms/description"))); } catch (Exception ex) { } distributionString = MetadataUtils.getString(distributionMetadata, RDFFormat.TURTLE) .replaceAll("\\<" + distributionMetadata.getUri() + "\\>", "<>"); // // System.out.println(catalogString); // System.out.println(datasetString); // System.out.println(distributionString); String catalogPost = null; String datasetPost = null; if (!catalog.getBoolean("_exists")) { catalogPost = IOUtils.toString(HttpUtils.post(fdp.getString("baseUri") + "/catalog?id=" + catalog.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + catalog.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_catalog, catalogString, "text/turtle").getContent(), "UTF-8"); } if (!dataset.getBoolean("_exists")) { datasetPost = IOUtils.toString(HttpUtils.post(fdp.getString("baseUri") + "/dataset?id=" + dataset.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + dataset.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_dataset, datasetString, "text/turtle").getContent(), "UTF-8"); } String distributionPost = IOUtils .toString(HttpUtils .post(fdp.getString("baseUri") + "/distribution?id=" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + "_" + uuid_distribution, distributionString, "text/turtle") .getContent(), "UTF-8"); String data = new JSONObject(jb.toString()).getString("data"); PushFairDataToResourceAdapter adapter = new PushFairDataToResourceAdapter(); if (fdp.getString("uploadtype").equals("ftp")) { r = new FtpResource(uploadConfiguration.getString("host"), uploadConfiguration.getString("username"), uploadConfiguration.getString("password"), uploadConfiguration.getString("directory"), "FAIRdistribution_" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + ".ttl"); } else if (fdp.getString("uploadtype").equals("virtuoso")) { r = new VirtuosoResource(uploadConfiguration.getString("host"), "FAIRdistribution_" + distribution.getString("http://purl.org/dc/terms/title").replace(" ", "_") + "_" + distribution.getString("http://purl.org/dc/terms/hasVersion").replace(" ", "_") + ".ttl", uploadConfiguration.getString("username"), uploadConfiguration.getString("password"), uploadConfiguration.getString("directory")); } r.setFairData(data); adapter.setResource(r); adapter.push(); res.setCharacterEncoding("UTF-8"); res.setHeader("Content-Type", "application/json"); JSONWriter writer = new JSONWriter(res.getWriter()); writer.object(); writer.key("code"); writer.value("ok"); if (!catalog.getBoolean("_exists")) { writer.key("catalogPost"); writer.value(catalogPost); } if (!dataset.getBoolean("_exists")) { writer.key("datasetPost"); writer.value(datasetPost); } writer.key("distributionPost"); writer.value(distributionPost); writer.endObject(); } catch (Exception ex) { respondException(res, ex); } }
From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param sr The servlet request. Must not be * {@code null}./*w w w . j a v a 2s . c o m*/ * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(sr); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(sr.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = sr.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, sr.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(sr.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = sr.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = sr.getReader(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:info.magnolia.services.httputils.filters.InternalProxyFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String[] requestedUrl = request.getRequestURI().split("/", 4); if (!requestedUrl[1].equals(FILTER_CONTEXT)) throw new ServletException( "Requested url does not have the right context, please check the configuration of the filter."); if (StringUtils.isBlank(requestedUrl[2])) throw new ServletException("Service name is missing."); if (StringUtils.isBlank(requestedUrl[3])) throw new ServletException("No resources specified in the url"); // calculate internal url String service = requestedUrl[2]; String resource = requestedUrl[3]; WebTarget target = null;/* www. j ava 2 s . c o m*/ //this.client.target("http://192.168.99.100:3004/").path(resource); // add query string String queryString = request.getQueryString(); if (StringUtils.isNotBlank(queryString)) target = target.path(queryString); // set content type String contentType = request.getContentType(); Invocation.Builder requestBuilder; if (StringUtils.isNotBlank(contentType)) requestBuilder = target.request(contentType); else requestBuilder = target.request(); // copy the original request body to the internal one StringBuilder internalBodyReq = new StringBuilder(); BufferedReader reader = request.getReader(); try { String line; while ((line = reader.readLine()) != null) { internalBodyReq.append(line); } } finally { reader.close(); } Response internalResp = null; // actually do the call based on the method String method = request.getMethod(); switch (method) { case "GET": internalResp = requestBuilder.get(); break; case "POST": internalResp = requestBuilder.post(Entity.entity(internalBodyReq, contentType)); break; case "PUT": internalResp = requestBuilder.put(Entity.entity(internalBodyReq, contentType)); break; case "DELETE": internalResp = requestBuilder.delete(); break; default: log.error("HTTP method not supported: " + method); break; } response.setStatus(internalResp.getStatus()); response.setContentType(internalResp.getMediaType().toString()); response.getOutputStream().print(internalResp.readEntity(String.class)); }
From source file:pa_SymposiumPlanner.ECAI2012ProgramChair.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w. j av a2 s . c om*/ address = PAConfiguration.getAddress(); port = PAConfiguration.getPort(instantiation); poslAddress = PAConfiguration.getPOSL(instantiation, topic); rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation); messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic); } catch (BadConfigurationException e) { System.out.println(e.getMessage()); e.printStackTrace(); System.exit(0); } response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { System.out.println("Programming Chair Servlet"); System.out.println(response.toString()); BufferedReader brd = request.getReader(); String input = ""; String message = ""; while (!input.equals("</RuleML>")) { input = brd.readLine(); message = message + input; } String[] varOrder = getVariableOrder(message); System.out.println("Received Message: " + message); POSLParser pp = new POSLParser(); // String contents = "c(a).\nc(b).\nc(c)."; Date t1 = new GregorianCalendar().getTime(); System.out.println(t1.getHours() + ":" + t1.getMinutes()); // append time to contents System.out.println("day: " + t1.getDay()); System.out.println("day: " + t1.getYear()); System.out.println("day: " + t1.getMonth()); // time String time = "time(" + t1.getHours() + ":integer)."; System.out.println(time); String url = poslAddress; // String url = "http://www.jdrew.org/oojdrew/test.posl"; String contents = ""; // day of the week int day = t1.getDay(); boolean weekday = true; if (day == 0 || day == 6) { weekday = false; } String dayOfWeek; if (weekday) { dayOfWeek = "day(weekday)."; } else { dayOfWeek = "day(weekend)."; } // full date Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day2 = cal.get(Calendar.DAY_OF_MONTH); String date; String day3 = "" + day2; if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8 || day2 == 9) { day3 = "0" + day2; } if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3; else date = "" + year + "0" + month + day3; date = "date(" + date + ":integer)."; System.out.println(date); String url2 = rdfAddress; HttpClient client2 = new HttpClient(); GetMethod method2 = new GetMethod(url2); method2.setFollowRedirects(true); String typestr = ""; // Execute the GET method int statusCode2 = client2.executeMethod(method2); if (statusCode2 != -1) { typestr = method2.getResponseBodyAsString(); } System.out.println("Types: " + typestr); Types.reset(); RDFSParser.parseRDFSString(typestr); try { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method.setFollowRedirects(true); // Execute the GET method int statusCode = client.executeMethod(method); if (statusCode != -1) { contents = method.getResponseBodyAsString(); } } catch (Exception e) { e.printStackTrace(); } contents = contents + "\n" + time; contents = contents + "\n" + dayOfWeek; contents = contents + "\n" + date; BackwardReasoner br = new BackwardReasoner(); Iterator solit = null; DefiniteClause dc = null; SymbolTable.reset(); pp.parseDefiniteClauses(contents); br.loadClauses(pp.iterator()); Iterator it = pp.iterator(); while (it.hasNext()) { DefiniteClause d = (DefiniteClause) it.next(); System.out.println("Loaded clause: " + d.toPOSLString()); } br = new BackwardReasoner(br.clauses, br.oids); MessageParser m = new MessageParser(message); Element atom = null; try { atom = m.parseForContent(); } catch (Exception e) { System.out.println("Invalid Message"); // out.flush(); } QueryBuilder q = new QueryBuilder(atom); String query = q.generateDoc(); System.out.println("ABOUT TO INPUT THIS QUERY:" + query); RuleMLParser qp = new RuleMLParser(); try { dc = qp.parseRuleMLQuery(query); } catch (Exception e) { System.out.println("Invalid Query"); // out.flush(); } // solit = br.iterativeDepthFirstSolutionIterator(dc); solit = br.iterativeDepthFirstSolutionIterator(dc); int varSize = 0; while (solit.hasNext()) { Vector data = new Vector(); BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next(); Hashtable varbind = gl.varBindings; javax.swing.tree.DefaultMutableTreeNode root = br.toTree(); root.setAllowsChildren(true); javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root); int i = 0; Object[][] rowdata = new Object[varbind.size()][2]; varSize = varbind.size(); Enumeration e = varbind.keys(); while (e.hasMoreElements()) { Object k = e.nextElement(); Object val = varbind.get(k); String ks = (String) k; rowdata[i][0] = ks; rowdata[i][1] = val; i++; } data.addElement(rowdata); String[] messages = new String[data.size()]; MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder); messages = g.Messages2(); String appender = ""; URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); for (int i1 = 0; i1 < data.size(); i1++) { System.out.println(i1 + ")" + messages[i1].toString()); props.put("text", messages[i1].toString()); InputStream in = msg.sendGetMessage(props); } System.out.println("NEXT MESSAGE"); } MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel()); URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); String finalMessage = g.finalMessage(query); System.out.println(finalMessage); props.put("text", finalMessage); InputStream in = msg.sendGetMessage(props); System.out.println("Stop_Communication"); } catch (Exception e) { System.out.println("ERROR has occured : " + e.toString()); } out.close(); }
From source file:pa_SymposiumPlanner.RuleML2008ChallengeChair.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w ww. j a v a 2s .c om*/ address = PAConfiguration.getAddress(); port = PAConfiguration.getPort(instantiation); poslAddress = PAConfiguration.getPOSL(instantiation, topic); rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation); messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic); } catch (BadConfigurationException e) { System.out.println(e.getMessage()); e.printStackTrace(); System.exit(0); } response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { System.out.println("5 Publicty Chair Servlet"); System.out.println(response.toString()); BufferedReader brd = request.getReader(); String input = ""; String message = ""; while (!input.equals("</RuleML>")) { input = brd.readLine(); message = message + input; } String[] varOrder = getVariableOrder(message); System.out.println("Received Message: " + message); // BackwardReasoner br = new BackwardReasoner(); // Iterator solit =null; // DefiniteClause dc = null; // SymbolTable.reset(); POSLParser pp = new POSLParser(); // String contents = "c(a).\nc(b).\nc(c)."; Date t1 = new GregorianCalendar().getTime(); System.out.println(t1.getHours() + ":" + t1.getMinutes()); // append time to contents System.out.println("day: " + t1.getDay()); System.out.println("day: " + t1.getYear()); System.out.println("day: " + t1.getMonth()); // time String time = "time(" + t1.getHours() + ":integer)."; System.out.println(time); String url = poslAddress; // String url = "http://www.jdrew.org/oojdrew/test.posl"; String contents = ""; // day of the week int day = t1.getDay(); boolean weekday = true; if (day == 0 || day == 6) { weekday = false; } String dayOfWeek; if (weekday) { dayOfWeek = "day(weekday)."; } else { dayOfWeek = "day(weekend)."; } // full date Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day2 = cal.get(Calendar.DAY_OF_MONTH); String date; String day3 = "" + day2; if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8 || day2 == 9) { day3 = "0" + day2; } if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3; else date = "" + year + "0" + month + day3; date = "date(" + date + ":integer)."; System.out.println(date); String url2 = rdfAddress; HttpClient client2 = new HttpClient(); GetMethod method2 = new GetMethod(url2); method2.setFollowRedirects(true); String typestr = ""; // Execute the GET method int statusCode2 = client2.executeMethod(method2); if (statusCode2 != -1) { typestr = method2.getResponseBodyAsString(); } System.out.println("Types: " + typestr); Types.reset(); RDFSParser.parseRDFSString(typestr); try { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method.setFollowRedirects(true); // Execute the GET method int statusCode = client.executeMethod(method); if (statusCode != -1) { contents = method.getResponseBodyAsString(); } } catch (Exception e) { e.printStackTrace(); } contents = contents + "\n" + time; contents = contents + "\n" + dayOfWeek; contents = contents + "\n" + date; BackwardReasoner br = new BackwardReasoner(); Iterator solit = null; DefiniteClause dc = null; SymbolTable.reset(); pp.parseDefiniteClauses(contents); br.loadClauses(pp.iterator()); System.out.println("TEST"); Iterator it = pp.iterator(); while (it.hasNext()) { DefiniteClause d = (DefiniteClause) it.next(); System.out.println("Loaded clause: " + d.toPOSLString()); } br = new BackwardReasoner(br.clauses, br.oids); MessageParser m = new MessageParser(message); Element atom = null; try { atom = m.parseForContent(); } catch (Exception e) { System.out.println("Invalid Message"); // out.flush(); } QueryBuilder q = new QueryBuilder(atom); String query = q.generateDoc(); System.out.println("ABOUT TO INPUT THIS QUERY:" + query); RuleMLParser qp = new RuleMLParser(); try { dc = qp.parseRuleMLQuery(query); } catch (Exception e) { System.out.println("Invalid Query"); // out.flush(); } // solit = br.iterativeDepthFirstSolutionIterator(dc); solit = br.iterativeDepthFirstSolutionIterator(dc); int varSize = 0; while (solit.hasNext()) { Vector data = new Vector(); BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next(); Hashtable varbind = gl.varBindings; javax.swing.tree.DefaultMutableTreeNode root = br.toTree(); root.setAllowsChildren(true); javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root); int i = 0; Object[][] rowdata = new Object[varbind.size()][2]; varSize = varbind.size(); Enumeration e = varbind.keys(); while (e.hasMoreElements()) { Object k = e.nextElement(); Object val = varbind.get(k); String ks = (String) k; rowdata[i][0] = ks; rowdata[i][1] = val; i++; } data.addElement(rowdata); String[] messages = new String[data.size()]; MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder); messages = g.Messages2(); String appender = ""; URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); for (int i1 = 0; i1 < data.size(); i1++) { System.out.println(i1 + ")" + messages[i1].toString()); props.put("text", messages[i1].toString()); InputStream in = msg.sendGetMessage(props); } System.out.println("NEXT MESSAGE"); } MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel()); URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); String finalMessage = g.finalMessage(query); System.out.println(finalMessage); props.put("text", finalMessage); InputStream in = msg.sendGetMessage(props); System.out.println("Stop_Communication"); } catch (Exception e) { System.out.println("ERROR has occured : " + e.toString()); } out.close(); }
From source file:com.impala.paga.all.RouteRemit.java
/** * /*from w w w . j ava 2s . c o m*/ * @param request * @return * @throws IOException */ private String moneytransfer(HttpServletRequest request) throws IOException, JSONException, NoSuchAlgorithmException { // joined json string Account account = null; String join = ""; JsonElement root = null, roots = null; JsonObject root2 = null, creditrequest = null; 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+"; String apiusername = "", apipassword = "", username = "", transactioinid = "", sourcecountrycode = "", recipientcurrencycode = "", recipientcountrycode = "", sourcemsisdn = "", recipientmobile = "", sendername = "", amountstring = "", remiturlss = "", responseobject = "", statuscode = "", statusdescription = "", 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); apiusername = root.getAsJsonObject().get("username").getAsString(); apipassword = root.getAsJsonObject().get("password").getAsString(); username = root.getAsJsonObject().get("sendingIMT").getAsString(); transactioinid = root.getAsJsonObject().get("transaction_id").getAsString(); sourcecountrycode = root.getAsJsonObject().get("sourcecountrycode").getAsString(); recipientcurrencycode = root.getAsJsonObject().get("recipientcurrencycode").getAsString(); recipientcountrycode = root.getAsJsonObject().get("recipientcountrycode").getAsString(); sendername = root.getAsJsonObject().get("Sender_Name").getAsString(); amountstring = root.getAsJsonObject().get("amount").getAsString(); remiturlss = root.getAsJsonObject().get("url").getAsString(); sourcemsisdn = root.getAsJsonObject().get("source_msisdn").getAsString(); recipientmobile = root.getAsJsonObject().get("beneficiary_msisdn").getAsString(); root2 = root.getAsJsonObject(); } catch (Exception e) { expected.put("command_status", APIConstants.COMMANDSTATUS_INVALID_PARAMETERS); String jsonResult = g.toJson(expected); return jsonResult; } // check for the presence of all required parameters if (StringUtils.isBlank(apiusername) || StringUtils.isBlank(apipassword) || StringUtils.isBlank(username) || StringUtils.isBlank(transactioinid) || StringUtils.isBlank(sourcecountrycode) || StringUtils.isBlank(recipientcurrencycode) || StringUtils.isBlank(sendername) || StringUtils.isBlank(amountstring) || StringUtils.isBlank(remiturlss) || StringUtils.isBlank(recipientcountrycode)) { expected.put("status_code", "server error"); expected.put("status_description", "missing parameters"); String jsonResult = g.toJson(expected); return jsonResult; } if (root2.has("vendor_uniquefields")) { } // Retrieve the account details Element element; if ((element = accountsCache.get(username)) != null) { account = (Account) element.getObjectValue(); } // Secure against strange servers making request(future upgrade should // lock on IP) if (account == null) { expected.put("status_code", "server error"); expected.put("status_description", "unauthorised user"); String jsonResult = g.toJson(expected); return jsonResult; } MessageDigest md = null; String saltedToken = transactioinid + amountstring + recipientmobile + 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(); int intamount = Integer.parseInt(amountstring); toPaga.put("referenceNumber", transactioinid); toPaga.put("amount", amountstring); toPaga.put("destinationAccount", recipientmobile); 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 roots1 = new JsonParser().parse(responseobject); int responseCode = roots1.getAsJsonObject().get("responseCode").getAsInt(); String switchresponse = Integer.toString(responseCode); //add String success = "S001"; if (responseCode == 0) { //exctract a specific json element from the object(status_code) statusdescription = roots1.getAsJsonObject().get("message").getAsString(); expected.put("am_referenceid", transactioinid); expected.put("am_timestamp", success); expected.put("status_code", "S001"); expected.put("status_description", statusdescription); String jsonResult = g.toJson(expected); return jsonResult; } expected.put("am_referenceid", ""); expected.put("am_timestamp", ""); expected.put("status_code", ""); expected.put("status_description", ""); String jsonResult = g.toJson(expected); return jsonResult; }
From source file:de.adorsys.oauth.server.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param servletRequest The servlet request. Must not be * {@code null}./*from w ww . ja v a 2s .c om*/ * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(servletRequest); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(servletRequest.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, servletRequest.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(servletRequest.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = servletRequest.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = servletRequest.getReader(); reader.reset(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.reset(); // reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:servlets.Analysis_servlets.java
private void get_analysis_handler(HttpServletRequest request, HttpServletResponse response) throws IOException { try {//from w w w . j a va2 s. c om DAO dao_instance = null; Analysis analysis = null; try { JsonParser parser = new JsonParser(); JsonObject requestData = (JsonObject) parser.parse(request.getReader()); String loggedUser = requestData.get("loggedUser").getAsString(); String sessionToken = requestData.get("sessionToken").getAsString(); /** * ******************************************************* * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF * ERROR --> throws exception if not valid session, GO TO STEP * 5b ELSE --> GO TO STEP 2 * ******************************************************* */ if (!checkAccessPermissions(loggedUser, sessionToken)) { throw new AccessControlException("Your session is invalid. User or session token not allowed."); } /** * ******************************************************* * STEP 2 Get THE ANALYSIS Object from DB. IF ERROR --> throws * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3 * ******************************************************* */ dao_instance = DAOProvider.getDAOByName("Analysis"); boolean loadRecursive = true; Object[] params = { loadRecursive }; String analysis_id = requestData.get("analysis_id").getAsString(); analysis = (Analysis) dao_instance.findByID(analysis_id, params); } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "get_analysis_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 3b CATCH ERROR. GO TO STEP 4 * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } else { /** * ******************************************************* * STEP 3A WRITE SUCCESS RESPONSE. GO TO STEP 4 * ******************************************************* */ response.getWriter().print(analysis.toJSON()); } /** * ******************************************************* * STEP 4 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "get_analysis_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }