Example usage for java.io PipedOutputStream PipedOutputStream

List of usage examples for java.io PipedOutputStream PipedOutputStream

Introduction

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

Prototype

public PipedOutputStream(PipedInputStream snk) throws IOException 

Source Link

Document

Creates a piped output stream connected to the specified piped input stream.

Usage

From source file:org.wso2.carbon.dataservices.sql.driver.TDriverUtil.java

/**
 * Method to write excel data to registry or file output streams.
 *
 * @param workbook//from   w  ww  . ja va2s .c o  m
 * @param filePath
 * @throws SQLException
 */
public static void writeRecords(Workbook workbook, String filePath) throws SQLException {
    OutputStream out = null;
    PipedInputStream pin = null;
    try {
        if (isRegistryPath(filePath)) {
            try {
                RegistryService registryService = SQLDriverDSComponent.getRegistryService();
                if (registryService == null) {
                    throw new SQLException(
                            "DBUtils.getInputStreamFromPath(): Registry service is not available");
                }
                Registry registry;
                if (filePath.startsWith(CONF_REGISTRY_PATH_PREFIX)) {
                    if (filePath.length() > CONF_REGISTRY_PATH_PREFIX.length()) {
                        filePath = filePath.substring(CONF_REGISTRY_PATH_PREFIX.length());
                        registry = registryService.getConfigSystemRegistry(getCurrentTenantId());
                    } else {
                        throw new SQLException("Empty configuration registry path given");
                    }
                } else {
                    if (filePath.length() > GOV_REGISTRY_PATH_PREFIX.length()) {
                        filePath = filePath.substring(GOV_REGISTRY_PATH_PREFIX.length());
                        registry = registryService.getGovernanceSystemRegistry(getCurrentTenantId());
                    } else {
                        throw new SQLException("Empty governance registry path given");
                    }
                }
                if (registry.resourceExists(filePath)) {
                    pin = new PipedInputStream();
                    out = new PipedOutputStream(pin);
                    new WorkBookOutputWriter(workbook, out).start();
                    Resource serviceResource = registry.get(filePath);
                    serviceResource.setContentStream(pin);
                    registry.put(filePath, serviceResource);
                } else {
                    throw new SQLException("The given XSLT resource path at '" + filePath + "' does not exist");
                }
            } catch (RegistryException e) {
                throw new SQLException(e);
            }
        } else {
            File file = new File(filePath);
            if (filePath.startsWith("." + File.separator) || filePath.startsWith(".." + File.separator)) {
                /* this is a relative path */
                filePath = file.getAbsolutePath();
            }
            out = new FileOutputStream(filePath);
            workbook.write(out);
        }
    } catch (FileNotFoundException e) {
        throw new SQLException("Error occurred while locating the EXCEL datasource", e);
    } catch (IOException e) {
        throw new SQLException("Error occurred while writing the records to the EXCEL " + "data source", e);
    } finally {
        if (pin != null) {
            try {
                pin.close();
            } catch (IOException ignore) {

            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignore) {

            }
        }
    }
}

From source file:edu.jhu.pha.vospace.node.ContainerNode.java

@Override
public InputStream exportData() {
    final PipedInputStream pipedIn = new PipedInputStream();
    PipedOutputStream pipedOut = null;

    try {/*from  ww w.  j a v a 2  s  .  com*/
        pipedOut = new PipedOutputStream(pipedIn);
        //final TarOutputStream tarOut = new TarOutputStream(new GZIPOutputStream(pipedOut));
        final TarOutputStream tarOut = new TarOutputStream(pipedOut);
        Runnable runTransfer = new Runnable() {
            @Override
            public void run() {
                try {
                    tarContainer("", tarOut);
                } catch (IOException ex) {
                    logger.error(ex.getMessage());
                } finally {
                    try {
                        if (null != tarOut)
                            tarOut.close();
                    } catch (Exception ex) {
                    }
                }
                logger.debug("Finishing node " + getUri() + " thread");
            }
        };

        Thread threadA = new Thread(runTransfer, "folderDownloadThread");
        threadA.start();
        return pipedIn;
    } catch (IOException e) {
        logger.debug("Error connectiong container output streams");
        e.printStackTrace();
    }
    return null;
}

From source file:org.rhq.enterprise.server.plugins.alertCli.CliSender.java

