List of usage examples for org.apache.commons.exec CommandLine addArgument
public CommandLine addArgument(final String argument, final boolean handleQuoting)
From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java
File createAndAddCustomizedAndroidManifestToSelendroidServer() throws IOException, ShellCommandException, AndroidSdkException { String targetPackageName = applicationUnderTest.getBasePackage(); File tmpDir = Files.createTempDir(); if (deleteTmpFiles()) { tmpDir.deleteOnExit();/*from w ww.j av a 2s .com*/ } File customizedManifest = new File(tmpDir, "AndroidManifest.xml"); if (deleteTmpFiles()) { customizedManifest.deleteOnExit(); } log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath()); // add target package InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate); if (inputStream == null) { throw new SelendroidException("AndroidApplication.xml template file was not found."); } String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName()); // find the first occurance of "package" and appending the targetpackagename to begining int i = content.toLowerCase().indexOf("package"); int cnt = 0; for (; i < content.length(); i++) { if (content.charAt(i) == '\"') { cnt++; } if (cnt == 2) { break; } } content = content.substring(0, i) + "." + targetPackageName + content.substring(i); log.info("Final Manifest File:\n" + content); content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName); // Seems like this needs to be done if (content.contains(ICON)) { content = content.replaceAll(ICON, ""); } OutputStream outputStream = new FileOutputStream(customizedManifest); IOUtils.write(content, outputStream, Charset.defaultCharset().displayName()); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); // adding the xml to an empty apk CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt()); File manifestApkFile = File.createTempFile("manifest", ".apk"); if (deleteTmpFiles()) { manifestApkFile.deleteOnExit(); } createManifestApk.addArgument("package", false); createManifestApk.addArgument("-M", false); createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false); createManifestApk.addArgument("-I", false); createManifestApk.addArgument(AndroidSdk.androidJar(), false); createManifestApk.addArgument("-F", false); createManifestApk.addArgument(manifestApkFile.getAbsolutePath(), false); createManifestApk.addArgument("-f", false); log.info(ShellCommand.exec(createManifestApk, 20000L)); ZipFile manifestApk = new ZipFile(manifestApkFile); ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml"); File finalSelendroidServerFile = File.createTempFile("selendroid-server", ".apk"); if (deleteTmpFiles()) { finalSelendroidServerFile.deleteOnExit(); } ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile); finalSelendroidServer.putArchiveEntry(binaryManifestXml); IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer); ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath()); Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries(); for (; entries.hasMoreElements();) { ZipArchiveEntry dd = entries.nextElement(); finalSelendroidServer.putArchiveEntry(dd); IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer); } finalSelendroidServer.closeArchiveEntry(); finalSelendroidServer.close(); manifestApk.close(); log.info("file: " + finalSelendroidServerFile.getAbsolutePath()); return finalSelendroidServerFile; }
From source file:io.selendroid.standalone.android.impl.AbstractDevice.java
public String runAdbCommand(String parameter) { if (parameter == null || parameter.isEmpty()) { return null; }//w w w .j a va2s. c om log.fine("running command: adb " + parameter); CommandLine command = adbCommand(); String[] params = parameter.split(" "); for (String param : params) { command.addArgument(param, false); } String commandOutput = executeCommandQuietly(command); return commandOutput.trim(); }
From source file:cc.arduino.Compiler.java
private void exec(String[] command) throws RunnerException { // eliminate any empty array entries List<String> stringList = new ArrayList<>(); for (String string : command) { string = string.trim();/* www. ja v a 2 s . co m*/ if (string.length() != 0) stringList.add(string); } command = stringList.toArray(new String[stringList.size()]); if (command.length == 0) return; if (verbose) { for (String c : command) System.out.print(c + " "); System.out.println(); } DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler() { @Override protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) { final Thread result = new Thread(new MyStreamPumper(is, Compiler.this)); result.setName("MyStreamPumper Thread"); result.setDaemon(true); return result; } }); CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]); for (int i = 1; i < command.length; i++) { commandLine.addArgument(command[i], false); } int result; executor.setExitValues(null); try { result = executor.execute(commandLine); } catch (IOException e) { RunnerException re = new RunnerException(e.getMessage()); re.hideStackTrace(); throw re; } executor.setExitValues(new int[0]); // an error was queued up by message(), barf this back to compile(), // which will barf it back to Editor. if you're having trouble // discerning the imagery, consider how cows regurgitate their food // to digest it, and the fact that they have five stomaches. // //System.out.println("throwing up " + exception); if (exception != null) throw exception; if (result > 1) { // a failure in the tool (e.g. unable to locate a sub-executable) System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result)); } if (result != 0) { RunnerException re = new RunnerException(tr("Error compiling.")); re.hideStackTrace(); throw re; } }
From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java
public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException { final String methodName = IServiceCheckProcessor.CNAME + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException"; if (DEBUG) {/*from w w w . j a v a 2 s. c o m*/ DEBUGGER.debug(methodName); DEBUGGER.debug("ServiceCheckRequest: {}", request); } int exitCode = -1; Socket socket = null; File sourceFile = null; CommandLine command = null; BufferedWriter writer = null; ExecuteStreamHandler streamHandler = null; ByteArrayOutputStream outputStream = null; ServiceCheckResponse response = new ServiceCheckResponse(); final DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { switch (request.getRequestType()) { case NETSTAT: sourceFile = scriptConfig.getScripts().get("netstat"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; case REMOTEDATE: response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData(System.currentTimeMillis()); break; case TELNET: response = new ServiceCheckResponse(); int targetPort = request.getPortNumber(); String targetServer = request.getTargetHost(); if (DEBUG) { DEBUGGER.debug("Target port: {}", targetPort); DEBUGGER.debug("Target server: {}", targetServer); } if (targetPort == 0) { throw new ServiceCheckException("Target port number was not assigned. Cannot action request."); } final String CRLF = "\r\n"; final String TERMINATE_TELNET = "^]"; synchronized (new Object()) { InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort); socket = new Socket(); socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT); socket.setSoLinger(false, 0); socket.setKeepAlive(false); try { socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + targetServer + " on port " + request.getPortNumber()); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(TERMINATE_TELNET + CRLF); pWriter.flush(); pWriter.close(); response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " successful."); } catch (ConnectException cx) { response.setRequestStatus(AgentStatus.FAILURE); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " failed with message: " + cx.getMessage()); } } break; case PROCESSLIST: sourceFile = scriptConfig.getScripts().get("processList"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; default: // unknown operation throw new ServiceCheckException("No valid operation was specified"); } } catch (UnknownHostException uhx) { ERROR_RECORDER.error(uhx.getMessage(), uhx); throw new ServiceCheckException(uhx.getMessage(), uhx); } catch (SocketException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new ServiceCheckException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ServiceCheckException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ServiceCheckException(ix.getMessage(), ix); } finally { try { if (writer != null) { writer.close(); } if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }
From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java
/** * Transforms an {@link ExecCommand} to a {@link CommandLine}. No quoting fo * the arguments is used./*from w ww. j a v a 2 s . co m*/ * * @param execCommand a not-null <code>ExecCommand</code> instance. * @return a {@link CommandLine} object. */ protected CommandLine toCommandLine(ExecCommand execCommand) { notNull(execCommand, "execCommand"); CommandLine cl = new CommandLine(execCommand.getExecutable()); List<String> args = execCommand.getArgs(); for (String arg : args) { // do not handle quoting here, it is already quoted cl.addArgument(arg, false); } return cl; }
From source file:org.apache.hcatalog.templeton.ExecServiceImpl.java
private CommandLine makeCommandLine(String program, List<String> args) throws NotAuthorizedException, IOException { String path = validateProgram(program); CommandLine cmd = new CommandLine(path); if (args != null) for (String arg : args) cmd.addArgument(arg, false); return cmd;//from www. j a v a 2s . c o m }
From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterManagedProcess.java
@Override public void start(String userName, Boolean isUserImpersonate) { // start server process try {/*from ww w. j a v a 2 s. c om*/ port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); } catch (IOException e1) { throw new InterpreterException(e1); } CommandLine cmdLine = CommandLine.parse(interpreterRunner); cmdLine.addArgument("-d", false); cmdLine.addArgument(interpreterDir, false); cmdLine.addArgument("-p", false); cmdLine.addArgument(Integer.toString(port), false); if (isUserImpersonate && !userName.equals("anonymous")) { cmdLine.addArgument("-u", false); cmdLine.addArgument(userName, false); } cmdLine.addArgument("-l", false); cmdLine.addArgument(localRepoDir, false); executor = new DefaultExecutor(); ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); ProcessLogOutputStream processOutput = new ProcessLogOutputStream(logger); processOutput.setOutputStream(cmdOut); executor.setStreamHandler(new PumpStreamHandler(processOutput)); watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); try { Map procEnv = EnvironmentUtils.getProcEnvironment(); procEnv.putAll(env); logger.info("Run interpreter process {}", cmdLine); executor.execute(cmdLine, procEnv, this); running = true; } catch (IOException e) { running = false; throw new InterpreterException(e); } long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < getConnectTimeout()) { if (!running) { try { cmdOut.flush(); } catch (IOException e) { // nothing to do } throw new InterpreterException(new String(cmdOut.toByteArray())); } try { if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", port)) { break; } else { try { Thread.sleep(500); } catch (InterruptedException e) { logger.error("Exception in RemoteInterpreterProcess while synchronized reference " + "Thread.sleep", e); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Remote interpreter not yet accessible at localhost:" + port); } } } processOutput.setOutputStream(null); }
From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcess.java
public int reference(InterpreterGroup interpreterGroup) { synchronized (referenceCount) { if (executor == null) { // start server process try { port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); } catch (IOException e1) { throw new InterpreterException(e1); }/* w w w.jav a2 s . c o m*/ CommandLine cmdLine = CommandLine.parse(interpreterRunner); cmdLine.addArgument("-d", false); cmdLine.addArgument(interpreterDir, false); cmdLine.addArgument("-p", false); cmdLine.addArgument(Integer.toString(port), false); executor = new DefaultExecutor(); watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); running = true; try { Map procEnv = EnvironmentUtils.getProcEnvironment(); procEnv.putAll(env); logger.info("Run interpreter process {}", cmdLine); executor.execute(cmdLine, procEnv, this); } catch (IOException e) { running = false; throw new InterpreterException(e); } long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < connectTimeout) { if (RemoteInterpreterUtils.checkIfRemoteEndpointAccessible("localhost", port)) { break; } else { try { Thread.sleep(500); } catch (InterruptedException e) { } } } clientPool = new GenericObjectPool<Client>(new ClientFactory("localhost", port)); remoteInterpreterEventPoller.setInterpreterGroup(interpreterGroup); remoteInterpreterEventPoller.setInterpreterProcess(this); remoteInterpreterEventPoller.start(); } return referenceCount.incrementAndGet(); } }
From source file:org.apache.zeppelin.python.PythonInterpreter.java
private void createGatewayServerAndStartScript() throws IOException { // start gateway server in JVM side int port = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); // use the FQDN as the server address instead of 127.0.0.1 so that python process in docker // container can also connect to this gateway server. String serverAddress = PythonUtils.getLocalIP(properties); String secret = PythonUtils.createSecret(256); this.gatewayServer = PythonUtils.createGatewayServer(this, serverAddress, port, secret, usePy4jAuth); gatewayServer.start();//from ww w . jav a2 s . c o m // launch python process to connect to the gateway server in JVM side createPythonScript(); String pythonExec = getPythonExec(); CommandLine cmd = CommandLine.parse(pythonExec); if (!pythonExec.endsWith(".py")) { // PythonDockerInterpreter set pythonExec with script cmd.addArgument(pythonWorkDir + "/zeppelin_python.py", false); } cmd.addArgument(serverAddress, false); cmd.addArgument(Integer.toString(port), false); executor = new DefaultExecutor(); outputStream = new InterpreterOutputStream(LOGGER); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT)); Map<String, String> env = setupPythonEnv(); if (usePy4jAuth) { env.put("PY4J_GATEWAY_SECRET", secret); } LOGGER.info("Launching Python Process Command: " + cmd.getExecutable() + " " + StringUtils.join(cmd.getArguments(), " ")); executor.execute(cmd, env, this); pythonScriptRunning.set(true); }
From source file:org.apache.zeppelin.shell.security.ShellSecurityImpl.java
public static void createSecureConfiguration(Properties properties, String shell) { String authType = properties.getProperty("zeppelin.shell.auth.type").trim().toUpperCase(); switch (authType) { case "KERBEROS": CommandLine cmdLine = CommandLine.parse(shell); cmdLine.addArgument("-c", false); String kinitCommand = String.format("kinit -k -t %s %s", properties.getProperty("zeppelin.shell.keytab.location"), properties.getProperty("zeppelin.shell.principal")); cmdLine.addArgument(kinitCommand, false); DefaultExecutor executor = new DefaultExecutor(); try {//w w w. j a v a 2 s.c om int exitVal = executor.execute(cmdLine); } catch (Exception e) { LOGGER.error("Unable to run kinit for zeppelin user " + kinitCommand, e); throw new InterpreterException(e); } } }