Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String cmdarray[]) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process.

Usage

From source file:com.sssemil.advancedsettings.MainService.java

@Override
public void onDisplayChanged(int displayId) {
    try {/*w  ww  . ja  v  a 2s.  co  m*/
        mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        mDisplayManager.registerDisplayListener(MainService.this, null);
        switch (mDisplayManager.getDisplay(displayId).getState()) {
        case Display.STATE_DOZE_SUSPEND:
        case Display.STATE_DOZE:
            try {
                //TODO: Need to fix screen_saver_brightness_settings. SELinux problems?
                Thread.sleep(3);
                int brightness = Integer
                        .parseInt(mSharedPreferences.getString("screen_saver_brightness_settings",
                                String.valueOf(Utils.getDeviceCfg(MainService.this).brightnessDefault)));
                boolean do_brightness = mSharedPreferences.getBoolean("manage_screen_saver_brightness_settings",
                        false);

                if (do_brightness) {
                    Log.i(TAG, "echo \"" + brightness + "\" > "
                            + Utils.getDeviceCfg(MainService.this).brightnessPath);

                    Runtime rt = Runtime.getRuntime();
                    String[] commands = { "su", "-c", "echo \"" + brightness + "\" > "
                            + Utils.getDeviceCfg(MainService.this).brightnessPath };
                    Process proc = rt.exec(commands);

                    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

                    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

                    String s;
                    while ((s = stdInput.readLine()) != null) {
                        System.out.println(s);
                    }
                    while ((s = stdError.readLine()) != null) {
                        System.out.println(s);
                    }
                }
            } catch (IOException | InterruptedException e) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "catch " + e.toString() + " hit in run", e);
                }
            }

            /*PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    "WakeLock");
            wakeLock.acquire();*/
            break;
        default:
            break;
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:org.atricore.josso.tooling.wrapper.InstallCommand.java

protected String getLinuxFlavor() {
    // There's no way to get linux flavor from Java system properties, so we use this 'hack'
    try {/*from  w  w  w .jav a 2s.com*/
        String cmd = "lsb_release -i";
        Runtime run = Runtime.getRuntime();
        Process pr = null;

        pr = run.exec(cmd);
        pr.waitFor();

        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        String result = "";
        while ((line = buf.readLine()) != null) {
            result += line;
        }

        return result;

    } catch (InterruptedException e) {
        logger.warn(e.getMessage());
        if (logger.isDebugEnabled())
            logger.debug(e);
    } catch (IOException e) {
        logger.warn(e.getMessage());
        if (logger.isDebugEnabled())
            logger.debug(e);
    } catch (Exception e) {
        logger.warn(e.getMessage());
        if (logger.isDebugEnabled())
            logger.debug(e);
    }

    return null;

}

From source file:ingestor.SingleFileProcessor.java

private String GetFileHeader(File thisFile) throws InterruptedException, IOException {
    String cmd = "/usr/bin/file " + thisFile.toString();
    logger.info("run command: " + cmd);
    Runtime run = Runtime.getRuntime();
    Process pr = null;//from w w w .  j a va 2 s  . c o m
    pr = run.exec(cmd);
    pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    return buf.readLine();
}

From source file:org.smartfrog.avalanche.client.sf.apps.gt4.gridftp.ConfigureGridFTP.java

