Example usage for java.io PipedInputStream close

List of usage examples for java.io PipedInputStream close

Introduction

In this page you can find the example usage for java.io PipedInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this piped input stream and releases any system resources associated with the stream.

Usage

From source file:com.emc.ecs.sync.CasMigrationTest.java

private String pipeAndGetMd5(byte[] source) throws Exception {
    PipedInputStream pin = new PipedInputStream(BUFFER_SIZE);
    PipedOutputStream pout = new PipedOutputStream(pin);

    Producer producer = new Producer(source, pout);

    // produce in parallel
    Thread producerThread = new Thread(producer);
    producerThread.start();//w ww . ja  v  a  2  s.  c o m

    // consume inside this thread
    byte[] dest = new byte[source.length];
    try {
        int read = 0;
        while (read < dest.length && read != -1) {
            read += pin.read(dest, read, dest.length - read);
        }
    } finally {
        try {
            pin.close();
        } catch (Throwable t) {
            // ignore
        }
    }

    // synchronize
    producerThread.join();

    return Hex.encodeHexString(MessageDigest.getInstance("MD5").digest(dest));
}

From source file:eu.esdihumboldt.hale.io.wfs.AbstractWFSWriter.java

@Override
public IOReport execute(ProgressIndicator progress) throws IOProviderConfigurationException, IOException {
    progress.begin("WFS Transaction", ProgressIndicator.UNKNOWN);

    // configure internal provider
    internalProvider.setDocumentWrapper(createTransaction());

    final PipedInputStream pIn = new PipedInputStream();
    PipedOutputStream pOut = new PipedOutputStream(pIn);
    currentExecuteStream = pOut;/*w  w  w  . ja  v  a  2s.  c  o  m*/

    Future<Response> futureResponse = null;
    IOReporter reporter = createReporter();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        // read the stream (in another thread)
        futureResponse = executor.submit(new Callable<Response>() {

            @Override
            public Response call() throws Exception {

                Proxy proxy = ProxyUtil.findProxy(targetWfs.getLocation());
                Request request = Request.Post(targetWfs.getLocation()).bodyStream(pIn,
                        ContentType.APPLICATION_XML);
                Executor executor = FluentProxyUtil.setProxy(request, proxy);

                // authentication
                String user = getParameter(PARAM_USER).as(String.class);
                String password = getParameter(PARAM_PASSWORD).as(String.class);

                if (user != null) {
                    // target host
                    int port = targetWfs.getLocation().getPort();
                    String hostName = targetWfs.getLocation().getHost();
                    String scheme = targetWfs.getLocation().getScheme();
                    HttpHost host = new HttpHost(hostName, port, scheme);

                    // add credentials
                    Credentials cred = ClientProxyUtil.createCredentials(user, password);
                    executor.auth(new AuthScope(host), cred);
                    executor.authPreemptive(host);
                }

                try {
                    return executor.execute(request);
                } finally {
                    pIn.close();
                }
            }
        });

        // write the stream
        SubtaskProgressIndicator subprogress = new SubtaskProgressIndicator(progress);
        reporter = (IOReporter) super.execute(subprogress);
    } finally {
        executor.shutdown();
    }

    try {
        Response response = futureResponse.get();
        HttpResponse res = response.returnResponse();
        int statusCode = res.getStatusLine().getStatusCode();
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        if (statusCode >= 200 && statusCode < 300) {
            // success
            reporter.setSuccess(reporter.isSuccess());

            // construct summary from response
            try {
                Document responseDoc = parseResponse(res.getEntity());

                // totalInserted
                String inserted = xpath.compile("//TransactionSummary/totalInserted").evaluate(responseDoc);
                // XXX totalUpdated
                // XXX totalReplaced
                // XXX totalDeleted
                reporter.setSummary("Inserted " + inserted + " features.");
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl(MessageFormat.format(
                        "Server returned status code {0}, but could not parse server response", statusCode),
                        e));
                reporter.setSuccess(false);
            }
        } else {
            // failure
            reporter.error(
                    new IOMessageImpl("Server reported failure with code " + res.getStatusLine().getStatusCode()
                            + ": " + res.getStatusLine().getReasonPhrase(), null));
            reporter.setSuccess(false);

            try {
                Document responseDoc = parseResponse(res.getEntity());
                String errorText = xpath.compile("//ExceptionText/text()").evaluate(responseDoc);
                reporter.setSummary("Request failed: " + errorText);
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl("Could not parse server response", e));
                reporter.setSuccess(false);
            }
        }
    } catch (ExecutionException | InterruptedException e) {
        reporter.error(new IOMessageImpl("Failed to execute WFS-T request", e));
        reporter.setSuccess(false);
    }

    progress.end();

    return reporter;
}

