Example usage for java.io PipedInputStream PipedInputStream

List of usage examples for java.io PipedInputStream PipedInputStream

Introduction

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

Prototype

public PipedInputStream() 

Source Link

Document

Creates a PipedInputStream so that it is not yet #connect(java.io.PipedOutputStream) connected .

Usage

From source file:org.apache.james.mailrepository.jcr.JCRMailRepository.java

/**
 * Writes the message content to the <code>jcr:content/jcr:data</code>
 * binary property.//w w w  . j ava  2 s .co  m
 * 
 * @param node
 *            mail node
 * @param message
 *            mail message
 * @throws MessagingException
 *             if a messaging error occurs
 * @throws RepositoryException
 *             if a repository error occurs
 * @throws IOException
 *             if an IO error occurs
 */
@SuppressWarnings("deprecation")
private void setMessage(Node node, final MimeMessage message) throws RepositoryException, IOException {
    try {
        node = node.getNode("jcr:content");
    } catch (PathNotFoundException e) {
        node = node.getProperty("jcr:content").getNode();
    }

    PipedInputStream input = new PipedInputStream();
    final PipedOutputStream output = new PipedOutputStream(input);
    new Thread() {
        public void run() {
            try {
                message.writeTo(output);
            } catch (Exception e) {
            } finally {
                try {
                    output.close();
                } catch (IOException e) {
                }
            }
        }
    }.start();
    node.setProperty("jcr:data", input);
}

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;/*  ww  w .ja va  2s .  c om*/
    while ((line = br.readLine()) != null) {
        LOG.info("line = " + line);
        if (!line.contains(jobId)) {
            continue;
        }
        assertTrue(line.contains(priority));
        break;
    }
    pis.close();
}

From source file:com.github.vatbub.awsvpnlauncher.Main.java

/**
 * Launches a new VPN server on AWS EC2 if everything is configured
 *
 * @see PropertyNotConfiguredException// w  w  w .ja va 2 s  .com
 * @see #terminate()
 */
