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:com.lenovo.tensorhusky.common.utils.Shell.java

/**
 * Run a command/*from ww w .  j  a v a 2 s  .  c  o m*/
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    final BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled. the stream draining thread will attempt to
            // drain that fd!! it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            // issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:org.apache.nifi.processors.standard.ExecuteStreamCommand.java

@Override
public void onTrigger(ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile inputFlowFile = session.get();
    if (null == inputFlowFile) {
        return;/* ww  w  .  j a  v a2s  .c o m*/
    }

    final ArrayList<String> args = new ArrayList<>();
    final boolean putToAttribute = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).isSet();
    final Integer attributeSize = context.getProperty(PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
    final String attributeName = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).getValue();

    final String executeCommand = context.getProperty(EXECUTION_COMMAND)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    args.add(executeCommand);
    final String commandArguments = context.getProperty(EXECUTION_ARGUMENTS)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    final boolean ignoreStdin = Boolean.parseBoolean(context.getProperty(IGNORE_STDIN).getValue());
    if (!StringUtils.isBlank(commandArguments)) {
        for (String arg : ArgumentUtils.splitArgs(commandArguments,
                context.getProperty(ARG_DELIMITER).getValue().charAt(0))) {
            args.add(arg);
        }
    }
    final String workingDir = context.getProperty(WORKING_DIR).evaluateAttributeExpressions(inputFlowFile)
            .getValue();

    final ProcessBuilder builder = new ProcessBuilder();

    logger.debug("Executing and waiting for command {} with arguments {}",
            new Object[] { executeCommand, commandArguments });
    File dir = null;
    if (!StringUtils.isBlank(workingDir)) {
        dir = new File(workingDir);
        if (!dir.exists() && !dir.mkdirs()) {
            logger.warn("Failed to create working directory {}, using current working directory {}",
                    new Object[] { workingDir, System.getProperty("user.dir") });
        }
    }
    final Map<String, String> environment = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (entry.getKey().isDynamic()) {
            environment.put(entry.getKey().getName(), entry.getValue());
        }
    }
    builder.environment().putAll(environment);
    builder.command(args);
    builder.directory(dir);
    builder.redirectInput(Redirect.PIPE);
    builder.redirectOutput(Redirect.PIPE);
    final Process process;
    try {
        process = builder.start();
    } catch (IOException e) {
        logger.error("Could not create external process to run command", e);
        throw new ProcessException(e);
    }
    try (final OutputStream pos = process.getOutputStream();
            final InputStream pis = process.getInputStream();
            final InputStream pes = process.getErrorStream();
            final BufferedInputStream bis = new BufferedInputStream(pis);
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pes))) {
        int exitCode = -1;
        final BufferedOutputStream bos = new BufferedOutputStream(pos);
        FlowFile outputFlowFile = putToAttribute ? inputFlowFile : session.create(inputFlowFile);

        ProcessStreamWriterCallback callback = new ProcessStreamWriterCallback(ignoreStdin, bos, bis, logger,
                attributeName, session, outputFlowFile, process, putToAttribute, attributeSize);
        session.read(inputFlowFile, callback);

        outputFlowFile = callback.outputFlowFile;
        if (putToAttribute) {
            outputFlowFile = session.putAttribute(outputFlowFile, attributeName,
                    new String(callback.outputBuffer, 0, callback.size));
        }

        exitCode = callback.exitCode;
        logger.debug("Execution complete for command: {}.  Exited with code: {}",
                new Object[] { executeCommand, exitCode });

        Map<String, String> attributes = new HashMap<>();

        final StringBuilder strBldr = new StringBuilder();
        try {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                strBldr.append(line).append("\n");
            }
        } catch (IOException e) {
            strBldr.append("Unknown...could not read Process's Std Error");
        }
        int length = strBldr.length() > 4000 ? 4000 : strBldr.length();
        attributes.put("execution.error", strBldr.substring(0, length));

        final Relationship outputFlowFileRelationship = putToAttribute ? ORIGINAL_RELATIONSHIP
                : OUTPUT_STREAM_RELATIONSHIP;
        if (exitCode == 0) {
            logger.info("Transferring flow file {} to {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName() });
        } else {
            logger.error("Transferring flow file {} to {}. Executable command {} ended in an error: {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName(), executeCommand,
                            strBldr.toString() });
        }

        attributes.put("execution.status", Integer.toString(exitCode));
        attributes.put("execution.command", executeCommand);
        attributes.put("execution.command.args", commandArguments);
        outputFlowFile = session.putAllAttributes(outputFlowFile, attributes);

        // This transfer will transfer the FlowFile that received the stream out put to it's destined relationship.
        // In the event the stream is put to the an attribute of the original, it will be transferred here.
        session.transfer(outputFlowFile, outputFlowFileRelationship);

        if (!putToAttribute) {
            logger.info("Transferring flow file {} to original", new Object[] { inputFlowFile });
            inputFlowFile = session.putAllAttributes(inputFlowFile, attributes);
            session.transfer(inputFlowFile, ORIGINAL_RELATIONSHIP);
        }

    } catch (final IOException ex) {
        // could not close Process related streams
        logger.warn("Problem terminating Process {}", new Object[] { process }, ex);
    } finally {
        process.destroy(); // last ditch effort to clean up that process.
    }
}

From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java

protected void decompressTile(final File outputFile, int jp2TileX, int jp2TileY) throws IOException {
    final int tileIndex = tileLayout.numXTiles * jp2TileY + jp2TileX;

    ProcessBuilder builder;

    if (S2Config.OPJ_DECOMPRESSOR_EXE != null) {
        if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) {
            String inputFileName = Utils.GetIterativeShortPathName(imageFile.getPath());
            String outputFileName = outputFile.getPath();

            if (inputFileName.length() == 0) {
                inputFileName = imageFile.getPath();
            }//www.j a  v  a 2 s.  com

            Guardian.assertTrue("Image file exists", new File(inputFileName).exists());

            builder = new ProcessBuilder(S2Config.OPJ_DECOMPRESSOR_EXE, "-i", inputFileName, "-o",
                    outputFileName, "-r", getLevel() + "", "-t", tileIndex + "");
        } else {
            SystemUtils.LOG.fine("Writing to " + outputFile.getPath());

            Guardian.assertTrue("Image file exists", imageFile.exists());

            builder = new ProcessBuilder(S2Config.OPJ_DECOMPRESSOR_EXE, "-i", imageFile.getPath(), "-o",
                    outputFile.getPath(), "-r", getLevel() + "", "-t", tileIndex + "");
        }
    } else {
        throw new UnexpectedException("OpenJpeg decompressor is not set");
    }

    builder = builder.directory(cacheDir);

    try {
        builder.redirectErrorStream(true);
        CommandOutput result = OpenJpegUtils.runProcess(builder);

        final int exitCode = result.getErrorCode();
        if (exitCode != 0) {
            SystemUtils.LOG.severe(String.format(
                    "Failed to uncompress tile: %s, exitCode = %d, command = [%s], command stdoutput = [%s], command stderr = [%s]",
                    imageFile.getPath(), exitCode, builder.command().toString(), result.getTextOutput(),
                    result.getErrorOutput()));
        }
    } catch (InterruptedException e) {
        SystemUtils.LOG.severe("Process was interrupted, InterruptedException: " + e.getMessage());
    }
}

