Java Projects
Grails Projects
|
PROJECT NAME: CommonFunctions
Common Functions is my Main Project Folder, This is where I put most of my not branching project or simple single class projects
AlphabetIncrement.java
/**------------------------------------------------------------------------------------
* Create Date: Aug 23, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Demostrate the way to count A-Z * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Aug 23, 2006 CLEUNG com.churkleung.CommonFunctions.AlphabetIncrement *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; /** * @author Churk Leung * */ public class AlphabetIncrement { /** * Printing A-Z using char and ascii values as incrementers * @param args */ public static void main(String[] args) { AlphabetIncrement alphabetIncrement = new AlphabetIncrement(); alphabetIncrement.performAction(); } public void performAction(){ char alphabet = 'A'; int a = (int) alphabet; for (int i = 0; i < 26; i++){ if (i+1%26 == 0) { System.out.println(""); } System.out.print(" " + alphabet++); System.out.print((char)(a+i)); } } } ClearTempFiles.java
/**------------------------------------------------------------------------------------
* Create Date: Aug 23, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Delete all temp files in temp file directories * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Aug 23, 2006 CLEUNG com.churkleung.CommonFunctions.ClearTempFiles *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.File; /** * @author Churk Y. Leung */ public class ClearTempFiles { /** * Main Function where the program begins * @param args this program takes no arguments */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Not valid # of arguements"); System.exit(0); } else { for (int i = 0; i < args.length; i++) { ClearTempFiles.execute(args[i]); } System.out.println("Clean up completed"); } } /** * Private method so that nothing else can be running the deletion * @param Directory The main directory to delete */ private static void execute(String Directory) { File profileDirectory = new File(Directory); String[] profileSubDir = profileDirectory.list(); for (int i = 0; i < profileSubDir.length; i++) { if (!profileSubDir[i].trim().equalsIgnoreCase("Default User") || !profileSubDir[i].trim().equalsIgnoreCase("All Users") || !profileSubDir[i].trim().equalsIgnoreCase(System.getProperty("user.name"))) { File current = new File(Directory + "/" + profileSubDir[i]); System.out.println("Deleting " + Directory + "/" + profileSubDir[i]); if (current.isDirectory()) { deleteDir(current); } else { current.delete(); } System.out.println(" .....Successful"); } } } /** * Delete directorys recursively * @param dir Directory as a file object * @return true or false on successful deletion */ private static boolean deleteDir(File dir) { try { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i if (!success) { return false; } } } } catch (Exception e) { System.out.println(dir.toString() + " was not deleted"); return true; } // The directory is now empty so delete it return dir.delete(); } } Commands.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 7, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.Commands *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; /** * @author Churk Leung * Commands interface */ public interface Commands { public void execute(); } CommonConfig.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 7, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.CommonConfig *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.File; import java.net.URL; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; /** * @author Churk Leung * CommonConfig Sets all the common configurations so that the entire program can use */ public class CommonConfig { private String logDirectory; private String zipFileName; private List private List public final int SECONDS = 1000; public final int MINUTE = 60000; private int frequency; // How frequent does the monitor run private URL url; private int maxRetry; private int httpTimeOut; // HTTP Request Time out private String expectedResponse; private String templatePlayerRequest; private List private List private List /** * Check Rather the passed in file exist or not * @param filename File is is being Check rather it exist or not * @return Boolean Value */ public boolean fileExist(String filename){ File file = new File(filename); return (file.exists()); } /** * * @param filename */ public void removeFileIfExist(String filename){ File file = new File(filename); if (file.exists()){ file.delete(); } } /** * Print out the list * @param list */ public void printList(List for (Iterator System.out.println(iter.next()); } } /** * @return String */ public String getLogDirectory(){ return logDirectory; } /** * * @param logDirectory */ public void setLogDirectory(String logDirectory){ this.logDirectory = logDirectory; } /** * @return String */ public String getZipFileName(){ Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DAY_OF_MONTH); return zipFileName + month + "_" + day + "_" + year + ".zip"; } /** * * @param zipFileName */ public void setZipFileName(String zipFileName){ this.zipFileName = zipFileName; } /** * @return Returns the filesToZip. * @uml.property name="filesToZip" */ public List /** * @param filesToZip The filesToZip to set. * @uml.property name="filesToZip" */ public void setFilesToZip(List /** * * @param filename filepath in a String */ public void addZippedFiles(String filename){ zippedFiles.add(filename); } /** * * @return List of zippedFiles filepaths */ public List /** * @param zippedFiles The zippedFiles to set. */ public void setZippedFiles(List /** * @return Returns the url. * @uml.property name="url" */ public URL getUrl(){ return url; } /** * @param url The url to set. * @uml.property name="url" */ public void setUrl(URL url){ this.url = url; } /** * @return Returns the frequency. * @uml.property name="frequency" */ public int getFrequency(){ return frequency; } /** * @param frequency The frequency to set. * @uml.property name="frequency" */ public void setFrequency(int frequency){ this.frequency = frequency; } /** * @return Returns the maxRetry. * @uml.property name="maxRetry" */ public int getMaxRetry(){ return maxRetry; } /** * @param maxRetry The maxRetry to set. * @uml.property name="maxRetry" */ public void setMaxRetry(int maxRetry){ this.maxRetry = maxRetry; } /** * @return Returns the httpTimeOut. * @uml.property name="httpTimeOut" */ public int getHttpTimeOut(){ return httpTimeOut; } /** * @param httpTimeOut The httpTimeOut to set. * @uml.property name="httpTimeOut" */ public void setHttpTimeOut(int httpTimeOut){ this.httpTimeOut = httpTimeOut; } /** * @return Returns the expectedResponse. */ public String getExpectedResponse() { return expectedResponse; } /** * @param expectedResponse The expectedResponse to set. */ public void setExpectedResponse(String expectedResponse) { this.expectedResponse = expectedResponse; } /** * @return Returns the templatePlayerRequest. */ public String getTemplatePlayerRequest() { return templatePlayerRequest; } /** * @param templatePlayerRequest The templatePlayerRequest to set. */ public void setTemplatePlayerRequest(String templatePlayerRequest) { this.templatePlayerRequest = templatePlayerRequest; } /** * @return List */ public List /** * @param myHelperCommands */ public void setMyHelperCommands(List /** * @return List */ public List /** * * @param dataGatherCommands */ public void setDataGatherCommands(List /** * @return List */ public List /** * * @param monitoringCommands */ public void setMonitoringCommands(List } CreateConnection.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 8, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 08, 2005 CLEUNG com.churkleung.CommonFunctions.CreateConnection *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; /** * @author Churk Leung * This creates a connection by the passed in URL and Timeout Request time. */ public class CreateConnection { private String data; private URLConnection conn; private final int MINUTE = 60000; /** * This Constructor creates a connection to the URL * @param url * @param httpTimeOut * @throws IOException * @throws IOException */ public CreateConnection(URL url, int httpTimeOut) throws IOException{ //Construct data data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8") + "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); conn = url.openConnection(); conn.setDoOutput(true); // Sets the connection and Reading of the webpage timeout conn.setReadTimeout(httpTimeOut*MINUTE); conn.setConnectTimeout(httpTimeOut*MINUTE); } /** * @return Returns the conn. */ public URLConnection getConn() { return conn; } /** * @param conn The conn to set. */ public void setConn(URLConnection conn) { this.conn = conn; } /** * @return Returns the data. */ public String getData() { return data; } /** * @param data The data to set. */ public void setData(String data) { this.data = data; } } DecompileJar.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 7, 2005 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.DecompileJar *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.zip.Deflater; import java.util.zip.ZipEntry; /** * @author Churk Leung */ public class DecompileJar { /** * @param args */ public static void main(String[] args) { DecompileJar decompileJar = new DecompileJar(); String pathString = args[0].replace("\\", "/"); File path = new File(pathString); if (!path.canRead() || !path.exists()) { System.out.println("Exit, Path is invalid"); } else { if (pathString.substring(pathString.length()-4).equalsIgnoreCase(".jar")) { try { File tempDir = new File(pathString.substring(0, pathString.length()-4)); // Extract the Jar Files decompileJar.extractJar(pathString, tempDir.toString()); // Delete the old Jar File decompileJar.deleteFile(pathString); // Decompile the class files decompileJar.processDir(tempDir); Thread.sleep(10000); // Rename all the file jad to java in the directory decompileJar.batchRename(tempDir.toString()); // Jar up the files FileOutputStream fileOutputStream = new FileOutputStream(pathString); JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream); jarOutputStream.setLevel(Deflater.BEST_COMPRESSION); decompileJar.zipFile(jarOutputStream, tempDir.toString(), tempDir); jarOutputStream.flush(); jarOutputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); // Delete the directory Thread.sleep(10000); // System.out.println("Deleting Dir"); decompileJar.deleteDir(tempDir); System.out.println("Finish!"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } else { if (path.isDirectory()) { String[] children = path.list(); for(int i = 0; i < children.length; i++) { if (children[i].substring(children[i].length()-4).equalsIgnoreCase(".jar")) { try { File tempDir = new File(path.toString().replace("\\", "/") + "/" + children[i].substring(0, children[i].length()-4)); // Extract the Jar Files decompileJar.extractJar(path.toString().replace("\\", "/") + "/" + children[i], tempDir.toString()); // Delete the old Jar File decompileJar.deleteFile(path.toString().replace("\\", "/") + "/" + children[i]); // Decompile the class files decompileJar.processDir(tempDir); // Rename all the file jad to java in the directory decompileJar.batchRename(tempDir.toString()); Thread.sleep(10000); // Jar up the files FileOutputStream fileOutPutStream = new FileOutputStream(path.toString().replace("\\", "/") + "/" + children[i]); JarOutputStream jarOutputStream = new JarOutputStream(fileOutPutStream); jarOutputStream.setLevel(Deflater.BEST_COMPRESSION); decompileJar.zipFile(jarOutputStream, tempDir.toString(), tempDir); jarOutputStream.flush(); jarOutputStream.close(); fileOutPutStream.flush(); fileOutPutStream.close(); // Delete the directory Thread.sleep(10000); // System.out.println("Deleting Dir"); decompileJar.deleteDir(tempDir); System.out.println("Finish!"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } } else { System.out.println("Exiting, Nothing to decompile"); } } } } /** * Extract a jar file * @param pathString path where the jar is * @param tempDir Where the files are being extracted * @return true or false on extracting the jar successfully */ public boolean extractJar(String pathString, String tempDir) { final int BUFFER = 2048; // Check rather tempDir exist, if not create it File workingDir = new File(tempDir); if (!workingDir.exists()) { workingDir.mkdirs(); } try { // Creating input and output streams ZipEntry entry; FileInputStream fileInputStream = new FileInputStream(pathString); JarInputStream jarInputStream = new JarInputStream(fileInputStream); while((entry = jarInputStream.getNextEntry()) != null) { if (entry.isDirectory()) { File currentDir = new File(tempDir + "/" + entry.getName()); if (!currentDir.exists()) { currentDir.mkdirs(); } continue; } // Double check for random directory errors File randomDir = new File(tempDir + "/" + entry.getName().substring(0,entry.getName().replace("\\", "/").lastIndexOf('/'))); if (!randomDir.exists()) { randomDir.mkdirs(); } int count; byte data[] = new byte[BUFFER]; FileOutputStream fileOutputStream = new FileOutputStream(tempDir + "/" + entry.getName()); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, BUFFER); while ((count = jarInputStream.read(data, 0, BUFFER)) != -1) { bufferedOutputStream.write(data, 0, count); } bufferedOutputStream.flush(); bufferedOutputStream.close(); fileOutputStream.flush(); fileOutputStream.close(); } jarInputStream.close(); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * Delete a file * @param path Path to the file * @return true or false on deleting the file successfully */ public boolean deleteFile(String path) { File currentFile = new File(path); return currentFile.delete(); } /** * Recursively calls it self until a file is found and process it. * @param dir * @return boolean on successful processing or not */ public boolean processDir(File dir){ boolean success = true; if (dir.isDirectory()){ String[] children = dir.list(); for (int i = 0; i < children.length; i++){ boolean temp = processDir(new File(dir, children[i])); if (!temp) { return false; } } } else { try { if (dir.toString().substring(dir.toString().length()-6).equalsIgnoreCase(".class")) { // System.out.print("Decompiling " + dir.getAbsolutePath()); File jadFile = new File(dir.toString().substring(0, dir.toString().length()-6) + ".jad"); if (jadFile.exists()) { jadFile.delete(); } Runtime.getRuntime().exec("jad158.exe -d " + dir.getParent().toString() + " " + dir.getAbsolutePath()); // System.out.println(" ..... Successful"); } } catch (IOException e) { e.printStackTrace(); success = false; } } return success; } /** * Zip up a list of files in a directory * @param jarOutputStream Output Jar File * @param originalFolder The parent Directory that contain all the files * @param listOfFiles List of file to zip * @return true or false on successful completion */ public boolean zipFile(JarOutputStream jarOutputStream, String originalFolder, File listOfFiles){ if (listOfFiles.isDirectory()) { String[] children = listOfFiles.list(); for (int i = 0; i < children.length; i++){ boolean temp = zipFile(jarOutputStream, originalFolder, new File(listOfFiles.toString().replace("\\", "/") + "/" + children[i])); if (!temp){ return false; } } } else { byte[] buffer = new byte[18024]; try { FileInputStream fileInputStream = new FileInputStream(listOfFiles.toString()); jarOutputStream.putNextEntry(new ZipEntry(listOfFiles.toString().replace("\\", "/").substring(originalFolder.length()+1))); // Write the file to zip int length; while((length = fileInputStream.read(buffer)) > 0){ jarOutputStream.write(buffer, 0, length); } // Close current Entry jarOutputStream.closeEntry(); fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } } return true; } /** * Renaming all files jad files in the directory * @param directory Directory * @return true or false */ public boolean batchRename(String directory) { File currentFile = new File(directory); if (currentFile.isDirectory()) { String[] children = currentFile.list(); for (int i = 0; i < children.length; i++) { boolean temp = batchRename(currentFile.toString().replace("\\", "/") + "/" + children[i]); if (!temp) { return false; } } } else { if (directory.substring(directory.length()-4).equalsIgnoreCase(".jad")) { File jadFile = new File(directory); File javaFile = new File(directory.toString().replace("\\", "/").substring(0, directory.length()-4) + ".java"); jadFile.renameTo(javaFile); } } return true; } /** * Delete directorys recursively * @param dir Directory as a file object * @return true or false on successful deletion */ public boolean deleteDir(File dir) { try { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i if (!success) { return false; } } } } catch (Exception e) { // System.out.println(dir.toString() + " was not deleted"); return true; } // The directory is now empty so delete it // System.out.println("Deleting: " + dir.toString()); return dir.delete(); } } DeleteFileByType.java
/**------------------------------------------------------------------------------------
* Create Date: Jan 19, 2007 * Author: Churk Leung * * Delete files by type. So delete all .txt files * Same as rm -rf `find . -iname "*.txt"` * * COPYRIGHT © [2007] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Jan 19, 2007 CLEUNG com.churkleung.CommonFunctionss.DeleteFileByType *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Churk Leung */ public class DeleteFileByType { private int totalFilesDelete = 0; /** * @param args */ public static void main(String[] args) { if (args.length < 2) { System.out.println("Expecting 2 arguments: Directory, and File Ending"); System.out.println("Usage: DeleteFileByType (Directory) (file Ending)"); return; } else { DeleteFileByType deleteFileByType = new DeleteFileByType(); deleteFileByType.performWork(args); } } private boolean performWork(String[] args) { String pattern = args[1]; String debug; if (args.length > 2) { debug = args[2]; } else { debug = null; } File workingDirectory = new File(args[0]); if (!workingDirectory.exists()) { System.out.println("Directory does not exist, exiting"); return false; } boolean success = deleteDir(workingDirectory, pattern, debug); System.out.println("Total Files Delete: " + totalFilesDelete); return success; } private boolean deleteDir(File dir, String pattern, String debug) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i if (!success) { return false; } } } else { if (regExpFind(dir.getName(), pattern)){ System.out.println("Delete " + dir.getAbsolutePath()); if (debug == null || !debug.equalsIgnoreCase("debug")) { totalFilesDelete++; return dir.delete(); } } else { return true; } } return true; } /** * Using regular Expression to search a string * @param string the text to search * @param patternString The pattern to look for * @return found or not */ private boolean regExpFind( String string, String patternString){ Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(string); return matcher.find(); } } DeleteProfile.java
/**------------------------------------------------------------------------------------
* Create Date: Sep 2, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * This was written when I was working as the BAC, to delete all user profiles so this * will clear room for PC to work on. * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Sep 02, 2006 CLEUNG com.churkleung.CommonFunctions.DeleteProfile *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.File; /** * @author Churk Y. Leung */ public class DeleteProfile { /** * Main Function where the program begins * @param args this program takes no arguments */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Not valid # of arguements"); System.exit(0); } else { for (int i = 0; i < args.length; i++) { DeleteProfile.execute(args[i]); } System.out.println("Clean up complete"); } } /** * Private method so that nothing else can be running the deletion * @param Directory The main directory to delete */ private static void execute(String Directory) { File profileDirectory = new File(Directory); String[] profileSubDir = profileDirectory.list(); for (int i = 0; i < profileSubDir.length; i++) { if (!profileSubDir[i].trim().equalsIgnoreCase("Default User") || !profileSubDir[i].trim().equalsIgnoreCase("All Users") || !profileSubDir[i].trim().equalsIgnoreCase(System.getProperty("user.name"))) { File current = new File(Directory + "/" + profileSubDir[i]); System.out.println("Deleting " + Directory + "/" + profileSubDir[i]); if (current.isDirectory()) { deleteDir(current); } else { current.delete(); } System.out.println(" .....Successful"); } } } /** * Delete directorys recursively * @param dir Directory as a file object * @return true or false on successful deletion */ private static boolean deleteDir(File dir) { try { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i if (!success) { return false; } } } } catch (Exception e) { System.out.println(dir.toString() + " was not deleted"); return true; } // The directory is now empty so delete it return dir.delete(); } } DiagnosticRunner.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 07, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.DiagnosticRunner *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.util.Iterator; /** * @author Churk Leung */ public class DiagnosticRunner { private Monitor monitor; /** * Default Constructor */ public DiagnosticRunner(){ monitor = new Monitor(); } /** * Constructor with Monitor Object * @param monitor */ DiagnosticRunner(Monitor monitor) { this.monitor = monitor; } /** * @param commonConfig */ @SuppressWarnings("unchecked") public void runDiagnostics(CommonConfig commonConfig) { //Check to see if the http request fail # consecutive times //If it is, start off the data gathering. if (shouldDiagnosticsBeRun(commonConfig, monitor)){ monitor.setStopMonitoring(true); System.out.println("System is about to crash, data gather process is beginning"); for (Iterator iter = commonConfig.getDataGatherCommands().iterator(); iter.hasNext();) { Commands cmd = (Commands) iter.next(); cmd.execute(); } } } /** * @param commonConfig * @param monitor * @return boolean */ public boolean shouldDiagnosticsBeRun(CommonConfig commonConfig, Monitor monitor) { return monitor.getCurrentQueue() >= commonConfig.getMaxRetry(); } /** * @return Returns the monitor. */ public Monitor getMonitor() { return monitor; } /** * @param monitor The monitor to set. */ public void setMonitor(Monitor monitor) { this.monitor = monitor; } } HttpRequestUtility.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 08, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 08, 2005 CLEUNG com.churkleung.CommonFunctions.Commands *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.security.Security; /** * @author Churk Leung * HttpRequestUtility Enables to user to ping a URL and see if it is active * isHttpRequestReponding Allow users to find out rather the URL is Active return true and false\ */ public class HttpRequestUtility implements Commands { private CommonConfig commonConfig; private Monitor monitor; /** * Let the user know rather the URL is responding or not * @param url * @param httpTimeOut * @param expectedResponse * @return boolean */ public boolean isHttpRequestReponding(URL url, int httpTimeOut, String expectedResponse){ boolean isResponding = false; CreateConnection connection = null; try { connection = new CreateConnection(url, httpTimeOut); } catch (IOException e1) { e1.printStackTrace(); return false; } try { writePostDataToHttpConnection(connection.getData(), connection.getConn()); isResponding = evaluateHttpResponse(connection.getConn(), expectedResponse); } catch (IOException e) { e.printStackTrace(); return false; } return isResponding; } /** * Lets the User know rather httpDataGather was successful or not. * @param url * @param filePath * @param httpTimeOut * @return true or false */ public boolean didHttpDataGatherSucceed(URL url, String filePath, int httpTimeOut){ boolean isGathering = false; //remove the file if already exist. commonConfig.removeFileIfExist(filePath); try{ CreateConnection connection = new CreateConnection(url, httpTimeOut); writePostDataToHttpConnection(connection.getData(), connection.getConn()); isGathering = writeHttpRequestToFile(url, filePath); } catch (Exception e){ e.printStackTrace(); System.out.println("Data Gathering for "+url+" was not successful"); } return isGathering; } /** * This function evaluate rather the Http Response matches with the expected Reponse * @param conn * @param expectedResponse * @return boolean * @throws IOException */ public boolean evaluateHttpResponse(URLConnection conn, String expectedResponse) throws IOException { boolean isCorrect = false; // Get the response String line; BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); if ((line = rd.readLine()) == null) { System.out.println("HTTP Request did not return any result"); } else if (line.equals(expectedResponse)){ isCorrect = true; } } finally { try { if (rd != null){ rd.close(); } } catch (IOException e) { e.printStackTrace(); } } return isCorrect; } /** * This function Setup the Output Stream Writer so the http Request can write to the output stream * This function in basic loads up the URL given by using the connection it is passed. * @param data * @param conn * @throws IOException */ public void writePostDataToHttpConnection(String data, URLConnection conn) throws IOException { OutputStreamWriter wr = null; try { wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); } finally { try { wr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * This function returns a true/false on rather it is able to gather information from a given URL * @param url URL that you want to get information from * @param filePath path and filename of the file that is going to be written * @return boolean * @throws IOException */ public boolean writeHttpRequestToFile(URL url, String filePath) throws IOException { boolean temp = false; // Get the response BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); String tempString = null; while ((tempString = reader.readLine()) != null) { // set return value because something is being written temp = true; // Write String to the file try { writer.write(tempString); } catch (IOException e) { e.printStackTrace(); System.out.println("Can not write to file"); } } writer.close(); return temp; } /** * The method inherited from the Commands interface. */ public void execute() { //Check rather http request is good try { // Add Capability to handle HTTPS System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); URL tempURL = new URL(commonConfig.getUrl().toString()+commonConfig.getTemplatePlayerRequest()); if (isHttpRequestReponding(tempURL, commonConfig.getHttpTimeOut(), commonConfig.getExpectedResponse())){ monitor.setCurrentQueue(1); } else { monitor.increaseCurrentQueue(); } } catch (IOException e) { e.printStackTrace(); } } /** * @return Returns the commonConfig */ public CommonConfig getCommonConfig(){ return commonConfig; } /** * * @param commonConfig */ public void setCommonConfig(CommonConfig commonConfig){ this.commonConfig = commonConfig; } /** * @return Monitor */ public Monitor getMonitor(){ return monitor; } /** * @param monitor */ public void setMonitor(Monitor monitor){ this.monitor = monitor; } } IsTwoTextFileEqual.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 07, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.IsTwoTextFileEqual *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * @author Churk Y. Leung */ public class IsTwoTextFileEqual { /** * * @param filePath1 * @param filePath2 * @return boolean */ public boolean isTwoTextFileEqual(String filePath1, String filePath2) { String L1 = null; String L2 = null; try { Scanner scanFile1 = new Scanner (new File(filePath1)); Scanner scanFile2 = new Scanner (new File(filePath2)); while (scanFile1.hasNext() && scanFile2.hasNext()) { L1 = scanFile1.nextLine(); L2 = scanFile2.nextLine(); for (int counter = 0; counter < L2.length(); counter++) { if (L1.charAt(counter) != L2.charAt(counter)) { return false; } } } } catch (FileNotFoundException e) { e.printStackTrace(); } return true; } } JdbcTester.java
/**------------------------------------------------------------------------------------
* Create Date: Jun 02, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Test JDBC connection * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Jun 02, 2006 CLEUNG com.churkleung.CommonFunctions.JdbcTester *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author Churk Y. Leung */ public class JdbcTester { /** * Main Method to test your JDBCUrl Connection * @param args */ public static void main(String[] args) { String jdbcURL = null; String username = null; String password = null; if (args.length == 3) { if (!args[0].substring(0,18).equals("jdbc:oracle:thin:@")) { jdbcURL = "jdbc:oracle:thin:@" + args[0]; } username = args[1]; password = args[2]; } else if (args.length == 5) { jdbcURL = "jdbc:oracle:thin:@" + args[0] + ":" + args[1] + ":" + args[2]; username = args[3]; password = args[4]; } else { System.out.println("Usage:"); System.out.println("JdbcTester System.out.println("JdbcTester System.exit(0); } Connection connection = null; try { // Load the JDBC driver Class.forName("oracle.jdbc.driver.OracleDriver"); // Create a connection to the database connection = DriverManager.getConnection(jdbcURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Could not find the database driver"); e.printStackTrace(); } catch (SQLException e) { System.out.println("Could not connect to the database"); e.printStackTrace(); } try { String sqlString = "Select count(*) as tableCount from tab"; Statement sqlStatement = connection.createStatement(); // Run Query and get the count of number of table ResultSet countTableResultSet = sqlStatement.executeQuery(sqlString); countTableResultSet.next(); int numberOfTable = countTableResultSet.getInt(1); countTableResultSet.close(); if (numberOfTable > 0) { System.out.println("Connection was made successfully"); } else { System.out.println("Connection was not "); } } catch (Exception e){ e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } ListFileExist.java
/**------------------------------------------------------------------------------------
* Create Date: Jan 28, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Check to see if a file exist or not. similar to Unix: find . -name "XX.XX" * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Jan 28, 2006 CLEUNG com.churkleung.CommonFunctions. *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; /** * @author Churk Y. Leung */ public class ListFileExist { /** * Main Method that iterates through the String[] and check each String * On rather the file exist or not. * @param args */ public static void main(String[] args) { File workingFile = new File(args[0]); ArrayList String line = null; if (!workingFile.exists()){ System.out.println("Input File Does Not Exist."); System.exit(0); } else { BufferedReader in; try { in = new BufferedReader(new FileReader(workingFile.toString())); while ((line = in.readLine()) != null){ filesToBeCheck.add(line); } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } for (Iterator String currentFile = iter.next(); File temp = new File(currentFile); if (temp.exists()){ System.out.println("Exist: "+currentFile); } else { System.out.println("Does Not Exist: "+currentFile); } } } } } LogOff.java
/**------------------------------------------------------------------------------------
* Create Date: Sep 9, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Log off of a windows computer * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Sep 09, 2006 CLEUNG com.churkleung.CommonFunctions.LogOff *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.IOException; /** * @author Churk Y. Leung */ public class LogOff { /** * @param args */ public static void main(String[] args) { try { LogOff logoff = new LogOff(); logoff.loggingOff(); } catch (IOException e) { e.printStackTrace(); } } public void loggingOff() throws IOException { Runtime.getRuntime().exec("shutdown -l -t 00 -f"); } } MailUtility.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 07, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.MailUtility *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * @author Churk Leung * Mail Utility allows the user to send an email with attachment */ public class MailUtility implements Commands { // Mail Variales private List private String fromAddress; private String popServer; private String smtpServer; private String userName; private String passWord; private String subject; private String messageBody; private Multipart multipartWithAttachment; private Multipart multipartWithoutAttachment; private MimeMessage messageWithAttachment; private MimeMessage messageWithoutAttachment; // Reference Class private CommonConfig commonConfig; /** * Sends the mail with the filename path defined * @param filename * @throws AddressException * @throws MessagingException */ public void sendMail(String filename) throws AddressException, MessagingException { // Create some properties and get the default Session Properties propsWithAttachment = new Properties(); propsWithAttachment.put("mail.smtp.host", smtpServer); //Create 2 messages, one with attachment, one just notifiy the system is going down messageWithAttachment = new MimeMessage(Session.getDefaultInstance(propsWithAttachment, null)); messageWithAttachment.setFrom(new InternetAddress(fromAddress)); messageWithoutAttachment = new MimeMessage(Session.getDefaultInstance(propsWithAttachment, null)); messageWithoutAttachment.setFrom(new InternetAddress(fromAddress)); // Change a List of address to an Array of Address InternetAddress[] addresses = convertListToArray(toAddress); // Sets the recepient and subject of the email messageWithAttachment.setRecipients(Message.RecipientType.TO, addresses); messageWithAttachment.setSubject(subject); messageWithoutAttachment.setRecipients(Message.RecipientType.TO, addresses); messageWithoutAttachment.setSubject(subject); //Create and fill TEXT part of the message multipartWithAttachment = fillTextBody(new MimeBodyPart(), messageBody); String messageBodywithoutAttachment = "This customer's System is about to crash. There is a zip bundle inside the log directory."; messageBodywithoutAttachment += "This bundle contains all the myHelper commands and the Logs of the moment of the crash."; messageBodywithoutAttachment += "\nPlease go and retrieve this bundle for investigation. The Bundle is in: "; messageBodywithoutAttachment += commonConfig.getLogDirectory().replace('\\', '/') + "/" + commonConfig.getZipFileName(); multipartWithoutAttachment = fillTextBody(new MimeBodyPart(), messageBodywithoutAttachment); //Create and fill ATTACHMENT part of the message fillAttachmentBody(new MimeBodyPart(), filename, multipartWithAttachment); //Put parts in message messageWithAttachment.setContent(multipartWithAttachment); messageWithoutAttachment.setContent(multipartWithoutAttachment); //Send the message Transport.send(messageWithAttachment); Transport.send(messageWithoutAttachment); } /** * Fill ATTACHMENT part of the message * @param tempMessageBodyPart * @param filename * @param tempMultipart * @throws MessagingException */ public void fillAttachmentBody(MimeBodyPart tempMessageBodyPart, String filename, Multipart tempMultipart) throws MessagingException { DataSource source = new FileDataSource(filename); tempMessageBodyPart.setDataHandler(new DataHandler(source)); tempMessageBodyPart.setFileName(filename); tempMultipart.addBodyPart(tempMessageBodyPart); } /** * Fill TEXT part of the message * @param tempMessageBodyPart * @param tempMessageBody * @return Multipart * @throws MessagingException */ public Multipart fillTextBody(MimeBodyPart tempMessageBodyPart, String tempMessageBody) throws MessagingException { tempMessageBodyPart.setText(tempMessageBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(tempMessageBodyPart); return multipart; } /** * Converts the List that is pass from the Spring Bean to an InternetAddress[] * The Problem was unable to directly use to .toArray() function of the collection so * We must use an iterator to slowly convert each object of the list into an InternetAddress * Object then add it to the new InternetAddress[] * @param tempAddress * @return InternetAddress[] * @throws AddressException */ public InternetAddress[] convertListToArray(List int AddressCounter = 0; InternetAddress[] tempAddresses = new InternetAddress[tempAddress.size()]; for (Iterator String address = iter.next(); tempAddresses [AddressCounter++] = new InternetAddress(address); } return tempAddresses; } String getSlash() { String thisSlash = "/"; String os = System.getProperty("os.name"); if (os.indexOf("Windows") > -1) { thisSlash = "\\"; } return thisSlash; } /** * Default Inherited execute Mothod from Commands */ public void execute() { try { //Send an email with the attached Zipped log sendMail(commonConfig.getLogDirectory() + getSlash() + commonConfig.getZipFileName()); } catch (AddressException ae) { System.out.println("Email address unreachable"); ae.printStackTrace(); } catch (MessagingException me) { System.out.println("Message undeliverable"); me.printStackTrace(); } } /** * @return Returns the toAddress. * @uml.property name="toAddress" */ public List /** * @param toAddress The toAddress to set. * @uml.property name="toAddress" */ public void setToAddress(List /** * @return Returns the popServer. * @uml.property name="popServer" */ public String getPopServer(){ return popServer; } /** * @param popServer The popServer to set. * @uml.property name="popServer" */ public void setPopServer(String popServer){ this.popServer = popServer; } /** * @return Returns the smtpServer. * @uml.property name="smtpServer" */ public String getSmtpServer(){ return smtpServer; } /** * @param smtpServer The smtpServer to set. * @uml.property name="smtpServer" */ public void setSmtpServer(String smtpServer){ this.smtpServer = smtpServer; } /** * @return Returns the fromAddress. * @uml.property name="fromAddress" */ public String getFromAddress(){ return fromAddress; } /** * @param fromAddress The fromAddress to set. * @uml.property name="fromAddress" */ public void setFromAddress(String fromAddress){ this.fromAddress = fromAddress; } /** * @return Returns the subject. * @uml.property name="subject" */ public String getSubject(){ return subject; } /** * @param subject The subject to set. * @uml.property name="subject" */ public void setSubject(String subject){ this.subject = subject; } /** * @return Returns the messageBody. * @uml.property name="messageBody" */ public String getMessageBody(){ return messageBody; } /** * @param messageBody The messageBody to set. * @uml.property name="messageBody" */ public void setMessageBody(String messageBody){ this.messageBody = messageBody; } /** * @return Returns the userName. * @uml.property name="userName" */ public String getUserName(){ return userName; } /** * @param userName The userName to set. * @uml.property name="userName" */ public void setUserName(String userName){ this.userName = userName; } /** * @return Returns the passWord. * @uml.property name="passWord" */ public String getPassWord(){ return passWord; } /** * @param passWord The passWord to set. * @uml.property name="passWord" */ public void setPassWord(String passWord){ this.passWord = passWord; } /** * @return CommonConfig */ public CommonConfig getCommonConfig(){ return commonConfig; } /** * * @param commonConfig */ public void setCommonConfig(CommonConfig commonConfig){ this.commonConfig = commonConfig; } /** * @return Returns the multipartWithAttachment. */ public Multipart getMultipartWithAttachment() { return multipartWithAttachment; } /** * @param multipartWithAttachment The multipartWithAttachment to set. */ public void setMultipartWithAttachment(Multipart multipartWithAttachment) { this.multipartWithAttachment = multipartWithAttachment; } /** * @return Returns the multipartWithoutAttachment. */ public Multipart getMultipartWithoutAttachment() { return multipartWithoutAttachment; } /** * @param multipartWithoutAttachment The multipartWithoutAttachment to set. */ public void setMultipartWithoutAttachment(Multipart multipartWithoutAttachment) { this.multipartWithoutAttachment = multipartWithoutAttachment; } /** * @return Returns the messageWithAttachment. */ public MimeMessage getMessageWithAttachment() { return messageWithAttachment; } /** * @param messageWithAttachment The messageWithAttachment to set. */ public void setMessageWithAttachment(MimeMessage messageWithAttachment) { this.messageWithAttachment = messageWithAttachment; } /** * @return Returns the messageWithoutAttachment. */ public MimeMessage getMessageWithoutAttachment() { return messageWithoutAttachment; } /** * @param messageWithoutAttachment The messageWithoutAttachment to set. */ public void setMessageWithoutAttachment(MimeMessage messageWithoutAttachment) { this.messageWithoutAttachment = messageWithoutAttachment; } } Monitor.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 07, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.Monitor *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.FileNotFoundException; import java.net.MalformedURLException; import java.util.Iterator; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Churk Leung */ public class Monitor { private int currentQueue = 0; private boolean stopMonitoring = false; // Reference Classes private HttpRequestUtility httpRequestUtility; private MailUtility mailUtility; private CommonConfig commonConfig; private MyHelper myHelper; private DiagnosticRunner diagnosticRunner = new DiagnosticRunner(this); /** * Main Method that creates a monitor object * @param args * @throws FileNotFoundException * @throws InterruptedException * @throws MalformedURLException */ public static void main(String[] args) throws FileNotFoundException, InterruptedException, MalformedURLException { BeanFactory beanFactory = new ClassPathXmlApplicationContext("src/monitor.xml"); Monitor monitor = (Monitor) beanFactory.getBean("Monitor"); monitor.monitor(monitor.commonConfig); } /** * Monitoring the health of the Application * @param commonConfig * @throws InterruptedException Exception that is thrown when the app close unexpectively * @throws MalformedURLException */ @SuppressWarnings("unchecked") public void monitor(CommonConfig commonConfig) throws InterruptedException, MalformedURLException { System.out.println("Monitoring has begun"); while (!stopMonitoring) { // Starts off all the Monitoring Commands for (Iterator iter = commonConfig.getMonitoringCommands().iterator(); iter.hasNext();) { Commands monCmd = (Commands) iter.next(); monCmd.execute(); } diagnosticRunner.runDiagnostics(commonConfig); System.out.println("Monitor going to sleep for " + commonConfig.getFrequency() + " minutes"); //Sleep for frequency milliseconds Thread.sleep(commonConfig.getFrequency() * commonConfig.MINUTE); } System.out.println("Monitor Existing"); } /** * @return boolean */ public boolean isStopMonitoring() { return stopMonitoring; } /** * @return Returns the currentQueue. * @uml.property name="currentQueue" */ public int getCurrentQueue(){ return currentQueue; } /** * @param currentQueue The currentQueue to set. * @uml.property name="currentQueue" */ public void setCurrentQueue(int currentQueue){ this.currentQueue = currentQueue; } /** * Increase the Current queue When HttpRequest Fails */ public void increaseCurrentQueue(){ currentQueue++; } /** * @return Returns the httpRequestUtility. * @uml.property name="httpRequestUtility" */ public HttpRequestUtility getHttpRequestUtility(){ return httpRequestUtility; } /** * @param httpRequestUtility The httpRequestUtility to set. * @uml.property name="httpRequestUtility" */ public void setHttpRequestUtility(HttpRequestUtility httpRequestUtility){ this.httpRequestUtility = httpRequestUtility; } /** * @return Returns the mailUtility. * @uml.property name="mailUtility" */ public MailUtility getMailUtility(){ return mailUtility; } /** * @param mailUtility The mailUtility to set. * @uml.property name="mailUtility" */ public void setMailUtility(MailUtility mailUtility){ this.mailUtility = mailUtility; } /** * @return Returns the commonConfig */ public CommonConfig getCommonConfig(){ return commonConfig; } /** * * @param commonConfig */ public void setCommonConfig(CommonConfig commonConfig){ this.commonConfig = commonConfig; } /** * @return MyHelper */ public MyHelper getMyHelper(){ return myHelper; } /** * * @param myHelper */ public void setMyHelper(MyHelper myHelper){ this.myHelper = myHelper; } /** * * @param diagnosticRunner */ public void setDiagnosticRunner(DiagnosticRunner diagnosticRunner) { this.diagnosticRunner = diagnosticRunner; } /** * * @param stopMonitoring */ public void setStopMonitoring(boolean stopMonitoring) { this.stopMonitoring = stopMonitoring; } } MyHelper.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 07, 2005 * Author: Churk Leung * * COPYRIGHT © [2005] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2005 CLEUNG com.churkleung.CommonFunctions.MyHelper *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.net.MalformedURLException; import java.net.URL; import java.security.Security; import java.util.Iterator; /** * @author Churk Leung * MyHelper Using the HttpRequestUtility, writes out files of what is being return by the MyHelper Functions */ public class MyHelper implements Commands { private CommonConfig commonConfig; private HttpRequestUtility httpRequestUtility; /** * Takes a myhelper call and gets the output from httpDataGather * @param call * @throws MalformedURLException */ public void myhelper(String call) throws MalformedURLException{ // Add Capability to handle HTTPS System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); try{ if (httpRequestUtility.didHttpDataGatherSucceed(new URL(commonConfig.getUrl()+"/servlet/myhelper?"+call), commonConfig.getLogDirectory()+"\\myhelper_"+call+".xml", commonConfig.getHttpTimeOut()*commonConfig.SECONDS)) { commonConfig.addZippedFiles(commonConfig.getLogDirectory()+"\\myhelper_"+call+".xml"); } } catch (MalformedURLException exception) { exception.printStackTrace(); System.out.println("myhelper " + call + "failed"); throw exception; } } /** * Default Inherited execute Mothod from Commands */ public void execute() { for (Iterator String currentCommand = iter.next(); try { myhelper(currentCommand); } catch (MalformedURLException e) { e.printStackTrace(); } } } /** * @return Returns a commonConfig */ public CommonConfig getCommonConfig(){ return commonConfig; } /** * @param commonConfig */ public void setCommonConfig(CommonConfig commonConfig){ this.commonConfig = commonConfig; } /** * @return Returns the httpRequestUtility. * @uml.property name="httpRequestUtility" */ public HttpRequestUtility getHttpRequestUtility(){ return httpRequestUtility; } /** * @param httpRequestUtility The httpRequestUtility to set. * @uml.property name="httpRequestUtility" */ public void setHttpRequestUtility(HttpRequestUtility httpRequestUtility){ this.httpRequestUtility = httpRequestUtility; } } PrimeGenerator.java
/**------------------------------------------------------------------------------------
* Create Date: Jul 20, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Class was create to generate prime numbers * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Jul 20, 2006 CLEUNG com.churkleung.CommonFunctions.PrimeGenerator *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Churk Y. Leung */ public class PrimeGenerator { /** * @param args */ public static void main(String[] args) { int upperRange = Integer.parseInt(args[0]); if (upperRange < 3) { System.out.println("Prime from 1 to 100 are: 1, 2"); return; } PrimeGenerator primeGenerator = new PrimeGenerator(); primeGenerator.performAction(upperRange); List for (Iterator System.out.print(iter.next() + ","); } } /** * Return top 30 prime; * @return List */ public List long systime = System.currentTimeMillis(); List result.add(2); int counter = 2; while(result.size() <= 1000) { counter++; boolean isPrime = true; for (Iterator if (counter % iter.next() == 0) { isPrime = false; break; } } if (isPrime) { result.add(counter); } } System.out.println(System.currentTimeMillis() - systime); return result; } /** * Perform the invoke action. * @param upperRange * @return ArrayList of Prime #'s */ public ArrayList ArrayList primeNumbers.add(2); System.out.println("Prime from 1 to " + upperRange + " are:"); System.out.println("1,"); System.out.println("2,"); for (int counter = 3; counter <= upperRange; counter++) { boolean isPrime = true; for (Iterator int currentPrime = iter.next(); if ((counter % currentPrime) == 0) { isPrime = false; break; } } if (isPrime) { primeNumbers.add(counter); System.out.println(counter + ","); } else { primeNumbers.add(counter); } } return primeNumbers; } } RegularExpressionSearch.java
/**------------------------------------------------------------------------------------
* Create Date: Sep 08, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Demostrate the user or regex search * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Sep 08, 2006 CLEUNG com.churkleung.CommonFunctions.RegularExpressionSearch *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Churk Leung */ public class RegularExpressionSearch { /** * @param args */ public static void main(String[] args) { RegularExpressionSearch regularExpressionSearch = new RegularExpressionSearch(); if (args.length > 1) { for (int i = 1; i < args.length; i++){ regularExpressionSearch.work(args[0], args[i]); } } } private void work(String searchPattern, String fileName) { // System.out.println("Processing " + fileName + " Begin"); StringBuffer stringBuffer = new StringBuffer(); try { BufferedReader bufferedReader = new BufferedReader( new FileReader(fileName)); String string = ""; while ((string = bufferedReader.readLine()) != null){ stringBuffer.append(string); } } catch (IOException e) { e.printStackTrace(); } String result = regExpFind(stringBuffer, searchPattern); // result = result.substring(result.indexOf("Subject: ") + 9, result.indexOf("")); System.out.println(result); // System.out.println("Processing " + fileName + " End"); } /** * Using regular Expression to search and replace a string buffer * @param stringBuffer the text to change * @param patternString The pattern to look for * @param replacementText The replacement string */ public void regExpReplaceAll( StringBuffer stringBuffer, String patternString, String replacementText) { Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(stringBuffer); String output = matcher.replaceAll(replacementText); stringBuffer.delete(0, stringBuffer.length()); stringBuffer.append(output); } /** * Using regular Expression to search a string buffer * @param stringBuffer the text to search * @param patternString The pattern to look for * @return if found the result string found else "" */ public String regExpFind( StringBuffer stringBuffer, String patternString){ String result = ""; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(stringBuffer); if (matcher.find()){ result = matcher.group(); } return result; } } RenameExt.java
/**------------------------------------------------------------------------------------
* Create Date: Sep 21, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Demostrate the use of renaming a file * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Sep 21, 2006 CLEUNG com.churkleung.CommonFunctions.RenameExt *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.File; /** * @author Churk Leung */ public class RenameExt { /** * @param args */ public static void main(String[] args) { String fileName = args[0].substring(0, args[0].lastIndexOf('.')); String newName = fileName + args[1]; File originalFile = new File(args[0]); File newFile = new File(newName); originalFile.renameTo(newFile); } } RestartComputer.java
/**------------------------------------------------------------------------------------
* Create Date: Sep 09, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Restart a window machine * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Sep 09, 2006 CLEUNG com.churkleung.CommonFunctions.RestartComputer *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.IOException; /** * @author Churk Y. Leung */ public class RestartComputer { /** * @param args */ public static void main(String[] args) { RestartComputer restartComputer = new RestartComputer(); try { restartComputer.restart(); } catch (IOException e) { e.printStackTrace(); } } public void restart() throws IOException { Runtime.getRuntime().exec("shutdown -r -f -t 00"); } } returnOddOccuenceInIntArray.java
/**------------------------------------------------------------------------------------
* Create Date: Jul 20, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * takes in an int[] and return the position where an odd interger Appears * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Jul 20, 2006 CLEUNG com.churkleung.CommonFunctions.returnOddOccuenceInIntArray *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.util.Arrays; /** * @author Churk Y. Leung */ public class returnOddOccuenceInIntArray { /** * Main Method where it takes in an int[] and return the position where an * odd interger Appears * @param myArray * @return int */ public int returnOddNumber(int[] myArray){ Arrays.sort(myArray); int myNumberToReturn = -1; int counter = 0; for (int i = 0; i < myArray.length; i++){ if (myNumberToReturn != myArray[i]){ myNumberToReturn = myArray[i]; if(counter % 2 != 0){ return myNumberToReturn; } else { counter = 0; } } else { counter++; } } return myNumberToReturn; } } RunExternalProgram.java
/**------------------------------------------------------------------------------------
* Create Date: Jul 05, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Call an external Program in windows * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Jul 05, 2006 CLEUNG com.churkleung.CommonFunctions.RunExternalProgram *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.IOException; /** * @author Churk Y. Leung */ public class RunExternalProgram { /** * Main Arguement to invoke to run an external program * @param args */ public static void main(String[] args) { args[0] = args[0].replace('\\','/'); if (args.length < 1) { System.out.println("Invalid number of arguement"); System.out.println("example of usage:"); System.out.println("RunExternalProgram /opt/myCommand.sh [args1 args2 ...]"); System.exit(0); } try { Process process; String commandLine = args[0]; if (args.length > 1) { for (int i = 1; i < args.length; i++) { commandLine += " " + args[i]; } } process = Runtime.getRuntime().exec(commandLine); process.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } ZipFileUtility.java
/**------------------------------------------------------------------------------------
* Create Date: Dec 07, 2006 * Author: Churk Leung * * COPYRIGHT © [2006] Leung Corp. All Rights Reserved. * ------------------------------------------------------------------------------------- * * Collection of Zip File Functions * * History: *====================================================================================== * Flags Date AUTHOR Comments *-------------------------------------------------------------------------------------- * CL01 Dec 07, 2006 CLEUNG com.churkleung.CommonFunctions.ZipFileUtility *------------------------------------------------------------------------------------*/ package com.churkleung.CommonFunctions; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author Churk Leung * The ZipFileUtility is used for zipping files during the data gathering process */ public class ZipFileUtility implements Commands { private CommonConfig commonConfig; /** * Takes in a list of files, a directory path, and a output file name * @param filesToZip * @param logDirectory * @param newZipName */ public void ZipFile(List byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(logDirectory+"/"+newZipName)); //Set Compression Ratio out.setLevel(Deflater.BEST_COMPRESSION); //More Compression Ratio Examples //out.setLevel(Deflater.BEST_SPEED); //out.setLevel(Deflater.DEFAULT_COMPRESSION); //out.setLevel(Deflater.NO_COMPRESSION); //iterate through the array of files, adding each to the zip file for (Iterator String currentFileBeingZip = iter.next(); System.out.println("Currently Compressing " + currentFileBeingZip); //Associate a file input stream for the current file FileInputStream in = new FileInputStream(currentFileBeingZip); //Add Zip Entry to output stream out.putNextEntry(new ZipEntry(currentFileBeingZip)); //Transfer bytes from the current file to the Zip file int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } //Close Current entry out.closeEntry(); //Close Current file input stream in.close(); } //Close the ZipOutputStream out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe){ ioe.printStackTrace(); } } String getSlash() { String thisSlash = "/"; String os = System.getProperty("os.name"); if (os.indexOf("Windows") > -1) { thisSlash = "\\"; } return thisSlash; } /** * The method inherited from the Commands interface. */ public void execute() { // Iterate through the list of file names that we want to zip. First check rather they exist for (Iterator String currentFile = iter.next(); if (commonConfig.fileExist(commonConfig.getLogDirectory() + getSlash() + currentFile)){ commonConfig.getZippedFiles().add(commonConfig.getLogDirectory() + getSlash() + currentFile); } } // Prints out the File paths that is going to be zipped // commonConfig.printList(commonConfig.getZippedFiles()); //Check to see if the newZipFile name already exist. If it does remove it. //Zip up Log files and send email alert with logs attachments //Zipped File would be at this location logDirectory/newZipName commonConfig.removeFileIfExist(commonConfig.getZipFileName()); ZipFile(commonConfig.getZippedFiles(), commonConfig.getLogDirectory(), commonConfig.getZipFileName()); } /** * @return CommonConfig */ public CommonConfig getCommonConfig(){ return commonConfig; } /** * @param commonConfig */ public void setCommonConfig(CommonConfig commonConfig){ this.commonConfig = commonConfig; } } |