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:eu.stratosphere.pact.runtime.task.util.OutputEmitterTest.java

@Test
public void testWrongKeyClass() {

    // Test for IntValue
    @SuppressWarnings("unchecked")
    final TypeComparator<Record> doubleComp = new RecordComparatorFactory(new int[] { 0 },
            new Class[] { DoubleValue.class }).createComparator();
    final ChannelSelector<SerializationDelegate<Record>> oe1 = new OutputEmitter<Record>(
            ShipStrategyType.PARTITION_HASH, doubleComp);
    final SerializationDelegate<Record> delegate = new SerializationDelegate<Record>(
            new RecordSerializerFactory().getSerializer());

    PipedInputStream pipedInput = new PipedInputStream(1024 * 1024);
    DataInputStream in = new DataInputStream(pipedInput);
    DataOutputStream out;// w ww  .j av a 2  s  .c om
    Record rec = null;

    try {
        out = new DataOutputStream(new PipedOutputStream(pipedInput));

        rec = new Record(1);
        rec.setField(0, new IntValue());

        rec.write(out);
        rec = new Record();
        rec.read(in);

    } catch (IOException e) {
        fail("Test erroneous");
    }

    try {
        delegate.setInstance(rec);
        oe1.selectChannels(delegate, 100);
    } catch (DeserializationException re) {
        return;
    }
    Assert.fail("Expected a NullKeyFieldException.");
}

From source file:org.cloudifysource.shell.commands.TestRecipe.java

/**
 * Execute a command line in with a given map of environment settings. The execution outupt is filtered unless
 * verbose is set to true./*  w w w.ja  v  a 2 s.  c  o  m*/
 *
 * @param cmdLine
 *            The command to execute
 * @param env
 *            Environment settings available for the command execution
 * @return the command's execution exit code, or -2 if the command failed to execute
 */
private int executeRecipe(final CommandLine cmdLine, final Map<Object, Object> env) {
    final DefaultExecutor executor = new DefaultExecutor();

    // The watchdog will terminate the process if it does not end within the
    // specified timeout
    final int externalProcessTimeout = (this.timeout + EXTERNAL_PROCESS_WATCHDOG_ADDITIONAL_TIMEOUT) * 1000;
    final ExecuteWatchdog watchdog = new TestRecipeWatchdog(externalProcessTimeout);
    executor.setWatchdog(watchdog);

    executor.setExitValue(0);
    int result = -1;

    PipedInputStream in = null;
    PipedOutputStream out = null;
    BufferedReader reader = null;
    try {
        in = new PipedInputStream();
        out = new PipedOutputStream(in);
        reader = new BufferedReader(new InputStreamReader(in));

        final Thread thread = new Thread(new FilteredOutputHandler(reader, this.verbose));
        thread.setDaemon(true);
        thread.start();

        final PumpStreamHandler psh = new PumpStreamHandler(out, out);
        executor.setStreamHandler(psh);
        result = executor.execute(cmdLine, env);
    } catch (final ExecuteException e) {
        logger.log(Level.SEVERE, "A problem was encountered while executing the recipe: " + e.getMessage(), e);
    } catch (final IOException e) {
        logger.log(Level.SEVERE,
                "An IO Exception was encountered while executing the recipe: " + e.getMessage(), e);
        result = UNEXPECTED_ERROR_EXIT_CODE;
    }

    return result;
}

From source file:org.apache.flink.runtime.operators.util.OutputEmitterTest.java

@Test
public void testWrongKeyClass() {

    // Test for IntValue
    @SuppressWarnings("unchecked")
    final TypeComparator<Record> doubleComp = new RecordComparatorFactory(new int[] { 0 },
            new Class[] { DoubleValue.class }).createComparator();
    final ChannelSelector<SerializationDelegate<Record>> oe1 = new OutputEmitter<Record>(
            ShipStrategyType.PARTITION_HASH, doubleComp);
    final SerializationDelegate<Record> delegate = new SerializationDelegate<Record>(
            new RecordSerializerFactory().getSerializer());

    PipedInputStream pipedInput = new PipedInputStream(1024 * 1024);
    DataInputStream in = new DataInputStream(pipedInput);
    DataOutputStream out;/*from ww  w.ja v  a  2s. c om*/
    Record rec = null;

    try {
        out = new DataOutputStream(new PipedOutputStream(pipedInput));

        rec = new Record(1);
        rec.setField(0, new IntValue());

        rec.write(new OutputViewDataOutputStreamWrapper(out));
        rec = new Record();
        rec.read(new InputViewDataInputStreamWrapper(in));

    } catch (IOException e) {
        fail("Test erroneous");
    }

    try {
        delegate.setInstance(rec);
        oe1.selectChannels(delegate, 100);
    } catch (DeserializationException re) {
        return;
    }
    Assert.fail("Expected a NullKeyFieldException.");
}

From source file:net.wastl.webmail.plugins.SendMessage.java

