List of usage examples for java.net URLConnection connect
public abstract void connect() throws IOException;
From source file:uk.ac.ebi.intact.editor.controller.curate.publication.PublicationController.java
public boolean isCitexploreOnline() { if (isCitexploreActive) { return true; }/*from w w w . ja v a 2 s . c o m*/ if (log.isDebugEnabled()) log.debug("Checking Europe Pubmed Central status"); try { URL url = new URL("http://www.ebi.ac.uk/webservices/citexplore/v3.0.1/service?wsdl"); final URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(1000); urlConnection.setReadTimeout(1000); urlConnection.connect(); } catch (Exception e) { log.debug("\tEurope Pubmed Central is not reachable"); isCitexploreActive = false; return false; } isCitexploreActive = true; return true; }
From source file:com.ucuenca.pentaho.plugin.step.EldaPDIStepDialog.java
/** * Metodo para cargar las propiedades por entidad *//*from w w w . ja va2s. c om*/ public void cargarTablaPropiedadesEntidad(String UrlEntidad) { ArrayList<String> propiedades = new ArrayList<String>(); //validacion URL servicio y acceso Boolean urlCorrecto = true; Boolean urlAcceso = true; try { URL url = new URL(wHelloFieldName.getText().trim()); URLConnection conn = url.openConnection(); conn.connect(); } catch (MalformedURLException e) { // URL mal formada logBasic("URL " + wHelloFieldName.getText() + " malformada "); System.out.println("URL " + wHelloFieldName.getText() + " malformada "); urlCorrecto = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.malformed") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } catch (IOException e) { // no hay conexion logBasic("Servicio a consultar caido " + wHelloFieldName.getText()); System.out.println("Servicio a consultar caido " + wHelloFieldName.getText()); urlAcceso = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.inalcanzable") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } if (urlCorrecto && urlAcceso) { //cuando hay servicio procedo a consultar //envio url del servicio y la url de la entidad propiedades = ConsultarPropiedadesXentidad(wHelloFieldName.getText().trim(), UrlEntidad); propiedadesTodasCargadas = propiedades; ArrayList<String> PropiedadesSeleccionadas = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadasNames = new ArrayList<String>(); Boolean psel = false; //propiedad seleccionada if (!PropiedadesSeleccionadasUsuario.isEmpty()) { psel = true; //si esta vacio antes lo carga con todos los valores } table2.removeAll(); //propiedades for (int i = 0; i < propiedades.size(); i++) { new TableItem(table2, SWT.NONE); TableEditor meditor2 = new TableEditor(table2); TableItem miti2 = table2.getItem(i); miti2.setText(0, (String) propiedades.get(i)); //cargo la propiedad if (psel) { for (int k = 0; k < PropiedadesSeleccionadasUsuario.size(); k++) { if (miti2.getText().trim().compareTo(PropiedadesSeleccionadasUsuario.get(k).trim()) == 0) { // comparo para ver si son las propiedades seleccionadas miti2.setChecked(true); if (k < PropiedadesSeleccionadasNamesUsuario.size()) { //validacion exista nombre para esa propiedad miti2.setText(1, PropiedadesSeleccionadasNamesUsuario.get(k).trim()); } } } } meditor2.setItem(miti2); //singleSelectList.add((String) propiedades.get(i), i); //guardo todas las Propiedades para pasar al meta----- combo if (!listIndicesPropiedadesCargadas.contains(String.valueOf(table.getSelectionIndex()))) { //compruebo no haber ya guaradado estas propiedades ArrayList<String> listItem = new ArrayList<String>(); listItem.add(propiedades.get(i).trim()); //propiedad listItem.add(String.valueOf(table.getSelectionIndex())); // entidad item index arrayPropiedades.add(listItem); } //------------------------- } listIndicesPropiedadesCargadas.add(String.valueOf(table.getSelectionIndex())); //una ves cargada todas las propiedes la guardo en la lista de las ya cargadas } }
From source file:com.ucuenca.pentaho.plugin.step.EldaPDIStepDialog.java
public void cargartablas() { meta.setListSelect(ListSource.toString()); meta.setListProper(ListProper.toString()); ArrayList<String> propiedades = new ArrayList<String>(); ArrayList<String> objetos = new ArrayList<String>(); //Servicio = "http://localhost:3030/myservice/query"; /*//from ww w . ja v a 2 s.co m String[] schemes = {"http","https"}; // DEFAULT schemes = "http", "https", "ftp" UrlValidator urlValidator = new UrlValidator(schemes); if (urlValidator.isValid("ftp://foo.bar.com/")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); }*/ //validacion URL servicio y acceso Boolean urlCorrecto = true; Boolean urlAcceso = true; try { URL url = new URL(wHelloFieldName.getText().trim()); URLConnection conn = url.openConnection(); conn.connect(); } catch (MalformedURLException e) { // URL mal formada logBasic("URL " + wHelloFieldName.getText() + " malformada "); System.out.println("URL " + wHelloFieldName.getText() + " malformada "); urlCorrecto = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.malformed") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } catch (IOException e) { // no hay conexion logBasic("Servicio a consultar caido " + wHelloFieldName.getText()); System.out.println("Servicio a consultar caido " + wHelloFieldName.getText()); urlAcceso = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.inalcanzable") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } if (urlCorrecto && urlAcceso) { logBasic("Servicio a consultar " + wHelloFieldName.getText()); //objetos = ConsultarFuseki(wHelloFieldName.getText()); propiedades = ConsultarFusekiPropiedades(wHelloFieldName.getText().trim()); objetos = ConsultarFuseki(wHelloFieldName.getText().trim()); //objetos = this.listarEntidadesRdf((String) wHelloFieldName // .getText()); //propiedades = listarPropiedades((String) wHelloFieldName.getText()); ArrayList<String> EntidadesSeleccionadas = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadas = new ArrayList<String>(); ArrayList<String> EntidadesSeleccionadasNames = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadasNames = new ArrayList<String>(); Boolean esel = false; //entidad fue seleccionada Boolean psel = false; //propiedad seleccionada if ((meta.getListSelect().compareTo("[]") != 0) && (meta.getListSelect() != null)) { EntidadesSeleccionadas = cleanspaces(meta.getListSelect()); EntidadesSeleccionadasNames = cleanspaces(meta.getListSelectNames()); esel = true; } if ((meta.getListProper().compareTo("[]") != 0) && (meta.getListProper() != null)) { psel = true; PropiedadesSeleccionadas = cleanspaces(meta.getListProper()); PropiedadesSeleccionadasNames = cleanspaces(meta.getListProperNames()); } //Cargando la tabla 1 table.removeAll(); //entidades for (int i = 0; i < objetos.size(); i++) { //if(i>=4){new TableItem(table, SWT.NONE);} //crear item suficientes new TableItem(table, SWT.NONE); TableEditor meditor1 = new TableEditor(table); TableItem miti = table.getItem(i); miti.setText(0, (String) objetos.get(i)); if (esel) { for (int k = 0; k < EntidadesSeleccionadas.size(); k++) { System.out.println(miti.getText() + " " + EntidadesSeleccionadas.get(k)); if (miti.getText().compareTo(EntidadesSeleccionadas.get(k)) == 0) { miti.setChecked(true); miti.setText(1, EntidadesSeleccionadasNames.get(k)); } } } meditor1.setItem(miti); } if (table.getItemCount() > 1) { //por defecto seleccion table.setSelection(0); //selecciono el primer elemento //table.select(arg0) table2.removeAll(); TableItem fila1 = table.getItem(table.getSelectionIndex()); if (!fila1.getText().isEmpty()) { //si no esta vacio el valor de la primera fila tabla1 fila1.setChecked(true); String urlEntidad = fila1.getText(); cargarTablaPropiedadesEntidad(urlEntidad); //propiedadesTodasCargadas } } //table2.removeAll(); //propiedades /* for (int i = 0; i < propiedades.size(); i++) { new TableItem(table2, SWT.NONE); TableEditor meditor2 = new TableEditor(table2); TableItem miti2 = table2.getItem(i); miti2.setText(0, (String) propiedades.get(i)); if(psel){ for(int k =0; k < PropiedadesSeleccionadas.size();k++) { if(miti2.getText().compareTo(PropiedadesSeleccionadas.get(k))==0){ miti2.setChecked(true); miti2.setText(1, PropiedadesSeleccionadasNames.get(k)); } } } meditor2.setItem(miti2); //singleSelectList.add((String) propiedades.get(i), i); } */ } }
From source file:JNLPAppletLauncher.java
/** * Download, cache, verify, and unpack the specified native jar file. * Before downloading, check the cached time stamp for the jar file * against the server. If the time stamp is valid and matches that of the * server, then we will use the locally cached files. This method assumes * that cacheDir and nativeTmpDir both exist. * * An IOException is thrown if the files cannot loaded for some reason. *//*from ww w . j av a 2 s. c o m*/ private void processNativeJar(URL url) throws IOException { assert cacheDir.isDirectory(); assert nativeTmpDir.isDirectory(); // 6618105: Map '\' to '/' prior to stripping off the path String urlString = url.toExternalForm().replace('\\', '/'); String nativeFileName = urlString.substring(urlString.lastIndexOf("/") + 1); File nativeFile = new File(cacheDir, nativeFileName); // Make sure the file is not "." or ".." if (nativeFile.isDirectory()) { throw new IOException(nativeFile + " is a directory"); } String tmpStr = nativeFileName; int idx = nativeFileName.lastIndexOf("."); if (idx > 0) { tmpStr = nativeFileName.substring(0, idx); } String indexFileName = tmpStr + ".idx"; File indexFile = new File(cacheDir, indexFileName); if (VERBOSE) { System.err.println("nativeFile = " + nativeFile); System.err.println("indexFile = " + indexFile); } displayMessage("Loading: " + nativeFileName); setProgress(0); URLConnection conn = url.openConnection(); conn.connect(); Map/*<String,List<String>>*/ headerFields = conn.getHeaderFields(); if (VERBOSE) { for (Iterator iter = headerFields.entrySet().iterator(); iter.hasNext();) { Entry/*<String,List<String>>*/ e = (Entry) iter.next(); for (Iterator iter2 = ((List/*<String>*/) e.getValue()).iterator(); iter2.hasNext();) { String s = (String) iter2.next(); if (e.getKey() != null) { System.err.print(e.getKey() + ": "); } System.err.print(s + " "); } System.err.println(); } System.err.println(); } // Validate the cache, download the jar if needed // TODO: rather than synchronizing on System.out during cache validation, // we should use a System property as a lock token (protected by // System.out) so we don't hold a synchronized lock on System.out during // a potentially long download operation. synchronized (System.out) { validateCache(conn, nativeFile, indexFile); } // Unpack the jar file displayMessage("Unpacking: " + nativeFileName); setProgress(0); // Enumerate the jar file looking for native libraries JarFile jarFile = new JarFile(nativeFile); Set/*<String>*/ rootEntries = getRootEntries(jarFile); Set/*<String>*/ nativeLibNames = getNativeLibNames(rootEntries); // Validate certificates; throws exception upon validation error validateCertificates(jarFile, rootEntries); // Extract native libraries from the jar file extractNativeLibs(jarFile, rootEntries, nativeLibNames); if (VERBOSE) { System.err.println(); } }
From source file:action.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w. ja v a2 s . com * * @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: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 {/* ww w . ja v a 2s .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:org.wso2.carbon.appmgt.hostobjects.APIProviderHostObject.java
public static String jsFunction_isURLValid(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws AppManagementException { String response = ""; if (args == null || !isStringValues(args)) { handleException("Invalid input parameters."); }// ww w . j a v a 2s. c om String urlVal = (String) args[1]; String type = (String) args[0]; if (urlVal != null && !urlVal.equals("")) { try { if (type != null && type.equals("wsdl")) { validateWsdl(urlVal); } else { URL url = new URL(urlVal); URLConnection conn = url.openConnection(); conn.connect(); } response = "success"; } catch (MalformedURLException e) { response = "malformed"; } catch (UnknownHostException e) { response = "unknown"; } catch (ConnectException e) { response = "Cannot establish connection to the provided address"; } catch (SSLHandshakeException e) { response = "ssl_error"; } catch (Exception e) { response = e.getMessage(); } } return response; }
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();/*from w ww . j a v a2 s. 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 . ja v a 2 s.com 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()); } }
From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java
/** * @param context/*from ww w . j a v a 2 s. c om*/ * @param namespaceURL * @return InputStream * @throws IOException */ public static InputStream getTldInputStream(ExternalContext context, String namespaceURL) throws IOException { // InputStream in = null; JarFile jarFile = null; String[] location = null; namespaceURL = String.valueOf(namespaceURL); // "jsp" is only a placeholder for standard JSP tags that are // not supported, so just return null if ("jsp".equals(namespaceURL)) { return null; } if ("http://java.sun.com/JSP/Page".equals(namespaceURL)) { return null; } // TldLocationsCache may fail esp. with SecurityException on SUN app server TldLocationsCache tldCache = new TldLocationsCache(context); try { location = tldCache.getLocation(namespaceURL); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } if (null == location) { if (namespaceURL.startsWith("/") && namespaceURL.endsWith(".tld")) { location = new String[] { namespaceURL }; } } if (null == location) { location = scanJars(context, namespaceURL); } if (null == location) { //look for Sun implementation URL tagURL = JspPageToDocument.class.getClassLoader().getResource(SUN_TAG_CLASS); if (null != tagURL) { // Bug 876 // Not all app servers (ie WebLogic 8.1) return // an actual JarURLConnection. URLConnection conn = tagURL.openConnection(); //ICE-3683: Special processing for JBoss 5 micro-container with VFS if (tagURL.getProtocol().equals("vfszip")) { String tagPath = tagURL.toExternalForm(); String jarPath = tagPath.substring(0, tagPath.indexOf(SUN_TAG_CLASS)); String tldPath = jarPath; if (namespaceURL.endsWith("html")) { tldPath += HTML_TLD_SUFFIX; } else if (namespaceURL.endsWith("core")) { tldPath += CORE_TLD_SUFFIX; } URL tldURL = new URL(tldPath); return tldURL.openConnection().getInputStream(); } if (conn instanceof JarURLConnection) { location = scanJar((JarURLConnection) conn, namespaceURL); } else { //OSGi-based servers (such as GlassFishv3 and WebSphere7) //do not provide JarURLConnection to their resources so //we handle the JSF TLDs as a special case. if (namespaceURL.endsWith("html")) { location = getBundleLocation(tagURL, HTML_TLD_SUFFIX); } else if (namespaceURL.endsWith("core")) { location = getBundleLocation(tagURL, CORE_TLD_SUFFIX); } } } } if (null == location) { try { // scan WebSphere dirs for JSF jars String separator = System.getProperty("path.separator"); String wsDirs = System.getProperty("ws.ext.dirs"); String[] dirs = null; if (null != wsDirs) { dirs = wsDirs.split(separator); } else { dirs = new String[] {}; } Iterator theDirs = Arrays.asList(dirs).iterator(); while (theDirs.hasNext()) { String dir = (String) theDirs.next(); try { location = scanJars(dir, namespaceURL); } catch (Exception e) { //catch all possible exceptions including runtime exception //so that the rest of jars still can be scanned. } if (null != location) { break; } } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } } if (null == location) { //look for MyFaces implementation URL tagURL = JspPageToDocument.class.getClassLoader().getResource(MYFACES_TAG_CLASS); if (null != tagURL) { URLConnection conn = tagURL.openConnection(); if (conn instanceof JarURLConnection) { location = scanJar((JarURLConnection) conn, namespaceURL); } else { //OSGi-based servers (such as GlassFishv3 and WebSphere7) //do not provide JarURLConnection to their resources so //we handle the JSF TLDs as a special case. if (namespaceURL.endsWith("html")) { location = getBundleLocation(tagURL, HTML_TLD_SUFFIX); } else if (namespaceURL.endsWith("core")) { location = getBundleLocation(tagURL, CORE_TLD_SUFFIX); } } } } if (null == location) { String msg = "Can't find TLD for location [" + namespaceURL + "]. JAR containing the TLD may not be in the classpath"; log.error(msg); return null; } else { if (log.isTraceEnabled()) { for (int i = 0; i < location.length; i++) { log.trace("Found TLD location for " + namespaceURL + " = " + location[i]); } } } if (!location[0].endsWith("jar")) { InputStream tldStream = context.getResourceAsStream(location[0]); if (null == tldStream) { tldStream = (new URL(location[0])).openConnection().getInputStream(); } return tldStream; } else { // Tag library is packaged in JAR file URL jarFileUrl = new URL("jar:" + location[0] + "!/"); JarURLConnection conn = (JarURLConnection) jarFileUrl.openConnection(); conn.setUseCaches(false); conn.connect(); jarFile = conn.getJarFile(); ZipEntry jarEntry = jarFile.getEntry(location[1]); return jarFile.getInputStream(jarEntry); } }