Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

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

Prototype

public Formatter(OutputStream os) 

Source Link

Document

Constructs a new formatter with the specified output stream.

Usage

From source file:ar.com.zauber.labs.kraken.providers.wikipedia.model.impl.HttpWikiPageRetriever.java

/** @see WikiPageRetriever#get(String) */
public final WikiPage get(final Language wikipediaLang, final String pageTitle) {
    Validate.isTrue(StringUtils.isNotBlank(pageTitle), "pageTitle is blank");
    Validate.notNull(wikipediaLang, "wikipediaLang is null");
    final UriTemplate uriTemplate;

    uriTemplate = new UriTemplate("http://" + wikipediaLang.getIsoName()
            + ".wikipedia.org/w/api.php?action=query&redirects=true&format=xml"
            + "&titles={title}&prop=langlinks{llcontinue}");

    Reader reader = null;/*  w ww .  j av a 2  s . com*/
    try {
        String llcontinue = null;
        final Set<String> titles = new TreeSet<String>();
        final Map<Language, WikiPage> langLink = new TreeMap<Language, WikiPage>();
        long pageid = 0;
        do {
            final URI url = uriTemplate.expand(pageTitle,
                    llcontinue == null ? "" : "&llcontinue=" + llcontinue);
            try {
                reader = contentProvider.getContent(url);
                final Api api = (Api) unmarshaller.unmarshal(reader);
                IOUtils.closeQuietly(reader);
                reader = null;

                final Query query = api.getQuery();

                if (query.getRedirects() != null) {
                    for (final R r : query.getRedirects().getR()) {
                        titles.add(r.getFrom());
                        titles.add(r.getTo());
                    }
                }
                final List<Page> pages = query.getPages().getPage();
                if (pages.size() == 1) {
                    final Page page = pages.get(0);
                    pageid = page.getPageid().longValue();
                    titles.add(page.getTitle());
                    if (page.getLanglinks() != null) {
                        for (final Ll ll : page.getLanglinks().getLl()) {
                            try {
                                final Language lang = LangUtils.getLang(ll.getLang());
                                langLink.put(lang, lazyWikiPageRetriever.get(lang, ll.getValue()));
                            } catch (final NoSuchEntityException e) {
                                final StringBuilder sb = new StringBuilder();
                                new Formatter(sb).format("Unknown language %s on wiki page `%s' (%s):" + " %s",
                                        e.getEntity(), pageTitle, wikipediaLang, url);
                                throw new IllegalArgumentException(sb.toString(), e);
                            }
                        }
                    }
                    if (api.getQueryContinue() == null) {
                        llcontinue = null;
                    } else {
                        llcontinue = api.getQueryContinue().getLanglinks().getLlcontinue();
                    }
                } else {
                    throw new AssertionError("1 page expected. got " + pages.size() + "unable to parse page "
                            + pageTitle + " (" + url + ")");
                }
            } catch (final NoSuchEntityException e) {
                throw new NoSuchEntityException(pageTitle + " (" + wikipediaLang + ")", e);
            } catch (final JAXBException e) {
                final StringBuilder sb = new StringBuilder();
                new Formatter(sb).format("parsing wiki page `%s' (%s): %s\n%s", pageTitle, wikipediaLang, url,
                        e);
                throw new UnhandledException(sb.toString(), e);
            }
        } while (llcontinue != null);

        return new SimpleWikiPage(pageid, wikipediaLang, titles, langLink);
    } finally {
        if (reader != null) {
            IOUtils.closeQuietly(reader);
        }
    }
}

From source file:com.itemanalysis.psychometrics.irt.estimation.ItemFitG2.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    f.format("%5s", "G2  ");
    f.format("%8.4d", getValue());
    f.format("%2s", "");
    f.format("%4d", (int) getDegreesOfFreedom());
    f.format("%2s", "");
    f.format("%1.4f", getPValue());
    return f.toString();
}

From source file:com.itemanalysis.psychometrics.polycor.PolychoricLogLikelihoodTwoStep.java

public String print(double[] x) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    double se = this.getStandardError(x);

    f.format("%34s", "Polychoric correlation, Two-step est. = ");
    f.format("%6.4f", rho);
    f.format(" (%6.4f)", se);
    f.format("%n");
    f.format("%n");
    f.format("%-20s", "Row Thresholds");
    f.format("%n");

    for (int i = 0; i < (alpha.length - 1); i++) {
        f.format("%6.4f", alpha[i]);
        f.format("%n");
    }//from   w  w w  . j  av a  2s.c o m

    f.format("%n");
    f.format("%n");
    f.format("%-20s", "Column Thresholds");
    f.format("%n");

    for (int i = 0; i < (beta.length - 1); i++) {
        f.format("% 6.4f", beta[i]);
        f.format("%n");
    }

    f.format("%n");
    return f.toString();

}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Calculates the domains per network feature for each cluster generated
 * on a specific run date./*from   w ww.  j  a va  2 s  .com*/
 * 
 * @param log_date the run date
 * @param window the number of days previous to use in feature calculation
 * @return a table of values where the keys are cluster ids and the values 
 *       are the feature values
 * @throws SQLException if there is an error calculating the feature values
 */