private static void launch() {
    File privateKey = new File(prefs.getPreference(Property.privateKeyFile));
    vpnPassword = prefs.getPreference(Property.openvpnPassword);

    if (!privateKey.exists() && !privateKey.isFile()) {
        throw new IllegalArgumentException("The file specified as " + Property.privateKeyFile.toString()
                + " does not exist or is not a file.");
    }

    FOKLogger.info(Main.class.getName(), "Preparing...");

    try {
        // Check if our security group exists already
        FOKLogger.info(Main.class.getName(), "Checking for the required security group...");
        DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest()
                .withGroupNames(securityGroupName);

        List<String> securityGroups = new ArrayList<>();
        boolean created = false; // will become true if the security group had to be created to avoid duplicate logs
        String securityGroupId;
        try {
            DescribeSecurityGroupsResult describeSecurityGroupsResult = client
                    .describeSecurityGroups(describeSecurityGroupsRequest);
            securityGroupId = describeSecurityGroupsResult.getSecurityGroups().get(0).getGroupId();
        } catch (AmazonEC2Exception e) {
            // Security group does not exist, create the security group
            created = true;
            FOKLogger.info(Main.class.getName(), "Creating the required security group...");
            CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest()
                    .withGroupName(securityGroupName).withDescription(
                            "This security group was automatically created to run a OpenVPN Access Server.");
            CreateSecurityGroupResult createSecurityGroupResult = client
                    .createSecurityGroup(createSecurityGroupRequest);

            securityGroupId = createSecurityGroupResult.getGroupId();

            IpRange ipRange = new IpRange().withCidrIp("0.0.0.0/0");
            IpPermission sshPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(22).withToPort(22);
            IpPermission sshPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(943).withToPort(943);
            IpPermission httpsPermission1 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("tcp")
                    .withFromPort(443).withToPort(443);
            IpPermission httpsPermission2 = new IpPermission().withIpv4Ranges(ipRange).withIpProtocol("udp")
                    .withFromPort(1194).withToPort(1194);

            AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
                    .withGroupName(securityGroupName).withIpPermissions(sshPermission1)
                    .withIpPermissions(sshPermission2).withIpPermissions(httpsPermission1)
                    .withIpPermissions(httpsPermission2);

            // retry while the security group is not yet ready
            int retries = 0;
            long lastPollTime = System.currentTimeMillis();
            boolean requestIsFailing = true;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPollTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    lastPollTime = System.currentTimeMillis();
                    try {
                        client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
                        // no exception => we made it
                        requestIsFailing = false;
                    } catch (AmazonEC2Exception e2) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the security group to be created, api error message is currently: "
                                        + e2.getMessage());
                        requestIsFailing = true;
                    }
                }
            } while (requestIsFailing);
            FOKLogger.info(Main.class.getName(), "The required security group has been successfully created!");
        }

        if (!created) {
            FOKLogger.info(Main.class.getName(), "The required security group already exists, we can continue");
        }
        securityGroups.add(securityGroupId);

        securityGroups.add(securityGroupId);

        FOKLogger.info(Main.class.getName(), "Creating the RunInstanceRequest...");
        RunInstancesRequest request = new RunInstancesRequest(getAmiId(awsRegion), 1, 1);
        request.setInstanceType(InstanceType.T2Micro);
        request.setKeyName(prefs.getPreference(Property.awsKeyPairName));
        request.setSecurityGroupIds(securityGroups);

        FOKLogger.info(Main.class.getName(), "Starting the EC2 instance...");
        RunInstancesResult result = client.runInstances(request);
        List<Instance> instances = result.getReservation().getInstances();

        // SSH config
        FOKLogger.info(Main.class.getName(), "Configuring SSH...");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        jsch.addIdentity(privateKey.getAbsolutePath());
        int retries = 0;

        for (Instance instance : instances) {
            // write the instance id to a properties file to be able to terminate it later on again
            prefs.reload();
            if (prefs.getPreference("instanceIDs", "").equals("")) {
                prefs.setPreference("instanceIDs", instance.getInstanceId());
            } else {
                prefs.setPreference("instanceIDs",
                        prefs.getPreference("instanceIDs", "") + ";" + instance.getInstanceId());
            }

            // Connect to the instance using ssh
            FOKLogger.info(Main.class.getName(), "Waiting for the instance to boot...");

            long lastPrintTime = System.currentTimeMillis();
            DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
            List<String> instanceId = new ArrayList<>(1);
            instanceId.add(instance.getInstanceId());
            describeInstancesRequest.setInstanceIds(instanceId);
            DescribeInstancesResult describeInstancesResult;
            newInstance = instance;

            do {
                // we're waiting

                if (System.currentTimeMillis() - lastPrintTime >= Math.pow(2, retries) * 100) {
                    retries = retries + 1;
                    describeInstancesResult = client.describeInstances(describeInstancesRequest);
                    newInstance = describeInstancesResult.getReservations().get(0).getInstances().get(0);
                    lastPrintTime = System.currentTimeMillis();
                    if (newInstance.getState().getCode() != 16) {
                        FOKLogger.info(Main.class.getName(),
                                "Still waiting for the instance to boot, current instance state is "
                                        + newInstance.getState().getName());
                    }
                }
            } while (newInstance.getState().getCode() != 16);

            FOKLogger.info(Main.class.getName(), "Instance is " + newInstance.getState().getName());

            // generate the ssh ip of the instance
            String sshIp = newInstance.getPublicDnsName();

            FOKLogger.info(Main.class.getName(), "The instance id is " + newInstance.getInstanceId());
            FOKLogger.info(Main.class.getName(), "The instance ip is " + newInstance.getPublicIpAddress());
            FOKLogger.info(Main.class.getName(), "Connecting using ssh to " + sshUsername + "@" + sshIp);
            FOKLogger.info(Main.class.getName(),
                    "The instance will need some time to configure ssh on its end so some connection timeouts are normal");
            boolean retry;
            session = jsch.getSession(sshUsername, sshIp, 22);
            session.setConfig(sshConfig);
            do {
                try {
                    session.connect();
                    retry = false;
                } catch (Exception e) {
                    FOKLogger.info(Main.class.getName(), e.getClass().getName() + ": " + e.getMessage()
                            + ", retrying, Press Ctrl+C to cancel");
                    retry = true;
                }
            } while (retry);

            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");
            FOKLogger.info(Main.class.getName(), "The following is the out- and input of the ssh session.");
            FOKLogger.info(Main.class.getName(), "Please note that out- and input may appear out of sync.");
            FOKLogger.info(Main.class.getName(),
                    "----------------------------------------------------------------------");

            PipedInputStream sshIn = new PipedInputStream();
            PipedOutputStream sshIn2 = new PipedOutputStream(sshIn);
            PrintStream sshInCommandStream = new PrintStream(sshIn2);
            Channel channel = session.openChannel("shell");
            channel.setInputStream(sshIn);
            channel.setOutputStream(new MyPrintStream());
            channel.connect();

            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("1\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("yes\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("\n");
            sshInCommandStream.print("echo \"" + adminUsername + ":" + vpnPassword + "\" | sudo chpasswd\n");
            sshInCommandStream.print("exit\n");

            NullOutputStream nullOutputStream = new NullOutputStream();
            Thread watchForSSHDisconnectThread = new Thread(() -> {
                while (channel.isConnected()) {
                    nullOutputStream.write(0);
                }
                // disconnected
                cont();
            });
            watchForSSHDisconnectThread.setName("watchForSSHDisconnectThread");
            watchForSSHDisconnectThread.start();
        }
    } catch (JSchException | IOException e) {
        e.printStackTrace();
        if (session != null) {
            session.disconnect();
        }
        System.exit(1);
    }
}

From source file:org.elasticsearch.index.mapper.attachment.AttachmentMapper.java