From source file:org.pshdl.model.simulation.codegenerator.DartCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {/*from   w ww  . j ava2 s  .c o  m*/
        IHDLInterpreterFactory<NativeRunner> _xblockexpression = null;
        {
            final String dartCode = this.generateMainCode();
            final File binDir = new File(tempDir, "bin");
            boolean _mkdirs = binDir.mkdirs();
            boolean _not = (!_mkdirs);
            if (_not) {
                throw new IllegalArgumentException(("Failed to create Directory " + binDir));
            }
            File _file = new File(binDir, "dut.dart");
            Files.write(dartCode, _file, StandardCharsets.UTF_8);
            final File testRunnerDir = new File(DartCodeGenerator.TESTRUNNER_DIR);
            final File testRunner = new File(testRunnerDir, "bin/darttestrunner.dart");
            String _name = testRunner.getName();
            File _file_1 = new File(binDir, _name);
            Files.copy(testRunner, _file_1);
            final File yaml = new File(testRunnerDir, "pubspec.yaml");
            String _name_1 = yaml.getName();
            File _file_2 = new File(tempDir, _name_1);
            Files.copy(yaml, _file_2);
            File _file_3 = new File(binDir, "packages");
            Path _path = _file_3.toPath();
            File _file_4 = new File(testRunnerDir, "packages");
            Path _path_1 = _file_4.toPath();
            java.nio.file.Files.createSymbolicLink(_path, _path_1);
            File _file_5 = new File(tempDir, "packages");
            Path _path_2 = _file_5.toPath();
            File _file_6 = new File(testRunnerDir, "packages");
            Path _path_3 = _file_6.toPath();
            java.nio.file.Files.createSymbolicLink(_path_2, _path_3);
            _xblockexpression = new IHDLInterpreterFactory<NativeRunner>() {
                public NativeRunner newInstance() {
                    try {
                        String _name = testRunner.getName();
                        String _plus = ("bin/" + _name);
                        ProcessBuilder _processBuilder = new ProcessBuilder(DartCodeGenerator.DART_EXEC, _plus,
                                DartCodeGenerator.this.unitName, DartCodeGenerator.this.library);
                        ProcessBuilder _directory = _processBuilder.directory(tempDir);
                        ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
                        final Process dartRunner = _redirectErrorStream.start();
                        InputStream _inputStream = dartRunner.getInputStream();
                        OutputStream _outputStream = dartRunner.getOutputStream();
                        return new NativeRunner(_inputStream, _outputStream, DartCodeGenerator.this.em,
                                dartRunner, 5, ((("Dart " + DartCodeGenerator.this.library) + ".")
                                        + DartCodeGenerator.this.unitName));
                    } catch (Throwable _e) {
                        throw Exceptions.sneakyThrow(_e);
                    }
                }
            };
        }
        return _xblockexpression;
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.openbi.kettle.plugins.refreshtableauextract.RefreshTableauExtract.java

public Result execute(Result previousResult, int nr) throws KettleException {
    Result result = previousResult;
    result.setResult(validate());/*from w w w  . j  a v  a2  s  .  c o m*/
    if (!result.getResult()) {
        return result;
    }
    String[] commands;
    String tableauCommand = getRealValue(getTableauClient()).trim();
    if (tableauCommand.toLowerCase().endsWith(".exe")) {
        tableauCommand = tableauCommand.substring(0, tableauCommand.length() - 4);
    }
    tableauCommand = "\"" + tableauCommand + "\"";
    if (getRefreshType() == 0 || getRefreshType() == 1) {
        tableauCommand += " refreshextract";
    } else if (getRefreshType() == 2) {
        tableauCommand += " addfiletoextract";
    } else {
        logError(BaseMessages.getString(PKG, "RefreshTableauExtract.Error.InvalidRefreshType"));
        result.setResult(false);
        return result;
    }

    tableauCommand += " --server " + protocolList[getProtocol()] + "://" + getRealValue(getServer());
    if (getRealValue(getServerPort()) != null && !getRealValue(getServerPort()).isEmpty()) {
        tableauCommand += ":" + getRealValue(getServerPort());
    }

    tableauCommand += " --username " + getRealValue(getServerUser());
    tableauCommand += " --password " + getRealValue(getServerPassword());
    tableauCommand += " --datasource \"" + getRealValue(getDataSource()) + "\"";

    if (getRealValue(getSiteName()) != null && !getRealValue(getSiteName()).isEmpty()) {
        tableauCommand += " --site \"" + getRealValue(getSiteName()) + "\"";
    }
    if (getRealValue(getProject()) != null && !getRealValue(getProject()).isEmpty()) {
        tableauCommand += " --project \"" + getRealValue(getProject()) + "\"";
    }
    if (getRealValue(getProxyUser()) != null && !getRealValue(getProxyUser()).isEmpty()) {
        tableauCommand += " --proxy-username " + getRealValue(getProxyUser());
    }
    if (getRealValue(getProxyPassword()) != null && !getRealValue(getProxyPassword()).isEmpty()) {
        tableauCommand += " --proxy-password " + getRealValue(getProxyPassword());
    }

    if (getRefreshType() == 0) {
        commands = new String[1];
        tableauCommand += " --original-file \"" + getRealValue(getExtractFile()) + "\"";
        commands[0] = new String(tableauCommand);
    } else if (getRefreshType() == 1) {
        commands = new String[1];
        if (getFullRefresh()) {
            tableauCommand += " --force-full-refresh";
        }
        if (getRealValue(getSourceUser()) != null && !getRealValue(getSourceUser()).isEmpty()) {
            tableauCommand += " --source-username " + getRealValue(getSourceUser());
        }
        if (getRealValue(getSourcePassword()) != null & !getRealValue(getSourcePassword()).isEmpty()) {
            tableauCommand += " --source-password " + getRealValue(getSourcePassword());
        }
        commands[0] = new String(tableauCommand);
    } else {
        String[] fileStrings = null;
        if (processResultFiles) {
            if (result != null && previousResult.getResultFiles().size() > 0) {

                int size = previousResult.getResultFiles().size();
                if (log.isBasic()) {
                    logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FilesFound", "" + size));
                }
                try {
                    List<ResultFile> resultFiles = previousResult.getResultFilesList();
                    List<String> files = new ArrayList<String>();
                    Iterator<ResultFile> it = resultFiles.iterator();
                    while (it.hasNext()) {
                        ResultFile f = it.next();
                        FileObject o = f.getFile();
                        if (o.getType().equals(FileType.FILE)) {
                            if (o.exists()) {
                                files.add(o.getName().toString().startsWith("file:///")
                                        ? o.getName().toString().substring(8)
                                        : o.getName().toString());
                            } else {
                                logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.FileNotExist",
                                        "" + o.getName()));
                            }
                        } else {
                            logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.ResultNotFile",
                                    "" + o.getName()));
                        }
                    }
                    if (files.size() > 0) {
                        Iterator<String> ite = files.iterator();
                        fileStrings = new String[files.size()];
                        int i = 0;
                        while (ite.hasNext()) {
                            fileStrings[i] = ite.next();
                            i++;
                        }

                    } else {
                        logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult"));
                        result.setResult(true);
                        return result;
                    }
                } catch (Exception ex) {
                    logError(ex.toString());
                    result.setResult(false);
                    return result;
                }
            } else {
                logBasic(BaseMessages.getString(PKG, "RefreshTableauExtract.NoFilesOnResult"));
                result.setResult(true);
                return result;
            }
        } else {
            // Get source and destination files, also wildcard
            String[] vFilePaths = filePaths;
            String[] vWildcards = wildcards;
            boolean[] includeSubfolders = new boolean[vFilePaths.length];
            String[] fileRequired = new String[vFilePaths.length];

            for (int i = 0; i < includeSubfolders.length; i++) {
                includeSubfolders[i] = false;
            }
            FileInputList files = FileInputList.createFileList(this, vFilePaths, vWildcards, fileRequired,
                    includeSubfolders);
            fileStrings = new String[files.getFileStrings().length];
            fileStrings = files.getFileStrings();
        }
        commands = new String[fileStrings.length];
        for (int i = 0; i < fileStrings.length; i++) {
            commands[i] = new String(tableauCommand + " --file \"" + fileStrings[i] + "\"");
        }
    }

    FileObject fileObject = null;
    String realScript = "";
    FileObject tempFile = null;

    for (int i = 0; i < commands.length; i++) {
        //    realScript+="echo Running: "+commands[i]+"\n";
        realScript += commands[i] + "\n";
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.Commands", commands[i]));
        }
    }
    try {
        // What's the exact command?
        String[] command;

        if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "RefreshTableuaExtract.RunningOn", Const.getOS()));
        }

        if (Const.getOS().equals("Windows 95")) {
            //base = new String[] { "command.com", "/C" };
            tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { "command.com", "/C",
                    "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" };
        } else if (Const.getOS().startsWith("Windows")) {
            //base = new String[] { "cmd.exe", "/C" };
            tempFile = KettleVFS.createTempFile("kettle", "shell.bat", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { "cmd.exe", "/C",
                    "\"" + Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) + "\"" };
        } else {
            tempFile = KettleVFS.createTempFile("kettle", "shell", null, this);
            fileObject = createTemporaryShellFile(tempFile, realScript);
            command = new String[] { Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject)) };
        }

        ProcessBuilder pb = new ProcessBuilder(command);

        Map<String, String> env = pb.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkingDirectory() != null && !Const.isEmpty(Const.rtrim(getRealValue(getWorkingDirectory())))) {
            String vfsFilename = environmentSubstitute(getRealValue(getWorkingDirectory()));
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this)));
            pb.directory(file);
        }

        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandStarted"));
        }
        Process proc = pb.start();
        // any error message?
        StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)");

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

        proc.waitFor();

        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "RefreshTableauExtract.CommandFinished"));
        }
        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            logError(BaseMessages.getString(PKG, "RefreshTableauExtract.ExitStatus",
                    "" + result.getExitStatus()));
            result.setResult(false);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (Exception ex) {
        logError(ex.toString());
        result.setResult(false);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                BaseMessages.getString(PKG, "RefreshTableauExtract.UnexpectedError", tempFile.toString(),
                        e.toString());
            }
        }
    }

    return result;

}