From source file:com.dtolabs.rundeck.core.execution.impl.jsch.JschNodeExecutor.java

public NodeExecutorResult executeCommand(final ExecutionContext context, final String[] command,
        final INodeEntry node) {
    if (null == node.getHostname() || null == node.extractHostname()) {
        return NodeExecutorResultImpl.createFailure(StepFailureReason.ConfigurationFailure,
                "Hostname must be set to connect to remote node '" + node.getNodename() + "'", node);
    }/* ww w. ja va2 s .  c  o m*/

    final ExecutionListener listener = context.getExecutionListener();
    final Project project = new Project();
    AntSupport.addAntBuildListener(listener, project);

    boolean success = false;
    final ExtSSHExec sshexec;
    //perform jsch sssh command
    final NodeSSHConnectionInfo nodeAuthentication = new NodeSSHConnectionInfo(node, framework, context);
    final int timeout = nodeAuthentication.getSSHTimeout();
    try {

        sshexec = SSHTaskBuilder.build(node, command, project, context.getDataContext(), nodeAuthentication,
                context.getLoglevel(), listener);
    } catch (SSHTaskBuilder.BuilderException e) {
        return NodeExecutorResultImpl.createFailure(StepFailureReason.ConfigurationFailure, e.getMessage(),
                node);
    }

    //Sudo support

    final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
        public Thread newThread(Runnable r) {
            return new Thread(null, r,
                    "SudoResponder " + node.getNodename() + ": " + System.currentTimeMillis());
        }
    });

    final Future<ResponderTask.ResponderResult> responderFuture;
    final SudoResponder sudoResponder = SudoResponder.create(node, framework, context);
    Runnable responderCleanup = null;
    if (sudoResponder.isSudoEnabled() && sudoResponder.matchesCommandPattern(command[0])) {
        final DisconnectResultHandler resultHandler = new DisconnectResultHandler();

        //configure two piped i/o stream pairs, to connect to the input/output of the SSH connection
        final PipedInputStream responderInput = new PipedInputStream();
        final PipedOutputStream responderOutput = new PipedOutputStream();
        final PipedInputStream jschInput = new PipedInputStream();
        //lead pipe allows connected inputstream to close and not hang the writer to this stream
        final PipedOutputStream jschOutput = new LeadPipeOutputStream();
        try {
            responderInput.connect(jschOutput);
            jschInput.connect(responderOutput);
        } catch (IOException e) {
            return NodeExecutorResultImpl.createFailure(StepFailureReason.IOFailure, e.getMessage(), node);
        }

        //first sudo prompt responder
        ResponderTask responder = new ResponderTask(sudoResponder, responderInput, responderOutput,
                resultHandler);

        /**
         * Callable will be executed by the ExecutorService
         */
        final Callable<ResponderTask.ResponderResult> responderResultCallable;

        //if 2nd responder
        final SudoResponder sudoResponder2 = SudoResponder.create(node, framework, context, SUDO2_OPT_PREFIX,
                DEFAULT_SUDO2_PASSWORD_OPTION, DEFAULT_SUDO2_COMMAND_PATTERN);
        if (sudoResponder2.isSudoEnabled()
                && sudoResponder2.matchesCommandPattern(CLIUtils.generateArgline(null, command, false))) {
            logger.debug("Enable second sudo responder");

            sudoResponder2.setDescription("Second " + SudoResponder.DEFAULT_DESCRIPTION);
            sudoResponder.setDescription("First " + SudoResponder.DEFAULT_DESCRIPTION);

            //sequence of the first then the second sudo responder
            responderResultCallable = responder.createSequence(sudoResponder2);
        } else {
            responderResultCallable = responder;
        }

        //set up SSH execution
        sshexec.setAllocatePty(true);
        sshexec.setInputStream(jschInput);
        sshexec.setSecondaryStream(jschOutput);
        sshexec.setDisconnectHolder(resultHandler);

        responderFuture = executor.submit(responderResultCallable);
        //close streams after responder is finished
        responderCleanup = new Runnable() {
            public void run() {
                logger.debug("SudoResponder shutting down...");
                try {
                    responderInput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    responderOutput.flush();
                    responderOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //executor pool shutdown
                executor.shutdownNow();
            }
        };
        executor.submit(responderCleanup);
    } else {
        responderFuture = null;
    }
    if (null != context.getExecutionListener()) {
        context.getExecutionListener().log(3, "Starting SSH Connection: " + nodeAuthentication.getUsername()
                + "@" + node.getHostname() + " (" + node.getNodename() + ")");
    }
    String errormsg = null;
    FailureReason failureReason = null;
    try {
        sshexec.execute();
        success = true;
    } catch (BuildException e) {
        final ExtractFailure extractJschFailure = extractFailure(e, node, timeout, framework);
        errormsg = extractJschFailure.getErrormsg();
        failureReason = extractJschFailure.getReason();
        context.getExecutionListener().log(0, errormsg);
    }
    if (null != responderCleanup) {
        responderCleanup.run();
    }
    shutdownAndAwaitTermination(executor);
    if (null != responderFuture) {
        try {
            logger.debug("Waiting 5 seconds for responder future result");
            final ResponderTask.ResponderResult result = responderFuture.get(5, TimeUnit.SECONDS);
            logger.debug("Responder result: " + result);
            if (!result.isSuccess() && !result.isInterrupted()) {
                context.getExecutionListener().log(0,
                        result.getResponder().toString() + " failed: " + result.getFailureReason());
            }
        } catch (InterruptedException e) {
            //ignore
        } catch (java.util.concurrent.ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            //ignore
        }
    }
    final int resultCode = sshexec.getExitStatus();

    if (success) {
        return NodeExecutorResultImpl.createSuccess(node);
    } else {
        return NodeExecutorResultImpl.createFailure(failureReason, errormsg, node, resultCode);
    }
}