public boolean restartInet() throws IOException {
    String os = System.getProperty("os.name");
    Runtime rt = Runtime.getRuntime();

    String cmd = null;//from   w  w w.  j a va 2 s  . c  o m
    Process p = null;
    GFTPConstants gftpConst = new GFTPConstants();
    int osCode = ((Integer) (gftpConst.osNames.get(os))).intValue();
    switch (osCode) {
    case GFTPConstants.LINUX:
        cmd = new String("/etc/rc.d/init.d/inetd restart");
        cmd = cmd.replace('\\', File.separatorChar);
        cmd = cmd.replace('/', File.separatorChar);

        p = rt.exec(cmd);
        try {
            if (p.waitFor() != 0) {
                log.error("Failed to restart inetd");
                return false;
            }
        } catch (InterruptedException ie) {
            log.error(ie);
            return false;
        }
        break;

    case GFTPConstants.HPUX:
        cmd = new String("inetd -c");
        p = rt.exec(cmd);
        try {
            if (p.waitFor() != 0) {
                log.error("Failed to restart inetd");
                return false;
            }
        } catch (InterruptedException ie) {
            log.error(ie);
            return false;
        }
        break;

    default:
        log.error("Currently " + os + " is not supported");
        return false;
    }
    return true;
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

private int losetup(String absoluteFileName, String loDevName) {
    try {//from ww w .  j  a  v a 2s .  c o  m
        Runtime rt = Runtime.getRuntime();
        Process proc = rt
                .exec(new String[] { eucaHome + EUCA_ROOT_WRAPPER, "losetup", loDevName, absoluteFileName });
        StreamConsumer error = new StreamConsumer(proc.getErrorStream());
        StreamConsumer output = new StreamConsumer(proc.getInputStream());
        error.start();
        output.start();
        int errorCode = proc.waitFor();
        output.join();
        LOG.info("losetup " + loDevName + " " + absoluteFileName);
        LOG.info(output.getReturnValue());
        LOG.info(error.getReturnValue());
        return errorCode;
    } catch (Throwable t) {
        LOG.error(t);
    }
    return -1;
}

From source file:it.cnr.icar.eric.client.admin.function.AddUser.java

/**
 * Lets the tool user edit the properties using their favourite
 * editor./*ww  w.j  a v a  2  s . co m*/
 *
 * @param userProps current user properties
 * @return edited user properties
 * @exception Exception if an error occurs
 */
Properties editProperties(Properties userProps) throws Exception {
    String editor = context.getEditor();

    // It should be sufficient to use userProps.store(), but
    // want to output only the known properties in a known order, so
    // do it all in the code.
    File tempFile = File.createTempFile("AddUser", "properties");

    // Property files are always ISO-8859-1, so write properties out
    // using ISO-8859-1 charset.
    Writer fileWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(tempFile), "ISO-8859-1"));

    for (int i = 0; i < propsData.length; i++) {
        String propertyName = (String) propsData[i][0];
        fileWriter.write(propertyName + "=" + userProps.getProperty(propertyName, "") + "\n");
    }

    fileWriter.close();

    if (context.getDebug()) {
        context.printMessage(format(rb, "debug.editor", new Object[] { editor, tempFile.getAbsolutePath() }));
    }

    Runtime r = Runtime.getRuntime();
    String command = editor + " " + tempFile.getAbsolutePath();
    String[] s = command.split("\\s+");

    Process p = r.exec(s);

    int exitStatus = p.waitFor();

    if (exitStatus != 0) {
        throw new AdminException(format(rb, "editFailed"));
    }

    if (context.getDebug()) {
        BufferedReader fileReader = new BufferedReader(new FileReader(tempFile));

        String line;

        while ((line = fileReader.readLine()) != null) {
            context.printMessage(line);
        }

        fileReader.close();
    }

    // Drop old userProps and read new set from tempFile.
    userProps = new Properties();
    userProps.load(new FileInputStream(tempFile));

    boolean tempFileIsDeleted = tempFile.delete();

    if (!tempFileIsDeleted) {
        context.printMessage(format(rb, "couldNotDelete", new Object[] { tempFile.getAbsolutePath() }));
    }

    return userProps;
}

From source file:com.f9g4.webapp.servicesFacade.impl.UploadFacadeApacheCommonsUploadImpl.java

