Example usage for java.io PrintStream flush

List of usage examples for java.io PrintStream flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * @param message//from  w w w  . jav  a 2  s .c  om
 *            the message as a string, that should send.
 * @return the result of the call
 * @throws UnknownHostException
 * @throws IOException
 */
private boolean sendMessage(String message) {

    StringBuilder result = new StringBuilder();

    try {
        Socket client = getSocket();

        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println(message);
        LOGGER.info("Send message to AUT:" + message);
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));

        int c;
        while ((c = in.read()) != -1) {
            result.append((char) c);
        }
        String myMessage = result.toString();
        if (myMessage.indexOf("ERROR ") > -1) {
            LOGGER.error("Fails: " + myMessage);
            throw new RuntimeException("Message: " + message + " fails with: " + myMessage);
        }

        client.close();

    } catch (UnknownHostException e) {
        LOGGER.error("SendMessage Host not Found", e);
    } catch (IOException e) {
        LOGGER.error("Send Message IOException ", e);
    }
    if (result.toString().startsWith("true")) {
        return true;
    }
    return false;
}

From source file:com.isentropy.accumulo.collections.AccumuloSortedMap.java

public void dump(PrintStream ps, int max_values_per_key) {
    K prev = null;/*from  w w w  . jav a 2 s  . c  om*/
    int valuesShown = 0;
    for (Iterator<Entry<K, V>> it = multiEntryIterator(); it.hasNext();) {
        Entry<K, V> e = it.next();
        K k = e.getKey();
        if (prev == null || !k.equals(prev)) {
            valuesShown = 0;
        }
        if (max_values_per_key < 0 || valuesShown++ < max_values_per_key) {
            ps.println(formatDumpLine(e));
        }
    }
    ps.flush();
}

From source file:edu.cornell.med.icb.goby.modes.SequenceVariationStatsMode.java

/**
 * Display sequence variations./*ww  w  .  jav a2s  .c om*/
 *
 * @throws java.io.IOException error reading / writing
 */