public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head)
        throws WebMailException, ServletException {
    if (sess1 == null) {
        throw new WebMailException(
                "No session was given. If you feel this is incorrect, please contact your system administrator");
    }/*from w w  w  . jav  a2  s  .  c o  m*/
    WebMailSession session = (WebMailSession) sess1;
    UserData user = session.getUser();
    HTMLDocument content;

    Locale locale = user.getPreferredLocale();

    /* Save message in case there is an error */
    session.storeMessage(head);

    if (head.isContentSet("SEND")) {
        /* The form was submitted, now we will send it ... */
        try {
            MimeMessage msg = new MimeMessage(mailsession);

            Address from[] = new Address[1];
            try {
                /**
                 * Why we need
                 * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()?
                 *
                 * Because we specify client browser's encoding to UTF-8, IE seems
                 * to send all data encoded in UTF-8. We have to transcode all byte
                 * sequences we received to UTF-8, and next we encode those strings
                 * using MimeUtility.encodeText() depending on user's locale. Since
                 * MimeUtility.encodeText() is used to convert the strings into its
                 * transmission format, finally we can use the strings in the
                 * outgoing e-mail which relies on receiver's email agent to decode
                 * the strings.
                 *
                 * As described in JavaMail document, MimeUtility.encodeText() conforms
                 * to RFC2047 and as a result, we'll get strings like "=?Big5?B......".
                 */
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()),
                //                  MimeUtility.encodeText(session.getUser().getFullName()));
                from[0] = new InternetAddress(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale),
                        TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null,
                                locale));
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName());
            }

            StringTokenizer t;
            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("TO").trim(), ",;");
            }

            /* Check To: field, when empty, throw an exception */
            if (t.countTokens() < 1) {
                throw new MessagingException("The recipient field must not be empty!");
            }
            Address to[] = new Address[t.countTokens()];
            int i = 0;
            while (t.hasMoreTokens()) {
                to[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("CC").trim(), ",;");
            }
            Address cc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                cc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("BCC").trim(), ",;");
            }
            Address bcc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                bcc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            session.setSent(false);

            msg.addFrom(from);
            if (to.length > 0) {
                msg.addRecipients(Message.RecipientType.TO, to);
            }
            if (cc.length > 0) {
                msg.addRecipients(Message.RecipientType.CC, cc);
            }
            if (bcc.length > 0) {
                msg.addRecipients(Message.RecipientType.BCC, bcc);
            }
            msg.addHeader("X-Mailer",
                    WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion());

            String subject = null;

            if (!head.isContentSet("SUBJECT")) {
                subject = "no subject";
            } else {
                try {
                    // subject=MimeUtility.encodeText(head.getContent("SUBJECT"));
                    subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1",
                            locale);
                } catch (UnsupportedEncodingException e) {
                    log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                    subject = head.getContent("SUBJECT");
                }
            }

            msg.addHeader("Subject", subject);

            if (head.isContentSet("REPLY-TO")) {
                // msg.addHeader("Reply-To",head.getContent("REPLY-TO"));
                msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"),
                        "ISO8859_1", locale));
            }

            msg.setSentDate(new Date(System.currentTimeMillis()));

            String contnt = head.getContent("BODY");

            //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
            String charset = "utf-8";

            MimeMultipart cont = new MimeMultipart();
            MimeBodyPart txt = new MimeBodyPart();

            // Transcode to UTF-8
            contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8");
            // Encode text
            if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                txt.setText(contnt, "Big5");
                txt.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            } else {
                txt.setText(contnt, "utf-8");
                txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            }

            /* Add an advertisement if the administrator requested to do so */
            cont.addBodyPart(txt);
            if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) {
                MimeBodyPart adv = new MimeBodyPart();
                String file = "";
                if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) {
                    file = store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                } else {
                    file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator")
                            + store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                }
                String advcont = "";
                try {
                    BufferedReader fin = new BufferedReader(new FileReader(file));
                    String line = fin.readLine();
                    while (line != null && !line.equals("")) {
                        advcont += line + "\n";
                        line = fin.readLine();
                    }
                    fin.close();
                } catch (IOException ex) {
                }

                /**
                 * Transcode to UTF-8; Since advcont comes from file, we transcode
                 * it from default encoding.
                 */
                // Encode text
                if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                    advcont = new String(advcont.getBytes(), "Big5");
                    adv.setText(advcont, "Big5");
                    adv.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                } else {
                    advcont = new String(advcont.getBytes(), "UTF-8");
                    adv.setText(advcont, "utf-8");
                    adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                }

                cont.addBodyPart(adv);
            }
            for (String attachmentKey : session.getAttachments().keySet()) {
                ByteStore bs = session.getAttachment(attachmentKey);
                InternetHeaders ih = new InternetHeaders();
                ih.addHeader("Content-Transfer-Encoding", "BASE64");

                PipedInputStream pin = new PipedInputStream();
                PipedOutputStream pout = new PipedOutputStream(pin);

                /* This is used to write to the Pipe asynchronously to avoid blocking */
                StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000);
                BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64"));
                encoder.write(bs.getBytes());
                encoder.flush();
                encoder.close();
                //MimeBodyPart att1=sconn.getResult();
                MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes());

                if (bs.getDescription() != "") {
                    att1.setDescription(bs.getDescription(), "utf-8");
                }
                /**
                 * As described in FileAttacher.java line #95, now we need to
                 * encode the attachment file name.
                 */
                // att1.setFileName(bs.getName());
                String fileName = bs.getName();
                String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry());
                String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null);
                if (encodedFileName.equals(fileName)) {
                    att1.addHeader("Content-Type", bs.getContentType());
                    att1.setFileName(fileName);
                } else {
                    att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset);
                    encodedFileName = encodedFileName.substring(localeCharset.length() + 5,
                            encodedFileName.length() - 2);
                    encodedFileName = encodedFileName.replace('=', '%');
                    att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''"
                            + encodedFileName);
                }
                cont.addBodyPart(att1);
            }
            msg.setContent(cont);
            //              }

            msg.saveChanges();

            boolean savesuccess = true;

            msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid"));
            if (session.getUser().wantsSaveSent()) {
                String folderhash = session.getUser().getSentFolder();
                try {
                    Folder folder = session.getFolder(folderhash);
                    Message[] m = new Message[1];
                    m[0] = msg;
                    folder.appendMessages(m);
                } catch (MessagingException e) {
                    savesuccess = false;
                } catch (NullPointerException e) {
                    // Invalid folder:
                    savesuccess = false;
                }
            }

            boolean sendsuccess = false;

            try {
                Transport.send(msg);
                Address sent[] = new Address[to.length + cc.length + bcc.length];
                int c1 = 0;
                int c2 = 0;
                for (c1 = 0; c1 < to.length; c1++) {
                    sent[c1] = to[c1];
                }
                for (c2 = 0; c2 < cc.length; c2++) {
                    sent[c1 + c2] = cc[c2];
                }
                for (int c3 = 0; c3 < bcc.length; c3++) {
                    sent[c1 + c2 + c3] = bcc[c3];
                }
                sendsuccess = true;
                throw new SendFailedException("success", new Exception("success"), sent, null, null);
            } catch (SendFailedException e) {
                session.handleTransportException(e);
            }

            //session.clearMessage();

            content = new XHTMLDocument(session.getModel(),
                    store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme()));
            //              if(sendsuccess) session.clearWork();
        } catch (Exception e) {
            log.error("Could not send messsage", e);
            throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")");
        }

    } else if (head.isContentSet("ATTACH")) {
        /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to
           have two targets without Javascript) */
        content = parent.getURLHandler().handleURL("/compose/attach", session, head);
    } else {
        throw new DocumentNotFoundException("Could not send message. (Reason: No content given)");
    }
    return content;
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

