<%-- CSA Receiver Page.jsp: Oracle EM Client System Analyzer "receiver" --%> <%@ page language="java" contentType="text/html" %> <%@ page import = "java.io.*" %> <%@ page import = "java.net.*" %> <%@ page import = "java.util.Enumeration" %> <%-- TEST ONLY imports ... --%> <%@ page import = "java.util.Date" %> <%@ page import = "java.text.SimpleDateFormat" %> Oracle EM Client System Analyzer "receiver" <%! class StreamProcessor extends Thread { InputStream is; String type; StreamProcessor(InputStream ins, String type) { this.is = ins; this.type = type; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = ""; while((line = br.readLine()) != null) { System.out.println("CSA Receiver: output type " + type + " is " + line); } br.close(); } catch(IOException e) { System.out.println("exception in type " + type); e.printStackTrace(); } } } %> <% String CSA_CONFIG_FILE_PATH = "CSA_CONFIG_FILE_PATH"; String csaJavaProperty = "csa.config_file_path"; // TBD: Specify no caching of JSP page??? response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 1); System.out.println("CSA Receiver Page: starting"); String httpMethod = request.getMethod(); int contentLen = request.getContentLength(); String sessionID = ""; long currTS = System.currentTimeMillis(); boolean XMLOutputDirError = false; // Configurable server XML output directory, etc ... String XMLOutputDir = ""; String outputEnabled = ""; int maxOutputFiles = 100; int maxFileSize = 100; //in KB String script = ""; String[] fileList = null; String fileSep = System.getProperty("file.separator"); long phfMaxAge = 60 * 60 * 24; // default is one day, in seconds // but is configurable option long msLastMod; // when file last updated/created, in ms since 1970 boolean scriptFailed = false; String sysOSProp = System.getProperty("os.name"); System.out.println("CSA Receiver Page: os name property is " + sysOSProp); //First we will implement our cleanup feature // Try reading config file ... //we should not bother to do anything unless this is a POST request if (httpMethod.equals("POST") && (contentLen > 0)) { try { int idx = -1; int idxEq = -1; int idxLb = -1; Process p; int envStatus = -1; String serverOS = System.getProperty("os.name"); String command = ""; String caPath = ""; caPath = System.getProperty(csaJavaProperty); System.out.println("CSA Receiver Page: caPath from system property is " + caPath); if((caPath == null) || (caPath.equals(""))) { if(serverOS.indexOf("Windows") != -1) { command = "cmd.exe /c set"; } else { command = "env"; } try { p = Runtime.getRuntime().exec(command); BufferedReader envReader = new BufferedReader( new InputStreamReader( p.getInputStream())); String line; while((line = envReader.readLine()) != null) { //System.out.println(line); int eqIdx = line.indexOf("="); String var = line.substring(0, eqIdx); String val = line.substring(eqIdx + 1); if(var.equals(CSA_CONFIG_FILE_PATH)) { caPath = val; System.out.println("CSA Receiver Page: CAPATH from env is " + caPath); break; } } envReader.close(); } catch(Exception e) { System.out.println("exception running script"); e.printStackTrace(); } if((caPath == null) || (caPath.equals(""))) { caPath = application.getRealPath("/csa_config/CSA.config"); } } // Construct CSA.config file spec from current CSA Receiver Page.jsp spec, // and note the idx-1 slight of hand ... File icf = new File(caPath); if (icf.exists()) { BufferedReader icfbr = new BufferedReader(new FileReader(icf)); String cfLine; while ((cfLine = icfbr.readLine()) != null) { idxEq = cfLine.indexOf("="); idxLb = cfLine.indexOf("#"); if (cfLine.trim().startsWith("XMLOutputDir")) { try { // Allow for trailing comments (ie starting with #) ... if (idxLb > idxEq) { XMLOutputDir = cfLine.substring(idxEq+1, idxLb).trim(); } else // no trailing comment { XMLOutputDir = cfLine.substring(idxEq+1).trim(); } } catch (Exception e) { XMLOutputDir = ""; } } else if (cfLine.trim().startsWith("maxOutputFiles")) { try { // Allow for trailing comments (ie starting with #) ... if (idxLb > idxEq) { maxOutputFiles = Integer.parseInt( cfLine.substring(idxEq+1, idxLb).trim()); } else // no trailing comment { maxOutputFiles = Integer.parseInt( cfLine.substring(idxEq+1).trim()); } } catch (Exception e) { } } else if(cfLine.trim().startsWith("maxFileSize")) { try { if (idxLb > idxEq) { maxFileSize = Integer.parseInt( cfLine.substring(idxEq+1, idxLb).trim()); } else // no trailing comment { maxFileSize = Integer.parseInt( cfLine.substring(idxEq+1).trim()); } } catch (Exception e) { } } else if(cfLine.trim().startsWith("outputEnabled")) { if(idxLb > idxEq) { outputEnabled = cfLine.substring(idxEq+1, idxLb).trim(); } else { outputEnabled = cfLine.substring(idxEq+1).trim(); } } else if(cfLine.trim().startsWith("script")) { if(idxLb > idxEq) { script = cfLine.substring(idxEq+1, idxLb).trim(); } else { script = cfLine.substring(idxEq+1).trim(); } } else if(cfLine.trim().startsWith("phfMaxAge")) { try { if(idxLb > idxEq) { phfMaxAge = Long.parseLong(cfLine.substring(idxEq+1, idxLb).trim()); } else { phfMaxAge = Long.parseLong(cfLine.substring(idxEq+1).trim()); } } catch(Exception e) { phfMaxAge = 60 * 60 * 24; // default to one day (in sec) } } } icfbr.close(); } } catch (Exception e) { XMLOutputDir = application.getRealPath("/"); } //if no xmloutput dir was specified in the config file, we assume that //the output dir is our current directory if((XMLOutputDir == null) || XMLOutputDir.equals("")) { System.out.println("CSA Receiver Page: setting default output dir"); XMLOutputDir = application.getRealPath("/"); } // Make sure that non-blank XMLOutputDir ends in fileSep (eg "/") ... if (!XMLOutputDir.equals("") && !XMLOutputDir.endsWith(fileSep)) { XMLOutputDir += fileSep; } File xod = new File(XMLOutputDir); // System.out.println("XML OUTPUT DIR IS " + XMLOutputDir); if((xod == null) || !xod.exists() || !xod.isDirectory() || !xod.canWrite()) { XMLOutputDirError = true; System.out.println("XML output error has occurred"); } else { System.out.println("xml output directory exists"); } if(XMLOutputDirError) { System.out.println("XML output directory error has occurred"); %>