public boolean upload(UploadProperties uploadDetails, int uploadMode, UploadResult result) {
    int exitVal;// w  w  w  . j  a  v  a  2  s. c om
    boolean isFailedProcessing = false;
    //check the folder, if not exist create it.=================
    uploadMode = 3;
    System.out.println("mode ");
    logger.trace("Beginning");

    File folder = new File(profileLocation);
    File folder_100x100 = new File(profileLocation_100);
    File folder_400x400 = new File(profileLocation_400);
    File folder_bigimage = new File(profileLocation_bigimage);
    File folder_source = new File(profileLocation_source);
    //Add folder for files
    File folder_files = new File(profileLocation_files);
    if (!folder.exists())
        folder.mkdir();
    if (!folder_100x100.exists())
        folder_100x100.mkdir();
    if (!folder_400x400.exists())
        folder_400x400.mkdir();
    if (!folder_bigimage.exists())
        folder_bigimage.mkdir();
    if (!folder_source.exists())
        folder_source.mkdir();
    if (!folder_files.exists())
        folder_files.mkdir();

    //      User u = userDAO.getUser(username);

    FileOutputStream fos = null;
    int extIndex = uploadDetails.getFiledata().getOriginalFilename().lastIndexOf('.');
    //fileName = file.name.substr(0, extIndex);
    String original_ext = uploadDetails.getFiledata().getOriginalFilename().substring(extIndex,
            uploadDetails.getFiledata().getOriginalFilename().length());
    //normalize file extension 06/11/2013
    original_ext = original_ext.toLowerCase(); //change to lower case
    if (extIndex != -1 && uploadMode != 3) //skip the ext check when uploadMode is files 
    {
        //if the extension is pdf, then change to AI
        if (original_ext.equals(".pdf"))
            original_ext = ".ai";
        if (original_ext.equals(".jpeg")) //if the extension equals to jpeg, reset to jpg
            original_ext = ".jpg";
    }
    //create filename
    final String uuid = UUID.randomUUID().toString();
    String filename = profileLocation + uuid + original_ext;
    /* 
    this.fileName=uuid + original_ext;
    this.fileName_size_100=UUID.randomUUID().toString()+".jpg";
    this.fileName_size_400=UUID.randomUUID().toString()+".jpg";
    this.fileName_size_original=UUID.randomUUID().toString()+".jpg";
    this.originalFileName = uploadDetails.getFiledata().getOriginalFilename();
    */

    //Set value to UploadResult object
    result.setOriginal_ext(original_ext.replace(".", ""));
    result.setFileName(uuid + original_ext);
    result.setFileName_size_100(UUID.randomUUID().toString() + ".jpg");
    result.setFileName_size_400(UUID.randomUUID().toString() + ".jpg");
    result.setFileName_size_original(UUID.randomUUID().toString() + ".jpg");
    result.setOriginalFileName(uploadDetails.getFiledata().getOriginalFilename());

    try {

        File f = new File(filename);
        if (!f.exists()) {
            f.createNewFile();
        }
        //      
        //         if (!f.exists()){
        //            boolean result = f.mkdir();
        //            
        //            if (!result){
        //               System.out.println("Could not create dir");
        //            }
        //            
        //         }

        //         fos = new FileOutputStream("C:\\Users\\kamlesh\\Downloads\\" + uploadDetails.getFiledata().getOriginalFilename().toUpperCase());
        fos = new FileOutputStream(f);

        fos.write(uploadDetails.getFiledata().getBytes());
        fos.flush();
        fos.close();

        //Convert AI files to Jpeg - use Utility along ghost script
        //decide the parameter by uploadMode
        //Mode==1, no watermark; Mode==2, with watermark; Mode==3, files mode. skip the plmsplitter process.

        String runtimecoomand = "";
        if (uploadMode == 1) {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparameters + " Renderer="
                    + ghostscript;
        } else if (uploadMode == 2) {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparametersWithWatermark
                    + " Renderer=" + ghostscript;
        } else if (uploadMode == 3) {
            // Do not need to run plmsplitter.
            // Move the file to files folder.
            //get file
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_files + result.getFileName());
            temp.renameTo(dest);
            return true;
        } else {
            runtimecoomand = plmsplitter + " " + filename + " " + plmsplitterparametersWithWatermark
                    + " Renderer=" + ghostscript;
        }

        //Process process= Runtime.getRuntime().exec(runtimecoomand);
        logger.trace("COMPLETE");

        //wait the process finish and continue the program.====================
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(runtimecoomand);

            // any error message?
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            exitVal = proc.waitFor();
            //this.uploadStatus=exitVal;
            if (exitVal != 0)
                isFailedProcessing = true;
            else
                isFailedProcessing = false;
        } catch (Throwable t) {
            t.printStackTrace();
            result.setFailedProcessing(true);
            return false;
        }
        /*try
        {
           process.wait();
        }
        catch (Exception e)
        //catch (InterruptedException e) 
        {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/

        logger.trace("READEING FILE LIST");
        File dir = new File(profileLocation);
        FilenameFilter filefilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                //if the file extension is .jpg return true, else false
                return name.matches(".*" + uuid + ".*jpg");
            }
        };
        String[] fileList = dir.list(filefilter);
        if (fileList.length <= 0) //if no thumbnails images are created after plmsplitter, it's failed processing.
        {
            isFailedProcessing = true;
        }
        //create a FilenameFilter and override its accept-method
        if (isFailedProcessing) {
            //create the dummy images to thumbnails folder to occupies the file name.
            //get dummy image file
            File dummyImageFile = new File(dummyImage);
            File dest100 = new File(profileLocation_100 + result.getFileName_size_100());
            File dest400 = new File(profileLocation_400 + result.getFileName_size_400());
            File destOriginalSize = new File(profileLocation_bigimage + result.getFileName_size_original());
            FileUtils.copyFile(dummyImageFile, dest100); //100*100
            FileUtils.copyFile(dummyImageFile, dest400); //400*400
            FileUtils.copyFile(dummyImageFile, destOriginalSize); //original image size
            //move the file to error files folder
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_error_files + result.getFileName());
            temp.renameTo(dest);
        } else {
            //move source files==================================
            //get file
            File temp = new File(filename);
            //create new file
            File dest = new File(profileLocation_source + result.getFileName());
            temp.renameTo(dest);
            //move generated jpg files.
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].matches(".*400x400.*")) {
                    logger.trace("MOVE " + fileList[i] + " to 400x400 folder");
                    //move to 400x400 folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_400 + result.getFileName_size_400());
                    temp.renameTo(dest);
                } else if (fileList[i].matches(".*100x100.*")) {
                    logger.trace("MOVE " + fileList[i] + " to 100x100 folder");
                    //move to 100x100 folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_100 + result.getFileName_size_100());
                    temp.renameTo(dest);
                } else {
                    logger.trace("MOVE " + fileList[i] + " to bigimage folder");
                    //move to original folder
                    //get file
                    temp = new File(profileLocation + fileList[i]);
                    //create new file
                    dest = new File(profileLocation_bigimage + result.getFileName_size_original());
                    temp.renameTo(dest);
                }
            }
        }
        /*Update uploadResult object*/
        result.setUploadStatus(exitVal);
        result.setFailedProcessing(isFailedProcessing);
        return true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Add Runtime to parse the AI files and convert it to jpg    
}