private static InputStream getPackageBits(int packageId, int repoId) throws IOException {
    final ContentSourceManagerLocal csm = LookupUtil.getContentSourceManager();
    RepoManagerLocal rm = LookupUtil.getRepoManagerLocal();
    final PackageVersion versionToUse = rm.getLatestPackageVersion(LookupUtil.getSubjectManager().getOverlord(),
            packageId, repoId);//from   ww w  .  j  av  a  2  s  .  c o  m

    if (versionToUse == null) {
        throw new IllegalArgumentException("The package with id " + packageId
                + " either doesn't exist at all or doesn't have any version. Can't execute a CLI script without a script to run.");
    }

    PipedInputStream ret = new PipedInputStream();
    final PipedOutputStream out = new PipedOutputStream(ret);

    Thread reader = new Thread(new Runnable() {
        public void run() {
            try {
                csm.outputPackageVersionBits(versionToUse, out);
            } catch (RuntimeException e) {
                LOG.warn("The thread for reading the bits of package version [" + versionToUse
                        + "] failed with exception.", e);
                throw e;
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    //doesn't happen in piped output stream
                    LOG.error(
                            "Failed to close the piped output stream receiving the package bits of package version "
                                    + versionToUse + ". This should never happen.",
                            e);
                }
            }
        }
    });
    reader.setName("CLI Alert download thread for package version " + versionToUse);
    reader.setDaemon(true);
    reader.start();

    return ret;
}

From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {

    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from  www .j  a v  a2s .  com*/

    monitor.beginTask(configuration.getName() + "...", 6);
    if (monitor.isCanceled()) {
        return;
    }

    try {
        monitor.subTask("Verifying launch attributes");

        String mainTypeName = getMainTypeName(configuration);
        File workingDir = getWorkingDirectory(configuration);
        String[] envp = getEnvironment(configuration);
        List<String> pgmArgs = splitArgs(getProgramArguments(configuration));
        List<String> vmArgs = splitArgs(getVMArguments(configuration));
        String[] classpath = getClasspath(configuration);
        String[] bootclasspath = getBootpath(configuration);
        IJavaProject javaProject = getJavaProject(configuration);
        int debuggerPort = findFreePort();
        boolean hasDebugPlugin = false;

        if (monitor.isCanceled()) {
            return;
        }

        // Verification done
        monitor.worked(1);

        RoboVMPlugin.consoleInfo("Building executable");

        monitor.subTask("Creating source locator");
        setDefaultSourceLocator(launch, configuration);
        monitor.worked(1);

        monitor.subTask("Creating build configuration");
        Config.Builder configBuilder;
        try {
            configBuilder = new Config.Builder();
        } catch (IOException e) {
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Launch failed. Check the RoboVM console for more information.", e));
        }
        configBuilder.logger(RoboVMPlugin.getConsoleLogger());

        File projectRoot = getJavaProject(configuration).getProject().getLocation().toFile();
        RoboVMPlugin.loadConfig(configBuilder, projectRoot, isTestConfiguration());

        Arch arch = getArch(configuration, mode);
        OS os = getOS(configuration, mode);

        configBuilder.os(os);
        configBuilder.arch(arch);

        File tmpDir = RoboVMPlugin.getBuildDir(getJavaProjectName(configuration));
        tmpDir = new File(tmpDir, configuration.getName());
        tmpDir = new File(new File(tmpDir, os.toString()), arch.toString());
        if (mainTypeName != null) {
            tmpDir = new File(tmpDir, mainTypeName);
        }

        if (ILaunchManager.DEBUG_MODE.equals(mode)) {
            configBuilder.debug(true);
            String sourcepaths = RoboVMPlugin.getSourcePaths(javaProject);
            configBuilder.addPluginArgument("debug:sourcepath=" + sourcepaths);
            configBuilder.addPluginArgument("debug:jdwpport=" + debuggerPort);
            configBuilder.addPluginArgument(
                    "debug:logdir=" + new File(projectRoot, "robovm-logs").getAbsolutePath());
            // check if we have the debug plugin
            for (Plugin plugin : configBuilder.getPlugins()) {
                if ("DebugLaunchPlugin".equals(plugin.getClass().getSimpleName())) {
                    hasDebugPlugin = true;
                }
            }
        }

        if (bootclasspath != null) {
            configBuilder.skipRuntimeLib(true);
            for (String p : bootclasspath) {
                configBuilder.addBootClasspathEntry(new File(p));
            }
        }
        for (String p : classpath) {
            configBuilder.addClasspathEntry(new File(p));
        }
        if (mainTypeName != null) {
            configBuilder.mainClass(mainTypeName);
        }
        // we need to filter those vm args that belong to plugins
        // in case of iOS run configs, we can only pass program args
        filterPluginArguments(vmArgs, configBuilder);
        filterPluginArguments(pgmArgs, configBuilder);

        configBuilder.tmpDir(tmpDir);
        configBuilder.skipInstall(true);

        Config config = null;
        AppCompiler compiler = null;
        try {
            RoboVMPlugin.consoleInfo("Cleaning output dir " + tmpDir.getAbsolutePath());
            FileUtils.deleteDirectory(tmpDir);
            tmpDir.mkdirs();

            Home home = RoboVMPlugin.getRoboVMHome();
            if (home.isDev()) {
                configBuilder.useDebugLibs(Boolean.getBoolean("robovm.useDebugLibs"));
                configBuilder.dumpIntermediates(true);
            }
            configBuilder.home(home);
            config = configure(configBuilder, configuration, mode).build();
            compiler = new AppCompiler(config);
            if (monitor.isCanceled()) {
                return;
            }
            monitor.worked(1);

            monitor.subTask("Building executable");
            AppCompilerThread thread = new AppCompilerThread(compiler, monitor);
            thread.compile();
            if (monitor.isCanceled()) {
                RoboVMPlugin.consoleInfo("Build canceled");
                return;
            }
            monitor.worked(1);
            RoboVMPlugin.consoleInfo("Build done");
        } catch (InterruptedException e) {
            RoboVMPlugin.consoleInfo("Build canceled");
            return;
        } catch (IOException e) {
            RoboVMPlugin.consoleError("Build failed");
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Build failed. Check the RoboVM console for more information.", e));
        }

        try {
            RoboVMPlugin.consoleInfo("Launching executable");
            monitor.subTask("Launching executable");
            mainTypeName = config.getMainClass();

            List<String> runArgs = new ArrayList<String>();
            runArgs.addAll(vmArgs);
            runArgs.addAll(pgmArgs);
            LaunchParameters launchParameters = config.getTarget().createLaunchParameters();
            launchParameters.setArguments(runArgs);
            launchParameters.setWorkingDirectory(workingDir);
            launchParameters.setEnvironment(envToMap(envp));
            customizeLaunchParameters(config, launchParameters, configuration, mode);
            String label = String.format("%s (%s)", mainTypeName,
                    DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()));
            // launch plugin may proxy stdout/stderr fifo, which
            // it then writes to. Need to save the original fifos
            File stdOutFifo = launchParameters.getStdoutFifo();
            File stdErrFifo = launchParameters.getStderrFifo();
            PipedInputStream pipedIn = new PipedInputStream();
            PipedOutputStream pipedOut = new PipedOutputStream(pipedIn);
            Process process = compiler.launchAsync(launchParameters, pipedIn);
            if (stdOutFifo != null || stdErrFifo != null) {
                InputStream stdoutStream = null;
                InputStream stderrStream = null;
                if (launchParameters.getStdoutFifo() != null) {
                    stdoutStream = new OpenOnReadFileInputStream(stdOutFifo);
                }
                if (launchParameters.getStderrFifo() != null) {
                    stderrStream = new OpenOnReadFileInputStream(stdErrFifo);
                }
                process = new ProcessProxy(process, pipedOut, stdoutStream, stderrStream, compiler);
            }

            IProcess iProcess = DebugPlugin.newProcess(launch, process, label);

            // setup the debugger
            if (ILaunchManager.DEBUG_MODE.equals(mode) && hasDebugPlugin) {
                VirtualMachine vm = attachToVm(monitor, debuggerPort);
                // we were canceled
                if (vm == null) {
                    process.destroy();
                    return;
                }
                if (vm instanceof VirtualMachineImpl) {
                    ((VirtualMachineImpl) vm).setRequestTimeout(DEBUGGER_REQUEST_TIMEOUT);
                }
                JDIDebugModel.newDebugTarget(launch, vm, mainTypeName + " at localhost:" + debuggerPort,
                        iProcess, true, false, true);
            }
            RoboVMPlugin.consoleInfo("Launch done");

            if (monitor.isCanceled()) {
                process.destroy();
                return;
            }
            monitor.worked(1);
        } catch (Throwable t) {
            RoboVMPlugin.consoleError("Launch failed");
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Launch failed. Check the RoboVM console for more information.", t));
        }

    } finally {
        monitor.done();
    }
}

From source file:fi.hip.sicx.webdav.WebdavClient.java

@Override
public OutputStream writeData(String fileInTheCloud, int indatasize, StorageClientObserver sco)
        throws StorageIOException {

    this.datasize = indatasize; // For calculating transfer progress
    //PipedOutputStream pos = null;

    // Parameters for the Thread call (final needed for parameters of the thread)
    final String paramfileInTheCloud = fileInTheCloud;
    final int paramindatasize = indatasize;
    final Host paramhost = host;
    final PipedInputStream ins = new PipedInputStream();
    try {//www  .j  av  a2  s. co  m
        this.dos = new DataOutputStream(new PipedOutputStream(ins));
    } catch (IOException e1) {
        throw new StorageIOException("Could not create pipeoutputstream.");
    }

    // Uploading is blocking so we need to execute it on separate thread
    this.future = myExecutor.submit(new Runnable() {
        public void run() {
            String justFileName = "INVALID-NAME.txt";
            try {
                justFileName = refreshUploadPath(paramfileInTheCloud);
                justFileName = generateValidStorageFilename(justFileName);
                if (path != null && pr != null) {
                    uploadedFile = ((Folder) pr).upload(justFileName, ins, (long) paramindatasize, null);
                } else {
                    uploadedFile = paramhost.upload(justFileName, ins, (long) paramindatasize, null);
                }
            } catch (NotAuthorizedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ConflictException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadRequestException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (HttpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("DONE: " + justFileName);
        }
    });

    return this.dos;
}

From source file:SubmitResults.java

private File populateRequest(final Main parent, String formStatus, String filePath, HttpPost req,
        final String changeIdXSLT, ContentType ct, MultipartEntityBuilder entityBuilder,
        final String newIdent) {

    File ammendedFile = null;/*from www.ja v  a2  s. c  o m*/

    final File instanceFile = new File(filePath);

    if (formStatus != null) {
        System.out.println("Setting form status in header: " + formStatus);
        req.setHeader("form_status", formStatus); // smap add form_status header
    } else {
        System.out.println("Form Status null");
    }

    if (newIdent != null) {
        // Transform the survey ID
        try {
            System.out.println("Transformaing Instance file: " + instanceFile);
            PipedInputStream in = new PipedInputStream();
            final PipedOutputStream outStream = new PipedOutputStream(in);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        InputStream xslStream = new ByteArrayInputStream(changeIdXSLT.getBytes("UTF-8"));
                        Transformer transformer = TransformerFactory.newInstance()
                                .newTransformer(new StreamSource(xslStream));
                        StreamSource source = new StreamSource(instanceFile);
                        StreamResult out = new StreamResult(outStream);
                        transformer.setParameter("surveyId", newIdent);
                        transformer.transform(source, out);
                        outStream.close();
                    } catch (TransformerConfigurationException e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerFactoryConfigurationError e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    } catch (IOException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    }
                }
            }).start();
            System.out.println("Saving stream to file");
            ammendedFile = saveStreamTemp(in);
        } catch (Exception e) {
            parent.appendToStatus("Error changing ident: " + e.toString());
        }
    }

    /*
     * Add submission file as file body, hence save to temporary file first
     */
    if (newIdent == null) {
        ct = ContentType.create("text/xml");
        entityBuilder.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
    } else {
        FileBody fb = new FileBody(ammendedFile);
        entityBuilder.addPart("xml_submission_file", fb);
    }

    parent.appendToStatus("Instance file path: " + instanceFile.getPath());

    /*
     *  find all files referenced by the survey
     *  Temporarily check to see if the parent directory is "uploadedSurveys". If it is
     *   then we will need to scan the submission file to get the list of attachments to 
     *   send. 
     *  Alternatively this is a newly submitted survey stored in its own directory just as
     *  surveys are stored on the phone.  We can then just add all the surveys that are in 
     *  the same directory as the submission file.
     */
    File[] allFiles = instanceFile.getParentFile().listFiles();

    // add media files ignoring invisible files and the submission file
    List<File> files = new ArrayList<File>();
    for (File f : allFiles) {
        String fileName = f.getName();
        if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file    
            files.add(f);
        }
    }

    for (int j = 0; j < files.size(); j++) {

        File f = files.get(j);
        String fileName = f.getName();
        ct = ContentType.create(getContentType(parent, fileName));
        FileBody fba = new FileBody(f, ct, fileName);
        entityBuilder.addPart(fileName, fba);

    }

    req.setEntity(entityBuilder.build());

    return ammendedFile;
}

From source file:org.kepler.ssh.GsiSshExec.java

public int executeCmd(String command, OutputStream streamOut, OutputStream streamErr, String thirdPartyTarget)
        throws ExecException {

    int exitCode = -1;
    SessionChannelClient sessionChannel;
    _streamReaderThread readerThread;/*from w  w w.  java 2 s  .  c  o  m*/
    boolean commandSuccess;
    ChannelInputStream stderrInputStream;

    // get the pwd to the third party if necessary
    String thirdPartyPwd = getPwdToThirdParty(thirdPartyTarget);
    // Form the command
    String updatedCmd = forcedCleanUp ? cleanUpInfoCmd + command : command;

    openConnection();
    log.debug("Connected");

    //int result = copyTo(new File("C:\\Chandrika\\test.txt"),"/home/chandrika",false);
    //return result;

    try {

        // Create piped stream if password has to be fed
        PipedInputStream pis = null;
        PipedOutputStream pos = null;
        if (thirdPartyPwd != null) {
            try {
                pis = new PipedInputStream();
                pos = new PipedOutputStream(pis);
            } catch (IOException ex) {
                log.error("Error when creating the piped stream for password feededing: " + ex);
                throw new ExecException("Error when creating the piped stream for password feededing: " + ex);
            }
            // setting pseudo terminal to true so that prompt for password
            // can be read
            // SshExec uses ptyexec.c instead of using pseudo terminal
            pseudoTerminal = true;
        }

        // Open channel and execute command
        synchronized (sshClient) {

            // Once authenticated the user's shell can be started
            // Open a session channel
            sessionChannel = sshClient.openSessionChannel();
            // create pseudo terminal if user has asked for it
            if (pseudoTerminal) {
                sessionChannel.requestPseudoTerminal("vt100", 80, 24, 640, 480, null);
            }
            if (thirdPartyPwd != null) {
                sessionChannel.bindInputStream(pis);
            }
            stderrInputStream = (ChannelInputStream) sessionChannel.getStderrInputStream();
            readerThread = new _streamReaderThread(sessionChannel, sessionChannel.getInputStream(), streamOut,
                    thirdPartyPwd, pos);
            readerThread.start();
            commandSuccess = sessionChannel.executeCommand(updatedCmd);
        }

        log.debug("boolean command excution result is" + commandSuccess);
        // command has finished executing. wait for the reader thread to
        // finish reading output
        // It will timeout at the latest if the command does not finish
        // 3 ways to finish:
        // - command terminates
        // - timeout
        // - IOException when reading the command's output or writing
        // the caller's output
        readerThread.join();

        // on timeout finish here with a nice Exception
        if (readerThread.timeoutHappened()) {
            log.error("Timeout: " + timeout + "s elapsed for command " + command);
            if (sessionChannel.isOpen()) {
                sessionChannel.close(); //closes channels and frees channel
            }
            if (forcedCleanUp) {
                // time for clean-up ;-)
                kill(readerThread.getProcessID(), true);
            }
            throw new ExecTimeoutException(command);
        }

        // if we cannot process output, still wait for the channel to be
        // closed
        // !!! This can lead to hang-up !!!
        while (!sessionChannel.isClosed()) {
            try {
                log.debug("Waiting for channel to close");
                Thread.sleep(500);
            } catch (Exception e) {
            }
        }
        Integer temp = sessionChannel.getExitCode();
        if (temp != null) {
            exitCode = temp.intValue();
        }
        // disconnect for now.
        //Remove this once session cache is implemented. If session is cached,
        //should call closeConnection to close the session
        //closeConnection();

        if (exitCode != 0 && forcedCleanUp) {
            kill(readerThread.getProcessID(), true);
        }
        //update streamErr with contents from stderrInputStream
        byte[] b = new byte[1024];
        int numread = stderrInputStream.read(b, 0, 1024);
        while (numread != -1) {
            streamErr.write(b, 0, numread);
            numread = stderrInputStream.read(b, 0, 1024);
        }

        // FORDEBUG
        /*System.out.println("Output===" + streamOut.toString());
        System.out.println("==Checking for error==");
        System.out.println("Error== " + streamErr.toString());
        System.out.println("Exiting GsiExec " );
        */// FORDEBUG

    } catch (Exception e) {
        throw new ExecException("Exception occured while executing command " + command + "\n" + e);
    }
    return exitCode;
}

From source file:org.springframework.integration.sftp.outbound.SftpServerOutboundTests.java

@Test
public void testInt3047ConcurrentSharedSession() throws Exception {
    final Session<?> session1 = this.sessionFactory.getSession();
    final Session<?> session2 = this.sessionFactory.getSession();
    final PipedInputStream pipe1 = new PipedInputStream();
    PipedOutputStream out1 = new PipedOutputStream(pipe1);
    final PipedInputStream pipe2 = new PipedInputStream();
    PipedOutputStream out2 = new PipedOutputStream(pipe2);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    Executors.newSingleThreadExecutor().execute(() -> {
        try {/*from www.j a  va2 s  .  co m*/
            session1.write(pipe1, "foo.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        latch1.countDown();
    });
    Executors.newSingleThreadExecutor().execute(() -> {
        try {
            session2.write(pipe2, "bar.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        latch2.countDown();
    });

    out1.write('a');
    out2.write('b');
    out1.write('c');
    out2.write('d');
    out1.write('e');
    out2.write('f');
    out1.close();
    out2.close();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
    session1.read("foo.txt", bos1);
    session2.read("bar.txt", bos2);
    assertEquals("ace", new String(bos1.toByteArray()));
    assertEquals("bdf", new String(bos2.toByteArray()));
    session1.remove("foo.txt");
    session2.remove("bar.txt");
    session1.close();
    session2.close();
}

From source file:org.kepler.ssh.SshExec.java

/**
 * Execute a command on the remote machine and expect a password/passphrase
 * question from the command. The stream <i>streamOut</i> should be provided
 * to get the output and errors merged. <i>streamErr</i> is not used in this
 * method (it will be empty string finally).
 * // ww w.j  av  a  2  s . c o  m
 * @return exit code of command if execution succeeded,
 * @throws ExecTimeoutException
 *             if the command failed because of timeout
 * @throws SshException
 *             if an error occurs for the ssh connection during the command
 *             execution Note: in this method, the SSH Channel is forcing a
 *             pseudo-terminal allocation {see setPty(true)} to allow remote
 *             commands to read something from their stdin (i.e. from us
 *             here), thus, (1) remote environment is not set from
 *             .bashrc/.cshrc and (2) stdout and stderr come back merged in
 *             one stream.
 */
public int executeCmd(String command, OutputStream streamOut, OutputStream streamErr, String thirdPartyTarget)
        throws ExecException {

    int exitCode = 0;
    String cmd = forcedCleanUp ? cleanUpInfoCmd + command : command;
    openConnection();

    // get the pwd to the third party (and perform authentication if not yet
    // done)
    String pwd = SshSession.getPwdToThirdParty(thirdPartyTarget);

    // create a piped stream to feed the input of the remote exec channel
    PipedInputStream pis = null;
    PipedOutputStream pos = null;
    if (pwd != null) {
        try {
            pis = new PipedInputStream();
            pos = new PipedOutputStream(pis);
        } catch (IOException ex) {
            log.error("Error when creating the piped stream for password feededing: " + ex);
        }
    }
    // At this point we have an opened session to the remote machine.
    // But session may be down, so this complex trial cycle here.

    boolean tryagain = true;
    while (tryagain) {
        tryagain = false;
        InputStream in = null;
        try {
            pwd = SshSession.getPwdToThirdParty(thirdPartyTarget);
            ChannelExec channel = null;
            _streamReaderThread readerThread;
            synchronized (session) {
                channel = (ChannelExec) jschSession.openChannel("exec");
                if (isDebugging)
                    log.debug("pseudoTerminal=" + pseudoTerminal);
                channel.setPty(pseudoTerminal);
                channel.setCommand(cmd);
                // channel.setOutputStream(streamOut); // use rather
                // getInputStream and read it
                channel.setErrStream(streamErr); // Useless!! stderr goes
                // into stdout
                channel.setInputStream(pis); // remote command will read
                // from our stream
                in = channel.getInputStream();

                // start output processing thread
                // it checks for timeout too
                readerThread = new _streamReaderThread(channel, in, streamOut, pwd, pos);
                readerThread.start();

                channel.connect(); // command starts here but we get back
                // the control
                // this thread runs further but reading of pis by the remote
                // process may block it
            }
            if (isDebugging) {
                log.debug("Started remote execution of command: " + command);
            }
            // wait for the reader thread to finish
            // It will timeout at the latest if the command does not finish
            // 3 ways to finish:
            // - command terminates
            // - timeout
            // - IOException when reading the command's output or writing
            // the caller's output
            readerThread.join();

            // on timeout finish here with a nice Exception
            if (readerThread.timeoutHappened()) {
                log.error("Timeout: " + timeout + "s elapsed for command " + command);
                // BUG?: disconnect does not kill the remote process!!!
                // Clean-up should be done somehow
                channel.disconnect();
                if (forcedCleanUp) {
                    // time for clean-up ;-)
                    kill(readerThread.getProcessID(), true);
                }
                throw new ExecTimeoutException(command);
            }
            // if we cannot process output, still wait for the channel to be
            // closed
            // !!! This can lead to hang-up !!!
            while (!channel.isClosed()) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                }
            }
            // command completed successfully
            if (isDebugging)
                log.debug("Command execution terminated, now waiting for the channel to be closed.");

            if (isDebugging)
                log.debug("Channel closed down, now get the exit status.");
            // this is the wrong test if the remote OS is OpenVMS,
            // but there doesn't seem to be a way to detect it.
            // Note: it must be called only when channel.isClosed() becomes
            // true.
            // Otherwise it may return -1, being not yet set to the exit
            // code
            exitCode = channel.getExitStatus();
            if (isDebugging)
                log.debug("Exit status = " + exitCode + ". Now disconnect channel.");
            // Note: The jsch source suggests that when the exit code is
            // set, the
            // package disconnects the channel, so the extra call to
            // disconnect()
            // may be unnecessary. But I inherited this way and am tired of
            // debugging...
            channel.disconnect();

            if (exitCode != 0 && forcedCleanUp) {
                // what is sure is sure ;-)
                kill(readerThread.getProcessID(), true);
            }

        } catch (JSchException ex) {
            if (ex.toString().indexOf("session is down") > -1) {
                log.error("Session to " + session.getUser() + "@" + session.getHost()
                        + " is down, try connect again");
                closeConnection();
                openConnection();
                tryagain = true;
            } else {
                throw new SshException("JSchException caught at command: " + command + "\n" + ex);
            }
        } catch (Exception e) {
            throw new SshException("Exception caught at command: " + command + "\n" + e);
        }
    } // end while

    return exitCode;

}

From source file:fi.hip.sicx.jclouds.JCloudClient.java

/**
 * Returns OutputStream that can be used to write data to the
 * specified filename in the cloud. The size of the file has to be
 * known and given.//from   www.j  ava2  s  .  c o m
 * 
 * @param fileInTheCloud Name of the file in the cloud
 * @param datasize Size of the file
 * @param sco observer
 * @return OutputStream that can be used to write data to the file in the cloud
 */
public OutputStream writeData(String infileInTheCloud, int indatasize, StorageClientObserver sco) {

    // Save parameters
    this.datasize = indatasize;
    this.fileInTheCloud = infileInTheCloud;

    // Filesystem is missing this feature so this is a workaround for now
    if (this.provider.equals("filesystem")) {
        // Create temporary test file
        String body = "sixc_secret_data1" + infileInTheCloud;
        String ending = ".tmp";
        try {
            this.fs_outfile = File.createTempFile(body, ending, null);
            this.fs_outstream = new FileOutputStream(this.fs_outfile);
            this.dos = new DataOutputStream(this.fs_outstream); // This is needed to know the number of bytes
                                                                // written
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this.dos;
    }

    // Lets make pipe where data can be written
    this.cis = null;
    this.in = new PipedInputStream();
    this.out = null;
    try {
        this.out = new PipedOutputStream(this.in);
        this.dos = new DataOutputStream(this.out); // This is needed to know the number of bytes written
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.writeToBlob = blobStore.blobBuilder(fileInTheCloud).payload(in).contentLength(this.datasize).build();
    this.responses = Maps.newHashMap();

    this.responses.put(this.writeToBlob, context.getAsyncBlobStore().putBlob(containerName, writeToBlob));

    return dos;
}