From source file:com.actuate.development.tool.task.InstallBRDPro.java

private void interruptOutput(final IProgressMonitor monitor, final int[] currentStep,
        final DefaultLogger consoleLogger, final boolean[] flag, final String[] defaultTaskName) {

    String threadName = "Monitor Output";
    if (current[0] != null && current[0].getName() != null) {
        linkBuffer.append(current[0].getName()).append("\n");
        threadName += (": " + current[0].getName());
    }/*ww  w.  ja  v  a2s . c o  m*/

    outputThread = new Thread(threadName) {

        public void run() {
            try {
                final Module module = current[0];
                final int step = currentStep[0];
                PipedInputStream pipedIS = new PipedInputStream();
                PipedOutputStream pipedOS = new PipedOutputStream();
                pipedOS.connect(pipedIS);
                BufferedReader input = new BufferedReader(new InputStreamReader(pipedIS));
                PrintStream ps = new PrintStream(pipedOS);
                consoleLogger.setOutputPrintStream(ps);
                final String[] line = new String[1];
                String extactingStr = "[exec] Extracting";
                int length = "[exec]".length();
                while ((line[0] = input.readLine()) != null) {
                    if (module != current[0])
                        break;
                    if (!flag[0]) {
                        int index = line[0].indexOf(extactingStr);
                        if (index != -1) {
                            String file = line[0].substring(index + length);
                            monitor.subTask("[Step " + step + "]" + file);
                            if (module == null) {
                                if (data.isInstallShield()) {

                                    file = file.trim().replaceAll("Extracting\\s+", "");
                                    if (file.toLowerCase().indexOf("eclipse") > -1) {
                                        file = ("\\" + file);
                                        installBuffer.append(file + "\n");
                                    }
                                } else {
                                    file = file.trim().replaceAll("Extracting\\s+BRDPro", "");
                                    installBuffer.insert(0, file + "\n");
                                }

                            } else if (module.getType() == ModuleType.source
                                    && file.indexOf("eclipse\\plugins") > -1 && file.indexOf("source") > -1) {
                                String prefix = "\\eclipse\\dropins";
                                file = (prefix + "\\" + file.trim().replaceAll("Extracting\\s+", ""));
                                sourceBuffer.append(file).append("\n");
                            }
                        } else {
                            monitor.subTask(defaultTaskName[0]);
                        }
                        System.out.println(line[0]);
                    }
                }
                input.close();
                pipedIS.close();
                consoleLogger.setOutputPrintStream(System.out);
            } catch (IOException e) {

            }
        }
    };
    outputThread.start();

}

From source file:org.apache.hadoop.mapred.TestJobClient.java