From source file:org.codehaus.enunciate.modules.amf.AMFDeploymentModule.java

/**
 * Invokes the flex compiler on the apps specified in the configuration file.
 *///from   w  w  w. j av a  2 s. c o  m
protected void doFlexCompile() throws EnunciateException, IOException {
    File swcFile = null;
    File asSources = null;
    Enunciate enunciate = getEnunciate();
    if (isSwcDownloadable() || !flexApps.isEmpty()) {
        if (this.flexHome == null) {
            throw new EnunciateException(
                    "To compile a flex app you must specify the Flex SDK home directory, either in configuration, by setting the FLEX_HOME environment variable, or setting the 'flex.home' system property.");
        }

        File flexHomeDir = new File(this.flexHome);
        if (!flexHomeDir.exists()) {
            throw new EnunciateException("Flex home not found ('" + flexHomeDir.getAbsolutePath() + "').");
        }

        File javaBinDir = new File(System.getProperty("java.home"), "bin");
        File javaExecutable = new File(javaBinDir, "java");
        if (!javaExecutable.exists()) {
            //append the "exe" for windows users.
            javaExecutable = new File(javaBinDir, "java.exe");
        }

        String javaCommand = javaExecutable.getAbsolutePath();
        if (!javaExecutable.exists()) {
            warn("No java executable found in %s.  We'll just hope the environment is set up to execute 'java'...",
                    javaBinDir.getAbsolutePath());
            javaCommand = "java";
        }

        int compileCommandIndex;
        int outputFileIndex;
        int sourcePathIndex;
        int mainMxmlPathIndex;
        List<String> commandLine = new ArrayList<String>();
        int argIndex = 0;
        commandLine.add(argIndex++, javaCommand);
        for (String jvmarg : this.compilerConfig.getJVMArgs()) {
            commandLine.add(argIndex++, jvmarg);
        }
        commandLine.add(argIndex++, "-cp");
        File flexHomeLib = new File(flexHomeDir, "lib");
        if (!flexHomeLib.exists()) {
            throw new EnunciateException("File not found: " + flexHomeLib);
        } else {
            StringBuilder builder = new StringBuilder();
            Iterator<File> flexLibIt = Arrays.asList(flexHomeLib.listFiles()).iterator();
            while (flexLibIt.hasNext()) {
                File flexJar = flexLibIt.next();
                if (flexJar.getAbsolutePath().endsWith("jar")) {
                    builder.append(flexJar.getAbsolutePath());
                    if (flexLibIt.hasNext()) {
                        builder.append(File.pathSeparatorChar);
                    }
                } else {
                    debug("File %s will not be included on the classpath because it's not a jar.", flexJar);
                }
            }
            commandLine.add(argIndex++, builder.toString());
        }

        compileCommandIndex = argIndex;
        commandLine.add(argIndex++, null);

        commandLine.add(argIndex++, "-output");
        outputFileIndex = argIndex;
        commandLine.add(argIndex++, null);

        if (compilerConfig.getFlexConfig() == null) {
            compilerConfig.setFlexConfig(new File(new File(flexHome, "frameworks"), "flex-config.xml"));
        }

        if (compilerConfig.getFlexConfig().exists()) {
            commandLine.add(argIndex++, "-load-config");
            commandLine.add(argIndex++, compilerConfig.getFlexConfig().getAbsolutePath());
        } else {
            warn("Configured flex configuration file %s doesn't exist.  Ignoring...",
                    compilerConfig.getFlexConfig());
        }

        if (compilerConfig.getContextRoot() == null) {
            if (getEnunciate().getConfig().getLabel() != null) {
                compilerConfig.setContextRoot("/" + getEnunciate().getConfig().getLabel());
            } else {
                compilerConfig.setContextRoot("/enunciate");
            }
        }

        commandLine.add(argIndex++, "-compiler.context-root");
        commandLine.add(argIndex++, compilerConfig.getContextRoot());

        if (compilerConfig.getLocale() != null) {
            commandLine.add(argIndex++, "-compiler.locale");
            commandLine.add(argIndex++, compilerConfig.getLocale());
        }

        if (compilerConfig.getLicenses().size() > 0) {
            commandLine.add(argIndex++, "-licenses.license");
            for (License license : compilerConfig.getLicenses()) {
                commandLine.add(argIndex++, license.getProduct());
                commandLine.add(argIndex++, license.getSerialNumber());
            }
        }

        if (compilerConfig.getOptimize() != null && compilerConfig.getOptimize()) {
            commandLine.add(argIndex++, "-compiler.optimize");
        }

        if (compilerConfig.getDebug() != null && compilerConfig.getDebug()) {
            commandLine.add(argIndex++, "-compiler.debug=true");
        }

        if (compilerConfig.getStrict() != null && compilerConfig.getStrict()) {
            commandLine.add(argIndex++, "-compiler.strict");
        }

        if (compilerConfig.getUseNetwork() != null && compilerConfig.getUseNetwork()) {
            commandLine.add(argIndex++, "-use-network");
        }

        if (compilerConfig.getIncremental() != null && compilerConfig.getIncremental()) {
            commandLine.add(argIndex++, "-compiler.incremental");
        }

        if (compilerConfig.getShowActionscriptWarnings() != null
                && compilerConfig.getShowActionscriptWarnings()) {
            commandLine.add(argIndex++, "-show-actionscript-warnings");
        }

        if (compilerConfig.getShowBindingWarnings() != null && compilerConfig.getShowBindingWarnings()) {
            commandLine.add(argIndex++, "-show-binding-warnings");
        }

        if (compilerConfig.getShowDeprecationWarnings() != null
                && compilerConfig.getShowDeprecationWarnings()) {
            commandLine.add(argIndex++, "-show-deprecation-warnings");
        }

        for (String arg : this.compilerConfig.getArgs()) {
            commandLine.add(argIndex++, arg);
        }

        commandLine.add(argIndex++, "-compiler.services");
        File xmlGenerateDir = getXMLGenerateDir();
        commandLine.add(argIndex++, new File(xmlGenerateDir, "merged-services-config.xml").getAbsolutePath());

        commandLine.add(argIndex, "-include-sources");
        File clientSideGenerateDir = getClientSideGenerateDir();
        commandLine.add(argIndex + 1, clientSideGenerateDir.getAbsolutePath());

        String swcName = getSwcName();

        if (swcName == null) {
            String label = "enunciate";
            if (getLabel() != null) {
                label = getLabel();
            } else if ((enunciate.getConfig() != null) && (enunciate.getConfig().getLabel() != null)) {
                label = enunciate.getConfig().getLabel();
            }

            swcName = label + "-as3-client.swc";
        }

        File swcCompileDir = getSwcCompileDir();
        swcFile = new File(swcCompileDir, swcName);
        boolean swcUpToDate = swcFile.exists() && enunciate.isUpToDate(xmlGenerateDir, swcCompileDir)
                && enunciate.isUpToDate(clientSideGenerateDir, swcCompileDir);

        if (!swcUpToDate) {
            commandLine.set(compileCommandIndex, compilerConfig.getSwcCompileCommand());
            commandLine.set(outputFileIndex, swcFile.getAbsolutePath());
            debug("Compiling %s for the client-side ActionScript classes...", swcFile.getAbsolutePath());
            if (enunciate.isDebug()) {
                StringBuilder command = new StringBuilder();
                for (String commandPiece : commandLine) {
                    command.append(' ').append(commandPiece);
                }
                debug("Executing SWC compile for client-side actionscript with the command: %s", command);
            }
            compileSwc(commandLine);
        } else {
            info("Skipping compilation of %s as everything appears up-to-date...", swcFile.getAbsolutePath());
        }

        //swc is compiled
        while (commandLine.size() > argIndex) {
            //remove the compc-specific options...
            commandLine.remove(argIndex);
        }

        if (compilerConfig.getProfile() != null && compilerConfig.getProfile()) {
            commandLine.add(argIndex++, "-compiler.profile");
        }

        if (compilerConfig.getWarnings() != null && compilerConfig.getWarnings()) {
            commandLine.add(argIndex++, "-warnings");
        }

        commandLine.add(argIndex++, "-source-path");
        commandLine.add(argIndex++, clientSideGenerateDir.getAbsolutePath());

        commandLine.add(argIndex++, "-source-path");
        sourcePathIndex = argIndex;
        commandLine.add(argIndex++, null);

        commandLine.add(argIndex++, "--");
        mainMxmlPathIndex = argIndex;
        commandLine.add(argIndex++, null);

        commandLine.set(compileCommandIndex, compilerConfig.getFlexCompileCommand());

        File outputDirectory = getSwfCompileDir();
        debug("Creating output directory: " + outputDirectory);
        outputDirectory.mkdirs();

        for (FlexApp flexApp : flexApps) {
            String mainMxmlPath = flexApp.getMainMxmlFile();
            if (mainMxmlPath == null) {
                throw new EnunciateException("A main MXML file for the flex app '" + flexApp.getName()
                        + "' must be supplied with the 'mainMxmlFile' attribute.");
            }

            File mainMxmlFile = enunciate.resolvePath(mainMxmlPath);
            if (!mainMxmlFile.exists()) {
                throw new EnunciateException(
                        "Main MXML file for the flex app '" + flexApp.getName() + "' doesn't exist.");
            }

            File swfDir = outputDirectory;
            if (flexApp.getOutputPath() != null && !"".equals(flexApp.getOutputPath())) {
                swfDir = new File(outputDirectory, flexApp.getOutputPath());
                swfDir.mkdirs();
            }
            File swfFile = new File(swfDir, flexApp.getName() + ".swf");
            File appSrcDir = enunciate.resolvePath(flexApp.getSrcDir());
            String swfFilePath = swfFile.getAbsolutePath();

            boolean swfUpToDate = swfFile.exists() && mainMxmlFile.lastModified() < swfFile.lastModified()
                    && enunciate.isUpToDate(appSrcDir, swfFile);

            if (!swfUpToDate) {
                commandLine.set(outputFileIndex, swfFilePath);
                commandLine.set(mainMxmlPathIndex, mainMxmlFile.getAbsolutePath());
                commandLine.set(sourcePathIndex, appSrcDir.getAbsolutePath());

                debug("Compiling %s ...", swfFilePath);
                if (enunciate.isDebug()) {
                    StringBuilder command = new StringBuilder();
                    for (String commandPiece : commandLine) {
                        command.append(' ').append(commandPiece);
                    }
                    debug("Executing flex compile for module %s with the command: %s", flexApp.getName(),
                            command);
                }

                ProcessBuilder processBuilder = new ProcessBuilder(
                        commandLine.toArray(new String[commandLine.size()]));
                processBuilder.directory(getSwfCompileDir());
                processBuilder.redirectErrorStream(true);
                Process process = processBuilder.start();
                BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = procReader.readLine();
                while (line != null) {
                    info(line);
                    line = procReader.readLine();
                }
                int procCode;
                try {
                    procCode = process.waitFor();
                } catch (InterruptedException e1) {
                    throw new EnunciateException("Unexpected inturruption of the Flex compile process.");
                }

                if (procCode != 0) {
                    throw new EnunciateException("Flex compile failed for module " + flexApp.getName());
                }
            } else {
                info("Skipping compilation of %s as everything appears up-to-date...", swfFilePath);
            }
        }
    }

    if (isAsSourcesDownloadable()) {
        String label = "enunciate";
        if ((enunciate.getConfig() != null) && (enunciate.getConfig().getLabel() != null)) {
            label = enunciate.getConfig().getLabel();
        }

        asSources = new File(new File(getCompileDir(), "src"), label + "-as3-sources.zip");
        enunciate.zip(asSources, getClientSideGenerateDir());
    }

    if (swcFile != null || asSources != null) {
        List<ArtifactDependency> clientDeps = new ArrayList<ArtifactDependency>();
        BaseArtifactDependency as3Dependency = new BaseArtifactDependency();
        as3Dependency.setId("flex-sdk");
        as3Dependency.setArtifactType("zip");
        as3Dependency.setDescription("The flex SDK.");
        as3Dependency.setURL("http://www.adobe.com/products/flex/");
        as3Dependency.setVersion("2.0.1");
        clientDeps.add(as3Dependency);

        ClientLibraryArtifact as3ClientArtifact = new ClientLibraryArtifact(getName(), "as3.client.library",
                "ActionScript 3 Client Library");
        as3ClientArtifact.setPlatform("Adobe Flex");
        //read in the description from file:
        as3ClientArtifact.setDescription(readResource("library_description.fmt"));
        as3ClientArtifact.setDependencies(clientDeps);

        if (swcFile != null) {
            NamedFileArtifact clientArtifact = new NamedFileArtifact(getName(), "as3.client.swc", swcFile);
            clientArtifact.setDescription("The compiled SWC.");
            clientArtifact.setPublic(false);
            clientArtifact.setArtifactType(ArtifactType.binaries);
            as3ClientArtifact.addArtifact(clientArtifact);
            enunciate.addArtifact(clientArtifact);
        }

        if (asSources != null) {
            NamedFileArtifact clientArtifact = new NamedFileArtifact(getName(), "as3.client.sources",
                    asSources);
            clientArtifact.setDescription("The client-side ActionScript sources.");
            clientArtifact.setPublic(false);
            clientArtifact.setArtifactType(ArtifactType.sources);
            as3ClientArtifact.addArtifact(clientArtifact);
            enunciate.addArtifact(clientArtifact);
        }

        enunciate.addArtifact(as3ClientArtifact);
    }
}