public Map<Integer, Double> calculateDomainsPerNetwork(Date log_date, int window) throws SQLException {
    HashMap<Integer, Double> retval = new HashMap<Integer, Double>();
    ArrayList<Date> prevDates = getPrevDates(log_date, window);
    if (prevDates.size() > 0) {
        String logDateStr = df.format(log_date);
        StringBuffer add_query = new StringBuffer();
        Formatter formatter = new Formatter(add_query);

        for (Date prevDate : prevDates) {
            String prevDateStr = df.format(prevDate);
            formatter.format(" " + properties.getProperty(DOMAINSPERNETWORK_QUERY1KEY) + " ", logDateStr,
                    prevDateStr, prevDateStr);
        }
        formatter.close();

        StringBuffer querybuf = new StringBuffer();
        formatter = new Formatter(querybuf);
        formatter.format(properties.getProperty(DOMAINSPERNETWORK_QUERY2KEY), logDateStr, logDateStr,
                logDateStr, add_query.toString());
        ResultSet rs = null;
        try {
            rs = dbi.executeQueryWithResult(querybuf.toString());
            while (rs.next()) {
                retval.put(rs.getInt(1), rs.getDouble(2));
            }
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        } finally {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }
            formatter.close();
        }
    }
    return retval;
}

From source file:com.cloudera.sqoop.manager.OracleCompatTest.java

@Override
protected String getBlobInsertStr(String blobData) {
    // Oracle wants blob data encoded as hex (e.g. '01fca3b5').

    StringBuilder sb = new StringBuilder();
    sb.append("'");

    Formatter fmt = new Formatter(sb);
    try {//from   w w  w  .  j  a  v  a2s .com
        for (byte b : blobData.getBytes("UTF-8")) {
            fmt.format("%02X", b);
        }
    } catch (UnsupportedEncodingException uee) {
        // Should not happen; Java always supports UTF-8.
        fail("Could not get utf-8 bytes for blob string");
        return null;
    }
    sb.append("'");
    return sb.toString();
}

From source file:org.apache.accumulo.core.util.shell.commands.FateCommand.java

@Override
public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
        throws ParseException, KeeperException, InterruptedException, IOException {
    Instance instance = shellState.getInstance();
    String[] args = cl.getArgs();
    if (args.length <= 0) {
        throw new ParseException("Must provide a command to execute");
    }//from  www . j ava2  s .co m
    String cmd = args[0];
    boolean failedCommand = false;

    AdminUtil<FateCommand> admin = new AdminUtil<FateCommand>(false);

    String path = ZooUtil.getRoot(instance) + Constants.ZFATE;
    String masterPath = ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK;
    IZooReaderWriter zk = getZooReaderWriter(shellState.getInstance(),
            cl.getOptionValue(secretOption.getOpt()));
    ZooStore<FateCommand> zs = new ZooStore<FateCommand>(path, zk);

    if ("fail".equals(cmd)) {
        if (args.length <= 1) {
            throw new ParseException("Must provide transaction ID");
        }
        for (int i = 1; i < args.length; i++) {
            if (!admin.prepFail(zs, zk, masterPath, args[i])) {
                System.out.printf("Could not fail transaction: %s%n", args[i]);
                failedCommand = true;
            }
        }
    } else if ("delete".equals(cmd)) {
        if (args.length <= 1) {
            throw new ParseException("Must provide transaction ID");
        }
        for (int i = 1; i < args.length; i++) {
            if (admin.prepDelete(zs, zk, masterPath, args[i])) {
                admin.deleteLocks(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, args[i]);
            } else {
                System.out.printf("Could not delete transaction: %s%n", args[i]);
                failedCommand = true;
            }
        }
    } else if ("list".equals(cmd) || "print".equals(cmd)) {
        // Parse transaction ID filters for print display
        Set<Long> filterTxid = null;
        if (args.length >= 2) {
            filterTxid = new HashSet<Long>(args.length);
            for (int i = 1; i < args.length; i++) {
                try {
                    Long val = Long.parseLong(args[i], 16);
                    filterTxid.add(val);
                } catch (NumberFormatException nfe) {
                    // Failed to parse, will exit instead of displaying everything since the intention was to potentially filter some data
                    System.out.printf("Invalid transaction ID format: %s%n", args[i]);
                    return 1;
                }
            }
        }

        // Parse TStatus filters for print display
        EnumSet<TStatus> filterStatus = null;
        if (cl.hasOption(statusOption.getOpt())) {
            filterStatus = EnumSet.noneOf(TStatus.class);
            String[] tstat = cl.getOptionValues(statusOption.getOpt());
            for (int i = 0; i < tstat.length; i++) {
                try {
                    filterStatus.add(TStatus.valueOf(tstat[i]));
                } catch (IllegalArgumentException iae) {
                    System.out.printf("Invalid transaction status name: %s%n", tstat[i]);
                    return 1;
                }
            }
        }

        StringBuilder buf = new StringBuilder(8096);
        Formatter fmt = new Formatter(buf);
        admin.print(zs, zk, ZooUtil.getRoot(instance) + Constants.ZTABLE_LOCKS, fmt, filterTxid, filterStatus);
        shellState.printLines(Collections.singletonList(buf.toString()).iterator(), true);
    } else {
        throw new ParseException("Invalid command option");
    }

    return failedCommand ? 1 : 0;
}

