List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:com.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops the Screen video capture/*from w ww . j a va 2s. c o m*/ */ private void stopScreenVideoCapture() { Log.i(TAG, "enter stopScreenVideoCapture at " + System.currentTimeMillis()); Process sh = null; DataOutputStream os = null; int pid = 0, exitValue = -1; try { pid = mAroUtils.getProcessID("ffmpeg"); } catch (IOException e1) { Log.e(TAG, "IOException in stopScreenVideoCapture", e1); } catch (InterruptedException e1) { Log.e(TAG, "exception in stopScreenVideoCapture", e1); } if (DEBUG) { Log.i(TAG, "stopScreenVideoCapture=" + pid); } if (pid != 0) { try { sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String command = "kill -15 " + pid + "\n"; os.writeBytes(command); command = "exit\n"; os.writeBytes(command); os.flush(); //clear the streams so that it doesnt block the process //sh.inputStream is actually the output from the process StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); exitValue = sh.waitFor(); if (exitValue == 0) { mVideoRecording = false; } if (DEBUG) { Log.i(TAG, "successfully returned from kill -15; exitValue= " + exitValue); } } catch (IOException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } catch (InterruptedException e) { Log.e(TAG, "exception in stopScreenVideoCapture", e); } finally { try { kill9Ffmpeg(); if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in stopScreenVideoCapture finally block", e); } if (DEBUG) { Log.i(TAG, "Stopped Video Capture in stopScreenVideoCapture()"); } } } if (DEBUG) { Log.i(TAG, "exit stopScreenVideoCapture"); } }
From source file:com.adito.agent.client.Agent.java
private void cleanupLinuxAgent() { // #ifdef DEBUG log.info("Clearing Linux agent cache"); //$NON-NLS-1$ // #endif// w ww . ja va 2 s . c o m try { String[] cmds = null; String homeDir = Utils.getHomeDirectory(); File cacheDir = getConfiguration().getCacheDir(); // #ifdef DEBUG log.info("Will remove " + cacheDir.getAbsolutePath()); //$NON-NLS-1$ // #endif File scriptFile = new File(homeDir, "agent-cleanup.sh"); File launchFile = new File(homeDir, "agent-cleanup-launch.sh"); // clean up script StringBuffer scriptContents = new StringBuffer(); scriptContents.append("#!/bin/sh\n"); scriptContents.append("sleep 3\n"); scriptContents.append("rm -fr \""); scriptContents.append(cacheDir.getAbsolutePath()); scriptContents.append("\" \""); File toRemove; for (Enumeration e = getConfiguration().getFilesToRemove(); e.hasMoreElements();) { toRemove = (File) e.nextElement(); scriptContents.append(toRemove.getAbsolutePath()); scriptContents.append("\" \""); } scriptContents.append(scriptFile.getAbsolutePath()); scriptContents.append("\" \""); scriptContents.append(launchFile.getAbsolutePath()); scriptContents.append("\"\n"); // launch script StringBuffer launchScript = new StringBuffer(); launchScript.append("#!/bin/sh\n"); launchScript.append("nohup sh \""); launchScript.append(scriptFile.getAbsolutePath()); launchScript.append("\" &\n"); cmds = new String[2]; cmds[0] = "sh"; cmds[1] = launchFile.getAbsolutePath(); FileOutputStream out = new FileOutputStream(scriptFile); out.write(scriptContents.toString().getBytes()); out.close(); out = new FileOutputStream(launchFile); out.write(launchScript.toString().getBytes()); out.close(); final Process proc = Runtime.getRuntime().exec(cmds); Thread t1 = new Thread(new Runnable() { public void run() { try { InputStream in = proc.getInputStream(); while (in.read() > -1) ; } catch (IOException e) { } } }); Thread t2 = new Thread(new Runnable() { public void run() { try { InputStream in = proc.getErrorStream(); while (in.read() > -1) ; } catch (IOException e) { } } }); t1.start(); t2.start(); } catch (Exception e) { } }
From source file:com.adito.agent.client.Agent.java
private void cleanupWindowsAgent() { // #ifdef DEBUG log.info("Clearing Windows agent cache"); //$NON-NLS-1$ // #endif// w w w .j av a2s . c om try { String[] cmds = null; String homeDir = Utils.getHomeDirectory(); File cwd = getConfiguration().getCacheDir(); // #ifdef DEBUG log.info("Will remove " + cwd.getAbsolutePath()); //$NON-NLS-1$ // #endif File scriptFile = new File(homeDir, "agent-cleanup.bat"); File launchFile = new File(homeDir, "agent-cleanup-launch.bat"); String scriptContents = "@echo off\r\n" + "echo Agent is removing all downloaded files\r\n" + ":Repeat\r\n" + "rd /S /Q \"" + cwd.getAbsolutePath() + "\" > NUL 2>&1\r\n" + "if exist \"" + cwd.getAbsolutePath() + "\" > NUL 2>&1 goto Repeat\r\n"; File toRemove; for (Enumeration e = getConfiguration().getFilesToRemove(); e.hasMoreElements();) { toRemove = (File) e.nextElement(); if (toRemove.exists()) { if (toRemove.isDirectory()) { scriptContents += "rd /S /Q \"" + toRemove.getAbsolutePath() + "\" > NUL 2>&1\r\n"; } else { scriptContents += "del \"" + toRemove.getAbsolutePath() + "\" > NUL 2>&1\r\n"; } } } scriptContents += "del \"" + scriptFile.getAbsolutePath() + "\" > NUL 2>&1 && exit\r\n"; String launchScript = "start \"Agent Cleanup\" /MIN \"" + scriptFile.getAbsolutePath() + "\"\r\n" + "del \"" + launchFile.getAbsolutePath() + "\" > NUL 2>&1\r\n"; cmds = new String[3]; cmds[0] = "cmd.exe"; cmds[1] = "/C"; cmds[2] = "\"" + launchFile.getAbsolutePath() + "\""; FileOutputStream out = new FileOutputStream(scriptFile); out.write(scriptContents.getBytes()); out.close(); out = new FileOutputStream(launchFile); out.write(launchScript.getBytes()); out.close(); final Process proc = Runtime.getRuntime().exec(cmds); Thread t1 = new Thread(new Runnable() { public void run() { try { InputStream in = proc.getInputStream(); while (in.read() > -1) ; } catch (IOException e) { } } }, "CleanupAgentInput"); Thread t2 = new Thread(new Runnable() { public void run() { try { InputStream in = proc.getErrorStream(); while (in.read() > -1) ; } catch (IOException e) { } } }, "CleanupAgentOutput"); t1.start(); t2.start(); } catch (Exception e) { } }
From source file:cz.cuni.amis.planning4j.validation.external.ValValidator.java
@Override public IValidationResult validate(IPDDLFileDomainProvider domainProvider, IPDDLFileProblemProvider problemProvider, List<ActionDescription> plan) { File mainExecutable = new File(validatorDirectory, getValidatorFolderName() + File.separatorChar + getValidatorExecutableName()); if (!mainExecutable.exists()) { String toolMessage = "Could not find validator executable '" + getValidatorExecutableName() + "' in directory " + validatorDirectory.getAbsolutePath(); throw new ValidationException(toolMessage); }/*from w ww. jav a 2s .c o m*/ FileWriter planWriter = null; Process process = null; try { /** * Write the plan to a temp file */ File planTempFile = File.createTempFile("plan", ".soln"); planWriter = new FileWriter(planTempFile); for (ActionDescription action : plan) { planWriter.write(action.getStartTime() + ": (" + action.getName() + " "); for (String param : action.getParameters()) { planWriter.write(param + " "); } planWriter.write(") [" + action.getDuration() + "]\n"); } planWriter.close(); planWriter = null; /** * Invoke the validator */ ProcessBuilder processBuilder = new ProcessBuilder(mainExecutable.getAbsolutePath(), "-s", //silent mode for simple parsing - only errors are printed to the stdout domainProvider.getDomainFile().getAbsolutePath(), problemProvider.getProblemFile().getAbsolutePath(), planTempFile.getAbsolutePath()); logger.info("Starting VAL validator."); if (logger.isDebugEnabled()) { logger.debug("The command: " + processBuilder.command()); } process = processBuilder.start(); Scanner outputScanner = new Scanner(process.getInputStream()); StringBuilder consoleOutputBuilder = new StringBuilder(); boolean hasNonEmptyLines = false; if (logger.isTraceEnabled()) { logger.trace("Validator output:"); } while (outputScanner.hasNextLine()) { String line = outputScanner.nextLine(); if (!consoleOutputBuilder.toString().isEmpty()) { consoleOutputBuilder.append("\n"); } if (!line.trim().isEmpty()) { hasNonEmptyLines = true; } consoleOutputBuilder.append(line); if (logger.isTraceEnabled()) { logger.trace(line); } } if (logger.isTraceEnabled()) { logger.trace("Validator output end."); } try { //clean the error stream. Otherwise this might prevent the process from being terminated / cleared from the process table IOUtils.toString(process.getErrorStream()); } catch (IOException ex) { logger.warn("Could not clear error stream.", ex); } process.waitFor(); boolean valid = !hasNonEmptyLines; //validator is run in silent mode, so any output means plan is not valid. logger.info("Validation finished. Result is: " + valid); return new ValidationResult(valid, consoleOutputBuilder.toString()); } catch (Exception ex) { if (planWriter != null) { try { planWriter.close(); } catch (Exception ignored) { } } if (process != null) { process.destroy(); try { //clean the streams so that the process does not hang in the process table IOUtils.toString(process.getErrorStream()); IOUtils.toString(process.getInputStream()); } catch (Exception ignored) { logger.warn("Could not clear output/error stream.", ignored); } } throw new ValidationException("Error during validation", ex); } }
From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
/** * Does the backup on a SwingWorker Thread. * @param isMonthly whether it is a monthly backup * @param doSendAppExit requests sending an application exit command when done * @return true if the prefs are set up and there were no errors before the SwingWorker thread was started *//*from w ww . ja va 2 s.c o m*/ private boolean doBackUp(final boolean isMonthly, final boolean doSendAppExit, final PropertyChangeListener propChgListener) { AppPreferences remotePrefs = AppPreferences.getLocalPrefs(); final String mysqldumpLoc = remotePrefs.get(MYSQLDUMP_LOC, getDefaultMySQLDumpLoc()); final String backupLoc = remotePrefs.get(MYSQLBCK_LOC, getDefaultBackupLoc()); if (!(new File(mysqldumpLoc)).exists()) { UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_DUMP", mysqldumpLoc); if (propChgListener != null) { propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } return false; } File backupDir = new File(backupLoc); if (!backupDir.exists()) { if (!backupDir.mkdir()) { UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_BK_DIR", backupDir.getAbsoluteFile()); if (propChgListener != null) { propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } return false; } } errorMsg = null; final String databaseName = DBConnection.getInstance().getDatabaseName(); getNumberofTables(); SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { protected String fullPath = null; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { FileOutputStream backupOut = null; try { Thread.sleep(100); // Create output file SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss"); String fileName = sdf.format(Calendar.getInstance().getTime()) + (isMonthly ? "_monthly" : "") + ".sql"; fullPath = backupLoc + File.separator + fileName; File file = new File(fullPath); backupOut = new FileOutputStream(file); writeStats(getCollectionStats(getTableNames()), getStatsName(fullPath)); String userName = DBConnection.getInstance().getUserName(); String password = DBConnection.getInstance().getPassword(); if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { Pair<String, String> up = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB(); if (up != null && up.first != null && up.second != null) { userName = up.first; password = up.second; } } String port = DatabaseDriverInfo.getDriver(DBConnection.getInstance().getDriverName()) .getPort(); String server = DBConnection.getInstance().getServerName(); Vector<String> args = new Vector<String>(); args.add(mysqldumpLoc); args.add("--user=" + userName); args.add("--password=" + password); args.add("--host=" + server); if (port != null) { args.add("--port=" + port); } args.add(databaseName); Process process = Runtime.getRuntime().exec(args.toArray(new String[0])); InputStream input = process.getInputStream(); byte[] bytes = new byte[8192 * 2]; double oneMeg = (1024.0 * 1024.0); long dspMegs = 0; long totalBytes = 0; do { int numBytes = input.read(bytes, 0, bytes.length); totalBytes += numBytes; if (numBytes > 0) { long megs = (long) (totalBytes / oneMeg); if (megs != dspMegs) { dspMegs = megs; long megsWithTenths = (long) ((totalBytes * 10.0) / oneMeg); firePropertyChange(MEGS, 0, megsWithTenths); } backupOut.write(bytes, 0, numBytes); } else { break; } } while (true); StringBuilder sb = new StringBuilder(); String line; BufferedReader errIn = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = errIn.readLine()) != null) { //System.err.println(line); if (line.startsWith("ERR") || StringUtils.contains(line, "Got error")) { sb.append(line); sb.append("\n"); if (StringUtils.contains(line, "1044") && StringUtils.contains(line, "LOCK TABLES")) { sb.append("\n"); sb.append(UIRegistry.getResourceString("MySQLBackupService.LCK_TBL_ERR")); sb.append("\n"); } } } errorMsg = sb.toString(); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); UIRegistry.showLocalizedError("MySQLBackupService.EXCP_BK"); } finally { if (backupOut != null) { try { backupOut.flush(); backupOut.close(); } catch (IOException ex) { ex.printStackTrace(); errorMsg = ex.toString(); } } } return null; } @Override protected void done() { super.done(); UIRegistry.getStatusBar().setProgressDone(STATUSBAR_NAME); UIRegistry.clearSimpleGlassPaneMsg(); if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (doSendAppExit) { CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit")); } if (propChgListener != null) { propChgListener .propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, null, fullPath)); } } }; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setIndeterminate(STATUSBAR_NAME, true); UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", databaseName), 24); backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (MEGS.equals(evt.getPropertyName())) { long value = (Long) evt.getNewValue(); double val = value / 10.0; statusBar.setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val)); } } }); backupWorker.execute(); return true; }
From source file:ch.kostceco.tools.kostval.validation.modulejp2.impl.ValidationAvalidationAModuleImpl.java
@Override public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationAjp2validationException { // Start mit der Erkennung // Eine JP2 Datei (.jp2) muss mit ....jP ...ftypjp2 // [0000000c6a5020200d0a870a] beginnen if (valDatei.isDirectory()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_ISDIRECTORY)); return false; } else if ((valDatei.getAbsolutePath().toLowerCase().endsWith(".jp2"))) { FileReader fr = null;/*from ww w . ja v a 2s. c o m*/ try { fr = new FileReader(valDatei); BufferedReader read = new BufferedReader(fr); // wobei hier nur die ersten 10 Zeichen der Datei ausgelesen werden // 1 00 010203 // 2 0c 04 // 3 6a 05 // 4 50 06 // 5 20 0708 // 6 0d 09 // 7 0a 10 // Hex 00 in Char umwandeln String str1 = "00"; int i1 = Integer.parseInt(str1, 16); char c1 = (char) i1; // Hex 0c in Char umwandeln String str2 = "0c"; int i2 = Integer.parseInt(str2, 16); char c2 = (char) i2; // Hex 6a in Char umwandeln String str3 = "6a"; int i3 = Integer.parseInt(str3, 16); char c3 = (char) i3; // Hex 50 in Char umwandeln String str4 = "50"; int i4 = Integer.parseInt(str4, 16); char c4 = (char) i4; // Hex 20 in Char umwandeln String str5 = "20"; int i5 = Integer.parseInt(str5, 16); char c5 = (char) i5; // Hex 0d in Char umwandeln String str6 = "0d"; int i6 = Integer.parseInt(str6, 16); char c6 = (char) i6; // Hex 0a in Char umwandeln String str7 = "0a"; int i7 = Integer.parseInt(str7, 16); char c7 = (char) i7; // auslesen der ersten 10 Zeichen der Datei int length; int i; char[] buffer = new char[10]; length = read.read(buffer); for (i = 0; i != length; i++) ; /* die beiden charArrays (soll und ist) mit einander vergleichen IST = c1c1c1c2c3c4c5c5c6c7 */ char[] charArray1 = buffer; char[] charArray2 = new char[] { c1, c1, c1, c2, c3, c4, c5, c5, c6, c7 }; if (Arrays.equals(charArray1, charArray2)) { /* hchstwahrscheinlich ein JP2 da es mit 0000000c6a5020200d0a respektive ....jP .. * beginnt */ } else { // TODO: Droid-Erkennung, damit Details ausgegeben werden knnen String nameOfSignature = getConfigurationService().getPathToDroidSignatureFile(); if (nameOfSignature == null) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + 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_JP2) + 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_JP2) + 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_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_INCORRECTFILE, puid)); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_INCORRECTFILE)); return false; } } else { // die Datei endet nicht mit jp2 -> Fehler getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_INCORRECTFILEENDING)); return false; } // Ende der Erkennung boolean isValid = false; // TODO: Erledigt - Initialisierung Jpylyzer -> existiert Jpylyzer? String pathToJpylyzerExe = "resources" + File.separator + "jpylyzer" + File.separator + "jpylyzer.exe"; File fJpylyzerExe = new File(pathToJpylyzerExe); if (!fJpylyzerExe.exists()) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_JPYLYZER_MISSING)); } pathToJpylyzerExe = "\"" + pathToJpylyzerExe + "\""; try { File report; Document doc = null; try { // jpylyzer-Befehl: pathToJpylyzerExe valDatei > valDatei.jpylyzer-log.xml String outputPath = directoryOfLogfile.getAbsolutePath(); String outputName = File.separator + valDatei.getName() + ".jpylyzer-log.xml"; String pathToJpylyzerReport = outputPath + outputName; File output = new File(pathToJpylyzerReport); Runtime rt = Runtime.getRuntime(); Process proc = null; try { report = output; // falls das File bereits existiert, z.B. von einem vorhergehenden Durchlauf, lschen wir // es if (report.exists()) { report.delete(); } /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl * gehts: cmd /c\"urspruenlicher Befehl\" */ String command = "cmd /c \"" + pathToJpylyzerExe + " \"" + valDatei.getAbsolutePath() + "\" > \"" + output.getAbsolutePath() + "\"\""; proc = rt.exec(command.toString().split(" ")); // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist! // Warte, bis proc fertig ist proc.waitFor(); } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_SERVICEFAILED, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } if (report.exists()) { // alles io } else { // Datei nicht angelegt... getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_NOREPORT)); return false; } // Ende Jpylyzer direkt auszulsen // TODO: Erledigt - Ergebnis auslesen BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pathToJpylyzerReport)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(bis); doc.normalize(); NodeList nodeLstI = doc.getElementsByTagName("isValidJP2"); // Node isValidJP2 enthlt im TextNode das Resultat TextNode ist ein ChildNode for (int s = 0; s < nodeLstI.getLength(); s++) { Node resultNode = nodeLstI.item(s); StringBuffer buf = new StringBuffer(); NodeList children = resultNode.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node textChild = children.item(i); if (textChild.getNodeType() != Node.TEXT_NODE) { continue; } buf.append(textChild.getNodeValue()); } String result = buf.toString(); // Das Resultat ist False oder True if (result.equalsIgnoreCase("True")) { // valid isValid = true; } else { // invalide getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_JPYLYZER_FAIL)); isValid = false; } } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } // TODO: Erledigt: Fehler Auswertung if (!isValid) { // Invalide JP2-Datei int isignatureBox = 0; int ifileTypeBox = 0; int iimageHeaderBox = 0; int ibitsPerComponentBox = 0; int icolourSpecificationBox = 0; int ipaletteBox = 0; int icomponentMappingBox = 0; int ichannelDefinitionBox = 0; int iresolutionBox = 0; int itileParts = 0; int isiz = 0; int icod = 0; int iqcd = 0; int icoc = 0; int icom = 0; int iqcc = 0; int irgn = 0; int ipoc = 0; int iplm = 0; int ippm = 0; int itlm = 0; int icrg = 0; int iplt = 0; int ippt = 0; int ixmlBox = 0; int iuuidBox = 0; int iuuidInfoBox = 0; int iunknownBox = 0; int icontainsImageHeaderBox = 0; int icontainsColourSpecificationBox = 0; int icontainsBitsPerComponentBox = 0; int ifirstJP2HeaderBoxIsImageHeaderBox = 0; int inoMoreThanOneImageHeaderBox = 0; int inoMoreThanOneBitsPerComponentBox = 0; int inoMoreThanOnePaletteBox = 0; int inoMoreThanOneComponentMappingBox = 0; int inoMoreThanOneChannelDefinitionBox = 0; int inoMoreThanOneResolutionBox = 0; int icolourSpecificationBoxesAreContiguous = 0; int ipaletteAndComponentMappingBoxesOnlyTogether = 0; int icodestreamStartsWithSOCMarker = 0; int ifoundSIZMarker = 0; int ifoundCODMarker = 0; int ifoundQCDMarker = 0; int iquantizationConsistentWithLevels = 0; int ifoundExpectedNumberOfTiles = 0; int ifoundExpectedNumberOfTileParts = 0; int ifoundEOCMarker = 0; NodeList nodeLstTest = doc.getElementsByTagName("tests"); // Node test enthlt alle invaliden tests for (int s = 0; s < nodeLstTest.getLength(); s++) { Node testNode = nodeLstTest.item(s); NodeList children = testNode.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node textChild = children.item(i); if (textChild.getNodeType() == Node.ELEMENT_NODE) { if (textChild.getNodeName().equals("signatureBox")) { isignatureBox = isignatureBox + 1; } else if (textChild.getNodeName().equals("fileTypeBox")) { ifileTypeBox = ifileTypeBox + 1; } else if (textChild.getNodeName().equals("jp2HeaderBox")) { NodeList childrenII = textChild.getChildNodes(); for (int j = 0; j < childrenII.getLength(); j++) { Node textChildII = childrenII.item(j); if (textChildII.getNodeType() == Node.ELEMENT_NODE) { if (textChildII.getNodeName().equals("imageHeaderBox")) { iimageHeaderBox = iimageHeaderBox + 1; } else if (textChildII.getNodeName().equals("bitsPerComponentBox")) { ibitsPerComponentBox = ibitsPerComponentBox + 1; } else if (textChildII.getNodeName().equals("colourSpecificationBox")) { icolourSpecificationBox = icolourSpecificationBox + 1; } else if (textChildII.getNodeName().equals("paletteBox")) { ipaletteBox = ipaletteBox + 1; } else if (textChildII.getNodeName().equals("componentMappingBox")) { icomponentMappingBox = icomponentMappingBox + 1; } else if (textChildII.getNodeName().equals("channelDefinitionBox")) { ichannelDefinitionBox = ichannelDefinitionBox + 1; } else if (textChildII.getNodeName().equals("resolutionBox")) { iresolutionBox = iresolutionBox + 1; } else if (textChildII.getNodeName().equals("containsImageHeaderBox")) { icontainsImageHeaderBox = icontainsImageHeaderBox + 1; } else if (textChildII.getNodeName() .equals("containsColourSpecificationBox")) { icontainsColourSpecificationBox = icontainsColourSpecificationBox + 1; } else if (textChildII.getNodeName() .equals("containsBitsPerComponentBox")) { icontainsBitsPerComponentBox = icontainsBitsPerComponentBox + 1; } else if (textChildII.getNodeName() .equals("firstJP2HeaderBoxIsImageHeaderBox")) { ifirstJP2HeaderBoxIsImageHeaderBox = ifirstJP2HeaderBoxIsImageHeaderBox + 1; } else if (textChildII.getNodeName() .equals("noMoreThanOneImageHeaderBox")) { inoMoreThanOneImageHeaderBox = inoMoreThanOneImageHeaderBox + 1; } else if (textChildII.getNodeName() .equals("noMoreThanOneBitsPerComponentBox")) { inoMoreThanOneBitsPerComponentBox = inoMoreThanOneBitsPerComponentBox + 1; } else if (textChildII.getNodeName().equals("noMoreThanOnePaletteBox")) { inoMoreThanOnePaletteBox = inoMoreThanOnePaletteBox + 1; } else if (textChildII.getNodeName() .equals("noMoreThanOneComponentMappingBox")) { inoMoreThanOneComponentMappingBox = inoMoreThanOneComponentMappingBox + 1; } else if (textChildII.getNodeName() .equals("noMoreThanOneChannelDefinitionBox")) { inoMoreThanOneChannelDefinitionBox = inoMoreThanOneChannelDefinitionBox + 1; } else if (textChildII.getNodeName().equals("noMoreThanOneResolutionBox")) { inoMoreThanOneResolutionBox = inoMoreThanOneResolutionBox + 1; } else if (textChildII.getNodeName() .equals("colourSpecificationBoxesAreContiguous")) { icolourSpecificationBoxesAreContiguous = icolourSpecificationBoxesAreContiguous + 1; } else if (textChildII.getNodeName() .equals("paletteAndComponentMappingBoxesOnlyTogether")) { ipaletteAndComponentMappingBoxesOnlyTogether = ipaletteAndComponentMappingBoxesOnlyTogether + 1; } } continue; } } else if (textChild.getNodeName().equals("contiguousCodestreamBox")) { NodeList childrenIII = textChild.getChildNodes(); for (int k = 0; k < childrenIII.getLength(); k++) { Node textChildIII = childrenIII.item(k); if (textChildIII.getNodeType() == Node.ELEMENT_NODE) { if (textChildIII.getNodeName().equals("tileParts")) { itileParts = itileParts + 1; } else if (textChildIII.getNodeName().equals("siz")) { isiz = isiz + 1; } else if (textChildIII.getNodeName().equals("cod")) { icod = icod + 1; } else if (textChildIII.getNodeName().equals("qcd")) { iqcd = iqcd + 1; } else if (textChildIII.getNodeName().equals("coc")) { icoc = icoc + 1; } else if (textChildIII.getNodeName().equals("com")) { icom = icom + 1; } else if (textChildIII.getNodeName().equals("qcc")) { iqcc = iqcc + 1; } else if (textChildIII.getNodeName().equals("rgn")) { irgn = irgn + 1; } else if (textChildIII.getNodeName().equals("poc")) { ipoc = ipoc + 1; } else if (textChildIII.getNodeName().equals("plm")) { iplm = iplm + 1; } else if (textChildIII.getNodeName().equals("ppm")) { ippm = ippm + 1; } else if (textChildIII.getNodeName().equals("tlm")) { itlm = itlm + 1; } else if (textChildIII.getNodeName().equals("crg")) { icrg = icrg + 1; } else if (textChildIII.getNodeName().equals("plt")) { iplt = iplt + 1; } else if (textChildIII.getNodeName().equals("ppt")) { ippt = ippt + 1; } else if (textChildIII.getNodeName() .equals("codestreamStartsWithSOCMarker")) { icodestreamStartsWithSOCMarker = icodestreamStartsWithSOCMarker + 1; } else if (textChildIII.getNodeName().equals("foundSIZMarker")) { ifoundSIZMarker = ifoundSIZMarker + 1; } else if (textChildIII.getNodeName().equals("foundCODMarker")) { ifoundCODMarker = ifoundCODMarker + 1; } else if (textChildIII.getNodeName().equals("foundQCDMarker")) { ifoundQCDMarker = ifoundQCDMarker + 1; } else if (textChildIII.getNodeName() .equals("quantizationConsistentWithLevels")) { iquantizationConsistentWithLevels = iquantizationConsistentWithLevels + 1; } else if (textChildIII.getNodeName() .equals("foundExpectedNumberOfTiles")) { ifoundExpectedNumberOfTiles = ifoundExpectedNumberOfTiles + 1; } else if (textChildIII.getNodeName() .equals("foundExpectedNumberOfTileParts")) { ifoundExpectedNumberOfTileParts = ifoundExpectedNumberOfTileParts + 1; } else if (textChildIII.getNodeName().equals("foundEOCMarker")) { ifoundEOCMarker = ifoundEOCMarker + 1; } } continue; } } else if (textChild.getNodeName().equals("xmlBox")) { ixmlBox = ixmlBox + 1; } else if (textChild.getNodeName().equals("uuidBox")) { iuuidBox = iuuidBox + 1; } else if (textChild.getNodeName().equals("uuidInfoBox")) { iuuidInfoBox = iuuidInfoBox + 1; } else if (textChild.getNodeName().equals("unknownBox")) { iunknownBox = iunknownBox + 1; } } continue; } continue; } if (isignatureBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_SIGNATURE)); } if (ifileTypeBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_A_JP2_FILETYPE)); } if (iimageHeaderBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_IMAGE)); } if (ibitsPerComponentBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_BITSPC)); } if (icolourSpecificationBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_COLOUR)); } if (ipaletteBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_PALETTE)); } if (icomponentMappingBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_MAPPING)); } if (ichannelDefinitionBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_CHANNEL)); } if (iresolutionBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_RESOLUTION)); } if (icontainsImageHeaderBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_NOIHB)); } if (icontainsColourSpecificationBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_NOCSB)); } if (icontainsBitsPerComponentBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_NBPCB)); } if (ifirstJP2HeaderBoxIsImageHeaderBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_IHBNF)); } if (inoMoreThanOneImageHeaderBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_IHBMO)); } if (inoMoreThanOneBitsPerComponentBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_OBPCMO)); } if (inoMoreThanOnePaletteBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_OPBMO)); } if (inoMoreThanOneComponentMappingBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_CMBMO)); } if (inoMoreThanOneChannelDefinitionBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_CDBMO)); } if (inoMoreThanOneResolutionBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_RBMO)); } if (icolourSpecificationBoxesAreContiguous >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_CSBNC)); } if (ipaletteAndComponentMappingBoxesOnlyTogether >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B_JP2) + getTextResourceService().getText(ERROR_XML_B_JP2_PACMB)); } if (icodestreamStartsWithSOCMarker >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_SOC)); } if (ifoundSIZMarker >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_FSIZ)); } if (ifoundCODMarker >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_FCOD)); } if (ifoundQCDMarker >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_FQCD)); } if (iquantizationConsistentWithLevels >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_PQCD)); } if (ifoundExpectedNumberOfTiles >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_NOTILES)); } if (ifoundExpectedNumberOfTileParts >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_NOTILESPART)); } if (ifoundEOCMarker >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_EOC)); } if (itileParts >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_TILEPARTS)); } if (isiz >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_SIZ)); } if (icod >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_COD)); } if (iqcd >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_QCD)); } if (icom >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_COM)); } if (icoc >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_COC)); } if (irgn >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_RGN)); } if (iqcc >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_QCC)); } if (ipoc >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_POC)); } if (iplm >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_PLM)); } if (ippm >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_PPM)); } if (itlm >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_TLM)); } if (icrg >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_CRG)); } if (iplt >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_PLT)); } if (ippt >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C_JP2) + getTextResourceService().getText(ERROR_XML_C_JP2_PPT)); } if (ixmlBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2) + getTextResourceService().getText(ERROR_XML_D_JP2_XML)); } if (iuuidBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2) + getTextResourceService().getText(ERROR_XML_D_JP2_UUID)); } if (iuuidInfoBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2) + getTextResourceService().getText(ERROR_XML_D_JP2_UUIDINFO)); } if (iunknownBox >= 1) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_D_JP2) + getTextResourceService().getText(ERROR_XML_D_JP2_UNKNOWN)); } } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_A_JP2) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); } return isValid; }
From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java
/** * Get PDF information with pdfinfo:/*from w w w.j a v a2 s . com*/ * - "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:com.att.android.arodatacollector.main.AROCollectorService.java
/** * This method creates a SU enabled shell Sets the execute permission for * tcpdump and key.db Starts the tcpdump on Completion or abnormal * termination of tcpdump Shell is destroyed * /*from ww w .j a va 2 s.c o m*/ * @throws IOException * @throws InterruptedException */ private void startTcpDump() throws IOException, InterruptedException { Log.d(TAG, "inside startTcpDump at timestamp " + System.currentTimeMillis()); Process sh = null; DataOutputStream os = null; int shExitValue = 0; try { startCalTime = Calendar.getInstance(); if (!AROCollectorUtils.isTcpDumpRunning()) { //only start tcpdump if it's not already running, to handle the case where the background //service was stopped and now restarting Log.i(TAG, "tcpdump is not running. Starting tcpdump in the shell now"); sh = Runtime.getRuntime().exec("su"); os = new DataOutputStream(sh.getOutputStream()); String Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + "\n"; os.writeBytes(Command); Command = "chmod 777 " + ARODataCollector.INTERNAL_DATA_PATH + "key.db" + "\n"; os.writeBytes(Command); //flurry timed event duration mApp.writeToFlurryAndLogEvent(flurryTimedEvent, "Flurry trace start", startCalTime.getTime().toString(), "Trace Duration", true); /*Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -w " + TRACE_FOLDERNAME + "\n";*/ Command = "." + ARODataCollector.INTERNAL_DATA_PATH + TCPDUMPFILENAME + " -i any -w " + TRACE_FOLDERNAME + "\n"; os.writeBytes(Command); Command = "exit\n"; os.writeBytes(Command); os.flush(); StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", true); new Thread(stdoutClearer).start(); StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true); new Thread(stderrClearer).start(); shExitValue = sh.waitFor(); if (DEBUG) { Log.i(TAG, "tcpdump waitFor returns exit value: " + shExitValue + " at " + System.currentTimeMillis()); } } else { Log.i(TAG, "timestamp " + System.currentTimeMillis() + ": tcpdump is already running"); } //We will continue and block the thread untill we see valid instance of tcpdump running in shell //waitFor() does not seems to be working on ICS firmware while (AROCollectorUtils.isTcpDumpRunning()) { continue; } if (DEBUG) { Log.d(TAG, "tcpdump process exit value: " + shExitValue); Log.i(TAG, "Coming out of startTcpDump at " + System.currentTimeMillis()); logTcpdumpPid(); } // Stopping the Video capture right after tcpdump coming out of // shell new Thread(new Runnable() { @Override public void run() { if (mVideoRecording && mApp.getAROVideoCaptureRunningFlag()) { stopScreenVideoCapture(); stopDmesg(); } } }).start(); final Calendar endCalTime = Calendar.getInstance(); FlurryAgent.endTimedEvent("Trace Duration"); mApp.writeToFlurry(flurryTimedEvent, "Flurry trace end", endCalTime.getTime().toString(), "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING); mApp.writeToFlurry(flurryTimedEvent, "calculated Flurry trace duration", getUpTime(endCalTime), "flurryTimedEvent", AROCollectorUtils.NOT_APPLICABLE, AROCollectorUtils.EMPTY_STRING); logFlurryEvents(); DataCollectorTraceStop(); } finally { try { mApp.setTcpDumpStartFlag(false); if (os != null) { os.close(); } if (sh != null) { sh.destroy(); } } catch (Exception e) { Log.e(TAG, "exception in startTcpDump DataOutputStream close", e); } } }
From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
/** * @param restoreFilePath/*from w ww .ja va2s . c o m*/ * @param mysqlLoc * @param databaseName * @return */ public boolean doRestore(final String restoreFilePath, final String mysqlLoc, final String databaseName, final String userName, final String password) { FileInputStream input = null; try { Vector<String> args = new Vector<String>(); args.add(mysqlLoc); args.add("--user=" + userName); args.add("--password=" + password); args.add(databaseName); Process process = Runtime.getRuntime().exec(args.toArray(new String[0])); //Thread.sleep(100); OutputStream out = process.getOutputStream(); // wait as long it takes till the other process has prompted. try { File inFile = new File(restoreFilePath); input = new FileInputStream(inFile); try { //long totalBytes = 0; byte[] bytes = new byte[8192 * 4]; // 32K do { int numBytes = input.read(bytes, 0, bytes.length); //totalBytes += numBytes; //System.out.println(numBytes+" / "+totalBytes); if (numBytes > 0) { out.write(bytes, 0, numBytes); } else { break; } } while (true); } finally { input.close(); } } catch (IOException ex) { ex.printStackTrace(); errorMsg = ex.toString(); return false; } catch (Exception ex) { ex.printStackTrace(); return false; } finally { out.flush(); out.close(); } BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = in.readLine()) != null) { //System.err.println(line); } in = new BufferedReader(new InputStreamReader(process.getErrorStream())); StringBuilder sb = new StringBuilder(); while ((line = in.readLine()) != null) { if (line.startsWith("ERR")) { sb.append(line); sb.append("\n"); } } errorMsg = sb.toString(); //System.out.println("errorMsg: ["+errorMsg+"]"); return errorMsg == null || errorMsg.isEmpty(); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); } return false; }
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 ww .j av a 2s .com*/ */ 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; }