From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java

private ProcessDescription start(final File jar) throws Exception {
    final ProcessDescription cfg = new ProcessDescription(this.configuration.getId(),
            this.configuration.getFolder());

    final ProcessBuilder builder = new ProcessBuilder();
    final List<String> args = new ArrayList<String>();

    args.add("java");
    add(args, this.configuration.getVmOpts());
    add(args, this.configuration.getVmDebugOpts(this.environment.getDebug()));

    args.add("-cp");
    args.add("bin");
    args.add(Main.class.getName());
    // first three arguments: jar, listener port, verbose
    args.add(jar.getPath());//from   ww w .j a  v  a2  s  .c o  m
    args.add(String.valueOf(cfg.getControlListener().getPort()));
    args.add("true");

    // from here on launchpad properties
    add(args, this.configuration.getOpts());

    final String contextPath = this.configuration.getContextPath();
    if (contextPath != null && contextPath.length() > 0 && !contextPath.equals("/")) {
        args.add("-r");
        args.add(contextPath);
    }

    if (this.configuration.getPort() != null) {
        args.add("-p");
        args.add(this.configuration.getPort());
    }

    if (this.configuration.getControlPort() != null) {
        args.add("-j");
        args.add(this.configuration.getControlPort());
    }
    if (this.configuration.getRunmode() != null && this.configuration.getRunmode().length() > 0) {
        args.add("-Dsling.run.modes=" + this.configuration.getRunmode());
    }
    if (!this.environment.isShutdownOnExit()) {
        args.add("start");
    }

    builder.command(args.toArray(new String[args.size()]));
    builder.directory(this.configuration.getFolder());
    builder.redirectErrorStream(true);
    builder.redirectOutput(Redirect.INHERIT);
    builder.redirectError(Redirect.INHERIT);

    logger.info("Starting Launchpad " + this.configuration.getId() + "...");
    logger.debug("Launchpad cmd: " + builder.command());
    logger.debug("Launchpad dir: " + builder.directory());

    try {
        cfg.setProcess(builder.start());
    } catch (final IOException e) {
        if (cfg.getProcess() != null) {
            cfg.getProcess().destroy();
            cfg.setProcess(null);
        }
        throw new Exception("Could not start the Launchpad", e);
    }

    return cfg;
}