From source file:org.estatio.dscm.services.SyncService.java

@Programmatic
public void saveDisplayAsset(Display display, Asset asset, Runtime rt) {
    String origin = createOriginAssetFilename(asset);
    String destination = createAssetFilename(display, asset);

    File displayAssetFile = new File(destination);
    displayAssetFile.getParentFile().mkdirs();

    String[] execCommand = { "ln", "-s", origin, destination };

    try {/*from   w ww.java2s.c o m*/
        rt.exec(execCommand);
    } catch (IOException IO) {
        // Print the stack trace in an error log
        File errLog = new File(destination.concat(".errorlog"));
        try {
            PrintStream ps = new PrintStream(errLog);
            IO.printStackTrace(ps);
            ps.close();
            errLog.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.salmonllc.ideTools.Tomcat50Engine.java

private void runBrowser(String command, String parms) {
    Runtime r = Runtime.getRuntime();
    String env[] = new String[0];

    try {//from   ww  w. j a  v a  2  s  .  co  m
        _browserProcess = r.exec('"' + command + '"' + (parms == null ? "" : (" " + parms)));
        //_browserProcess = r.exec(command+' ' + (parms == null ? "" : (" " + parms)));
        IDETool.slurpProcessOutput(_browserProcess);
    } catch (IOException e) {
        MessageLog.writeErrorMessage("runBrowser", e, this);
    }
}

From source file:com.panet.imeta.trans.steps.orabulkloader.OraBulkLoader.java

public boolean execute(OraBulkLoaderMeta meta, boolean wait) throws KettleException {
    Runtime rt = Runtime.getRuntime();

    try {/*www .  java  2 s.  com*/
        sqlldrProcess = rt.exec(createCommandLine(meta, true));
        // any error message?
        StreamLogger errorLogger = new StreamLogger(sqlldrProcess.getErrorStream(), "ERROR");

        // any output?
        StreamLogger outputLogger = new StreamLogger(sqlldrProcess.getInputStream(), "OUTPUT");

        // kick them off
        errorLogger.start();
        outputLogger.start();

        if (wait) {
            // any error???
            int exitVal = sqlldrProcess.waitFor();
            sqlldrProcess = null;
            logBasic(Messages.getString("OraBulkLoader.Log.ExitValueSqlldr", "" + exitVal)); //$NON-NLS-1$
            checkExitVal(exitVal);
        }
    } catch (Exception ex) {
        // Don't throw the message upwards, the message contains the password.
        throw new KettleException("Error while executing sqlldr \'" + createCommandLine(meta, false) + "\'");
    }

    return true;
}