List of usage examples for java.lang Runtime exec
public Process exec(String cmdarray[]) throws IOException
From source file:net.ftb.util.OSUtils.java
public static boolean genThreadDump(long pid) { if (OSUtils.getCurrentOS() == OS.WINDOWS) { // TODO: implement Logger.logError("Not implemented yet / Might fail"); try {//from www . j a v a2 s .c o m Runtime runtime = Runtime.getRuntime(); runtime.exec(new String[] { "sendsignal.exe", Long.toString(pid) }); } catch (Exception e) { Logger.logError( "Failed. You need to install sendsignal.exe in your path to eanble this functionality"); Logger.logError("Failed", e); return false; } return true; } else if (OSUtils.getCurrentOS() == OS.UNIX || OSUtils.getCurrentOS() == OS.MACOSX) { Runtime runtime = Runtime.getRuntime(); try { runtime.exec(new String[] { "kill", "-3", Long.toString(pid) }); } catch (Exception e) { Logger.logError("Failed", e); return false; } return true; } else { Logger.logError("Unable to find genThreadDump implementation"); return false; } }
From source file:GenAppStoreSales.java
/** Connects to the AppleStore and download pending sale reports * (if they are still available)/* w ww .j av a 2 s . c om*/ * Requires Auntoingestion.class in the same path together with GenAppStoreSales * @throws IOException */ private static void autoingestionDownload(String reportName, String dateType, String dateCode) throws IOException { File reportFile = new File(sourcePath, reportName); Runtime rt = Runtime.getRuntime(); if (!reportFile.isFile()) { String s; System.out.println(reportName + " requesting..."); Process downloadReport = rt .exec("java Autoingestion" + autoingestionPreArgs + dateType + " " + "Summary " + dateCode); BufferedReader stdInput = new BufferedReader(new InputStreamReader(downloadReport.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(downloadReport.getErrorStream())); // read the output from the command while ((s = stdInput.readLine()) != null) System.out.println(s); // read any errors from the attempted command while ((s = stdError.readLine()) != null) System.out.println(s); // System.out.println("gzip -d " + currentPath.replace(" ", "\\ ") + "/" + reportName); // System.out.println("mv " + reportName + " " + sourcePath.replace(" ", "\\ ") + "/" + reportName); rt.exec("gzip -d " + currentPath.replace(" ", "\\ ") + "/" + reportName); rt.exec("mv " + reportName + " " + sourcePath.replace(" ", "\\ ") + "/" + reportName); rt.exec("rm " + currentPath.replace(" ", "\\ ") + "/*.gz"); } // else System.out.println(reportName + " verified"); }
From source file:com.eucalyptus.storage.TGTWrapper.java
/** * executeTGTs the specified tgt command in a separate process. * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on * the process using {@link java.util.concurrent.ExecutorService ExecutorService} * framework. If the process does not complete with in the timeout, it is cancelled. * /*from ww w. j a v a2 s. c o m*/ * @param command * @param timeout * @return CommandOutput * @throws EucalyptusCloudException */ private static CommandOutput execute(@NotNull String[] command, @NotNull Long timeout) throws EucalyptusCloudException, CallTimeoutException { try { Integer returnValue = -999999; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(command); StreamConsumer error = new StreamConsumer(process.getErrorStream()); StreamConsumer output = new StreamConsumer(process.getInputStream()); error.start(); output.start(); Callable<Integer> processMonitor = new ProcessMonitor(process); Future<Integer> processController = service.submit(processMonitor); try { returnValue = processController.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException tex) { String commandStr = buildCommand(command); LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out"); processController.cancel(true); Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller") .withVar("timeout", Long.toString(timeout)).log(); throw new CallTimeoutException("No response from the command " + commandStr + ". Process timed out after waiting for " + timeout + " milliseconds"); } output.join(); error.join(); LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout=" + output.getReturnValue() + "\n stderr=" + error.getReturnValue()); return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue()); } catch (CallTimeoutException e) { throw e; } catch (Exception ex) { throw new EucalyptusCloudException(ex); } }
From source file:com.yanghe.sujiu.network.image.ImageCache.java
/** ??*/ public static File initPath(Context context) { String path;//from w ww . java2 s . c o m // SD???? if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { path = Environment.getExternalStorageDirectory().getPath(); } else { Log.v("MKDIR", "No SD card!!!"); path = "/data/data"; } path = path + context.getPackageName(); File file = new File(path); if (!file.exists()) { file.mkdirs(); Log.d("INITPATH", "ROOT"); } Runtime runtime = Runtime.getRuntime(); try { runtime.exec("chmod 755 " + path); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file; }
From source file:com.orange.atk.results.logger.documentGenerator.GraphGenerator.java
/** * Generate a graph in png from the provided plot list. The X axis of the * graph is in minutes./*ww w.ja va 2 s . co m*/ * * @param plotList * plotlist to save. Xvalues must be stored in milliseconds. * @param associatedName * kind of the list * @param folderWhereResultsAreSaved * folder where graph while be saved * @param yLabel * name of the y label * @param pictureFile * name of the file where the picture would be saved (path should * be absolute) * @param yDivisor divisor of the measurements */ public static void generateGraph(PlotList plotList, String associatedName, String folderWhereResultsAreSaved, String yLabel, String pictureFile, float yDivisor) { Logger.getLogger("generateGraph").debug(folderWhereResultsAreSaved + associatedName + ".cmd"); // Store measurements in a file try { dumpInFile(plotList, folderWhereResultsAreSaved + associatedName + ".csv"); // Create gnuplot scripts used to generate graphs if (plotList.isEmpty()) { Logger.getLogger(GraphGenerator.class).warn(associatedName + " plot list is empty"); return; } // create a .cmd which will be given to the gnuplot program File commandFile = new File(folderWhereResultsAreSaved + associatedName + ".cmd"); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(commandFile))); // Picture will be saved in png bufferedWriter.write("set terminal png" + Platform.LINE_SEP); // Name of the picture bufferedWriter.write( "set output '" + folderWhereResultsAreSaved + associatedName + ".png'" + Platform.LINE_SEP); // format of the number on the y-axis bufferedWriter.write("set format y \"%.3s\"" + Platform.LINE_SEP); // Names of the axis bufferedWriter.write("set xlabel \"Time\"" + Platform.LINE_SEP); bufferedWriter.write("set ylabel \"" + yLabel + "\"" + Platform.LINE_SEP); // Set the range on y axis bufferedWriter.write("set yrange [" + (plotList.getMin() / yDivisor) * 0.9998 + ":" + (plotList.getMax() / yDivisor) * 1.0002 + "]" + Platform.LINE_SEP); bufferedWriter.write("set xtics autofreq" + Platform.LINE_SEP); bufferedWriter.write("set ytics autofreq" + Platform.LINE_SEP); bufferedWriter.write("plot '" + folderWhereResultsAreSaved + associatedName + ".csv' with lines" + Platform.LINE_SEP); bufferedWriter.flush(); bufferedWriter.close(); // call gnuplot for generating graphs Runtime runtime = Runtime.getRuntime(); String gnuplotName = null; if (Platform.OS_NAME.toLowerCase().contains("windows")) { gnuplotName = "wgnuplot"; } else { gnuplotName = "gnuplot"; } String[] cmdsCpu1 = { gnuplotName, folderWhereResultsAreSaved + associatedName + ".cmd" }; if (!plotList.isEmpty()) { // Call gnuplot int returnValue = runtime.exec(cmdsCpu1).waitFor(); if (returnValue != 0) { Logger.getLogger(GraphGenerator.class).warn( "Problem while creating graph. Does " + gnuplotName + " program belongs to PATH?"); } } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.eucalyptus.blockstorage.TGTWrapper.java
/** * executeTGTs the specified tgt command in a separate process. * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on * the process using {@link java.util.concurrent.ExecutorService ExecutorService} * framework. If the process does not complete with in the timeout, it is cancelled. * /* w ww . j ava2 s. c om*/ * @param command * @param timeout * @return CommandOutput * @throws EucalyptusCloudException */ private static CommandOutput execute(@Nonnull String[] command, @Nonnull Long timeout) throws EucalyptusCloudException, CallTimeoutException { try { Integer returnValue = -999999; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(command); StreamConsumer error = new StreamConsumer(process.getErrorStream()); StreamConsumer output = new StreamConsumer(process.getInputStream()); error.start(); output.start(); Callable<Integer> processMonitor = new ProcessMonitor(process); Future<Integer> processController = getExecutorWithInit().submit(processMonitor); try { returnValue = processController.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException tex) { String commandStr = buildCommand(command); LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out"); processController.cancel(true); Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller") .withVar("timeout", Long.toString(timeout)).log(); throw new CallTimeoutException("No response from the command " + commandStr + ". Process timed out after waiting for " + timeout + " milliseconds"); } output.join(); error.join(); LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout=" + output.getReturnValue() + "\n stderr=" + error.getReturnValue()); return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue()); } catch (CallTimeoutException e) { throw e; } catch (Exception ex) { throw new EucalyptusCloudException(ex); } }
From source file:org.openhab.binding.fems.FEMSCore.java
/** * Initialize FEMS/FEMSmonitor system//from ww w . j a v a 2s . c om */ private static void init() { int returnCode = 0; try { log.info("FEMS Initialization"); // start IO Agent Constants.IO_AGENT.start(); // init LCD display Constants.IO_AGENT.setLcdText(true, "FEMS Selbsttest"); // Init runtime variables Runtime rt = Runtime.getRuntime(); Process proc; InitStatus initStatus = new InitStatus(); try { // check for valid ip address InetAddress ip = Tools.getIPaddress(); if (ip == null) { try { proc = rt.exec("/sbin/dhclient eth0"); proc.waitFor(); ip = Tools.getIPaddress(); /* try again */ if (ip == null) { /* still no IP */ throw new IPException(); } } catch (IOException | InterruptedException e) { throw new IPException(e.getMessage()); } } log.info("IP: " + ip.getHostAddress()); initStatus.setIp(true); Constants.IO_AGENT.setLcdText(initStatus + " IP ok "); Constants.IO_AGENT.handleCommand(Constants.UserLED_1, OnOffType.ON); // check time if (Tools.isDateValid()) { /* date is valid, so we check internet access only */ log.info("Date ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); try { URL url = new URL("https://fenecon.de"); URLConnection con = url.openConnection(); con.setConnectTimeout(5000); con.getContent(); } catch (IOException e) { throw new InternetException(e.getMessage()); } } else { log.info("Date not ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); try { proc = rt.exec( "/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"); proc.waitFor(); if (!Tools.isDateValid()) { // try one more time proc = rt.exec( "/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org"); proc.waitFor(); if (!Tools.isDateValid()) { throw new InternetException( "Wrong Date: " + Constants.LONG_DATE_FORMAT.format(new Date())); } } log.info("Date now ok: " + Constants.LONG_DATE_FORMAT.format(new Date())); } catch (IOException | InterruptedException e) { throw new InternetException(e.getMessage()); } } log.info("Internet access is available"); initStatus.setInternet(true); Constants.IO_AGENT.setLcdText(initStatus + " Internet ok"); Constants.IO_AGENT.handleCommand(Constants.UserLED_2, OnOffType.ON); // test modbus if (isModbusWorking(log, ess)) { log.info("Modbus is ok"); initStatus.setModbus(true); Constants.IO_AGENT.setLcdText(initStatus + " RS485 ok "); Constants.IO_AGENT.handleCommand(Constants.UserLED_3, OnOffType.ON); } else { if (debug) { // if we are in debug mode: ignore RS485-errors log.info("Ignore RS485-Error"); } else { throw new RS485Exception(); } } // Exit message log.info("Finished without error"); Constants.IO_AGENT.setLcdText(initStatus + " erfolgreich"); // announce systemd finished log.info("Announce systemd: ready"); try { proc = rt.exec("/bin/systemd-notify --ready"); proc.waitFor(); } catch (IOException | InterruptedException e) { log.error(e.getMessage()); } } catch (FEMSException e) { log.error(e.getMessage()); log.error("Finished with error"); Constants.IO_AGENT.setLcdText(initStatus + " " + e.getMessage()); returnCode = 1; } // Check if Yaler is active if (FEMSYaler.getFEMSYaler().isActive()) { log.info("Yaler is activated"); } else { log.info("Yaler is deactivated"); } // Send message if (apikey == null) { log.error("Apikey is not available"); } else { // start Agents Constants.ONLINE_MONITORING_AGENT.setApikey(apikey); Constants.ONLINE_MONITORING_AGENT.start(); Constants.ONLINE_MONITORING_CACHE_AGENT.setApikey(apikey); Constants.ONLINE_MONITORING_CACHE_AGENT.start(); Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); } // start system update log.info("Start system update"); try { proc = rt.exec("/usr/bin/fems-autoupdate"); proc.waitFor(); } catch (IOException | InterruptedException e) { log.error(e.getMessage()); } Constants.IO_AGENT.handleCommand(Constants.UserLED_4, OnOffType.ON); } catch (Throwable e) { // Catch everything else returnCode = 2; StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error("Critical error: " + sw.toString()); e.printStackTrace(); Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); // try to send log } try { Thread.sleep(2000); // give the agents some time to try sending } catch (InterruptedException e) { e.printStackTrace(); } // Stop agents Constants.ONLINE_MONITORING_AGENT.interrupt(); try { Constants.ONLINE_MONITORING_AGENT.join(); } catch (InterruptedException e) { e.printStackTrace(); } Constants.ONLINE_MONITORING_CACHE_AGENT.interrupt(); try { Constants.ONLINE_MONITORING_CACHE_AGENT.join(); } catch (InterruptedException e) { e.printStackTrace(); } Constants.IO_AGENT.interrupt(); try { Constants.IO_AGENT.join(); } catch (InterruptedException e) { e.printStackTrace(); } // Exit System.exit(returnCode); }
From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java
/** * Run command as root.//from w w w.j a v a 2s. com * * @param command command * @return true, if command was successfully executed */ private static boolean runAsRoot(final String command) { Log.i(TAG, "running command as root: ", command); try { Runtime r = Runtime.getRuntime(); Process p = r.exec("su"); DataOutputStream d = new DataOutputStream(p.getOutputStream()); d.writeBytes(command); d.writeBytes("\nexit\n"); d.flush(); int retval = p.waitFor(); Log.i(TAG, "done"); return (retval == 0); } catch (Exception e) { Log.e(TAG, "runAsRoot", e); return false; } }
From source file:oscar.util.Doc2PDF.java
public static int topdf(HttpServletRequest request, HttpServletResponse response, String filename)// I - Name of file to convert { String command; // Command string Process process; // Process for HTMLDOC Runtime runtime; // Local runtime object java.io.InputStream input; // Output from HTMLDOC byte buffer[]; // Buffer for output data int bytes; // Number of bytes // Construct the command string command = "htmldoc --quiet --webpage -t pdf " + filename; try {/*ww w . j av a2s .co m*/ // Run the process and wait for it to complete... runtime = Runtime.getRuntime(); // Create a new HTMLDOC process... process = runtime.exec(command); // Get stdout from the process and a buffer for the data... input = process.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); // Compress the data byte[] buf = new byte[1024]; // Read output from HTMLDOC until we have it all... while ((bytes = input.read(buf)) > 0) bos.write(buf, 0, bytes); PrintPDFFromBytes(response, bos.toByteArray()); // Return the exit status from HTMLDOC... return (process.waitFor()); } catch (Exception e) { // An error occurred - send it to stderr for the web server... logger.error(e.toString() + " caught while running:\n\n"); logger.error(" " + command + "\n"); logger.error("", e); return (1); } }
From source file:com.tvh.gmaildrafter.Drafter.java
private static void composeMail(Credentials credentials, String subjectText, String bodyText, String[] attachments, String[] attachmentnames, String[] destinations, String[] cc, String[] bcc, Boolean sendImmediately) throws IOException, AuthenticationFailedException { if (subjectText == null) { subjectText = ""; }//w ww . j av a 2s. c o m if (bodyText == null) { bodyText = ""; } try { Properties props = null; Session session = null; if (!sendImmediately) { props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); session = Session.getDefaultInstance(props, null); } else { props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); final String username = credentials.getUsername(); final String password = credentials.getPassword(); session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } String signature = Signature.getSignature(credentials); if (signature == null) signature = ""; // Create the message Message draftMail = new MimeMessage(session); draftMail.setSubject(subjectText); Multipart parts = new MimeMultipart(); BodyPart body = new MimeBodyPart(); if (bodyText.toLowerCase().indexOf("<body") < 0) // rough guess to see if the body is html { bodyText = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>" + StringEscapeUtils.escapeHtml(bodyText).replace("\n", "<br />" + "\n") + "<br>" + "</body></html>"; } if (signature != null && signature != "") { StringBuilder b = new StringBuilder(bodyText); if (signature.indexOf("</") < 0) // assume it's html if there's no </, rough guess { signature = StringEscapeUtils.escapeHtml(signature); } b.replace(bodyText.lastIndexOf("</body>"), bodyText.lastIndexOf("</body>") + 7, "<br>" + signature + "</body>"); bodyText = b.toString(); } body.setContent(bodyText, "text/html; charset=utf-8"); body.setDisposition("inline"); parts.addBodyPart(body); if (attachments != null) { for (int i = 0; i < attachments.length; i++) { BodyPart attachment = new MimeBodyPart(); DataSource source = new FileDataSource(attachments[i]); attachment.setDataHandler(new DataHandler(source)); if (attachmentnames != null && attachmentnames.length > i) { attachment.setFileName(attachmentnames[i]); } else { File file = new File(attachments[i]); attachment.setFileName(file.getName()); } parts.addBodyPart(attachment); } } draftMail.setContent(parts); if (destinations != null && destinations.length > 0) draftMail.setRecipients(Message.RecipientType.TO, stringToInternetAddress(destinations)); if (cc != null && cc.length > 0) draftMail.setRecipients(Message.RecipientType.CC, stringToInternetAddress(cc)); if (bcc != null && bcc.length > 0) draftMail.setRecipients(Message.RecipientType.BCC, stringToInternetAddress(bcc)); draftMail.setFlag(Flags.Flag.SEEN, true); if (sendImmediately) { Transport.send(draftMail); } else { URLName url = new URLName("imaps://imap.gmail.com"); IMAPSSLStore store = new IMAPSSLStore(session, url); store.connect(credentials.getUsername(), credentials.getPassword()); Folder[] f = store.getDefaultFolder().xlist("*"); long threadId = 0; for (Folder fd : f) { IMAPFolder folder = (IMAPFolder) fd; boolean thisIsDrafts = false; String atts[] = folder.getAttributes(); for (String a : atts) { if (a.equalsIgnoreCase("\\Drafts")) { thisIsDrafts = true; break; } } if (thisIsDrafts) { folder.open(Folder.READ_WRITE); Message[] messages = new Message[1]; messages[0] = draftMail; folder.appendMessages(messages); /* * Determine the Google Message Id, needed to open it in the * browser. Because we just created the message it is * reasonable to assume it is the last message in the draft * folder. If this turns out not to be the case we could * start creating the message with a random unique dummy * subject, find it using that subject and then modify the * subject to what it was supposed to be. */ messages[0] = folder.getMessage(folder.getMessageCount()); FetchProfile fp = new FetchProfile(); fp.add(IMAPFolder.FetchProfileItem.X_GM_THRID); folder.fetch(messages, fp); IMAPMessage googleMessage = (IMAPMessage) messages[0]; threadId = googleMessage.getGoogleMessageThreadId(); folder.close(false); } } if (threadId == 0) { System.exit(6); } store.close(); // Open the message in the default browser Runtime rt = Runtime.getRuntime(); String drafturl = "https://mail.google.com/mail/#drafts/" + Long.toHexString(threadId); File chrome = new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"); if (!chrome.exists()) chrome = new File("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"); if (!chrome.exists()) { // Chrome not found, using default browser rt.exec("rundll32 url.dll,FileProtocolHandler " + drafturl); } else { String[] commandLine = new String[2]; commandLine[0] = chrome.getPath(); commandLine[1] = drafturl; rt.exec(commandLine); } } // else branch for sendImmediately } catch (NoSuchProviderException e) { e.printStackTrace(); System.exit(4); } catch (AuthenticationFailedException e) { throw (e); } catch (MessagingException e) { e.printStackTrace(); System.exit(5); } }