List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java
public void getRawTextFromUrlIfNeeded(DocumentPojo doc, SourceRssConfigPojo feedConfig) throws IOException { if (null != doc.getFullText()) { // Nothing to do return;/*from ww w.j a v a 2s . c o m*/ } Scanner s = null; OutputStreamWriter wr = null; try { URL url = new URL(doc.getUrl()); URLConnection urlConnect = null; String postContent = null; if (null != feedConfig) { urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride())); if (null != feedConfig.getUserAgent()) { urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent()); } // TESTED (by hand) if (null != feedConfig.getHttpFields()) { for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) { if (httpFieldPair.getKey().equalsIgnoreCase("content")) { postContent = httpFieldPair.getValue(); urlConnect.setDoInput(true); urlConnect.setDoOutput(true); } else { urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue()); } } } //TESTED (by hand) } else { urlConnect = url.openConnection(); } InputStream urlStream = null; try { securityManager.setSecureFlag(true); // (disallow file/local URL access) if (null != postContent) { wr = new OutputStreamWriter(urlConnect.getOutputStream()); wr.write(postContent.toCharArray()); wr.flush(); } //TESTED urlStream = urlConnect.getInputStream(); } catch (SecurityException se) { throw se; } catch (Exception e) { // Try one more time, this time exception out all the way securityManager.setSecureFlag(false); // (some file stuff - so need to re-enable) if (null != feedConfig) { urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride())); if (null != feedConfig.getUserAgent()) { urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent()); } // TESTED if (null != feedConfig.getHttpFields()) { for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) { if (httpFieldPair.getKey().equalsIgnoreCase("content")) { urlConnect.setDoInput(true); // (need to do this again) urlConnect.setDoOutput(true); } else { urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue()); } } } //TESTED } else { urlConnect = url.openConnection(); } securityManager.setSecureFlag(true); // (disallow file/local URL access) if (null != postContent) { wr = new OutputStreamWriter(urlConnect.getOutputStream()); wr.write(postContent.toCharArray()); wr.flush(); } //TESTED urlStream = urlConnect.getInputStream(); } finally { securityManager.setSecureFlag(false); // (turn security check for local URL/file access off) } // Grab any interesting header fields Map<String, List<String>> headers = urlConnect.getHeaderFields(); BasicDBObject metadataHeaderObj = null; for (Map.Entry<String, List<String>> it : headers.entrySet()) { if (null != it.getKey()) { if (it.getKey().startsWith("X-") || it.getKey().startsWith("Set-") || it.getKey().startsWith("Location")) { if (null == metadataHeaderObj) { metadataHeaderObj = new BasicDBObject(); } metadataHeaderObj.put(it.getKey(), it.getValue()); } } } //TESTED // Grab the response code try { HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect; int responseCode = httpUrlConnect.getResponseCode(); if (200 != responseCode) { if (null == metadataHeaderObj) { metadataHeaderObj = new BasicDBObject(); } metadataHeaderObj.put("responseCode", String.valueOf(responseCode)); } } //TESTED catch (Exception e) { } // interesting, not an HTTP connect ... shrug and carry on if (null != metadataHeaderObj) { doc.addToMetadata("__FEED_METADATA__", metadataHeaderObj); } //TESTED s = new Scanner(urlStream, "UTF-8"); doc.setFullText(s.useDelimiter("\\A").next()); } catch (MalformedURLException me) { // This one is worthy of a more useful error message throw new MalformedURLException(me.getMessage() + ": Likely because the document has no full text (eg JSON) and you are calling a contentMetadata block without setting flags:'m' or 'd'"); } finally { //(release resources) if (null != s) { s.close(); } if (null != wr) { wr.close(); } } }
From source file:action.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w.java 2 s . co m*/ * * @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 { HttpSession session = request.getSession(); String form_action = (String) request.getParameter("form_action"); if (form_action == null) { form_action = ""; } PrintWriter out = response.getWriter(); if (form_action.equalsIgnoreCase("cekauth")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); JSONObject obj1 = (JSONObject) obj; String admin = "N"; String icw = "N"; String email = obj1.get("email").toString(); String first_name = obj1.get("first_name").toString(); String gender = obj1.get("gender").toString(); String id = obj1.get("id").toString(); String last_name = obj1.get("last_name").toString(); String link = obj1.get("link").toString(); String name = obj1.get("name").toString(); String verified = obj1.get("verified").toString(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key linkKey = KeyFactory.createKey("userTable", "user"); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Filter posisinama = new FilterPredicate("link", FilterOperator.EQUAL, link.toLowerCase()); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("userTable", linkKey).setFilter(posisinama); List<Entity> userTables = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); Date date = new Date(); if (userTables.isEmpty()) { Entity userTable = new Entity("userTable", linkKey); userTable.setProperty("email", email); userTable.setProperty("first_name", first_name); userTable.setProperty("gender", gender); userTable.setProperty("id", id); userTable.setProperty("last_name", last_name); userTable.setProperty("link", link.toLowerCase()); userTable.setProperty("name", name); userTable.setProperty("verified", verified); userTable.setProperty("lastLogin", date); if (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || name.equalsIgnoreCase("Khairul Anshar")) { userTable.setProperty("admin", "Y"); userTable.setProperty("icw", "Y"); } else { userTable.setProperty("admin", admin); userTable.setProperty("icw", "N"); } userTable.setProperty("imported", "N"); datastore.put(userTable); } else { for (Entity userTable : userTables) { admin = userTable.getProperty("admin").toString(); try { icw = userTable.getProperty("icw").toString(); } catch (Exception e) { userTable.setProperty("icw", "N"); icw = "N"; } userTable.setProperty("lastLogin", date); datastore.put(userTable); } } if (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || name.equalsIgnoreCase("Khairul Anshar")) { admin = "Y"; icw = "Y"; } obj1.put("admin", admin); obj1.put("icw", icw); session.setAttribute("userAccount", obj1); record.put("userAccount", obj1); } catch (Exception e) { } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getiframeData")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String src = obj1.get("src").toString(); final URL url = new URL(src); final URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); urlConnection.connect(); final InputStream inputStream = urlConnection.getInputStream(); InputStreamReader is = new InputStreamReader(inputStream); StringBuilder sb1 = new StringBuilder(); BufferedReader br = new BufferedReader(is); String read = br.readLine(); while (read != null) { sb1.append(read); read = br.readLine(); } record.put("data", sb1.toString()); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("postCommentPosisi")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String dept = obj1.get("dept").toString(); String star = obj1.get("star").toString(); String comment = obj1.get("comment").toString(); String id = userAccount.get("id").toString(); String name = userAccount.get("name").toString(); String link = userAccount.get("link").toString(); postData2(name, dept, "", star, comment, id, "AlasanStarCalonPosisi", "dept", dept, link); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("postLikeComment")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String id = obj1.get("id").toString(); String star = obj1.get("star").toString(); JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String name = userAccount.get("name").toString(); String link = userAccount.get("link").toString(); postData11("AlasanStarLike", "id", id, star, link, name); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getLikeComment")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); String idx_ = ""; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; idx_ = obj1.get("id").toString(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); LinkedHashMap record11 = new LinkedHashMap(); String link_ = ""; try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); link_ = userAccount.get("link").toString(); } catch (Exception e) { } Key guestbookKey = KeyFactory.createKey("id", idx_); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("AlasanStarLike", guestbookKey).addSort("date", Query.SortDirection.DESCENDING); //List<Entity> AlasanStars = datastore.prepare(query); PreparedQuery pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); JSONArray obj11p = new JSONArray(); JSONArray obj11n = new JSONArray(); int i = 0; int ip = 0; int in = 0; double total = 0; double totalp = 0; double totaln = 0; for (Entity AlasanStar : pq.asIterable()) { LinkedHashMap record1 = new LinkedHashMap(); String date = AlasanStar.getProperty("date").toString(); String star = AlasanStar.getProperty("star").toString(); String name = AlasanStar.getProperty("user").toString(); String link = AlasanStar.getProperty("link").toString(); record1.put("date", date); record1.put("star", star); record1.put("name", name); record1.put("link", link); obj11.add(record1); i++; double d = Double.parseDouble(star); total = total + d; if (d >= 0) { obj11p.add(record1); ip++; totalp = totalp + d; } else { obj11n.add(record1); in++; totaln = totaln + d; } if (link_.equalsIgnoreCase(link)) { record11.put("date", date); record11.put("star", star); record11.put("name", name); record11.put("link", link); } } double avg = total / i; if (i == 0) { avg = 0; } DecimalFormat df = new DecimalFormat("#.##"); record.put("total", total); record.put("totalp", totalp); record.put("totaln", totaln); record.put("avg", df.format(avg)); //record.put("AlasanStars", obj11); record.put("AlasanStarsp", obj11p); record.put("AlasanStarsn", obj11n); record.put("AlasanStar", record11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getMyCommentPosisi")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); String dept = ""; DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); LinkedHashMap record1 = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; dept = obj1.get("dept").toString(); String link_ = ""; try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); link_ = userAccount.get("link").toString(); } catch (Exception e) { } LinkedHashMap record11 = new LinkedHashMap(); Key guestbookKey = KeyFactory.createKey("dept", dept); Query query = new Query("AlasanStarCalonPosisi", guestbookKey).addSort("date", Query.SortDirection.DESCENDING); PreparedQuery pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); JSONArray obj11p = new JSONArray(); JSONArray obj11n = new JSONArray(); int i = 0; int ip = 0; int in = 0; double total = 0; double totalp = 0; double totaln = 0; for (Entity AlasanStar : pq.asIterable()) { record1 = new LinkedHashMap(); String id = AlasanStar.getProperty("user").toString(); //DateTime dateTime = AlasanStar.getProperties().getDateTimeValue(); Date time = (Date) AlasanStar.getProperty("date"); String date = time.toString();//AlasanStar.getProperty("date").toString(); String star = AlasanStar.getProperty("star").toString(); String comment = AlasanStar.getProperty("comment").toString(); comment = comment.replaceAll("\n", "<br/>"); String name = AlasanStar.getProperty("name").toString(); String link = AlasanStar.getProperty("link").toString(); String id__ = AlasanStar.getKey().toString(); record1.put("id_", id__); record1.put("id", id); record1.put("date", date); record1.put("star", star); record1.put("comment", comment); record1.put("name", name); record1.put("link", link); obj11.add(record1); i++; double d = Double.parseDouble(star); total = total + d; if (d >= 0) { obj11p.add(record1); ip++; totalp = totalp + d; } else { obj11n.add(record1); in++; totaln = totaln + d; } if (link_.equalsIgnoreCase(link)) { record11.put("id_", id__); record11.put("id", id); record11.put("date", date); record11.put("star", star); record11.put("comment", comment); record11.put("name", name); record11.put("link", link); } } double avg = total / i; if (i == 0) { avg = 0; } DecimalFormat df = new DecimalFormat("#.##"); record.put("total", total); record.put("totalp", totalp); record.put("totaln", totaln); record.put("avg", df.format(avg)); //record.put("AlasanStars", obj11); record.put("AlasanStarsp", obj11p); record.put("AlasanStarsn", obj11n); record.put("AlasanStar", record11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("postComment")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String dept = obj1.get("dept").toString(); String namaCalon = obj1.get("namaCalon").toString(); String star = obj1.get("star").toString(); String comment = obj1.get("comment").toString(); String id = userAccount.get("id").toString(); String name = userAccount.get("name").toString(); String link = userAccount.get("link").toString(); postData2(name, dept, namaCalon, star, comment, id, "AlasanStarCalon", dept, namaCalon, link); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getMyComment")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); String dept = ""; String namaCalon = ""; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; dept = obj1.get("dept").toString(); namaCalon = obj1.get("namaCalon").toString(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); String link_ = ""; LinkedHashMap record11 = new LinkedHashMap(); try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); link_ = userAccount.get("link").toString(); } catch (Exception e) { } Key guestbookKey = KeyFactory.createKey(dept, namaCalon); Query query = new Query("AlasanStarCalon", guestbookKey).addSort("date", Query.SortDirection.DESCENDING); PreparedQuery pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); JSONArray obj11p = new JSONArray(); JSONArray obj11n = new JSONArray(); int i = 0; int ip = 0; int in = 0; double total = 0; double totalp = 0; double totaln = 0; for (Entity AlasanStar : pq.asIterable()) { LinkedHashMap record1 = new LinkedHashMap(); String id = AlasanStar.getProperty("user").toString(); Date time = (Date) AlasanStar.getProperty("date"); String date = time.toString();//AlasanStar.getProperty("date").toString(); String star = AlasanStar.getProperty("star").toString(); String comment = AlasanStar.getProperty("comment").toString(); comment = comment.replaceAll("\n", "<br/>"); String name = AlasanStar.getProperty("name").toString(); String link = AlasanStar.getProperty("link").toString(); String id__ = AlasanStar.getKey().toString(); record1.put("id_", id__); record1.put("id", id); record1.put("date", date); record1.put("star", star); record1.put("comment", comment); record1.put("name", name); record1.put("link", link); obj11.add(record1); i++; double d = Double.parseDouble(star); total = total + d; if (d >= 0) { obj11p.add(record1); ip++; totalp = totalp + d; } else { obj11n.add(record1); in++; totaln = totaln + d; } if (link_.equalsIgnoreCase(link)) { record11.put("id_", id__); record11.put("id", id); record11.put("date", date); record11.put("star", star); record11.put("comment", comment); record11.put("name", name); record11.put("link", link); } } double avg = total / i; if (i == 0) { avg = 0; } DecimalFormat df = new DecimalFormat("#.##"); record.put("total", total); record.put("totalp", totalp); record.put("totaln", totaln); record.put("avg", df.format(avg)); record.put("AlasanStarsp", obj11p); record.put("AlasanStarsn", obj11n); record.put("AlasanStar", record11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getAlasanStarCalon")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String dept = obj1.get("dept").toString(); String namaCalon = obj1.get("namaCalon").toString(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key guestbookKey = KeyFactory.createKey(dept, namaCalon); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("AlasanStarCalon", guestbookKey).addSort("date", Query.SortDirection.DESCENDING); //List<Entity> AlasanStars = datastore.prepare(query); PreparedQuery pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); int i = 0; double total = 0; for (Entity AlasanStar : pq.asIterable()) { LinkedHashMap record1 = new LinkedHashMap(); String id = AlasanStar.getProperty("user").toString(); String date = AlasanStar.getProperty("date").toString(); String star = AlasanStar.getProperty("star").toString(); String comment = AlasanStar.getProperty("comment").toString(); comment = comment.replaceAll("\n", "<br/>"); String name = AlasanStar.getProperty("name").toString(); String link = AlasanStar.getProperty("link").toString(); String id__ = AlasanStar.getKey().toString(); record1.put("id_", id__); record1.put("id", id); record1.put("date", date); record1.put("star", star); record1.put("comment", comment); record1.put("name", name); record1.put("link", link); obj11.add(record1); i++; double d = Double.parseDouble(star); total = total + d; } double avg = total / i; if (i == 0) { avg = 0; } DecimalFormat df = new DecimalFormat("#.##"); record.put("total", total); record.put("avg", df.format(avg)); record.put("AlasanStars", obj11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("postUsulan")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String dept = obj1.get("dept").toString(); String usulan = obj1.get("usulan").toString(); JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String id = userAccount.get("id").toString(); String name = userAccount.get("name").toString(); String email = userAccount.get("email").toString(); String link = userAccount.get("link").toString(); Key usulanCalonKey = KeyFactory.createKey("dept", dept); Date date = new Date(); Entity usulanCalon = new Entity("usulanCalon", usulanCalonKey); usulanCalon.setProperty("user", id); usulanCalon.setProperty("name", name); usulanCalon.setProperty("email", email); usulanCalon.setProperty("link", link); usulanCalon.setProperty("date", date); usulanCalon.setProperty("usulan", usulan); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); usulanCalon.setProperty("imported", "N"); datastore.put(usulanCalon); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getSet1")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String input = obj1.get("input").toString(); String type = obj1.get("type").toString(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key typeKey = KeyFactory.createKey("posisi", type.toLowerCase().replaceAll(" ", "")); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("posisi", typeKey).addSort("date", Query.SortDirection.ASCENDING); //List<Entity> AlasanStars = datastore.prepare(query); PreparedQuery pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); String id = ""; try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); id = userAccount.get("id").toString(); } catch (Exception ex1) { } for (Entity typeEntity : pq.asIterable()) { String reviewed = typeEntity.getProperty("reviewed").toString(); if (reviewed.equalsIgnoreCase("Y")) { LinkedHashMap record1 = new LinkedHashMap(); String posisi = typeEntity.getProperty("posisi").toString(); String nama = typeEntity.getProperty("nama").toString(); String link = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); record1.put("posisi", posisi); record1.put("nama", nama); record1.put("link", link); record1.put("date", date); String detail1 = ""; try { Text detail0 = (Text) typeEntity.getProperty("detail"); detail1 = detail0.getValue(); } catch (Exception e) { detail1 = ""; } record1.put("detail", detail1); obj11.add(record1); } else { String user = typeEntity.getProperty("user").toString(); if (user.equalsIgnoreCase(id)) { LinkedHashMap record1 = new LinkedHashMap(); String posisi = typeEntity.getProperty("posisi").toString(); String nama = typeEntity.getProperty("nama").toString(); String link = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); record1.put("posisi", posisi); record1.put("nama", nama); record1.put("link", link); record1.put("date", date); String detail1 = ""; try { Text detail0 = (Text) typeEntity.getProperty("detail"); detail1 = detail0.getValue(); } catch (Exception e) { detail1 = ""; } record1.put("detail", detail1); obj11.add(record1); } } } record.put("records", obj11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("setSet1")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String id = userAccount.get("id").toString(); String nama = userAccount.get("name").toString(); String email = userAccount.get("email").toString(); String link = userAccount.get("link").toString(); String admin = userAccount.get("admin").toString(); BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String input = obj1.get("input").toString(); String type = obj1.get("type").toString(); String value = obj1.get("value").toString(); String detail = obj1.get("value1").toString(); Key typeKey = KeyFactory.createKey("posisi", type.toLowerCase().replaceAll(" ", "")); Filter posisinama = new FilterPredicate("posisi", FilterOperator.EQUAL, value); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("posisi", typeKey).setFilter(posisinama); //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING); //List<Entity> AlasanStars = datastore.prepare(query); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); PreparedQuery pq = datastore.prepare(query); boolean found = pq.asIterable().iterator().hasNext(); if (found) { if (admin.equalsIgnoreCase("Y")) { for (Entity psosisiEntity : pq.asList(FetchOptions.Builder.withLimit(1))) { Date date = new Date(); psosisiEntity.setProperty("date", date); psosisiEntity.setProperty("detail", new Text(detail)); datastore.put(psosisiEntity); } } } if (!found) { Date date = new Date(); Entity psosisiEntity = new Entity("posisi", typeKey); psosisiEntity.setProperty("user", id); psosisiEntity.setProperty("link", link); psosisiEntity.setProperty("nama", nama); psosisiEntity.setProperty("email", email); psosisiEntity.setProperty("date", date); psosisiEntity.setProperty("posisi", value); psosisiEntity.setProperty("detail", new Text(detail)); if (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y")) { psosisiEntity.setProperty("reviewed", "Y"); psosisiEntity.setProperty("nama", "Kawal Menteri"); psosisiEntity.setProperty("link", "https://www.facebook.com/KawalMenteri"); } else { psosisiEntity.setProperty("reviewed", "N"); } psosisiEntity.setProperty("imported", "N"); datastore.put(psosisiEntity); } query = new Query("posisi", typeKey).addSort("date", Query.SortDirection.ASCENDING); pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); for (Entity typeEntity : pq.asIterable()) { String reviewed = typeEntity.getProperty("reviewed").toString(); if (reviewed.equalsIgnoreCase("Y")) { LinkedHashMap record1 = new LinkedHashMap(); String posisi = typeEntity.getProperty("posisi").toString(); String nama1 = typeEntity.getProperty("nama").toString(); String link1 = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); record1.put("posisi", posisi); record1.put("nama", nama1); record1.put("link", link1); record1.put("date", date); String detail1 = ""; try { Text detail0 = (Text) typeEntity.getProperty("detail"); detail1 = detail0.getValue(); } catch (Exception e) { detail1 = ""; } record1.put("detail", detail1); obj11.add(record1); } else { String user = typeEntity.getProperty("user").toString(); if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) { LinkedHashMap record1 = new LinkedHashMap(); String posisi = typeEntity.getProperty("posisi").toString(); String nama1 = typeEntity.getProperty("nama").toString(); String link1 = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); record1.put("posisi", posisi); record1.put("nama", nama1); record1.put("link", link1); record1.put("date", date); String detail1 = ""; try { Text detail0 = (Text) typeEntity.getProperty("detail"); detail1 = detail0.getValue(); } catch (Exception e) { detail1 = ""; } record1.put("detail", detail1); obj11.add(record1); } } } record.put("records", obj11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("getSet2")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String input = obj1.get("input").toString(); String input0 = obj1.get("input0").toString(); String type0 = obj1.get("type0").toString(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key typeKey = KeyFactory.createKey("kandidat" + type0, input); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("kandidat", typeKey).addSort("date", Query.SortDirection.ASCENDING); //List<Entity> AlasanStars = datastore.prepare(query); PreparedQuery pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); String id = ""; String nama = ""; String email = ""; String link = ""; String admin = ""; String icw = ""; try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); id = userAccount.get("id").toString(); nama = userAccount.get("name").toString(); email = userAccount.get("email").toString(); link = userAccount.get("link").toString(); admin = userAccount.get("admin").toString(); icw = userAccount.get("icw").toString(); } catch (Exception ex1) { } for (Entity typeEntity : pq.asIterable()) { String reviewed = typeEntity.getProperty("reviewed").toString(); if (reviewed.equalsIgnoreCase("Y")) { LinkedHashMap record1 = new LinkedHashMap(); String kandidat = typeEntity.getProperty("kandidat").toString(); String desc = typeEntity.getProperty("desc").toString(); Text detail0 = (Text) typeEntity.getProperty("detail"); String detail = detail0.getValue(); String nama1 = typeEntity.getProperty("nama").toString(); String link1 = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); String icwcomment = ""; try { icwcomment = typeEntity.getProperty("icwcomment").toString(); } catch (Exception e) { icwcomment = ""; } record1.put("key", "kandidat" + type0); record1.put("val", input); record1.put("kandidat", kandidat); record1.put("desc", desc); record1.put("detail", detail); record1.put("nama", nama1); record1.put("link", link1); record1.put("date", date); record1.put("icwcomment", icwcomment); obj11.add(record1); } else { String user = typeEntity.getProperty("user").toString(); if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) { LinkedHashMap record1 = new LinkedHashMap(); String kandidat = typeEntity.getProperty("kandidat").toString(); String desc = typeEntity.getProperty("desc").toString(); Text detail0 = (Text) typeEntity.getProperty("detail"); String detail = detail0.getValue(); String nama1 = typeEntity.getProperty("nama").toString(); String link1 = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); record1.put("key", "kandidat" + type0); record1.put("val", input); record1.put("kandidat", kandidat); record1.put("desc", desc); record1.put("detail", detail); record1.put("nama", nama1); record1.put("link", link1); record1.put("date", date); String icwcomment = ""; if (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y") || icw.equalsIgnoreCase("Y")) { try { icwcomment = typeEntity.getProperty("icwcomment").toString(); } catch (Exception e) { icwcomment = ""; } } record1.put("icwcomment", icwcomment); obj11.add(record1); } } } record.put("records", obj11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("setIcwComment")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String icw = userAccount.get("icw").toString(); if (icw.equalsIgnoreCase("N")) { } else { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String input = obj1.get("input").toString(); String input0 = obj1.get("input0").toString(); String type0 = obj1.get("type0").toString(); String value = obj1.get("value").toString(); String menteri = obj1.get("menteri").toString(); String kandidat = obj1.get("kandidat").toString(); Key typeKey = KeyFactory.createKey("kandidat" + type0, input); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Filter namaKandidat = new FilterPredicate("kandidat", FilterOperator.EQUAL, kandidat); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("kandidat", typeKey).setFilter(namaKandidat); //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING); //List<Entity> AlasanStars = datastore.prepare(query); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); for (Entity psosisiEntity : datastore.prepare(query) .asList(FetchOptions.Builder.withLimit(1))) { psosisiEntity.setProperty("icwcomment", value); datastore.put(psosisiEntity); } } record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("setSet2")) { StringBuffer sb = new StringBuffer(); String line = null; LinkedHashMap record = new LinkedHashMap(); try { JSONObject userAccount = (JSONObject) session.getAttribute("userAccount"); String id = userAccount.get("id").toString(); String nama = userAccount.get("name").toString(); String email = userAccount.get("email").toString(); String link = userAccount.get("link").toString(); String admin = userAccount.get("admin").toString(); String icw = userAccount.get("icw").toString(); BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } Object obj = JSONValue.parse(sb.toString()); //JSONArray records = (JSONArray) obj; JSONObject obj1 = (JSONObject) obj; String input = obj1.get("input").toString(); String input0 = obj1.get("input0").toString(); String type0 = obj1.get("type0").toString(); String value = obj1.get("value").toString(); String value1 = obj1.get("value1").toString(); String value2 = obj1.get("value2").toString(); String menteri = obj1.get("menteri").toString(); Key typeKey = KeyFactory.createKey("kandidat" + type0, input); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Filter namaKandidat = new FilterPredicate("kandidat", FilterOperator.EQUAL, value); // Run an ancestor query to ensure we see the most up-to-date // view of the Greetings belonging to the selected Guestbook. Query query = new Query("kandidat", typeKey).setFilter(namaKandidat); //Query query = new Query("posisi", typeKey);//.addSort("date", Query.SortDirection.DESCENDING); //List<Entity> AlasanStars = datastore.prepare(query); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); PreparedQuery pq = datastore.prepare(query); boolean found = pq.asIterable().iterator().hasNext(); if (found) { if (admin.equalsIgnoreCase("Y")) { for (Entity psosisiEntity : pq.asList(FetchOptions.Builder.withLimit(1))) { Date date = new Date(); psosisiEntity.setProperty("date", date); psosisiEntity.setProperty("detail", new Text(value2)); datastore.put(psosisiEntity); } } } if (!found) { Date date = new Date(); Entity psosisiEntity = new Entity("kandidat", typeKey); psosisiEntity.setProperty("user", id); psosisiEntity.setProperty("link", link); psosisiEntity.setProperty("nama", nama); psosisiEntity.setProperty("email", email); psosisiEntity.setProperty("date", date); psosisiEntity.setProperty("kandidat", value); psosisiEntity.setProperty("desc", value1); psosisiEntity.setProperty("posisi", menteri); psosisiEntity.setProperty("detail", new Text(value2)); psosisiEntity.setProperty("icwcomment", ""); if (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y")) { psosisiEntity.setProperty("reviewed", "Y"); psosisiEntity.setProperty("nama", "Kawal Menteri"); psosisiEntity.setProperty("link", "https://www.facebook.com/KawalMenteri"); } else { psosisiEntity.setProperty("reviewed", "N"); } psosisiEntity.setProperty("imported", "N"); datastore.put(psosisiEntity); } query = new Query("kandidat", typeKey).addSort("date", Query.SortDirection.ASCENDING); pq = datastore.prepare(query); JSONArray obj11 = new JSONArray(); for (Entity typeEntity : pq.asIterable()) { String reviewed = typeEntity.getProperty("reviewed").toString(); if (reviewed.equalsIgnoreCase("Y")) { LinkedHashMap record1 = new LinkedHashMap(); String kandidat = typeEntity.getProperty("kandidat").toString(); String desc = typeEntity.getProperty("desc").toString(); Text detail0 = (Text) typeEntity.getProperty("detail"); String detail = detail0.getValue(); String nama1 = typeEntity.getProperty("nama").toString(); String link1 = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); String icwcomment = ""; try { icwcomment = typeEntity.getProperty("icwcomment").toString(); } catch (Exception e) { icwcomment = ""; } record1.put("key", "kandidat" + type0); record1.put("val", input); record1.put("kandidat", kandidat); record1.put("desc", desc); record1.put("detail", detail); record1.put("nama", nama1); record1.put("link", link1); record1.put("date", date); record1.put("icwcomment", icwcomment); obj11.add(record1); } else { String user = typeEntity.getProperty("user").toString(); if (user.equalsIgnoreCase(id) || (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y"))) { LinkedHashMap record1 = new LinkedHashMap(); String kandidat = typeEntity.getProperty("kandidat").toString(); String desc = typeEntity.getProperty("desc").toString(); Text detail0 = (Text) typeEntity.getProperty("detail"); String detail = detail0.getValue(); String nama1 = typeEntity.getProperty("nama").toString(); String link1 = typeEntity.getProperty("link").toString(); String date = typeEntity.getProperty("date").toString(); record1.put("key", "kandidat" + type0); record1.put("val", input); record1.put("kandidat", kandidat); record1.put("desc", desc); record1.put("detail", detail); record1.put("nama", nama1); record1.put("link", link1); record1.put("date", date); String icwcomment = ""; if (email.equalsIgnoreCase("khairul.anshar@gmail.com") || id.equalsIgnoreCase("112525777678499279265") || id.equalsIgnoreCase("10152397276159760") || nama.equalsIgnoreCase("Khairul Anshar") || admin.equalsIgnoreCase("Y") || icw.equalsIgnoreCase("Y")) { try { icwcomment = typeEntity.getProperty("icwcomment").toString(); } catch (Exception e) { icwcomment = ""; } } record1.put("icwcomment", icwcomment); obj11.add(record1); } } } record.put("records", obj11); record.put("status", "OK"); } catch (Exception e) { record.put("status", "error"); record.put("errormsg", e.toString()); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } }
From source file:com.amalto.workbench.utils.Util.java
public static String getResponseFromURL(String url, TreeObject treeObj) throws Exception { InputStreamReader doc = null; try {/*from w ww .j a va2 s .c om*/ Encoder encoder = Base64.getEncoder(); StringBuffer buffer = new StringBuffer(); String credentials = encoder.encodeToString((new String(treeObj.getServerRoot().getUsername() + ":"//$NON-NLS-1$ + treeObj.getServerRoot().getPassword()).getBytes())); URL urlCn = new URL(url); URLConnection conn = urlCn.openConnection(); conn.setAllowUserInteraction(true); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Authorization", "Basic " + credentials);//$NON-NLS-1$//$NON-NLS-2$ conn.setRequestProperty("Expect", "100-continue");//$NON-NLS-1$//$NON-NLS-2$ doc = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(doc); String line = reader.readLine(); while (line != null) { buffer.append(line); line = reader.readLine(); } return buffer.toString(); } finally { if (doc != null) { doc.close(); } } }
From source file:com.adobe.aem.demomachine.communities.Loader.java
private static void postAnalytics(String analytics, String body) { if (analytics != null && body != null) { URLConnection urlConn = null; DataOutputStream printout = null; BufferedReader input = null; String tmp = null;/*from w ww . ja v a 2 s . co m*/ try { logger.debug("New Analytics Event: " + body); URL sitecaturl = new URL("http://" + analytics); urlConn = sitecaturl.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); printout.writeBytes(body); printout.flush(); printout.close(); input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while (null != ((tmp = input.readLine()))) { logger.debug(tmp); } printout.close(); input.close(); } catch (Exception ex) { logger.warn("Connectivity error: " + ex.getMessage()); } finally { try { input.close(); printout.close(); } catch (Exception e) { // Omitted } } } }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {/*w w w .jav a2s .c om*/ URL url = new URL(uri); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }
From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java
/** * /*from www .j a v a 2 s . c o m*/ * also @see com.compositesw.ps.deploytool.dao.RegressionPubTestDAO#executeWs(com.compositesw.ps.deploytool.dao.RegressionPubTestDAO.Item, String, String) */ public static int executeWs(RegressionItem item, String outputFile, CompositeServer cisServerConfig, RegressionTestType regressionConfig, String delimiter, String printOutputType) throws CompositeException { // Set the command and action name String command = "executeWs"; String actionName = "REGRESSION_TEST"; // Check the input parameter values: if (cisServerConfig == null || regressionConfig == null) { throw new CompositeException( "XML Configuration objects are not initialized when trying to run Regression test."); } URLConnection urlConn = null; BufferedReader rd = null; OutputStreamWriter wr = null; int rows = 0; String host = cisServerConfig.getHostname(); int wsPort = cisServerConfig.getPort(); // port in servers.xml defines WS port boolean useHttps = cisServerConfig.isUseHttps(); // Execute the webservice try { // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { boolean encrypt = item.encrypt; // Override the encrypt flag when useHttps is set from an overall PDTool over SSL (https) setting. if (useHttps && !encrypt) { encrypt = true; RegressionManagerUtils.printOutputStr(printOutputType, "summary", "The regression input file encrypt=false has been overridden by useHttps=true for path=" + item.path, ""); } String urlString = "http://" + host + ":" + wsPort + item.path; if (encrypt) { urlString = "https://" + host + ":" + (wsPort + 2) + item.path; } RegressionManagerUtils.printOutputStr(printOutputType, "summary", "urlString=" + urlString, ""); URL url = new URL(urlString); urlConn = url.openConnection(); if (encrypt) { // disable hostname verification ((HttpsURLConnection) urlConn).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }); } // 2014-02-09 (mtinius) - added basic authorization to allow for connections with new users String credentials = cisServerConfig.getUser() + ":" + CommonUtils.decrypt(cisServerConfig.getPassword()); String encoded = Base64EncodeDecode.encodeString(credentials); urlConn.setRequestProperty("Authorization", "Basic " + encoded); urlConn.setRequestProperty("SOAPAction", item.action); urlConn.setRequestProperty("Content-Type", item.contentType); urlConn.setDoOutput(true); wr = new OutputStreamWriter(urlConn.getOutputStream()); wr.write(item.input); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = rd.readLine()) != null) { rows++; buf.append(line); if (outputFile != null) CommonUtils.appendContentToFile(outputFile, line); } line = buf.toString(); RegressionManagerUtils.printOutputStr(printOutputType, "results", line, ""); if (line.indexOf("<fault") >= 0 || line.indexOf(":fault") >= 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("Fault encountered."); } if (line.trim().length() == 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("No response document."); } urlConn.getInputStream().close(); // urlConn.getOutputStream().flush(); wr.close(); rd.close(); RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeWs()", ""); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } return rows; } catch (IOException e) { try { HttpURLConnection httpConn = (HttpURLConnection) urlConn; BufferedReader brd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = brd.readLine()) != null) { buf.append(line + "\n"); } brd.close(); String error = buf.toString(); throw new ApplicationException("executeWs(): " + error, e); } catch (Exception err) { String error = e.getMessage() + "\n" + "DETAILED_MESSAGE=[" + err.getMessage() + "]"; //debug: System.out.println("*************** ERROR ENCOUNTERED IN executeWs THREAD FOR TYPE:webservice *****************"); throw new ApplicationException("executeWs(): " + error, err); } } finally { try { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } } catch (Exception e) { rd = null; wr = null; throw new CompositeException( "executeWs(): unable to close BufferedReader (rd) and OutputStreamWriter (wr): " + e.getMessage()); } } }
From source file:com.MainFiles.Functions.java
public String getCustomerDetails(String strAccountNumber) throws IOException { String[] strCustomerNameArray; String strCustomerName = ""; String fname = ""; String mname = ""; String lname = ""; try {/* w ww. j ava 2s . c om*/ URL url = new URL(CUSTOMER_DETAILS_URL); Map<String, String> params = new LinkedHashMap<>(); params.put("username", CUSTOMER_DETAILS_USERNAME); params.put("password", CUSTOMER_DETAILS_PASSWORD); params.put("source", CUSTOMER_DETAILS_SOURCE_ID); params.put("account", strAccountNumber); StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (postData.length() != 0) { postData.append('&'); } postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } String urlParameters = postData.toString(); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); String result = ""; String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { result += line; } writer.close(); reader.close(); JSONObject respobj = new JSONObject(result); if (respobj.has("FSTNAME") || respobj.has("MIDNAME") || respobj.has("LSTNAME")) { if (respobj.has("FSTNAME")) { fname = respobj.get("FSTNAME").toString().toUpperCase() + ' '; } if (respobj.has("MIDNAME")) { mname = respobj.get("MIDNAME").toString().toUpperCase() + ' '; } if (respobj.has("LSTNAME")) { lname = respobj.get("LSTNAME").toString().toUpperCase() + ' '; } strCustomerName = fname + mname + lname; } else { strCustomerName = "N/A"; } } catch (Exception ex) { this.log("\nINFO : Function getCustomerDetails() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "ERROR"); } // System.out.println(strCustomerName); return strCustomerName; }
From source file:com.arm.connector.bridge.transport.HttpTransport.java
@SuppressWarnings("empty-statement") private String doHTTP(String verb, String url_str, String username, String password, String data, String content_type, String auth_domain, boolean doInput, boolean doOutput, boolean doSSL, boolean use_api_token, String api_token) { String result = ""; String line = ""; URLConnection connection = null; SSLContext sc = null;//from w ww .j a v a 2s . c o m try { URL url = new URL(url_str); // Http Connection and verb if (doSSL) { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } catch (NoSuchAlgorithmException | KeyManagementException e) { // do nothing ; } // open the SSL connction connection = (HttpsURLConnection) (url.openConnection()); ((HttpsURLConnection) connection).setRequestMethod(verb); ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } else { connection = (HttpURLConnection) (url.openConnection()); ((HttpURLConnection) connection).setRequestMethod(verb); } connection.setDoInput(doInput); if (doOutput && data != null && data.length() > 0) { connection.setDoOutput(doOutput); } else { connection.setDoOutput(false); } // enable basic auth if requested if (use_api_token == false && username != null && username.length() > 0 && password != null && password.length() > 0) { String encoding = Base64.encodeBase64String((username + ":" + password).getBytes()); connection.setRequestProperty("Authorization", this.m_basic_auth_qualifier + " " + encoding); //this.errorLogger().info("Basic Authorization: " + username + ":" + password + ": " + encoding); } // enable ApiTokenAuth auth if requested if (use_api_token == true && api_token != null && api_token.length() > 0) { // use qualification for the authorization header... connection.setRequestProperty("Authorization", this.m_auth_qualifier + " " + api_token); //this.errorLogger().info("ApiTokenAuth Authorization: " + api_token); // Always reset to the established default this.resetAuthorizationQualifier(); } // ETag support if requested if (this.m_etag_value != null && this.m_etag_value.length() > 0) { // set the ETag header value connection.setRequestProperty("ETag", this.m_etag_value); //this.errorLogger().info("ETag Value: " + this.m_etag_value); // Always reset to the established default this.resetETagValue(); } // If-Match support if requested if (this.m_if_match_header_value != null && this.m_if_match_header_value.length() > 0) { // set the If-Match header value connection.setRequestProperty("If-Match", this.m_if_match_header_value); //this.errorLogger().info("If-Match Value: " + this.m_if_match_header_value); // Always reset to the established default this.resetIfMatchValue(); } // specify content type if requested if (content_type != null && content_type.length() > 0) { connection.setRequestProperty("Content-Type", content_type); connection.setRequestProperty("Accept", "*/*"); } // add Connection: keep-alive (does not work...) //connection.setRequestProperty("Connection", "keep-alive"); // special gorp for HTTP DELETE if (verb != null && verb.equalsIgnoreCase("delete")) { connection.setRequestProperty("Access-Control-Allow-Methods", "OPTIONS, DELETE"); } // specify domain if requested if (auth_domain != null && auth_domain.length() > 0) { connection.setRequestProperty("Domain", auth_domain); } // DEBUG dump the headers //if (doSSL) // this.errorLogger().info("HTTP: Headers: " + ((HttpsURLConnection)connection).getRequestProperties()); //else // this.errorLogger().info("HTTP: Headers: " + ((HttpURLConnection)connection).getRequestProperties()); // specify data if requested - assumes it properly escaped if necessary if (doOutput && data != null && data.length() > 0) { try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) { out.write(data); } } // setup the output if requested if (doInput) { try { try (InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content))) { while ((line = in.readLine()) != null) { result += line; } } } catch (java.io.FileNotFoundException ex) { this.errorLogger().info("HTTP(" + verb + ") empty response (OK)."); result = ""; } } else { // no result expected result = ""; } // save off the HTTP response code... if (doSSL) this.saveResponseCode(((HttpsURLConnection) connection).getResponseCode()); else this.saveResponseCode(((HttpURLConnection) connection).getResponseCode()); // DEBUG //if (doSSL) // this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpsURLConnection)connection).getResponseCode()); //else // this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpURLConnection)connection).getResponseCode()); } catch (IOException ex) { this.errorLogger().warning("Caught Exception in doHTTP(" + verb + "): " + ex.getMessage()); result = null; } // return the result return result; }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI();/* www . ja va 2s . c o m*/ // Is this a CONNECT request? if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) { response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE???? handleConnect(pathInContext, pathParams, request, response); return; } try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) sendForbid(request, response, uri); return; } if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warn(e.toString()); LogSupport.ignore(log, e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request); } }
From source file:org.lockss.proxy.ProxyHandler.java
/** Proxy a connection using Java's native URLConection */ void doSun(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { URI uri = request.getURI();//from ww w. jav a 2 s . c o m try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) { sendForbid(request, response, uri); logAccess(request, "forbidden method: " + request.getMethod()); } return; } if (jlog.isDebugEnabled()) jlog.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean hasContent = false; Enumeration en = request.getFieldNames(); while (en.hasMoreElements()) { // XXX could be better than this! String hdr = (String) en.nextElement(); if (_DontProxyHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equalsIgnoreCase(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); } } } // Proxy headers connection.addRequestProperty(HttpFields.__Via, makeVia(request)); connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(jlog, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(jlog, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addField(HttpFields.__Via, makeVia(request)); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warning("doSun error", e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request, e.getMessage()); } }