Example usage for java.util Formatter out

List of usage examples for java.util Formatter out

Introduction

In this page you can find the example usage for java.util Formatter out.

Prototype

public Appendable out() 

Source Link

Document

Returns the destination for the output.

Usage

From source file:Main.java

public static void main(String[] args) {

    StringBuffer buffer = new StringBuffer();
    Formatter formatter = new Formatter(buffer, Locale.US);

    // format a new string
    String name = "from java2s.com";
    formatter.format("Hello %s !", name);

    // print the formatted string with default locale
    System.out.println(formatter);

    // print the output
    System.out.println(formatter.out());
}

From source file:org.mskcc.cbio.portal.util.MakeOncoPrint.java

/**
 * Format percentage.//from ww  w  .  j  a v a  2 s.com
*
 * <p/>
 * if value == 0 return "--"
 * case value
 * 0: return "--"
 * 0<value<=0.01: return "<1%"
 * 1<value: return "<value>%"
 *
 * @param value double
*
 * @return String
 */
public static String alterationValueToString(double value) {

    // in oncoPrint show 0 percent as 0%, not --
    if (0.0 < value && value <= 0.01) {
        return "<1%";
    }

    // if( 1.0 < value ){
    Formatter f = new Formatter();
    f.format("%.0f", value * 100.0);
    return f.out().toString() + "%";
}

From source file:edu.berkeley.compbio.ml.cluster.hierarchical.HierarchicalCentroidCluster.java

/**
 * {@inheritDoc}/* ww  w.j  a v  a 2 s.  c o  m*/
 */
@Override
public String toString() {
    final Formatter f = new Formatter();
    f.format("l=%.2f w=%.2f %s", length, weight, value);//%[Cluster %d] n=%d sd=%.2f", id, n, getStdDev());

    return f.out().toString();
}

From source file:fr.gael.dhus.sync.smart.download.ProductDownloadTask.java

/**
 * raise an IOException with the given StatusLine and cause Header (cause may be null).
 *//*from   w  ww . j a v  a2 s.  c o  m*/
private void raiseFailure(StatusLine stl, Header cause) throws IOException {
    Formatter ff = new Formatter();
    ff.format("Cannot download %s, Reason='%s' (HTTP%d)", this.url, stl.getReasonPhrase(), stl.getStatusCode());
    if (cause != null) {
        String cause_msg = cause.getValue();
        if (cause_msg != null && !cause_msg.isEmpty()) {
            ff.format(" Cause='%s'", cause_msg);
        }
    }

    IOException exception = new IOException(ff.out().toString());
    ff.close();
    throw exception;
}

From source file:eu.stratosphere.pact.runtime.hash.HashFunctionCollisionBenchmark.java

private void printStatistics() {
    for (int level = 0; level < maxLevel; level++) {
        int bucketCountInLevel = 0;

        SortedMap<Integer, Integer> levelMap = bucketSizesPerLevel.get(level);
        Iterator<Integer> bucketSizeIterator = levelMap.keySet().iterator();

        LOG.debug("Statistics for level: " + level);
        LOG.debug("----------------------------------------------");
        LOG.debug("");
        LOG.debug("Bucket Size |      Count");
        LOG.debug("------------------------");

        int i = 0;
        while (bucketSizeIterator.hasNext()) {
            int bucketSize = bucketSizeIterator.next();
            if (bucketSize != 0) {
                int countForBucketSize = levelMap.get(bucketSize);
                bucketCountInLevel += countForBucketSize;
                Formatter formatter = new Formatter();
                formatter.format(" %10d | %10d", bucketSize, countForBucketSize);

                if (levelMap.size() < 20 || i < 3 || i >= (levelMap.size() - 3)) {
                    LOG.debug(formatter.out());
                } else if (levelMap.size() / 2 == i) {
                    LOG.debug("         .. |         ..");
                    LOG.debug(formatter.out());
                    LOG.debug("         .. |         ..");
                }/* ww w  . ja  v  a 2s  .co  m*/
                i++;
                formatter.close();
            }
        }

        LOG.debug("");
        LOG.debug("Number of non-empty buckets in level: " + bucketCountInLevel);
        LOG.debug("Number of empty buckets in level    : " + levelMap.get(0));
        LOG.debug("Number of different bucket sizes    : " + (levelMap.size() - 1));
        LOG.debug("");
        LOG.debug("");
        LOG.debug("");
    }
}

From source file:eu.stratosphere.pact.runtime.hash.MultiLevelHashITCase.java

private void printStatistics() {
    for (int level = 0; level < maxLevel; level++) {
        int bucketCountInLevel = 0;

        SortedMap<Integer, Integer> levelMap = bucketSizesPerLevel.get(level);
        Iterator<Integer> bucketSizeIterator = levelMap.keySet().iterator();

        LOG.debug("Statistics for level: " + level);
        LOG.debug("----------------------------------------------");
        LOG.debug("");
        LOG.debug("Bucket Size |      Count");
        LOG.debug("------------------------");

        int i = 0;
        while (bucketSizeIterator.hasNext()) {
            int bucketSize = bucketSizeIterator.next();
            if (bucketSize != 0) {
                int countForBucketSize = levelMap.get(bucketSize);
                bucketCountInLevel += countForBucketSize;
                Formatter formatter = new Formatter();
                formatter.format(" %10d | %10d", bucketSize, countForBucketSize);

                if (levelMap.size() < 20 || i < 3 || i >= (levelMap.size() - 3)) {
                    LOG.debug(formatter.out());
                } else if (levelMap.size() / 2 == i) {
                    LOG.debug("         .. |         ..");
                    LOG.debug(formatter.out());
                    LOG.debug("         .. |         ..");
                }/*  w  ww.ja va 2  s  .com*/
                i++;
            }
        }

        LOG.debug("");
        LOG.debug("Number of non-empty buckets in level: " + bucketCountInLevel);
        LOG.debug("Number of empty buckets in level    : " + levelMap.get(0));
        LOG.debug("Number of different bucket sizes    : " + (levelMap.size() - 1));
        LOG.debug("");
        LOG.debug("");
        LOG.debug("");
    }
}