@Override
public void execute() throws IOException {
    PrintStream stream = null;
    try {
        stream = outputFilename == null ? System.out : new PrintStream(new FileOutputStream(outputFilename));
        switch (outputFormat) {
        case TAB_DELIMITED:
        case TSV:
            stream.println(
                    "basename\tread-index\tcount-variation-bases\tbases-at-index/all-variations-bases\tbases-at-index/all-reference-bases\tcount-reference-bases");
            break;
        }

        for (final String basename : basenames) {
            alignmentIterator.resetTallies();
            final String[] singleBasename = { basename };
            // Iterate through each alignment and write sequence variations to output file:
            alignmentIterator.iterate(singleBasename);

            final Long2LongMap readIndexTallies = alignmentIterator.getReadIndexVariationTally();
            final double totalNumberOfVariationBases = sum(readIndexTallies.values());
            final double numberOfAlignmentEntries = alignmentIterator.getNumAlignmentEntries();

            final long countReferenceBases = alignmentIterator.getReferenceBaseCount();
            for (final long readIndex : readIndexTallies.keySet()) {
                final long countVariationBasesAtReadIndex = readIndexTallies.get(readIndex);
                final double frequency = ((double) countVariationBasesAtReadIndex)
                        / totalNumberOfVariationBases;
                final double alignFrequency = ((double) countVariationBasesAtReadIndex) / countReferenceBases;

                stream.printf("%s\t%d\t%d\t%s\t%f\t%d%n", FilenameUtils.getBaseName(basename), readIndex,
                        countVariationBasesAtReadIndex, frequency, alignFrequency, countReferenceBases);
            }
            stream.flush();
        }
    } finally {
        if (stream != System.out) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:com.act.lcms.plotter.WriteAndPlotMS1Results.java

public List<Pair<String, String>> writeMS1Values(Map<String, List<XZ>> ms1s, Double maxIntensity,
        Map<String, Double> metlinMzs, OutputStream os, boolean heatmap, boolean applyThreshold,
        Set<String> ionsToWrite) throws IOException {
    // Write data output to outfile
    PrintStream out = new PrintStream(os);

    List<Pair<String, String>> plotID = new ArrayList<>(ms1s.size());
    for (Map.Entry<String, List<XZ>> ms1ForIon : ms1s.entrySet()) {
        String ion = ms1ForIon.getKey();
        // Skip ions not in the ionsToWrite set if that set is defined.
        if (ionsToWrite != null && !ionsToWrite.contains(ion)) {
            continue;
        }//from  ww  w  .ja  v  a 2 s  . c  om

        List<XZ> ms1 = ms1ForIon.getValue();
        String plotName = String.format("ion: %s, mz: %.5f", ion, metlinMzs.get(ion));
        plotID.add(Pair.of(ion, plotName));
        // print out the spectra to outDATA
        for (XZ xz : ms1) {
            if (heatmap) {
                /*
                * When we are building heatmaps, we use gnuplots pm3d package
                * along with `dgrid3d 2000,2` (which averages data into grids
                * that are 2000 on the time axis and 2 in the y axis), and
                * `view map` that flattens a 3D graphs into a 2D view.
                * We want time to be on the x-axis and intensity on the z-axis
                * (because that is the one that is mapped to heat colors)
                * but then we need an artificial y-axis. We create proxy y=1
                * and y=2 datapoints, and then dgrid3d averaging over 2 creates
                * a vertical "strip".
                */
                out.format("%.4f\t1\t%.4f\n", xz.getTime(), xz.getIntensity());
                out.format("%.4f\t2\t%.4f\n", xz.getTime(), xz.getIntensity());
            } else {
                out.format("%.4f\t%.4f\n", xz.getTime(), xz.getIntensity());
            }
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }

    return plotID;
}

From source file:Main.java

protected static void print(PrintStream out, Node node) {
    if (node == null)
        return;// w  ww.  j  a  v a2 s . c o  m
    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        //out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        NodeList nodelist = node.getChildNodes();
        int size = nodelist.getLength();
        for (int i = 0; i < size; i++)
            print(out, nodelist.item(i));
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType docType = (DocumentType) node;
        out.print("<!DOCTYPE " + getDocumentTypeData(docType) + ">\n");
        break;
    }

    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            int size = map.getLength();
            for (int i = 0; i < size; i++) {
                Attr attr = (Attr) map.item(i);
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
        }

        if (!node.hasChildNodes())
            out.print("/>");
        else {
            out.print('>');
            NodeList nodelist = node.getChildNodes();
            int numChildren = nodelist.getLength();
            for (int i = 0; i < numChildren; i++)
                print(out, nodelist.item(i));

            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        NodeList nodelist = node.getChildNodes();
        if (nodelist != null) {
            int size = nodelist.getLength();
            for (int i = 0; i < size; i++)
                print(out, nodelist.item(i));

        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String s = node.getNodeValue();
        if (s != null && s.length() > 0) {
            out.print(' ');
            out.print(s);
        }
        out.print("?>");
        break;
    }

    case Node.COMMENT_NODE: {
        out.print("<!--");
        out.print(node.getNodeValue());
        out.print("-->");
        break;
    }

    default: {
        out.print(normalize(node.getNodeValue()));
        break;
    }
    }
    out.flush();
}

From source file:Main.java

protected static void print(PrintStream out, Node node) {
    if (node == null)
        return;/*  w ww.j  av  a 2  s  .co  m*/
    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        // out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
        NodeList nodelist = node.getChildNodes();
        int size = nodelist.getLength();
        for (int i = 0; i < size; i++)
            print(out, nodelist.item(i));
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType docType = (DocumentType) node;
        out.print("<!DOCTYPE " + getDocumentTypeData(docType) + ">\n");
        break;
    }

    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            int size = map.getLength();
            for (int i = 0; i < size; i++) {
                Attr attr = (Attr) map.item(i);
                out.print(' ');
                out.print(attr.getNodeName());
                out.print("=\"");
                out.print(normalize(attr.getNodeValue()));
                out.print('"');
            }
        }

        if (!node.hasChildNodes())
            out.print("/>");
        else {
            out.print('>');
            NodeList nodelist = node.getChildNodes();
            int numChildren = nodelist.getLength();
            for (int i = 0; i < numChildren; i++)
                print(out, nodelist.item(i));

            out.print("</");
            out.print(node.getNodeName());
            out.print('>');
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        NodeList nodelist = node.getChildNodes();
        if (nodelist != null) {
            int size = nodelist.getLength();
            for (int i = 0; i < size; i++)
                print(out, nodelist.item(i));

        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String s = node.getNodeValue();
        if (s != null && s.length() > 0) {
            out.print(' ');
            out.print(s);
        }
        out.print("?>");
        break;
    }

    case Node.COMMENT_NODE: {
        out.print("<!--");
        out.print(node.getNodeValue());
        out.print("-->");
        break;
    }

    default: {
        out.print(normalize(node.getNodeValue()));
        break;
    }
    }
    out.flush();
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

@Override
public void initScheduler() throws ProvisioningException {
    if (this.cfgMgr.getCfg().getProvisioning() == null
            || this.cfgMgr.getCfg().getProvisioning().getScheduler() == null) {
        logger.warn("Scheduler not defined");
        return;/* w  ww  .  j  a v a  2s. c  o m*/
    }

    SchedulingType sct = this.cfgMgr.getCfg().getProvisioning().getScheduler();

    Properties scheduleProps = new Properties();

    scheduleProps.setProperty("org.quartz.scheduler.instanceName", sct.getInstanceLabel());

    String instanceLabel = null;
    try {
        Enumeration<NetworkInterface> enumer = NetworkInterface.getNetworkInterfaces();
        while (enumer.hasMoreElements()) {
            NetworkInterface ni = enumer.nextElement();
            Enumeration<InetAddress> enumeri = ni.getInetAddresses();
            while (enumeri.hasMoreElements()) {
                InetAddress addr = enumeri.nextElement();
                if (addr.getHostAddress().startsWith(sct.getInstanceIPMask())) {
                    instanceLabel = addr.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        throw new ProvisioningException("Could not read network addresses", e);
    }

    if (instanceLabel == null) {
        logger.warn("No IP starts with '" + sct.getInstanceIPMask() + "'");
        instanceLabel = "AUTO";
    }

    scheduleProps.setProperty("org.quartz.scheduler.instanceId", instanceLabel);
    scheduleProps.setProperty("org.quartz.threadPool.threadCount", Integer.toString(sct.getThreadCount()));

    if (sct.isUseDB()) {
        scheduleProps.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        scheduleProps.setProperty("org.quartz.jobStore.driverDelegateClass",
                sct.getScheduleDB().getDelegateClassName());
        scheduleProps.setProperty("org.quartz.jobStore.dataSource", "scheduleDB");
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.driver", sct.getScheduleDB().getDriver());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.URL", sct.getScheduleDB().getUrl());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.user", sct.getScheduleDB().getUser());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.password",
                sct.getScheduleDB().getPassword());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.maxConnections",
                Integer.toString(sct.getScheduleDB().getMaxConnections()));
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.validationQuery",
                sct.getScheduleDB().getValidationQuery());
        scheduleProps.setProperty("org.quartz.jobStore.useProperties", "true");
        scheduleProps.setProperty("org.quartz.jobStore.isClustered", "true");
    } else {
        scheduleProps.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
    }

    try {

        /*String classpath = System.getProperty("java.class.path");
        String[] classpathEntries = classpath.split(File.pathSeparator);
        for (String cp : classpathEntries) {
           System.out.println(cp);
        }*/

        PrintStream out = new PrintStream(new FileOutputStream(
                System.getProperty(OpenUnisonConstants.UNISON_CONFIG_QUARTZDIR) + "/quartz.properties"));
        scheduleProps.store(out, "Unison internal scheduler properties");
        out.flush();
        out.close();
    } catch (IOException e) {
        throw new ProvisioningException("Could not write to quartz.properties", e);
    }

    try {
        this.scheduler = StdSchedulerFactory.getDefaultScheduler();
        this.scheduler.start();
        this.cfgMgr.addThread(new StopScheduler(this.scheduler));
        HashSet<String> jobKeys = new HashSet<String>();

        for (JobType jobType : sct.getJob()) {
            jobKeys.add(jobType.getName() + "-" + jobType.getGroup());
            JobKey jk = new JobKey(jobType.getName(), jobType.getGroup());
            JobDetail jd = this.scheduler.getJobDetail(jk);
            if (jd == null) {
                logger.info("Adding new job '" + jobType.getName() + "' / '" + jobType.getGroup() + "'");
                try {
                    addJob(jobType, jk);

                } catch (ClassNotFoundException e) {
                    throw new ProvisioningException("Could not initialize job", e);
                }

            } else {
                //check to see if we need to modify
                StringBuffer cron = new StringBuffer();
                cron.append(jobType.getCronSchedule().getSeconds()).append(' ')
                        .append(jobType.getCronSchedule().getMinutes()).append(' ')
                        .append(jobType.getCronSchedule().getHours()).append(' ')
                        .append(jobType.getCronSchedule().getDayOfMonth()).append(' ')
                        .append(jobType.getCronSchedule().getMonth()).append(' ')
                        .append(jobType.getCronSchedule().getDayOfWeek()).append(' ')
                        .append(jobType.getCronSchedule().getYear());

                Properties configProps = new Properties();
                for (ParamType pt : jobType.getParam()) {
                    configProps.setProperty(pt.getName(), pt.getValue());
                }

                Properties jobProps = new Properties();
                for (String key : jd.getJobDataMap().getKeys()) {
                    jobProps.setProperty(key, (String) jd.getJobDataMap().getString(key));
                }

                List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jd.getKey());
                CronTrigger trigger = (CronTrigger) triggers.get(0);

                if (!jobType.getClassName().equals(jd.getJobClass().getName())) {
                    logger.info("Reloading job '" + jobType.getName() + "' / '" + jobType.getGroup()
                            + "' - change in class name");
                    reloadJob(jobType, jd);
                } else if (!cron.toString().equalsIgnoreCase(trigger.getCronExpression())) {
                    logger.info("Reloading job '" + jobType.getName() + "' / '" + jobType.getGroup()
                            + "' - change in schedule");
                    reloadJob(jobType, jd);
                } else if (!configProps.equals(jobProps)) {
                    logger.info("Reloading job '" + jobType.getName() + "' / '" + jobType.getGroup()
                            + "' - change in properties");
                    reloadJob(jobType, jd);
                }
            }
        }

        for (String groupName : scheduler.getJobGroupNames()) {

            for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

                String jobName = jobKey.getName();
                String jobGroup = jobKey.getGroup();

                //get job's trigger
                List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);

                if (!jobKeys.contains(jobName + "-" + jobGroup)) {
                    logger.info("Removing jab '" + jobName + "' / '" + jobGroup + "'");
                    scheduler.deleteJob(jobKey);
                }

            }

        }

    } catch (SchedulerException e) {
        throw new ProvisioningException("Could not initialize scheduler", e);
    } catch (ClassNotFoundException e) {
        throw new ProvisioningException("Could not initialize scheduler", e);
    }

}