From source file:com.itemanalysis.psychometrics.cmh.CmhTable.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    double score = 0.0;

    Iterator<Comparable<?>> iter = columnMargin.valuesIterator();
    f.format("%26s", " ");
    while (iter.hasNext()) {
        score = ((Double) iter.next()).doubleValue();
        f.format("%10.0f", score);
        f.format("%5s", " ");
    }// w  ww . j a v a  2 s . co  m
    f.format("%n");
    f.format("%51s", "-------------------------");

    iter = columnMargin.valuesIterator();
    int index = 0;
    while (iter.hasNext()) {
        score = ((Double) iter.next()).doubleValue();
        if (index > 1)
            f.format("%15s", "---------------");
        index++;
    }
    f.format("%n");

    f.format("%11s", "Reference: ");
    f.format("%-100s", referenceRow.toString());
    f.format("%n");
    f.format("%11s", "Focal:     ");
    f.format("%-100s", focalRow.toString());
    f.format("%n");

    return f.toString();
}

From source file:com.itemanalysis.psychometrics.cfa.AbstractConfirmatoryFactorAnalysisEstimator.java

public String printEstimates(ArrayList<VariableAttributes> items) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    double[] fl = model.getFactorLoading();
    double[] er = model.getErrorVariance();
    //        f.format("%50s", "       CONFIRMATORY FACTOR ANALYSIS RESULTS       ");
    f.format("%n");
    f.format("%-50s", model.getName());
    f.format("%n");
    f.format("%50s", "==================================================");
    f.format("%n");
    f.format("%10s", "     ");
    f.format("%5s", "");
    f.format("%10s", "Factor ");
    f.format("%5s", "");
    f.format("%10s", " Error");
    f.format("%n");
    f.format("%10s", " Item");
    f.format("%5s", "");
    f.format("%10s", "Loading");
    f.format("%5s", "");
    f.format("%10s", "Variance");
    f.format("%n");
    f.format("%50s", "--------------------------------------------------");
    f.format("%n");

    for (int i = 0; i < items.size(); i++) {
        f.format("%10s", items.get(i));
        f.format("%5s", "");
        f.format("% 10.4f", fl[i]);
        f.format("%5s", "");
        f.format("% 10.4f", er[i]);
        f.format("%n");
    }/*from w  w  w.  j  a  v  a  2  s  .  c  om*/
    f.format("%50s", "--------------------------------------------------");
    f.format("%n");
    return f.toString();
}

From source file:com.itemanalysis.psychometrics.factoranalysis.MINRESmethod.java

public String printStartValues() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    double[] start = getStartValues();
    for (int i = 0; i < start.length; i++) {
        f.format("%8.4f", start[i]);
        f.format("%n");
    }//from ww  w . jav  a  2  s .c  o m
    return f.toString();
}

From source file:gemlite.core.internal.db.AsyncEventHelper.java

/**
 * Log the given formatted message and exception to the provided logger. The
 * format expected is the same as supported by
 * {@link String#format(String, Object...)}.
 * /*from w w  w .j  a va  2s.co m*/
 * @param logger
 *          the {@link Logger} to log the message to
 * @param level
 *          the {@link Level} to use for logging the message
 * @param t
 *          the exception whose backtrace is to be logged; can be null in
 *          which case it is ignored
 * @param format
 *          the message format
 * @param params
 *          the parameters to the message format
 * 
 * @see String#format(String, Object...)
 * @see Formatter#format(String, Object...)
 */
public final void logFormat(Logger logger, Level level, Throwable t, String format, Object... params) {
    StringBuilder sb = new StringBuilder();
    Formatter fmt = new Formatter(sb);
    fmt.format(format, params);
    if (t != null) {
        sb.append(": ");
        getStackTrace(t, sb);
    }
    if (Level.SEVERE.equals(level.toString()))
        logger.error(sb.toString());
    else
        logger.info(sb.toString());
    fmt.close();
}