From source file:org.codehaus.enunciate.modules.gwt.GWTDeploymentModule.java

/**
 * Invokes GWTCompile on the apps specified in the configuration file.
 *//*from  w  w w.java  2 s .c o  m*/
protected void doGWTCompile() throws EnunciateException, IOException {
    if (this.gwtHome == null) {
        throw new EnunciateException(
                "To compile a GWT app you must specify the GWT home directory, either in configuration, by setting the GWT_HOME environment variable, or setting the 'gwt.home' system property.");
    }

    File gwtHomeDir = new File(this.gwtHome);
    if (!gwtHomeDir.exists()) {
        throw new EnunciateException("GWT home not found ('" + gwtHomeDir.getAbsolutePath() + "').");
    }

    File gwtUserJar = new File(gwtHomeDir, "gwt-user.jar");
    if (!gwtUserJar.exists()) {
        warn("Unable to find %s. You may be GWT compile errors.", gwtUserJar.getAbsolutePath());
    }

    //now we have to find gwt-dev.jar.
    //start by assuming linux...
    File gwtDevJar = new File(gwtHomeDir, "gwt-dev.jar");
    if (!gwtDevJar.exists()) {
        File linuxDevJar = new File(gwtHomeDir, "gwt-dev-linux.jar");
        gwtDevJar = linuxDevJar;

        if (!gwtDevJar.exists()) {
            //linux not found. try mac...
            File macDevJar = new File(gwtHomeDir, "gwt-dev-mac.jar");
            gwtDevJar = macDevJar;

            if (!gwtDevJar.exists()) {
                //okay, we'll try windows if we have to...
                File windowsDevJar = new File(gwtHomeDir, "gwt-dev-windows.jar");
                gwtDevJar = windowsDevJar;

                if (!gwtDevJar.exists()) {
                    throw new EnunciateException(
                            String.format("Unable to find GWT dev jar. Looked for %s, %s, and %s.",
                                    linuxDevJar.getAbsolutePath(), macDevJar.getAbsolutePath(),
                                    windowsDevJar.getAbsolutePath()));
                }
            }
        }
    }

    boolean windows = false;
    File javaBinDir = new File(System.getProperty("java.home"), "bin");
    File javaExecutable = new File(javaBinDir, "java");
    if (!javaExecutable.exists()) {
        //append the "exe" for windows users.
        javaExecutable = new File(javaBinDir, "java.exe");
        windows = true;
    }

    String javaCommand = javaExecutable.getAbsolutePath();
    if (!javaExecutable.exists()) {
        warn("No java executable found in %s.  We'll just hope the environment is set up to execute 'java'...",
                javaBinDir.getAbsolutePath());
        javaCommand = "java";
    }

    StringBuilder classpath = new StringBuilder(enunciate.getEnunciateRuntimeClasspath());
    //append the client-side gwt directory.
    classpath.append(File.pathSeparatorChar).append(getClientSideGenerateDir().getAbsolutePath());
    //append the gwt-user jar.
    classpath.append(File.pathSeparatorChar).append(gwtUserJar.getAbsolutePath());
    //append the gwt-dev jar.
    classpath.append(File.pathSeparatorChar).append(gwtDevJar.getAbsolutePath());

    //so here's the GWT compile command:
    //java [extra jvm args] -cp [classpath] [compilerClass] -gen [gwt-gen-dir] -style [style] -out [out] [moduleName]
    List<String> jvmargs = getGwtCompileJVMArgs();
    List<String> compilerArgs = getGwtCompilerArgs();
    List<String> gwtcCommand = new ArrayList<String>(jvmargs.size() + compilerArgs.size() + 11);
    int argIndex = 0;
    gwtcCommand.add(argIndex++, javaCommand);
    for (String arg : jvmargs) {
        gwtcCommand.add(argIndex++, arg);
    }
    gwtcCommand.add(argIndex++, "-cp");
    int classpathArgIndex = argIndex; //app-specific arg.
    gwtcCommand.add(argIndex++, null);
    int compileClassIndex = argIndex;
    gwtcCommand.add(argIndex++, getGwtCompilerClass());
    gwtcCommand.add(argIndex++, "-gen");
    gwtcCommand.add(argIndex++, getGwtGenDir().getAbsolutePath());
    gwtcCommand.add(argIndex++, "-style");
    int styleArgIndex = argIndex;
    gwtcCommand.add(argIndex++, null); //app-specific arg.
    gwtcCommand.add(argIndex++, gwtVersionGreaterThan(1, 5) ? "-war" : "-out");
    int outArgIndex = argIndex;
    gwtcCommand.add(argIndex++, null); //app-specific arg.
    for (String arg : compilerArgs) {
        gwtcCommand.add(argIndex++, arg);
    }
    int moduleNameIndex = argIndex;
    gwtcCommand.add(argIndex, null); //module-specific arg.

    for (GWTApp gwtApp : gwtApps) {
        String appName = gwtApp.getName();
        File appSource = enunciate.resolvePath(gwtApp.getSrcDir());
        String style = gwtApp.getJavascriptStyle().toString();
        File appDir = getAppGenerateDir(appName);

        gwtcCommand.set(classpathArgIndex,
                classpath.toString() + File.pathSeparatorChar + appSource.getAbsolutePath());
        gwtcCommand.set(styleArgIndex, style);
        gwtcCommand.set(outArgIndex, appDir.getAbsolutePath());

        boolean upToDate = enunciate.isUpToDate(getClientSideGenerateDir(), appDir)
                && enunciate.isUpToDate(appSource, appDir);
        if (!upToDate) {
            for (GWTAppModule appModule : gwtApp.getModules()) {
                String moduleName = appModule.getName();

                gwtcCommand.set(moduleNameIndex, moduleName);
                debug("Executing GWTCompile for module '%s'...", moduleName);
                if (enunciate.isDebug()) {
                    StringBuilder command = new StringBuilder();
                    for (String commandPiece : gwtcCommand) {
                        command.append(' ').append(commandPiece);
                    }
                    debug("Executing GWTCompile for module %s with the command: %s", moduleName, command);
                }
                ProcessBuilder processBuilder = new ProcessBuilder(gwtcCommand);
                processBuilder.directory(getGenerateDir());
                processBuilder.redirectErrorStream(true);
                Process process = processBuilder.start();
                BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = procReader.readLine();
                while (line != null) {
                    line = URLDecoder.decode(line, "utf-8").replaceAll("%", "%%").trim(); //GWT URL-encodes spaces and other weird Windows characters.
                    info(line);
                    line = procReader.readLine();
                }
                int procCode;
                try {
                    procCode = process.waitFor();
                } catch (InterruptedException e1) {
                    throw new EnunciateException("Unexpected inturruption of the GWT compile process.");
                }

                if (procCode != 0) {
                    throw new EnunciateException("GWT compile failed for module " + moduleName);
                }

                if (!gwtVersionGreaterThan(1, 5)) {
                    File moduleOutputDir = appDir;
                    String outputPath = appModule.getOutputPath();
                    if ((outputPath != null) && (!"".equals(outputPath.trim()))) {
                        moduleOutputDir = new File(appDir, outputPath);
                    }

                    File moduleGenDir = new File(appDir, moduleName);
                    if (!moduleOutputDir.equals(moduleGenDir)) {
                        moduleOutputDir.mkdirs();
                        enunciate.copyDir(moduleGenDir, moduleOutputDir);
                        deleteDir(moduleGenDir);
                    }
                }

                StringBuilder shellCommand = new StringBuilder();
                for (int i = 0; i < moduleNameIndex; i++) {
                    String commandArg = gwtcCommand.get(i);
                    if (i == compileClassIndex) {
                        commandArg = gwtVersionGreaterThan(1, 5) ? "com.google.gwt.dev.HostedMode"
                                : "com.google.gwt.dev.GWTShell";
                    } else if (commandArg.indexOf(' ') >= 0) {
                        commandArg = '"' + commandArg + '"';
                    }

                    shellCommand.append(commandArg).append(' ');
                }

                //add any extra args before the module name.
                shellCommand.append(windows ? "%*" : "$@").append(' ');

                String shellPage = getModuleId(moduleName) + ".html";
                if (appModule.getShellPage() != null) {
                    shellPage = appModule.getShellPage();
                }

                if (!gwtVersionGreaterThan(1, 5)) {
                    //when invoking the shell for GWT 1.4 or 1.5, it requires a URL to load.
                    //The URL is the [moduleName]/[shellPage.html]
                    shellCommand.append(moduleName).append('/').append(shellPage);
                } else {
                    //as of 1.6, you invoke it with -startupUrl [shellPage.html] [moduleName]
                    shellCommand.append("-startupUrl ").append(shellPage).append(' ').append(moduleName);
                }

                File scriptFile = getShellScriptFile(appName, moduleName);
                scriptFile.getParentFile().mkdirs();
                FileWriter writer = new FileWriter(scriptFile);
                writer.write(shellCommand.toString());
                writer.flush();
                writer.close();

                File shellFile = getShellScriptFile(appName, moduleName);
                if (shellFile.exists()) {
                    StringBuilder scriptArtifactId = new StringBuilder();
                    if ((appName != null) && (appName.trim().length() > 0)) {
                        scriptArtifactId.append(appName).append('.');
                    }
                    scriptArtifactId.append(moduleName).append(".shell");
                    getEnunciate()
                            .addArtifact(new FileArtifact(getName(), scriptArtifactId.toString(), shellFile));
                } else {
                    debug("No GWT shell script file exists at %s.  No artifact added.", shellFile);
                }
            }
        } else {
            info("Skipping GWT compile for app %s as everything appears up-to-date...", appName);
        }
    }
}