private void verifyJobPriority(String jobId, String priority) throws Exception {
    PipedInputStream pis = new PipedInputStream();
    PipedOutputStream pos = new PipedOutputStream(pis);
    int exitCode = runTool(createJobConf(), new JobClient(), new String[] { "-list", "all" }, pos);
    assertEquals("Exit code", 0, exitCode);
    BufferedReader br = new BufferedReader(new InputStreamReader(pis));
    String line = null;/*from ww  w .  ja  va2 s  .  co  m*/
    while ((line = br.readLine()) != null) {
        LOG.info("line = " + line);
        if (!line.startsWith(jobId)) {
            continue;
        }
        assertTrue(line.contains(priority));
        break;
    }
    pis.close();
}

From source file:org.apache.hadoop.mapreduce.TestMRJobClient.java

protected void verifyJobPriority(String jobId, String priority, Configuration conf, CLI jc) throws Exception {
    PipedInputStream pis = new PipedInputStream();
    PipedOutputStream pos = new PipedOutputStream(pis);
    int exitCode = runTool(conf, jc, new String[] { "-list", "all" }, pos);
    assertEquals("Exit code", 0, exitCode);
    BufferedReader br = new BufferedReader(new InputStreamReader(pis));
    String line;/*from   ww  w  .  ja  v  a2s .com*/
    while ((line = br.readLine()) != null) {
        LOG.info("line = " + line);
        if (!line.contains(jobId)) {
            continue;
        }
        assertTrue(line.contains(priority));
        break;
    }
    pis.close();
}

From source file:org.apache.oozie.cli.TestCLIParser.java

private String readCommandOutput(CLIParser parser, CLIParser.Command c) throws IOException {
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
    PipedOutputStream pipeOut = new PipedOutputStream();
    PipedInputStream pipeIn = new PipedInputStream(pipeOut, 1024 * 10);
    System.setOut(new PrintStream(pipeOut));

    parser.showHelp(c.getCommandLine());
    pipeOut.close();/*from   ww  w . ja v  a2 s .  co  m*/
    ByteStreams.copy(pipeIn, outBytes);
    pipeIn.close();
    return new String(outBytes.toByteArray());
}

From source file:org.geoserver.wfs.xslt.XSLTOutputFormat.java

@Override
protected void write(final FeatureCollectionResponse featureCollection, OutputStream output,
        Operation operation) throws IOException, ServiceException {
    // get the transformation we need
    TransformInfo info = locateTransformation(featureCollection, operation);
    Transformer transformer = repository.getTransformer(info);
    // force Xalan to indent the output
    if (transformer.getOutputProperties() != null
            && "yes".equals(transformer.getOutputProperties().getProperty("indent"))) {
        try {/*  w ww  .  ja v a 2s .  c  om*/
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } catch (IllegalArgumentException e) {
            LOGGER.log(Level.FINE, "Could not set indent amount", e);
            // in case it's not Xalan
        }
    }

    // prepare the fake operation we're providing to the source output format
    final Operation sourceOperation = buildSourceOperation(operation, info);

    // lookup the operation we are going to use
    final Response sourceResponse = findSourceResponse(sourceOperation, info);
    if (sourceResponse == null) {
        throw new WFSException("Could not locate a response that can generate the desired source format '"
                + info.getSourceFormat() + "' for transformation '" + info.getName() + "'");

    }

    // prepare the stream connections, so that we can do the transformation on the fly
    PipedInputStream pis = new PipedInputStream();
    final PipedOutputStream pos = new PipedOutputStream(pis);

    // submit the source output format execution, tracking exceptions
    Future<Void> future = executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            try {
                sourceResponse.write(featureCollection, pos, sourceOperation);
            } finally {
                // close the stream to make sure the transformation won't keep on waiting
                pos.close();
            }

            return null;
        }
    });

    // run the transformation
    TransformerException transformerException = null;
    try {
        transformer.transform(new StreamSource(pis), new StreamResult(output));
    } catch (TransformerException e) {
        transformerException = e;
    } finally {
        pis.close();
    }

    // now handle exceptions, starting from the source
    try {
        future.get();
    } catch (Exception e) {
        throw new WFSException(
                "Failed to run the output format generating the source for the XSTL transformation", e);
    }
    if (transformerException != null) {
        throw new WFSException("Failed to run the the XSTL transformation", transformerException);
    }

}

From source file:org.waarp.openr66.context.task.ExecMoveTask.java