/**
 * {@inheritDoc}/*from ww  w .j a v a 2s  . c o  m*/
 */
@Override
public void sendEmail(Session session, final MimeMessage message) throws Exception {
    boolean haveSession = false;

    try {
        if (session != null && session.isLive()) {
            haveSession = true;
        } else {
            session = repository.loginAdministrative(null);
        }

        // Store mail to Spool folder
        Node mailNode = session.getRootNode().getNode(spoolFolder).addNode(UUID.randomUUID().toString(),
                nodeType);
        mailNode = mailNode.addNode(propertyName, "nt:resource");

        PipedInputStream in = new PipedInputStream();
        final PipedOutputStream out = new PipedOutputStream(in);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    message.writeTo(out);
                    out.close();
                } catch (IOException e) {
                    log.error("Could not write mail message stream", e);
                } catch (MessagingException e) {
                    log.error("Could not write mail message stream", e);
                }
            }
        }).start();
        BinaryValue bv = null;
        try {
            bv = new BinaryValue(in);
        } catch (IllegalArgumentException e) {
            // The jackrabbit closes the PipedInputStream, thats incorrect
        }
        if (bv != null) {
            mailNode.setProperty("jcr:data", bv);
        }
        mailNode.setProperty("jcr:lastModified", Calendar.getInstance());
        mailNode.setProperty("jcr:mimeType", "message/rfc822");

    } catch (Exception ex) {
        log.error("Cannot create mail: ", ex);
        throw ex;
    } finally {
        if (!haveSession && session != null) {
            if (session.hasPendingChanges())
                try {
                    session.save();
                } catch (Throwable th) {
                }
            session.logout();
        }
    }
}

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  a  va  2  s. c om
 * 
 * @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;//from   ww w  .ja v  a2 s  .  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. j a  v  a2s .c om
 * @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));
    }//  ww w.j  a  v  a2 s .com
    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 w ww .j  a  v  a2s  .  c  o  m*/
    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;
}