List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java
/** * Get PDF information with pdfinfo://w w w . ja v a2 s . co m * - "Pages: X": number of pages; * - "Page X size: www.ww hhh.hh": size of each page, in pts. * @returns a map: * - [Pages][n] * - [Page 1][111.11 222.22] * - [Page i][www.ww hhh.hh] * - [Page n][999.99 1000.00] */ private static Map<String, String> getPDFProperties(ImageRecord input) throws DjatokaException { logger.debug("Getting PDF info"); try { setPDFCommandsPath(); } catch (IllegalStateException e) { logger.error("Failed to set PDF commands path: ", e); throw e; } HashMap<String, String> pdfProperties = new HashMap<String, String>(); String sourcePath = null; if (input.getImageFile() != null) { logger.debug("PDFInfo image file: " + input.getImageFile()); sourcePath = input.getImageFile(); } else if (input.getObject() != null && (input.getObject() instanceof InputStream)) { FileInputStream fis = null; fis = (FileInputStream) input.getObject(); File in; // Copy to tmp file try { String cacheDir = OpenURLJP2KService.getCacheDir(); if (cacheDir != null) { in = File.createTempFile("tmp", ".pdf", new File(cacheDir)); } else { in = File.createTempFile("tmp", ".pdf"); } in.deleteOnExit(); FileOutputStream fos = new FileOutputStream(in); IOUtils.copyStream(fis, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } sourcePath = in.getAbsolutePath(); } else { throw new DjatokaException("File not defined and Input Object Type " + input //.getObject().getClass().getName() + " is not supported"); } String pdfinfoCmd[] = PDFINFO_COMMAND.clone(); pdfinfoCmd[PDFINFO_COMMAND_POSITION_BIN] = pdfinfoPath; pdfinfoCmd[PDFINFO_COMMAND_POSITION_FIRSTPAGE] = "1"; pdfinfoCmd[PDFINFO_COMMAND_POSITION_LASTPAGE] = "-1"; // Last page even we not knowing its number. pdfinfoCmd[PDFINFO_COMMAND_POSITION_FILE] = sourcePath; Process pdfProc = null; try { ArrayList<MatchResult> pageSizes = new ArrayList<MatchResult>(); MatchResult pages = null; pdfProc = Runtime.getRuntime().exec(pdfinfoCmd); BufferedReader lr = new BufferedReader(new InputStreamReader(pdfProc.getInputStream())); String line; for (line = lr.readLine(); line != null; line = lr.readLine()) { Matcher mm1 = PAGES_PATT.matcher(line); if (mm1.matches()) pages = mm1.toMatchResult(); Matcher mm2 = MEDIABOX_PATT.matcher(line); if (mm2.matches()) pageSizes.add(mm2.toMatchResult()); } int istatus = pdfProc.waitFor(); if (istatus != 0) logger.error("pdfinfo proc failed, exit status=" + istatus + ", file=" + sourcePath); if (pages == null) { logger.error("Did not find 'Pages' line in output of pdfinfo command: " + Arrays.deepToString(pdfinfoCmd)); pdfProperties.put("Pages", "0"); } else { //int n = Integer.parseInteger(pages.group(1)); pdfProperties.put("Pages", pages.group(1)); } if (pageSizes.isEmpty()) { logger.error("Did not find \"Page X size\" lines in output of pdfinfo command: " + Arrays.deepToString(pdfinfoCmd)); throw new IllegalArgumentException("Failed to get pages size of PDF with pdfinfo."); } else { for (MatchResult mr : pageSizes) { String page = mr.group(1); float x0 = Float.parseFloat(mr.group(2)); float y0 = Float.parseFloat(mr.group(3)); float x1 = Float.parseFloat(mr.group(4)); float y1 = Float.parseFloat(mr.group(5)); float w = Math.abs(x1 - x0); float h = Math.abs(y1 - y0); // Have to scale page sizes by max dpi (MAX_DPI / DEFAULT_DENSITY). Otherwise, BookReader.js will request the wrong zoom level (svc.level). float ws = w * MAX_DPI / DEFAULT_DENSITY; float hs = h * MAX_DPI / DEFAULT_DENSITY; String width = "" + ws; //mr.group(2); String height = "" + hs; //mr.group(3); pdfProperties.put("Page " + page, width + " " + height); } } } catch (Exception e) { logger.error("Failed getting PDF information: ", e); throw new DjatokaException("Failed getting PDF information: ", e); } finally { // Our exec() should just consume one of the streams, but we want to stay safe. // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream()); } return pdfProperties; }
From source file:marytts.tools.voiceimport.HTKLabeler.java
/** * Flat-start initialization for automatic labeling * @throws Exception/*from w w w .jav a 2 s. com*/ */ private void herestTraining() throws Exception { String herest = getProp(HTKDIR) + File.separator + "HERest"; String hhed = getProp(HTKDIR) + File.separator + "HHEd"; File htkFile = new File(herest); if (!htkFile.exists()) { throw new RuntimeException("File " + htkFile.getAbsolutePath() + " does not exist"); } String configFile = getProp(HTDIR) + File.separator + "config" + File.separator + "htkTrain.conf"; String hhedconf = getProp(HTDIR) + File.separator + "config" + File.separator + "sil.hed"; String hhedconf_vp = getProp(HTDIR) + File.separator + "config" + File.separator + "sil_vp.hed"; String trainList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htkTrain.list"; String phoneList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phone.list"; String hmmDir = getProp(HTDIR) + File.separator + "hmm" + File.separator; String phoneMlf = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones.mlf"; int BEST_ITERATION = MAX_ITERATIONS; int SP_ITERATION = -1; int VP_ITERATION = -1; int FA_ITERATION = -1; int change_mix_iteration = -1; for (int iteration = 1; iteration <= MAX_ITERATIONS; iteration++) { System.out.println("Iteration number: " + iteration); File hmmItDir = new File(hmmDir + "hmm" + iteration); if (!hmmItDir.exists()) hmmItDir.mkdir(); Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); if (PHASE_NUMBER == 0) { if (iteration == (SP_ITERATION + 1)) { phoneMlf = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones2.mlf"; phoneList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phone2.list"; System.out.println("( cd " + getProp(HTDIR) + "; " + hhed + " " + HTK_SO + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + hhedconf + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.println("( cd " + getProp(HTDIR) + "; " + hhed + " " + HTK_SO + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + hhedconf + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); //now we enter in PHASE 1 PHASE_NUMBER = 1; System.out.println("Now we enter in PHASE:" + PHASE_NUMBER); continue; } // check epsilon_array if (iteration > 2) { if (epsilon_array.get(iteration - 2) < epsilon_PHASE[PHASE_NUMBER] || iteration == MAX_SP_ITERATION) { SP_ITERATION = iteration; insertShortPause(iteration); String oldMacro = hmmDir + "hmm" + (iteration - 1) + File.separator + "macros"; String newMacro = hmmDir + "hmm" + iteration + File.separator + "macros"; FileUtils.copy(oldMacro, newMacro); // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); continue; } } } ///----------------- if (PHASE_NUMBER == 1) { if (iteration == (VP_ITERATION + 1)) { phoneMlf = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones3.mlf"; phoneList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phone3.list"; System.out.println("( cd " + getProp(HTDIR) + "; " + hhed + " " + HTK_SO + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + hhedconf_vp + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.println("( cd " + getProp(HTDIR) + "; " + hhed + " " + HTK_SO + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + hhedconf_vp + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); //now we enter in PHASE 2 PHASE_NUMBER = 2; System.out.println("Now we enter in PHASE:" + PHASE_NUMBER); continue; } // check epsilon_array if (epsilon_array.get(iteration - 2) < epsilon_PHASE[PHASE_NUMBER] || iteration == MAX_VP_ITERATION) { VP_ITERATION = iteration; insertVirtualPauseThreeStates(iteration); String oldMacro = hmmDir + "hmm" + (iteration - 1) + File.separator + "macros"; String newMacro = hmmDir + "hmm" + iteration + File.separator + "macros"; FileUtils.copy(oldMacro, newMacro); // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); continue; } } ///----------------- if (PHASE_NUMBER == 2) { if (iteration == (FA_ITERATION + 1)) { String logfile = "log_hviteMultiplePronunciationAligning_" + iteration + ".txt"; String labDir = "'*'";//getProp(HTDIR)+File.separator+"lab"; String alignedMlf = getProp(HTDIR) + File.separator + "aligned_words.mlf"; hviteMultiplePronunciationAligning("hmm" + (iteration - 1), alignedMlf, false, labDir, true, logfile, false); phoneMlf = getProp(HTDIR) + File.separator + "aligned_words.mlf"; System.out.println("Copy hmm" + (iteration - 1) + " in " + "hmm" + iteration); String oldMacro = hmmDir + "hmm" + (iteration - 1) + File.separator + "macros"; String newMacro = hmmDir + "hmm" + iteration + File.separator + "macros"; FileUtils.copy(oldMacro, newMacro); String oldHmmdefs = hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs"; String newHmmdefs = hmmDir + "hmm" + iteration + File.separator + "hmmdefs"; FileUtils.copy(oldHmmdefs, newHmmdefs); // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); //now we enter in PHASE 3 PHASE_NUMBER = 3; System.out.println("Now we enter in PHASE:" + PHASE_NUMBER); continue; } // check epsilon_array if (epsilon_array.get(iteration - 2) < epsilon_PHASE[PHASE_NUMBER] || iteration == MAX_FA_ITERATION) { FA_ITERATION = iteration; System.out.println("Copy hmm" + (iteration - 1) + " in " + "hmm" + iteration); String oldMacro = hmmDir + "hmm" + (iteration - 1) + File.separator + "macros"; String newMacro = hmmDir + "hmm" + iteration + File.separator + "macros"; FileUtils.copy(oldMacro, newMacro); String oldHmmdefs = hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs"; String newHmmdefs = hmmDir + "hmm" + iteration + File.separator + "hmmdefs"; FileUtils.copy(oldHmmdefs, newHmmdefs); // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); continue; } } ///----------------- if (PHASE_NUMBER == 3) { // check epsilon_array // the following change_mix_iteration + 2 is used to allow more than one re-estimation after insertion of new mixture // Because just after the insertion the delta can be negative if (((iteration != change_mix_iteration + 2) && (epsilon_array.get(iteration - 2) < epsilon_PHASE[PHASE_NUMBER])) || iteration == MAX_MIX_ITERATION) { System.out.println("Condition = true: " + "iteration=" + iteration + " change_mix_iteration=" + change_mix_iteration + " epsilon_array.get(iteration-2)=" + epsilon_array.get(iteration - 2) + " epsilon_PHASE[PHASE_NUMBER]=" + epsilon_PHASE[PHASE_NUMBER] + " MAX_MIX_ITERATION" + MAX_MIX_ITERATION); change_mix_iteration = iteration; MAX_MIX_ITERATION = -1; // Creating Increasing mixture config file dynamic iteration String hhedconf_mix = getProp(HTDIR) + File.separator + "config" + File.separator + "sil_mix_" + iteration + ".hed"; File file = new File(hhedconf_mix); PrintWriter hhed_conf_pw = new PrintWriter(new FileWriter(file)); //MU 3 {*.state[2].mix} Boolean need_other_updates = false; for (int state = 0; state < num_mixtures_for_state.length; state++) { if (current_number_of_mixtures[state] < num_mixtures_for_state[state]) { int wanted_mix = current_number_of_mixtures[state] + 1; int state_to_print = state + 2; hhed_conf_pw.println("MU " + wanted_mix + "{*.state[" + state_to_print + "].mix}"); current_number_of_mixtures[state] = wanted_mix; if (current_number_of_mixtures[state] < num_mixtures_for_state[state]) { need_other_updates = true; } } } if (!need_other_updates) { // copy of logProbFrame_array in current iteration //logProbFrame_array.add(logProbFrame_array.get(iteration-2)); //epsilon_array.add(100000000.0); //now we enter in PHASE 3 PHASE_NUMBER = PHASE_NUMBER + 1; System.out.println("Now we enter in PHASE:" + PHASE_NUMBER); String logfile = "log_hviteMultiplePronunciationAligning_" + iteration + ".txt"; String labDir = "'*'";//getProp(HTDIR)+File.separator+"lab"; String alignedMlf = getProp(HTDIR) + File.separator + "aligned_words.mlf"; hviteMultiplePronunciationAligning("hmm" + (iteration - 1), alignedMlf, false, labDir, true, logfile, false); phoneMlf = getProp(HTDIR) + File.separator + "aligned_words.mlf"; //continue; } hhed_conf_pw.flush(); hhed_conf_pw.close(); System.out.println("( cd " + getProp(HTDIR) + "; " + hhed + " " + HTK_SO + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + hhedconf_mix + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.println("( cd " + getProp(HTDIR) + "; " + hhed + " " + HTK_SO + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + hhedconf_mix + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } // copy of logProbFrame_array in current iteration logProbFrame_array.add(logProbFrame_array.get(iteration - 2)); epsilon_array.add(100000000.0); continue; } } ///----------------- if (PHASE_NUMBER == 4) { // check epsilon_array if (((iteration != change_mix_iteration + 2) && (epsilon_array.get(iteration - 2) < epsilon_PHASE[PHASE_NUMBER])) || iteration == MAX_ITERATIONS) { int last = iteration - 1; int previus_last = iteration - 2; System.out.println( "Average log prob per frame has not beeen increased too much respect the previus iteration:"); System.out.println("Average log prob per frame at last HREST iteration (" + last + ")-> " + logProbFrame_array.get(iteration - 2)); System.out.println("Average log prob per frame at previus HREST iteration (" + previus_last + ")-> " + logProbFrame_array.get(iteration - 3)); System.out.println("Delta -> " + epsilon_array.get(iteration - 2)); System.out.println("Suggested Action -> stop the iterations."); if (logProbFrame_array.get(iteration - 3) > logProbFrame_array.get(iteration - 2)) { BEST_ITERATION = iteration - 2; } else { BEST_ITERATION = iteration - 1; } break; } } //Normal HEREST: System.out.println("( cd " + getProp(HTDIR) + "; " + herest + " " + HTK_SO + " -C " + configFile + " -I " + phoneMlf + " -t 250.0 150.0 1000.0" + " -S " + trainList + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.println("( cd " + getProp(HTDIR) + "; " + herest + " " + HTK_SO + " -C " + configFile + " -I " + phoneMlf + " -t 250.0 150.0 1000.0" + " -S " + trainList + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "macros" + " -H " + hmmDir + "hmm" + (iteration - 1) + File.separator + "hmmdefs" + " -M " + hmmDir + "hmm" + iteration + " " + phoneList + " >> log_herestTraining_" + iteration + ".txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } // update average_log_prob_per_frame and deltas check_average_log_prob_per_frame(iteration); System.out.println("Delta average log prob per frame to respect previus iteration-> " + epsilon_array.get(iteration - 1)); System.out.println("Current PHASE: " + PHASE_NUMBER); System.out.println("Current state and number of mixtures (for each phoneme): " + Arrays.toString(current_number_of_mixtures)); System.out.println("---------------------------------------"); } System.out.println("***********\n"); System.out.println("BEST ITERATION: " + BEST_ITERATION); System.out.println("COPYNING BEST ITERATION FILES IN hmm-final directory"); System.out.println("logProbFrame_array:" + logProbFrame_array.toString()); System.out.println("epsilon_array:" + epsilon_array.toString()); System.out.println("***********\n"); String oldMacro = hmmDir + "hmm" + BEST_ITERATION + File.separator + "macros"; String newMacro = hmmDir + "hmm-final" + File.separator + "macros"; FileUtils.copy(oldMacro, newMacro); String oldHmmdefs = hmmDir + "hmm" + BEST_ITERATION + File.separator + "hmmdefs"; String newHmmdefs = hmmDir + "hmm-final" + File.separator + "hmmdefs"; FileUtils.copy(oldHmmdefs, newHmmdefs); }
From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java
/** * Extracts region defined in DjatokaDecodeParam as BufferedImage * @param input absolute file path of PDF file. * @param params DjatokaDecodeParam instance containing region and transform settings. * @return extracted region as a BufferedImage * @throws DjatokaException/*from w ww . ja v a 2s . c o m*/ */ @Override public BufferedImage process(String input, DjatokaDecodeParam params) throws DjatokaException { logger.debug("ExtractPDF.process:\n\tinput: " + input + "\n\tparams: " + params); if (input == null) throw new DjatokaException("Unknown failure while converting file: no image produced."); try { setPDFCommandsPath(); } catch (IllegalStateException e) { logger.error("Failed to set PDF commands path: ", e); throw e; } int page_number = 1 + params.getCompositingLayer(); // From 0-based to 1-based. int status = 0; BufferedImage processedImage = null; try { /* // First get max physical dim of bounding box of the page // to compute the DPI to ask for.. otherwise some AutoCAD // drawings can produce enormous files even at 75dpi, for // 48" drawings.. int dpi = 0; Dimension pageSize = getPDFPageSize(input, page_number); if (pageSize == null) { logger.error("Sanity check: Did not find \"Page " + page_number + " size\" line in output of pdfinfo, file="+input); throw new IllegalArgumentException("Failed to get \"Page " + page_number + " size\" of PDF with pdfinfo."); } else { double w = pageSize.getWidth(); double h = pageSize.getHeight(); int maxdim = (int)Math.max(Math.abs(w), Math.abs(h)); dpi = Math.min(MAX_DPI, (MAX_PX * 72 / maxdim)); logger.debug("DPI: pdfinfo method got dpi="+dpi+" for max dim="+maxdim+" (points, 1/72\")"); } */ // Scale int dpi = getScaledDPI(params); // Requires Sun JAI imageio additions to read ppm directly. // this will get "-[0]+1.ppm" appended to it by pdftoppm File outPrefixF = File.createTempFile("pdftopng", "out"); String outPrefix = outPrefixF.toString(); outPrefixF.delete(); //String pdfCmd[] = PDFTOPPM_COMMAND.clone(); ArrayList<String> pdfCmd = new ArrayList<String>(Arrays.asList(PDFTOPPM_COMMAND)); pdfCmd.set(PDFTOPPM_COMMAND_POSITION_BIN, pdftoppmPath); pdfCmd.set(PDFTOPPM_COMMAND_POSITION_FIRSTPAGE, "" + page_number); pdfCmd.set(PDFTOPPM_COMMAND_POSITION_LASTPAGE, "" + page_number); pdfCmd.set(PDFTOPPM_COMMAND_POSITION_DPI, String.valueOf(dpi)); pdfCmd.set(PDFTOPPM_COMMAND_POSITION_FILE, input.toString()); pdfCmd.set(PDFTOPPM_COMMAND_POSITION_OUTPUTFILE, outPrefix); // Crop Rectangle crop = getCropParam(params); if (crop != null) { String[] cropParams = { "-x", "" + (int) crop.getX(), "-y", "" + (int) crop.getY(), "-W", "" + (int) crop.getWidth(), "-H", "" + (int) crop.getHeight() }; pdfCmd.addAll(PDFTOPPM_COMMAND_POSITION_OPTIONAL_EXTRAS, Arrays.asList(cropParams)); } String[] pdfCmdA = pdfCmd.toArray(new String[pdfCmd.size()]); logger.debug("Running pdftoppm command: " + Arrays.deepToString(pdfCmdA)); //logger.debug("Running pdftoppm command: " + pdfCmd.toString()); File outf = null; Process pdfProc = null; try { pdfProc = Runtime.getRuntime().exec(pdfCmdA); status = pdfProc.waitFor(); logger.debug("status: " + status); // pdftoppm uses variable numbers of padding 0s to the output prefix. // E.g., may be prefix-000001.png, prefix-001.png or even prefix-01.png. // Version 0.12.3 (Poppler, not XPDF) seems to consider the total number of pages. // So, for example, in a PDF with 90 pages, the output will be "prefix-02.png"; // for a PDF with 350 pages, the output will be "prefix-002.png". // FIXME: try some approach where the PDF number of pages is considered without // running pdfinfo command again, thus making it simpler to determine the number // of padding zeros. Right now we going "brute force" because we do not know if // it is feasable to once again run the pdfinfo command. String tests[] = { outPrefix + "-" + page_number + ".png", outPrefix + "-0" + page_number + ".png", outPrefix + "-00" + page_number + ".png", outPrefix + "-000" + page_number + ".png", outPrefix + "-0000" + page_number + ".png", outPrefix + "-00000" + page_number + ".png" }; for (String outname : tests) { if ((new File(outname)).exists()) { outf = new File(outname); break; } } logger.debug("PDFTOPPM output is: " + outf + ", exists=" + outf != null ? outf.exists() : "!"); processedImage = ImageIO.read(outf); // Rotate if (params.getRotationDegree() > 0) { processedImage = ImageProcessingUtils.rotate(processedImage, params.getRotationDegree()); } } catch (InterruptedException e) { logger.error("Failed converting PDF file to image: ", e); throw new IllegalArgumentException("Failed converting PDF file to image: ", e); } finally { if (outf != null) outf.delete(); // Our exec() should not produce any output, but we want to stay safe. // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream()); } } catch (Exception e) { logger.error("Failed converting PDF file to image: ", e); throw new IllegalArgumentException("Failed converting PDF file to image: ", e); } finally { if (status != 0) logger.error("PDF conversion proc failed, exit status=" + status + ", file=" + input); } return processedImage; }
From source file:ch.kostceco.tools.kostsimy.comparison.moduleim.impl.CompareImageModuleImpl.java
@Override public boolean validate(File origDatei, File repDatei, File directoryOfLogfile) throws CompareImageException { boolean isValid = true; // boolean isValidFailed = false; boolean compResult = false; int allInt = 0; boolean allNoInt = false; String allStr = ""; String imToleranceTxt = getConfigurationService().getImTolerance(); String imTolerance = "5%"; float percentageInvalid = 99.9999f; /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ /* Initialisierung ImageMagick -> berprfen der Angaben: existiert die compare.exe, * msvcp120.dll, msvcr120.dll, vcomp120.dll am vorgegebenen Ort? */ String compareExe = "compare.exe"; String msvcp120Dll = "msvcp120.dll"; String msvcr120Dll = "msvcr120.dll"; String vcomp120Dll = "vcomp120.dll"; String im = "resources" + File.separator + "ImageMagickCompare-6.9.1-Q16"; boolean imExist = true; File fCompareExe = new File(im + File.separator + compareExe); if (!fCompareExe.exists()) { // Compare.exe von ImageMagick existiert nicht, kein Vergleich --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, compareExe)); imExist = false;/*from w ww . j a va2 s .com*/ } File fMsvcp120Dll = new File(im + File.separator + msvcp120Dll); if (!fMsvcp120Dll.exists()) { // msvcp120.dll von ImageMagick existiert nicht, kein Vergleich --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, msvcp120Dll)); imExist = false; } File fMsvcr120Dll = new File(im + File.separator + msvcr120Dll); if (!fMsvcr120Dll.exists()) { // msvcr120.dll von ImageMagick existiert nicht, kein Vergleich --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, msvcr120Dll)); imExist = false; } File fVcomp120Dll = new File(im + File.separator + vcomp120Dll); if (!fVcomp120Dll.exists()) { // vcomp120.dll von ImageMagick existiert nicht, kein Vergleich --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, vcomp120Dll)); imExist = false; } if (!imExist) { // compare.exe/msvcp120.dll/msvcr120.dll/vcomp120.dll von ImageMagick existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, vcomp120Dll)); return false; } if (imToleranceTxt.contains("N") || imToleranceTxt.contains("n")) { // null = 0% imTolerance = "0%"; percentageInvalid = (float) 100.000000000; imToleranceTxt = "N"; } else if (imToleranceTxt.contains("S") || imToleranceTxt.contains("s")) { // small = 2% imTolerance = "2%"; percentageInvalid = (float) 99.9999; imToleranceTxt = "S"; } else if (imToleranceTxt.contains("XL") || imToleranceTxt.contains("xl")) { // xlarge = 15% imTolerance = "15%"; percentageInvalid = (float) 99.9; imToleranceTxt = "XL"; } else if (imToleranceTxt.contains("L") || imToleranceTxt.contains("l")) { // large = 10% imTolerance = "10%"; percentageInvalid = (float) 99.99; imToleranceTxt = "L"; } else { // medium = 5% imTolerance = "5%"; imToleranceTxt = "M"; percentageInvalid = (float) 99.999; } String pathToCompareExe = fCompareExe.getAbsolutePath(); File report; File reportId; String imgPx1 = "1"; StringBuffer concatenatedOutputs = new StringBuffer(); try { String pathToOutput = directoryOfLogfile.getAbsolutePath() + File.separator + origDatei.getName() + "_compare_report.txt"; String pathToOutputId = directoryOfLogfile.getAbsolutePath() + File.separator + origDatei.getName() + "_identify_report.txt"; String pathToMask = directoryOfLogfile.getAbsolutePath() + File.separator + origDatei.getName() + "_mask.jpg"; /* compare -fuzz 15% -metric AE -quiet -identify -verbose -highlight-color DarkRed Image_1.jpg * Image_2.jpg mask.jpg >>results_id.txt 2>results.txt */ String command = "cmd /c \"\"" + pathToCompareExe + "\" -fuzz " + imTolerance + " -metric AE -quiet -identify -verbose -highlight-color DarkRed \"" + origDatei.getAbsolutePath() + "\" \"" + repDatei.getAbsolutePath() + "\" \"" + pathToMask + "\" >>\"" + pathToOutputId + "\" 2>\"" + pathToOutput + "\""; /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl * gehts: cmd /c\"urspruenlicher Befehl\" */ Process proc = null; Runtime rt = null; try { report = new File(pathToOutput); reportId = new File(pathToOutputId); // falls das File bereits existiert, z.B. von einem vorhergehenden Durchlauf, lschen // wir es if (report.exists()) { report.delete(); } if (reportId.exists()) { reportId.delete(); } Util.switchOffConsole(); rt = Runtime.getRuntime(); proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Fehleroutput holen StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // Output holen StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // Threads starten errorGobbler.start(); outputGobbler.start(); // Warte, bis wget fertig ist proc.waitFor(); Util.switchOnConsole(); // Kontrolle ob die Reports existieren if (!report.exists()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORT, report.getAbsolutePath())); if (!reportId.exists()) { getMessageService().logError( getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService() .getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath())); return false; } return false; } if (!reportId.exists()) { getMessageService().logError( getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService() .getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath())); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_SERVICEFAILED, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } // Kontrolle ob die Reports existieren if (!report.exists()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORT, report.getAbsolutePath())); if (!reportId.exists()) { getMessageService().logError( getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService() .getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath())); return false; } return false; } if (!reportId.exists()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath())); return false; } // Ende IMCMP direkt auszulsen // TODO: Marker: ReportId und auswerten (Grsse und der Pixel) try { BufferedReader in = new BufferedReader(new FileReader(reportId)); String line; String imgSize1 = "1"; String imgSize2 = "2"; String imgPx2 = "2"; while ((line = in.readLine()) != null) { concatenatedOutputs.append(line); concatenatedOutputs.append(NEWLINE); /* Format: TIFF (Tagged Image File Format) Mime type: image/tiff * * Geometry: 2469x3568+0+0 * * Channel statistics: * * Pixels: 8809392 * * Geometry und Pixels scheinen immer ausgegeben zu werden * * Gemotry und Pixels mssen identisch sein */ if (line.contains(" Geometry: ")) { if (imgSize1.equals("1")) { imgSize1 = line; } else { imgSize2 = line; } } else if (line.contains(" Pixels: ")) { if (imgPx1.equals("1")) { imgPx1 = line; } else { imgPx2 = line; } } // TODO: Marker: Auswertung und Fehlerausgabe wenn nicht bestanden. } if (imgPx1.equals("1") && imgPx2.equals("2") && imgSize1.equals("1") && imgSize2.equals("2")) { // identify_report ist leer oder enthlt nicht das was er sollte isValid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORTTEXT)); in.close(); return false; } if (!imgPx1.equals(imgPx2)) { // die beiden Bilder haben nicht gleich viel Pixels isValid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_CI_PIXELINVALID, imgPx1, imgPx2)); } if (!imgSize1.equals(imgSize2)) { // die beiden Bilder sind nicht gleich gross isValid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_CI_SIZEINVALID, imgSize1, imgSize2)); } if (!isValid) { // die beiden Bilder sind nicht gleich gross in.close(); return false; } in.close(); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_UNKNOWN, "identify: " + e.getMessage())); return false; } // TODO: Marker: Report auswerten (Bildvergleich) wenn grsse & PixelAnzahl identisch try { BufferedReader in = new BufferedReader(new FileReader(report)); String line; boolean allNull = false; boolean allExist = false; while ((line = in.readLine()) != null) { concatenatedOutputs.append(line); concatenatedOutputs.append(NEWLINE); /* img1.tif[0] TIFF 2469x3568 2469x3568+0+0 8-bit Grayscale Gray 8.833MB 1.451u 0:01.774 * * img2.jp2[0] JP2 2469x3568 2469x3568+0+0 8-bit Gray 1.842MB 1.357u 0:01.378 * * all: 0 * * in den ersten zwei zeilen sind die eigenschaften der beiden Bilder enthalten * * Danach die Anzahl Pixel mit einer grsseren Abweichung aus, allg: 0= vergleichbar */ if (line.contains(" all: ")) { allExist = true; if (line.contains(" all: 0")) { allNull = true; } else { /* Invalide Px extrahieren " all: 3563" extrahieren */ String lineReportAll = line.substring(9); try { // lineReport = 3563 allInt = Integer.parseInt(lineReportAll); } catch (Exception e) { allNoInt = true; allStr = lineReportAll; } } } if (allNull) { compResult = true; } } in.close(); if (!allExist) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_IMCMP_NOALL)); return false; } if (!compResult) { // Bildvergleich nicht bestanden if (allNoInt) { /* Bilder mit vielen Pixels die Abweichen (Potenz -> String): Vereinfachte Fehlerausgabe */ /* Invalide [allStr] und total px z2 aus imgPx1 " Pixels: 8809392" extrahieren */ String lineReport = imgPx1.substring(12); // lineReport = 8809392 isValid = false; getMessageService().logError( getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService() .getText(ERROR_XML_CI_CIINVALIDSTR, lineReport, imToleranceTxt, allStr)); } else { /* Bilder mit einer Abweichung (Int): Prozent ermitteln und mit percentageInvalid * abgleichen */ double z1 = 0; double z2 = 0; float percentageCalc = (float) 0.0; float percentageCalcInv = (float) 0.0; /* Invalide z1 [allInt] und total px z2 aus imgPx1 " Pixels: 8809392" extrahieren */ String lineReport = imgPx1.substring(12); // lineReport = 8809392 z2 = Double.parseDouble(lineReport); z1 = allInt; percentageCalc = (float) (100 - (100 / z2 * z1)); percentageCalcInv = 100 - percentageCalc; // Prozentzahlen vergleichen if (percentageInvalid > percentageCalc) { // Bilder mit einer grsseren Abweichung isValid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_CI_CIINVALID, percentageCalcInv, z2, imToleranceTxt, z1)); } } } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_UNKNOWN, "compare: " + e.getMessage())); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } // reports lschen if (report.exists()) { report.delete(); } if (reportId.exists()) { reportId.delete(); } return isValid; }
From source file:de.fosd.jdime.strategy.LinebasedStrategy.java
/** * This line-based <code>merge</code> method uses the merging routine of * the external tool <code>git</code>. * <p>//from w w w . ja v a 2 s . c o m * Basically, the input <code>FileArtifacts</code> are passed as arguments to * `git merge-file -q -p`. * <p> * In a common run, the number of processed lines of code, the number of * conflicting situations, and the number of conflicting lines of code will * be counted. Empty lines and comments are skipped to keep * <code>MergeStrategies</code> comparable, as JDime does (in its current * implementation) not respect comments. * <p> * In case of a performance benchmark, the output is simply ignored for the * sake of speed, and the merge will be run the specified amount of times, * aiming to allow the computation of a reasonable mean runtime. * * @param operation <code>MergeOperation</code> that is executed by this strategy * @param context <code>MergeContext</code> that is used to retrieve environmental parameters * * @throws IOException * @throws InterruptedException */ @Override public final void merge(final MergeOperation<FileArtifact> operation, final MergeContext context) throws IOException, InterruptedException { assert (operation != null); assert (context != null); MergeTriple<FileArtifact> triple = operation.getMergeTriple(); assert (triple != null); assert (triple.isValid()) : "The merge triple is not valid!"; assert (triple.getLeft() instanceof FileArtifact); assert (triple.getBase() instanceof FileArtifact); assert (triple.getRight() instanceof FileArtifact); assert (triple.getLeft().exists() && !triple.getLeft().isDirectory()); assert ((triple.getBase().exists() && !triple.getBase().isDirectory()) || triple.getBase().isEmptyDummy()); assert (triple.getRight().exists() && !triple.getRight().isDirectory()); context.resetStreams(); FileArtifact target = null; if (operation.getTarget() != null) { assert (operation.getTarget() instanceof FileArtifact); target = operation.getTarget(); assert (!target.exists() || target.isEmpty()) : "Would be overwritten: " + target; } List<String> cmd = new ArrayList<>(); cmd.add(BASECMD); cmd.addAll(Arrays.asList(BASEARGS)); for (FileArtifact file : triple.getList()) { cmd.add(file.getPath()); } ProcessBuilder pb = new ProcessBuilder(cmd); ArrayList<Long> runtimes = new ArrayList<>(); int conflicts = 0; int loc = 0; int cloc = 0; // launch the merge process by invoking GNU merge (rcs has to be // installed) LOG.debug("Running external command: " + StringUtils.join(cmd, " ")); for (int i = 0; i < context.getBenchmarkRuns() + 1 && (i == 0 || context.isBenchmark()); i++) { long cmdStart = System.currentTimeMillis(); Process pr = pb.start(); if (i == 0 && (!context.isBenchmark() || context.hasStats())) { // process input stream BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); boolean conflict = false; boolean comment = false; int tmp = 0; String line; while ((line = buf.readLine()) != null) { context.appendLine(line); if (context.hasStats()) { if (line.matches("^$") || line.matches("^\\s*$") || line.matches("^\\s*//.*$")) { // skip empty lines and single line comments continue; } else if (line.matches("^\\s*/\\*.*")) { if (line.matches("^\\s*/\\*.*?\\*/")) { // one line comment continue; } else { // starting block comment comment = true; continue; } } else if (line.matches("^.*?\\*/")) { // ending block comment comment = false; continue; } if (line.matches("^\\s*<<<<<<<.*")) { if (LOG.isDebugEnabled()) { LOG.debug("CONFLICT in " + triple); } conflict = true; comment = false; tmp = cloc; conflicts++; } else if (line.matches("^\\s*=======.*")) { comment = false; } else if (line.matches("^\\s*>>>>>>>.*")) { conflict = false; comment = false; if (tmp == cloc) { // only conflicting comments or empty lines conflicts--; } } else { loc++; if (conflict && !comment) { cloc++; } } } } buf.close(); // process error stream buf = new BufferedReader(new InputStreamReader(pr.getErrorStream())); while ((line = buf.readLine()) != null) { if (i == 0 && (!context.isBenchmark() || context.hasStats())) { context.appendErrorLine(line); } } buf.close(); } pr.getInputStream().close(); pr.getErrorStream().close(); pr.getOutputStream().close(); pr.waitFor(); long runtime = System.currentTimeMillis() - cmdStart; runtimes.add(runtime); if (LOG.isInfoEnabled() && context.isBenchmark() && context.hasStats()) { if (i == 0) { LOG.info("Initial run: " + runtime + " ms"); } else { LOG.info("Run " + i + " of " + context.getBenchmarkRuns() + ": " + runtime + " ms"); } } } if (context.isBenchmark() && runtimes.size() > 1) { // remove first run as it took way longer due to all the counting runtimes.remove(0); } Long runtime = MergeContext.median(runtimes); LOG.debug("Linebased merge time was " + runtime + " ms."); if (context.hasErrors()) { LOG.fatal("Errors occured while calling '" + cmd + "')"); System.err.println(context.getStdErr()); } // write output if (target != null) { assert (target.exists()); target.write(context.getStdIn()); } // add statistical data to context if (context.hasStats()) { assert (cloc <= loc); Stats stats = context.getStats(); StatsElement linesElement = stats.getElement("lines"); assert (linesElement != null); StatsElement newElement = new StatsElement(); newElement.setMerged(loc); newElement.setConflicting(cloc); linesElement.addStatsElement(newElement); if (conflicts > 0) { assert (cloc > 0); stats.addConflicts(conflicts); StatsElement filesElement = stats.getElement("files"); assert (filesElement != null); filesElement.incrementConflicting(); } else { assert (cloc == 0); } stats.increaseRuntime(runtime); MergeTripleStats scenariostats = new MergeTripleStats(triple, conflicts, cloc, loc, runtime, null, null, null); stats.addScenarioStats(scenariostats); } }
From source file:net.pms.dlna.RootFolder.java
/** * Returns Aperture folder. Used by manageRoot, so it is usually used as * a folder at the root folder. Only works when PMS is run on Mac OS X. * TODO: Requirements for Aperture.//from w w w .j a v a2 s. co m */ private DLNAResource getApertureFolder() { VirtualFolder res = null; if (Platform.isMac()) { Process process = null; try { process = Runtime.getRuntime().exec("defaults read com.apple.iApps ApertureLibraries"); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); // Every line entry is one aperture library. We want all of them as a dlna folder. String line; res = new VirtualFolder("Aperture libraries", null); while ((line = in.readLine()) != null) { if (line.startsWith("(") || line.startsWith(")")) { continue; } line = line.trim(); // remove extra spaces line = line.substring(1, line.lastIndexOf("\"")); // remove quotes and spaces VirtualFolder apertureLibrary = createApertureDlnaLibrary(line); if (apertureLibrary != null) { res.addChild(apertureLibrary); } } in.close(); } catch (Exception e) { logger.error("Something went wrong with the aperture library scan: ", e); } finally { // Avoid zombie processes, or open stream failures if (process != null) { try { // The process seems to always finish, so we can wait for it. // If the result code is not read by parent. The process might turn into a zombie (they are real!) process.waitFor(); } catch (InterruptedException e) { // Can this thread be interrupted? Don't think so, or, and even when, what will happen? logger.warn("Interrupted while waiting for stream for process" + e.getMessage()); } try { process.getErrorStream().close(); } catch (Exception e) { logger.warn("Could not close stream for output process", e); } try { process.getInputStream().close(); } catch (Exception e) { logger.warn("Could not close stream for output process", e); } try { process.getOutputStream().close(); } catch (Exception e) { logger.warn("Could not close stream for output process", e); } } } } return res; }
From source file:marytts.tools.voiceimport.HTKLabeler.java
/** * Force Align database for Automatic labels * @throws Exception/* w w w . ja v a 2 s .co m*/ */ private void hviteMultiplePronunciationAligning(String hmmNumber, String alignedMlf, boolean labOutput, String labDir, boolean full, String logfile, boolean cmp) throws Exception { String hvite = getProp(HTKDIR) + File.separator + "HVite"; // -A -D -V -T 1 "; // to add -A -D -V -T 1 in every function File htkFile = new File(hvite); if (!htkFile.exists()) { throw new RuntimeException("File " + htkFile.getAbsolutePath() + " does not exist"); } String configFile = getProp(HTDIR) + File.separator + "config" + File.separator + "htkTrain.conf"; String listFile = getProp(HTDIR) + File.separator + "etc" + File.separator + "htkTrain.list"; // Virtual sp change_ phoneList should be a member? // Without sp: /*String phoneList = getProp(HTDIR)+File.separator +"etc"+File.separator+"htk.phone2.list";*/ // Whit sp: String phoneList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phone3.list"; String hmmDef = getProp(HTDIR) + File.separator + "hmm" + File.separator + hmmNumber + File.separator + "hmmdefs"; String macros = getProp(HTDIR) + File.separator + "hmm" + File.separator + hmmNumber + File.separator + "macros"; // Virtual sp change_ phoneMlf should be a member? // Without sp: /*String phoneMlf = getProp(HTDIR)+File.separator +"etc"+File.separator+"htk.phones2.mlf";*/ // Whit sp: String phoneMlf = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.words3.mlf"; String phoneDict = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.words.dict"; Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell //when no sp use (-m)! String cmd; String alignout, mOptioon, oOption; if (labOutput) alignout = ""; else alignout = " -i " + alignedMlf; if (full) { if (labOutput) mOptioon = ""; else mOptioon = " -m"; cmd = "( cd " + getProp(HTDIR) + "; " + hvite + " " + HTK_SO + " -b sil -l " + labDir + " -C " + configFile + mOptioon + " -a -H " + macros + " -H " + hmmDef + alignout + " -t 250.0 -y lab" + " -I " + phoneMlf + " -S " + listFile + " " + phoneDict + " " + phoneList + " > " + logfile + "; exit )\n"; } else { if (cmp) oOption = " -o TS"; else oOption = " -o W"; cmd = "( cd " + getProp(HTDIR) + "; " + hvite + " " + HTK_SO + " -b sil -l " + labDir + oOption + " -C " + configFile + " -m -a -H " + macros + " -H " + hmmDef + alignout + " -t 250.0 -y lab" + " -I " + phoneMlf + " -S " + listFile + " " + phoneDict + " " + phoneList + " > " + logfile + "; exit )\n"; } PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println(cmd); pw.println(cmd); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } }
From source file:GestoSAT.GestoSAT.java
public boolean actualizarConfiguracion(Vector<String> mySQL, Vector<String> confSeg, int iva, String logo) throws Exception { FileReader file;//from w w w. ja v a 2 s. c om try { this.iva = Math.abs(iva); BufferedImage image = null; byte[] imageByte; BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(logo.split(",")[1]); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); bis.close(); // write the image to a file File outputfile = new File("logo"); String formato = logo.split("/")[1].split(";")[0]; ImageIO.write(image, formato, outputfile); // MySQL if (mySQL.elementAt(0).equals(this.mySQL.elementAt(0))) { if (!mySQL.elementAt(1).equals(this.mySQL.elementAt(1)) && !mySQL.elementAt(2).equals(this.mySQL.elementAt(2)) && (!mySQL.elementAt(3).equals(this.mySQL.elementAt(3)) || !mySQL.elementAt(0).equals(""))) { Class.forName("com.mysql.jdbc.Driver"); this.con.close(); this.con = DriverManager.getConnection("jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); this.mySQL.set(0, mySQL.elementAt(0)); this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + ""); this.mySQL.set(2, mySQL.elementAt(2)); this.mySQL.set(3, mySQL.elementAt(3)); } } else { // Comprobar que pass != "" Process pGet = Runtime.getRuntime() .exec("mysqldump -u " + this.mySQL.elementAt(2) + " -p" + this.mySQL.elementAt(3) + " -h " + this.mySQL.elementAt(0) + " -P " + this.mySQL.elementAt(1) + " gestosat"); InputStream is = pGet.getInputStream(); FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql"); byte[] bufferOut = new byte[1000]; int leido = is.read(bufferOut); while (leido > 0) { fos.write(bufferOut, 0, leido); leido = is.read(bufferOut); } fos.close(); Class.forName("com.mysql.jdbc.Driver"); this.con.close(); this.con = DriverManager.getConnection( "jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); this.mySQL.set(0, mySQL.elementAt(0)); this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + ""); this.mySQL.set(2, mySQL.elementAt(2)); this.mySQL.set(3, mySQL.elementAt(3)); Process pPut = Runtime.getRuntime() .exec("mysql -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h " + mySQL.elementAt(0) + " -P " + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + " gestosat"); OutputStream os = pPut.getOutputStream(); FileInputStream fis = new FileInputStream("backupGestoSAT.sql"); byte[] bufferIn = new byte[1000]; int escrito = fis.read(bufferIn); while (escrito > 0) { os.write(bufferIn, 0, leido); escrito = fis.read(bufferIn); } os.flush(); os.close(); fis.close(); } // FTP FTPClient cliente = new FTPClient(); if (!confSeg.elementAt(3).equals("")) { cliente.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1))); if (cliente.login(confSeg.elementAt(2), confSeg.elementAt(3))) { cliente.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql")); cliente.enterLocalPassiveMode(); cliente.storeFile("backupGestoSAT.sql", buffIn); buffIn.close(); cliente.logout(); cliente.disconnect(); this.confSeg = confSeg; } else return false; } File archConf = new File("confGestoSAT"); BufferedWriter bw = new BufferedWriter(new FileWriter(archConf)); bw.write(this.mySQL.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.mySQL.elementAt(1))) + ";" + this.mySQL.elementAt(2) + ";" + this.mySQL.elementAt(3) + ";" + this.confSeg.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.confSeg.elementAt(1))) + ";" + this.confSeg.elementAt(2) + ";" + this.confSeg.elementAt(3) + ";" + Math.abs(iva)); bw.close(); return true; } catch (Exception ex) { file = new FileReader("confGestoSAT"); BufferedReader b = new BufferedReader(file); String cadena; cadena = b.readLine(); String[] valores = cadena.split(";"); this.mySQL.add(valores[0]); this.mySQL.add(Math.abs(Integer.parseInt(valores[1])) + ""); this.mySQL.add(valores[2]); this.mySQL.add(valores[3]); con.close(); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager .getConnection("jdbc:mysql://" + this.mySQL.elementAt(0) + ":" + this.mySQL.elementAt(1) + "/gestosat?user=" + this.mySQL.elementAt(2) + "&password=" + this.mySQL.elementAt(3)); this.confSeg.add(valores[4]); this.confSeg.add(Math.abs(Integer.parseInt(valores[5])) + ""); this.confSeg.add(valores[6]); this.confSeg.add(valores[7]); file.close(); Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:ch.kostceco.tools.kostval.validation.modulepdfa.impl.ValidationAvalidationAiModuleImpl.java
@Override public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationApdfvalidationException { @SuppressWarnings("unused") boolean valid = false; // Version & Level herausfinden String pdfa1 = getConfigurationService().pdfa1(); String pdfa2 = getConfigurationService().pdfa2(); Integer pdfaVer1 = 0;// ww w. ja v a 2 s .c om Integer pdfaVer2 = 0; /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ // Vorbereitung fr eine allfllige Festhaltung bei unterschiedlichen Validierungsresultaten in // einer PDF_Diagnosedatei File pdfDia = null; String pdfDiaPath = getConfigurationService().getPathToDiagnose(); try { pdfDia = new File(pdfDiaPath + File.separator + "PDF-Diagnosedaten.kost-val.xml"); if (!pdfDia.exists()) { pdfDia.createNewFile(); PrintWriter output; BufferedWriter buffer; FileWriter fileWriter; fileWriter = new FileWriter(pdfDia); buffer = new BufferedWriter(fileWriter); output = new PrintWriter(buffer); try { output.print(getTextResourceService().getText(MESSAGE_XML_DIAHEADER) + "\n"); output.print(getTextResourceService().getText(MESSAGE_XML_DIAEND)); } finally { output.close(); buffer.close(); fileWriter.close(); } } File xslDiaOrig = new File("resources" + File.separator + "kost-val_PDFdia.xsl"); File xslDiaCopy = new File(pdfDiaPath + File.separator + "kost-val_PDFdia.xsl"); if (!xslDiaCopy.exists()) { Util.copyFile(xslDiaOrig, xslDiaCopy); } } catch (IOException e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); } /* Neu soll die Validierung mit PDFTron konfigurier bar sein Mgliche Werte 1A, 1B und no sowie * 2A, 2B, 2U und no Da Archive beide Versionen erlauben knnen sind es 2 config eintrge Es * gibt mehre Mglichkeiten das PDF in der gewnschten Version zu testen - Unterscheidung anhand * DROID --> braucht viel Zeit auch mit KaD_Signaturefile - Unterscheidung anhand PDF/A-Eintrag * wie Droid aber selber programmiert --> ist viel schneller */ if (pdfa2.equals("2A") || pdfa2.equals("2B") || pdfa2.equals("2U")) { // gltiger Konfigurationseintrag und V2 erlaubt pdfaVer2 = 2; } else { // v2 nicht erlaubt oder falscher eintrag pdfa2 = "no"; } if (pdfa1.equals("1A") || pdfa1.equals("1B")) { // gltiger Konfigurationseintrag und V1 erlaubt pdfaVer1 = 1; } else { // v1 nicht erlaubt oder falscher eintrag pdfa1 = "no"; } if (pdfa1 == "no" && pdfa2 == "no") { // keine Validierung mglich. keine PDFA-Versionen konfiguriert getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_NOCONFIG)); valid = false; return false; } String level = "no"; // Richtiges Level definieren if (pdfaVer1 != 1) { // Level 1 nicht erlaubt --> Level 2 level = pdfa2; } else if (pdfaVer2 != 2) { // Level 2 nicht erlaubt --> Level 1 level = pdfa1; } else { try { // Beide sind mglich --> Level je nach File auswhlen pdfaVer1 = 0; pdfaVer2 = 0; BufferedReader in = new BufferedReader(new FileReader(valDatei)); String line; while ((line = in.readLine()) != null) { // hufige Partangaben: pdfaid:part>1< pdfaid:part='1' pdfaid:part="1" if (line.contains("pdfaid:part")) { // pdfaid:part if (line.contains("pdfaid:part>1<")) { level = pdfa1; pdfaVer1 = 1; } else if (line.contains("pdfaid:part='1'")) { level = pdfa1; pdfaVer1 = 1; } else if (line.contains("pdfaid:part=\"1\"")) { level = pdfa1; pdfaVer1 = 1; } else if (line.contains("pdfaid:part>2<")) { level = pdfa2; pdfaVer2 = 2; } else if (line.contains("pdfaid:part='2'")) { level = pdfa2; pdfaVer2 = 2; } else if (line.contains("pdfaid:part=\"2\"")) { level = pdfa2; pdfaVer2 = 2; } else if (line.contains("pdfaid:part") && line.contains("1")) { // PDFA-Version = 1 level = pdfa1; pdfaVer1 = 1; } else if (line.contains("pdfaid:part") && line.contains("2")) { // PDFA-Version = 2 level = pdfa2; pdfaVer2 = 2; } } if (pdfaVer1 == 0 && pdfaVer2 == 0) { // der Part wurde nicht gefunden --> Level 2 level = pdfa2; } } } catch (Throwable e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); } } getMessageService().logError(getTextResourceService().getText(MESSAGE_PDFAVALIDATION_VL, level)); // Start mit der Erkennung // Eine PDF Datei (.pdf / .pdfa) muss mit %PDF [25504446] beginnen if (valDatei.isDirectory()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_ISDIRECTORY)); return false; } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".pdf") || valDatei.getAbsolutePath().toLowerCase().endsWith(".pdfa"))) { FileReader fr = null; try { fr = new FileReader(valDatei); BufferedReader read = new BufferedReader(fr); // Hex 25 in Char umwandeln String str1 = "25"; int i1 = Integer.parseInt(str1, 16); char c1 = (char) i1; // Hex 50 in Char umwandeln String str2 = "50"; int i2 = Integer.parseInt(str2, 16); char c2 = (char) i2; // Hex 44 in Char umwandeln String str3 = "44"; int i3 = Integer.parseInt(str3, 16); char c3 = (char) i3; // Hex 46 in Char umwandeln String str4 = "46"; 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 IST = c1c2c3c4 char[] charArray1 = buffer; char[] charArray2 = new char[] { c1, c2, c3, c4 }; if (Arrays.equals(charArray1, charArray2)) { // hchstwahrscheinlich ein PDF da es mit 25504446 respektive %PDF beginnt valid = true; } else { // Droid-Erkennung, damit Details ausgegeben werden knnen String nameOfSignature = getConfigurationService().getPathToDroidSignatureFile(); if (nameOfSignature == null) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(MESSAGE_XML_CONFIGURATION_ERROR_NO_SIGNATURE)); return false; } // existiert die SignatureFile am angebenen Ort? File fnameOfSignature = new File(nameOfSignature); if (!fnameOfSignature.exists()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(MESSAGE_XML_CA_DROID)); return false; } Droid droid = null; try { /* kleiner Hack, weil die Droid libraries irgendwo ein System.out drin haben, welche den * Output stren Util.switchOffConsole() als Kommentar markieren wenn man die * Fehlermeldung erhalten mchte */ Util.switchOffConsole(); droid = new Droid(); droid.readSignatureFile(nameOfSignature); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_CANNOT_INITIALIZE_DROID)); return false; } finally { Util.switchOnConsole(); } File file = valDatei; String puid = ""; IdentificationFile ifile = droid.identify(file.getAbsolutePath()); for (int x = 0; x < ifile.getNumHits(); x++) { FileFormatHit ffh = ifile.getHit(x); FileFormat ff = ffh.getFileFormat(); puid = ff.getPUID(); } getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_INCORRECTFILE, puid)); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_INCORRECTFILE)); return false; } } else { // die Datei endet nicht mit pdf oder pdfa -> Fehler getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_INCORRECTFILEENDING)); return false; } // Ende der Erkennung boolean isValid = false; boolean dual = false; // Initialisierung PDFTron -> berprfen der Angaben: existiert die PdftronExe am angebenen Ort? String pathToPdftronExe = getConfigurationService().getPathToPdftronExe(); String producerFirstValidator = getConfigurationService().firstValidator(); String dualValidation = getConfigurationService().dualValidation(); /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ if (dualValidation.contentEquals("dual")) { // Duale Validierung gewnscht dual = true; } if (!producerFirstValidator.contentEquals("PDFTron")) { // nicht der Validator von PDFTron --> PDFTools wird verwendet producerFirstValidator = "PDFTools"; } File fPdftronExe = new File(pathToPdftronExe); if (!fPdftronExe.exists() || !fPdftronExe.getName().equals("pdfa.exe")) { // Keine Duale Validierung mglich if (dualValidation.contentEquals("dual") || producerFirstValidator.contentEquals("PDFTron")) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_PDFTRON_MISSING)); dual = false; producerFirstValidator = "PDFTools"; } } pathToPdftronExe = "\"" + pathToPdftronExe + "\""; String pdfTools = ""; String pdfTron = ""; String newPdfDiaTxt = ""; try { int iCategory = 999999999; // Create object PdfValidatorAPI docPdf = new PdfValidatorAPI(); // TODO: Erledigt Start mit PDFTron if (producerFirstValidator.contentEquals("PDFTron")) { // zuerst mit PDFTron und danach ggf mit PDFTools File report; Document doc = null; try { // Pfad zum Programm Pdftron File pdftronExe = new File(pathToPdftronExe); File output = directoryOfLogfile; String pathToPdftronOutput = output.getAbsolutePath(); StringBuffer command = new StringBuffer(pdftronExe + " "); command.append("-l " + level); command.append(" -o "); command.append("\""); command.append(output.getAbsolutePath()); command.append("\""); command.append(" "); command.append("\""); command.append(valDatei.getAbsolutePath()); command.append("\""); Process proc = null; Runtime rt = null; try { /* Der Name des generierten Reports lautet per default report.xml und es scheint keine * Mglichkeit zu geben, dies zu bersteuern. */ report = new File(pathToPdftronOutput, "report.xml"); // falls das File bereits existiert, z.B. von einem vorhergehenden Durchlauf, lschen // wir es if (report.exists()) { report.delete(); } Util.switchOffConsole(); rt = Runtime.getRuntime(); proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Fehleroutput holen StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // Output holen StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // Threads starten errorGobbler.start(); outputGobbler.start(); // Warte, bis wget fertig ist proc.waitFor(); Util.switchOnConsole(); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_SERVICEFAILED, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } // Ende PDFTRON direkt auszulsen String pathToPdftronReport = report.getAbsolutePath(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToPdftronReport)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(bis); doc.normalize(); Integer passCount = new Integer(0); NodeList nodeLstI = doc.getElementsByTagName("Pass"); // Valide pdfa-Dokumente enthalten "<Validation> <Pass FileName..." Anzahl pass = anzahl // Valider pdfa for (int s = 0; s < nodeLstI.getLength(); s++) { passCount = passCount + 1; // Valide PDFA-Datei Module A-J sind Valid isValid = true; } if (passCount == 0) { if (dual) { // Duale Validierung mit PDFTools if (docPdf.open(valDatei.getAbsolutePath(), "", NativeLibrary.COMPLIANCE.ePDFUnk)) { // PDF Konnte geffnet werden docPdf.setStopOnError(true); docPdf.setReportingLevel(1); } else { docPdf.setStopOnError(true); docPdf.setReportingLevel(1); if (docPdf.getErrorCode() == NativeLibrary.ERRORCODE.PDF_E_PASSWORD) { getMessageService().logError(getTextResourceService() .getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_ENCRYPTED)); return false; } else { getMessageService().logError(getTextResourceService() .getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_DAMAGED)); return false; } } /* ePDFA1a 5122 ePDFA1b 5121 ePDFA2a 5891 ePDFA2b 5889 ePDFA2u 5890 */ if (level.contentEquals("1A")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5122)) { docPdf.validate(); } } else if (level.contentEquals("1B")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5121)) { docPdf.validate(); } } else if (level.contentEquals("2A")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5891)) { docPdf.validate(); } } else if (level.contentEquals("2B")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) { docPdf.validate(); } } else if (level.contentEquals("2U")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5890)) { docPdf.validate(); } } else { // Validierung nach 2b level = "2B"; if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) { docPdf.validate(); } } // Error Category iCategory = docPdf.getCategories(); /* die Zahl kann auch eine Summe von Kategorien sein z.B. 6144=2048+4096 -> * getCategoryText gibt nur die erste Kategorie heraus (z.B. 2048) */ int success = 0; /* ErrorCode kann ungleich Null sein, wenn es nur eine Information zu einer nicht * einhaltung einer Empfehlung gefunden wurde. * * Entsprechend wird der ErrorCode ignoriert. */ PdfError err = docPdf.getFirstError(); PdfError err1 = docPdf.getFirstError(); @SuppressWarnings("unused") int iError = 0; while (err != null) { iError = err1.getErrorCode(); success = success + 1; // Get next error err = docPdf.getNextError(); } if (success == 0 && iCategory == 0) { // valide isValid = true; // Diskrepanz => PDF-Diagnosedaten ErrorCodes von PDFTron holen NodeList nodeLst = doc.getElementsByTagName("Error"); String errorCodes = ""; for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); errorCodes = errorCodes + " " + errorCode; } pdfTools = "<PDFTools><iCategory>0</iCategory><iError>0</iError></PDFTools>"; pdfTron = "<PDFTron><Code>" + errorCodes + "</Code></PDFTron>"; newPdfDiaTxt = "<Validation><ValFile>" + valDatei.getAbsolutePath() + "</ValFile><PdfaVL>" + level + "</PdfaVL>" + pdfTools + pdfTron + "</Validation>\n" + getTextResourceService().getText(MESSAGE_XML_DIAEND); Util.pdfDia(newPdfDiaTxt, pdfDia); Util.amp(pdfDia); } else { // invalid isValid = false; } } else { // keine duale Validierung -> invalid isValid = false; } } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } } else { // TODO: Erledigt Start mit PDFTools // zuerst mit PDFTools und danach ggf mit PDFTron if (docPdf.open(valDatei.getAbsolutePath(), "", NativeLibrary.COMPLIANCE.ePDFUnk)) { // PDF Konnte geffnet werden } else { if (docPdf.getErrorCode() == NativeLibrary.ERRORCODE.PDF_E_PASSWORD) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_ENCRYPTED)); return false; } else { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFTOOLS_DAMAGED)); return false; } } /* ePDFA1a 5122 ePDFA1b 5121 ePDFA2a 5891 ePDFA2b 5889 ePDFA2u 5890 */ if (level.contentEquals("1A")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5122)) { docPdf.validate(); } } else if (level.contentEquals("1B")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5121)) { docPdf.validate(); } } else if (level.contentEquals("2A")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5891)) { docPdf.validate(); } } else if (level.contentEquals("2B")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) { docPdf.validate(); } } else if (level.contentEquals("2U")) { if (docPdf.open(valDatei.getAbsolutePath(), "", 5890)) { docPdf.validate(); } } else { // Validierung nach 2b level = "2B"; if (docPdf.open(valDatei.getAbsolutePath(), "", 5889)) { docPdf.validate(); } } docPdf.setStopOnError(false); docPdf.setReportingLevel(2); // Error Category iCategory = docPdf.getCategories(); /* die Zahl kann auch eine Summe von Kategorien sein z.B. 6144=2048+4096 -> getCategoryText * gibt nur die erste Kategorie heraus (z.B. 2048) */ int success = 0; PdfError err = docPdf.getFirstError(); PdfError err1 = docPdf.getFirstError(); int iError = 0; while (err != null) { iError = err1.getErrorCode(); success = success + 1; // Get next error err = docPdf.getNextError(); } if (success == 0 && iCategory == 0) { // valide isValid = true; } else { if (dual) { // duale Validierung File report; Document doc = null; try { // Pfad zum Programm Pdftron File pdftronExe = new File(pathToPdftronExe); File output = directoryOfLogfile; String pathToPdftronOutput = output.getAbsolutePath(); StringBuffer command = new StringBuffer(pdftronExe + " "); command.append("-l " + level); command.append(" -o "); command.append("\""); command.append(output.getAbsolutePath()); command.append("\""); command.append(" "); command.append("\""); command.append(valDatei.getAbsolutePath()); command.append("\""); Process proc = null; Runtime rt = null; try { /* Der Name des generierten Reports lautet per default report.xml und es scheint * keine Mglichkeit zu geben, dies zu bersteuern. */ report = new File(pathToPdftronOutput, "report.xml"); // falls das File bereits existiert, z.B. von einemvorhergehenden Durchlauf, lschen // wir es if (report.exists()) { report.delete(); } Util.switchOffConsole(); rt = Runtime.getRuntime(); proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Fehleroutput holen StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // Output holen StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // Threads starten errorGobbler.start(); outputGobbler.start(); // Warte, bis wget fertig ist proc.waitFor(); Util.switchOnConsole(); } catch (Exception e) { getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_SERVICEFAILED, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } // Ende PDFTRON direkt auszulsen String pathToPdftronReport = report.getAbsolutePath(); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(pathToPdftronReport)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(bis); doc.normalize(); Integer passCount = new Integer(0); NodeList nodeLstI = doc.getElementsByTagName("Pass"); // Valide pdfa-Dokumente enthalten "<Validation> <Pass FileName..." Anzahl pass = // anzahl Valider pdfa for (int s = 0; s < nodeLstI.getLength(); s++) { passCount = passCount + 1; // Valide PDFA-Datei Module A-J sind Valid isValid = true; // Diskrepanz => PDF-Diagnosedaten pdfTools = "<PDFTools><iCategory>" + iCategory + "</iCategory><iError>" + iError + "</iError></PDFTools>"; pdfTron = "<PDFTron><Code>Pass</Code></PDFTron>"; newPdfDiaTxt = "<Validation><ValFile>" + valDatei.getAbsolutePath() + "</ValFile><PdfaVL>" + level + "</PdfaVL>" + pdfTools + pdfTron + "</Validation>\n" + getTextResourceService().getText(MESSAGE_XML_DIAEND); Util.pdfDia(newPdfDiaTxt, pdfDia); Util.amp(pdfDia); } if (passCount == 0) { // Invalide PDFA-Datei (doppelt besttigt) isValid = false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_SERVICEFAILED, e.getMessage())); return false; } } else { // keine duale Validierung -> invalid isValid = false; } } } // TODO: Erledigt: Fehler Auswertung if (!isValid) { // Invalide PDFA-Datei boolean exponent0 = false; boolean exponent1 = false; boolean exponent2 = false; boolean exponent3 = false; boolean exponent4 = false; boolean exponent5 = false; boolean exponent6 = false; boolean exponent7 = false; boolean exponent8 = false; boolean exponent9 = false; boolean exponent10 = false; boolean exponent11 = false; boolean exponent12 = false; boolean exponent13 = false; boolean exponent14 = false; boolean exponent15 = false; boolean exponent16 = false; boolean exponent17 = false; boolean exponent18 = false; int iExp0 = (int) Math.pow(2, 0); int iExp1 = (int) Math.pow(2, 1); int iExp2 = (int) Math.pow(2, 2); int iExp3 = (int) Math.pow(2, 3); int iExp4 = (int) Math.pow(2, 4); int iExp5 = (int) Math.pow(2, 5); int iExp6 = (int) Math.pow(2, 6); int iExp7 = (int) Math.pow(2, 7); int iExp8 = (int) Math.pow(2, 8); int iExp9 = (int) Math.pow(2, 9); int iExp10 = (int) Math.pow(2, 10); int iExp11 = (int) Math.pow(2, 11); int iExp12 = (int) Math.pow(2, 12); int iExp13 = (int) Math.pow(2, 13); int iExp14 = (int) Math.pow(2, 14); int iExp15 = (int) Math.pow(2, 15); int iExp16 = (int) Math.pow(2, 16); int iExp17 = (int) Math.pow(2, 17); int iExp18 = (int) Math.pow(2, 18); if (producerFirstValidator.contentEquals("PDFTools") || dual) { // Invalide Kategorien von PDF-Tools if (iCategory >= iExp18) { exponent18 = true; iCategory = iCategory - iExp18; } if (iCategory >= iExp17) { exponent17 = true; iCategory = iCategory - iExp17; } if (iCategory >= iExp16) { exponent16 = true; iCategory = iCategory - iExp16; } if (iCategory >= iExp15) { exponent15 = true; iCategory = iCategory - iExp15; } if (iCategory >= iExp14) { exponent14 = true; iCategory = iCategory - iExp14; } if (iCategory >= iExp13) { exponent13 = true; iCategory = iCategory - iExp13; } if (iCategory >= iExp12) { exponent12 = true; iCategory = iCategory - iExp12; } if (iCategory >= iExp11) { exponent11 = true; iCategory = iCategory - iExp11; } if (iCategory >= iExp10) { exponent10 = true; iCategory = iCategory - iExp10; } if (iCategory >= iExp9) { exponent9 = true; iCategory = iCategory - iExp9; } if (iCategory >= iExp8) { exponent8 = true; iCategory = iCategory - iExp8; } if (iCategory >= iExp7) { exponent7 = true; iCategory = iCategory - iExp7; } if (iCategory >= iExp6) { exponent6 = true; iCategory = iCategory - iExp6; } if (iCategory >= iExp5) { exponent5 = true; iCategory = iCategory - iExp5; } if (iCategory >= iExp4) { exponent4 = true; iCategory = iCategory - iExp4; } if (iCategory >= iExp3) { exponent3 = true; iCategory = iCategory - iExp3; } if (iCategory >= iExp2) { exponent2 = true; iCategory = iCategory - iExp2; } if (iCategory >= iExp1) { exponent1 = true; iCategory = iCategory - iExp1; } if (iCategory >= iExp0) { exponent0 = true; iCategory = iCategory - iExp0; } } else { iCategory = 0; } File report = new File(directoryOfLogfile.getAbsolutePath(), "report.xml"); Document doc = null; if (producerFirstValidator.contentEquals("PDFTron") || dual) { // aus dem Output von Pdftron die Fehlercodes extrahieren und bersetzen String pathToPdftronReport = report.getAbsolutePath(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToPdftronReport)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(bis); doc.normalize(); // Bsp. fr einen Error Code: <Error Code="e_PDFA173" die erste Ziffer nach e_PDFA ist der // Error Code. } /** Modul A **/ if (exponent1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_AI_1, "iCategory_1")); } if (exponent2) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_AI_2, "iCategory_2")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // aus dem Output von Pdftron die Fehlercodes extrahieren und bersetzen String errorDigitA = "Fehler"; NodeList nodeLst = doc.getElementsByTagName("Error"); /* Bsp. fr einen Error Code: <Error Code="e_PDFA173" die erste Ziffer nach e_PDFA ist der * Error Code. */ for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); errorDigitA = errorCode.substring(6, 7); // der Error Code kann auch "Unknown" sein, dieser wird in den Code "0" bersetzt if (errorDigitA.equals("U")) { errorDigitA = "0"; } if (errorDigitA.equals("n")) { errorDigitA = "0"; } try { if (errorDigitA.equals("0")) { // Allgemeiner Fehler -> A isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } if (errorDigitA.equals("Fehler")) { // Fehler bei der Initialisierung Passierte bei einem Leerschlag im Namen isValid = false; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_A_PDFA_INIT)); return false; } } /** Modul B **/ if (exponent0) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA) + getTextResourceService().getText(ERROR_XML_AI_0, "iCategory_0")); } if (exponent7) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA) + getTextResourceService().getText(ERROR_XML_AI_7, "iCategory_7")); } if (exponent18) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA) + getTextResourceService().getText(ERROR_XML_AI_18, "iCategory_18")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("1")) { // Struktur Fehler -> B isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul C **/ if (exponent3) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA) + getTextResourceService().getText(ERROR_XML_AI_3, "iCategory_3")); } if (exponent4) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA) + getTextResourceService().getText(ERROR_XML_AI_4, "iCategory_4")); } if (exponent5) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA) + getTextResourceService().getText(ERROR_XML_AI_5, "iCategory_5")); } if (exponent6) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA) + getTextResourceService().getText(ERROR_XML_AI_6, "iCategory_6")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("2")) { // Grafik Fehler -> C isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul D **/ if (exponent8) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA) + getTextResourceService().getText(ERROR_XML_AI_8, "iCategory_8")); } if (exponent9) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA) + getTextResourceService().getText(ERROR_XML_AI_9, "iCategory_9")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("3")) { // Schrift Fehler -> D isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul E **/ if (exponent10) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_E_PDFA) + getTextResourceService().getText(ERROR_XML_AI_10, "iCategory_10")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("4")) { // Transparenz Fehler -> E isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_E_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_E_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul F **/ if (exponent11) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA) + getTextResourceService().getText(ERROR_XML_AI_11, "iCategory_11")); } if (exponent12) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA) + getTextResourceService().getText(ERROR_XML_AI_12, "iCategory_12")); } if (exponent13) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA) + getTextResourceService().getText(ERROR_XML_AI_13, "iCategory_13")); } if (exponent14) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA) + getTextResourceService().getText(ERROR_XML_AI_14, "iCategory_14")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("5")) { // Annotations Fehler -> F isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_F_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul G **/ if (exponent15) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA) + getTextResourceService().getText(ERROR_XML_AI_15, "iCategory_15")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("6")) { // Aktions Fehler -> G isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } // neu sind die Interaktionen (J) bei den Aktionen (G) if (errorDigit.equals("9")) { // Interaktions Fehler -> J isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_G_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul H **/ if (exponent16) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_PDFA) + getTextResourceService().getText(ERROR_XML_AI_16, "iCategory_16")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("7")) { // Metadaten Fehler -> H isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul I **/ if (exponent17) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_I_PDFA) + getTextResourceService().getText(ERROR_XML_AI_17, "iCategory_17")); } if (producerFirstValidator.contentEquals("PDFTron") || dual) { // Analog Modul A NodeList nodeLst = doc.getElementsByTagName("Error"); for (int s = 0; s < nodeLst.getLength(); s++) { Node dateiNode = nodeLst.item(s); NamedNodeMap nodeMap = dateiNode.getAttributes(); Node errorNode = nodeMap.getNamedItem("Code"); String errorCode = errorNode.getNodeValue(); String errorCodeMsg = "error.xml.ai." + errorCode.substring(2); Node errorNodeM = nodeMap.getNamedItem("Message"); String errorMessage = errorNodeM.getNodeValue(); String errorDigit = errorCode.substring(6, 7); try { if (errorDigit.equals("8")) { // Zugnglichkeit Fehler -> I isValid = false; getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_MODUL_I_PDFA) + getTextResourceService().getText(errorCodeMsg, errorCode)); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_I_PDFA) + getTextResourceService().getText(ERROR_XML_AI_TRANSLATE, errorCode, errorMessage)); } } } /** Modul J **/ // neu sind die Interaktionen (J) bei den Aktionen (G) docPdf.close(); // Destroy the object docPdf.destroyObject(); } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_PDFA) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); } return isValid; }
From source file:br.com.riselabs.cotonet.builder.commands.ExternalGitCommand.java
/** * OBS: this method returns {@code null} when calling ' * {@code git reset --hard}'.//from w w w . j a va 2s. c o m * * @return * @throws IOException */ public List<ConflictChunk<CommandLineBlameResult>> call() throws BlameException { Runtime run = Runtime.getRuntime(); Process pr = null; String cmd = null; String[] env = {}; BufferedReader buf; List<ConflictChunk<CommandLineBlameResult>> conflicts = null; int exitCode; try { switch (type) { case RESET: cmd = "git reset --hard"; pr = run.exec(cmd, env, file); break; case BLAME: default: cmd = "git blame -p --line-porcelain"; env = new String[1]; // we need this to disable the pager env[0] = "GIT_PAGER=cat"; pr = run.exec(cmd + " " + file, env, file.getParentFile()); // parse output buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); conflicts = new ArrayList<ConflictChunk<CommandLineBlameResult>>(); final String CONFLICT_START = "<<<<<<<"; final String CONFLICT_SEP = "======="; final String CONFLICT_END = ">>>>>>>"; boolean addBlame = false; ConflictChunk<CommandLineBlameResult> conflict = new ConflictChunk<CommandLineBlameResult>( file.getCanonicalPath()); CommandLineBlameResult bResult; bResult = new CommandLineBlameResult(file.getCanonicalPath()); Blame<CommandLineBlameResult> cBlame; cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult); List<String> block; while ((block = readPorcelainBlock(buf)) != null) { String commit = block.get(0).split(" ")[0]; // for (String line : block) // System.out.println(line); Map<PKeys, String> data = getDataFromPorcelainBlock(block); String contentLine = data.get(PKeys.content); int n; if ((n = contentLine.trim().indexOf(" ")) == -1) { // line without blank space contentLine = contentLine.trim(); } else { contentLine = contentLine.trim().substring(0, n); } if (contentLine.equals(CONFLICT_START)) { addBlame = true; continue; } else if (contentLine.equals(CONFLICT_SEP)) { addBlame = true; cBlame.setRevision(scenario.getLeft()); conflict.setBase(scenario.getBase()); conflict.setLeft(cBlame); bResult = new CommandLineBlameResult(file.getCanonicalPath()); cBlame = new Blame<CommandLineBlameResult>(scenario.getRight(), bResult); continue; } else if (contentLine.equals(CONFLICT_END)) { conflict.setRight(cBlame); conflict.setLine(Integer.valueOf(data.get(PKeys.linenumber))); conflicts.add(conflict); addBlame = false; bResult = new CommandLineBlameResult(file.getCanonicalPath()); cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult); //@gustavo added this line conflict = new ConflictChunk<CommandLineBlameResult>(file.getCanonicalPath()); } else if (addBlame) { // we are in one of the conflicting chunks Integer linenumber = Integer.valueOf(data.get(PKeys.linenumber)); contentLine = data.get(PKeys.content); String name = data.get(PKeys.authorname); String email = data.get(PKeys.authormail); DeveloperNode dev = new DeveloperNode(name, email); conflict.setLine(linenumber); bResult.addLineAuthor(linenumber, dev); bResult.addLineContent(linenumber, contentLine); bResult.addLineCommit(linenumber, commit); continue; } } buf.close(); break; } /* * already finished to execute the process. now, we should process * the error output. */ buf = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String stdErr = IOUtils.toString(pr.getErrorStream(), StandardCharsets.UTF_8).trim(); IOUtils.closeQuietly(pr.getInputStream()); IOUtils.closeQuietly(pr.getErrorStream()); IOUtils.closeQuietly(pr.getOutputStream()); exitCode = pr.waitFor(); buf.close(); if (!stdErr.isEmpty()) { Logger.log(String.format("Execution of '%s' returned standard error output:%n%s", cmd, stdErr)); throw new RuntimeException( String.format("Error on external call with exit code %d", pr.exitValue())); } } catch (IOException io) { try { throw new BlameException(file.getCanonicalPath(), "IO Exception", io); } catch (IOException e) { } } catch (InterruptedException ie) { // waitFor() exception exitCode = 666; try { throw new BlameException(file.getCanonicalPath(), String.format( "Interrupted while waiting for '%s' to finish. Error code: '%s'", cmd, exitCode), ie); } catch (IOException io) { } } catch (RuntimeException re) { try { throw new BlameException(file.getCanonicalPath(), "Runtime Exception", re); } catch (IOException e) { } } finally { run.freeMemory(); } pr.destroyForcibly(); return conflicts; }