List of usage examples for java.io File separator
String separator
To view the source code for java.io File separator.
Click Source Link
From source file:com.galois.fiveui.HeadlessRunner.java
/** * @param args list of headless run description filenames * @throws IOException/*from w w w .ja v a 2 s . com*/ * @throws URISyntaxException * @throws ParseException */ @SuppressWarnings("static-access") public static void main(final String[] args) throws IOException, URISyntaxException, ParseException { // Setup command line options Options options = new Options(); Option help = new Option("h", "print this help message"); Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file") .create("o"); Option report = OptionBuilder.withArgName("report directory").hasArg() .withDescription("write HTML reports to given directory").create("r"); options.addOption(output); options.addOption(report); options.addOption("v", false, "verbose output"); options.addOption("vv", false, "VERY verbose output"); options.addOption(help); // Parse command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line option parsing failed. Reason: " + e.getMessage()); System.exit(1); } // Display help if requested if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("headless <input file 1> [<input file 2> ...]", options); System.exit(1); } // Set logging levels BasicConfigurator.configure(); Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui"); Logger rootLogger = Logger.getRootLogger(); if (cmd.hasOption("v")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.ERROR); } else if (cmd.hasOption("vv")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); } else { fiveuiLogger.setLevel(Level.ERROR); rootLogger.setLevel(Level.ERROR); } // Setup output file if requested PrintWriter outStream = null; if (cmd.hasOption("o")) { String outfile = cmd.getOptionValue("o"); try { outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } catch (IOException e) { System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile")); System.exit(1); } } else { outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); } // Setup HTML reports directory before the major work happens in case we // have to throw an exception. PrintWriter summaryFile = null; PrintWriter byURLFile = null; PrintWriter byRuleFile = null; if (cmd.hasOption("r")) { String repDir = cmd.getOptionValue("r"); try { File file = new File(repDir); if (!file.exists()) { file.mkdir(); logger.info("report directory created: " + repDir); } else { logger.info("report directory already exists!"); } summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html")); byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html")); byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html")); } catch (IOException e) { System.err.println("could not open report directory / files for writing"); System.exit(1); } } // Major work: process input files ImmutableList<Result> results = null; for (String in : cmd.getArgs()) { HeadlessRunDescription descr = HeadlessRunDescription.parse(in); logger.debug("invoking headless run..."); BatchRunner runner = new BatchRunner(); results = runner.runHeadless(descr); logger.debug("runHeadless returned " + results.size() + " results"); // write results to the output stream as we go for (Result result : results) { outStream.println(result.toString()); } outStream.flush(); } outStream.close(); // Write report files if requested if (cmd.hasOption("r") && results != null) { Reporter kermit = new Reporter(results); summaryFile.write(kermit.getSummary()); summaryFile.close(); byURLFile.write(kermit.getByURL()); byURLFile.close(); byRuleFile.write(kermit.getByRule()); byRuleFile.close(); } }
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/* w w w .j a va 2s . c om*/ * * 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:com.doculibre.constellio.utils.ConstellioAnnotationUtils.java
public static void main(String[] args) { // Will write the code that needs to be placed in addAnnotatedClasses(AnnotationConfiguration) // method...// w ww . j a v a 2 s.c o m File srcDir = new File(args[0]); String entitiesDirPath = "com.doculibre.constellio.entities".replace(".", File.separator); File entitiesDir = new File(srcDir, entitiesDirPath); List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(entitiesDir, new String[] { ".java" }, true); for (File javaFile : javaFiles) { System.out.println("config.addAnnotatedClass(" + javaFile.getName().replace("java", ".class") + ");"); } }
From source file:iac.cnr.it.TestSearcher.java
public static void main(String[] args) throws IOException, ParseException { /** Command line parser and options */ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OPT_INDEX, true, "Index path"); options.addOption(OPT_QUERY, true, "The query"); CommandLine cmd = null;/* w w w . jav a 2 s.co m*/ try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { logger.fatal("Error while parsing command line arguments"); System.exit(1); } /** Check for mandatory options */ if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) { usage(); System.exit(0); } /** Read options */ File casePath = new File(cmd.getOptionValue(OPT_INDEX)); String query = cmd.getOptionValue(OPT_QUERY); /** Check correctness of the path containing an ISODAC case */ if (!casePath.exists() || !casePath.isDirectory()) { logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid"); System.exit(1); } /** Check existance of the info.dat file */ File infoFile = new File(casePath, INFO_FILENAME); if (!infoFile.exists()) { logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")"); System.exit(1); } /** Load the mapping image_uuid --> image_filename */ imagesMap = new HashMap<Integer, String>(); BufferedReader reader = new BufferedReader(new FileReader(infoFile)); while (reader.ready()) { String line = reader.readLine(); logger.info("Read the line: " + line); String currentID = line.split("\t")[0]; String currentImgFile = line.split("\t")[1]; imagesMap.put(Integer.parseInt(currentID), currentImgFile); logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map"); } reader.close(); /** Load all the directories containing an index */ ArrayList<String> indexesDirs = new ArrayList<String>(); for (File f : casePath.listFiles()) { logger.info("Analyzing: " + f); if (f.isDirectory()) indexesDirs.add(f.getAbsolutePath()); } logger.info(indexesDirs.size() + " directories found!"); /** Set-up the searcher */ Searcher searcher = null; try { String[] array = indexesDirs.toArray(new String[indexesDirs.size()]); searcher = new Searcher(array); TopDocs results = searcher.search(query, Integer.MAX_VALUE); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; System.out.println(numTotalHits + " total matching documents"); for (int i = 0; i < numTotalHits; i++) { Document doc = searcher.doc(hits[i].doc); String path = doc.get(FIELD_PATH); String filename = doc.get(FIELD_FILENAME); String image_uuid = doc.get(FIELD_IMAGE_ID); if (path != null) { //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score); // System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid); System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + imagesMap.get(Integer.parseInt(image_uuid))); } else { System.out.println((i + 1) + ". " + "No path for this document"); } } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } finally { if (searcher != null) searcher.close(); } }
From source file:edu.ku.brc.dbsupport.ImportExportDB.java
public static void main(String[] args) { Pair<String, String> usernamePassword = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB(); UIHelper.tryLogin("com.mysql.jdbc.Driver", "org.hibernate.dialect.MySQLDialect", //$NON-NLS-1$ //$NON-NLS-2$ "testfish", "jdbc:mysql://localhost/testfish", //$NON-NLS-1$ //$NON-NLS-2$ usernamePassword.first, usernamePassword.second); Session testSession = HibernateUtil.getCurrentSession(); String workingFolder = "Specify6ImportExport"; //$NON-NLS-1$ File wf = new File(workingFolder); if (!wf.exists()) { wf.mkdirs();/*from w ww. j a v a 2 s. com*/ } //String dbTable = "Division"; //$NON-NLS-1$ ImportExportDB impexp = new ImportExportDB(testSession, workingFolder + File.separator); try { // record set // impexp.importSingleDBObject(dbTable, 1, false); // impexp.printRecordSet(dbTable); // impexp.printSingleRecordXML(dbTable, 3); // impexp.writeRecordSet(dbTable, 1); // impexp.writeSingleRecordXML(dbTable, 1); // impexp.exportTables(); // List<String> temp = new ArrayList(); // impexp.getImmediateParentTables(dbTable,temp , false); // impexp.getRequiredFields("Geography"); // import System.out.println("importing..."); //$NON-NLS-1$ // impexp.importTable(dbTable); // impexp.importTable("LoanAgent"); // print results System.out.println("printing..."); //$NON-NLS-1$ //impexp.printXML(dbTable); // impexp.printXML("Geography"); // impexp.printXML("LoanAgent"); // impexp.printXML("CollectionObject"); // impexp.printXML("LoanReturnPreparation"); // impexp.printXML("CollectionObject"); // impexp.printXML("Collector"); // export // impexp.writeSingleRecordXML(dbTable,1); //impexp.exportTables(); impexp.writeXMLfile("PrepType"); //$NON-NLS-1$ } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImportExportDB.class, ex); ex.printStackTrace(); } finally { impexp.close(); System.out.println("...done"); //$NON-NLS-1$ } }
From source file:com.smartmarmot.dbforbix.DBforBix.java
public static void main(final String[] args) { Config config = Config.getInstance(); String action = ""; options = new Options(); options.addOption("v", false, "display version and exit"); options.addOption("t", false, "test configuration"); options.addOption("h", false, "display help"); options.addOption("b", true, "base directory"); options.addOption("c", true, "config file location"); // options.addOption("d", false, "enable debugging"); options.addOption("C", false, "enable console output"); options.addOption("a", true, "action (start/stop/status)"); // handle command line parameters try {/* ww w . java 2 s .c om*/ CommandLineParser cmdparser = new DefaultParser(); CommandLine cmd = cmdparser.parse(options, args); if (cmd.hasOption("v")) { System.out.println(Constants.BANNER); System.exit(0); } if (cmd.hasOption("t")) { System.out.println("not implemented"); System.exit(0); } if (args.length == 0 || cmd.hasOption("h")) { displayUsage(); System.exit(0); } // if (cmd.hasOption("d")) { // debug = true; // Logger.getRootLogger().setLevel(Level.ALL); // } if (cmd.hasOption("C")) Logger.getRootLogger().addAppender(new ConsoleAppender(new SimpleLayout())); action = cmd.getOptionValue("a", "help"); /** * set config file path */ config.setBasedir(cmd.getOptionValue("b", ".")); config.setConfigFile(cmd.getOptionValue("c", config.getBasedir() + File.separator + "conf" + File.separator + "config.properties")); } catch (ParseException e) { System.err.println("Error in parameters: " + e.getLocalizedMessage()); System.exit(-1); } //autoupdate cycle while (true) { try { switch (action.toLowerCase()) { case "start": { reinit(); LOG.info("Starting " + Constants.BANNER); // writePid(_pid, _pidfile); _zabbixSender = new ZabbixSender(ZabbixSender.PROTOCOL.V32); _zabbixSender.updateServerList(config.getZabbixServers().toArray(new ZabbixServer[0])); _zabbixSender.start(); //persSender = new PersistentDBSender(PersistentDBSender.PROTOCOL.V18); //persSender.updateServerList(config.getZabbixServers().toArray(new ZServer[0])); //persSender.start(); config.startChecks(); action = "update"; } break; case "update": { LOG.info("Sleeping before configuration update..."); Thread.sleep(config.getUpdateConfigTimeout() * 1000); LOG.info("Updating DBforBix configuration..."); if (config.checkConfigChanges()) action = "stop"; } break; case "stop": { LOG.info("Stopping DBforBix..."); config = config.reset(); if (_zabbixSender != null) { _zabbixSender.terminate(); while (_zabbixSender.isAlive()) Thread.yield(); } //workTimers=new HashMap<String, Timer>(); _zabbixSender = null; if (persSender != null) { persSender.terminate(); while (persSender.isAlive()) Thread.yield(); } DBManager dbman = DBManager.getInstance(); dbman = dbman.cleanAll(); action = "start"; } break; default: { LOG.error("Unknown action " + action); System.exit(-5); } break; } } catch (Throwable th) { LOG.fatal("DBforBix crashed!", th); } } }
From source file:contractEditor.contractClients.java
public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "clientTemplate"); obj.put("context", "VM-deployment"); //obj.put("Context", new Integer); HashMap serviceRequirement = new HashMap(); HashMap serviceDescription = new HashMap(); serviceRequirement.put("VM1_volume", "18_GB"); serviceDescription.put("VM1_purpose", "dev"); serviceDescription.put("VM1_data", "private"); serviceDescription.put("VM1_application", "internal"); serviceRequirement.put("VM2_volume", "20_GB"); serviceDescription.put("VM2_purpose", "prod"); serviceDescription.put("VM2_data", "public"); serviceDescription.put("VM2_application", "business"); serviceRequirement.put("VM3_volume", "30_GB"); serviceDescription.put("VM3_purpose", "test"); serviceDescription.put("VM3_data", "public"); serviceDescription.put("VM3_application", "business"); serviceRequirement.put("VM4_volume", "20_GB"); serviceDescription.put("VM4_purpose", "prod"); serviceDescription.put("VM4_data", "public"); serviceDescription.put("VM4_application", "business"); obj.put("serviceRequirement", serviceRequirement); obj.put("serviceDescription", serviceDescription); HashMap gauranteeTerm = new HashMap(); gauranteeTerm.put("VM1_availability", "more_97_percentage"); gauranteeTerm.put("VM2_availability", "more_99_percentage"); gauranteeTerm.put("VM3_availability", "more_95_percentage"); gauranteeTerm.put("VM4_availability", "more_99_percentage"); obj.put("gauranteeTerm", gauranteeTerm); //Constraint1 HashMap host_rule1 = new HashMap(); HashMap VM_rule1 = new HashMap(); host_rule1.put("certificate", "true"); VM_rule1.put("purpose", "dev"); ArrayList rule1 = new ArrayList(); rule1.add("permission"); rule1.add(host_rule1);//from w w w . j av a 2 s .c om rule1.add(VM_rule1); HashMap host_rule1_2 = new HashMap(); HashMap VM_rule1_2 = new HashMap(); host_rule1_2.put("certificate", "true"); VM_rule1_2.put("purpose", "prod"); ArrayList rule1_2 = new ArrayList(); rule1_2.add("permission"); rule1_2.add(host_rule1_2); rule1_2.add(VM_rule1_2); HashMap host_rule1_3 = new HashMap(); HashMap VM_rule1_3 = new HashMap(); host_rule1_3.put("certificate", "true"); VM_rule1_3.put("purpose", "test"); ArrayList rule1_3 = new ArrayList(); rule1_3.add("permission"); rule1_3.add(host_rule1_3); rule1_3.add(VM_rule1_3); HashMap host_rule2 = new HashMap(); HashMap VM_rule2 = new HashMap(); host_rule2.put("location", "France"); VM_rule2.put("ID", "VM2"); ArrayList rule2 = new ArrayList(); rule2.add("permission"); rule2.add(host_rule2); rule2.add(VM_rule2); HashMap host_rule2_1 = new HashMap(); HashMap VM_rule2_1 = new HashMap(); host_rule2_1.put("location", "UK"); VM_rule2_1.put("ID", "VM2"); ArrayList rule2_1 = new ArrayList(); rule2_1.add("permission"); rule2_1.add(host_rule2_1); rule2_1.add(VM_rule2_1); HashMap host_rule3 = new HashMap(); HashMap VM_rule3 = new HashMap(); host_rule3.put("location", "France"); VM_rule3.put("application", "business"); ArrayList rule3 = new ArrayList(); rule3.add("permission"); rule3.add(host_rule3); rule3.add(VM_rule3); HashMap host_rule3_1 = new HashMap(); HashMap VM_rule3_1 = new HashMap(); host_rule3_1.put("location", "UK"); VM_rule3_1.put("application", "business"); ArrayList rule3_1 = new ArrayList(); rule3_1.add("permission"); rule3_1.add(host_rule3_1); rule3_1.add(VM_rule3_1); HashMap VMSeperation_rule_1_1 = new HashMap(); HashMap VMSeperation_rule_1_2 = new HashMap(); VMSeperation_rule_1_1.put("ID", "VM1"); VMSeperation_rule_1_2.put("ID", "VM3"); ArrayList rule4 = new ArrayList(); rule4.add("separation"); rule4.add(VMSeperation_rule_1_1); rule4.add(VMSeperation_rule_1_2); ArrayList policyInConstraint1 = new ArrayList(); policyInConstraint1.add(rule1); policyInConstraint1.add(rule1_2); policyInConstraint1.add(rule1_3); policyInConstraint1.add(rule2); policyInConstraint1.add(rule2_1); policyInConstraint1.add(rule3); policyInConstraint1.add(rule3_1); policyInConstraint1.add(rule4); ArrayList creationConstraint1 = new ArrayList(); creationConstraint1.add("RP4"); creationConstraint1.add("true"); creationConstraint1.add("true"); creationConstraint1.add(policyInConstraint1); ArrayList totalConstraint = new ArrayList(); totalConstraint.add(creationConstraint1); obj.put("creationConstraint", totalConstraint); try { FileWriter file = new FileWriter("confClient" + File.separator + "test3.json"); file.write(obj.toJSONString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } System.out.print(obj); /* JSONParser parser = new JSONParser(); try { Object obj2 = parser.parse(new FileReader("test2.json")); JSONObject jsonObject = (JSONObject) obj2; HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription"); method.printHashMap(serviceDescription2); HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm"); method.printHashMap(gauranteeTerm2); ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint"); method.printArrayList(creationConstraint); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } */ }
From source file:at.tuwien.ifs.somtoolbox.apps.VisualisationImageSaver.java
public static void main(String[] args) { JSAPResult res = OptionFactory.parseResults(args, OPTIONS); String uFile = res.getString("unitDescriptionFile"); String wFile = res.getString("weightVectorFile"); String dwmFile = res.getString("dataWinnerMappingFile"); String cFile = res.getString("classInformationFile"); String vFile = res.getString("inputVectorFile"); String tFile = res.getString("templateVectorFile"); String ftype = res.getString("filetype"); boolean unitGrid = res.getBoolean("unitGrid"); String basename = res.getString("basename"); if (basename == null) { basename = FileUtils.extractSOMLibInputPrefix(uFile); }//from w w w . j ava 2 s . c o m basename = new File(basename).getAbsolutePath(); int unitW = res.getInt("width"); int unitH = res.getInt("height", unitW); String[] vizs = res.getStringArray("vis"); GrowingSOM gsom = null; CommonSOMViewerStateData state = CommonSOMViewerStateData.getInstance(); try { SOMLibFormatInputReader inputReader = new SOMLibFormatInputReader(wFile, uFile, null); gsom = new GrowingSOM(inputReader); SharedSOMVisualisationData d = new SharedSOMVisualisationData(cFile, null, null, dwmFile, vFile, tFile, null); d.readAvailableData(); state.inputDataObjects = d; gsom.setSharedInputObjects(d); Visualizations.initVisualizations(d, inputReader, 0, Palettes.getDefaultPalette(), Palettes.getAvailablePalettes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } catch (SOMLibFileFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } if (ArrayUtils.isEmpty(vizs)) { System.out.println("No specific visualisation specified - saving all available visualisations."); vizs = Visualizations.getReadyVisualizationNames(); System.out.println("Found " + vizs.length + ": " + Arrays.toString(vizs)); } for (String viz : vizs) { BackgroundImageVisualizerInstance v = Visualizations.getVisualizationByName(viz); if (v == null) { System.out.println("Visualization '" + viz + "' not found!"); continue; } BackgroundImageVisualizer i = v.getVis(); GrowingLayer layer = gsom.getLayer(); try { int height = unitH * layer.getYSize(); int width = unitW * layer.getXSize(); HashMap<String, BufferedImage> visualizationFlavours = i.getVisualizationFlavours(v.getVariant(), gsom, width, height); ArrayList<String> keys = new ArrayList<String>(visualizationFlavours.keySet()); Collections.sort(keys); // if the visualisation has more than 5 flavours, we create a sub-dir for it String subDirName = ""; String oldBasename = basename; // save original base name for later if (keys.size() > 5) { String parentDir = new File(basename).getParentFile().getPath(); // get the parent path String filePrefix = basename.substring(parentDir.length()); // end the file name prefix subDirName = parentDir + File.separator + filePrefix + "_" + viz + File.separator; // compose a new // subdir name new File(subDirName).mkdir(); // create the dir basename = subDirName + filePrefix; // and extend the base name by the subdir } for (String key : keys) { File out = new File(basename + "_" + viz + key + "." + ftype); System.out.println("Generating visualisation '" + viz + "' as '" + out.getPath() + "'."); BufferedImage image = visualizationFlavours.get(key); if (unitGrid) { VisualisationUtils.drawUnitGrid(image, gsom, width, height); } ImageIO.write(image, ftype, out); } basename = oldBasename; // reset base name } catch (SOMToolboxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.exit(0); }
From source file:com.rtl.http.Upload.java
public static void main(String[] args) throws Exception { if (args.length != 4) { // Jxj001 20150603 d:\rpt_rtl_0001.txt d:\confDir logger.error("??4,dataTypedataVersionfilePathconfDir"); // System.out.println("??3,dataTypedataVersionfilePath"); return;//from w w w . ja va2 s .c o m } else { Upload upload = new Upload(); upload.readInfo(args[3]); Date date = new Date(); DateFormat format1 = new SimpleDateFormat("yyyyMMdd"); String todayDir = format1.format(date); File dir = new File(logDir + File.separator + todayDir); if (dir != null && !dir.exists()) { dir.mkdirs(); } // SimpleLayout layout = new SimpleLayout(); PatternLayout layout = new PatternLayout("%d %-5p %c - %m%n"); FileAppender appender = null; try { appender = new FileAppender(layout, dir.getPath() + File.separator + todayDir + "client.log", true); } catch (Exception e) { logger.error(""); } logger.addAppender(appender); logger.setLevel(Level.INFO); InputStream fileIn; dataType = args[0]; dataVersion = args[1]; filePath = args[2]; logger.info("dataType=" + dataType); logger.info("dataVersion=" + dataVersion); logger.info("filePath=" + filePath); try { File file = new File(filePath); if (!file.exists()) { // System.out.println("?:"+filePath); logger.error("?:" + filePath); return; } fileIn = new FileInputStream(filePath); String responseStr = send(upload.getJson(), fileIn, url); if (responseStr != null) { String[] values = responseStr.split(","); if ("ok".equals(values[0])) { System.out.println("0"); logger.info("ok"); } else { System.out.println("1"); logger.info(" A" + values[1]); } } else { System.out.println("1"); logger.info(" B????"); } } catch (Exception e) { System.out.println("1"); logger.error(" C" + e.getMessage()); } } logger.info("??"); // System.out.println("??"); }
From source file:edu.indiana.d2i.htrc.corpus.analysis.LDAAnalysisDriver.java
public static void main(String[] args) throws Exception { GenericOptionsParser parser = new GenericOptionsParser(new Configuration(), args); CommandLine commandLine = parser.getCommandLine(); Option[] options = commandLine.getOptions(); /**//from w ww. j av a2s . com * appArgs[0] = <path/to/input/directory> (where sequence files reside) * appArgs[1] = <path/to/output/directory/prefix> (where LDA state file * should go) appArgs[2] = <path/local/property/file> * * Note: the passed in <path/to/output/directory/prefix> is only a * prefix, we automatically append the iteration number suffix */ String[] appArgs = parser.getRemainingArgs(); // load property file Properties prop = new Properties(); prop.load(new FileInputStream(appArgs[2])); int maxIterationNum = Integer.parseInt( prop.getProperty(Constants.LDA_ANALYSIS_MAX_ITER, Constants.LDA_ANALYSIS_DEFAULT_MAX_ITER)); int iterationCount = 0; /** * in the first iteration (iteration 0), there is no LDA state */ String[] arguments = generateArgs(options, new String[0], appArgs[0], appArgs[1] + "-iter-" + iterationCount); /** * iterate until convergence or maximum iteration number reached */ while (true) { int exitCode = ToolRunner.run(new LDAAnalysisDriver(), arguments); System.out.println(String.format("LDA analysis finished iteration %d, with exitCode = %d", iterationCount, exitCode)); /** * LDA state is the output (sequence file) from current iteration * and is used to initialize the words-topics table and * topics-documents table for the next iteration */ String ldaStateFilePath = appArgs[1] + "-iter-" + iterationCount + File.separator + "part-r-00000"; /** * load LDA state to check whether it is converged */ if (isAnalysisConverged(ldaStateFilePath)) { System.out.println(String.format("LDA analysis converged at iteration %d", iterationCount)); break; } if ((iterationCount + 1) >= maxIterationNum) { System.out.println(String.format( "LDA analysis reached the maximum iteration number %d, going to stop", maxIterationNum)); break; } String[] otherOps = { "-D", "user.args.lda.state.filepath=" + ldaStateFilePath }; /** * generate arguments for the next iteration and increase iteration * count */ arguments = generateArgs(options, otherOps, appArgs[0], appArgs[1] + "-iter-" + ++iterationCount); } }