csaPostStatus=1 <% } else { // System.out.println("No XML output errors"); if(!(outputEnabled == "false")) { // Try processing any posted data ... try { // Note during development: if path to output file isn't specified, // then for server in ADE view the output file will be created in: // - $AVR/emdw directory for 10iBeta view // - j2ee/home for a 4.0.1 emdw label // Get reader for request body and read first line ... BufferedReader ibr = request.getReader(); String line = ibr.readLine(); int byteLength = 0; // First line from request body should be CSA.jsp session ID ... if ((line != null) && line.trim().startsWith("sessionID")) { byteLength += line.getBytes().length; sessionID = line.substring(line.indexOf("=")+1).trim(); // Verify that CSA.jsp created a placeholder file on server; // if not then don't output XML file to server ... String phFile = ""; String outputFile = ""; phFile = XMLOutputDir + "pCSA" + sessionID + currTS + ".xml"; boolean isAN=true; final char[] chars = phFile.toCharArray(); for (int x = 0; x < chars.length; x++) { final char c = chars[x]; if ((c >= 'a') && (c <= 'z')) continue; // lowercase if ((c >= 'A') && (c <= 'Z')) continue; // uppercase if ((c >= '0') && (c <= '9')) continue; // numeric isAN = false; break; } if (!isAN) throw new Exception ("Invalid sessionID.."); outputFile = XMLOutputDir + "CSA" + sessionID + currTS + ".xml"; System.out.println("CSA Receiver Page: placeholder file is " + phFile); System.out.println("CSA Receiver Page: output file is " + outputFile); File phf = new File(phFile); File opf = new File(outputFile); PrintWriter fpw = new PrintWriter( new BufferedWriter( new FileWriter(phFile, true))); // Read (rest of) request body and write to output ... while ( ((line = ibr.readLine()) != null) && ((byteLength / 1024) <= maxFileSize) ) { // Since applet did URLEncoder.encode, must decode here ... byteLength += line.getBytes().length; fpw.println(URLDecoder.decode(line)); } // Close the input buffered reader and the output PrintWriter ... ibr.close(); fpw.close(); //now we check if the posted data was too big if((byteLength / 1024) > maxFileSize) { System.out.println("CSA Receiver Page:error file was too big"); System.out.println("CSA Receiver Page: size is " + (byteLength / 1024) + " max is " + maxFileSize); if(!phf.delete()) { System.out.println("CSA Receiver Page: ERROR: could not delete file"); } %>

csaPostStatus=3 <% } //end if file was too big else { //file isn't too big //the file wasn't too big, so we should process it //now, before we rename the file, we must run the user's script on the file if((script != null) && !script.equals("")) { //we assume that the script provided is the full path //so we should just set up the command and run it Process proc; int status = -1; String[] commands = {script, phFile}; try { proc = Runtime.getRuntime().exec(commands); //try to flush the output //and error streams //let's try to flush the output from the stream first StreamProcessor errProcessor = new StreamProcessor(proc.getErrorStream(), "error"); StreamProcessor outProcessor = new StreamProcessor( proc.getInputStream(), "out"); outProcessor.start(); errProcessor.start(); try { status = proc.waitFor(); System.out.println("script status is " + status); } catch (InterruptedException e) { System.out.println("Script interrupted"); scriptFailed = true; } if(status != 0) { scriptFailed = true; } } catch(Exception e) { System.out.println("exception running script"); e.printStackTrace(); scriptFailed = true; } } // Now rename the placeholder file to XML output file form ... if (phf.renameTo(opf)) { // Let applet know that post was apparently successful ... if(scriptFailed) { %>

