List of usage examples for java.lang String equalsIgnoreCase
public boolean equalsIgnoreCase(String anotherString)
From source file:net.iiit.siel.analysis.lang.LanguageIdentifier.java
/** * The main method./*from w w w. j a v a2 s .c o m*/ * * @param args the arguments */ public static void main(String args[]) { String usage = "Usage: LanguageIdentifier " + "[-identifyrows filename maxlines] " + "[-identifyfile charset filename] " + "[-identifyfileset charset files] " + "[-identifytext text] " + "[-identifyurl url]"; int command = 0; final int IDFILE = 1; final int IDTEXT = 2; final int IDURL = 3; final int IDFILESET = 4; final int IDROWS = 5; Vector fileset = new Vector(); String filename = ""; String charset = ""; String url = ""; String text = ""; int max = 0; // TODO niket writing test args here.. /* args = new String[2]; args[0] = "-identifyurl"; args[1] = "file:/home1/niket/TamilSamplePage.html"; //args[2] = "/home1/niket/nutch-clia/input.txt"; */ // TODO niket end here if (args.length == 0) { System.err.println(usage); System.exit(-1); } for (int i = 0; i < args.length; i++) { // parse command line if (args[i].equals("-identifyfile")) { command = IDFILE; charset = args[++i]; filename = args[++i]; } if (args[i].equals("-identifyurl")) { command = IDURL; filename = args[++i]; } if (args[i].equals("-identifyrows")) { command = IDROWS; filename = args[++i]; max = Integer.parseInt(args[++i]); } if (args[i].equals("-identifytext")) { command = IDTEXT; for (i++; i < args.length - 1; i++) text += args[i] + " "; } if (args[i].equals("-identifyfileset")) { command = IDFILESET; charset = args[++i]; for (i++; i < args.length; i++) { File[] files = null; File f = new File(args[i]); if (f.isDirectory()) { files = f.listFiles(); } else { files = new File[] { f }; } for (int j = 0; j < files.length; j++) { fileset.add(files[j].getAbsolutePath()); } } } } Configuration conf = NutchConfiguration.create(); String lang = null; LanguageIdentifier idfr = new LanguageIdentifier(conf); File f; FileInputStream fis; try { switch (command) { case IDTEXT: lang = idfr.identify(text); System.out.println("Lang :" + lang); break; case IDFILE: f = new File(filename); fis = new FileInputStream(f); lang = idfr.identify(fis, charset); fis.close(); break; case IDURL: lang = LangIdentifierUtility.IdentifyLangFromURLDirectly(filename); /* * our url identifier is confused or couldn't identify lang from * URL */ if (lang == null || lang.equalsIgnoreCase("en")) { System.out.println("Ambuguity in identifying language from URL"); } else { System.out.println("Lang was identified(using URL) as: " + lang); } break; case IDROWS: f = new File(filename); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String line; while (max > 0 && (line = br.readLine()) != null) { line = line.trim(); if (line.length() > 2) { max--; lang = idfr.identify(line); System.out.println("R=" + lang + ":" + line); } } br.close(); System.exit(0); break; case IDFILESET: /* * used for benchs for (int j=128; j<=524288; j*=2) { long start * = System.currentTimeMillis(); idfr.analyzeLength = j; */ System.out.println("FILESET"); Iterator i = fileset.iterator(); while (i.hasNext()) { try { filename = (String) i.next(); f = new File(filename); fis = new FileInputStream(f); lang = idfr.identify(fis, charset); fis.close(); } catch (Exception e) { System.out.println(e); } System.out.println(filename + " was identified as " + lang); } /* * used for benchs System.out.println(j + "/" + * (System.currentTimeMillis()-start)); } */ System.exit(0); break; } } catch (Exception e) { System.out.println(e); System.out.println("lang could not be identified properly"); e.printStackTrace(); } System.out.println("text was identified as " + lang); /* * DONOT delete the next few lines, they should be enabled, when a lang. * mapping map needs to be generated. TODO this is for printing * the hashMapRangeLangIDTable only * * idfr.langMarkerObject.printHashmapTableWithFormatting(); * * System.out * .println("\n\n\n Printing english text contents in this file:\n"); * System.out.println(idfr.langMarkerObject.getLangCharacters( * LanguageIdentifierConstants.LangShortNames.ENGLISH * .langShortName()).toString()); * * System.out * .println("\n\n\n Printing telugu text contents in this file:\n"); * System.out.println(idfr.langMarkerObject.getLangCharacters( * LanguageIdentifierConstants.LangShortNames.TELUGU * .langShortName()).toString()); * * System.out * .println("\n\n\n Printing unknown text contents in this file:\n"); * System.out.println(idfr.langMarkerObject.getLangCharacters( * LanguageIdentifierConstants.LangShortNames.UNKNOWN_LANG * .langShortName()).toString()); */ }
From source file:com.pari.nm.utils.backup.BackupRestore.java
/** * @param args//from www . ja v a 2 s.co m */ public static void main(String[] args) { com.maverick.ssh.LicenseManager.addLicense("----BEGIN 3SP LICENSE----\r\n" + "Product : J2SSH Maverick\r\n" + "Licensee: Pari Networks Inc.\r\n" + "Comments: Sreenivas Devalla\r\n" + "Type : Foundation License\r\n" + "Created : 20-Jun-2007\r\n" + "\r\n" + "3787201A027FCA5BA600F3CF9CCEF4C85068187D70F94ABC\r\n" + "E7D7280AAFB06CE499DC968A4CB25795475D5B79FDDD6CB4\r\n" + "7971A60E947E84A4DADFAB2F89E2F52470182ED2EF429A2F\r\n" + "2EC6D8B49CAF167605A7F56C4EB736ECA7150819FCF04DC6\r\n" + "01B1404EA9BC83BEAA4AB2F4FC7AB344BEC08CF9DDDAAA34\r\n" + "EC80C1C14FA8BB1A8B47E86D393FAECD3C0E7C450E0D1FE3\r\n" + "----END 3SP LICENSE----\r\n"); String mode = null; BufferedReader br = null; if (args.length < 9) { System.err.println("BackUpDatabase: Invalid Syntax."); System.err.println( "Usage - java BackUpDatabase <ftpserver> <ftpuser> <ftppassword> <ftpdir> <ftpfile> <localdir> <backup | recovery> "); System.exit(-1); } try { mode = args[8]; System.out.println("Request received with mode :" + mode + "\n"); // BackupRestore tbk = BackupRestore.getInstance(); BackupRestore tbk = new BackupRestore(); if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("recovery")) { File restoreDir = new File(args[7], args[6].substring(0, args[6].length() - 4)); System.out.println("Restore Directory :" + restoreDir + "\n"); if (!restoreDir.exists()) { try { FTPServerType serverType = FTPServerType.valueOf(FTPServerType.class, args[0]); System.out.println("Fetching the backup File :" + args[6] + "\n"); System.out.println("Please wait, it may take sometime....." + "\n"); if (tbk.fetchAndExtractBackupFile(serverType, args[1], Integer.parseInt(args[2]), args[3], args[4], args[5], args[6], args[7]) == null) { System.err.println("Error : Failed to fetch the backup File.\n"); System.exit(-1); } System.out.println("Successfully fetched the backup File :" + args[6] + "\n"); } catch (Exception e) { System.out.println( "Error : Exception while fetching the backup file.Failed to restore the backup File.\n"); e.printStackTrace(); System.exit(-1); } } try { Thread.sleep(10000); } catch (Exception ee) { ee.printStackTrace(); } System.out.println("Starting recovery ...\n"); if (!File.separator.equals("\\")) { System.out.println("Stopping the Pari Server process.\n"); Process p = Runtime.getRuntime().exec("killall -9 pari_server"); MyReader min = new MyReader(p.getInputStream()); MyReader merr = new MyReader(p.getErrorStream()); try { min.join(20000); } catch (Exception ee) { } try { merr.join(20000); } catch (Exception ex) { } } if (!File.separator.equals("\\")) { System.out.println("Stopping the Pari Server process.\n"); // Process p = Runtime.getRuntime().exec("killall -9 pari_server"); Process p = Runtime.getRuntime().exec("/etc/init.d/dash stop"); MyReader min = new MyReader(p.getInputStream()); MyReader merr = new MyReader(p.getErrorStream()); try { min.join(20000); } catch (Exception ee) { } try { merr.join(20000); } catch (Exception ex) { } } System.out.println("Start recovering the backup file.\n"); if (tbk.doRecovery(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])) { System.out.println("Done recovering...\n"); validateCSPCInstanace(); } else { System.out.println("Failed to recover the backup File...\n"); } try { Process p = null; String cmd = ""; if (File.separator == "\\") { cmd = "cmd /k start_server.cmd > pari.out 2>&1"; } else { cmd = "/etc/init.d/dash start"; } System.err.println(cmd); Runtime.getRuntime().exec(cmd); Boolean flag = false; int count = 0; String[] nccmStatusCheckCmd = { "/bin/sh", "-c", "netstat -an | grep 42605 | grep LISTEN | wc -l" }; do { count++; Thread.sleep(60000); // The command output will be 1 if NCCM server started and Listening on port 42605 otherwise it // will return 0 p = Runtime.getRuntime().exec(nccmStatusCheckCmd); int ex = -1; try { ex = p.waitFor(); } catch (InterruptedException e) { System.out.println("Normal execution, exception: " + e); } System.out.println("Normal execution, exit value: " + ex); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String thisLine = null; while ((thisLine = br.readLine()) != null) { System.out.println("Command Execution Result:" + thisLine); if (thisLine.equals("1")) { flag = true; break; } } System.out.println("Count - " + count); BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((thisLine = error.readLine()) != null) { System.out.println(thisLine); } } while ((!flag) && count < 30); if (flag) { // System.out.println("NCCM Server came to listening state: after " + count + " mins"); // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/shutdown.sh"); Thread.sleep(60000); System.out.println("NCCM Server came to listening state: after " + count + " mins"); // Runtime.getRuntime().exec("sh $DASH_HOME/webui/tomcat/bin/startup.sh"); } else { System.out.println("NCCM Server didn't come to listening state: last " + count + " mins"); System.out.println("Please verify NCCM Server and start tomcat server manually."); } System.exit(1); } catch (Exception ee) { ee.printStackTrace(); } } else if ((mode != null) && (mode.length() > 0) && mode.equalsIgnoreCase("ftplist")) { PariFTP pftp = new PariFTP("10.100.1.20", "guest", "guest", "/"); String[] list = pftp.getRemoteListing(); System.out.println("List of Files\n"); for (int i = 0; (list != null) && (i < list.length); i++) { System.out.println(list[i] + "\n"); } } else { System.out.println("Mode \t" + mode + "\t not supported\n"); } System.exit(-1); } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:ch.kostceco.tools.siardexcerpt.SIARDexcerpt.java
/** Die Eingabe besteht aus mind 3 Parameter: [0] Pfad zur SIARD-Datei oder Verzeichnis [1] * configfile [2] Modul//from w w w .j av a2 s. co m * * bersicht der Module: --init --search --extract sowie --finish * * bei --search kommen danach noch die Suchtexte und bei --extract die Schlssel * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml"); /** SIARDexcerpt: Aufbau des Tools * * 1) init: Config Kopieren und ggf SIARD-Datei ins Workverzeichnis entpacken * * 2) search: gemss config die Tabelle mit Suchtext befragen und Ausgabe des Resultates * * 3) extract: mit den Keys anhand der config einen Records herausziehen und anzeigen * * 4) finish: Config-Kopie sowie Workverzeichnis lschen */ /* TODO: siehe Bemerkung im applicationContext-services.xml bezglich Injection in der * Superklasse aller Impl-Klassen ValidationModuleImpl validationModuleImpl = * (ValidationModuleImpl) context.getBean("validationmoduleimpl"); */ SIARDexcerpt siardexcerpt = (SIARDexcerpt) context.getBean("siardexcerpt"); // Ist die Anzahl Parameter (mind 3) korrekt? if (args.length < 3) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE)); System.exit(1); } String module = new String(args[2]); File siardDatei = new File(args[0]); File configFile = new File(args[1]); /* arg 1 gibt den Pfad zur configdatei an. Da dieser in ConfigurationServiceImpl hartcodiert * ist, wird diese nach "configuration/SIARDexcerpt.conf.xml" kopiert. */ File configFileHard = new File("configuration" + File.separator + "SIARDexcerpt.conf.xml"); // excerpt ist der Standardwert wird aber anhand der config dann gesetzt File directoryOfOutput = new File("excerpt"); // temp_SIARDexcerpt ist der Standardwert wird aber anhand der config dann gesetzt File tmpDir = new File("temp_SIARDexcerpt"); boolean okA = false; boolean okB = false; boolean okC = false; // die Anwendung muss mindestens unter Java 6 laufen String javaRuntimeVersion = System.getProperty("java.vm.version"); if (javaRuntimeVersion.compareTo("1.6.0") < 0) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WRONG_JRE)); System.exit(1); } if (module.equalsIgnoreCase("--init")) { /** 1) init: Config Kopieren und ggf SIARD-Datei ins Workverzeichnis entpacken * * a) config muss existieren und SIARDexcerpt.conf.xml noch nicht * * b) Excerptverzeichnis mit schreibrechte und ggf anlegen * * c) Workverzeichnis muss leer sein und mit schreibrechte * * d) SIARD-Datei entpacken * * e) Struktur-Check SIARD-Verzeichnis * * TODO: Erledigt */ System.out.println("SIARDexcerpt: init"); /** a) config muss existieren und SIARDexcerpt.conf.xml noch nicht */ if (!configFile.exists()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_CONFIGFILE_FILENOTEXISTING, configFile.getAbsolutePath())); System.exit(1); } if (configFileHard.exists()) { System.out .println(siardexcerpt.getTextResourceService().getText(ERROR_CONFIGFILEHARD_FILEEXISTING)); System.exit(1); } Util.copyFile(configFile, configFileHard); /** b) Excerptverzeichnis mit schreibrechte und ggf anlegen */ String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput(); directoryOfOutput = new File(pathToOutput); if (!directoryOfOutput.exists()) { directoryOfOutput.mkdir(); } // Im Logverzeichnis besteht kein Schreibrecht if (!directoryOfOutput.canWrite()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE, directoryOfOutput)); // Lschen des configFileHard, falls eines angelegt wurde if (configFileHard.exists()) { Util.deleteDir(configFileHard); } System.exit(1); } if (!directoryOfOutput.isDirectory()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY)); // Lschen des configFileHard, falls eines angelegt wurde if (configFileHard.exists()) { Util.deleteDir(configFileHard); } System.exit(1); } /** c) Workverzeichnis muss leer sein und mit schreibrechte */ String pathToWorkDir = siardexcerpt.getConfigurationService().getPathToWorkDir(); tmpDir = new File(pathToWorkDir); /* bestehendes Workverzeichnis Abbruch wenn nicht leer, da am Schluss das Workverzeichnis * gelscht wird und entsprechend bestehende Dateien gelscht werden knnen */ if (tmpDir.exists()) { if (tmpDir.isDirectory()) { // Get list of file in the directory. When its length is not zero the folder is not empty. String[] files = tmpDir.list(); if (files.length > 0) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)); // Lschen des configFileHard, falls eines angelegt wurde if (configFileHard.exists()) { Util.deleteDir(configFileHard); } System.exit(1); } } } if (!tmpDir.exists()) { tmpDir.mkdir(); } // Im Workverzeichnis besteht kein Schreibrecht if (!tmpDir.canWrite()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, pathToWorkDir)); // Lschen des configFileHard, falls eines angelegt wurde if (configFileHard.exists()) { Util.deleteDir(configFileHard); } System.exit(1); } /** d) SIARD-Datei entpacken */ if (!siardDatei.exists()) { // SIARD-Datei existiert nicht System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_SIARDFILE_FILENOTEXISTING, siardDatei.getAbsolutePath())); // Lschen des configFileHard, falls eines angelegt wurde if (configFileHard.exists()) { Util.deleteDir(configFileHard); } System.exit(1); } if (!siardDatei.isDirectory()) { /* SIARD-Datei ist eine Datei * * Die Datei muss ins Workverzeichnis extrahiert werden. Dies erfolgt im Modul A. * * danach der Pfad zu SIARD-Datei dorthin zeigen lassen */ Controllerexcerpt controllerexcerpt = (Controllerexcerpt) context.getBean("controllerexcerpt"); File siardDateiNew = new File(pathToWorkDir + File.separator + siardDatei.getName()); okA = controllerexcerpt.executeA(siardDatei, siardDateiNew, ""); if (!okA) { // SIARD Datei konte nicht entpackt werden System.out.println(MESSAGE_XML_MODUL_A); System.out.println(ERROR_XML_A_CANNOTEXTRACTZIP); // Lschen des Arbeitsverzeichnisses und configFileHard, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (configFileHard.exists()) { Util.deleteDir(configFileHard); } // Fehler Extraktion --> invalide System.exit(2); } else { @SuppressWarnings("unused") File siardDateiOld = siardDatei; siardDatei = siardDateiNew; } } else { /* SIARD-Datei entpackt oder Datei war bereits ein Verzeichnis. * * Gerade bei grsseren SIARD-Dateien ist es sinnvoll an einer Stelle das ausgepackte SIARD * zu haben, damit diese nicht immer noch extrahiert werden muss */ } /** e) Struktur-Check SIARD-Verzeichnis */ File content = new File(siardDatei.getAbsolutePath() + File.separator + "content"); File header = new File(siardDatei.getAbsolutePath() + File.separator + "header"); File xsd = new File( siardDatei.getAbsolutePath() + File.separator + "header" + File.separator + "metadata.xsd"); File metadata = new File( siardDatei.getAbsolutePath() + File.separator + "header" + File.separator + "metadata.xml"); if (!content.exists() || !header.exists() || !xsd.exists() || !metadata.exists()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_XML_B_STRUCTURE)); // Lschen des Arbeitsverzeichnisses und configFileHard, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (configFileHard.exists()) { Util.deleteDir(configFileHard); } // Fehler Extraktion --> invalide System.exit(2); } else { // Struktur sieht plausibel aus, extraktion kann starten } } // End init if (module.equalsIgnoreCase("--search")) { /** 2) search: gemss config die Tabelle mit Suchtext befragen und Ausgabe des Resultates * * a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext * * b) Suchtext einlesen * * c) search.xml vorbereiten (Header) und xsl in Output kopieren * * d) grep ausfhren * * e) Suchergebnis speichern und anzeigen (via GUI) * * TODO: Noch offen */ System.out.println("SIARDexcerpt: search"); String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput(); directoryOfOutput = new File(pathToOutput); if (!directoryOfOutput.exists()) { directoryOfOutput.mkdir(); } /** a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext */ if (args.length < 4) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE)); System.exit(1); } if (!siardDatei.isDirectory()) { File siardDateiNew = new File(tmpDir.getAbsolutePath() + File.separator + siardDatei.getName()); if (!siardDateiNew.exists()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_NOINIT)); System.exit(1); } else { siardDatei = siardDateiNew; } } /** b) Suchtext einlesen */ String searchString = new String(args[3]); /** c) search.xml vorbereiten (Header) und xsl in Output kopieren */ // Zeitstempel der Datenextraktion java.util.Date nowStartS = new java.util.Date(); java.text.SimpleDateFormat sdfStartS = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeStartS = sdfStartS.format(nowStartS); /* Der SearchString kann zeichen enthalten, welche nicht im Dateinamen vorkommen drfen. * Entsprechend werden diese normalisiert */ String searchStringFilename = searchString.replaceAll("/", "_"); searchStringFilename = searchStringFilename.replaceAll(">", "_"); searchStringFilename = searchStringFilename.replaceAll("<", "_"); searchStringFilename = searchStringFilename.replace(".*", "_"); searchStringFilename = searchStringFilename.replaceAll("___", "_"); searchStringFilename = searchStringFilename.replaceAll("__", "_"); String outDateiNameS = siardDatei.getName() + "_" + searchStringFilename + "_SIARDsearch.xml"; outDateiNameS = outDateiNameS.replaceAll("__", "_"); // Informationen zum Archiv holen String archiveS = siardexcerpt.getConfigurationService().getArchive(); // Konfiguration des Outputs, ein File Logger wird zustzlich erstellt LogConfigurator logConfiguratorS = (LogConfigurator) context.getBean("logconfigurator"); String outFileNameS = logConfiguratorS.configure(directoryOfOutput.getAbsolutePath(), outDateiNameS); File outFileSearch = new File(outFileNameS); // Ab hier kann ins Output geschrieben werden... // Informationen zum XSL holen String pathToXSLS = siardexcerpt.getConfigurationService().getPathToXSLsearch(); File xslOrigS = new File(pathToXSLS); File xslCopyS = new File(directoryOfOutput.getAbsolutePath() + File.separator + xslOrigS.getName()); if (!xslCopyS.exists()) { Util.copyFile(xslOrigS, xslCopyS); } LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_HEADER, xslCopyS.getName())); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStartS)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_ARCHIVE, archiveS)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_INFO)); /** d) search: dies ist in einem eigenen Modul realisiert */ Controllerexcerpt controllerexcerptS = (Controllerexcerpt) context.getBean("controllerexcerpt"); okB = controllerexcerptS.executeB(siardDatei, outFileSearch, searchString); /** e) Ausgabe und exitcode */ if (!okB) { // Suche konnte nicht erfolgen LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_MODUL_B)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(ERROR_XML_B_CANNOTSEARCHRECORD)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND)); System.out.println(MESSAGE_XML_MODUL_B); System.out.println(ERROR_XML_B_CANNOTSEARCHRECORD); System.out.println(""); // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish // Fehler Extraktion --> invalide System.exit(2); } else { // Suche konnte durchgefhrt werden LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish // Record konnte extrahiert werden System.exit(0); } } // End search if (module.equalsIgnoreCase("--excerpt")) { /** 3) extract: mit den Keys anhand der config einen Records herausziehen und anzeigen * * a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext * * b) extract.xml vorbereiten (Header) und xsl in Output kopieren * * c) extraktion: dies ist in einem eigenen Modul realisiert * * d) Ausgabe und exitcode * * TODO: Erledigt */ System.out.println("SIARDexcerpt: extract"); String pathToOutput = siardexcerpt.getConfigurationService().getPathToOutput(); directoryOfOutput = new File(pathToOutput); if (!directoryOfOutput.exists()) { directoryOfOutput.mkdir(); } /** a) Ist die Anzahl Parameter (mind 4) korrekt? arg4 = Suchtext */ if (args.length < 4) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_PARAMETER_USAGE)); System.exit(1); } if (!siardDatei.isDirectory()) { File siardDateiNew = new File(tmpDir.getAbsolutePath() + File.separator + siardDatei.getName()); if (!siardDateiNew.exists()) { System.out.println(siardexcerpt.getTextResourceService().getText(ERROR_NOINIT)); System.exit(1); } else { siardDatei = siardDateiNew; } } /** b) extract.xml vorbereiten (Header) und xsl in Output kopieren */ // Zeitstempel der Datenextraktion java.util.Date nowStart = new java.util.Date(); java.text.SimpleDateFormat sdfStart = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeStart = sdfStart.format(nowStart); String excerptString = new String(args[3]); String outDateiName = siardDatei.getName() + "_" + excerptString + "_SIARDexcerpt.xml"; // Informationen zum Archiv holen String archive = siardexcerpt.getConfigurationService().getArchive(); // Konfiguration des Outputs, ein File Logger wird zustzlich erstellt LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator"); String outFileName = logConfigurator.configure(directoryOfOutput.getAbsolutePath(), outDateiName); File outFile = new File(outFileName); // Ab hier kann ins Output geschrieben werden... // Informationen zum XSL holen String pathToXSL = siardexcerpt.getConfigurationService().getPathToXSL(); File xslOrig = new File(pathToXSL); File xslCopy = new File(directoryOfOutput.getAbsolutePath() + File.separator + xslOrig.getName()); if (!xslCopy.exists()) { Util.copyFile(xslOrig, xslCopy); } LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_HEADER, xslCopy.getName())); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_ARCHIVE, archive)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_INFO)); /** c) extraktion: dies ist in einem eigenen Modul realisiert */ Controllerexcerpt controllerexcerpt = (Controllerexcerpt) context.getBean("controllerexcerpt"); okC = controllerexcerpt.executeC(siardDatei, outFile, excerptString); /** d) Ausgabe und exitcode */ if (!okC) { // Record konnte nicht extrahiert werden LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_MODUL_C)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(ERROR_XML_C_CANNOTEXTRACTRECORD)); LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND)); System.out.println(MESSAGE_XML_MODUL_C); System.out.println(ERROR_XML_C_CANNOTEXTRACTRECORD); System.out.println(""); // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish // Fehler Extraktion --> invalide System.exit(2); } else { // Record konnte extrahiert werden LOGGER.logError(siardexcerpt.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Lschen des Arbeitsverzeichnisses und configFileHard erfolgt erst bei schritt 4 finish // Record konnte extrahiert werden System.exit(0); } } // End extract if (module.equalsIgnoreCase("--finish")) { /** 4) finish: Config-Kopie sowie Workverzeichnis lschen * * TODO: Erledigt */ System.out.println("SIARDexcerpt: finish"); // Lschen des Arbeitsverzeichnisses und confiFileHard, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (configFileHard.exists()) { Util.deleteDir(configFileHard); } } // End finish }
From source file:frankhassanabad.com.github.Jasperize.java
/** * Main method to call through Java in order to take a LinkedInProfile on disk and load it. * * @param args command line arguments where the options are stored * @throws FileNotFoundException Thrown if any file its expecting cannot be found. * @throws JRException If there's generic overall Jasper issues. * @throws ParseException If there's command line parsing issues. *//* w ww .j a v a2 s . c om*/ public static void main(String[] args) throws IOException, JRException, ParseException { Options options = new Options(); options.addOption("h", "help", false, "Shows the help documentation"); options.addOption("v", "version", false, "Shows the help documentation"); options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml"); options.addOption("sig", true, "Picture of your signature to add to the cover letter."); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Version:" + version); System.exit(0); } boolean useCoverLetter = cmd.hasOption("cl"); String signatureLocation = cmd.getOptionValue("sig"); BufferedImage signatureImage = null; if (signatureLocation != null) { signatureImage = ImageIO.read(new File(signatureLocation)); ; } @SuppressWarnings("unchecked") List<String> arguments = cmd.getArgList(); final String jrxmlFile; final String jasperOutput; if (arguments.size() == 2) { jrxmlFile = arguments.get(0); jasperOutput = arguments.get(1); System.out.println("*Detected* the command line arguments of:"); System.out.println(" [InputjrxmlFile] " + jrxmlFile); System.out.println(" [OutputExportFile] " + jasperOutput); } else if (arguments.size() == 3) { jrxmlFile = arguments.get(1); jasperOutput = arguments.get(2); System.out.println("*Detected* the command line arguments of:"); System.out.println(" [InputjrxmlFile] " + jrxmlFile); System.out.println(" [OutputExportFile] " + jasperOutput); } else { System.out.println("Using the default arguments of:"); jrxmlFile = "data/jasperTemplates/resume1.jrxml"; jasperOutput = "data/jasperOutput/linkedInResume.pdf"; System.out.println(" [InputjrxmlFile] " + jrxmlFile); System.out.println(" [OutputExportFile] " + jasperOutput); } final String compiledMasterFile; final String outputType; final String jrPrintFile; //Split the inputFile final String[] inputSplit = jrxmlFile.split("\\."); if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) { //Error System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:"); System.out.println(" data/jasperTemplates/resume1.jrxml"); System.exit(1); } //Split the outputFile final String[] outputSplit = jasperOutput.split("\\."); if (outputSplit.length != 2) { //Error System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:"); System.out.println(" data/jasperOutput/linkedInResume.pdf"); System.exit(1); } File inputFile = new File(inputSplit[0]); String inputFileName = inputFile.getName(); String inputFileParentPath = inputFile.getParent(); File outputFile = new File(outputSplit[0]); String outputFileParentPath = outputFile.getParent(); System.out.println("Compiling report(s)"); compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath); System.out.println("Done compiling report(s)"); compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper"; jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint"; System.out.println("Filling report: " + compiledMasterFile); Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage); System.out.println("Done filling reports"); outputType = outputSplit[1]; System.out.println("Creating output export file of: " + jasperOutput); if (outputType.equalsIgnoreCase("pdf")) { Reporting.pdf(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("pptx")) { Reporting.pptx(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("docx")) { Reporting.docx(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("odt")) { Reporting.odt(jrPrintFile, jasperOutput); } if (outputType.equalsIgnoreCase("xhtml")) { Reporting.xhtml(jrPrintFile, jasperOutput); } System.out.println("Done creating output export file of: " + jasperOutput); }
From source file:Counter.java
/** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage();/*w ww .j a va 2s . co m*/ System.exit(1); } // variables Counter counter = new Counter(); PrintWriter out = new PrintWriter(System.out); ParserWrapper parser = null; int repetition = DEFAULT_REPETITION; boolean namespaces = DEFAULT_NAMESPACES; boolean validation = DEFAULT_VALIDATION; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = (ParserWrapper) Class.forName(parserName).newInstance(); } catch (Exception e) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number (" + number + ")."); } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parser == null) { // create parser try { parser = (ParserWrapper) Class.forName(DEFAULT_PARSER_NAME).newInstance(); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // parse file try { long beforeParse = System.currentTimeMillis(); Document document = null; for (int j = 0; j < repetition; j++) { document = parser.parse(arg); } long afterParse = System.currentTimeMillis(); long parse = afterParse - beforeParse; ParserWrapper.DocumentInfo documentInfo = parser.getDocumentInfo(); counter.setDocumentInfo(documentInfo); long beforeTraverse1 = System.currentTimeMillis(); counter.count(document); long afterTraverse1 = System.currentTimeMillis(); long traverse1 = afterTraverse1 - beforeTraverse1; long beforeTraverse2 = System.currentTimeMillis(); counter.count(document); long afterTraverse2 = System.currentTimeMillis(); long traverse2 = afterTraverse2 - beforeTraverse2; counter.printResults(out, arg, parse, traverse1, traverse2, repetition); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); Exception se = e; if (e instanceof SAXException) { se = ((SAXException) e).getException(); } if (se != null) se.printStackTrace(System.err); else e.printStackTrace(System.err); } } }
From source file:DocumentTracer.java
/** Main. */ public static void main(String[] argv) throws Exception { // is there anything to do? if (argv.length == 0) { printUsage();//ww w . j av a 2 s . c o m System.exit(1); } // variables DocumentTracer tracer = new DocumentTracer(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); } } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("xd")) { externalDTD = option.equals("xd"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // set handlers parser.setDTDHandler(tracer); parser.setErrorHandler(tracer); if (parser instanceof XMLReader) { parser.setContentHandler(tracer); try { parser.setProperty("http://xml.org/sax/properties/declaration-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } try { parser.setProperty("http://xml.org/sax/properties/lexical-handler", tracer); } catch (SAXException e) { e.printStackTrace(System.err); } } else { ((Parser) parser).setDocumentHandler(tracer); } // parse file try { parser.parse(arg); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } }
From source file:com.github.codingtogenomic.CodingToGenomic.java
public static void main(String[] args) throws Exception { //parse commandline Options options = new Options(); CommandLineParser parser = new PosixParser(); String gene = new String(); String transcript = new String(); String species = "human"; boolean mapCdna = false; String coordinate = new String(); StringBuilder errorMsg = new StringBuilder(); try {/*from w ww. j a v a 2s.c o m*/ options = getOptions(args); } catch (org.apache.commons.cli.ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); System.exit(1); } CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { showHelp(options); } if (line.hasOption("gene")) { gene = line.getOptionValue("gene"); } else { if (!line.hasOption("transcript")) { errorMsg.append("Either --gene or --transcript argument is required\n"); } } if (line.hasOption("transcript")) { if (line.hasOption("gene")) { errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n"); } else { transcript = line.getOptionValue("transcript"); if (line.hasOption("species")) { System.out.println("Ignoring --species option when using --transcript argument"); } } } if (line.hasOption("coordinate")) { coordinate = line.getOptionValue("coordinate"); } else { errorMsg.append("--coordinate argument is required\n"); } if (line.hasOption("species")) { species = line.getOptionValue("species").replaceAll("\\s+", "_"); } if (line.hasOption("b37")) { if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) { SERVER = GRCh37Server; } else { System.out.println("--b37 argument will be ignored - it can only be " + "used when human is the species of interest. Current species" + " is " + species + ".\n"); } } if (line.hasOption("noncoding")) { mapCdna = true; } if (errorMsg.length() > 0) { showHelp(options, errorMsg.toString(), 2); } int c = 0; boolean threePrimeUtr = false; String prefix = "c."; if (mapCdna) { prefix = "n."; try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } else if (coordinate.startsWith("*")) { threePrimeUtr = true; prefix = "c.*"; String coord = coordinate.replaceFirst("\\*", ""); try { c = Integer.parseInt(coord); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer or UTR coordinate", 2); } } else { try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } //got arguments String result; String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate"; if (!gene.isEmpty()) { IdParser idParser = new IdParser(gene); System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType()); if (idParser.isEnsemblId()) { if (line.hasOption("species")) { System.out.println("Ignoring --species option when searching Ensembl ID."); } if (idParser.isTranscript()) { result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna); } else if (idParser.isEnsp()) { result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna); } } else { if (idParser.isTranscript()) { //append user input to beginning result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna); } } if (idParser.isTranscript() || idParser.isEnsp()) { result = gene + ":" + prefix + c + "\t" + result; } else { result = convertGeneResult(result, gene, c, prefix); } } else { System.out.println("Searching for " + transcript + " as Ensembl transcript ID"); result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna); //append user input to beginning result = transcript + ":" + prefix + c + "\t" + result; } System.out.println(header); System.out.println(result); }
From source file:me.gloriouseggroll.quorrabot.Quorrabot.java
public static void main(String[] args) throws IOException { String user = ""; String oauth = ""; String apioauth = ""; String channelName = ""; String webauth = ""; String webauthro = ""; String clientid = ""; String owner = ""; String hostname = ""; int baseport = 25300; InetAddress ip = InetAddress.getByName("127.0.0.1"); int port = 0; double msglimit30 = 18.75; String datastore = ""; String datastoreconfig = ""; String youtubekey = ""; String gamewispauth = ""; String gamewisprefresh = ""; String twitchalertstoken = ""; String lastfmuser = ""; String tpetoken = ""; String twittertoken = ""; String twittertokensecret = ""; String streamtiptoken = ""; String streamtipid = ""; boolean webenable = true; boolean musicenable = true; boolean usehttps = false; String keystorepath = ""; String keystorepassword = ""; String timeZone = ""; String mySqlConn = ""; String mySqlHost = ""; String mySqlPort = ""; String mySqlName = ""; String mySqlUser = ""; String mySqlPass = ""; FollowersCache followersCache;/*from ww w . j ava 2 s. co m*/ ChannelUsersCache channelUsersCache; ChannelHostCache hostCache; SubscribersCache subscribersCache; String discordToken = ""; String discordMainChannel = ""; boolean changed = false; try { if (new File("./botlogin.txt").exists()) { String data = FileUtils.readFileToString(new File("./botlogin.txt")); String[] lines = data.replaceAll("\\r", "").split("\\n"); for (String line : lines) { if (line.startsWith("logtimezone=") && line.length() >= 15) { timeZone = line.substring(12); } if (line.startsWith("websocketircab")) { Quorrabot.webSocketIRCAB = true; } if (line.startsWith("user=") && line.length() > 8) { user = line.substring(5); } if (line.startsWith("oauth=") && line.length() > 9) { oauth = line.substring(6); } if (line.startsWith("apioauth=") && line.length() > 12) { apioauth = line.substring(9); } if (line.startsWith("clientid=") && line.length() > 12) { clientid = line.substring(9); } if (line.startsWith("channel=") && line.length() > 11) { channelName = line.substring(8); } if (line.startsWith("owner=") && line.length() > 9) { owner = line.substring(6); } if (line.startsWith("baseport=") && line.length() > 10) { baseport = Integer.parseInt(line.substring(9)); } if (line.startsWith("ip=") && line.length() > 4) { ip = InetAddress.getByName(line.substring(3)); } if (line.startsWith("hostname=") && line.length() > 10) { hostname = line.substring(9); } if (line.startsWith("port=") && line.length() > 6) { port = Integer.parseInt(line.substring(5)); } if (line.startsWith("msglimit30=") && line.length() > 12) { msglimit30 = Double.parseDouble(line.substring(11)); } if (line.startsWith("datastore=") && line.length() > 11) { datastore = line.substring(10); } if (line.startsWith("youtubekey=") && line.length() > 12) { youtubekey = line.substring(11); } if (line.startsWith("gamewispauth=") && line.length() > 14) { gamewispauth = line.substring(13); } if (line.startsWith("gamewisprefresh=") && line.length() > 17) { gamewisprefresh = line.substring(16); } if (line.startsWith("twitchalertstoken=") && line.length() > 19) { twitchalertstoken = line.substring(18); } if (line.startsWith("lastfmuser=") && line.length() > 12) { lastfmuser = line.substring(11); } if (line.startsWith("tpetoken=") && line.length() > 10) { tpetoken = line.substring(9); } if (line.startsWith("twittertoken=") && line.length() > 14) { twittertoken = line.substring(13); } if (line.startsWith("twittertokensecret=") && line.length() > 20) { twittertokensecret = line.substring(19); } if (line.startsWith("streamtiptoken=") && line.length() > 16) { streamtiptoken = line.substring(15); } if (line.startsWith("streamtipid=") && line.length() > 13) { streamtipid = line.substring(12); } if (line.startsWith("webenable=") && line.length() > 11) { webenable = Boolean.valueOf(line.substring(10)); } if (line.startsWith("musicenable=") && line.length() > 13) { musicenable = Boolean.valueOf(line.substring(12)); } if (line.startsWith("usehttps=") && line.length() > 10) { usehttps = Boolean.valueOf(line.substring(9)); } if (line.startsWith("mysqlhost=") && line.length() > 11) { mySqlHost = line.substring(10); } if (line.startsWith("mysqlport=") && line.length() > 11) { mySqlPort = line.substring(10); } if (line.startsWith("mysqlname=") && line.length() > 11) { mySqlName = line.substring(10); } if (line.startsWith("mysqluser=") && line.length() > 11) { mySqlUser = line.substring(10); } if (line.startsWith("mysqlpass=") && line.length() > 11) { mySqlPass = line.substring(10); } if (line.startsWith("keystorepath=") && line.length() > 14) { keystorepath = line.substring(13); } if (line.startsWith("keystorepassword=") && line.length() > 18) { keystorepassword = line.substring(17); } if (line.startsWith("webauth=") && line.length() > 9) { webauth = line.substring(8); } if (line.startsWith("webauthro=") && line.length() > 11) { webauthro = line.substring(10); } if (line.startsWith("discordtoken=") && line.length() >= 14) { discordToken = line.substring(13); } if (line.startsWith("discordmainchannel=") && line.length() >= 20) { discordMainChannel = line.substring(19); } } } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } /** * Check to see if there's a soundboardauth set */ if (webauth.isEmpty()) { webauth = generateWebAuth(); com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt"); changed = true; } /** * Check to see if there's a soundboardauthread set */ if (webauthro.isEmpty()) { webauthro = generateWebAuth(); com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt"); changed = true; } try { if (user.isEmpty()) { com.gmt2001.Console.out.print("Please enter the bot's twitch username: "); user = System.console().readLine().trim().toLowerCase(); changed = true; } if (oauth.isEmpty()) { com.gmt2001.Console.out.println( "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below."); com.gmt2001.Console.out .println("IMPORTANT: This MUST be done while logged in as the BOT account!" + "\n"); com.gmt2001.Console.out.println("Please enter the bot's tmi oauth token: "); oauth = System.console().readLine().trim(); changed = true; } if (channelName.isEmpty()) { com.gmt2001.Console.out.print( "Please enter the name of the twitch channel the bot should join (not the url, just the name): "); channelName = System.console().readLine().trim().toLowerCase(); changed = true; } if (apioauth.isEmpty()) { com.gmt2001.Console.out.println( "Visit http://quorrabot.com/pages/twitchapi/ to generate oAuth tokens for both the bot and the channel owner accounts (including 'oauth:') & type it below."); com.gmt2001.Console.out.println( "IMPORTANT: This MUST be done while logged in on the CHANNEL OWNER account!" + "\n"); com.gmt2001.Console.out.println("Please enter the channel owner's tmi oauth token: "); apioauth = System.console().readLine().trim(); changed = true; } } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); } if (owner.isEmpty()) { owner = channelName; changed = true; } if (args.length > 0) { for (String arg : args) { if (arg.equalsIgnoreCase("printlogin")) { com.gmt2001.Console.out.println("user='" + user + "'"); com.gmt2001.Console.out.println("oauth='" + oauth + "'"); com.gmt2001.Console.out.println("apioauth='" + apioauth + "'"); com.gmt2001.Console.out.println("clientid='" + clientid + "'"); com.gmt2001.Console.out.println("channel='" + channelName + "'"); com.gmt2001.Console.out.println("owner='" + owner + "'"); com.gmt2001.Console.out.println("baseport='" + baseport + "'"); com.gmt2001.Console.out.println("ip='" + ip.getHostAddress() + "'"); com.gmt2001.Console.out.println("hostname='" + hostname + "'"); com.gmt2001.Console.out.println("port='" + port + "'"); com.gmt2001.Console.out.println("msglimit30='" + msglimit30 + "'"); com.gmt2001.Console.out.println("datastore='" + datastore + "'"); com.gmt2001.Console.out.println("youtubekey='" + youtubekey + "'"); com.gmt2001.Console.out.println("gamewispauth=" + gamewispauth + "'"); com.gmt2001.Console.out.println("gamewisprefresh=" + gamewisprefresh + "'"); com.gmt2001.Console.out.println("twitchalertstoken='" + twitchalertstoken + "'"); com.gmt2001.Console.out.println("lastfmuser='" + lastfmuser + "'"); com.gmt2001.Console.out.println("tpetoken='" + tpetoken + "'"); com.gmt2001.Console.out.println("twittertoken='" + twittertoken + "'"); com.gmt2001.Console.out.println("twittertokensecret='" + twittertokensecret + "'"); com.gmt2001.Console.out.println("streamtiptoken='" + streamtiptoken + "'"); com.gmt2001.Console.out.println("streamtipid='" + streamtipid + "'"); com.gmt2001.Console.out.println("webenable=" + webenable); com.gmt2001.Console.out.println("musicenable=" + musicenable); com.gmt2001.Console.out.println("usehttps=" + usehttps); com.gmt2001.Console.out.println("keystorepath='" + keystorepath + "'"); com.gmt2001.Console.out.println("keystorepassword='" + keystorepassword + "'"); com.gmt2001.Console.out.println("discordtoken='" + discordToken + "'"); com.gmt2001.Console.out.println("discordmainchannel='" + discordMainChannel + "'"); } if (arg.equalsIgnoreCase("debugon")) { Quorrabot.enableDebugging = true; } if (arg.equalsIgnoreCase("ini2sqlite")) { com.gmt2001.Console.out.println("Converting default IniStore to default SqliteStore..."); ini2sqlite(false); com.gmt2001.Console.out.println("Operation complete. The bot will now exit"); System.exit(0); return; } if (arg.toLowerCase().startsWith("user=") && arg.length() > 8) { if (!user.equals(arg.substring(5))) { user = arg.substring(5).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("oauth=") && arg.length() > 9) { if (!oauth.equals(arg.substring(6))) { oauth = arg.substring(6); changed = true; } } if (arg.toLowerCase().startsWith("apioauth=") && arg.length() > 12) { if (!apioauth.equals(arg.substring(9))) { apioauth = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("mysqlhost=") && arg.length() > 11) { if (!mySqlHost.equals(arg.substring(10))) { mySqlHost = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlport=") && arg.length() > 11) { if (!mySqlPort.equals(arg.substring(10))) { mySqlPort = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlname=") && arg.length() > 11) { if (!mySqlName.equals(arg.substring(10))) { mySqlName = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqluser=") && arg.length() > 11) { if (!mySqlUser.equals(arg.substring(14))) { mySqlUser = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("mysqlpass=") && arg.length() > 11) { if (!mySqlPass.equals(arg.substring(10))) { mySqlPass = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("clientid=") && arg.length() > 12) { if (!clientid.equals(arg.substring(9))) { clientid = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("channel=") && arg.length() > 11) { if (!channelName.equals(arg.substring(8))) { channelName = arg.substring(8).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("owner=") && arg.length() > 9) { if (!owner.equals(arg.substring(6))) { owner = arg.substring(6).toLowerCase(); changed = true; } } if (arg.toLowerCase().startsWith("baseport=") && arg.length() > 10) { if (baseport != Integer.parseInt(arg.substring(9))) { baseport = Integer.parseInt(arg.substring(9)); changed = true; } } if (arg.toLowerCase().startsWith("ip=") && arg.length() > 4) { if (ip != InetAddress.getByName(arg.substring(3))) { ip = InetAddress.getByName(arg.substring(3)); changed = true; } } if (arg.toLowerCase().startsWith("hostname=") && arg.length() > 10) { if (!hostname.equals(arg.substring(9))) { hostname = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("port=") && arg.length() > 6) { if (port != Integer.parseInt(arg.substring(5))) { port = Integer.parseInt(arg.substring(5)); changed = true; } } if (arg.toLowerCase().startsWith("msglimit30=") && arg.length() > 12) { if (msglimit30 != Double.parseDouble(arg.substring(11))) { msglimit30 = Double.parseDouble(arg.substring(11)); changed = true; } } if (arg.toLowerCase().startsWith("datastore=") && arg.length() > 11) { if (!datastore.equals(arg.substring(10))) { datastore = arg.substring(10); changed = true; } } if (arg.toLowerCase().startsWith("datastoreconfig=") && arg.length() > 17) { datastoreconfig = arg.substring(16); } if (arg.toLowerCase().startsWith("youtubekey=") && arg.length() > 12) { if (!youtubekey.equals(arg.substring(11))) { youtubekey = arg.substring(11); changed = true; } } if (arg.toLowerCase().startsWith("gamewispauth=") && arg.length() > 14) { if (!gamewispauth.equals(arg.substring(13))) { gamewispauth = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("gamewisprefresh=") && arg.length() > 17) { if (!gamewisprefresh.equals(arg.substring(16))) { gamewisprefresh = arg.substring(16); changed = true; } } if (arg.toLowerCase().startsWith("twitchalertstoken=") && arg.length() > 19) { if (!twitchalertstoken.equals(arg.substring(18))) { twitchalertstoken = arg.substring(18); changed = true; } } if (arg.toLowerCase().startsWith("lastfmuser=") && arg.length() > 12) { if (!lastfmuser.equals(arg.substring(11))) { lastfmuser = arg.substring(11); changed = true; } } if (arg.toLowerCase().startsWith("tpetoken=") && arg.length() > 10) { if (!tpetoken.equals(arg.substring(9))) { tpetoken = arg.substring(9); changed = true; } } if (arg.toLowerCase().startsWith("twittertoken=") && arg.length() > 14) { if (!twittertoken.equals(arg.substring(13))) { twittertoken = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("twittertokensecret=") && arg.length() > 20) { if (!twittertokensecret.equals(arg.substring(19))) { twittertokensecret = arg.substring(19); changed = true; } } if (arg.toLowerCase().startsWith("streamtiptoken=") && arg.length() > 16) { if (!streamtiptoken.equals(arg.substring(15))) { streamtiptoken = arg.substring(15); changed = true; } } if (arg.toLowerCase().startsWith("streamtipid=") && arg.length() > 13) { if (!streamtipid.equals(arg.substring(12))) { streamtipid = arg.substring(12); changed = true; } } if (arg.toLowerCase().startsWith("webenable=") && arg.length() > 11) { if (webenable != Boolean.valueOf(arg.substring(10))) { webenable = Boolean.valueOf(arg.substring(10)); changed = true; } } if (arg.toLowerCase().startsWith("musicenable=") && arg.length() > 13) { if (musicenable != Boolean.valueOf(arg.substring(12))) { musicenable = Boolean.valueOf(arg.substring(12)); changed = true; } } if (arg.toLowerCase().startsWith("usehttps=") && arg.length() > 10) { if (usehttps != Boolean.valueOf(arg.substring(9))) { usehttps = Boolean.valueOf(arg.substring(9)); changed = true; } } if (arg.toLowerCase().startsWith("keystorepath=") && arg.length() > 14) { if (!keystorepath.equals(arg.substring(13))) { keystorepath = arg.substring(13); changed = true; } } if (arg.toLowerCase().startsWith("keystorepassword=") && arg.length() > 18) { if (!keystorepassword.equals(arg.substring(17))) { keystorepassword = arg.substring(17); changed = true; } } if (arg.equalsIgnoreCase("help") || arg.equalsIgnoreCase("--help") || arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-?")) { com.gmt2001.Console.out.println( "Usage: java -Dfile.encoding=UTF-8 -jar QuorraBot.jar [printlogin] [user=<bot username>] " + "[oauth=<bot irc oauth>] [apioauth=<editor oauth>] [clientid=<oauth clientid>] [channel=<channel to join>] " + "[owner=<bot owner username>] [baseport=<bot webserver port, music server will be +1>] [ip=<IP address (optional) to bind to>] [hostname=<custom irc server>] " + "[port=<custom irc port>] [msglimit30=<message limit per 30 seconds>] " + "[datastore=<DataStore type, for a list, run java -jar QuorraBot.jar storetypes>] " + "[datastoreconfig=<Optional DataStore config option, different for each DataStore type>] " + "[youtubekey=<youtube api key>] [webenable=<true | false>] [musicenable=<true | false>] " + "[gamewispauth=<gamewisp oauth>] " + "[gamewisprefresh=<gamewisp refresh key>] " + "[twitchalertstoken=<TwitchAlerts access token>] " + "[lastfmuser=<Last.FM username>] " + "[tpetoken=<Tipeeestream access token>] " + "[streamtiptoken=<StreamTip access token>] " + "[streamtipid=<StreamTip Client ID>] " + "[twittertoken=<Twitter access token>] " + "[twittertokensecret=<Twitter access token secret>]"); return; } if (arg.equalsIgnoreCase("storetypes")) { com.gmt2001.Console.out.println( "DataStore types: IniStore (datastoreconfig parameter is folder name, stores in .ini files), " + "TempStore (Stores in memory, lost on shutdown), " + "SqliteStore (Default, Stores in a SQLite3 database, datastoreconfig parameter is a config file"); return; } } } if (changed) { String data = ""; data += "user=" + user + "\r\n"; data += "oauth=" + oauth + "\r\n"; data += "apioauth=" + apioauth + "\r\n"; data += "clientid=" + clientid + "\r\n"; data += "webauth=" + webauth + "\r\n"; data += "webauthro=" + webauthro + "\r\n"; data += "channel=" + channelName + "\r\n"; data += "owner=" + owner + "\r\n"; data += "baseport=" + baseport + "\r\n"; data += "ip=" + ip.getHostAddress() + "\r\n"; data += "hostname=" + hostname + "\r\n"; data += "port=" + port + "\r\n"; data += "msglimit30=" + msglimit30 + "\r\n"; data += "datastore=" + datastore + "\r\n"; data += "youtubekey=" + youtubekey + "\r\n"; data += "gamewispauth=" + gamewispauth + "\r\n"; data += "gamewisprefresh=" + gamewisprefresh + "\r\n"; data += "twitchalertstoken=" + twitchalertstoken + "\r\n"; data += "lastfmuser=" + lastfmuser + "\r\n"; data += "tpetoken=" + tpetoken + "\r\n"; data += "twittertoken=" + twittertoken + "\r\n"; data += "twittertokensecret=" + twittertokensecret + "\r\n"; data += "streamtiptoken=" + streamtiptoken + "\r\n"; data += "streamtipid=" + streamtipid + "\r\n"; data += "webenable=" + webenable + "\r\n"; data += "musicenable=" + musicenable + "\r\n"; data += "usehttps=" + usehttps + "\r\n"; data += "logtimezone=" + timeZone + "\r\n"; data += "mysqlhost=" + mySqlHost + "\r\n"; data += "mysqlport=" + mySqlPort + "\r\n"; data += "mysqlname=" + mySqlName + "\r\n"; data += "mysqluser=" + mySqlUser + "\r\n"; data += "mysqlpass=" + mySqlPass + "\r\n"; data += "keystorepath=" + keystorepath + "\r\n"; data += "keystorepassword=" + keystorepassword + "\r\n"; data += "discordtoken=" + discordToken + "\r\n"; data += "discordmainchannel=" + discordMainChannel; Files.write(Paths.get("./botlogin.txt"), data.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } channelUsersCache = ChannelUsersCache.instance(owner); followersCache = FollowersCache.instance(owner); hostCache = ChannelHostCache.instance(owner); subscribersCache = SubscribersCache.instance(owner); Quorrabot.instance = new Quorrabot(user, oauth, apioauth, clientid, channelName, owner, baseport, ip, hostname, port, msglimit30, datastore, datastoreconfig, youtubekey, gamewispauth, gamewisprefresh, twitchalertstoken, lastfmuser, tpetoken, twittertoken, twittertokensecret, streamtiptoken, streamtipid, webenable, webauth, webauthro, musicenable, usehttps, timeZone, mySqlHost, mySqlPort, mySqlConn, mySqlPass, mySqlUser, mySqlName, keystorepath, followersCache, hostCache, channelUsersCache, subscribersCache, discordToken, discordMainChannel); }
From source file:Writer.java
/** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage();/*from w ww .j a va2 s .c om*/ System.exit(1); } // variables Writer writer = null; XMLReader parser = null; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean externalDTD = DEFAULT_LOAD_EXTERNAL_DTD; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean xincludeProcessing = DEFAULT_XINCLUDE; boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS; boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE; boolean canonical = DEFAULT_CANONICAL; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser (" + parserName + ")"); e.printStackTrace(System.err); } } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("xd")) { externalDTD = option.equals("xd"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("xi")) { xincludeProcessing = option.equals("xi"); continue; } if (option.equalsIgnoreCase("xb")) { xincludeFixupBaseURIs = option.equals("xb"); continue; } if (option.equalsIgnoreCase("xl")) { xincludeFixupLanguage = option.equals("xl"); continue; } if (option.equalsIgnoreCase("c")) { canonical = option.equals("c"); continue; } if (option.equals("h")) { printUsage(); continue; } } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")"); e.printStackTrace(System.err); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println( "warning: Parser does not support feature (" + NAMESPACE_PREFIXES_FEATURE_ID + ")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(LOAD_EXTERNAL_DTD_FEATURE_ID, externalDTD); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + LOAD_EXTERNAL_DTD_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")"); } try { parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")"); } try { parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")"); } try { parser.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing); } catch (SAXNotRecognizedException e) { System.err.println("warning: Parser does not recognize feature (" + XINCLUDE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")"); } try { parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage); } catch (SAXNotRecognizedException e) { System.err.println( "warning: Parser does not recognize feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } catch (SAXNotSupportedException e) { System.err.println( "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")"); } // setup writer if (writer == null) { writer = new Writer(); try { writer.setOutput(System.out, "UTF8"); } catch (UnsupportedEncodingException e) { System.err.println("error: Unable to set output. Exiting."); System.exit(1); } } // set parser parser.setContentHandler(writer); parser.setErrorHandler(writer); try { parser.setProperty(LEXICAL_HANDLER_PROPERTY_ID, writer); } catch (SAXException e) { // ignore } // parse file writer.setCanonical(canonical); try { parser.parse(arg); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - " + e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException) e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } }
From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java
public static void main(String args[]) { int numberEvents = 10000; //int brake = 1000; String server = "ags104"; int in_port = 5565; int out_port = 5575; int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("s", true, "Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("o", true, "Output TCP Port"); opts.addOption("r", true, "Range"); opts.addOption("h", false, "Help"); try {//from ww w . j ava2 s . c o m CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("s")) { server = cmd.getOptionValue("s"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { in_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("o")) { String val = cmd.getOptionValue("o"); try { out_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for o. Must be integer.\n"; } } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new ParseException("Rate must be three comma seperated values or a single value"); } } catch (ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new ParseException(cmdInputErrorMsg); } DecimalFormat df = new DecimalFormat("##0"); RunTcpInTcpOutTest t = new RunTcpInTcpOutTest(); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, server, in_port, out_port, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); //for (int rate: rates) { for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, server, in_port, out_port, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumEvents -s Server -i InputPort -o OutputPort -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }