List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:org.ala.spatial.web.services.GDMWSController.java
private int runGDM(int level, String params) { Runtime runtime = Runtime.getRuntime(); Process proc; InputStreamReader isre = null, isr = null; BufferedReader bre = null, br = null; int exitValue = -1; try {//from ww w .ja va 2 s. c o m String command = AlaspatialProperties.getAnalysisGdmCmd() + " -g" + level + " " + params; System.out.println("Running gdm: " + command); // return 111; proc = runtime.exec(command); isre = new InputStreamReader(proc.getErrorStream()); bre = new BufferedReader(isre); isr = new InputStreamReader(proc.getInputStream()); br = new BufferedReader(isr); String line; while ((line = bre.readLine()) != null) { System.out.println(line); } while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = proc.waitFor(); // any error??? exitValue = exitVal; } catch (Exception e) { System.out.println("Error executing GDM: "); e.printStackTrace(System.out); } finally { try { isre.close(); bre.close(); isr.close(); br.close(); } catch (IOException ioe) { System.out.println("Error closing output and error streams"); } } return exitValue; }
From source file:hu.sztaki.lpds.pgportal.portlets.asm.ClientError.java
private ArrayList<String> getOutputfiles(String resultzipPath, String outputfileMask) { String temp_output = resultzipPath; String temp_filename = "wf_out.zip"; String temp_dir = "wf_dir"; String output_filename = "*.pdbqt"; //String output_filename="*.*"; try {//from www. ja va2s . c o m runSystemcmd(); Process process; process = Runtime.getRuntime().exec("rm -rf /tmp/" + temp_dir); process.waitFor(); process = Runtime.getRuntime().exec("mkdir -p /tmp/" + temp_dir); process.waitFor(); process = Runtime.getRuntime().exec("cp " + temp_output + " /tmp/" + temp_filename); process.waitFor(); process = Runtime.getRuntime().exec("unzip -o /tmp/" + temp_filename + " -d /tmp/" + temp_dir); process.waitFor(); // get the output_filename location // MODIFIED TO SIMULATE MULTIPLE OUTPUT Process pr = Runtime.getRuntime() .exec(new String[] { "find", "/tmp/" + temp_dir, "-name", output_filename }); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line = null; String string_error = ""; ArrayList<String> resultPaths = new ArrayList<String>(1); while ((line = input.readLine()) != null) { resultPaths.add(line); } string_error = error.readLine(); // MOVE RESULTS to PDBQT dir String pdbqtStorePath = "../webapps/" + request.getContextPath() + "/script/jmol/model/result/"; ArrayList<String> pdbqtList = new ArrayList<String>(resultPaths.size()); for (String result : resultPaths) { UUID idOne = UUID.randomUUID(); File resultx = new File(result); String pdbqtNewName = idOne + "-" + resultx.getName() + ".pdbqt"; Runtime.getRuntime().exec("cp -f " + result + " " + pdbqtStorePath + pdbqtNewName); pdbqtList.add("" + pdbqtNewName); } } catch (Exception ex) { ; } }
From source file:com.twinsoft.convertigo.engine.Engine.java
public static synchronized void start() throws EngineException { if (Engine.theApp == null) { System.out.println("Starting Convertigo Enterprise Mobility Server"); // If the engine has been stopped by the admin, we must reload // properties EnginePropertiesManager.loadProperties(); boolean bProjectsDataCompatibilityMode = Boolean.parseBoolean( EnginePropertiesManager.getProperty(PropertyName.PROJECTS_DATA_COMPATIBILITY_MODE)); if (bProjectsDataCompatibilityMode) { System.out.println("Projects data compatibility mode required"); try { Engine.PROJECTS_PATH = new File(Engine.WEBAPP_PATH + "/projects").getCanonicalPath(); File projectsDir = new File(Engine.PROJECTS_PATH); projectsDir.mkdir();/* w w w . j a va 2 s. c o m*/ } catch (IOException e) { throw new EngineException("Unable to update projects path for compatibility mode", e); } } isStarted = false; isStartFailed = false; RequestableObject.nbCurrentWorkerThreads = 0; Engine.startStopDate = System.currentTimeMillis(); System.out.println("Creating/updating loggers"); String logFile = EnginePropertiesManager.getProperty(PropertyName.LOG4J_APPENDER_CEMSAPPENDER_FILE); System.out.println("Log file: " + logFile); // Main loggers Engine.logConvertigo = Logger.getLogger("cems"); Engine.logEngine = Logger.getLogger("cems.Engine"); Engine.logAdmin = Logger.getLogger("cems.Admin"); Engine.logBeans = Logger.getLogger("cems.Beans"); Engine.logBillers = Logger.getLogger("cems.Billers"); Engine.logEmulators = Logger.getLogger("cems.Emulators"); Engine.logContext = Logger.getLogger("cems.Context"); Engine.logUser = Logger.getLogger("cems.Context.User"); Engine.logUsageMonitor = Logger.getLogger("cems.UsageMonitor"); Engine.logStatistics = Logger.getLogger("cems.Statistics"); Engine.logScheduler = Logger.getLogger("cems.Scheduler"); Engine.logSiteClipper = Logger.getLogger("cems.SiteClipper"); /** #3437 : Disabled ExternalBrowser feature because it's not terminated Engine.logExternalBrowser = Logger.getLogger("cems.ExternalBrowser"); */ Engine.logAudit = Logger.getLogger("cems.Context.Audit"); // Managers Engine.logContextManager = Logger.getLogger("cems.ContextManager"); Engine.logCacheManager = Logger.getLogger("cems.CacheManager"); Engine.logTracePlayerManager = Logger.getLogger("cems.TracePlayerManager"); Engine.logJobManager = Logger.getLogger("cems.JobManager"); Engine.logCertificateManager = Logger.getLogger("cems.CertificateManager"); Engine.logDatabaseObjectManager = Logger.getLogger("cems.DatabaseObjectManager"); Engine.logProxyManager = Logger.getLogger("cems.ProxyManager"); Engine.logDevices = Logger.getLogger("cems.Devices"); Engine.logCouchDbManager = Logger.getLogger("cems.CouchDbManager"); Engine.logSecurityTokenManager = Logger.getLogger("cems.SecurityTokenManager"); // Logger for compatibility issues Engine.log = new LogWrapper(Engine.logConvertigo); LogWrapper.initWrapper(Engine.logEmulators); try { Engine.logEngine.info("==========================================================="); Engine.logEngine.info("Web app home: " + Engine.WEBAPP_PATH); Engine.logEngine.info("User workspace: " + Engine.USER_WORKSPACE_PATH); Engine.logEngine.info("Configuration path: " + Engine.CONFIGURATION_PATH); Engine.logEngine.info("Projects path: " + Engine.PROJECTS_PATH); if (bProjectsDataCompatibilityMode) { Engine.logEngine.warn("Projects data compatibility mode required"); } Engine.logEngine.info("Log: " + Engine.LOG_PATH); if (cloud_customer_name != null) { Engine.logEngine.info("Cloud customer: " + cloud_customer_name); } // Check environment and native dependencies if (!isStudioMode()) { StartupDiagnostics.run(); } // Initializing the engine Engine.theApp = new Engine(); CachedIntrospector.prefetchDatabaseObjectsAsync(); try { Engine.theApp.usageMonitor = new UsageMonitor(); Engine.theApp.usageMonitor.init(); Thread vulture = new Thread(Engine.theApp.usageMonitor); vulture.setName("UsageMonitor"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the usage monitor.", e); } Engine.theApp.eventManager = new EventManager(); Engine.theApp.eventManager.init(); Engine.theApp.databaseObjectsManager = new DatabaseObjectsManager(); Engine.theApp.databaseObjectsManager.init(); Engine.theApp.sqlConnectionManager = new JdbcConnectionManager(); Engine.theApp.sqlConnectionManager.init(); Engine.theApp.filePropertyManager = new FilePropertyManager(); Engine.theApp.filePropertyManager.init(); try { Engine.theApp.proxyManager = new ProxyManager(); Engine.theApp.proxyManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the proxy manager.", e); } try { Engine.theApp.billingManager = new BillingManager(); Engine.theApp.billingManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the billing manager.", e); } // Initialization of the trace player try { Engine.theApp.tracePlayerManager = new TracePlayerManager(); Engine.theApp.tracePlayerManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the trace player.", e); } try { Engine.theApp.minificationManager = new MinificationManager(); Engine.theApp.minificationManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the minification manager.", e); } try { Engine.theApp.couchDbManager = new CouchDbManager(); Engine.theApp.couchDbManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the couchDbProxy manager.", e); } try { Engine.theApp.pluginsManager = new PluginsManager(); Engine.theApp.pluginsManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the plugins manager.", e); } try { Engine.theApp.restApiManager = RestApiManager.getInstance(); Engine.theApp.restApiManager.init(); } catch (Exception e) { Engine.logEngine.error("Unable to run the rest api manager.", e); } Engine.logEngine.info("Current working directory is '" + System.getProperty("user.dir") + "'."); // Creating the Carioca Authentication objects Engine.logEngine.debug("Creating the Carioca Authentication objects"); String cariocaUserName = EnginePropertiesManager .getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME); String cariocaPassword = EnginePropertiesManager .getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD); Engine.theApp.authentications = new HashMap<String, Authentication>(); // Initialization of the default TAS properties try { KeyManager.log = new LogWrapper(Engine.logEngine); Authentication auth = Engine.theApp.getAuthenticationObject("", null); auth.login(cariocaUserName, cariocaPassword); } catch (Exception e) { Engine.logEngine.error("The authentication to Carioca has failed (user name: \"" + cariocaUserName + "\", user password: \"" + cariocaPassword + "\").", e); } // TODO : retrieve SOA flag from KeyManager isSOA = true; // Creation of the session manager Engine.theApp.sessionManager = new SessionManager(); Engine.theApp.sessionManager.setLog(new LogWrapper(Engine.logEngine)); Engine.theApp.sessionManager.setProductCode(SessionManager.CONVERTIGO); String s = EnginePropertiesManager.getProperty(PropertyName.CONNECTORS_MONITORING); Engine.theApp.setMonitored(s.equalsIgnoreCase("true")); // Create Projects directory if needed File projectsDirFile = new File(Engine.PROJECTS_PATH); try { if (!projectsDirFile.exists()) projectsDirFile.mkdirs(); } catch (Exception e) { Engine.logEngine.error("An error occured while creating projects directory.", e); } // Starts projects migration process MigrationManager.performProjectsMigration(); // Security providers registration try { File dir = new File(Engine.CERTIFICATES_PATH); String[] files = dir.list(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith((".pkcs11")); } }); if (files != null && files.length > 0) { Engine.logEngine.info("Registering security providers..."); try { Class<?> sunPKCS11Class = Class.forName("sun.security.pkcs11.SunPKCS11"); String file; for (int i = 0; i < files.length; i++) { file = Engine.CERTIFICATES_PATH + "/" + files[i]; try { Constructor<?> constructor = sunPKCS11Class .getConstructor(new Class[] { String.class }); Provider provider = (Provider) constructor.newInstance(new Object[] { file }); Security.addProvider(provider); Engine.logEngine.info("Provider '" + provider.getName() + "' has been successfully registered."); } catch (Exception e) { Engine.logEngine.error("Unable to register security provider from file: " + file + " . Please check that the implementation library is in the Java lib path."); } } } catch (ClassNotFoundException e) { Engine.logEngine.error( "Unable to find sun.security.pkcs11.SunPKCS11 class! PKCS#11 authentication won't be available. You must use JVM 1.5 or higher in order to use PKCS#11 authentication."); } } Provider[] providers = Security.getProviders(); String sProviders = ""; for (int i = 0; i < providers.length; i++) { sProviders += providers[i].getName() + ", "; } Engine.logEngine.debug("Registered providers: " + sProviders); } catch (Exception e) { Engine.logEngine.error("Unable to register security providers.", e); } // Launch the cache manager try { String cacheManagerClassName = EnginePropertiesManager .getProperty(PropertyName.CACHE_MANAGER_CLASS); Engine.logEngine.debug("Cache manager class: " + cacheManagerClassName); Engine.theApp.cacheManager = (CacheManager) Class.forName(cacheManagerClassName).newInstance(); Engine.theApp.cacheManager.init(); Thread vulture = new Thread(Engine.theApp.cacheManager); Engine.theApp.cacheManager.executionThread = vulture; vulture.setName("CacheManager"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.logEngine.error("Unable to launch the cache manager.", e); } // Launch the thread manager try { Engine.theApp.threadManager = new ThreadManager(); Engine.theApp.threadManager.init(); Thread vulture = new Thread(Engine.theApp.threadManager); Engine.theApp.threadManager.executionThread = vulture; vulture.setName("ThreadManager"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.theApp.threadManager = null; Engine.logEngine.error("Unable to launch the thread manager.", e); } // Launch the context manager try { Engine.theApp.contextManager = new ContextManager(); Engine.theApp.contextManager.init(); Thread vulture = new Thread(Engine.theApp.contextManager); Engine.theApp.contextManager.executionThread = vulture; vulture.setName("ContextManager"); vulture.setDaemon(true); vulture.start(); } catch (Exception e) { Engine.theApp.contextManager = null; Engine.logEngine.error("Unable to launch the context manager.", e); } // Launch the security token manager Engine.theApp.securityTokenManager = new SecurityTokenManager(); Engine.theApp.securityTokenManager.init(); // Initialize the HttpClient try { Engine.logEngine.debug("HttpClient initializing..."); Engine.theApp.httpClient = HttpUtils.makeHttpClient3(true); Engine.theApp.httpClient4 = HttpUtils.makeHttpClient4(true); Engine.logEngine.debug("HttpClient initialized!"); } catch (Exception e) { Engine.logEngine.error("Unable to initialize the HttpClient.", e); } // Initialization of the schedule manager Engine.theApp.schedulerManager = new SchedulerManager(true); // Initialization of the RSA manager Engine.theApp.rsaManager = new RsaManager(); Engine.theApp.rsaManager.init(); // Initialization of the External Browser manager /** #3437 : Disabled ExternalBrowser feature because it's not terminated Engine.theApp.externalBrowserManager = new ExternalBrowserManager(); Engine.theApp.externalBrowserManager.init(); */ // Initialization of the Schema manager Engine.theApp.schemaManager = new SchemaManager(); Engine.theApp.schemaManager.init(); // XUL initialization String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath"); if (xulrunner_url == null || xulrunner_url.equals("")) { xulrunner_url = EnginePropertiesManager.getProperty(PropertyName.XULRUNNER_URL); } File f = new File(xulrunner_url); if (f.exists()) { xulrunner_url = f.getAbsolutePath(); Engine.logEngine .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url); System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url); } else { Engine.logEngine.error("Error in initMozillaSWT: " + xulrunner_url + " doesn't exist, fix it with xulrunner.url"); } if (Engine.isEngineMode() && Engine.isLinux() && "true".equals(EnginePropertiesManager.getProperty(PropertyName.LINUX_LAUNCH_XVNC))) { Engine.logEngine .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url); final String display = System.getenv("DISPLAY"); if (display != null) { try { String port = System.getProperty("xvnc.port"); if (port == null) { port = "" + (Integer.parseInt(display.replaceAll(".*:(\\d*)", "$1")) + 5900); System.setProperty("xvnc.port", port); } Engine.logEngine.debug("Xvnc should listen on " + port + " port"); } catch (Exception e) { } try { File vncDir = new File(Engine.WEBAPP_PATH + "/WEB-INF/xvnc"); File Xvnc = new File(vncDir, "/Xvnc"); File fonts = new File(vncDir, "/fonts"); File wm = new File(vncDir, "/matchbox-window-manager"); if (vncDir.exists() && Xvnc.exists() && fonts.exists() && wm.exists()) { for (File file : GenericUtils.<File>asList(Xvnc, wm)) { new ProcessBuilder("/bin/chmod", "u+x", file.getAbsolutePath()).start() .waitFor(); } String depth = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_DEPTH); String geometry = EnginePropertiesManager .getProperty(PropertyName.LINUX_XVNC_GEOMETRY); Engine.logEngine .debug("Xvnc will use depth " + depth + " and geometry " + geometry); Process pr_xvnc = new ProcessBuilder(Xvnc.getAbsolutePath(), display, "-fp", fonts.getAbsolutePath(), "-depth", depth, "-geometry", geometry).start(); Thread.sleep(500); try { int exit = pr_xvnc.exitValue(); InputStream err = pr_xvnc.getErrorStream(); byte[] buf = new byte[err.available()]; err.read(buf); Engine.logEngine.debug("Xvnc failed to run with exit code " + exit + " and this error : <<" + new String(buf, "UTF-8") + ">>"); } catch (Exception e) { new ProcessBuilder(wm.getAbsolutePath()).start(); Engine.logEngine.debug("Xvnc successfully started !"); } } else { Engine.logEngine.info( vncDir.getAbsolutePath() + " not found or incomplet, cannot start Xvnc"); } } catch (Exception e) { Engine.logEngine.info("failed to launch Xvnc (maybe already launched", e); } } else Engine.logEngine .warn("Trying to start Xvnc on Linux without DISPLAY environment variable !"); } // SAP provider registration try { SapJcoDestinationDataProvider.init(); Engine.logEngine.debug("SAP destination provider successfully registered"); } catch (Throwable e) { Engine.logEngine.error("Error while registering SAP destination provider", e); } isStarted = true; Engine.logEngine.info("Convertigo engine started"); } catch (Throwable e) { isStartFailed = true; Engine.logEngine.error("Unable to successfully start the engine.", e); } } else { Engine.logEngine.info("Convertigo engine already started"); } }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
private static void verifyMessage(File messageFile, X509Certificate rootCertificate, File outputFile) throws IOException { OpenSSLWrapper wrapper = new OpenSSLWrapper(); wrapper.setCertificateAuthorities(rootCertificate); Process p = wrapper.verify(messageFile); InputStream result = p.getInputStream(); FileOutputStream output = new FileOutputStream(outputFile); IOUtils.copy(result, output);/*from w w w . j a v a2 s . co m*/ output.close(); String error = IOUtils.toString(p.getErrorStream(), "US-ASCII"); assertTrue("Error message: " + error, error.startsWith("Verification successful")); }
From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java
private static void decryptMessage(File messageFile, PrivateKey privateKey, File outputFile) throws IOException { OpenSSLWrapper wrapper = new OpenSSLWrapper(); wrapper.setPrivateKey(privateKey);//from www . j a v a2 s.c o m Process p = wrapper.decrypt(messageFile); InputStream result = p.getInputStream(); FileOutputStream output = new FileOutputStream(outputFile); IOUtils.copy(result, output); output.close(); String error = IOUtils.toString(p.getErrorStream(), "US-ASCII"); assertEquals("", error.trim()); }
From source file:hu.sztaki.lpds.pgportal.portlets.asm.ClientError.java
@SuppressWarnings("empty-statement") public void doCheckStatus(ActionRequest request, ActionResponse response) throws PortletException, MalformedURLException, IOException { try {//from w ww . ja v a 2 s . c o m String selected_job = "collector.sh"; String selected_port = "0"; String userId = request.getRemoteUser(); String status_code = ""; String status = ""; String jobid = "wtf"; String output_port = "0"; String status_str = ""; try { status_str = asm_service.getWorkflowStatus(userId, selected_wf).getStatus(); } catch (Exception ex) { ; } if (status_str.equals("FINISHED")) { String temp_output = asm_service.getFiletoPortalServer(userId, selected_wf, selected_job, output_port); // EXTRACT THE OUTPUTVALUE FROM RESULTZIP FILE String temp_filename = "wf_out.zip"; String temp_dir = "wf_dir"; String output_filename = "*.pdbqt"; //String output_filename="*.*"; Process process; process = Runtime.getRuntime().exec("rm -rf /tmp/" + temp_dir); process.waitFor(); process = Runtime.getRuntime().exec("mkdir -p /tmp/" + temp_dir); process.waitFor(); process = Runtime.getRuntime().exec("cp " + temp_output + " /tmp/" + temp_filename); process.waitFor(); process = Runtime.getRuntime().exec("unzip -o /tmp/" + temp_filename + " -d /tmp/" + temp_dir); process.waitFor(); // get the output_filename location // MODIFIED TO SIMULATE MULTIPLE OUTPUT Process pr = Runtime.getRuntime() .exec(new String[] { "find", "/tmp/" + temp_dir, "-name", output_filename }); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line = null; String string_error = ""; ArrayList<String> resultPaths = new ArrayList<String>(1); while ((line = input.readLine()) != null) { resultPaths.add(line); } string_error = error.readLine(); // MOVE RESULTS to PDBQT dir String pdbqtStorePath = "../webapps/" + request.getContextPath() + "/script/jmol/model/result/"; ArrayList<String> pdbqtList = new ArrayList<String>(resultPaths.size()); for (String result : resultPaths) { UUID idOne = UUID.randomUUID(); File resultx = new File(result); String pdbqtNewName = idOne + "-" + resultx.getName() + ".pdbqt"; Runtime.getRuntime().exec("cp -f " + result + " " + pdbqtStorePath + pdbqtNewName); pdbqtList.add("" + pdbqtNewName); } /* String result =temp_output; UUID idOne = UUID.randomUUID(); File resultx=new File(result); String pdbqtNewName=idOne +"-"+resultx.getName()+".pdbqt"; Runtime.getRuntime().exec("cp -f "+result+" "+pdbqtStorePath+pdbqtNewName); pdbqtList.add(""+pdbqtNewName); */ throwError("found results: " + resultPaths.size() + " e:" + string_error, 10); request.setAttribute("resultpdbqts", pdbqtList); } else { request.setAttribute("resultpdbqts", ""); } // } catch (Exception ex) { throwError(ex.getMessage(), 10); } request.setAttribute("layerMoleculaVisualizeEnableVar", "1"); request.setAttribute("nextJSP", DISPLAY_PAGE); String nextJSP = DISPLAY_PAGE; PortletRequestDispatcher dispatcher; dispatcher = getPortletContext().getRequestDispatcher(nextJSP); dispatcher.include(request, response); }
From source file:vmTools.java
private String runCommand(String command) { String result = ""; String error = ""; String s = null;/*w ww. j a va2 s .c o m*/ try { Process p = Runtime.getRuntime().exec(command); //p.waitFor(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { result = result + s; } // read any errors from the attempted command while ((s = stdError.readLine()) != null) { error = error + s; } if (error != "") { return error; } else { return result; } } catch (IOException e) { return "unknown error"; } }
From source file:dk.clarin.tools.create.java
public boolean PDFhasNoFonts(File pdfFile) { String lastline = ""; String lasterrline = ""; try {//from w w w . j ava2s . co m String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; String command = "/usr/bin/pdffonts " + pdfFile.getAbsolutePath(); final Process process = Runtime.getRuntime().exec(command); stdin = process.getOutputStream(); stderr = process.getErrorStream(); stdout = process.getInputStream(); stdin.close(); // clean up if any output in stdout BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout)); while ((line = brCleanUp.readLine()) != null) { lastline = line; } brCleanUp.close(); // clean up if any output in stderr brCleanUp = new BufferedReader(new InputStreamReader(stderr)); while ((line = brCleanUp.readLine()) != null) { lasterrline = line; } brCleanUp.close(); } catch (Exception e) { logger.error("cannot analyse: " + pdfFile.getName() + ", error is: " + e.getMessage()); } logger.debug("lasterrline [" + lasterrline + "] lastline [" + lastline + "]"); return lasterrline.equals("") && (lastline.endsWith("---------")); }
From source file:com.taobao.adfs.util.Utilities.java
public static String runCommand(String command, Integer expectedExitCode, String extraPath, String libPath, boolean destory) throws IOException { BufferedReader stdOutputReader = null; StringBuilder output = new StringBuilder(); Process process = runCommand(command, extraPath, libPath); ;// w w w.j a va 2s . com try { stdOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = stdOutputReader.readLine()) != null) { output.append(line).append('\n'); } if (output.length() > 0) output.deleteCharAt(output.length() - 1); if (expectedExitCode != null && process.waitFor() != expectedExitCode) throw new IOException( "exit code=" + process.exitValue() + ", expected exit code=" + expectedExitCode); } catch (Throwable t) { destory = true; throw new IOException("fail to exceute " + command + ", output=" + output + (extraPath == null ? "" : ", extraPath=" + extraPath) + (libPath == null ? "" : ", libPath=" + libPath), t); } finally { if (stdOutputReader != null) stdOutputReader.close(); process.getOutputStream().close(); process.getInputStream().close(); process.getErrorStream().close(); if (destory) process.destroy(); } return output.toString(); }
From source file:mrcg.MRCGInstance.java
private void createSQL() throws Exception { String databaseType = getString("database.type"); DBScripter dbScripter = DB_SCRIPTER.get(databaseType); String script = dbScripter.buildScript(getString("database.name"), types); File file = new File(projectPath + "database/" + databaseType + "/01-create-generated.sql"); boolean changed = content(file, script, true); if (isSkipDatabaseEnabled()) return;/* w w w . java 2 s . co m*/ if (isDesignAlwaysModeEnabled() || (changed && isDesignModeEnabled())) { System.out.print("Running SQL Script..."); Process process = Runtime.getRuntime().exec("bash runall.sh", null, new File(projectPath + "database/" + databaseType)); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); System.out.println(process.waitFor()); while (in.ready() || err.ready()) { if (in.ready()) { System.out.println(in.readLine()); } else if (err.ready()) { System.err.println(err.readLine()); } } } }