@Override
public void run() {
    /*/*from  w  w w.j  a v  a2 s  .  c  o  m*/
     * First apply all replacements and format to argRule from context and argTransfer. Will
     * call exec (from first element of resulting string) with arguments as the following value
     * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last
     * line of stdout will be the new name given to the R66File in case of status 0. The
     * previous file should be deleted by the script or will be deleted in case of status 0. If
     * the status is 1, no change is made to the file.
     */
    logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Force the WaitForValidation
    waitForValidation = true;
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            LocalExecResult result = localExecClient.getLocalExecResult();
            move(result.getStatus(), result.getResult(), finalname);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    String[] args = finalname.split(" ");
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + finalname);
            R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner());
            futureCompletion.setResult(result);
            futureCompletion.cancel();
            return;
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = null;
    try {
        outputStream = new PipedOutputStream(inputStream);
    } catch (IOException e1) {
        try {
            inputStream.close();
        } catch (IOException e) {
        }
        logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1);
        futureCompletion.setFailure(e1);
        return;
    }
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;

    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    LastLineReader lastLineReader = new LastLineReader(inputStream);
    Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId());
    thread.setDaemon(true);
    Configuration.configuration.getExecutorService().execute(thread);
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(Configuration.RETRYINMS);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with "
                        + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error(
                        "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            }
        } else {
            try {
                outputStream.close();
            } catch (IOException e1) {
            }
            thread.interrupt();
            try {
                inputStream.close();
            } catch (IOException e1) {
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e2) {
            }
            logger.error(
                    "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
            futureCompletion.setFailure(e);
            return;
        }
    } catch (IOException e) {
        try {
            outputStream.close();
        } catch (IOException e1) {
        }
        thread.interrupt();
        try {
            inputStream.close();
        } catch (IOException e1) {
        }
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
        futureCompletion.setFailure(e);
        return;
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
    }
    try {
        outputStream.close();
    } catch (IOException e) {
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    try {
        if (delay > 0) {
            thread.join(delay);
        } else {
            thread.join();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    try {
        inputStream.close();
    } catch (IOException e1) {
    }
    String newname = null;
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        status = -1;
        newname = "TimeOut";
    } else {
        newname = lastLineReader.getLastLine();
        if (status == 0 && (newname == null || newname.isEmpty())) {
            status = 1;
        }
    }
    move(status, newname, commandLine.toString());
}

From source file:org.waarp.openr66.context.task.ExecOutputTask.java

@Override
public void run() {
    /*//from w ww .j  a  v  a  2 s.  co  m
     * First apply all replacements and format to argRule from context and argTransfer. Will
     * call exec (from first element of resulting string) with arguments as the following value
     * from the replacements. Return 0 if OK, else 1 for a warning else as an error. In case of
     * an error (> 0), all the line from output will be send back to the partner with the Error
     * code. No change is made to the file.
     */
    logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Force the WaitForValidation
    waitForValidation = true;
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            LocalExecResult result = localExecClient.getLocalExecResult();
            finalize(result.getStatus(), result.getResult(), finalname);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    String[] args = finalname.split(" ");
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + finalname);
            R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner());
            futureCompletion.setResult(result);
            futureCompletion.cancel();
            return;
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = null;
    try {
        outputStream = new PipedOutputStream(inputStream);
    } catch (IOException e1) {
        try {
            inputStream.close();
        } catch (IOException e) {
        }
        logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1);
        futureCompletion.setFailure(e1);
        return;
    }
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    AllLineReader allLineReader = new AllLineReader(inputStream);
    Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId());
    thread.setDaemon(true);
    Configuration.configuration.getExecutorService().execute(thread);
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(Configuration.RETRYINMS);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status,
                        commandLine);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.flush();
                } catch (IOException e2) {
                }
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error(
                        "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            }
        } else {
            finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status,
                    commandLine);
            return;
        }
    } catch (IOException e) {
        try {
            outputStream.close();
        } catch (IOException e1) {
        }
        thread.interrupt();
        try {
            inputStream.close();
        } catch (IOException e1) {
        }
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
        futureCompletion.setFailure(e);
        return;
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
    }
    try {
        outputStream.close();
    } catch (IOException e) {
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    try {
        if (delay > 0) {
            thread.join(delay);
        } else {
            thread.join();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    try {
        inputStream.close();
    } catch (IOException e1) {
    }
    String newname = null;
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        status = -1;
        newname = "TimeOut";
    } else {
        newname = allLineReader.getLastLine().toString();
    }
    finalize(status, newname, commandLine.toString());
}