List of usage examples for org.apache.commons.exec DefaultExecutor setExitValue
public void setExitValue(final int value)
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 va2 s . c om 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:Logi.GSeries.Service.LogiGSKService.java
public void showSystemTray() { if ((systemTray != null) && !systemTrayVisible) { systemTray.setEnabled(true);// w w w. ja v a 2 s. c o m systemTrayVisible = true; return; } try { systemTray = SystemTray.getNative(); } catch (Exception ex) { System.out.println(ex.getMessage()); Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } if (systemTray != null) { try { systemTray.setImage(GSK_Icon); } catch (Exception e) { System.err.println("Problem setting system tray icon."); } systemTrayVisible = true; callbackOpen = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); try { CommandLine commandLine = new CommandLine("java"); commandLine.addArgument("-jar"); String jarPath = new URI( LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getPath(); commandLine.addArgument(jarPath, false); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); executor.execute(commandLine, new DefaultExecuteResultHandler()); } catch (URISyntaxException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } } }; callbackAbout = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK", JOptionPane.INFORMATION_MESSAGE); } }; Menu mainMenu = systemTray.getMenu(); MenuItem openEntry = new MenuItem("Open", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); entry.setCallback(callbackOpen); try { CommandLine commandLine = new CommandLine("java"); commandLine.addArgument("-jar"); String jarPath = new URI( LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getPath(); commandLine.addArgument(jarPath, false); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); executor.execute(commandLine, new DefaultExecuteResultHandler()); } catch (URISyntaxException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } } }); openEntry.setShortcut('O'); mainMenu.add(openEntry); mainMenu.add(new Separator()); MenuItem aboutEntry = new MenuItem("About", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK", JOptionPane.INFORMATION_MESSAGE); entry.setCallback(callbackAbout); } }); openEntry.setShortcut('A'); mainMenu.add(aboutEntry); /*} else { System.err.println("System tray is null!"); }*/ } }
From source file:it.drwolf.ridire.session.async.Mapper.java
@SuppressWarnings("unchecked") private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager) throws IOException, InterruptedException { String workingDirName = System.getProperty("java.io.tmpdir"); String userDir = System.getProperty("user.dir"); byte[] buf = new byte[Mapper.BUFLENGTH]; int count = 0; GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((count = gzis.read(buf)) != -1) { baos.write(buf, 0, count);/*from w w w. j a v a 2s . c om*/ } gzis.close(); baos.close(); byte[] byteArray = baos.toByteArray(); String uuid = UUID.randomUUID().toString(); String pdfFileName = uuid + ".pdf"; String htmlFileName = uuid + ".html"; File tmpDir = new File(workingDirName); String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName; File fileToConvert = new File(tmpDir, pdfFileName); FileUtils.writeByteArrayToFile(fileToConvert, byteArray); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY); CommandLine commandLine = CommandLine.parse(cp.getCommandValue()); commandLine.addArgument("-c"); commandLine.addArgument("-i"); commandLine.addArgument(fileToConvert.getAbsolutePath()); commandLine.addArgument(htmlFileNameCompletePath); executor.setExitValue(0); executor.execute(commandLine); try { FileUtils.moveFileToDirectory( new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false); } catch (IOException e) { } cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY); commandLine = CommandLine .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue()); commandLine.addArgument(htmlFileNameCompletePath); commandLine.addArgument("39"); commandLine.addArgument("6"); commandLine.addArgument("5"); executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT); executor.setWatchdog(watchdog); ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024); ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null); executor.setStreamHandler(executeStreamHandler); int exitValue = executor.execute(commandLine); String htmlString = null; if (exitValue == 0) { htmlString = baosStdOut.toString(); } FileUtils.deleteQuietly(new File(htmlFileNameCompletePath)); PrefixFileFilter pff = new PrefixFileFilter(uuid); for (File f : FileUtils.listFiles(tmpDir, pff, null)) { FileUtils.deleteQuietly(f); } if (htmlString != null) { htmlString = htmlString.replaceAll(" ", " "); htmlString = htmlString.replaceAll("<br.*?>", " "); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(htmlString.getBytes()); String encoding = charsetDetector.detect().getName(); return new StringWithEncoding(htmlString, encoding); } return null; }
From source file:it.drwolf.ridire.session.async.Mapper.java
private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager) throws SAXException, TikaException, IOException, TransformerConfigurationException, InterruptedException {//w w w . j av a2 s. c o m File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", "")) + JobMapperMonitor.RESOURCESDIR); String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue(); String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue(); String resourceFileName = cr.getDigest() + ".gz"; File resourceFile = new File(resourceDir, resourceFileName); StringWithEncoding rawContentAndEncoding = null; String contentType = cr.getContentType(); // long t1 = System.currentTimeMillis(); if (contentType != null && contentType.contains("application/msword")) { rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("application/rtf")) { rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("text/plain")) { // txt -> html -> txt is for txt cleaning rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("pdf")) { rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("html")) { rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile); } // long t2 = System.currentTimeMillis(); // System.out.println("Transformation: " + (t2 - t1)); if (rawContentAndEncoding != null) { if (rawContentAndEncoding.getEncoding() == null) { rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8"); } // t1 = System.currentTimeMillis(); String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString()); rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding()); File tmpFile = File.createTempFile("ridire", null); FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8"); String ridireCleanerJar = entityManager .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue(); String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue(); CommandLine commandLine = CommandLine .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar); commandLine.addArgument("-f"); commandLine.addArgument(tmpFile.getPath()); commandLine.addArgument("-e"); commandLine.addArgument("UTF-8"); commandLine.addArgument("-h"); commandLine.addArgument(host); commandLine.addArgument("-k"); commandLine.addArgument(alchemyKey); commandLine.addArgument("-r"); commandLine.addArgument(readabilityKey); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_TIMEOUT); executor.setWatchdog(watchdog); ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024); ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024); ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null); executor.setStreamHandler(executeStreamHandler); int exitValue = executor.execute(commandLine); if (exitValue == 0) { rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8"); // TODO filter real errors rawContentAndEncoding.setCleaner(baosStdErr.toString().trim()); } FileUtils.deleteQuietly(tmpFile); } return rawContentAndEncoding; }
From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java
/** * Run an arbitrary command and check it against an expected return value * * @param line/*from w ww .ja v a 2s. c om*/ * @param expectedReturnValue * @param dir working directory, can be null if you don't want to change directories * @return * @throws IOException */ public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException { Log.info("Running " + line); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(line); DefaultExecutor exec = new DefaultExecutor(); if (dir != null) { exec.setWorkingDirectory(dir); } PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.setExitValue(expectedReturnValue); try { int exitValue = exec.execute(commandline); Assert.assertTrue( "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue, exitValue == expectedReturnValue); String output = outputStream.toString(); return output; } catch (ExecuteException e) { Log.error("Execution failed with:"); Log.error(outputStream.toString()); throw e; } }
From source file:org.apache.drill.exec.client.DrillClient.java
/** * Run external script/*from w w w .j a v a2 s.co m*/ * * @param command */ public void runScript(String command) { //System.out.println("RUNNING COMMAND: " + command); String sCommandString = command; CommandLine oCmdLine = CommandLine.parse(sCommandString); DefaultExecutor oDefaultExecutor = new DefaultExecutor(); oDefaultExecutor.setExitValue(0); try { int iExitValue = oDefaultExecutor.execute(oCmdLine); } catch (ExecuteException e) { System.err.println("Execution failed."); e.printStackTrace(); } catch (IOException e) { System.err.println("permission denied."); e.printStackTrace(); } }
From source file:org.apache.tika.parser.geo.topic.GeoParser.java
public HashMap<String, ArrayList<String>> searchGeoNames(ArrayList<String> locationNameEntities) throws ExecuteException, IOException { CommandLine cmdLine = new CommandLine("lucene-geo-gazetteer"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); cmdLine.addArgument("-s"); for (String name : locationNameEntities) { cmdLine.addArgument(name);//ww w. ja va2s . c o m } LOG.fine("Executing: " + cmdLine); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); exec.setWatchdog(watchdog); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment()); String outputJson = outputStream.toString("UTF-8"); JSONArray json = (JSONArray) JSONValue.parse(outputJson); HashMap<String, ArrayList<String>> returnHash = new HashMap<String, ArrayList<String>>(); for (int i = 0; i < json.size(); i++) { JSONObject obj = (JSONObject) json.get(i); for (Object key : obj.keySet()) { String theKey = (String) key; JSONArray vals = (JSONArray) obj.get(theKey); ArrayList<String> stringVals = new ArrayList<String>(vals.size()); for (int j = 0; j < vals.size(); j++) { String val = (String) vals.get(j); stringVals.add(val); } returnHash.put(theKey, stringVals); } } return returnHash; }
From source file:org.apache.tika.parser.pot.PooledTimeSeriesParser.java
private String computePoT(File input) throws IOException, TikaException { CommandLine cmdLine = new CommandLine("pooled-time-series"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); cmdLine.addArgument("-f"); cmdLine.addArgument(input.getAbsolutePath()); LOG.trace("Executing: {}", cmdLine); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); exec.setWatchdog(watchdog);/*from ww w . ja va2 s . c o m*/ PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment()); return outputStream.toString("UTF-8"); }
From source file:org.bonitasoft.platform.setup.PlatformSetupDistributionIT.java
@Test public void setupSh_should_work_with_init_on_h2_and_prevent_pushing_deletion() throws Exception { //given/*from w w w .java2s .c o m*/ CommandLine oCmdLine = PlatformSetupTestUtils.createCommandLine(); oCmdLine.addArgument("init"); DefaultExecutor executor = PlatformSetupTestUtils.createExecutor(distFolder); executor.setStreamHandler(PlatformSetupTestUtils.getExecuteStreamHandler("yes")); //when int iExitValue = executor.execute(oCmdLine); //then assertThat(iExitValue).isEqualTo(0); Connection jdbcConnection = PlatformSetupTestUtils.getJdbcConnection(distFolder); Statement statement = jdbcConnection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) AS nb FROM CONFIGURATION"); resultSet.next(); assertThat(resultSet.getInt("nb")).isGreaterThan(0); oCmdLine = PlatformSetupTestUtils.createCommandLine(); oCmdLine.addArgument("pull"); iExitValue = executor.execute(oCmdLine); assertThat(iExitValue).isEqualTo(0); final Path platform_engine = distFolder.toPath().resolve("platform_conf").resolve("current") .resolve("platform_engine"); FileUtils.deleteDirectory(platform_engine.toFile()); oCmdLine = PlatformSetupTestUtils.createCommandLine(); oCmdLine.addArgument("push"); executor.setExitValue(1); iExitValue = executor.execute(oCmdLine); assertThat(iExitValue).isEqualTo(1); oCmdLine.addArgument("--force"); executor.setExitValue(0); iExitValue = executor.execute(oCmdLine); assertThat(iExitValue).isEqualTo(0); }
From source file:org.bonitasoft.platform.setup.PlatformSetupDistributionIT.java
@Test public void setupSh_should_have_error_with_no_argument() throws Exception { //given//from w ww . j a va 2s . c om CommandLine oCmdLine = PlatformSetupTestUtils.createCommandLine(); DefaultExecutor oDefaultExecutor = PlatformSetupTestUtils.createExecutor(distFolder); oDefaultExecutor.setExitValue(1); //when int iExitValue = oDefaultExecutor.execute(oCmdLine); //then assertThat(iExitValue).isEqualTo(1); }