From source file:fr.gael.dhus.util.http.DownloadableProduct.java

/** raise an IOException with the given StatusLine and cause Header (cause may be null). */
private void raiseFailure(StatusLine stl, Header cause) throws IOException {
    Formatter ff = new Formatter();
    ff.format("Cannot download %s, Reason='%s' (HTTP%d)", this.url, stl.getReasonPhrase(), stl.getStatusCode());
    if (cause != null) {
        String cause_msg = cause.getValue();
        if (cause_msg != null && !cause_msg.isEmpty()) {
            ff.format(" Cause='%s'", cause_msg);
        }//from w ww .  j  av  a  2s .  c o  m
    }
    throw new IOException(ff.out().toString());
}

From source file:net.dv8tion.jda.core.entities.impl.MessageImpl.java

@Override
public void formatTo(Formatter formatter, int flags, int width, int precision) {
    boolean upper = (flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE;
    boolean leftJustified = (flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY;
    boolean alt = (flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE;

    String out = alt ? getRawContent() : getContent();

    if (upper)/*www.  j a v  a 2  s .  c  o  m*/
        out = out.toUpperCase(formatter.locale());

    try {
        Appendable appendable = formatter.out();
        if (precision > -1 && out.length() > precision) {
            appendable.append(Helpers.truncate(out, precision - 3)).append("...");
            return;
        }

        if (leftJustified)
            appendable.append(Helpers.rightPad(out, width));
        else
            appendable.append(Helpers.leftPad(out, width));
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/**
 * Uses the given `http_client` to download `url` into `out_tmp`.
 * Renames `out_tmp` to the value of the filename param of the Content-Disposition header field.
 * Returns a path to the renamed file.//  w w  w  . j  a  v a2 s.  c  o  m
 *
 * @param http_client synchronous interruptible HTTP client.
 * @param out_tmp download destination file on disk (will be created if does not exist).
 * @param url what to download.
 * @return Path to file with its actual name.
 * @throws IOException Anything went wrong (with IO or network, or if the HTTP header field
 *       Content-Disposition is missing).
 * @throws InterruptedException Thread has been interrupted.
 */
private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client, Path out_tmp, String url)
        throws IOException, InterruptedException {
    try (FileChannel output = FileChannel.open(out_tmp, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {

        HttpResponse response = http_client.interruptibleGet(url, output);

        // If the response's status code is not 200, something wrong happened
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Formatter ff = new Formatter();
            ff.format(
                    "Synchronizer#%d cannot download product at %s,"
                            + " remote dhus returned message '%s' (HTTP%d)",
                    getId(), url, response.getStatusLine().getReasonPhrase(),
                    response.getStatusLine().getStatusCode());
            throw new IOException(ff.out().toString());
        }

        // Gets the filename from the HTTP header field `Content-Disposition'
        Pattern pat = Pattern.compile("filename=\"(.+?)\"", Pattern.CASE_INSENSITIVE);
        String contdis = response.getFirstHeader("Content-Disposition").getValue();
        Matcher m = pat.matcher(contdis);
        if (!m.find()) {
            throw new IOException("Synchronizer#" + getId()
                    + " Missing HTTP header field `Content-Disposition` that determines the filename");
        }
        String filename = m.group(1);
        if (filename == null || filename.isEmpty()) {
            throw new IOException(
                    "Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`");
        }

        // Renames the downloaded file
        output.close();
        Path dest = out_tmp.getParent().resolve(filename);
        Files.move(out_tmp, dest, StandardCopyOption.ATOMIC_MOVE);

        DownloadResult res = new DownloadResult(dest, response.getEntity().getContentType().getValue(),
                response.getEntity().getContentLength());

        return res;
    } finally {
        if (Files.exists(out_tmp)) {
            Files.delete(out_tmp);
        }
    }
}

From source file:org.LexGrid.LexBIG.example.ScoreTerm.java

/**
 * Display results to the user./*from w  ww  . j av  a  2 s .com*/
 * 
 * @param result
 */
protected void printReport(BidiMap result) {
    final String Dash6 = "------";
    final String Dash10 = "----------";
    final String Dash60 = "------------------------------------------------------------";

    Formatter f = new Formatter();

    // Print header.
    String format = "%-5.5s|%-10.10s|%-60.60s\n";
    Object[] hSep = new Object[] { Dash6, Dash10, Dash60 };
    f.format(format, hSep);
    f.format(format, new Object[] { "Score", "Code", "Term" });
    f.format(format, hSep);

    // Iterate over the result.
    for (MapIterator items = result.inverseBidiMap().mapIterator(); items.hasNext();) {
        ScoredTerm st = (ScoredTerm) items.next();
        String code = (String) items.getValue();

        // Evaluate code
        if (code != null && code.length() > 10)
            code = code.substring(0, 7) + "...";

        // Evaluate term (wrap if necessary)
        String term = st.term;
        if (term != null && term.length() < 60)
            f.format(format, new Object[] { st.score, code, term });
        else {
            String sub = term.substring(0, 60);
            f.format(format, new Object[] { st.score, code, sub });
            int begin = 60;
            int end = term.length();
            while (begin < end) {
                sub = term.substring(begin, Math.min(begin + 60, end));
                f.format(format, new Object[] { "", "", sub });
                begin += 60;
            }
        }
    }
    Util.displayMessage(f.out().toString());
}