From source file:org.apache.streams.instagram.test.data.InstagramUserInfoDataConverterIT.java

@Test
public void InstagramUserInfoDataConverterIT() throws Exception {
    InputStream is = InstagramUserInfoDataConverterIT.class.getResourceAsStream("/testUserInfoData.txt");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    PrintStream outStream = new PrintStream(new BufferedOutputStream(
            new FileOutputStream("target/test-classes/InstagramUserInfoDataConverterIT.txt")));

    try {//  w ww  .j  a  va 2s.co m
        while (br.ready()) {
            String line = br.readLine();
            if (!StringUtils.isEmpty(line)) {

                LOGGER.info("raw: {}", line);

                UserInfoData userInfoData = gson.fromJson(line, UserInfoData.class);

                ActivityObjectConverter<UserInfoData> converter = new InstagramUserInfoDataConverter();

                ActivityObject activityObject = converter.toActivityObject(userInfoData);

                LOGGER.info("activityObject: {}", activityObject.toString());

                assertThat(activityObject, is(not(nullValue())));

                assertThat(activityObject.getId(), is(not(nullValue())));
                assertThat(activityObject.getImage(), is(not(nullValue())));
                assertThat(activityObject.getDisplayName(), is(not(nullValue())));
                assertThat(activityObject.getSummary(), is(not(nullValue())));

                Map<String, Object> extensions = (Map<String, Object>) activityObject.getAdditionalProperties()
                        .get("extensions");
                assertThat(extensions, is(not(nullValue())));
                assertThat(extensions.get("following"), is(not(nullValue())));
                assertThat(extensions.get("followers"), is(not(nullValue())));
                assertThat(extensions.get("screenName"), is(not(nullValue())));
                assertThat(extensions.get("posts"), is(not(nullValue())));

                assertThat(activityObject.getAdditionalProperties().get("handle"), is(not(nullValue())));
                assertThat(activityObject.getId(), is(not(nullValue())));
                assertThat(activityObject.getUrl(), is(not(nullValue())));

                assertThat(activityObject.getAdditionalProperties().get("provider"), is(not(nullValue())));

                outStream.println(mapper.writeValueAsString(activityObject));

            }
        }
        outStream.flush();

    } catch (Exception ex) {
        LOGGER.error("Exception: ", ex);
        outStream.flush();
        Assert.fail();
    }
}

