/* Show context number lines of string before and after target line. Add HTML formatting to bold the target line. */ String showScriptContextHTML(String s, int lineNo, int context) { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new StringReader(s)); int beginLine = Math.max(1, lineNo - context); int endLine = lineNo + context; for (int i = 1; i <= lineNo + context + 1; i++) { if (i < beginLine) { try { br.readLine(); } catch (IOException e) { throw new RuntimeException(e.toString()); } continue; } if (i > endLine) break; String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e.toString()); } if (line == null) break; if (i == lineNo) sb.append("<font color=\"red\">" + i + ": " + line + "</font><br/>"); else sb.append(i + ": " + line + "<br/>"); } return sb.toString(); }
/** * Permet de repondre a une requete web En affichant la liste des Spectacles et representations : * Utiliste JQuery javascript pour la mise en forme * * @param HttpServletRequest request requete * @param HttpServletResponse response reponse * @throw IOException, ServletException * @return void */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Get the session object HttpSession session = req.getSession(true); // Get the output stream ServletOutputStream out = res.getOutputStream(); res.setContentType("text/html"); out.println("<HEAD><TITLE>Reservation de tickets </TITLE></HEAD><BODY>"); out.println("<h1> Reservations de tickets </h1>"); out.println("<BODY bgproperties=\"fixed\" background=\"/images/rideau.JPG\">"); out.println("<p align=\"Right\"><font face=\"Monotype Corsiva\"style=\"font-size: 16pt\">"); try { // Open the file that is the first // command line parameter String relativeWebPath = "/WEB-INF/files/JAVASCRIPTPROG.txt"; String absoluteDiskPath = this.getServletContext().getRealPath(relativeWebPath); File file = new File(absoluteDiskPath); FileInputStream fstream = new FileInputStream(file); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console out.println(strLine); } // Close the input stream in.close(); } catch (Exception e) { // Catch exception if any out.println("Error: " + e.getMessage()); } if (session.isNew() || session.getAttribute("session.PanierListe") == null) out.println("<a href=\"admin/admin.html\">Caddie (vide)</a></font><br></p>"); else if (session.getAttribute("session.PanierListe") != null) if (((PanierListe) session.getAttribute("session.PanierListe")).getSize() > 0) out.println( "<a href=\"admin/admin.html\">afficher caddie(" + ((PanierListe) session.getAttribute("session.PanierListe")).Liste.size() + "Representations dans le panier)" + "</a></font><br></p>"); try { Utilisateur user = Utilitaires.Identification(this); out.println(Utilitaires.AffichageAchat(user)); } catch (Exception e) { out.println(e.getMessage()); } out.println("</BODY>"); out.close(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * // Create path components to save the file final String path = * request.getParameter("destination"); final Part filePart = * request.getPart("file"); final String fileName = * getFileName(filePart); */ String path = request.getContextPath(); String csvFileToRead = request.getRealPath("/") + "mail.csv"; BufferedReader br = null; String line = ""; String splitBy = ","; JSONArray jArrayMails = new JSONArray(); try { br = new BufferedReader(new FileReader(csvFileToRead)); while ((line = br.readLine()) != null) { jArrayMails.add(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } response.setContentType("application/json"); PrintWriter out = response.getWriter(); JSONObject jobj = new JSONObject(); jobj.put("studentEmailsArray", jArrayMails); out.print(jobj); }
public static List<String> readConfig(Path path, Configuration conf) throws IOException { final FileSystem fs = FileSystem.get(conf); final BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(path))); try { final ArrayList<String> addrs = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { addrs.add(line); } return addrs; } finally { reader.close(); } }
/** @service the servlet service request. called once for each servlet request. */ public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException { String name; String value[]; String val; servRes.setHeader("AUTHORIZATION", "user fred:mypassword"); ServletOutputStream out = servRes.getOutputStream(); HttpSession session = servReq.getSession(true); session.setAttribute("timemilis", new Long(System.currentTimeMillis())); if (session.isNew()) { out.println("<p> Session is new "); } else { out.println("<p> Session is not new "); } Long l = (Long) session.getAttribute("timemilis"); out.println("<p> Session id = " + session.getId()); out.println("<p> TimeMillis = " + l); out.println("<H2>Servlet Params</H2>"); Enumeration e = servReq.getParameterNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); value = servReq.getParameterValues(name); out.println(name + " : "); for (int i = 0; i < value.length; ++i) { out.println(value[i]); } out.println("<p>"); } out.println("<H2> Request Headers : </H2>"); e = servReq.getHeaderNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); val = (String) servReq.getHeader(name); out.println("<p>" + name + " : " + val); } try { BufferedReader br = servReq.getReader(); String line = null; while (null != (line = br.readLine())) { out.println(line); } } catch (IOException ie) { ie.printStackTrace(); } session.invalidate(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); String location = URLDecoder.decode(request.getParameter("location")); String type = URLDecoder.decode(request.getParameter("type")); String unit = URLDecoder.decode(request.getParameter("unit")); String awsURL = "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location=" + URLEncoder.encode(location) + "&type=" + type + "&unit=" + unit; // out.write(awsURL); String myurl = URLEncoder.encode(awsURL); // out.write("\n"+myurl); URL url = new URL(awsURL); URLConnection urlConnection = url.openConnection(); InputStream awsResponse = urlConnection.getInputStream(); InputStreamReader iSReader = new InputStreamReader(awsResponse); StringBuffer sb = new StringBuffer(); String xmlLine; BufferedReader buf = new BufferedReader(iSReader); try { while ((xmlLine = buf.readLine()) != null) { sb.append(xmlLine); } } catch (IOException ex) { ex.printStackTrace(); } xmlLine = sb.toString(); response.setContentType("application/json; charset=UTF-8"); int indent = 6; try { JSONObject jsonObj = XML.toJSONObject(xmlLine); String json1 = jsonObj.toString(indent); out.write(json1); } catch (JSONException ex) { ex.printStackTrace(); } }
public static void main(String args[]) throws IOException { // Function References String path = "http://motherlode.ucar.edu:8081/thredds/radarServer/nexrad/level3/IDD/dataset.xml"; try { catURI = new URI(StringUtil2.escape(path, "/:-_.")); } catch (URISyntaxException e) { System.out.println("radarServer main: URISyntaxException=" + e.getMessage()); return; } // read the catalog System.out.println("radarServer main: full path=" + path); InputStream ios = null; try { URL url = new URL(path); ios = url.openStream(); // ios = new FileInputStream(path); // acat = factory.readXML(ios, catURI ); BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios)); while (true) { String line = dataIS.readLine(); if (line == null) break; System.out.println(line); } } catch (Throwable t) { System.out.println("radarServer main: Exception on catalog=" + path + " " + t.getMessage()); return; } finally { if (ios != null) { try { ios.close(); } catch (IOException e) { System.out.println("radarServer main: error closing" + path); } } } return; }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); int i, j; String amount = req.getParameter("amount"); String from = req.getParameter("from"); String to = req.getParameter("to"); String ch = req.getParameter("choice"); String answer, answer1, answer2, answer3; if ("INFO".equals(ch)) { Redirect_info newurl = (Redirect_info) getServletContext().getAttribute("redirect"); res.sendRedirect(newurl.getUrl()); } else { out.println("<html>"); out.println("<title>Currency Converter</title>"); String addr = "http://www.google.com/ig/calculator?hl=en&q=" + amount + from + "=?" + to; URL convert = new URL(addr); BufferedReader in = new BufferedReader(new InputStreamReader(convert.openStream())); answer = in.readLine(); answer = new String(answer.getBytes("ISO-8859-1"), "ISO-8859-7"); from = new String(from.getBytes("ISO-8859-1"), "ISO-8859-7"); to = new String(to.getBytes("ISO-8859-1"), "ISO-8859-7"); amount = new String(amount.getBytes("ISO-8859-1"), "ISO-8859-7"); in.close(); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(i + 1); i = answer.indexOf('"'); answer = answer.substring(0, i); out.println("<p ALIGN=CENTER>" + amount + " " + from + " == " + answer + "(" + to + ")</p>"); out.println("</body>"); out.println("</html>"); } }
// ***************************************************** // Process the initial request from Proshop_main // ***************************************************** // @SuppressWarnings("deprecation") public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // Prevent caching so sessions are not mangled // resp.setHeader("Pragma", "no-cache"); // for HTTP 1.0 resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // for HTTP 1.1 resp.setDateHeader("Expires", 0); // prevents caching at the proxy server resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); HttpSession session = SystemUtils.verifyPro(req, out); // check for intruder if (session == null) { return; } String club = (String) session.getAttribute("club"); // get club name String templott = (String) session.getAttribute("lottery"); // get lottery support indicator int lottery = Integer.parseInt(templott); // // Call is to display the new features page. // // Display a page to provide a link to the new feature page // out.println("<html><head>"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">"); out.println("<meta http-equiv=\"Content-Language\" content=\"en-us\">"); out.println("<title> \"ForeTees Proshop Announcement Page\"</title>"); // out.println("<link rel=\"stylesheet\" href=\"/" +rev+ "/web utilities/foretees.css\" // type=\"text/css\"></link>"); out.println( "<script language=\"JavaScript\" src=\"/" + rev + "/web utilities/foretees.js\"></script>"); out.println("</head>"); out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\">"); SystemUtils.getProshopSubMenu(req, out, lottery); File f; FileReader fr; BufferedReader br; String tmp = ""; String path = ""; try { path = req.getRealPath(""); tmp = "/proshop_features.htm"; // "/" +rev+ f = new File(path + tmp); fr = new FileReader(f); br = new BufferedReader(fr); if (!f.isFile()) { // do nothing } } catch (FileNotFoundException e) { out.println("<br><br><p align=center>Missing New Features Page.</p>"); out.println("</BODY></HTML>"); out.close(); return; } catch (SecurityException se) { out.println("<br><br><p align=center>Access Denied.</p>"); out.println("</BODY></HTML>"); out.close(); return; } while ((tmp = br.readLine()) != null) out.println(tmp); br.close(); out.println("</BODY></HTML>"); out.close(); } // end of doGet
/* * Procesamiento de peticiones GET y POST * @param request * @param response * @throws ServletException * @throws IOException */ public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Comprobar si es un GET if (request.getMethod().equalsIgnoreCase("GET")) { return; } // Se trata de un POST // La respuesta es JSON response.setContentType("application/json; charset=UTF-8"); // Crear los filtros definidos para todos los servicios es.tid.frawa.service.servlet.Filter[] filters = new es.tid.frawa.service.servlet.Filter[0]; PrintWriter output = null; StringBuffer input = null; String action = ""; try { // Crea una sesión si no existe (esta opción está marcada en el modelo de servicios) request.getSession(true); // Invocar el método startService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].startService(request, response); } // Invocar el método frawaService() de la clase derivada (si está implementado) if (!frawaService(request, response)) { // Ha retornado false, por tanto abortamos el procesamiento del servicio return; } // Mensaje por defecto para los filtros que no necesitan el texto JSON StringBuffer soapStr = new StringBuffer(""); // Leer el mensaje JSON if (request.getParameter("JSONAction") != null && request.getParameter("JSONAction").length() > 0) { action = request.getParameter("JSONAction"); String tmp = request.getParameter("JSON"); if (tmp == null || tmp.length() == 0) { throw new Exception( getClass().getName() + ".service() JSONAction viene en la URL pero no viene el parámetro JSON con los datos"); } input = new StringBuffer(tmp); } else { action = request.getHeader("JSONAction"); if (action == null || action.length() == 0) { throw new Exception( getClass().getName() + ".service() La cabecera HTTP JSONAction no esta definida"); } // new es.tid.frawa.common.TdiFrawaTraceListener().trace(getClass().getName()+".service() // Leyendo mensaje JSON"); BufferedReader input_r = new BufferedReader(request.getReader()); input = new StringBuffer(); String line = input_r.readLine(); while (line != null) { input.append(line); line = input_r.readLine(); } } // Invocar el método beforeParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeParse(request, response, input.toString()); } // // Invocar al servicio adecuado en función del header JSONAction // if (action.equals("http://www.qualipso.org/advdoc/ws/storage/CreateFolder")) { // SERVICIO: CreateFolder // Parámetro de entrada al servicio CreateFolder_req inbean = new CreateFolder_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio CreateFolder_resp outbean = new CreateFolder_resp(); // Crear un objeto que implementa la operación CreateFolderService serviceImplementation = new CreateFolderService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: CreateFolder]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetFiles")) { // SERVICIO: GetFiles // Parámetro de entrada al servicio GetFiles_req inbean = new GetFiles_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio GetFiles_resp outbean = new GetFiles_resp(); // Crear un objeto que implementa la operación GetFilesService serviceImplementation = new GetFilesService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: GetFiles]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetSubFolders")) { // SERVICIO: GetSubFolders // Parámetro de entrada al servicio GetSubFolders_req inbean = new GetSubFolders_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio GetSubFolders_resp outbean = new GetSubFolders_resp(); // Crear un objeto que implementa la operación GetSubFoldersService serviceImplementation = new GetSubFoldersService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: GetSubFolders]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadBinaryFile")) { // SERVICIO: LoadBinaryFile // Parámetro de entrada al servicio LoadBinaryFile_req inbean = new LoadBinaryFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio LoadBinaryFile_resp outbean = new LoadBinaryFile_resp(); // Crear un objeto que implementa la operación LoadBinaryFileService serviceImplementation = new LoadBinaryFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: LoadBinaryFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadFile")) { // SERVICIO: LoadFile // Parámetro de entrada al servicio LoadFile_req inbean = new LoadFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio LoadFile_resp outbean = new LoadFile_resp(); // Crear un objeto que implementa la operación LoadFileService serviceImplementation = new LoadFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: LoadFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFile")) { // SERVICIO: RemoveFile // Parámetro de entrada al servicio RemoveFile_req inbean = new RemoveFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio RemoveFile_resp outbean = new RemoveFile_resp(); // Crear un objeto que implementa la operación RemoveFileService serviceImplementation = new RemoveFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: RemoveFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFolder")) { // SERVICIO: RemoveFolder // Parámetro de entrada al servicio RemoveFolder_req inbean = new RemoveFolder_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio RemoveFolder_resp outbean = new RemoveFolder_resp(); // Crear un objeto que implementa la operación RemoveFolderService serviceImplementation = new RemoveFolderService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: RemoveFolder]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreBinaryFile")) { // SERVICIO: StoreBinaryFile // Parámetro de entrada al servicio StoreBinaryFile_req inbean = new StoreBinaryFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio StoreBinaryFile_resp outbean = new StoreBinaryFile_resp(); // Crear un objeto que implementa la operación StoreBinaryFileService serviceImplementation = new StoreBinaryFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: StoreBinaryFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreFile")) { // SERVICIO: StoreFile // Parámetro de entrada al servicio StoreFile_req inbean = new StoreFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio StoreFile_resp outbean = new StoreFile_resp(); // Crear un objeto que implementa la operación StoreFileService serviceImplementation = new StoreFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: StoreFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestLoopback")) { // SERVICIO: TestLoopback // Parámetro de entrada al servicio org.qualipso.advdoc.ws.client.storage.beans.TestLoopback inbean = new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio org.qualipso.advdoc.ws.client.storage.beans.TestLoopback outbean = new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback(); // Crear un objeto que implementa la operación TestLoopbackService serviceImplementation = new TestLoopbackService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: TestLoopback]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestParser")) { // SERVICIO: TestParser // Parámetro de entrada al servicio org.qualipso.advdoc.ws.client.storage.beans.TestParser inbean = new org.qualipso.advdoc.ws.client.storage.beans.TestParser(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio org.qualipso.advdoc.ws.client.storage.beans.TestParser outbean = new org.qualipso.advdoc.ws.client.storage.beans.TestParser(); // Crear un objeto que implementa la operación TestParserService serviceImplementation = new TestParserService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: TestParser]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else { throw new Exception(getClass().getName() + ".service() Operación " + action + " no válida"); } } catch (ServletException e) { // Ha ocurrido un error en los filtros // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(e); new es.tid.frawa.common.TdiFrawaTraceListener().trace(e); // Enviar <Fault> al cliente if (output == null) { output = response.getWriter(); } TdiServiceException se = new TdiServiceException(-1, "Filter exception", e.getMessage()); sendError(output, se); } catch (Throwable t) { // Invocar el método onException() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].onException(request, response, t, "QualiPSoStorage", action); } // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(t); new es.tid.frawa.common.TdiFrawaTraceListener().trace(t); // Elevar una ServletException throw new ServletException( getClass().getName() + ".service() Server Exception: " + t.getClass().getName() + " -> " + t.getMessage()); // if (output == null) { // output = response.getWriter(); // } // TdiServiceException se = new TdiServiceException(-2,t.getClass().getName(),t.getMessage()); // sendError(output,se); } finally { // Invocar el método onFinally() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].onFinally(request, response, "QualiPSoStorage", action); } } }
public void init() throws ServletException { final String CONFIG_PATH = getServletContext().getRealPath("/") + "config.ini"; final String APPLICATION_NAME = getServletContext().getServletContextName(); BasicConfigurator.configure(); FileInputStream config_file = null; File config = new File(CONFIG_PATH); if (config.canRead()) { log.debug("Parsing " + CONFIG_PATH); try { config_file = new FileInputStream(CONFIG_PATH); } catch (java.io.FileNotFoundException e) { throw new ServletException(e); } Properties config_prop = new Properties(); try { config_prop.load(config_file); } catch (java.io.IOException e) { throw new ServletException(e); } this.config = config_prop; log.debug("Parsing finished"); } else { log.fatal("Error, cannot read " + CONFIG_PATH); } log.debug("maximumRecords : " + this.config.getProperty("default_maximumRecords")); log.debug("srw_header_file: " + this.config.getProperty("srw_header_file")); log.debug("srw_diag: " + this.config.getProperty("srw_diag_file")); // log.debug("server_list: " + this.config.getProperty("server_list")); try { FileReader fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_header_file")); BufferedReader in1 = new BufferedReader(fis); fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_footer_file")); BufferedReader in2 = new BufferedReader(fis); fis = new FileReader( getServletContext().getRealPath("/") + this.config.getProperty("srw_diag_file")); BufferedReader in3 = new BufferedReader(fis); try { String line = null; while ((line = in1.readLine()) != null) { this.SRW_HEADER = this.SRW_HEADER + line; } while ((line = in2.readLine()) != null) { this.SRW_FOOTER = this.SRW_FOOTER + line; } while ((line = in3.readLine()) != null) { this.SRW_DIAG = this.SRW_DIAG + line; } } finally { in1.close(); in2.close(); in3.close(); } } catch (IOException ex) { ex.printStackTrace(); } }
public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) { StringBuffer bodyContent = null; OutputStream out = null; PrintWriter writer = null; String serviceKey = null; try { BufferedReader in = req.getReader(); String line = null; while ((line = in.readLine()) != null) { if (bodyContent == null) bodyContent = new StringBuffer(); bodyContent.append(line); } } catch (Exception e) { } try { if (requireSession) { // check to see if there was a session created for this request // if not assume it was from another domain and blow up // Wrap this to prevent Portlet exeptions HttpSession session = req.getSession(false); if (session == null) { res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } serviceKey = req.getParameter("id"); // only to preven regressions - Remove before 1.0 if (serviceKey == null) serviceKey = req.getParameter("key"); // check if the services have been loaded or if they need to be reloaded if (services == null || configUpdated()) { getServices(res); } String urlString = null; String xslURLString = null; String userName = null; String password = null; String format = "json"; String callback = req.getParameter("callback"); String urlParams = req.getParameter("urlparams"); String countString = req.getParameter("count"); // encode the url to prevent spaces from being passed along if (urlParams != null) { urlParams = urlParams.replace(' ', '+'); } try { if (services.has(serviceKey)) { JSONObject service = services.getJSONObject(serviceKey); // default to the service default if no url parameters are specified if (urlParams == null && service.has("defaultURLParams")) { urlParams = service.getString("defaultURLParams"); } String serviceURL = service.getString("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } String apikey = ""; if (service.has("username")) userName = service.getString("username"); if (service.has("password")) password = service.getString("password"); if (service.has("apikey")) apikey = service.getString("apikey"); urlString = serviceURL + apikey; if (urlParams != null) urlString += "&" + urlParams; if (service.has("xslStyleSheet")) { xslURLString = service.getString("xslStyleSheet"); } } // code for passing the url directly through instead of using configuration file else if (req.getParameter("url") != null) { String serviceURL = req.getParameter("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } urlString = serviceURL; if (urlParams != null) urlString += urlParams; } else { writer = res.getWriter(); if (serviceKey == null) writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required."); else writer.write( "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not found."); writer.flush(); return; } } catch (Exception ex) { getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex); } Map paramsMap = new HashMap(); paramsMap.put("format", format); // do not allow for xdomain unless the context level setting is enabled. if (callback != null && allowXDomain) { paramsMap.put("callback", callback); } if (countString != null) { paramsMap.put("count", countString); } InputStream xslInputStream = null; if (urlString == null) { writer = res.getWriter(); writer.write( "XmlHttpProxyServlet parameters: id[Required] urlparams[Optional] format[Optional] callback[Optional]"); writer.flush(); return; } // default to JSON res.setContentType(responseContentType); out = res.getOutputStream(); // get the stream for the xsl stylesheet if (xslURLString != null) { // check the web root for the resource URL xslURL = null; xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString); // if not in the web root check the classpath if (xslURL == null) { xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString); } if (xslURL != null) { xslInputStream = xslURL.openStream(); } else { String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey + ". Please check the XMLHttpProxy configuration."; getLogger().severe(message); try { out.write(message.getBytes()); out.flush(); return; } catch (java.io.IOException iox) { } } } if (!isPost) { xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password); } else { if (bodyContent == null) getLogger() .info( "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content"); xhp.doPost( urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(), userName, password); } } catch (Exception iox) { iox.printStackTrace(); getLogger().severe("XmlHttpProxyServlet: caught " + iox); try { writer = res.getWriter(); writer.write(iox.toString()); writer.flush(); } catch (java.io.IOException ix) { ix.printStackTrace(); } return; } finally { try { if (out != null) out.close(); if (writer != null) writer.close(); } catch (java.io.IOException iox) { } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); PrintWriter webPageOutput = null; try { webPageOutput = response.getWriter(); } catch (IOException error) { Routines.writeToLog(servletName, "getWriter error : " + error, false, context); } HttpSession session = request.getSession(); session.setAttribute("redirect", request.getRequestURL() + "?" + request.getQueryString()); Connection database = null; try { database = pool.getConnection(servletName); } catch (SQLException error) { Routines.writeToLog(servletName, "Unable to connect to database : " + error, false, context); } if (Routines.loginCheck(true, request, response, database, context)) { return; } String server = context.getInitParameter("server"); boolean liveSever = false; if (server == null) { server = ""; } if (server.equals("live")) { response.setHeader("Refresh", "60"); } Routines.WriteHTMLHead( "View System Log", // title false, // showMenu 13, // menuHighLight false, // seasonsMenu false, // weeksMenu false, // scores false, // standings false, // gameCenter false, // schedules false, // previews false, // teamCenter false, // draft database, // database request, // request response, // response webPageOutput, // webPageOutput context); // context webPageOutput.println("<CENTER>"); webPageOutput.println( "<IMG SRC=\"../Images/Admin.gif\"" + " WIDTH='125' HEIGHT='115' ALT='Admin'>"); webPageOutput.println("</CENTER>"); pool.returnConnection(database); webPageOutput.println(Routines.spaceLines(1)); Routines.tableStart(false, webPageOutput); Routines.tableHeader("System Log", 0, webPageOutput); Routines.tableDataStart(true, false, false, true, true, 0, 0, "scoresrow", webPageOutput); boolean firstLine = true; int numOfLines = 0; try { String file = context.getRealPath("/"); FileReader logFile = new FileReader(file + "/Data/log.txt"); BufferedReader logFileBuffer = new BufferedReader(logFile); boolean endOfFile = false; while (!endOfFile) { String logFileText = logFileBuffer.readLine(); if (logFileText == null) { endOfFile = true; } else { if (firstLine) { firstLine = false; } else { webPageOutput.println(Routines.spaceLines(1)); } numOfLines++; webPageOutput.println(logFileText); } } logFileBuffer.close(); } catch (IOException error) { Routines.writeToLog(servletName, "Problem with log file : " + error, false, context); } Routines.tableDataEnd(false, true, true, webPageOutput); Routines.tableEnd(webPageOutput); if (numOfLines < 20) { webPageOutput.println(Routines.spaceLines(20 - numOfLines)); } Routines.WriteHTMLTail(request, response, webPageOutput); }
/** * Process an HTML get or post. * * @exception ServletException From inherited class. * @exception IOException From inherited class. */ public void scanOutXML( PrintWriter out, String strDirectory, String strFilename, String[] strPlus, String[] strMinus, boolean bExcludeParams, boolean bAnalyzeParams) throws IOException { File dir = new File(strDirectory + '/' + strFilename); if (dir.isDirectory()) return; try { FileReader is = new FileReader(strDirectory + '/' + strFilename); BufferedReader r = new BufferedReader(is); String string = null; Hashtable ht = new Hashtable(); Set setstrExtensions = new HashSet(); int iCount = 0; int iBytes = 0; while ((string = r.readLine()) != null) { StringTokenizer st = new StringTokenizer(string, " \"", false); Data data = new Data(); int iTokenCount = 0; while (st.hasMoreTokens()) { iTokenCount++; string = st.nextToken(); if (iTokenCount == IP) data.m_IP = string; if (iTokenCount == URL) { if (bExcludeParams) if (string.indexOf('?') != -1) string = string.substring(0, string.indexOf('?')); if (bAnalyzeParams) if (string.indexOf('?') != -1) string = string.substring(string.indexOf('?') + 1); data.m_URL = string; } if (iTokenCount == PROTOCOL) if (!string.startsWith("HTTP")) { data.m_URL += " " + string; iTokenCount--; } if (iTokenCount == BYTES) data.m_iBytes = Integer.parseInt(string); } if (!this.filterURL(data.m_URL, strPlus, strMinus, setstrExtensions)) continue; iCount++; iBytes += data.m_iBytes; if (ht.get(data.m_URL) == null) ht.put(data.m_URL, data); else { int iThisBytes = data.m_iBytes; data = (Data) ht.get(data.m_URL); data.m_iCount++; data.m_iBytes += iThisBytes; } } Comparator comparator = new Test(); TreeMap tm = new TreeMap(comparator); Iterator iterator = ht.values().iterator(); while (iterator.hasNext()) { Data data = (Data) iterator.next(); tm.put(new Integer(data.m_iCount), data); } out.println("<file>"); this.printXML(out, "directory", strDirectory); this.printXML(out, "name", strFilename); iterator = tm.values().iterator(); while (iterator.hasNext()) { out.println("<data>"); Data data = (Data) iterator.next(); this.printXML(out, "url", data.m_URL); this.printXML(out, "count", Integer.toString(data.m_iCount)); out.println("</data>"); } this.printXML(out, "hits", Integer.toString(iCount)); this.printXML(out, "bytes", Integer.toString(iBytes)); this.printXML(out, "unique", Integer.toString(tm.size())); iterator = setstrExtensions.iterator(); out.println("<extensions>"); while (iterator.hasNext()) { this.printXML(out, "extension", (String) iterator.next()); } out.println("</extensions>"); out.println("</file>"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, "error.jsp", true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\n\n\n\n\n"); org.jivesoftware.admin.AdminPageBean pageinfo = null; synchronized (request) { pageinfo = (org.jivesoftware.admin.AdminPageBean) _jspx_page_context.getAttribute("pageinfo", PageContext.REQUEST_SCOPE); if (pageinfo == null) { pageinfo = new org.jivesoftware.admin.AdminPageBean(); _jspx_page_context.setAttribute("pageinfo", pageinfo, PageContext.REQUEST_SCOPE); } } out.write('\n'); out.write('\n'); out.write('\n'); out.write('\n'); // Get parameters String log = ParamUtils.getParameter(request, "log"); String numLinesParam = ParamUtils.getParameter(request, "lines"); int numLines = ParamUtils.getIntParameter(request, "lines", 50); String mode = ParamUtils.getParameter(request, "mode"); // Only allow requests for valid log file names. if (!("debug".equals(log) || "warn".equals(log) || "info".equals(log) || "error".equals(log))) { log = null; } // Set defaults if (log == null) { log = "error"; } if (mode == null) { mode = "asc"; } if (numLinesParam == null) { numLinesParam = "50"; } // Other vars File logDir = new File(Log.getLogDirectory()); String filename = log + ".log"; File logFile = new File(logDir, filename); String lines[] = new String[0]; int start = 0; try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "UTF-8")); String line; int totalNumLines = 0; while ((line = in.readLine()) != null) { totalNumLines++; } in.close(); // adjust the 'numLines' var to match totalNumLines if 'all' was passed in: if ("All".equals(numLinesParam)) { numLines = totalNumLines; } lines = new String[numLines]; in = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "UTF-8")); // skip lines start = totalNumLines - numLines; if (start < 0) { start = 0; } for (int i = 0; i < start; i++) { in.readLine(); } int i = 0; if ("asc".equals(mode)) { while ((line = in.readLine()) != null && i < numLines) { line = StringUtils.escapeHTMLTags(line); line = parseDate(line); line = hilite(line); lines[i] = line; i++; } } else { int end = lines.length - 1; while ((line = in.readLine()) != null && i < numLines) { line = StringUtils.escapeHTMLTags(line); line = parseDate(line); line = hilite(line); lines[end - i] = line; i++; } } numLines = start + i; } catch (FileNotFoundException ex) { Log.info("Could not open (log)file.", ex); } out.write("\n\n<html>\n<head>\n <title>"); out.print(log); out.write( "</title>\n <meta name=\"decorator\" content=\"none\"/>\n <style type=\"text/css\">\n .log TABLE {\n border : 1px #ccc solid;\n }\n .log TH {\n font-family : verdana, arial, sans-serif;\n font-weight : bold;\n font-size : 8pt;\n }\n .log TR TH {\n background-color : #ddd;\n border-bottom : 1px #ccc solid;\n padding-left : 2px;\n padding-right : 2px;\n text-align : left;\n }\n .log .head-num {\n border-right : 1px #ccc solid;\n }\n .log TD {\n font-family : courier new,monospace;\n font-size : 9pt;\n background-color : #ffe;\n }\n .log .num {\n width : 1%;\n background-color : #eee !important;\n border-right : 1px #ccc solid;\n padding-left : 2px;\n padding-right : 2px;\n }\n .log .line {\n padding-left : 10px;\n }\n .hilite {\n color : #900;\n }\n .hilite-marker {\n background-color : #ff0;\n color : #000;\n font-weight : bold;\n }\n </style>\n"); out.write( "</head>\n<body>\n\n<div class=\"log\">\n<table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n<tr>\n <th class=\"head-num\">"); if (_jspx_meth_fmt_message_0(_jspx_page_context)) return; out.write( "</th>\n <th> </th>\n</tr>\n<tr>\n <td width=\"1%\" nowrap class=\"num\">\n "); if ("asc".equals(mode)) { out.write("\n "); for (int j = start + 1; j <= numLines; j++) { out.write("\n "); out.print(j); out.write("<br>\n "); } out.write("\n "); } else { out.write("\n "); for (int j = numLines; j >= start + 1; j--) { out.write("\n "); out.print(j); out.write("<br>\n "); } out.write("\n "); } out.write("\n </td>\n <td width=\"99%\" class=\"line\">\n "); for (String line1 : lines) { if (line1 != null) { out.write("\n <nobr>"); out.print(line1); out.write("\n </nobr>\n <br>\n\n "); } } out.write("\n </td>\n</tr>\n</table>\n</div>\n\n</body>\n</html>"); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { address = PAConfiguration.getAddress(); port = PAConfiguration.getPort(instantiation); poslAddress = PAConfiguration.getPOSL(instantiation, topic); rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation); messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic); } catch (BadConfigurationException e) { System.out.println(e.getMessage()); e.printStackTrace(); System.exit(0); } response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { System.out.println("5 Publicty Chair Servlet"); System.out.println(response.toString()); BufferedReader brd = request.getReader(); String input = ""; String message = ""; while (!input.equals("</RuleML>")) { input = brd.readLine(); message = message + input; } String[] varOrder = getVariableOrder(message); System.out.println("Received Message: " + message); // BackwardReasoner br = new BackwardReasoner(); // Iterator solit =null; // DefiniteClause dc = null; // SymbolTable.reset(); POSLParser pp = new POSLParser(); // String contents = "c(a).\nc(b).\nc(c)."; Date t1 = new GregorianCalendar().getTime(); System.out.println(t1.getHours() + ":" + t1.getMinutes()); // append time to contents System.out.println("day: " + t1.getDay()); System.out.println("day: " + t1.getYear()); System.out.println("day: " + t1.getMonth()); // time String time = "time(" + t1.getHours() + ":integer)."; System.out.println(time); String url = poslAddress; // String url = "http://www.jdrew.org/oojdrew/test.posl"; String contents = ""; // day of the week int day = t1.getDay(); boolean weekday = true; if (day == 0 || day == 6) { weekday = false; } String dayOfWeek; if (weekday) { dayOfWeek = "day(weekday)."; } else { dayOfWeek = "day(weekend)."; } // full date Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day2 = cal.get(Calendar.DAY_OF_MONTH); String date; String day3 = "" + day2; if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8 || day2 == 9) { day3 = "0" + day2; } if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3; else date = "" + year + "0" + month + day3; date = "date(" + date + ":integer)."; System.out.println(date); String url2 = rdfAddress; HttpClient client2 = new HttpClient(); GetMethod method2 = new GetMethod(url2); method2.setFollowRedirects(true); String typestr = ""; // Execute the GET method int statusCode2 = client2.executeMethod(method2); if (statusCode2 != -1) { typestr = method2.getResponseBodyAsString(); } System.out.println("Types: " + typestr); Types.reset(); RDFSParser.parseRDFSString(typestr); try { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method.setFollowRedirects(true); // Execute the GET method int statusCode = client.executeMethod(method); if (statusCode != -1) { contents = method.getResponseBodyAsString(); } } catch (Exception e) { e.printStackTrace(); } contents = contents + "\n" + time; contents = contents + "\n" + dayOfWeek; contents = contents + "\n" + date; BackwardReasoner br = new BackwardReasoner(); Iterator solit = null; DefiniteClause dc = null; SymbolTable.reset(); pp.parseDefiniteClauses(contents); br.loadClauses(pp.iterator()); System.out.println("TEST"); Iterator it = pp.iterator(); while (it.hasNext()) { DefiniteClause d = (DefiniteClause) it.next(); System.out.println("Loaded clause: " + d.toPOSLString()); } br = new BackwardReasoner(br.clauses, br.oids); MessageParser m = new MessageParser(message); Element atom = null; try { atom = m.parseForContent(); } catch (Exception e) { System.out.println("Invalid Message"); // out.flush(); } QueryBuilder q = new QueryBuilder(atom); String query = q.generateDoc(); System.out.println("ABOUT TO INPUT THIS QUERY:" + query); RuleMLParser qp = new RuleMLParser(); try { dc = qp.parseRuleMLQuery(query); } catch (Exception e) { System.out.println("Invalid Query"); // out.flush(); } // solit = br.iterativeDepthFirstSolutionIterator(dc); solit = br.iterativeDepthFirstSolutionIterator(dc); int varSize = 0; while (solit.hasNext()) { Vector data = new Vector(); BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next(); Hashtable varbind = gl.varBindings; javax.swing.tree.DefaultMutableTreeNode root = br.toTree(); root.setAllowsChildren(true); javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root); int i = 0; Object[][] rowdata = new Object[varbind.size()][2]; varSize = varbind.size(); Enumeration e = varbind.keys(); while (e.hasMoreElements()) { Object k = e.nextElement(); Object val = varbind.get(k); String ks = (String) k; rowdata[i][0] = ks; rowdata[i][1] = val; i++; } data.addElement(rowdata); String[] messages = new String[data.size()]; MessageGenerator g = new MessageGenerator( data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder); messages = g.Messages2(); String appender = ""; URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); for (int i1 = 0; i1 < data.size(); i1++) { System.out.println(i1 + ")" + messages[i1].toString()); props.put("text", messages[i1].toString()); InputStream in = msg.sendGetMessage(props); } System.out.println("NEXT MESSAGE"); } MessageGenerator g = new MessageGenerator( null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel()); URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); String finalMessage = g.finalMessage(query); System.out.println(finalMessage); props.put("text", finalMessage); InputStream in = msg.sendGetMessage(props); System.out.println("Stop_Communication"); } catch (Exception e) { System.out.println("ERROR has occured : " + e.toString()); } out.close(); }