private Map<String, Object> parseAndCalculateChecksumWithThreads(XContentParser parser, int indexedChars)
        throws SecurityException, IllegalAccessException, NoSuchFieldException, IOException,
        InterruptedException, ExecutionException, TimeoutException {

    Map<String, Object> resultMap = new HashMap<String, Object>();
    Metadata metadata = new Metadata();
    JsonParser jsonParser = getInternalJsonParser(parser);

    PipedInputStream pipedIs = new PipedInputStream();
    PipedOutputStream pipedOs = new PipedOutputStream(pipedIs);

    PipedInputStream pipedIs2 = new PipedInputStream();
    PipedOutputStream pipedOs2 = new PipedOutputStream(pipedIs2);

    ExecutorService pool = Executors.newFixedThreadPool(2);
    Future future = pool.submit(new ParsingThread(pipedIs, metadata, indexedChars));
    Future checksumFuture = null;
    if (calculateChecksum) {
        checksumFuture = pool.submit(new CalcualteChecksumThread(pipedIs2));
    }/*from w w  w  . j  a v  a 2 s.co  m*/
    TeeOutputStream tos = new TeeOutputStream(pipedOs, pipedOs2);
    int readBinaryValue = jsonParser.readBinaryValue(tos);
    // tee stream perhaps
    IOUtils.closeQuietly(tos);
    IOUtils.closeQuietly(pipedOs);
    IOUtils.closeQuietly(pipedOs2);

    System.out.println("main thread finish read" + readBinaryValue);
    ParseResult parseResult = (ParseResult) future.get(10 * 100, TimeUnit.SECONDS);
    CalcualteChecksumResult checksumResult = null;
    if (calculateChecksum && checksumFuture != null) {
        checksumResult = (CalcualteChecksumResult) checksumFuture.get(10 * 100, TimeUnit.SECONDS);
        System.out.println(checksumResult.checksum);
    }
    System.out.println("parseResult");
    metadata = parseResult.metadata;
    // although metadata is reference, better return and use for easier
    // refactoring laters
    System.out.println(metadata);
    System.out.println("Thread join");
    pool.shutdown();
    pool.awaitTermination(10 * 100, TimeUnit.SECONDS);
    //TODO align static class and map
    resultMap.put("parseResult", parseResult);
    resultMap.put("checksumResult", checksumResult);
    return resultMap;
}

From source file:org.keycloak.testsuite.AbstractKeycloakTest.java

protected static InputStream httpsAwareConfigurationStream(InputStream input) throws IOException {
    if (!AUTH_SERVER_SSL_REQUIRED) {
        return input;
    }/*from   www.  ja  v  a  2  s . c om*/
    PipedInputStream in = new PipedInputStream();
    final PipedOutputStream out = new PipedOutputStream(in);
    try (PrintWriter pw = new PrintWriter(out)) {
        try (Scanner s = new Scanner(input)) {
            while (s.hasNextLine()) {
                String lineWithReplaces = s.nextLine().replace("http://localhost:8180/auth",
                        AUTH_SERVER_SCHEME + "://localhost:" + AUTH_SERVER_PORT + "/auth");
                pw.println(lineWithReplaces);
            }
        }
    }
    return in;
}

From source file:com.aurel.track.lucene.util.StringUtilTest.java

/**
 * Run the String read(InputStream) method test.
 *
 * @throws Exception//from ww  w  .ja v  a2 s. c o m
 *
 * @generatedBy CodePro at 13.04.15 23:38
 */
@Test(expected = java.io.IOException.class)
public void testRead_1() throws Exception {
    InputStream is = new PipedInputStream();

    String result = StringUtil.read(is);

    // add additional test code here
    assertNotNull(result);
}

From source file:com.aurel.track.lucene.util.StringUtilTest.java

/**
 * Run the String read(InputStream) method test.
 *
 * @throws Exception/*from  ww w  .  j a  v a2  s.c o  m*/
 *
 * @generatedBy CodePro at 13.04.15 23:38
 */
@Test(expected = java.io.IOException.class)
public void testRead_2() throws Exception {
    InputStream is = new PipedInputStream();

    String result = StringUtil.read(is);

    // add additional test code here
    assertNotNull(result);
}

From source file:com.aurel.track.lucene.util.StringUtilTest.java

/**
 * Run the String read(InputStream) method test.
 *
 * @throws Exception//  ww w.  j av a2 s  .c  o  m
 *
 * @generatedBy CodePro at 13.04.15 23:38
 */
@Test(expected = java.io.IOException.class)
public void testRead_3() throws Exception {
    InputStream is = new PipedInputStream();

    String result = StringUtil.read(is);

    // add additional test code here
    assertNotNull(result);
}

From source file:com.aurel.track.lucene.util.StringUtilTest.java

/**
 * Run the String read(InputStream) method test.
 *
 * @throws Exception//from  w w w  . j  a  v a  2s  . com
 *
 * @generatedBy CodePro at 13.04.15 23:38
 */
@Test(expected = java.io.IOException.class)
public void testRead_4() throws Exception {
    InputStream is = new PipedInputStream();

    String result = StringUtil.read(is);

    // add additional test code here
    assertNotNull(result);
}

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());
    }/* w w w  .  ja va 2  s.  com*/

    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();

}