From source file:org.apache.giraph.zk.ZooKeeperManager.java

/**
 * If this task has been selected, online a ZooKeeper server.  Otherwise,
 * wait until this task knows that the ZooKeeper servers have been onlined.
 *//*www . jav a  2  s  .  c o m*/
public void onlineZooKeeperServers() {
    Integer taskId = zkServerPortMap.get(myHostname);
    if ((taskId != null) && (taskId.intValue() == taskPartition)) {
        File zkDirFile = new File(this.zkDir);
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("onlineZooKeeperServers: Trying to delete old " + "directory " + this.zkDir);
            }
            FileUtils.deleteDirectory(zkDirFile);
        } catch (IOException e) {
            LOG.warn("onlineZooKeeperServers: Failed to delete " + "directory " + this.zkDir, e);
        }
        generateZooKeeperConfigFile(new ArrayList<String>(zkServerPortMap.keySet()));
        ProcessBuilder processBuilder = new ProcessBuilder();
        List<String> commandList = Lists.newArrayList();
        String javaHome = System.getProperty("java.home");
        if (javaHome == null) {
            throw new IllegalArgumentException("onlineZooKeeperServers: java.home is not set!");
        }
        commandList.add(javaHome + "/bin/java");
        String zkJavaOptsString = GiraphConstants.ZOOKEEPER_JAVA_OPTS.get(conf);
        String[] zkJavaOptsArray = zkJavaOptsString.split(" ");
        if (zkJavaOptsArray != null) {
            commandList.addAll(Arrays.asList(zkJavaOptsArray));
        }
        commandList.add("-cp");
        Path fullJarPath = new Path(conf.get(GiraphConstants.ZOOKEEPER_JAR));
        commandList.add(fullJarPath.toString());
        commandList.add(QuorumPeerMain.class.getName());
        commandList.add(configFilePath);
        processBuilder.command(commandList);
        File execDirectory = new File(zkDir);
        processBuilder.directory(execDirectory);
        processBuilder.redirectErrorStream(true);
        if (LOG.isInfoEnabled()) {
            LOG.info("onlineZooKeeperServers: Attempting to " + "start ZooKeeper server with command "
                    + commandList + " in directory " + execDirectory.toString());
        }
        try {
            synchronized (this) {
                zkProcess = processBuilder.start();
                zkProcessCollector = new StreamCollector(zkProcess.getInputStream());
                zkProcessCollector.start();
            }
            Runnable runnable = new Runnable() {
                public void run() {
                    LOG.info("run: Shutdown hook started.");
                    synchronized (this) {
                        if (zkProcess != null) {
                            LOG.warn("onlineZooKeeperServers: " + "Forced a shutdown hook kill of the "
                                    + "ZooKeeper process.");
                            zkProcess.destroy();
                            int exitCode = -1;
                            try {
                                exitCode = zkProcess.waitFor();
                            } catch (InterruptedException e) {
                                LOG.warn("run: Couldn't get exit code.");
                            }
                            LOG.info("onlineZooKeeperServers: ZooKeeper process exited " + "with " + exitCode
                                    + " (note that 143 " + "typically means killed).");
                        }
                    }
                }
            };
            Runtime.getRuntime().addShutdownHook(new Thread(runnable));
            LOG.info("onlineZooKeeperServers: Shutdown hook added.");
        } catch (IOException e) {
            LOG.error("onlineZooKeeperServers: Failed to start " + "ZooKeeper process", e);
            throw new RuntimeException(e);
        }

        // Once the server is up and running, notify that this server is up
        // and running by dropping a ready stamp.
        int connectAttempts = 0;
        final int maxConnectAttempts = conf.getZookeeperConnectionAttempts();
        while (connectAttempts < maxConnectAttempts) {
            try {
                if (LOG.isInfoEnabled()) {
                    LOG.info("onlineZooKeeperServers: Connect attempt " + connectAttempts + " of "
                            + maxConnectAttempts + " max trying to connect to " + myHostname + ":" + zkBasePort
                            + " with poll msecs = " + pollMsecs);
                }
                InetSocketAddress zkServerAddress = new InetSocketAddress(myHostname, zkBasePort);
                Socket testServerSock = new Socket();
                testServerSock.connect(zkServerAddress, 5000);
                if (LOG.isInfoEnabled()) {
                    LOG.info("onlineZooKeeperServers: Connected to " + zkServerAddress + "!");
                }
                break;
            } catch (SocketTimeoutException e) {
                LOG.warn("onlineZooKeeperServers: Got " + "SocketTimeoutException", e);
            } catch (ConnectException e) {
                LOG.warn("onlineZooKeeperServers: Got " + "ConnectException", e);
            } catch (IOException e) {
                LOG.warn("onlineZooKeeperServers: Got " + "IOException", e);
            }

            ++connectAttempts;
            try {
                Thread.sleep(pollMsecs);
            } catch (InterruptedException e) {
                LOG.warn("onlineZooKeeperServers: Sleep of " + pollMsecs + " interrupted - " + e.getMessage());
            }
        }
        if (connectAttempts == maxConnectAttempts) {
            throw new IllegalStateException(
                    "onlineZooKeeperServers: Failed to connect in " + connectAttempts + " tries!");
        }
        Path myReadyPath = new Path(serverDirectory, myHostname + HOSTNAME_TASK_SEPARATOR + taskPartition);
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("onlineZooKeeperServers: Creating my filestamp " + myReadyPath);
            }
            fs.createNewFile(myReadyPath);
        } catch (IOException e) {
            LOG.error("onlineZooKeeperServers: Failed (maybe previous " + "task failed) to create filestamp "
                    + myReadyPath, e);
        }
    } else {
        List<String> foundList = new ArrayList<String>();
        int readyRetrievalAttempt = 0;
        while (true) {
            try {
                FileStatus[] fileStatusArray = fs.listStatus(serverDirectory);
                foundList.clear();
                if ((fileStatusArray != null) && (fileStatusArray.length > 0)) {
                    for (int i = 0; i < fileStatusArray.length; ++i) {
                        String[] hostnameTaskArray = fileStatusArray[i].getPath().getName()
                                .split(HOSTNAME_TASK_SEPARATOR);
                        if (hostnameTaskArray.length != 2) {
                            throw new RuntimeException("getZooKeeperServerList: Task 0 failed " + "to parse "
                                    + fileStatusArray[i].getPath().getName());
                        }
                        foundList.add(hostnameTaskArray[0]);
                    }
                    if (LOG.isInfoEnabled()) {
                        LOG.info("onlineZooKeeperServers: Got " + foundList + " " + foundList.size()
                                + " hosts from " + fileStatusArray.length + " ready servers when " + serverCount
                                + " required (polling period is " + pollMsecs + ") on attempt "
                                + readyRetrievalAttempt);
                    }
                    if (foundList.containsAll(zkServerPortMap.keySet())) {
                        break;
                    }
                } else {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("onlineZooKeeperSErvers: Empty " + "directory " + serverDirectory
                                + ", waiting " + pollMsecs + " msecs.");
                    }
                }
                Thread.sleep(pollMsecs);
                ++readyRetrievalAttempt;
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                LOG.warn("onlineZooKeeperServers: Strange interrupt from " + e.getMessage(), e);
            }
        }
    }
}

