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: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 a 2s .co m 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:com.handany.base.generator.Generator.java
public static void main(String[] args) throws IOException { String directoryPath = "src/main/java"; String modelDirectory = directoryPath + File.separator + StringUtils.replace(MODEL_PACKAGE, ".", File.separator) + File.separator; String daoDirectory = directoryPath + File.separator + StringUtils.replace(DAO_PACKAGE, ".", File.separator) + File.separator;// www .ja v a 2 s . c om String serviceDirectory = directoryPath + File.separator + StringUtils.replace(SERVICE_PACKAGE, ".", File.separator) + File.separator; String serviceImplDirectory = directoryPath + File.separator + StringUtils.replace(SERVICE_IMPL_PACKAGE, ".", File.separator) + File.separator; String controllerDirectory = directoryPath + File.separator + StringUtils.replace(CONTROLLER_PACKAGE, ".", File.separator) + File.separator; File fileDirectory = new File(directoryPath); if (!fileDirectory.isDirectory()) { FileUtils.forceMkdir(fileDirectory); } List<TableBean> tableBeanList = getTables(); ArrayList<String> nameList = new ArrayList<>(); // nameList.add("bm_classroom_course"); nameList.add("bm_sales_promotion"); for (TableBean tableBean : tableBeanList) { System.out.println("table:" + tableBean.getTableName()); String tableName = tableBean.getTableName(); if (!nameList.contains(tableName.toLowerCase())) { continue; } Map<String, Object> varMap = new HashMap<>(); varMap.put("tableBean", tableBean); varMap.put("schemaName", SCHEMA_NAME); varMap.put("modelPackage", MODEL_PACKAGE); varMap.put("daoPackage", DAO_PACKAGE); varMap.put("servicePackage", SERVICE_PACKAGE); varMap.put("serviceImplPackage", SERVICE_IMPL_PACKAGE); varMap.put("controllerPackage", CONTROLLER_PACKAGE); Template modelTemplate = FreemarkerUtil.getTemplate("model.ftl"); FreemarkerUtil.outputProcessResult(modelDirectory + tableBean.getTableNameCapitalized() + ".java", modelTemplate, varMap); // Template daoTemplate = FreemarkerUtil.getTemplate("dao.ftl"); // FreemarkerUtil.outputProcessResult(daoDirectory + tableBean.getTableNameCapitalized() + "Mapper.java", daoTemplate, varMap); Template mapperTemplate = FreemarkerUtil.getTemplate("mapper.ftl"); FreemarkerUtil.outputProcessResult(daoDirectory + tableBean.getTableNameCapitalized() + "Mapper.xml", mapperTemplate, varMap); // Template serviceTemplate = FreemarkerUtil.getTemplate("service.ftl"); // FreemarkerUtil.outputProcessResult(serviceDirectory + tableBean.getTableNameCapitalized() + "Service.java", serviceTemplate, varMap); // // Template serviceImplTemplate = FreemarkerUtil.getTemplate("serviceimpl.ftl"); // FreemarkerUtil.outputProcessResult(serviceImplDirectory + tableBean.getTableNameCapitalized() + "ServiceImpl.java", serviceImplTemplate, varMap); // // Template controllerTemplate = FreemarkerUtil.getTemplate("controller.ftl"); // FreemarkerUtil.outputProcessResult(controllerDirectory + tableBean.getTableNameCapitalized() + "Controller.java", controllerTemplate, varMap); } }
From source file:com.mindcognition.mindraider.MindRaiderApplication.java
/** * The main procedure./*w w w . j av a 2 s .c o m*/ * * @param args * program arguments. */ public static void main(String[] args) { boolean help = false; boolean debugMode = false; // analyze arguments if (args != null) { // while there are some arguments try to consume them int i = 0; while (i < args.length) { if (ARG_HELP.equals(args[i]) || "--help".equals(args[i]) //$NON-NLS-1$ || "/h".equals(args[i]) || "/?".equals(args[i])) { //$NON-NLS-1$ //$NON-NLS-2$ help = true; } else { if (ARG_PROFILE.equals(args[i])) { // take next arg - there is path to the profile i++; MindRaider.profilesDirectory = args[i]; } else { if (ARG_TWIKI_IMPORT.equals(args[i])) { // take next arg - there is path to the twiki file // to be imported i++; String command = args[i]; if (StringUtils.isNotEmpty(command)) { new Commander(COMMAND_TWIKI_IMPORT + command); } else { System.err.println(MindRaiderApplication.getString("MindRaiderApplication.0") //$NON-NLS-1$ + command + MindRaiderApplication.getString("MindRaiderApplication.1")); //$NON-NLS-1$ } System.exit(0); } else { if (ARG_DEBUG.equals(args[i])) { debugMode = true; } else { System.out.println( MindRaiderApplication.getString("MindRaiderApplication.11") + args[i]); //$NON-NLS-1$ help = true; } } } } i++; } // process arguments if (help) { help(); return; } } // reset log4j configuration try { BasicConfigurator.resetConfiguration(); if (debugMode) { PropertyConfigurator.configure(System.getProperty("log4j.configuration.debug")); //$NON-NLS-1$ } else { String log4jconfig = System.getProperty("log4j.configuration"); PropertyConfigurator.configure(log4jconfig); //$NON-NLS-1$ } } catch (Throwable e) { logger.debug(getString(MindRaiderApplication.getString("MindRaiderApplication.2"))); //$NON-NLS-1$ BasicConfigurator.resetConfiguration(); } logger.debug(MindRaider.getTitle()); String javaVersion; try { javaVersion = System.getProperty("java.version"); //$NON-NLS-1$ } catch (NullPointerException e) { javaVersion = ""; //$NON-NLS-1$ } logger.debug(getString("MindRaiderApplication.javaVersion", new Object[] { javaVersion, System.getProperty("java.vendor"), System.getProperty("java.home") })); if (javaVersion.compareTo("1.1.2") < 0) { logger.debug(getString("MindRaiderApplication.swing112version")); return; } // initialization if (MindRaiderConstants.EARLY_ACCESS) { MindRaider.setUser(System.getProperty("user.name"), System.getProperty("user.home") + File.separator + MindRaiderConstants.MR + "-eap"); //$NON-NLS-1$ } else { MindRaider.setUser(System.getProperty("user.name"), System //$NON-NLS-1$ .getProperty("user.home")); //$NON-NLS-1$ } MindRaider.setInstallationDirectory(System.getProperty("user.dir")); //$NON-NLS-1$ logger.debug(getString("MindRaiderApplication.installationDirectory", MindRaider.installationDirectory)); logger.debug(getString("MindRaiderApplication.profileName", MindRaider.user.getName())); logger.debug(getString("MindRaiderApplication.userHome", MindRaider.user.getHome())); MindRaider.eapProfilesDirectory = System.getProperty("user.home") + File.separator + MindRaiderConstants.MR + "-eap" + File.separator + ".mindraider.profile.eap"; // set profile if (MindRaider.profilesDirectory == null) { if (MindRaiderConstants.EARLY_ACCESS) { MindRaider.profilesDirectory = MindRaider.eapProfilesDirectory; } else { MindRaider.profilesDirectory = MindRaider.user.getHome() + File.separator + ".mindraider.profile"; //$NON-NLS-1$ } } MindRaider.setMainJFrame(MindRaiderMainWindow.getInstance()); }
From source file:edu.ehu.galan.lite.Lite.java
/** * Main entry point for LiTe from the command Line use -h option for help * * @param args/*w w w . j a v a 2 s . co m*/ */ public static void main(String[] args) { // create Options object Options options = new Options(); Option corpus = new Option("c", true, "the location (directory) of the corpus to process, containing only one document at the moment"); Option language = new Option("l", true, "the language of the corpus (lowercase ISO format, for example 'en'"); Option algorithms = new Option("a", true, "the algorithms you want to process separated by commas: \n" + "see the documentation for see the available algorithms for each language"); Option help = new Option("h", false, "print this message"); Option resources = new Option("r", true, "the location of the lite resources folder"); Option output = new Option("o", true, "The directory where the results will be stored, by default the one where the vm has been launched"); Option listAlgs = new Option("listAlgs", false, " Algorithm list names with the supported languages (remember that the cvalue will be processed chosen or not):\n" + "===================================================\n" + "tfidf => processes the TFIDF algorithm, process terms of the input document using the Wikipedia corpus as IDF (en,es)\n" + "cvalue => processes the CValue altorithm for the inputdocument, CValue is processed whether is chosed or not! (en, es)\n" + "shallow => processes the shallow parsing grammar algorithm (en)\n" + "rake => processes the rake algorithm (language agnostig)\n" + "kpminer => processes the KPMiner algorithm (en)\n" + "chisquare => processes the ChiSquare using the NLTK toolkit (language agnostic)\n" + "pmi=> processes the Point Mutual Information using the NLTK toolkit (language agnostic)\n" + "likehood=> processes the Likehood Ratio using the NLTK toolkit (language agnostic)\n" + "tstudent=> processes the T-Student using the NLTK toolkit (language agnostic)\n" + "rawfreq=> processes the raw frequency algorithm using the NLTK toolkit (language agnostic)\n" + "freelingner=> processes the FreeLing ner algorithm via external call(es, en)\n"); options.addOption(resources); options.addOption(corpus); options.addOption(language); options.addOption(algorithms); options.addOption(listAlgs); options.addOption(output); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); String[] s = new String[] {}; // create the parser CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption('c') && line.hasOption('l') && line.hasOption('a') && line.hasOption('r')) { if (!line.getOptionValue('l').equals("en") && !line.getOptionValue("l").equals("es")) { System.out.println( "Supported languages \"en\" or \"es\", however you may use the statistical algorithms via the API"); } else { String outputDir = ""; if (line.hasOption('o')) { outputDir = line.getOptionValue('o'); } String lang = line.getOptionValue('l'); Corpus cor = new Corpus(line.getOptionValue('l')); cor.loadCorpus(line.getOptionValue('c'), Document.SourceType.wikipedia); String res = line.getOptionValue('r'); List<String> algs = Arrays.asList(line.getOptionValue('a').split(",")); System.out.println("Processing.... (it may take a while...)"); runner(lang, res + File.separator, algs, cor, outputDir); } } if (line.hasOption('c') && line.hasOption('l') && line.hasOption('r')) { if (!line.getOptionValue('l').equals("en") && !line.getOptionValue("l").equals("es")) { System.out.println( "Supported languages \"en\" or \"es\", however you may use the statistical algorithms via the API"); } else { String outputDir = ""; if (line.hasOption('o')) { outputDir = line.getOptionValue('o'); } System.out.println( "Processing with default algorithms (TFIDF/CValue).... (it may take a while...)"); Corpus cor = new Corpus(line.getOptionValue('l')); String res = line.getOptionValue('r'); cor.loadCorpus(line.getOptionValue('c'), Document.SourceType.wikipedia); String lang = line.getOptionValue('l'); List<String> algos = null; switch (lang) { case "es": { String[] algs = { "cvalue", "tfidf", "rake" }; algos = Arrays.asList(algs); break; } case "en": { String[] algs = { "cvalue", "tfidf", "rake" }; algos = Arrays.asList(algs); break; } } runner(lang, res + File.separator, algos, cor, outputDir); } } else if (line.hasOption("h")) { formatter.printHelp("LiTe: a language indepent term extractor", options); } else if (line.getOptions().length == 0) { formatter.printHelp("LiTe: a language indepent term extractor", options); } else { System.err.println("The 'c', 'l' and 'r' arguments are required \n"); formatter.printHelp("LiTe: a language indepent term extractor", options); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage() + "\n"); formatter.printHelp("LiTe: a language indepent term extractor", options); } }
From source file:evaluation.evaluation1VMPolicyGeneration.java
public static void main(String[] args) { int VMNumber = 5; int attributeNumber = 20; 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", "1_GB"); serviceDescription.put("VM1_purpose", "dev"); serviceDescription.put("VM1_data", "private"); serviceDescription.put("VM1_application", "internal"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM1_other" + j, "other"); }//from w ww. j av a2 s .c o m serviceRequirement.put("VM2_volume", "2_GB"); serviceDescription.put("VM2_purpose", "prod"); serviceDescription.put("VM2_data", "public"); serviceDescription.put("VM2_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM2_other" + j, "other"); } serviceRequirement.put("VM3_volume", "1_GB"); serviceDescription.put("VM3_purpose", "test"); serviceDescription.put("VM3_data", "public"); serviceDescription.put("VM3_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM3_other" + j, "other"); } serviceRequirement.put("VM4_volume", "12_GB"); serviceDescription.put("VM4_purpose", "prod"); serviceDescription.put("VM4_data", "public"); serviceDescription.put("VM4_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM4_other" + j, "other"); } for (int i = 5; i < VMNumber; i++) { serviceRequirement.put("VM" + i + "_volume", "20_GB"); serviceDescription.put("VM" + i + "_purpose", "prod"); serviceDescription.put("VM" + i + "_data", "public"); serviceDescription.put("VM" + i + "_application", "business"); for (int j = 5; j < attributeNumber; j++) { serviceDescription.put("VM" + i + "_other" + j, "other"); } } 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); 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:ch.kostceco.tools.kostval.KOSTVal.java
/** Die Eingabe besteht aus 2 oder 3 Parameter: [0] Validierungstyp [1] Pfad zur Val-File [2] * option: Verbose/*from w w w. j a v a2 s . co m*/ * * @param args * @throws IOException */ @SuppressWarnings("unused") public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml"); // Zeitstempel Start 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); /* TODO: siehe Bemerkung im applicationContext-services.xml bezglich Injection in der * Superklasse aller Impl-Klassen ValidationModuleImpl validationModuleImpl = * (ValidationModuleImpl) context.getBean("validationmoduleimpl"); */ KOSTVal kostval = (KOSTVal) context.getBean("kostval"); File configFile = new File("configuration" + File.separator + "kostval.conf.xml"); // Ueberprfung des Parameters (Log-Verzeichnis) String pathToLogfile = kostval.getConfigurationService().getPathToLogfile(); File directoryOfLogfile = new File(pathToLogfile); if (!directoryOfLogfile.exists()) { directoryOfLogfile.mkdir(); } // Im Logverzeichnis besteht kein Schreibrecht if (!directoryOfLogfile.canWrite()) { System.out.println( kostval.getTextResourceService().getText(ERROR_LOGDIRECTORY_NOTWRITABLE, directoryOfLogfile)); System.exit(1); } if (!directoryOfLogfile.isDirectory()) { System.out.println(kostval.getTextResourceService().getText(ERROR_LOGDIRECTORY_NODIRECTORY)); System.exit(1); } // Ist die Anzahl Parameter (mind. 2) korrekt? if (args.length < 2) { System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE)); System.exit(1); } File valDatei = new File(args[1]); File logDatei = null; logDatei = valDatei; // Informationen zum Arbeitsverzeichnis holen String pathToWorkDir = kostval.getConfigurationService().getPathToWorkDir(); /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ // Informationen holen, welche Formate validiert werden sollen String pdfaValidation = kostval.getConfigurationService().pdfaValidation(); String siardValidation = kostval.getConfigurationService().siardValidation(); String tiffValidation = kostval.getConfigurationService().tiffValidation(); String jp2Validation = kostval.getConfigurationService().jp2Validation(); // Konfiguration des Loggings, ein File Logger wird zustzlich erstellt LogConfigurator logConfigurator = (LogConfigurator) context.getBean("logconfigurator"); String logFileName = logConfigurator.configure(directoryOfLogfile.getAbsolutePath(), logDatei.getName()); File logFile = new File(logFileName); // Ab hier kann ins log geschrieben werden... String formatValOn = ""; // ermitteln welche Formate validiert werden knnen respektive eingeschaltet sind if (pdfaValidation.equals("yes")) { formatValOn = "PDF/A"; if (tiffValidation.equals("yes")) { formatValOn = formatValOn + ", TIFF"; } if (jp2Validation.equals("yes")) { formatValOn = formatValOn + ", JP2"; } if (siardValidation.equals("yes")) { formatValOn = formatValOn + ", SIARD"; } } else if (tiffValidation.equals("yes")) { formatValOn = "TIFF"; if (jp2Validation.equals("yes")) { formatValOn = formatValOn + ", JP2"; } if (siardValidation.equals("yes")) { formatValOn = formatValOn + ", SIARD"; } } else if (jp2Validation.equals("yes")) { formatValOn = "JP2"; if (siardValidation.equals("yes")) { formatValOn = formatValOn + ", SIARD"; } } else if (siardValidation.equals("yes")) { formatValOn = "SIARD"; } LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_HEADER)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_START, ausgabeStart)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_END)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMATON, formatValOn)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_INFO)); System.out.println("KOST-Val"); System.out.println(""); if (args[0].equals("--format") && formatValOn.equals("")) { // Formatvalidierung aber alle Formate ausgeschlossen LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_NOFILEENDINGS))); System.out.println(kostval.getTextResourceService().getText(ERROR_NOFILEENDINGS)); System.exit(1); } File xslOrig = new File("resources" + File.separator + "kost-val.xsl"); File xslCopy = new File(directoryOfLogfile.getAbsolutePath() + File.separator + "kost-val.xsl"); if (!xslCopy.exists()) { Util.copyFile(xslOrig, xslCopy); } File 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) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir))); System.out.println( kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_EXISTS, pathToWorkDir)); System.exit(1); } } } // Im Pfad keine Sonderzeichen xml-Validierung SIP 1d und SIARD C strzen ab String patternStr = "[^!#\\$%\\(\\)\\+,\\-_\\.=@\\[\\]\\{\\}\\~:\\\\a-zA-Z0-9 ]"; Pattern pattern = Pattern.compile(patternStr); String name = tmpDir.getAbsolutePath(); String[] pathElements = name.split("/"); for (int i = 0; i < pathElements.length; i++) { String element = pathElements[i]; Matcher matcher = pattern.matcher(element); boolean matchFound = matcher.find(); if (matchFound) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name))); System.out.println(kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)); System.exit(1); } } // die Anwendung muss mindestens unter Java 6 laufen String javaRuntimeVersion = System.getProperty("java.vm.version"); if (javaRuntimeVersion.compareTo("1.6.0") < 0) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_WRONG_JRE))); System.out.println(kostval.getTextResourceService().getText(ERROR_WRONG_JRE)); System.exit(1); } // bestehendes Workverzeichnis wieder anlegen if (!tmpDir.exists()) { tmpDir.mkdir(); } // Im workverzeichnis besteht kein Schreibrecht if (!tmpDir.canWrite()) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir))); System.out.println(kostval.getTextResourceService().getText(ERROR_WORKDIRECTORY_NOTWRITABLE, tmpDir)); System.exit(1); } /* Vorberitung fr eine allfllige Festhaltung bei unterschiedlichen PDFA-Validierungsresultaten * in einer PDF_Diagnosedatei sowie Zhler der SIP-Dateiformate */ String diaPath = kostval.getConfigurationService().getPathToDiagnose(); // Im diaverzeichnis besteht kein Schreibrecht File diaDir = new File(diaPath); if (!diaDir.exists()) { diaDir.mkdir(); } if (!diaDir.canWrite()) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_DIADIRECTORY_NOTWRITABLE, diaDir))); System.out.println(kostval.getTextResourceService().getText(ERROR_DIADIRECTORY_NOTWRITABLE, diaDir)); System.exit(1); } File xmlDiaOrig = new File("resources" + File.separator + "KaD-Diagnosedaten.kost-val.xml"); File xmlDiaCopy = new File(diaPath + File.separator + "KaD-Diagnosedaten.kost-val.xml"); if (!xmlDiaCopy.exists()) { Util.copyFile(xmlDiaOrig, xmlDiaCopy); } File xslDiaOrig = new File("resources" + File.separator + "kost-val_KaDdia.xsl"); File xslDiaCopy = new File(diaPath + File.separator + "kost-val_KaDdia.xsl"); if (!xslDiaCopy.exists()) { Util.copyFile(xslDiaOrig, xslDiaCopy); } /* Ueberprfung des optionalen Parameters (2 -v --> im Verbose-mode werden die originalen Logs * nicht gelscht (PDFTron, Jhove & Co.) */ boolean verbose = false; if (args.length > 2) { if (!(args[2].equals("-v"))) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_PARAMETER_OPTIONAL_1))); System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_OPTIONAL_1)); System.exit(1); } else { verbose = true; } } /* Initialisierung TIFF-Modul B (JHove-Validierung) berprfen der Konfiguration: existiert die * jhove.conf am angebenen Ort? */ String jhoveConf = kostval.getConfigurationService().getPathToJhoveConfiguration(); File fJhoveConf = new File(jhoveConf); if (!fJhoveConf.exists() || !fJhoveConf.getName().equals("jhove.conf")) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_JHOVECONF_MISSING))); System.out.println(kostval.getTextResourceService().getText(ERROR_JHOVECONF_MISSING)); System.exit(1); } // Im Pfad keine Sonderzeichen xml-Validierung SIP 1d und SIARD C strzen ab name = valDatei.getAbsolutePath(); pathElements = name.split("/"); for (int i = 0; i < pathElements.length; i++) { String element = pathElements[i]; Matcher matcher = pattern.matcher(element); boolean matchFound = matcher.find(); if (matchFound) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name))); System.out.println(kostval.getTextResourceService().getText(ERROR_SPECIAL_CHARACTER, name)); System.exit(1); } } // Ueberprfung des Parameters (Val-Datei): existiert die Datei? if (!valDatei.exists()) { LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_VALFILE_FILENOTEXISTING))); System.out.println(kostval.getTextResourceService().getText(ERROR_VALFILE_FILENOTEXISTING)); System.exit(1); } if (args[0].equals("--format")) { LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT1)); Integer countNio = 0; Integer countSummaryNio = 0; Integer count = 0; Integer pdfaCountIo = 0; Integer pdfaCountNio = 0; Integer siardCountIo = 0; Integer siardCountNio = 0; Integer tiffCountIo = 0; Integer tiffCountNio = 0; Integer jp2CountIo = 0; Integer jp2CountNio = 0; // TODO: Formatvalidierung an einer Datei --> erledigt --> nur Marker if (!valDatei.isDirectory()) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2)); // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e) { LOGGER.logError("<Error>" + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } if (valFile) { // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // Validierte Datei valide System.exit(0); } else { // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // Fehler in Validierte Datei --> invalide System.exit(2); } } else { // TODO: Formatvalidierung ber ein Ordner --> erledigt --> nur Marker Map<String, File> fileMap = Util.getFileMap(valDatei, false); Set<String> fileMapKeys = fileMap.keySet(); for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) { String entryName = iterator.next(); File newFile = fileMap.get(entryName); if (!newFile.isDirectory()) { valDatei = newFile; count = count + 1; // Ausgabe Dateizhler Ersichtlich das KOST-Val Dateien durchsucht System.out.print(count + " "); System.out.print("\r"); if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2"))) && jp2Validation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (valFile) { jp2CountIo = jp2CountIo + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } else { jp2CountNio = jp2CountNio + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".tiff") || valDatei.getAbsolutePath().toLowerCase().endsWith(".tif"))) && tiffValidation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (valFile) { tiffCountIo = tiffCountIo + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } else { tiffCountNio = tiffCountNio + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".siard")) && siardValidation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (valFile) { siardCountIo = siardCountIo + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } else { siardCountNio = siardCountNio + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf") || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa"))) && pdfaValidation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (valFile) { pdfaCountIo = pdfaCountIo + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } else { pdfaCountNio = pdfaCountNio + 1; // Lschen des Arbeitsverzeichnisses, falls eines angelegt wurde if (tmpDir.exists()) { Util.deleteDir(tmpDir); } } } else { countNio = countNio + 1; } } } System.out.print(" "); System.out.print("\r"); if (countNio.equals(count)) { // keine Dateien Validiert LOGGER.logError( kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn)); System.out.println( kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn)); } LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e) { LOGGER.logError("<Error>" + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio; if (countNio.equals(count)) { // keine Dateien Validiert bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } System.exit(1); } else if (countSummaryNio == 0) { // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // alle Validierten Dateien valide System.exit(0); } else { // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } // Fehler in Validierten Dateien --> invalide System.exit(2); } if (tmpDir.exists()) { Util.deleteDir(tmpDir); tmpDir.deleteOnExit(); } } LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2)); } else if (args[0].equals("--sip")) { LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT1)); // TODO: Sipvalidierung --> erledigt --> nur Marker boolean validFormat = false; File originalSipFile = valDatei; File unSipFile = valDatei; File outputFile3c = null; String fileName3c = null; File tmpDirZip = null; // zuerst eine Formatvalidierung ber den Content dies ist analog aufgebaut wie --format Integer countNio = 0; Integer countSummaryNio = 0; Integer countSummaryIo = 0; Integer count = 0; Integer pdfaCountIo = 0; Integer pdfaCountNio = 0; Integer siardCountIo = 0; Integer siardCountNio = 0; Integer tiffCountIo = 0; Integer tiffCountNio = 0; Integer jp2CountIo = 0; Integer jp2CountNio = 0; if (!valDatei.isDirectory()) { Boolean zip = false; // Eine ZIP Datei muss mit PK.. beginnen if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".zip") || valDatei.getAbsolutePath().toLowerCase().endsWith(".zip64"))) { FileReader fr = null; try { fr = new FileReader(valDatei); BufferedReader read = new BufferedReader(fr); // Hex 03 in Char umwandeln String str3 = "03"; int i3 = Integer.parseInt(str3, 16); char c3 = (char) i3; // Hex 04 in Char umwandeln String str4 = "04"; int i4 = Integer.parseInt(str4, 16); char c4 = (char) i4; // auslesen der ersten 4 Zeichen der Datei int length; int i; char[] buffer = new char[4]; length = read.read(buffer); for (i = 0; i != length; i++) ; // die beiden charArrays (soll und ist) mit einander vergleichen char[] charArray1 = buffer; char[] charArray2 = new char[] { 'P', 'K', c3, c4 }; if (Arrays.equals(charArray1, charArray2)) { // hchstwahrscheinlich ein ZIP da es mit 504B0304 respektive PK.. beginnt zip = true; } } catch (Exception e) { LOGGER.logError("<Error>" + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } } // wenn die Datei kein Directory ist, muss sie mit zip oder zip64 enden if ((!(valDatei.getAbsolutePath().toLowerCase().endsWith(".zip") || valDatei.getAbsolutePath().toLowerCase().endsWith(".zip64"))) || zip == false) { // Abbruch! D.h. Sip message beginnen, Meldung und Beenden ab hier bis System.exit( 1 ); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1)); valDatei = originalSipFile; LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE, kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION))); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE, valDatei.getAbsolutePath())); System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)); System.out.println(valDatei.getAbsolutePath()); // die eigentliche Fehlermeldung LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_MODUL_Aa_SIP) + kostval.getTextResourceService().getText(ERROR_XML_AA_INCORRECTFILEENDING)); System.out.println(kostval.getTextResourceService().getText(ERROR_XML_AA_INCORRECTFILEENDING)); // Fehler im Validierten SIP --> invalide & Abbruch LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE)); System.out.println("Invalid"); System.out.println(""); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e) { LOGGER.logError("<Error>" + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } System.exit(1); } else { // geziptes SIP --> in temp dir entzipen String toplevelDir = valDatei.getName(); int lastDotIdx = toplevelDir.lastIndexOf("."); toplevelDir = toplevelDir.substring(0, lastDotIdx); tmpDirZip = new File( tmpDir.getAbsolutePath() + File.separator + "ZIP" + File.separator + toplevelDir); try { Zip64Archiver.unzip(valDatei.getAbsolutePath(), tmpDirZip.getAbsolutePath()); } catch (Exception e) { try { Zip64Archiver.unzip64(valDatei, tmpDirZip); } catch (Exception e1) { // Abbruch! D.h. Sip message beginnen, Meldung und Beenden ab hier bis System.exit LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1)); valDatei = originalSipFile; LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE, kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION))); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE, valDatei.getAbsolutePath())); System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)); System.out.println(valDatei.getAbsolutePath()); // die eigentliche Fehlermeldung LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_MODUL_Aa_SIP) + kostval.getTextResourceService().getText(ERROR_XML_AA_CANNOTEXTRACTZIP)); System.out.println( kostval.getTextResourceService().getText(ERROR_XML_AA_CANNOTEXTRACTZIP)); // Fehler im Validierten SIP --> invalide & Abbruch LOGGER.logError( kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID)); LOGGER.logError( kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE)); System.out.println("Invalid"); System.out.println(""); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat( "dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e2) { LOGGER.logError("<Error>" + kostval.getTextResourceService() .getText(ERROR_XML_UNKNOWN, e2.getMessage())); System.out.println("Exception: " + e2.getMessage()); } // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } System.exit(1); } } valDatei = tmpDirZip; File toplevelfolder = new File( valDatei.getAbsolutePath() + File.separator + valDatei.getName()); if (toplevelfolder.exists()) { valDatei = toplevelfolder; } unSipFile = valDatei; } } else { // SIP ist ein Ordner valDatei bleibt unverndert } // Vorgngige Formatvalidierung (Schritt 3c) Map<String, File> fileMap = Util.getFileMap(valDatei, false); Set<String> fileMapKeys = fileMap.keySet(); int pdf = 0; int tiff = 0; int siard = 0; int txt = 0; int csv = 0; int xml = 0; int xsd = 0; int wave = 0; int mp3 = 0; int jp2 = 0; int jpx = 0; int jpeg = 0; int png = 0; int dng = 0; int svg = 0; int mpeg2 = 0; int mp4 = 0; int xls = 0; int odt = 0; int ods = 0; int odp = 0; int other = 0; for (Iterator<String> iterator = fileMapKeys.iterator(); iterator.hasNext();) { String entryName = iterator.next(); File newFile = fileMap.get(entryName); if (!newFile.isDirectory() && newFile.getAbsolutePath().contains(File.separator + "content" + File.separator)) { valDatei = newFile; count = count + 1; // Ausgabe Dateizhler Ersichtlich das KOST-Val Dateien durchsucht System.out.print(count + " "); System.out.print("\r"); String extension = valDatei.getName(); int lastIndexOf = extension.lastIndexOf("."); if (lastIndexOf == -1) { // empty extension extension = "other"; } else { extension = extension.substring(lastIndexOf); } if (extension.equalsIgnoreCase(".pdf") || extension.equalsIgnoreCase(".pdfa")) { pdf = pdf + 1; } else if (extension.equalsIgnoreCase(".tiff") || extension.equalsIgnoreCase(".tif")) { tiff = tiff + 1; } else if (extension.equalsIgnoreCase(".siard")) { siard = siard + 1; } else if (extension.equalsIgnoreCase(".txt")) { txt = txt + 1; } else if (extension.equalsIgnoreCase(".csv")) { csv = csv + 1; } else if (extension.equalsIgnoreCase(".xml")) { xml = xml + 1; } else if (extension.equalsIgnoreCase(".xsd")) { xsd = xsd + 1; } else if (extension.equalsIgnoreCase(".wav")) { wave = wave + 1; } else if (extension.equalsIgnoreCase(".mp3")) { mp3 = mp3 + 1; } else if (extension.equalsIgnoreCase(".jp2")) { jp2 = jp2 + 1; } else if (extension.equalsIgnoreCase(".jpx") || extension.equalsIgnoreCase(".jpf")) { jpx = jpx + 1; } else if (extension.equalsIgnoreCase(".jpe") || extension.equalsIgnoreCase(".jpeg") || extension.equalsIgnoreCase(".jpg")) { jpeg = jpeg + 1; } else if (extension.equalsIgnoreCase(".png")) { png = png + 1; } else if (extension.equalsIgnoreCase(".dng")) { dng = dng + 1; } else if (extension.equalsIgnoreCase(".svg")) { svg = svg + 1; } else if (extension.equalsIgnoreCase(".mpeg") || extension.equalsIgnoreCase(".mpg")) { mpeg2 = mpeg2 + 1; } else if (extension.equalsIgnoreCase(".f4a") || extension.equalsIgnoreCase(".f4v") || extension.equalsIgnoreCase(".m4a") || extension.equalsIgnoreCase(".m4v") || extension.equalsIgnoreCase(".mp4")) { mp4 = mp4 + 1; } else if (extension.equalsIgnoreCase(".xls") || extension.equalsIgnoreCase(".xlw") || extension.equalsIgnoreCase(".xlsx")) { xls = xls + 1; } else if (extension.equalsIgnoreCase(".odt") || extension.equalsIgnoreCase(".ott")) { odt = odt + 1; } else if (extension.equalsIgnoreCase(".ods") || extension.equalsIgnoreCase(".ots")) { ods = ods + 1; } else if (extension.equalsIgnoreCase(".odp") || extension.equalsIgnoreCase(".otp")) { odp = odp + 1; } else { other = other + 1; } if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2"))) && jp2Validation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); if (valFile) { jp2CountIo = jp2CountIo + 1; } else { jp2CountNio = jp2CountNio + 1; } } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".tiff") || valDatei.getAbsolutePath().toLowerCase().endsWith(".tif"))) && tiffValidation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); if (valFile) { tiffCountIo = tiffCountIo + 1; } else { tiffCountNio = tiffCountNio + 1; } } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".siard")) && siardValidation.equals("yes")) { // Arbeitsverzeichnis zum Entpacken des Archivs erstellen String pathToWorkDirSiard = kostval.getConfigurationService().getPathToWorkDir(); File tmpDirSiard = new File(pathToWorkDirSiard + File.separator + "SIARD"); if (tmpDirSiard.exists()) { Util.deleteDir(tmpDirSiard); } if (!tmpDirSiard.exists()) { tmpDirSiard.mkdir(); } boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); if (valFile) { siardCountIo = siardCountIo + 1; } else { siardCountNio = siardCountNio + 1; } } else if (((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf") || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa"))) && pdfaValidation.equals("yes")) { boolean valFile = valFile(valDatei, logFileName, directoryOfLogfile, verbose); if (valFile) { pdfaCountIo = pdfaCountIo + 1; } else { pdfaCountNio = pdfaCountNio + 1; } } else { countNio = countNio + 1; } } } countSummaryNio = pdfaCountNio + siardCountNio + tiffCountNio + jp2CountNio; countSummaryIo = pdfaCountIo + siardCountIo + tiffCountIo + jp2CountIo; int countSummaryIoP = 100 / count * countSummaryIo; int countSummaryNioP = 100 / count * countSummaryNio; int countNioP = 100 / count * countNio; String summary3c = kostval.getTextResourceService().getText(MESSAGE_XML_SUMMARY_3C, count, countSummaryIo, countSummaryNio, countNio, countSummaryIoP, countSummaryNioP, countNioP); if (countSummaryNio == 0) { // alle Validierten Dateien valide validFormat = true; fileName3c = "3c_Valide.txt"; } else { // Fehler in Validierten Dateien --> invalide validFormat = false; fileName3c = "3c_Invalide.txt"; } // outputFile3c = new File( directoryOfLogfile + fileName3c ); outputFile3c = new File(pathToWorkDir + File.separator + fileName3c); try { outputFile3c.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (countNio == count) { // keine Dateien Validiert LOGGER.logError(kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn)); System.out .println(kostval.getTextResourceService().getText(ERROR_INCORRECTFILEENDINGS, formatValOn)); } LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_FORMAT2)); // Start Normale SIP-Validierung mit auswertung Format-Val. im 3c LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP1)); valDatei = unSipFile; LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALTYPE, kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION))); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALFILE, originalSipFile.getAbsolutePath())); System.out.println(kostval.getTextResourceService().getText(MESSAGE_SIPVALIDATION)); System.out.println(originalSipFile.getAbsolutePath()); Controllersip controller = (Controllersip) context.getBean("controllersip"); boolean okMandatory = false; okMandatory = controller.executeMandatory(valDatei, directoryOfLogfile); boolean ok = false; /* die Validierungen 1a - 1d sind obligatorisch, wenn sie bestanden wurden, knnen die * restlichen Validierungen, welche nicht zum Abbruch der Applikation fhren, ausgefhrt * werden. * * 1a wurde bereits getestet (vor der Formatvalidierung entsprechend fngt der Controller mit * 1b an */ if (okMandatory) { ok = controller.executeOptional(valDatei, directoryOfLogfile); } // Formatvalidierung validFormat ok = (ok && okMandatory && validFormat); if (ok) { // Validiertes SIP valide LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_VALID)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE)); System.out.println("Valid"); System.out.println(""); } else { // Fehler im Validierten SIP --> invalide LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_INVALID)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_VALERGEBNIS_CLOSE)); System.out.println("Invalid"); System.out.println(""); } // ggf. Fehlermeldung 3c ergnzen Util.val3c(summary3c, logFile ); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2)); LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_LOGEND)); // Zeitstempel End java.util.Date nowEnd = new java.util.Date(); java.text.SimpleDateFormat sdfEnd = new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); String ausgabeEnd = sdfEnd.format(nowEnd); ausgabeEnd = "<End>" + ausgabeEnd + "</End>"; Util.valEnd(ausgabeEnd, logFile); Util.val3c(summary3c, logFile); Util.amp(logFile); // Die Konfiguration hereinkopieren try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setExpandEntityReferences(false); Document docConfig = factory.newDocumentBuilder().parse(configFile); NodeList list = docConfig.getElementsByTagName("configuration"); Element element = (Element) list.item(0); Document docLog = factory.newDocumentBuilder().parse(logFile); Node dup = docLog.importNode(element, true); docLog.getDocumentElement().appendChild(dup); FileWriter writer = new FileWriter(logFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ElementToStream(docLog.getDocumentElement(), baos); String stringDoc2 = new String(baos.toByteArray()); writer.write(stringDoc2); writer.close(); // Der Header wird dabei leider verschossen, wieder zurck ndern String newstring = kostval.getTextResourceService().getText(MESSAGE_XML_HEADER); String oldstring = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><KOSTValLog>"; Util.oldnewstring(oldstring, newstring, logFile); } catch (Exception e) { LOGGER.logError( "<Error>" + kostval.getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); System.out.println("Exception: " + e.getMessage()); } // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } StringBuffer command = new StringBuffer("rd " + tmpDir.getAbsolutePath() + " /s /q"); try { // KaD-Diagnose-Datei mit den neusten Anzahl Dateien pro KaD-Format Updaten DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlDiaCopy); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("KOSTVal_FFCounter"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; if (pdf > 0) { String pdfNodeString = eElement.getElementsByTagName("pdf").item(0).getTextContent(); int pdfNodeValue = Integer.parseInt(pdfNodeString); pdf = pdf + pdfNodeValue; Util.kadDia("<pdf>" + pdfNodeValue + "</pdf>", "<pdf>" + pdf + "</pdf>", xmlDiaCopy); } if (tiff > 0) { String tiffNodeString = eElement.getElementsByTagName("tiff").item(0).getTextContent(); int tiffNodeValue = Integer.parseInt(tiffNodeString); tiff = tiff + tiffNodeValue; Util.kadDia("<tiff>" + tiffNodeValue + "</tiff>", "<tiff>" + tiff + "</tiff>", xmlDiaCopy); } if (siard > 0) { String siardNodeString = eElement.getElementsByTagName("siard").item(0) .getTextContent(); int siardNodeValue = Integer.parseInt(siardNodeString); siard = siard + siardNodeValue; Util.kadDia("<siard>" + siardNodeValue + "</siard>", "<siard>" + siard + "</siard>", xmlDiaCopy); } if (txt > 0) { String txtNodeString = eElement.getElementsByTagName("txt").item(0).getTextContent(); int txtNodeValue = Integer.parseInt(txtNodeString); txt = txt + txtNodeValue; Util.kadDia("<txt>" + txtNodeValue + "</txt>", "<txt>" + txt + "</txt>", xmlDiaCopy); } if (csv > 0) { String csvNodeString = eElement.getElementsByTagName("csv").item(0).getTextContent(); int csvNodeValue = Integer.parseInt(csvNodeString); csv = csv + csvNodeValue; Util.kadDia("<csv>" + csvNodeValue + "</csv>", "<csv>" + csv + "</csv>", xmlDiaCopy); } if (xml > 0) { String xmlNodeString = eElement.getElementsByTagName("xml").item(0).getTextContent(); int xmlNodeValue = Integer.parseInt(xmlNodeString); xml = xml + xmlNodeValue; Util.kadDia("<xml>" + xmlNodeValue + "</xml>", "<xml>" + xml + "</xml>", xmlDiaCopy); } if (xsd > 0) { String xsdNodeString = eElement.getElementsByTagName("xsd").item(0).getTextContent(); int xsdNodeValue = Integer.parseInt(xsdNodeString); xsd = xsd + xsdNodeValue; Util.kadDia("<xsd>" + xsdNodeValue + "</xsd>", "<xsd>" + xsd + "</xsd>", xmlDiaCopy); } if (wave > 0) { String waveNodeString = eElement.getElementsByTagName("wave").item(0).getTextContent(); int waveNodeValue = Integer.parseInt(waveNodeString); wave = wave + waveNodeValue; Util.kadDia("<wave>" + waveNodeValue + "</wave>", "<wave>" + wave + "</wave>", xmlDiaCopy); } if (mp3 > 0) { String mp3NodeString = eElement.getElementsByTagName("mp3").item(0).getTextContent(); int mp3NodeValue = Integer.parseInt(mp3NodeString); mp3 = mp3 + mp3NodeValue; Util.kadDia("<mp3>" + mp3NodeValue + "</mp3>", "<mp3>" + mp3 + "</mp3>", xmlDiaCopy); } if (jp2 > 0) { String jp2NodeString = eElement.getElementsByTagName("jp2").item(0).getTextContent(); int jp2NodeValue = Integer.parseInt(jp2NodeString); jp2 = jp2 + jp2NodeValue; Util.kadDia("<jp2>" + jp2NodeValue + "</jp2>", "<jp2>" + jp2 + "</jp2>", xmlDiaCopy); } if (jpx > 0) { String jpxNodeString = eElement.getElementsByTagName("jpx").item(0).getTextContent(); int jpxNodeValue = Integer.parseInt(jpxNodeString); jpx = jpx + jpxNodeValue; Util.kadDia("<jpx>" + jpxNodeValue + "</jpx>", "<jpx>" + jpx + "</jpx>", xmlDiaCopy); } if (jpeg > 0) { String jpegNodeString = eElement.getElementsByTagName("jpeg").item(0).getTextContent(); int jpegNodeValue = Integer.parseInt(jpegNodeString); jpeg = jpeg + jpegNodeValue; Util.kadDia("<jpeg>" + jpegNodeValue + "</jpeg>", "<jpeg>" + jpeg + "</jpeg>", xmlDiaCopy); } if (png > 0) { String pngNodeString = eElement.getElementsByTagName("png").item(0).getTextContent(); int pngNodeValue = Integer.parseInt(pngNodeString); png = png + pngNodeValue; Util.kadDia("<png>" + pngNodeValue + "</png>", "<png>" + png + "</png>", xmlDiaCopy); } if (dng > 0) { String dngNodeString = eElement.getElementsByTagName("dng").item(0).getTextContent(); int dngNodeValue = Integer.parseInt(dngNodeString); dng = dng + dngNodeValue; Util.kadDia("<dng>" + dngNodeValue + "</dng>", "<dng>" + dng + "</dng>", xmlDiaCopy); } if (svg > 0) { String svgNodeString = eElement.getElementsByTagName("svg").item(0).getTextContent(); int svgNodeValue = Integer.parseInt(svgNodeString); svg = svg + svgNodeValue; Util.kadDia("<svg>" + svgNodeValue + "</svg>", "<svg>" + svg + "</svg>", xmlDiaCopy); } if (mpeg2 > 0) { String mpeg2NodeString = eElement.getElementsByTagName("mpeg2").item(0) .getTextContent(); int mpeg2NodeValue = Integer.parseInt(mpeg2NodeString); mpeg2 = mpeg2 + mpeg2NodeValue; Util.kadDia("<mpeg2>" + mpeg2NodeValue + "</mpeg2>", "<mpeg2>" + mpeg2 + "</mpeg2>", xmlDiaCopy); } if (mp4 > 0) { String mp4NodeString = eElement.getElementsByTagName("mp4").item(0).getTextContent(); int mp4NodeValue = Integer.parseInt(mp4NodeString); mp4 = mp4 + mp4NodeValue; Util.kadDia("<mp4>" + mp4NodeValue + "</mp4>", "<mp4>" + mp4 + "</mp4>", xmlDiaCopy); } if (xls > 0) { String xlsNodeString = eElement.getElementsByTagName("xls").item(0).getTextContent(); int xlsNodeValue = Integer.parseInt(xlsNodeString); xls = xls + xlsNodeValue; Util.kadDia("<xls>" + xlsNodeValue + "</xls>", "<xls>" + xls + "</xls>", xmlDiaCopy); } if (odt > 0) { String odtNodeString = eElement.getElementsByTagName("odt").item(0).getTextContent(); int odtNodeValue = Integer.parseInt(odtNodeString); odt = odt + odtNodeValue; Util.kadDia("<odt>" + odtNodeValue + "</odt>", "<odt>" + odt + "</odt>", xmlDiaCopy); } if (ods > 0) { String odsNodeString = eElement.getElementsByTagName("ods").item(0).getTextContent(); int odsNodeValue = Integer.parseInt(odsNodeString); ods = ods + odsNodeValue; Util.kadDia("<ods>" + odsNodeValue + "</ods>", "<ods>" + ods + "</ods>", xmlDiaCopy); } if (odp > 0) { String odpNodeString = eElement.getElementsByTagName("odp").item(0).getTextContent(); int odpNodeValue = Integer.parseInt(odpNodeString); odp = odp + odpNodeValue; Util.kadDia("<odp>" + odpNodeValue + "</odp>", "<odp>" + odp + "</odp>", xmlDiaCopy); } if (other > 0) { String otherNodeString = eElement.getElementsByTagName("other").item(0) .getTextContent(); int otherNodeValue = Integer.parseInt(otherNodeString); other = other + otherNodeValue; Util.kadDia("<other>" + otherNodeValue + "</other>", "<other>" + other + "</other>", xmlDiaCopy); } } } } catch (Exception e) { e.printStackTrace(); } if (ok) { // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (tmpDir.exists()) { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(command.toString()); } System.exit(0); } else { // bestehendes Workverzeichnis ggf. lschen if (tmpDir.exists()) { Util.deleteDir(tmpDir); } if (tmpDir.exists()) { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(command.toString()); } System.exit(2); } LOGGER.logError(kostval.getTextResourceService().getText(MESSAGE_XML_SIP2)); } else { /* Ueberprfung des Parameters (Val-Typ): format / sip args[0] ist nicht "--format" oder * "--sip" --> INVALIDE */ LOGGER.logError(kostval.getTextResourceService().getText(ERROR_IOE, kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE))); System.out.println(kostval.getTextResourceService().getText(ERROR_PARAMETER_USAGE)); if (tmpDir.exists()) { Util.deleteDir(tmpDir); tmpDir.deleteOnExit(); } System.exit(1); } }
From source file:de.uni_koblenz.jgralab.utilities.tgraphbrowser.TGraphBrowserServer.java
/** * Runs the server. Needed args: -w --workspace the workspace * //from w w w . j av a 2 s . c o m * @param args */ public static void main(String[] args) { CommandLine comLine = processCommandLineOptions(args); assert comLine != null; try { starttime = System.currentTimeMillis(); String portnumber = comLine.getOptionValue("p"); String workspacePath; if (comLine.hasOption("r")) { TwoDVisualizer.PRINT_ROLE_NAMES = true; } if (comLine.hasOption("w")) { workspacePath = comLine.getOptionValue("w"); } else { File workspace = new File(System.getProperty("java.io.tmpdir") + File.separator + "tgraphbrowser"); if (!workspace.exists()) { if (!workspace.mkdir()) { logger.info("The temp folder " + workspace.getAbsolutePath() + " could not be created."); } } workspace = new File(workspace.getAbsoluteFile() + File.separator + "workspace"); if (!workspace.exists()) { if (!workspace.mkdir()) { logger.info( "The default workspace " + workspace.getAbsolutePath() + " could not be created."); } } workspacePath = workspace.getAbsolutePath(); } new TGraphBrowserServer(portnumber == null ? DEFAULT_PORT : Integer.parseInt(portnumber), workspacePath, comLine.getOptionValue("m"), comLine.getOptionValue("s")).start(); if (comLine.getOptionValue("ic") != null) { TabularVisualizer.NUMBER_OF_INCIDENCES_PER_PAGE = Math .max(Integer.parseInt(comLine.getOptionValue("ic")), 1); } if (comLine.hasOption("d")) { StateRepository.dot = comLine.getOptionValue("d"); } else { System.out.println("The 2D-Visualization is disabled because parameter -d is not set."); } String timeout = comLine.getOptionValue("t"); String checkIntervall = comLine.getOptionValue("i"); new DeleteUnusedStates(timeout == null ? 600 : Integer.parseInt(timeout), checkIntervall == null ? 60 : Integer.parseInt(checkIntervall)).start(); if (comLine.hasOption("td")) { TwoDVisualizer.SECONDS_TO_WAIT_FOR_DOT = Integer.parseInt(comLine.getOptionValue("td")); } } catch (IOException e) { System.out.println(e); } }
From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java
public static void main(String[] args) throws IOException { final PrepareLocalEiffelSchemas prepareLocalSchema = new PrepareLocalEiffelSchemas(); final Proxy proxy = prepareLocalSchema.getProxy(httpProxyUrl, httpProxyPort, httpProxyUsername, httpProxyPassword);/* ww w . j a v a2s . c o m*/ if (proxy != null) { prepareLocalSchema.setProxy(proxy); } final String eiffelRepoUrl = args[0]; final String eiffelRepoBranch = args[1]; final String operationRepoUrl = args[2]; final String operationRepoBranch = args[3]; final File localEiffelRepoPath = new File( System.getProperty(EiffelConstants.USER_HOME) + File.separator + EiffelConstants.EIFFEL); final File localOperationsRepoPath = new File(System.getProperty(EiffelConstants.USER_HOME) + File.separator + EiffelConstants.OPERATIONS_REPO_NAME); // Clone Eiffel Repo from GitHub prepareLocalSchema.cloneEiffelRepo(eiffelRepoUrl, eiffelRepoBranch, localEiffelRepoPath); //Clone Eiffel operations Repo from GitHub prepareLocalSchema.cloneEiffelRepo(operationRepoUrl, operationRepoBranch, localOperationsRepoPath); //Copy operations repo Schemas to location where Eiffel repo schemas available prepareLocalSchema.copyOperationSchemas(localOperationsRepoPath.getAbsolutePath(), localEiffelRepoPath.getAbsolutePath()); // Read and Load JsonSchemas from Cloned Directory final LocalRepo localRepo = new LocalRepo(localEiffelRepoPath); localRepo.readSchemas(); final ArrayList<String> jsonEventNames = localRepo.getJsonEventNames(); final ArrayList<File> jsonEventSchemas = localRepo.getJsonEventSchemas(); // Schema changes final SchemaFile schemaFile = new SchemaFile(); // Iterate the Each jsonSchema file to Add and Modify the necessary properties if (jsonEventNames != null && jsonEventSchemas != null) { for (int i = 0; i < jsonEventNames.size(); i++) { schemaFile.modify(jsonEventSchemas.get(i), jsonEventNames.get(i)); } } }
From source file:imp.lstm.main.Driver.java
public static void main(String[] args) throws FileNotFoundException, IOException, ConfigurationException, InvalidParametersException { FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>( PropertiesConfiguration.class).configure( new Parameters().properties().setFileName(args[0]).setThrowExceptionOnMissing(true) .setListDelimiterHandler(new DefaultListDelimiterHandler(';')) .setIncludesAllowed(false)); Configuration config = builder.getConfiguration(); String inputSongPath = config.getString("input_song"); String outputFolderPath = config.getString("output_folder"); String autoEncoderParamsPath = config.getString("auto_encoder_params"); String nameGeneratorParamsPath = config.getString("name_generator_params"); String queueFolderPath = config.getString("queue_folder"); String referenceQueuePath = config.getString("reference_queue", "nil"); String inputCorpusFolder = config.getString("input_corpus_folder"); boolean shouldWriteQueue = config.getBoolean("should_write_generated_queue"); boolean frankensteinTest = config.getBoolean("queue_tests_frankenstein"); boolean interpolateTest = config.getBoolean("queue_tests_interpolation"); boolean iterateOverCorpus = config.getBoolean("iterate_over_corpus", false); boolean shouldGenerateSongTitle = config.getBoolean("generate_song_title"); boolean shouldGenerateSong = config.getBoolean("generate_leadsheet"); LogTimer.initStartTime(); //start our logging timer to keep track of our execution time LogTimer.log("Creating name generator..."); //here is just silly code for generating name based on an LSTM lol $wag LSTM lstm = new LSTM(); FullyConnectedLayer fullLayer = new FullyConnectedLayer(Operations.None); Loadable titleNetLoader = new Loadable() { @Override/*from www. j ava2s . c o m*/ public boolean load(INDArray array, String path) { String car = pathCar(path); String cdr = pathCdr(path); switch (car) { case "full": return fullLayer.load(array, cdr); case "lstm": return lstm.load(array, cdr); default: return false; } } }; LogTimer.log("Packing name generator from files..."); (new NetworkConnectomeLoader()).load(nameGeneratorParamsPath, titleNetLoader); String characterString = " !\"'[],-.01245679:?ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz"; //Initialization LogTimer.log("Creating autoencoder..."); int inputSize = 34; int outputSize = EncodingParameters.noteEncoder.getNoteLength(); int featureVectorSize = 100; ProductCompressingAutoencoder autoencoder = new ProductCompressingAutoencoder(24, 48, 84 + 1, false); //create our network int numInterpolationDivisions = 5; //"pack" the network from weights and biases file directory LogTimer.log("Packing autoencoder from files"); (new NetworkConnectomeLoader()).load(autoEncoderParamsPath, autoencoder); File[] songFiles; if (iterateOverCorpus) { songFiles = new File(inputCorpusFolder).listFiles(); } else { songFiles = new File[] { new File(inputSongPath) }; } for (File inputFile : songFiles) { (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate"); String songTitle; if (shouldGenerateSong) { Random rand = new Random(); AVector charOut = Vector.createLength(characterString.length()); GroupedSoftMaxSampler sampler = new GroupedSoftMaxSampler( new Group[] { new Group(0, characterString.length(), true) }); songTitle = ""; for (int i = 0; i < 50; i++) { charOut = fullLayer.forward(lstm.step(charOut)); charOut = sampler.filter(charOut); int charIndex = 0; for (; charIndex < charOut.length(); charIndex++) { if (charOut.get(charIndex) == 1.0) { break; } } songTitle += characterString.substring(charIndex, charIndex + 1); } songTitle = songTitle.trim(); LogTimer.log("Generated song name: " + songTitle); } else { songTitle = "The Song We Never Name"; } LogTimer.log("Reading file..."); LeadSheetDataSequence inputSequence = LeadSheetIO.readLeadSheet(inputFile); //read our leadsheet to get a data vessel as retrieved in rbm-provisor LeadSheetDataSequence outputSequence = inputSequence.copy(); outputSequence.clearMelody(); if (interpolateTest) { LeadSheetDataSequence additionalOutput = outputSequence.copy(); for (int i = 0; i < numInterpolationDivisions; i++) { outputSequence.concat(additionalOutput.copy()); } } LeadSheetDataSequence decoderInputSequence = outputSequence.copy(); LogTimer.startLog("Encoding data..."); //TradingTimer.initStart(); //start our trading timer to keep track our our generation versus realtime play while (inputSequence.hasNext()) { //iterate through time steps in input data //TradingTimer.waitForNextTimedInput(); autoencoder.encodeStep(inputSequence.retrieve()); //feed the resultant input vector into the network if (advanceDecoding) { //if we are using advance decoding (we start decoding as soon as we can) if (autoencoder.canDecode()) { //if queue has enough data to decode from outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are } } } LogTimer.endLog(); if (shouldWriteQueue) { String queueFilePath = queueFolderPath + java.io.File.separator + inputFile.getName().replace(".ls", ".q"); FragmentedNeuralQueue currQueue = autoencoder.getQueue(); currQueue.writeToFile(queueFilePath); LogTimer.log("Wrote queue " + inputFile.getName().replace(".ls", ".q") + " to file..."); } if (shouldGenerateSong) { if (interpolateTest) { FragmentedNeuralQueue refQueue = new FragmentedNeuralQueue(); refQueue.initFromFile(referenceQueuePath); FragmentedNeuralQueue currQueue = autoencoder.getQueue(); //currQueue.writeToFile(queueFilePath); autoencoder.setQueue(currQueue.copy()); while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{ outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are } for (int i = 1; i <= numInterpolationDivisions; i++) { System.out.println("Starting interpolation " + ((1.0 / numInterpolationDivisions) * (i))); (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate"); FragmentedNeuralQueue currCopy = currQueue.copy(); currCopy.basicInterpolate(refQueue, (1.0 / numInterpolationDivisions) * (i)); autoencoder.setQueue(currCopy); int timeStep = 0; while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{ System.out.println("interpolation " + i + " step " + ++timeStep); outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are } } } if (frankensteinTest) { LogTimer.startLog("Loading queues"); File queueFolder = new File(queueFolderPath); int numComponents = config.getInt("frankenstein_num_components", 5); int numCombinations = config.getInt("frankenstein_num_combinations", 6); double interpolationMagnitude = config.getDouble("frankenstein_magnitude", 2.0); if (queueFolder.isDirectory()) { File[] queueFiles = queueFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(".q"); } }); List<File> fileList = new ArrayList<>(); for (File file : queueFiles) { fileList.add(file); } Collections.shuffle(fileList); int numSelectedFiles = (numComponents > queueFiles.length) ? queueFiles.length : numComponents; for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) { fileList.remove(fileList.size() - 1); } List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size()); songTitle += " - a mix of "; for (File file : fileList) { FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue(); newQueue.initFromFile(file.getPath()); queuePopulation.add(newQueue); songTitle += file.getName().replaceAll(".ls", "") + ", "; } LogTimer.endLog(); LeadSheetDataSequence additionalOutput = outputSequence.copy(); for (int i = 1; i < numCombinations; i++) { outputSequence.concat(additionalOutput.copy()); } decoderInputSequence = outputSequence.copy(); FragmentedNeuralQueue origQueue = autoencoder.getQueue(); for (int i = 0; i < numCombinations; i++) { LogTimer.startLog("Performing queue interpolation..."); AVector combinationStrengths = Vector.createLength(queuePopulation.size()); Random vectorRand = new Random(i); for (int j = 0; j < combinationStrengths.length(); j++) { combinationStrengths.set(j, vectorRand.nextDouble()); } combinationStrengths.divide(combinationStrengths.elementSum()); FragmentedNeuralQueue currQueue = origQueue.copy(); for (int k = 0; k < combinationStrengths.length(); k++) { currQueue.basicInterpolate(queuePopulation.get(k), combinationStrengths.get(k) * interpolationMagnitude); } LogTimer.endLog(); autoencoder.setQueue(currQueue); LogTimer.startLog("Refreshing autoencoder state..."); (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate"); LogTimer.endLog(); LogTimer.startLog("Decoding segment..."); while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{ outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are } LogTimer.endLog(); } } } while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{ outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are } LogTimer.log("Writing file..."); String outputFilename = outputFolderPath + java.io.File.separator + inputFile.getName().replace(".ls", "_Output"); //we'll write our generated file with the same name plus "_Output" LeadSheetIO.writeLeadSheet(outputSequence, outputFilename, songTitle); System.out.println(outputFilename); } else { autoencoder.setQueue(new FragmentedNeuralQueue()); } } LogTimer.log("Process finished"); //Done! }
From source file:io.sightly.tck.TCK.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OptionBuilder.withLongOpt(CLI_EXTRACT).withDescription(CLI_EXTRACT_DESCRIPTION) .hasOptionalArg().withArgName("DIR").create()); options.addOption(OptionBuilder.withLongOpt(CLI_URL).withDescription(CLI_URL_DESCRIPTION).hasOptionalArg() .withArgName("URL").create()); options.addOption(OptionBuilder.withLongOpt(CLI_AUTH_USER).withDescription(CLI_AUTH_USER_DESCRIPTION) .hasOptionalArg().withArgName("USER").create()); options.addOption(OptionBuilder.withLongOpt(CLI_AUTH_PASS).withDescription(CLI_AUTH_PASS_DESCRIPTION) .hasOptionalArg().withArgName("PASS").create()); try {//from w w w . ja va2s. c o m CommandLine line = parser.parse(options, args); if (!line.iterator().hasNext()) { printUsage(options); die(); } else if (line.hasOption(CLI_EXTRACT)) { String extractDir = line.getOptionValue(CLI_EXTRACT); if (StringUtils.isEmpty(extractDir)) { // assume user wants to extract stuff in current directory extractDir = System.getProperty("user.dir"); } INSTANCE.extract(extractDir); LOG.info("Extracted testing resources in folder {}.", extractDir + File.separator + TESTFILES); } else { if (line.hasOption(CLI_URL)) { String url = line.getOptionValue(CLI_URL); if (StringUtils.isEmpty(url)) { LOG.error("Missing value for --" + CLI_URL + " command line option."); printUsage(options); die(); } System.setProperty(Constants.SYS_PROP_SERVER_URL, url); } if (line.hasOption(CLI_AUTH_USER) || line.hasOption(CLI_AUTH_PASS)) { String user = line.getOptionValue(CLI_AUTH_USER); if (StringUtils.isEmpty(user)) { LOG.error("Missing value for --" + CLI_AUTH_USER + " command line option"); printUsage(options); die(); } String pass = line.getOptionValue(CLI_AUTH_PASS); if (StringUtils.isEmpty(pass)) { LOG.error("Missing value for --" + CLI_AUTH_PASS + " command line option"); printUsage(options); die(); } System.setProperty(Constants.SYS_PROP_USER, user); System.setProperty(Constants.SYS_PROP_PASS, pass); } INSTANCE.run(); } } catch (ParseException e) { printUsage(options); die(); } catch (IOException e) { LOG.error("IO Error.", e); die(); } }