csaPostStatus=6 <% } else { %>

csaPostStatus=0 <% } } else // file rename failed { %>

csaPostStatus=2

Warning: posted data was written to placeholder file '<%= phFile %>', but rename of placeholder to final output XML filename failed.

<% } //end else rename failed }//end else file wasn't too big }//end if file has session id // Else file doesn't begin with a sessionID else { %>

csaPostStatus=4 <% } //end else file has no session id }//end try catch (Exception e) { // TBD: it's better to leave any partial XML that may have already // been generated at the server by the time the exception occurred, // assuming that agent/loader will detect and report this error. // Just report the exception to the applet ... System.out.println("CSA Receiver Page: caught exception " + e.getMessage()); %>

csaPostStatus=5

Exception processing posted CSA data

<% }//end catch }//end if output enabled else { //the data will not get written, but the user doesn't need to know that %>

csaPostStatus=0 <% } }//end else no xml output directory errors //implement policy to clean up old output files if(!XMLOutputDirError) { try{ fileList = xod.list(); // System.out.println("FILE LIST LENGTH IS " + fileList.length); boolean outFilesExist = false; int numOutputFiles = 0; int fileIdx = 0; File currFile = null; String currFileName = null; long currAge = 0; long oldest = 0; int oldestIdx = 0; String oldestName = ""; for(fileIdx = 0; fileIdx < fileList.length; fileIdx++) { currFileName = fileList[fileIdx]; // System.out.println("" + fileIdx + ": " + currFileName); if(currFileName.startsWith("CSA") && currFileName.endsWith(".xml")) { try{ currFile = new File(XMLOutputDir + currFileName); oldest = currFile.lastModified(); numOutputFiles++; oldestIdx = fileIdx; oldestName = currFileName; break; } catch(Exception e) { System.out.println("exception while reading the file name"); e.printStackTrace(); } } } //now we've found the first file in the list that is a CSA file if(fileIdx < fileList.length) { //if the index was equal to the length, it means that there were //no output files at all outFilesExist = true; } if(outFilesExist) { // System.out.println("output files exist"); for( fileIdx = fileIdx + 1; fileIdx < fileList.length; fileIdx++) { currFileName = fileList[fileIdx]; // System.out.println("" + fileIdx + ": " + currFileName); if(currFileName.startsWith("CSA") && currFileName.endsWith(".xml")) { try{ currFile = new File(XMLOutputDir + currFileName); currAge = currFile.lastModified(); if(currAge < oldest) { oldest = currAge; oldestIdx = fileIdx; oldestName = currFileName; } numOutputFiles++; } catch(Exception e) { System.out.println("exception while reading the file name"); e.printStackTrace(); } } } // System.out.println("oldest index is " + oldestIdx); // System.out.println("oldest name is " + oldestName); // System.out.println("num output files is " + numOutputFiles + " max is " + maxOutputFiles); if(numOutputFiles > maxOutputFiles) { try { currFile = new File(XMLOutputDir + oldestName); if(!currFile.delete()) { System.out.println("ERROR in CSA Receiver: could not delete output file"); } } catch(Exception e) { System.out.println("Exception while trying to delete file"); } } } } catch(Exception e) { System.out.println("EXCEPTION IN GETTING FILE LIST"); e.printStackTrace(); } } // Just clean up any old (and perhaps extra) placeholder files; // post-4.1 these may be collected to log applet refusal ... try { File dirFile = new File(XMLOutputDir); String[] fileNameArray; String fileName; File aFile; int ii; // Existence, etc of XMLOutputDir was already verified in CSA.jsp; // but make sure that File version of XMLOutputDir is created ... if (dirFile != null) { // Get an array of filenames in the directory ... if (((fileNameArray = dirFile.list()) != null) && (fileNameArray.length > 0)) { for (ii = 0; ii < fileNameArray.length; ii++) { // Just look at pCSA*.xml files ... fileName = fileNameArray[ii]; if (fileName.startsWith("pCSA") && fileName.endsWith(".xml")) { aFile = new File(XMLOutputDir + fileName); // Not likely, but make sure this file isn't a directory ... if (aFile.isFile()) { msLastMod = aFile.lastModified(); // If this placeholder file is older than phfMaxAge limit, // then delete it ... if ((currTS - msLastMod) >= (phfMaxAge * 1000)) { aFile.delete(); } } } } } } } catch (Exception e) { %>

Exception processing out-dated placeholder files

<% } }//end if POST method %>