List of usage examples for java.lang Process exitValue
public abstract int exitValue();
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);//from w w w . j av a 2 s.c o m 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:marytts.tools.voiceimport.HTKLabeler.java
/** * delete sp repetition on htk.phones3.mlf * @throws Exception/*from ww w.j av a2 s . co m*/ */ private void delete_multiple_sp_in_PhoneMLFile(String filein, String fileout) throws Exception { String hled = getProp(HTKDIR) + File.separator + "HLEd"; File htkFile = new File(hled); if (!htkFile.exists()) { throw new RuntimeException("File " + htkFile.getAbsolutePath() + " does not exist"); } //String phoneMLF3 = getProp(HTDIR)+File.separator // +"etc"+File.separator+"htk.phones3.mlf"; // String phoneMLFtmpin = getProp(HTDIR)+File.separator // +"etc"+File.separator+"htk.phones3_tmp_in.mlf"; //String phoneMLFtmpout = getProp(HTDIR)+File.separator // +"etc"+File.separator+"htk.phones3_tmp_out.mlf"; String mkphoneLED = getProp(HTDIR) + File.separator + "config" + File.separator + "mkphone1.led"; Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println("( " + hled + " -l '*' -i " + fileout + " " + mkphoneLED + " " + filein + "; exit )\n"); pw.print("( " + hled + " -l '*' -i " + fileout + " " + mkphoneLED + " " + filein //+"; " + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); process.exitValue(); }
From source file:marytts.tools.voiceimport.HTKLabeler.java
/** * create phone master label file (Not used?) * @throws Exception//from w w w . ja v a 2 s . c o m */ private void createPhoneMLFile() throws Exception { String hled = getProp(HTKDIR) + File.separator + "HLEd"; File htkFile = new File(hled); if (!htkFile.exists()) { throw new RuntimeException("File " + htkFile.getAbsolutePath() + " does not exist"); } String dict = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.dict"; String phoneMLF = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones.mlf"; String wordsMLF = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.words.mlf"; String mkphoneLED = getProp(HTDIR) + File.separator + "config" + File.separator + "mkphone0.led"; Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println("( " + hled + " -l '*' -d " + dict + " -i " + phoneMLF + " " + mkphoneLED + " " + wordsMLF + "; exit )\n"); pw.print("( " + hled + " -l '*' -d " + dict + " -i " + phoneMLF + " " + mkphoneLED + " " + wordsMLF //+"; " + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } }
From source file:marytts.tools.voiceimport.HTKLabeler.java
/** * Setup the HTK directory/*from w w w . j av a 2 s . co m*/ * @throws IOException, InterruptedException * @throws MaryConfigurationException */ private void setup() throws IOException, InterruptedException, MaryConfigurationException { htk.mkdir(); File lab = new File(htk.getAbsolutePath() + "/lab"); //call setup of HTK in this directory Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); //go to htk directory and setup Directory Structure pw.print("( cd " + htk.getAbsolutePath() + "; mkdir -p hmm" + "; mkdir -p etc" + "; mkdir -p feat" + "; mkdir -p config" + "; mkdir -p lab" + "; mkdir -p htk-full/lab" + "; mkdir -p htk-full/wrd" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } // TODO: temporary: at the moment fix path to load the dictionary lexicon = new FSTLookup(new FileInputStream( "/home/fabio/voice_building_5_0/marytts-it/marytts-lang-it/src/main/resources/marytts/language/it/lexicon/it_lexicon.fst"), "it_lexicon.fst"); /* System.out.print("Starting builtin MARY TTS..."); Mary.startup(); System.out.println(" MARY TTS started."); e poi */ }
From source file:marytts.tools.voiceimport.HTKLabeler.java
private void saveHTKWordDictionary() throws Exception { String dict0 = outputDir + File.separator + "htk.words0.dict"; String dict = outputDir + File.separator + "htk.words.dict"; PrintWriter wordDictOut = new PrintWriter(new FileOutputStream(new File(dict0))); HTKdictionary.add("sil sil"); HTKdictionary.add("ssil ssil"); HTKdictionary.add("sp sp"); Iterator<String> itr = HTKdictionary.iterator(); while (itr.hasNext()) { wordDictOut.println(itr.next()); }//from w w w. ja v a 2 s .c o m wordDictOut.flush(); wordDictOut.close(); String fileded = getProp(HTDIR) + File.separator + "config" + File.separator + "dict.ded"; PrintWriter dedDictOut = new PrintWriter(new FileOutputStream(new File(fileded))); dedDictOut.println("AS sp"); dedDictOut.println("MP sil sil sp"); dedDictOut.println("MP ssil ssil sp"); dedDictOut.println("MP sp sp sp"); dedDictOut.flush(); dedDictOut.close(); Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell //when no sp use (-m)! String hdman = getProp(HTKDIR) + File.separator + "HDMan"; PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); String cmd = "( cd " + getProp(HTDIR) + "; " + hdman + " -g " + fileded + " " + dict + " " + dict0 + "; exit )\n"; System.out.println(cmd); pw.println(cmd); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } }
From source file:marytts.tools.voiceimport.HTKLabeler.java
/** * Create HMMs for each phone from Global HMMs * @throws Exception/*from w w w .j a v a 2 s. c om*/ */ private void createTrainFile() throws Exception { String script; String hmmDir = getProp(HTDIR) + File.separator + "hmm" + File.separator; /**TODO: * Replace below 'gawk' script with Java method. */ script = "mkdir hmm/hmm0\n" + "head -3 hmm/hmm-dummy/htk > hmm/hmm0/hmmdefs\n" + "for s in `cat etc/htk.phone.list`\n" + "do\n" + "echo \"~h \\\"$s\\\"\" >> hmm/hmm0/hmmdefs\n" + "gawk '/BEGINHMM/,/ENDHMM/ { print $0 }' hmm/hmm-dummy/htk >> hmm/hmm0/hmmdefs\n" + "done\n"; // creating list of training files File file = new File(getProp(HTDIR) + File.separator + "etc" + File.separator + "htkTrainScript.sh"); PrintWriter pw = new PrintWriter(new FileWriter(file)); pw.println(script); pw.flush(); pw.close(); Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println("( cd " + getProp(HTDIR) + "; sh etc" + File.separator + "htkTrainScript.sh" + " > log_htkTrainScript.txt" + "; exit )\n"); pw.print("( cd " + getProp(HTDIR) + "; sh etc" + File.separator + "htkTrainScript.sh" + " > log_htkTrainScript.txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } PrintWriter macroFile = new PrintWriter( new FileOutputStream(new File(hmmDir + "hmm0" + File.separator + "macros"))); macroFile.println("~o\n" + "<VecSize> 13\n" + "<" + Train_FEAT + ">"); macroFile.println( FileUtils.getFileAsString(new File(hmmDir + "hmm-dummy" + File.separator + "vFloors"), "ASCII")); macroFile.flush(); macroFile.close(); }
From source file:marytts.tools.voiceimport.HTKLabeler.java
/** * Feature Extraction for HTK Training // w ww .ja v a 2 s . c om * @throws Exception */ private void featureExtraction() throws Exception { String hcopy = getProp(HTKDIR) + File.separator + "HCopy"; File htkFile = new File(hcopy); if (!htkFile.exists()) { throw new RuntimeException("File " + htkFile.getAbsolutePath() + " does not exist"); } String configFile = getProp(HTDIR) + File.separator + "config" + File.separator + "featEx.conf"; String listFile = getProp(HTDIR) + File.separator + "etc" + File.separator + "featEx.list"; Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println("( cd " + getProp(HTDIR) + "; " + hcopy + " -T 1 -C " + configFile + " -S " + listFile + " > log_featureExtraction.txt" + "; exit )\n"); pw.print("( cd " + getProp(HTDIR) + "; " + hcopy + " -T 1 -C " + configFile + " -S " + listFile + " > log_featureExtraction.txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } }
From source file:cz.muni.fi.xklinec.zipstream.Mallory.java
/** * Simple helper for executing a command. * /*from w ww . ja v a 2 s .c o m*/ * @param command * @param outOpt * @param workingDir * @return * @throws IOException * @throws InterruptedException */ public CmdExecutionResult execute(final String command, OutputOpt outOpt, File workingDir, OutputStream os) throws IOException, InterruptedException { CmdExecutionResult res = new CmdExecutionResult(); // Execute motelist command Process p = workingDir == null ? Runtime.getRuntime().exec(command) : Runtime.getRuntime().exec(command, null, workingDir); // If interested only in stdErr, single thread is OK, otherwise 2 stream // reading threads are needed. if (outOpt == OutputOpt.EXECUTE_STDERR_ONLY || outOpt == OutputOpt.EXECUTE_STDOUT_ONLY) { StringBuilder sb = new StringBuilder(); BufferedReader bri = new BufferedReader(new InputStreamReader( outOpt == OutputOpt.EXECUTE_STDERR_ONLY ? p.getErrorStream() : p.getInputStream())); String line; while ((line = bri.readLine()) != null) { sb.append(line).append("\n"); } bri.close(); if (outOpt == OutputOpt.EXECUTE_STDOUT_ONLY) res.stdOut = sb.toString(); else if (outOpt == OutputOpt.EXECUTE_STDERR_ONLY) res.stdErr = sb.toString(); // synchronous call, wait for command completion p.waitFor(); } else if (outOpt == OutputOpt.EXECUTE_STD_COMBINE) { // Combine both streams together StreamMerger sm = new StreamMerger(p.getInputStream(), p.getErrorStream()); if (os != null) { sm.setOutputStream(os); } sm.run(); // synchronous call, wait for command completion p.waitFor(); res.stdOut = sm.getOutput(); } else { // Consume streams, older jvm's had a memory leak if streams were not read, // some other jvm+OS combinations may block unless streams are consumed. StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), true); StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), true); errorGobbler.start(); outputGobbler.start(); // synchronous call, wait for command completion p.waitFor(); res.stdErr = errorGobbler.getOutput(); res.stdOut = outputGobbler.getOutput(); } res.exitValue = p.exitValue(); return res; }
From source file:org.auraframework.integration.test.archetype.AuraArchetypeSimpleTestMANUAL.java
@Test public void testProjectCreation() throws Throwable { Process jettyProcess = null; workspace = new File(IOUtil.newTempDir("archetype")); try {//from ww w. ja v a 2 s . com // create a workspace to place the project files in workspace.mkdirs(); // generate a project from the archetype Process genProcess = startProcess(workspace, ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo, "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId, "-DarchetypeArtifactId=" + archetype.artifactId, "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId, "-DartifactId=" + project.artifactId, "-Dversion=" + project.version, "-Dpackage=" + projectPackage, "-DinteractiveMode=false")); goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!"); File projectDir = new File(workspace, project.artifactId); assertDirectory(projectDir); verifyGeneratedResources(projectDir); // build the new project Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install")); goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!"); // get a free port for jetty ServerSocket socket = new ServerSocket(0); int jettyPort = socket.getLocalPort(); socket.close(); // start up jetty jettyProcess = startProcess(projectDir, ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort)); int status = 0; for (int i = 0; i < 30; i++) { try { HttpGet get = obtainGetMethod("/"); HttpResponse response = perform(get); status = getStatusCode(response); get.releaseConnection(); break; } catch (ConnectException ce) { // expected, before server is listening Thread.sleep(1000); } } assertEquals("Failed to connect to server", HttpStatus.SC_OK, status); verifyDefaultDocument(); verifySampleComponents(); } catch (Throwable t) { // if any errors in Jetty requests, let's print out the Jetty // console output for diag before killing the // test if (jettyProcess != null) { InputStream is = jettyProcess.getInputStream(); int len = is.available(); byte[] buf = new byte[len]; is.read(buf); System.err.println(new String(buf)); } throw t; } finally { // kill Jetty if (jettyProcess != null) { try { jettyProcess.exitValue(); } catch (IllegalThreadStateException e) { jettyProcess.destroy(); } } // cleanup generated workspace IOUtil.delete(workspace); } }
From source file:marytts.tools.voiceimport.HTKLabeler.java
private void htkExtraModels() throws Exception { String hlstats = getProp(HTKDIR) + File.separator + "HLStats"; String hbuild = getProp(HTKDIR) + File.separator + "HBuild"; File htkFile = new File(hlstats); if (!htkFile.exists()) { throw new RuntimeException("File " + htkFile.getAbsolutePath() + " does not exist"); }//w ww. ja v a2 s . com String configFile = getProp(HTDIR) + File.separator + "config" + File.separator + "htkTrain.conf"; String bigFile = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones.big"; String phoneList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phone.list"; String phoneMlf = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones.mlf"; String phoneDict = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phone.dict"; String phoneAugDict = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.aug.phone.dict"; String phoneAugList = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.aug.phone.list"; String netFile = getProp(HTDIR) + File.separator + "etc" + File.separator + "htk.phones.net"; Runtime rtime = Runtime.getRuntime(); //get a shell Process process = rtime.exec("/bin/bash"); //get an output stream to write to the shell PrintWriter pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println("( cd " + getProp(HTDIR) + "; " + hlstats + " -T 1 -C " + configFile + " -b " + bigFile + " -o " + phoneList + " " + phoneMlf + " > log_hlstats.txt" + "; exit )\n"); pw.println("( cd " + getProp(HTDIR) + "; " + hlstats + " -T 1 -C " + configFile + " -b " + bigFile + " -o " + phoneList + " " + phoneMlf + " > log_hlstats.txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } String fileDict = FileUtils.getFileAsString(new File(phoneDict), "ASCII"); PrintWriter augPhoneDict = new PrintWriter(new FileWriter(phoneAugDict)); augPhoneDict.println("!ENTER sil"); augPhoneDict.print(fileDict); augPhoneDict.println("!EXIT sil"); augPhoneDict.flush(); augPhoneDict.close(); String fileList = FileUtils.getFileAsString(new File(phoneList), "ASCII"); PrintWriter augPhoneList = new PrintWriter(new FileWriter(phoneAugList)); augPhoneList.println("!ENTER"); augPhoneList.print(fileList); augPhoneList.println("!EXIT"); augPhoneList.flush(); augPhoneList.close(); rtime = Runtime.getRuntime(); //get a shell process = rtime.exec("/bin/bash"); //get an output stream to write to the shell pw = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); System.out.println("( cd " + getProp(HTDIR) + "; " + hbuild + " -T 1 -C " + configFile + " -n " + bigFile + " " + phoneAugList + " " + netFile + " > log_hbuild.txt" + "; exit )\n"); pw.println("( cd " + getProp(HTDIR) + "; " + hbuild + " -T 1 -C " + configFile + " -n " + bigFile + " " + phoneAugList + " " + netFile + " > log_hbuild.txt" + "; exit )\n"); pw.flush(); //shut down pw.close(); process.waitFor(); // check exit value if (process.exitValue() != 0) { BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); throw new MaryConfigurationException(errorReader.readLine()); } }