List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptBSearchModuleImpl.java
@Override public boolean validate(File siardDatei, File outFileSearch, String searchString) throws ExcerptBSearchException { boolean isValid = true; File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe"); String pathToGrepExe = fGrepExe.getAbsolutePath(); if (!fGrepExe.exists()) { // grep.exe existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath())); return false; } else {//from w ww. j av a 2 s.c o m File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll"); if (!fMsys10dll.exists()) { // msys-1.0.dll existiert nicht --> Abbruch getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath())); return false; } } File tempOutFile = new File(outFileSearch.getAbsolutePath() + ".tmp"); String content = ""; String contentAll = ""; // Records aus table herausholen try { if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim * entsprechenden Modul die property anzugeben: <property name="configurationService" * ref="configurationService" /> */ String name = getConfigurationService().getSearchtableName(); String folder = getConfigurationService().getSearchtableFolder(); File fSearchtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator + "schema0" + File.separator + folder + File.separator + folder + ".xml"); searchString = searchString.replaceAll("\\.", "\\.*"); try { // grep -E "REGEX-Suchbegriff" table13.xml >> output.txt String command = "cmd /c \"" + pathToGrepExe + " -E \"" + searchString + "\" " + fSearchtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\""; /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl * gehts: cmd /c\"urspruenlicher Befehl\" */ // System.out.println( command ); Process proc = null; Runtime rt = null; getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name)); try { 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_B) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } finally { if (proc != null) { closeQuietly(proc.getOutputStream()); closeQuietly(proc.getInputStream()); closeQuietly(proc.getErrorStream()); } } Scanner scanner = new Scanner(tempOutFile); contentAll = ""; content = ""; contentAll = scanner.useDelimiter("\\Z").next(); scanner.close(); content = contentAll; /* im contentAll ist jetzt der Gesamtstring, dieser soll anschliessend nur noch aus den 4 * Such-Zellen und den weiteren 4 ResultateZellen bestehen -> content */ String nr1 = getConfigurationService().getcellNumber1(); String nr2 = getConfigurationService().getcellNumber2(); String nr3 = getConfigurationService().getcellNumber3(); String nr4 = getConfigurationService().getcellNumber4(); String nr5 = getConfigurationService().getcellNumberResult1(); String nr6 = getConfigurationService().getcellNumberResult2(); String nr7 = getConfigurationService().getcellNumberResult3(); String nr8 = getConfigurationService().getcellNumberResult4(); String cellLoop = ""; // Loop von 1, 2, 3 ... bis 499999. for (int i = 1; i < 500000; i++) { cellLoop = ""; cellLoop = "c" + i; if (cellLoop.equals(nr1) || cellLoop.equals(nr2) || cellLoop.equals(nr3) || cellLoop.equals(nr4) || cellLoop.equals(nr5) || cellLoop.equals(nr6) || cellLoop.equals(nr7) || cellLoop.equals(nr8)) { // wird behalten } else { String deletString = "<c" + i + ">" + ".*" + "</c" + i + ">"; content = content.replaceAll(deletString, ""); } } getMessageService() .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content)); getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name)); if (tempOutFile.exists()) { Util.deleteDir(tempOutFile); } contentAll = ""; content = ""; // Ende Grep } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } } catch (Exception e) { getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_B) + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage())); return false; } return isValid; }
From source file:eu.interedition.collatex.tools.CollationServer.java
public void service(Request request, Response response) throws Exception { final Deque<String> path = path(request); if (path.isEmpty() || !"collate".equals(path.pop())) { response.sendError(404);// ww w. j a v a 2 s . c om return; } final SimpleCollation collation = JsonProcessor.read(request.getInputStream()); if (maxCollationSize > 0) { for (SimpleWitness witness : collation.getWitnesses()) { final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken) .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum(); if (witnessLength > maxCollationSize) { response.sendError(413, "Request Entity Too Large"); return; } } } response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>()); collationThreads.submit(() -> { try { final VariantGraph graph = new VariantGraph(); collation.collate(graph); // CORS support response.setHeader("Access-Control-Allow-Origin", Optional.ofNullable(request.getHeader("Origin")).orElse("*")); response.setHeader("Access-Control-Allow-Methods", Optional.ofNullable(request.getHeader("Access-Control-Request-Method")) .orElse("GET, POST, HEAD, OPTIONS")); response.setHeader("Access-Control-Allow-Headers", Optional.ofNullable(request.getHeader("Access-Control-Request-Headers")) .orElse("Content-Type, Accept, X-Requested-With")); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Credentials", "true"); final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse(""); if (clientAccepts.contains("text/plain")) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); try (final Writer out = response.getWriter()) { new SimpleVariantGraphSerializer(graph).toDot(out); } response.resume(); } else if (clientAccepts.contains("application/tei+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/tei+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toTEI(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("application/graphml+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/graphml+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toGraphML(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("image/svg+xml")) { if (dotPath == null) { response.sendError(204); response.resume(); } else { final StringWriter dot = new StringWriter(); new SimpleVariantGraphSerializer(graph).toDot(dot); final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph", "-Tsvg").start(); final StringWriter errors = new StringWriter(); CompletableFuture.allOf(CompletableFuture.runAsync(() -> { final char[] buf = new char[8192]; try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) { int len; while ((len = errorStream.read(buf)) >= 0) { errors.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(), "UTF-8")) { dotProcStream.write(dot.toString()); } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { response.setContentType("image/svg+xml"); final byte[] buf = new byte[8192]; try (final InputStream in = dotProc.getInputStream(); final OutputStream out = response.getOutputStream()) { int len; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try { if (!dotProc.waitFor(60, TimeUnit.SECONDS)) { throw new CompletionException(new RuntimeException( "dot processing took longer than 60 seconds, process was timed out.")); } if (dotProc.exitValue() != 0) { throw new CompletionException(new IllegalStateException(errors.toString())); } } catch (InterruptedException e) { throw new CompletionException(e); } }, processThreads)).exceptionally(t -> { t.printStackTrace(); return null; }).thenRunAsync(response::resume, processThreads); } } else { response.setContentType("application/json"); try (final OutputStream responseStream = response.getOutputStream()) { JsonProcessor.write(graph, responseStream); } response.resume(); } } catch (IOException e) { // FIXME: ignored } }); }
From source file:de.flyingsnail.ipv6droid.android.VpnThread.java
/** * Try to fix the problem detected by checkRouting. This requires rooted devices :-( */// w w w . j a v a2 s.c o m private void fixRouting() { try { Process routeAdder = Runtime.getRuntime().exec( new String[] { "/system/bin/su", "-c", "/system/bin/ip -f inet6 route add default dev tun0" }); BufferedReader reader = new BufferedReader(new InputStreamReader(routeAdder.getErrorStream())); String errors = reader.readLine(); try { routeAdder.waitFor(); } catch (InterruptedException e) { // we got interrupted, so we kill our process routeAdder.destroy(); } if (errors != null) { Log.e(TAG, "Command to set default route created error message: " + errors); } } catch (IOException e) { Log.d(TAG, "Failed to fix routing", e); } }
From source file:com.gnuroot.debian.GNURootMain.java
private void exec(String command, boolean setError) { Runtime runtime = Runtime.getRuntime(); Process process; try {/*from w ww. j av a 2 s . c om*/ process = runtime.exec(command); try { String str; process.waitFor(); BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((str = stdError.readLine()) != null) { Log.e("Exec", str); if (setError) errOcc = true; } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); } catch (InterruptedException e) { if (setError) errOcc = true; } } catch (IOException e1) { errOcc = true; } }
From source file:com.legstar.protobuf.cobol.ProtoCobol.java
/** * From Google's org.waveprotocol.pst.PstFileDescriptor. * <p/>// w ww .j a v a2 s .c o m * Call the protoc compiler, waiting a limited amount of time for * completion. * * @param protoFile the protocol buffer file (proto file) * @param protoPath additional imported protocol buffer files will be picked * up from this location * @param javaOut where, on the file system, the generated java class will * be produced * @param timeout how long to wait before canceling (in seconds) * @return the generated java source file * @throws ProtoCobolException if invokation fails */ public File runProtoJava(File protoFile, File protoPath, File javaOut, int timeout) throws ProtoCobolException { try { String[] protocCommand = new String[] { "protoc", protoFile.getAbsolutePath(), "-I" + protoPath.getAbsolutePath(), "--java_out", javaOut.getAbsolutePath() }; logger.info("About to execute: " + StringUtils.join(protocCommand, ' ')); Process protoc = Runtime.getRuntime().exec(protocCommand); killProcessAfter(timeout, TimeUnit.SECONDS, protoc); int exitCode = protoc.waitFor(); if (exitCode != 0) { throw new ProtoCobolException("Command failed. " + IOUtils.toString(protoc.getErrorStream())); } logger.info("Command succeeded. " + IOUtils.toString(protoc.getInputStream())); return locateJavaSourceFile(javaOut); } catch (IOException e) { throw new ProtoCobolException(e); } catch (InterruptedException e) { throw new ProtoCobolException(e); } }
From source file:com.clustercontrol.ping.util.ReachAddressFping.java
/** * ????????????/*www.j a v a 2 s . c o m*/ * * @param info * @return PING */ public boolean isReachable(HashSet<String> hosts, int version) { Process process = null;//fping int m_exitValue = 0; //fping? String fpingPath; if (version == 6) { fpingPath = PingProperties.getFping6Path(); } else { fpingPath = PingProperties.getFpingPath(); } String cmd[] = FpingCommand.getCommand(fpingPath, hosts, m_sentCount, m_sentInterval, m_timeout, m_bytes); try { process = Runtime.getRuntime().exec(cmd); if (process != null) { //??? StreamReader errStreamReader = new StreamReader(process.getErrorStream()); errStreamReader.start(); StreamReader inStreamReader = new StreamReader(process.getInputStream()); inStreamReader.start(); // m_exitValue = process.waitFor(); //? inStreamReader.join(); m_resultMsg = inStreamReader.getResult(); m_log.debug("isReachable() STDOUT :" + inStreamReader.getResult().toString()); errStreamReader.join(); m_errMsg = errStreamReader.getResult(); m_log.debug("isReachable() STDERR :" + errStreamReader.getResult().toString()); } } catch (IOException e) { m_errMsg = new ArrayList<String>(); m_errMsg.add(e.getMessage()); m_log.warn("isReachable() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); return false; } catch (InterruptedException e) { m_errMsg = new ArrayList<String>(); m_errMsg.add(e.getMessage()); m_log.warn("isReachable() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); return false; } finally { if (process != null) { process.destroy(); } } if (m_exitValue == 0 || m_exitValue == 1) { m_log.debug("exit value = " + m_exitValue); //fping??0???? //fping??unreachable??1??????1??? return true; } else { String errMsg = "fping exit value is not 0 or 1. exit value = " + m_exitValue; m_log.info(errMsg); for (int j = 0; j < cmd.length; j++) { m_log.info("cmd[" + j + "] = " + cmd[j]); } m_errMsg = new ArrayList<String>(); m_errMsg.add(errMsg); //fping??!0 or !1??? return false; } }
From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java
@Test() public void getRealNodeNameTest() throws IOException { Process shell = mock(Process.class); String[] cmd = { anyString() }; when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shell).thenReturn(shell); String str = "\"testnodename.openstacklocal\""; when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8"))) .thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8"))); String strEr = " "; when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8"))) .thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8"))); Assert.assertTrue("testnodename.openstacklocal".equals(actionsService.getRealNodeName("testnodename"))); }
From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java
@SuppressWarnings("unchecked") private List<Future<?>> createProcessStreams(Process process) { if (output == null) { this.outputStream = new ByteArrayOutputStream(); this.output = commandOutputFactory.create(outputStream); }//from w w w. j a v a 2 s .c o m if (error == null) { this.errorStream = new ByteArrayOutputStream(); this.error = commandErrorFactory.create(errorStream); } if (input == null) { byte[] bytes = "".getBytes(); InputStream stream = new ByteArrayInputStream(bytes); this.input = commandInputFactory.create(stream); } input.setOutput(process.getOutputStream()); output.setInput(process.getInputStream()); error.setInput(process.getErrorStream()); return new ArrayList<Future<?>>( asList(threads.submit(input), threads.submit(output), threads.submit(error))); }
From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java
@Test(expected = NoSuchElementException.class) public void deleteNodeTestPuupetDBConnError() throws IOException { Process shell = mock(Process.class); Process shell2 = mock(Process.class); Process shellNodeName = mock(Process.class); String[] cmd = { anyString() }; // call to puppet cert list --all when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shellNodeName).thenReturn(shell) .thenReturn(shell2);//w w w. j a v a 2 s . c o m String strNodeName = "nodename"; when(shellNodeName.getInputStream()).thenReturn(new ByteArrayInputStream(strNodeName.getBytes("UTF-8"))); when(shellNodeName.getErrorStream()).thenReturn(new ByteArrayInputStream(" ".getBytes("UTF-8"))); String str = "Node 1 is registered"; String strdelete = "Node 1 unregistered"; when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8"))) .thenReturn(new ByteArrayInputStream(strdelete.getBytes("UTF-8"))); String strEr = " "; when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8"))); String str2 = "Node1.novalocal"; when(shell2.getInputStream()).thenReturn(new ByteArrayInputStream(str2.getBytes("UTF-8"))); String strEr2 = " "; when(shell2.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr2.getBytes("UTF-8"))); when(catalogManagerMongo.getNode("1")).thenReturn(node1).thenThrow(new NoSuchElementException()) .thenReturn(node1); actionsService.deleteNode("1"); verify(shell, times(1)).getInputStream(); verify(shell2, times(2)).getInputStream(); verify(processBuilderFactory, times(3)).createProcessBuilder((String[]) anyObject()); }
From source file:com.thebuzzmedia.exiftool.ExifToolNew3.java
/** * There is a bug that prevents exiftool to read unicode file names. We can get the windows filename if necessary * with getMSDOSName//from w ww .j av a2 s.c o m * * @link(http://perlmaven.com/unicode-filename-support-suggested-solution) * @link(http://stackoverflow.com/questions/18893284/how-to-get-short-filenames-in-windows-using-java) */ public static String getMSDOSName(File file) { try { String path = getAbsolutePath(file); String path2 = file.getAbsolutePath(); System.out.println(path2); // String toExecute = "cmd.exe /c for %I in (\"" + path2 + "\") do @echo %~fsI"; // ProcessBuilder pb = new ProcessBuilder("cmd","/c","for","%I","in","(" + path2 + ")","do","@echo","%~sI"); path2 = new File( "d:\\aaaaaaaaaaaaaaaaaaaaaaaaaaaa\\bbbbbbbbbbbbbbbbbb\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg") .getAbsolutePath(); path2 = new File( "d:\\personal\\photos-tofix\\2013-proposed1-bad\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg") .getAbsolutePath(); System.out.println(path2); ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "for", "%I", "in", "(\"" + path2 + "\")", "do", "@echo", "%~fsI"); // ProcessBuilder pb = new ProcessBuilder("cmd","/c","chcp 65001 & dir",path2); // ProcessBuilder pb = new ProcessBuilder("cmd","/c","ls",path2); Process process = pb.start(); // Process process = Runtime.getRuntime().exec(execLine); // Process process = Runtime.getRuntime().exec(new String[]{"cmd","/c","for","%I","in","(\"" + path2 + // "\")","do","@echo","%~fsI"}); process.waitFor(); byte[] data = new byte[65536]; // InputStreamReader isr = new InputStreamReader(process.getInputStream(), "UTF-8"); // String charset = Charset.defaultCharset().name(); String charset = "UTF-8"; String lines = IOUtils.toString(process.getInputStream(), charset); // int size = process.getInputStream().read(data); // String path3 = path; // if (size > 0) // path3 = new String(data, 0, size).replaceAll("\\r\\n", ""); String path3 = lines; System.out.println(pb.command()); System.out.println(path3); byte[] data2 = new byte[65536]; int size2 = process.getErrorStream().read(data2); if (size2 > 0) { String error = new String(data2, 0, size2); System.out.println(error); throw new RuntimeException("Error was thrown " + error); } return path3; } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } }