List of usage examples for java.io PipedInputStream PipedInputStream
public PipedInputStream()
PipedInputStream
so that it is not yet #connect(java.io.PipedOutputStream) connected . From source file:org.whitesource.agent.utils.ZipUtils.java
private static void fillExportStreamCompress(InputStream inputStream, OutputStream outputStream) { try {/*from ww w. ja v a 2 s. c o m*/ try (PipedInputStream pipedInputStream = new PipedInputStream()) { try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) { pipedInputStream.connect(pipedOutputStream); Runnable producer = new Runnable() { @Override public void run() { produceCompressDataFromStream(inputStream, pipedOutputStream); } }; Runnable consumer = new Runnable() { @Override public void run() { consumeCompressData(pipedInputStream, outputStream); } }; transferData(producer, consumer); } } } catch (IOException e) { // logger.error("Failed to produce data :", e); } }
From source file:org.wso2.carbon.dataservices.sql.driver.TDriverUtil.java
/** * Method to write excel data to registry or file output streams. * * @param workbook//w w w .j a va 2s. co 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:org.whitesource.agent.utils.ZipUtils.java
private static void fillExportStreamCompress(String text, OutputStream exportByteArrayOutputStream) { try {//from w w w . ja v a 2s . com try (PipedInputStream pipedInputStream = new PipedInputStream()) { try (PipedOutputStream pipedOutputStream = new PipedOutputStream()) { pipedInputStream.connect(pipedOutputStream); Runnable producer = new Runnable() { @Override public void run() { produceCompressDataFromText(text, pipedOutputStream); } }; Runnable consumer = new Runnable() { @Override public void run() { consumeCompressData(pipedInputStream, exportByteArrayOutputStream); } }; transferData(producer, consumer); } } } catch (IOException e) { // logger.error("Failed to produce data :", e); } }
From source file:edu.jhu.pha.vospace.node.ContainerNode.java
@Override public InputStream exportData() { final PipedInputStream pipedIn = new PipedInputStream(); PipedOutputStream pipedOut = null; try {/*from w w w . j a va2 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 w w w .ja v a2 s .c om 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(); }// w w w . ja v a2 s .c o m 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 {//w w w . ja v a 2s. c o 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 w w w. jav a 2 s .c om*/ 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. ja v a 2 s. c om 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.apache.pig.shock.SSHSocketImplFactory.java
@Override protected void connect(SocketAddress address, int timeout) throws IOException { try {// w w w . ja v a 2 s . c o m if (!session.isConnected()) { session.connect(); } channel = (ChannelDirectTCPIP) session.openChannel("direct-tcpip"); //is = channel.getInputStream(); //os = channel.getOutputStream(); channel.setHost(((InetSocketAddress) address).getHostName()); channel.setPort(((InetSocketAddress) address).getPort()); channel.setOrgPort(22); is = new PipedInputStream(); os = new PipedOutputStream(); channel.setInputStream(new PipedInputStream((PipedOutputStream) os)); channel.setOutputStream(new PipedOutputStream((PipedInputStream) is)); channel.connect(); if (!channel.isConnected()) { log.error("Not connected"); } if (channel.isEOF()) { log.error("EOF"); } } catch (JSchException e) { log.error(e); IOException newE = new IOException(e.getMessage()); newE.setStackTrace(e.getStackTrace()); throw newE; } }