List of usage examples for org.apache.commons.exec CommandLine parse
public static CommandLine parse(final String line)
From source file:com.jaeksoft.searchlib.ocr.OcrManager.java
public void checkTesseract() throws SearchLibException { rwl.r.lock();// w w w . j av a 2 s . c om try { if (tesseractPath == null || tesseractPath.length() == 0) throw new SearchLibException("Please enter a path"); File file = new File(tesseractPath); if (!file.exists()) throw new SearchLibException("The file don't exist"); CommandLine cmdLine = CommandLine.parse(tesseractPath); StringBuilder sbResult = new StringBuilder(); run(cmdLine, 60, 1, sbResult); String result = sbResult.toString(); if (!tesseractCheckPattern.matcher(result).find()) throw new SearchLibException("Wrong returned message: " + result); } catch (IOException e) { throw new SearchLibException(e); } finally { rwl.r.unlock(); } }
From source file:drat.proteus.DratStartForm.java
private void parseAsVersionControlledRepo(String path, String command, boolean downloadPhase) throws IOException { if (!downloadPhase) { startDrat(path, command);// w w w .java 2 s . c o m return; } String projectName = null; boolean git = path.endsWith(".git"); File tmpDir = new File(System.getProperty("java.io.tmpdir")); String tmpDirPath = tmpDir.getCanonicalPath(); String line = null; if (git) { projectName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); line = "git clone --depth 1 --branch master " + path; } else { projectName = path.substring(path.lastIndexOf("/") + 1); line = "svn export " + path; } String clonePath = tmpDirPath + File.separator + projectName; File cloneDir = new File(clonePath); if (cloneDir.isDirectory() && cloneDir.exists()) { LOG.info("Git / SVN clone: [" + clonePath + "] already exists, removing it."); FileUtils.removeDir(cloneDir); } LOG.info("Cloning Git / SVN project: [" + projectName + "] remote repo: [" + path + "] into " + tmpDirPath); CommandLine cmdLine = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(tmpDir); int exitValue = executor.execute(cmdLine); if (git) { String gitHiddenDirPath = clonePath + File.separator + ".git"; File gitHiddenDir = new File(gitHiddenDirPath); LOG.info("Removing .git directory from " + gitHiddenDirPath); FileUtils.removeDir(gitHiddenDir); } startDrat(clonePath, command); }
From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java
protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir, InputStream input) throws IOException { // Create the result object TestJobResult.TransformResult result = new TestJobResult.TransformResult(); CountingOutputStream output = null;/* w w w .ja v a2 s . c om*/ CountingOutputStream error = null; try { // Create and open temporary file for standard output File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir); output = new CountingOutputStream(new FileOutputStream(outputFile)); // Create and open temporary file for standard error File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir); error = new CountingOutputStream(new FileOutputStream(errorFile)); // If executable is relative, try to resolve in working directory // (This emulates the behavior of Streaming) if (!executable.isAbsolute()) { File resolvedExecutable = new File(workingDir, executable.toString()); if (resolvedExecutable.isFile()) { resolvedExecutable.setExecutable(true); executable = resolvedExecutable.getAbsoluteFile(); } } // Run the transform CommandLine command; if (_switchUserCommand == null) command = new CommandLine(executable); else { command = CommandLine.parse(_switchUserCommand); HashMap<String, String> substitutionMap = new HashMap<String, String>(); substitutionMap.put("cmd", executable.toString()); command.setSubstitutionMap(substitutionMap); } DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT); PumpStreamHandler pump = new PumpStreamHandler(output, error, input); executor.setWorkingDirectory(workingDir); executor.setWatchdog(dog); executor.setStreamHandler(pump); executor.setExitValues(null); int exitCode = executor.execute(command); result.setExitCode(exitCode); // Check whether it produced any output if (output.getByteCount() == 0) { output.close(); outputFile.delete(); } else result.setOutputFile(outputFile); // Check whether it produced any error output if (error.getByteCount() == 0) { error.close(); errorFile.delete(); } else result.setErrorFile(errorFile); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(error); } return result; }
From source file:com.jredrain.startup.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }// w w w. j a v a 2 s . co m String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[redrain]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = RedRain.StatusCode.ERROR_EXEC.getValue(); } if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[redrain]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[redrain]:error:{}", e); } } if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[redrain]:execute result:{}", response.toString()); watchdog.stop(); return response; }
From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java
private void packageApplication() throws MojoExecutionException { String line = getPlay2().getAbsolutePath(); CommandLine cmdLine = CommandLine.parse(line); cmdLine.addArgument("package"); DefaultExecutor executor = new DefaultExecutor(); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog);/*from w ww . java 2 s.c o m*/ } executor.setWorkingDirectory(project.getBasedir()); executor.setExitValue(0); try { executor.execute(cmdLine, getEnvironment()); } catch (IOException e) { throw new MojoExecutionException("Error during packaging", e); } }
From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java
/** * Runs a command line task and returns the screen output or throws and * error if something bad happened//w ww . j a va 2s . c om * * @param command Command to run * * @return Screen output * * @throws Exception */ public static String execToString(String command) throws Exception { // Prepare the command line CommandLine commandline = CommandLine.parse(command); // Prepare the output stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); // Prepare the executor DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); exec.setStreamHandler(streamHandler); exec.setWatchdog(new ExecuteWatchdog(5000)); // Execute the command try { exec.execute(commandline); return (outputStream.toString()); } catch (Exception e) { throw new Exception(String.format("%s - %s", outputStream.toString(), e.getMessage())); } }
From source file:io.cettia.ProtocolTest.java
@Test public void protocol() throws Exception { final DefaultServer server = new DefaultServer(); server.onsocket(new Action<ServerSocket>() { @Override// w w w. j a va 2 s . co m public void on(final ServerSocket socket) { log.debug("socket.uri() is {}", socket.uri()); socket.on("abort", new VoidAction() { @Override public void on() { socket.close(); } }).on("echo", new Action<Object>() { @Override public void on(Object data) { socket.send("echo", data); } }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() { @Override public void on(Reply<Map<String, Object>> reply) { Map<String, Object> data = reply.data(); switch ((String) data.get("type")) { case "resolved": reply.resolve(data.get("data")); break; case "rejected": reply.reject(data.get("data")); break; } } }).on("/reply/outbound", new Action<Map<String, Object>>() { @Override public void on(Map<String, Object> data) { switch ((String) data.get("type")) { case "resolved": socket.send("test", data.get("data"), new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; case "rejected": socket.send("test", data.get("data"), null, new Action<Object>() { @Override public void on(Object data) { socket.send("done", data); } }); break; } } }); } }); final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server); final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server); org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(jetty); jetty.addConnector(connector); connector.setPort(8000); ServletContextHandler handler = new ServletContextHandler(); jetty.setHandler(handler); handler.addEventListener(new ServletContextListener() { @Override @SuppressWarnings("serial") public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Map<String, String[]> params = req.getParameterMap(); if (params.containsKey("heartbeat")) { server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0])); } if (params.containsKey("_heartbeat")) { server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0])); } } }); regSetup.addMapping("/setup"); // For HTTP transport Servlet servlet = new AsityServlet().onhttp(httpTransportServer); ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet); reg.setAsyncSupported(true); reg.addMapping("/cettia"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }); // For WebSocket transport ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia") .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer)); } }).build(); container.addEndpoint(config); jetty.start(); CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node") .addArgument("./src/test/resources/runner").addArgument("--cettia.transports") .addArgument("websocket,httpstream,httplongpoll"); DefaultExecutor executor = new DefaultExecutor(); // The exit value of mocha is the number of failed tests. executor.execute(cmdLine); jetty.stop(); }
From source file:com.blackducksoftware.tools.scmconnector.integrations.git.GitConnector.java
private void gitCheckoutBranchShaOrPrefixedTag(String branchShaOrPrefixedTag) throws Exception { CommandLine command = CommandLine.parse(EXECUTABLE); String sourceDirIncludingModule = addPathComponentToPath(getFinalSourceDirectory(), getModuleNameFromURLGit(repositoryURL)); File targetDir = new File(sourceDirIncludingModule); command.addArgument("checkout"); command.addArgument(branchShaOrPrefixedTag); int exitStatus = commandLineExecutor.executeCommand(log, command, targetDir); if (exitStatus != 0) { throw new Exception("Git checkout " + branchShaOrPrefixedTag + " failed: " + exitStatus); }/* ww w .jav a 2 s. c o m*/ }
From source file:de.akquinet.innovation.play.maven.Play2PackageMojo.java
private void packageDistribution() throws MojoExecutionException { String line = getPlay2().getAbsolutePath(); CommandLine cmdLine = CommandLine.parse(line); cmdLine.addArgument("dist"); DefaultExecutor executor = new DefaultExecutor(); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog);//from w w w . j a va2 s . co m } executor.setWorkingDirectory(project.getBasedir()); executor.setExitValue(0); try { executor.execute(cmdLine, getEnvironment()); } catch (IOException e) { throw new MojoExecutionException("Error during distribution creation", e); } }
From source file:net.openbyte.gui.WorkFrame.java
private void menuItem2ActionPerformed(ActionEvent e) { if (this.api == ModificationAPI.BUKKIT) { showBukkitIncompatibleFeature(); return;/* www .j a va 2 s.c o m*/ } System.out.println("Starting server..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild() .forTasks("runServer").run(); return null; } }; if (this.api == ModificationAPI.MCP) { worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (System.getProperty("os.name").startsWith("Windows")) { Runtime.getRuntime().exec("cmd /c startserver.bat", null, workDirectory); return null; } try { CommandLine startServer = CommandLine.parse("python " + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath() + " $@"); CommandLine authServer = CommandLine.parse("chmod 755 " + new File(new File(workDirectory, "runtime"), "startserver.py").getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workDirectory); executor.execute(authServer); executor.execute(startServer); } catch (Exception e) { e.printStackTrace(); } return null; } }; } worker.execute(); }