From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {/*from w  ww.  j  a v  a 2s .  c o m*/
        final File testCFile = new File(tempDir, "test.c");
        String _generateMainCode = this.generateMainCode();
        Files.write(_generateMainCode, testCFile, StandardCharsets.UTF_8);
        final File testRunner = new File(tempDir, "runner.c");
        final InputStream runnerStream = CCodeGenerator.class
                .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.c");
        final FileOutputStream fos = new FileOutputStream(testRunner);
        try {
            ByteStreams.copy(runnerStream, fos);
        } finally {
            runnerStream.close();
            fos.close();
        }
        final File executable = new File(tempDir, "testExec");
        this.writeAuxiliaryContents(tempDir);
        String _absolutePath = tempDir.getAbsolutePath();
        String _absolutePath_1 = testCFile.getAbsolutePath();
        String _absolutePath_2 = testRunner.getAbsolutePath();
        String _absolutePath_3 = executable.getAbsolutePath();
        final ProcessBuilder builder = new ProcessBuilder(CCodeGenerator.COMPILER, "-I", _absolutePath, "-O3",
                _absolutePath_1, _absolutePath_2, "-o", _absolutePath_3);
        ProcessBuilder _directory = builder.directory(tempDir);
        ProcessBuilder _inheritIO = _directory.inheritIO();
        final Process process = _inheritIO.start();
        process.waitFor();
        int _exitValue = process.exitValue();
        boolean _notEquals = (_exitValue != 0);
        if (_notEquals) {
            throw new RuntimeException("Process did not terminate with 0");
        }
        return new IHDLInterpreterFactory<NativeRunner>() {
            public NativeRunner newInstance() {
                try {
                    String _absolutePath = executable.getAbsolutePath();
                    final ProcessBuilder execBuilder = new ProcessBuilder(_absolutePath);
                    ProcessBuilder _directory = execBuilder.directory(tempDir);
                    ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
                    final Process testExec = _redirectErrorStream.start();
                    InputStream _inputStream = testExec.getInputStream();
                    OutputStream _outputStream = testExec.getOutputStream();
                    String _absolutePath_1 = executable.getAbsolutePath();
                    return new NativeRunner(_inputStream, _outputStream, CCodeGenerator.this.em, testExec, 5,
                            _absolutePath_1);
                } catch (Throwable _e) {
                    throw Exceptions.sneakyThrow(_e);
                }
            }
        };
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}