From source file:com.github.lindenb.jvarkit.tools.misc.AlleleFrequencyCalculator.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {
    PrintStream out = null;
    VcfIterator in = null;/*w w  w.  j av a  2 s .c om*/
    try {
        final List<String> args = this.getInputFiles();
        if (inputName == null) {
            LOG.info("reading stdin");
            in = new VcfIteratorImpl(stdin());
        } else {
            LOG.info("reading " + args.get(0));
            in = VCFUtils.createVcfIterator(inputName);
        }

        out = openFileOrStdoutAsPrintStream();

        out.println("CHR\tPOS\tID\tREF\tALT\tTOTAL_CNT\tALT_CNT\tFRQ");
        while (in.hasNext() && !out.checkError()) {

            VariantContext ctx = in.next();
            Allele ref = ctx.getReference();
            if (ref == null)
                continue;
            if (ctx.getNSamples() == 0 || ctx.getAlternateAlleles().isEmpty())
                continue;
            Allele alt = ctx.getAltAlleleWithHighestAlleleCount();
            if (alt == null)
                continue;

            GenotypesContext genotypes = ctx.getGenotypes();
            if (genotypes == null)
                continue;
            int total_ctn = 0;
            int alt_ctn = 0;
            for (int i = 0; i < genotypes.size(); ++i) {
                Genotype g = genotypes.get(i);
                for (Allele allele : g.getAlleles()) {
                    if (allele.equals(ref)) {
                        total_ctn++;
                    } else if (allele.equals(alt)) {
                        total_ctn++;
                        alt_ctn++;
                    }
                }

            }

            out.print(ctx.getContig());
            out.print("\t");
            out.print(ctx.getStart());
            out.print("\t");
            out.print(ctx.hasID() ? ctx.getID() : ".");
            out.print("\t");
            out.print(ref.getBaseString());
            out.print("\t");
            out.print(alt.getBaseString());
            out.print("\t");
            out.print(total_ctn);
            out.print("\t");
            out.print(alt_ctn);
            out.print("\t");
            out.print(alt_ctn / (float) total_ctn);
            out.println();
        }
        out.flush();

        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {
        CloserUtil.close(out);
        CloserUtil.close(in);
    }
}