Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

In this page you can find the example usage for java.lang ProcessBuilder directory.

Prototype

File directory

To view the source code for java.lang ProcessBuilder directory.

Click Source Link

Usage

From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java

/**
 * Execute the python script that builds MulVAL inputs
 *
 * @return boolean true if the execution was right
 *///from  w  w  w  .ja  v  a  2 s  . c  om
public static boolean prepareMulVALInputs() {
    try {
        //Load python script properties

        String pythonPath = ProjectProperties.getProperty("python-path");
        String mulvalInputScriptFolder = ProjectProperties.getProperty("mulval-input-script-folder");
        String mulvalInputScriptPath = mulvalInputScriptFolder + "main.py";

        String hostInterfacePath = ProjectProperties.getProperty("host-interfaces-path");
        String vlansPath = ProjectProperties.getProperty("vlans-path");
        String routingPath = ProjectProperties.getProperty("routing-path");
        String flowMatrixPath = ProjectProperties.getProperty("flow-matrix-path");
        String vulnerabilityScanPath = ProjectProperties.getProperty("vulnerability-scan-path");
        String mulvalInputPath = ProjectProperties.getProperty("mulval-input");
        String topologyPath = ProjectProperties.getProperty("topology-path");

        File mulvalInputFile = new File(mulvalInputPath);
        if (mulvalInputFile.exists()) {
            mulvalInputFile.delete();
        }

        Logger.getAnonymousLogger().log(Level.INFO, "Genering MulVAL inputs");

        //TODO: use parameter nessus-files-path rather than vulnerability-scan-path, in order to manage when
        // mutliple nessus files are provided.
        ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, mulvalInputScriptPath,
                "--hosts-interfaces-file", hostInterfacePath, "--vlans-file", vlansPath, "--flow-matrix-file",
                flowMatrixPath, "--vulnerability-scan", vulnerabilityScanPath, "--routing-file", routingPath,
                "--mulval-output-file", mulvalInputFile.getAbsolutePath(), "--to-fiware-xml-topology",
                topologyPath);
        processBuilder.directory(new File(mulvalInputScriptFolder));
        StringBuilder command = new StringBuilder();
        for (String str : processBuilder.command())
            command.append(str + " ");
        Logger.getAnonymousLogger().log(Level.INFO,
                "Launch generation of MulVAL inputs with command : \n" + command.toString());
        processBuilder.redirectOutput(
                new File(ProjectProperties.getProperty("output-path") + "/input-generation.log"));
        processBuilder.redirectError(
                new File(ProjectProperties.getProperty("output-path") + "/input-generation.log"));
        Process process = processBuilder.start();
        process.waitFor();

        if (!mulvalInputFile.exists()) {
            Logger.getAnonymousLogger().log(Level.WARNING,
                    "A problem happened in the generation of mulval inputs");
            return false;
        }

        return true;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:autoupdater.DownloadLatestZipFromRepo.java

/**
 * Simple jar launch through a {@code ProcessBuilder}.
 *
 * @param downloadedFile the downloaded jar file to start
 * @param args           the args to give to the jar file
 * @return true if the launch succeeded//from   ww w  .  ja v a 2 s  .  c o  m
 * @throws IOException if the process could not start
 */
private static Process launchJar(MavenJarFile downloadedFile, String[] args)
        throws NullPointerException, IOException {
    Process jar;
    ProcessBuilder p;
    List<String> processToRun = new ArrayList<String>();
    try {
        processToRun.add("java");
        processToRun.add("-jar");
        processToRun.add(downloadedFile.getAbsoluteFilePath());
        if (args != null) {
            processToRun.addAll(Arrays.asList(args));
        }
        p = new ProcessBuilder(processToRun);
        p.directory(new File(downloadedFile.getAbsoluteFilePath()).getParentFile());
        jar = p.start();
    } catch (NullPointerException npe) {
        throw new IOException("could not start the jar");
    }
    return jar;
}

From source file:org.exist.launcher.Launcher.java

protected static void run(List<String> args, BiConsumer<Integer, String> consumer) {
    final ProcessBuilder pb = new ProcessBuilder(args);
    final Optional<Path> home = ConfigurationHelper.getExistHome();
    if (home.isPresent()) {
        pb.directory(home.get().toFile());
    }//from  ww w  . j a  v  a  2s.c o m
    pb.redirectErrorStream(true);
    try {
        final Process process = pb.start();
        if (consumer != null) {
            final StringBuilder output = new StringBuilder();
            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append('\n').append(line);
                }
            }
            final int exitValue = process.waitFor();
            consumer.accept(exitValue, output.toString());
        }
    } catch (IOException | InterruptedException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error Running Process", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

public static boolean deleteStudy(String studyUID) {
    InputStream is = null;//  w  w  w.  j  a va  2s  .c o m
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;
    try {
        log.info("Deleting study " + studyUID + " files - command: ./dcmdeleteStudy " + studyUID);

        String[] command = { "./dcmdeleteStudy", studyUID };

        ProcessBuilder pb = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteStudy");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteStudy");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        pb.directory(new File(dicomScriptsDir));

        Process process = pb.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            log.info("./dcmdeleteStudy: " + line);
            sb.append(line).append("\n");
        }

        try {
            int exitValue = process.waitFor();
            log.info("DICOM delete study exit value is: " + exitValue);
            if (exitValue == 0)
                success = true;
        } catch (Exception e) {
            log.warning("Failed to delete DICOM study " + studyUID, e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (Exception e) {
        log.warning("Failed to delete DICOM study " + studyUID, e);
    }
    return success;
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

/**
 * TODO This does not work. The ./dcmdeleteSeries script invoked the dcm4chee twiddle command but it appears that the
 * moveSeriesToTrash operation it calls has no effect in this version of dcm4chee. See:
 * http://www.dcm4che.org/jira/browse/WEB-955
 *//*from  w  ww.ja va2s  .c o  m*/
public static boolean deleteSeries(String seriesUID, String seriesPk) {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;

    try {
        log.info("Deleting series " + seriesUID + " seriesPK:" + seriesPk);

        String[] command = { "./dcmdeleteSeries", seriesPk, EPADConfig.xnatUploadProjectPassword };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteSeries");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteSeries");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        processBuilder.directory(new File(dicomScriptsDir));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmdeleteSeries: " + line);
        }
        try {
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                log.info("Deleted DICOM series " + seriesUID + " pk:" + seriesPk);
                success = true;
            } else {
                log.warning("Failed to delete DICOM series " + seriesUID + " pk=" + seriesPk + "; exitValue="
                        + exitValue + "\n" + sb.toString());
            }
        } catch (Exception e) {
            log.warning("Failed to delete DICOM series " + seriesUID, e);
        }

        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (IOException e) {
        log.warning("Failed to delete DICOM series " + seriesUID, e);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
    return success;
}

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Extract an attachment/*from  ww w  . jav a 2 s  .  c om*/
 *
 * @param attachment the attachment to extract
 * @param setImage true, if a set image should be extracted; in this case ".set" is append before file extension
 * @param counter a counter (only used for NFOs cause there may be multiple NFOs in one file)
 * @return
 */
private static File extractAttachment(Attachment attachment) {
    File sourceFile = attachment.getSourceFile();
    if (sourceFile == null) {
        // source file must exist
        return null;
    } else if (!sourceFile.exists()) {
        // source file must exist
        return null;
    }

    // build return file name
    StringBuilder returnFileName = new StringBuilder();
    returnFileName.append(tempDirectory.getAbsolutePath());
    returnFileName.append(File.separatorChar);
    returnFileName.append(FilenameUtils.removeExtension(sourceFile.getName()));
    // add attachment id so the extracted file becomes unique per movie file
    returnFileName.append(".");
    returnFileName.append(attachment.getAttachmentId());

    switch (attachment.getContentType()) {
    case NFO:
        returnFileName.append(".nfo");
        break;
    case POSTER:
    case FANART:
    case BANNER:
    case SET_POSTER:
    case SET_FANART:
    case SET_BANNER:
    case VIDEOIMAGE:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    default:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    }

    File returnFile = new File(returnFileName.toString());
    if (returnFile.exists() && (returnFile.lastModified() >= sourceFile.lastModified())) {
        // already present or extracted
        LOG.debug("File to extract already exists; no extraction needed");
        return returnFile;
    }

    LOG.trace("Extract attachement ({})", attachment);
    try {
        // Create the command line
        List<String> commandMedia = new ArrayList<>(MT_EXTRACT_EXE);
        commandMedia.add("attachments");
        commandMedia.add(sourceFile.getAbsolutePath());
        commandMedia.add(attachment.getAttachmentId() + ":" + returnFileName.toString());

        ProcessBuilder pb = new ProcessBuilder(commandMedia);
        pb.directory(MT_PATH);
        Process p = pb.start();

        if (p.waitFor() != 0) {
            LOG.error("Error during extraction - ErrorCode={}", p.exitValue());
            returnFile = null;
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
        returnFile = null;
    }

    if (returnFile != null) {
        if (returnFile.exists()) {
            // need to reset last modification date to last modification date
            // of source file to fulfill later checks
            try {
                returnFile.setLastModified(sourceFile.lastModified());
            } catch (Exception ignore) {
                // nothing to do anymore
            }
        } else {
            // reset return file to null if not existent
            returnFile = null;
        }
    }
    return returnFile;
}

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Scans a matroska movie file for attachments.
 *
 * @param movieFile the movie file to scan
 *//*  w w  w  . java 2  s .  c o m*/
private static void scanAttachments(MovieFile movieFile) {
    if (movieFile.isAttachmentsScanned()) {
        // attachments has been scanned during rescan of movie
        return;
    }

    // clear existing attachments
    movieFile.clearAttachments();

    // the file with possible attachments
    File scanFile = movieFile.getFile();

    LOG.debug("Scanning file {}", scanFile.getName());
    int attachmentId = 0;
    try {
        // create the command line
        List<String> commandMkvInfo = new ArrayList<>(MT_INFO_EXE);
        commandMkvInfo.add(scanFile.getAbsolutePath());

        ProcessBuilder pb = new ProcessBuilder(commandMkvInfo);

        // set up the working directory.
        pb.directory(MT_PATH);

        Process p = pb.start();

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = localInputReadLine(input);
        while (line != null) {
            if (line.contains("+ Attached")) {
                // increase the attachment id
                attachmentId++;
                // next line contains file name
                String fileNameLine = localInputReadLine(input);
                // next line contains MIME type
                String mimeTypeLine = localInputReadLine(input);

                Attachment attachment = createAttachment(attachmentId, fileNameLine, mimeTypeLine,
                        movieFile.getFirstPart(), movieFile.getLastPart());
                if (attachment != null) {
                    attachment.setSourceFile(movieFile.getFile());
                    movieFile.addAttachment(attachment);
                }
            }

            line = localInputReadLine(input);
        }

        if (p.waitFor() != 0) {
            LOG.error("Error during attachment retrieval - ErrorCode={}", p.exitValue());
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
    }

    // attachments has been scanned; no double scan of attachments needed
    movieFile.setAttachmentsScanned(Boolean.TRUE);
}

From source file:jeplus.EPlusWinTools.java

public static String runJavaProgram(final String dir, final String jar, final String[] cmdline) {
    List<String> command = new ArrayList<>();
    command.add("java");
    command.add("-jar");
    command.add(dir + (dir.endsWith(File.separator) ? "" : File.separator) + jar);
    command.addAll(Arrays.asList(cmdline));
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(new File(dir));
    builder.redirectErrorStream(true);//from w  ww . j a  va2s .c o  m
    try {
        Process proc = builder.start();
        // int ExitValue = proc.waitFor();
        StringBuilder buf = new StringBuilder();
        try (BufferedReader ins = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
            String res = ins.readLine();
            while (res != null) {
                buf.append(res);
                res = ins.readLine();
            }
        }
        if (proc.exitValue() != 0) {
            return "Error: " + buf.toString();
        }
        return buf.toString();
    } catch (IOException ex) {
        logger.error("Cannot run Java program.", ex);
    }
    return "Error: failed to run the specified Java program.";
}

From source file:com.github.born2snipe.project.setup.scm.GitRepoInitializer.java

private void executeCommandIn(File projectDir, String... commands) {
    try {/* w  w w .ja  v  a2 s  . com*/
        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.directory(projectDir);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        System.out.println(IOUtils.toString(process.getInputStream()));
        process.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.dickthedeployer.dick.web.service.CommandService.java

public String invoke(Path workingDir, String... command) throws RuntimeException {
    try {//  w w  w  . j a  va 2 s.  c o  m
        log.info("Executing command {} in path {}", Arrays.toString(command), workingDir.toString());
        StringBuilder text = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(workingDir.toFile());
        builder.redirectErrorStream(true);

        Process process = builder.start();

        try (Scanner s = new Scanner(process.getInputStream())) {
            while (s.hasNextLine()) {
                text.append(s.nextLine());
            }
            int result = process.waitFor();
            log.info("Process exited with result {} and output {}", result, text);

            if (result != 0) {
                throw new CommandExecutionException();
            }
            return text.toString();
        }
    } catch (IOException | InterruptedException ex) {
        throw new CommandExecutionException(ex);
    }
}