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:edu.uga.cs.fluxbuster.analytics.ClusterSimilarityCalculator.java

/**
 * Calculate domainname-based cluster similarities between all of the clusters generated
 * during the runs on the two supplied dates.
 *
 * @param adate the date of the first clustering run
 * @param bdate the date of the second clustering run
 * @return the list of domainname-based cluster similarities
 * @throws IOException if the similarities could not be calculated
 *///from  w  ww.  j a  v  a  2  s.c om
public List<ClusterSimilarity> calculateDomainnameSimilarities(Date adate, Date bdate) throws IOException {
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
    String adatestr = df.format(adate);
    String bdatestr = df.format(bdate);

    String query = properties.getProperty(DOMAINSKEY);
    StringBuffer querybuf = new StringBuffer();
    Formatter formatter = new Formatter(querybuf);
    formatter.format(query, adatestr, adatestr, adatestr, adatestr, bdatestr, bdatestr);
    query = querybuf.toString();
    formatter.close();
    return this.executeSimilarityQuery(query, adate, bdate);
}

From source file:org.apache.accumulo.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  w w w . ja  v a2 s  . c o  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(),
                !cl.hasOption(disablePaginationOpt.getOpt()));
    } else if ("dump".equals(cmd)) {
        List<Long> txids;

        if (args.length == 1) {
            txids = zs.list();
        } else {
            txids = new ArrayList<>();
            for (int i = 1; i < args.length; i++) {
                txids.add(Long.parseLong(args[i], 16));
            }
        }

        Gson gson = new GsonBuilder().registerTypeAdapter(ReadOnlyRepo.class, new InterfaceSerializer<>())
                .registerTypeAdapter(Repo.class, new InterfaceSerializer<>())
                .registerTypeAdapter(byte[].class, new ByteArraySerializer()).setPrettyPrinting().create();

        List<FateStack> txStacks = new ArrayList<>();

        for (Long txid : txids) {
            List<ReadOnlyRepo<FateCommand>> repoStack = zs.getStack(txid);
            txStacks.add(new FateStack(txid, repoStack));
        }

        System.out.println(gson.toJson(txStacks));
    } else {
        throw new ParseException("Invalid command option");
    }

    return failedCommand ? 1 : 0;
}

From source file:com.hyperaware.conference.android.fragment.SessionDetailFragment.java

private void updateSessionDetail() {
    tvTopic.setText(agendaItem.getTopic());
    host.setTitle(agendaItem.getTopic());

    final StringBuilder sb = new StringBuilder();
    final Formatter formatter = new Formatter(sb);

    final long start_ms = TimeUnit.SECONDS.toMillis(agendaItem.getEpochStartTime());
    final long end_ms = TimeUnit.SECONDS.toMillis(agendaItem.getEpochEndTime());

    sb.setLength(0);//from w  w  w .  j  a  v  a2  s .c o  m
    DateUtils.formatDateRange(getActivity(), formatter, start_ms, end_ms,
            DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY, tz.getID());
    tvDate.setText(formatter.toString());

    sb.setLength(0);
    DateUtils.formatDateRange(getActivity(), formatter, start_ms, end_ms, DateUtils.FORMAT_SHOW_TIME,
            tz.getID());
    tvTime.setText(formatter.toString());

    final String location = agendaItem.getLocation();
    if (!Strings.isNullOrEmpty(location)) {
        tvLocation.setText(agendaItem.getLocation());
    } else {
        tvLocation.setVisibility(View.GONE);
    }

    tvDescription.setText(agendaItem.getDescription());

    // Only sessions with speakers can have feedback
    final View feedback = vgActions.findViewById(R.id.tv_session_feedback);
    if (speakerItems.size() > 0) {
        feedback.setOnClickListener(new SessionFeedbackOnClickListener());
        vgActions.setVisibility(View.VISIBLE);
    } else {
        vgActions.setVisibility(View.GONE);
    }

    if (speakerItems.size() > 0) {
        vgSpeakers.setVisibility(View.VISIBLE);
        vgSpeakers.removeAllViews();
        final LayoutInflater inflater = getActivity().getLayoutInflater();

        for (final SpeakerItem item : speakerItems) {
            final View view = inflater.inflate(R.layout.item_session_speaker, vgSpeakers, false);

            ImageView iv = (ImageView) view.findViewById(R.id.iv_pic);
            Glide.with(SessionDetailFragment.this).load(item.getImage100()).placeholder(R.drawable.nopic)
                    .into(iv);

            ((TextView) view.findViewById(R.id.tv_name)).setText(item.getName());

            if (host != null) {
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Fragment next = SpeakerDetailFragment.instantiate(item.getId());
                        host.pushFragment(next, "speaker_detail");
                    }
                });
            }

            vgSpeakers.addView(view);
        }
    }
}

From source file:contrail.stages.CompressAndCorrect.java

/**
 * PopBubbles in the graph./*from  w  w w  . j  a  va 2 s  . c om*/
 * @param inputPath
 * @param outputPath
 * @return JobInfo
 */
private JobInfo popBubbles(String inputPath, String outputPath) throws Exception {
    FindBubblesAvro findStage = new FindBubblesAvro();
    findStage.setConf(getConf());
    String findOutputPath = new Path(outputPath, "FindBubbles").toString();
    {
        // Make a shallow copy of the stage options required.
        Map<String, Object> stageOptions = ContrailParameters.extractParameters(this.stage_options,
                findStage.getParameterDefinitions().values());

        stageOptions.put("inputpath", inputPath);
        stageOptions.put("outputpath", findOutputPath);
        findStage.setParameters(stageOptions);
    }

    RunningJob findJob = findStage.runJob();

    if (findJob == null) {
        JobInfo result = new JobInfo();
        result.logMessage = "FindBubbles stage was skipped because graph would not change.";
        sLogger.info(result.logMessage);
        result.graphPath = inputPath;
        result.graphChanged = false;
        return result;
    }

    // Check if any bubbles were found.
    long bubblesFound = findJob.getCounters()
            .findCounter(FindBubblesAvro.num_bubbles.group, FindBubblesAvro.num_bubbles.tag).getValue();

    if (bubblesFound == 0) {
        // Since no bubbles were found, we don't need to run the second phase
        // of pop bubbles.
        JobInfo result = new JobInfo();
        result.graphChanged = false;
        // Since the graph didn't change return the input path as the path to
        // the graph.
        result.graphPath = inputPath;
        result.logMessage = "FindBubbles found 0 bubbles.";
        return result;
    }

    PopBubblesAvro popStage = new PopBubblesAvro();
    popStage.setConf(getConf());
    String popOutputPath = new Path(outputPath, "PopBubbles").toString();
    {
        // Make a shallow copy of the stage options required.
        Map<String, Object> stageOptions = ContrailParameters.extractParameters(this.stage_options,
                popStage.getParameterDefinitions().values());

        stageOptions.put("inputpath", findOutputPath);
        stageOptions.put("outputpath", popOutputPath);
        popStage.setParameters(stageOptions);
    }
    RunningJob popJob = popStage.runJob();

    JobInfo result = new JobInfo();
    result.graphChanged = true;
    result.graphPath = popOutputPath;

    Formatter formatter = new Formatter(new StringBuilder());
    result.logMessage = formatter.format("FindBubbles: number of nodes removed %d", bubblesFound).toString();
    return result;
}

From source file:adapters.BoxSeriesCollectionAdapter.java

/**
 * Returns in a <TT>String</TT> all data contained in the current object.
 *
 * @return All data contained in the current object as a {@link String}.
 *
 *///w  w w  . j  av  a  2  s .  c o m
public String toString() {
    Formatter formatter = new Formatter(Locale.US);
    for (int i = 0; i < seriesCollection.getRowCount(); i++) {
        formatter.format(" Series " + i + " : %n");
        for (int j = 0; j < seriesCollection.getColumnCount(); j++)
            formatter.format(",%15e%n", seriesCollection.getValue(i, j));
    }
    return formatter.toString();
}

From source file:org.jboss.as.test.clustering.cluster.web.passivation.SessionPassivationTestCase.java

private static String showHeaders(final org.apache.http.Header[] headers) {
    StringBuilder stringBuilder = new StringBuilder();
    try (Formatter result = new Formatter(stringBuilder)) {
        for (Header header : headers) {
            result.format("{name=%s, value=%s}, ", header.getName(), header.getValue());
        }/*  w ww.j a v a2s .  c o m*/
        return result.toString();
    }
}

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

public String print(double[] x) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    int am1 = alpha.length - 1;
    int bm1 = beta.length - 1;

    f.format("%34s", "Polychoric correlation, ML est. = ");
    f.format("%6.4f", rho);
    f.format(" (%6.4f)", Math.sqrt(variance[0][0]));
    f.format("%n");
    f.format("%41s", "Test of bivariate normality: Chisquare = ");
    f.format("%-8.4f", chiSquare);
    f.format("%6s", " df = ");
    f.format("%-6.0f", df);
    f.format("%5s", " p = ");
    f.format("%-6.4f", probChiSquare);
    f.format("%n");
    f.format("%n");
    f.format("%18s", "Row Thresholds");
    f.format("%n");
    f.format("%-15s", "Threshold");
    f.format("%-10s", "Std.Err.");
    f.format("%n");

    for (int i = 0; i < am1; i++) {
        f.format("%6.4f", x[i + 1]);
        f.format("%9s", "");
        f.format("%6.4f", Math.sqrt(variance[i + 1][i + 1]));
        f.format("%n");
    }/*from ww w . ja v a  2s .  c  o  m*/

    f.format("%n");
    f.format("%n");
    f.format("%19s", "Column Thresholds");
    f.format("%n");
    f.format("%-15s", "Threshold");
    f.format("%-10s", "Std.Err.");
    f.format("%n");

    for (int i = 0; i < bm1; i++) {
        f.format("% 6.4f", x[i + 1 + am1]);
        f.format("%9s", "");
        f.format("% 6.4f", Math.sqrt(variance[i + 1 + am1][i + 1 + am1]));
        f.format("%n");
    }

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

}

From source file:com.netradius.hibernate.support.HibernateUtil.java

/**
 * Pretty prints a list of String arrays. This method assumes the first array in the list
 * is the header.//w w w  .j ava2  s.co  m
 *
 * @param rows the rows to print
 */
private static void prettyPrint(List<String[]> rows) {
    if (!rows.isEmpty()) {
        final int numCol = rows.get(0).length;
        final int[] maxLength = new int[numCol];
        Arrays.fill(maxLength, 0);
        for (String[] row : rows) {
            for (int i = row.length - 1; i >= 0; i--) {
                if (row[i] == null && maxLength[i] < 4)
                    maxLength[i] = 4;
                else if (row[i] != null && row[i].length() > maxLength[i])
                    maxLength[i] = row[i].length();
            }
        }
        final StringBuilder sb = new StringBuilder();
        int totalLength = 0;
        for (int i = 0; i < maxLength.length; i++) {
            totalLength += maxLength[i];
            if (i == 0)
                sb.append("| ");
            sb.append("%").append(i + 1).append("$-").append(maxLength[i]).append("s | ");
            if (i == maxLength.length - 1)
                sb.append("\n");
        }
        totalLength += numCol * 3 + 1;
        final String pattern = sb.toString();
        final Formatter formatter = new Formatter(System.out);
        System.out.print(line('=', totalLength));
        for (int i = 0; i < rows.size(); i++) {
            formatter.format(pattern, (Object[]) rows.get(i));
            if (i == 0)
                System.out.print(line('=', totalLength));
            else
                System.out.print(line('-', totalLength));
        }
    }
}

From source file:fll.web.scoreEntry.ScoreEntry.java

/**
 * Generate the body of the refresh function
 *///from www. ja v  a 2  s  . com
public static void generateRefreshBody(final Writer writer, final ServletContext application)
        throws ParseException, IOException {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Entering generateRefreshBody");
    }

    final ChallengeDescription description = ApplicationAttributes.getChallengeDescription(application);
    final Formatter formatter = new Formatter(writer);

    final PerformanceScoreCategory performanceElement = description.getPerformance();

    // output the assignments of each element
    for (final AbstractGoal agoal : performanceElement.getGoals()) {
        if (agoal.isComputed()) {
            // output calls to the computed goal methods

            final String goalName = agoal.getName();
            final String computedVarName = getVarNameForComputedScore(goalName);
            formatter.format("%s();%n", getComputedMethodName(goalName));

            // add to the total score
            formatter.format("score += %s;%n", computedVarName);

            formatter.format("%n");

        } else {
            final Goal goal = (Goal) agoal;
            final String name = goal.getName();
            final double multiplier = goal.getMultiplier();
            final double min = goal.getMin();
            final double max = goal.getMax();
            final String rawVarName = getVarNameForRawScore(name);
            final String computedVarName = getVarNameForComputedScore(name);

            if (LOG.isTraceEnabled()) {
                LOG.trace("name: " + name);
                LOG.trace("multiplier: " + multiplier);
                LOG.trace("min: " + min);
                LOG.trace("max: " + max);
            }

            formatter.format("<!-- %s -->%n", name);

            if (goal.isEnumerated()) {
                // enumerated
                final List<EnumeratedValue> posValues = agoal.getSortedValues();
                for (int valueIdx = 0; valueIdx < posValues.size(); valueIdx++) {
                    final EnumeratedValue valueEle = posValues.get(valueIdx);

                    final String value = valueEle.getValue();
                    final double valueScore = valueEle.getScore();
                    if (valueIdx > 0) {
                        formatter.format("} else ");
                    }

                    formatter.format("if(%s == \"%s\") {%n", rawVarName, value);
                    formatter.format("  document.scoreEntry.%s[%d].checked = true;%n", name, valueIdx);
                    formatter.format("  %s = %f * %s;%n", computedVarName, valueScore, multiplier);

                    formatter.format("  document.scoreEntry.%s.value = '%s'%n",
                            getElementNameForYesNoDisplay(name), value.toUpperCase());
                } // foreach value
                formatter.format("}%n");
            } else if (goal.isYesNo()) {
                // set the radio button to match the gbl variable
                formatter.format("if(%s == 0) {%n", rawVarName);
                // 0/1 needs to match the order of the buttons generated in
                // generateYesNoButtons
                formatter.format("  document.scoreEntry.%s[0].checked = true%n", name);
                formatter.format("  document.scoreEntry.%s_radioValue.value = 'NO'%n", name);
                formatter.format("} else {%n");
                formatter.format("  document.scoreEntry.%s[1].checked = true%n", name);
                formatter.format("  document.scoreEntry.%s_radioValue.value = 'YES'%n", name);
                formatter.format("}%n");
                formatter.format("%s = %s * %s;%n", computedVarName, rawVarName, multiplier);
            } else {
                // set the count form element
                formatter.format("document.scoreEntry.%s.value = %s;%n", name, rawVarName);
                formatter.format("%s = %s * %s;%n", computedVarName, rawVarName, multiplier);
            }

            // add to the total score
            formatter.format("score += %s;%n", computedVarName);

            // set the score form element
            formatter.format("document.scoreEntry.score_%s.value = %s;%n", name, computedVarName);
            formatter.format("%n");
        }
    } // end foreach goal

    // set the radio buttons for score verification
    formatter.format("if(Verified == 0) {%n");
    // order of elements needs to match generateYesNoButtons
    formatter.format("  document.scoreEntry.Verified[0].checked = true%n"); // NO
    formatter.format("} else {%n");
    formatter.format("  document.scoreEntry.Verified[1].checked = true%n"); // YES
    formatter.format("}%n");

    if (LOG.isTraceEnabled()) {
        LOG.trace("Exiting generateRefreshBody");
    }

}

From source file:org.apache.metron.profiler.hbase.SaltyRowKeyBuilderTest.java

private void printBytes(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    Formatter formatter = new Formatter(sb);
    for (byte b : bytes) {
        formatter.format("%02x ", b);
    }/*  w ww.  j a v a  2  s  . c o m*/
    System.out.println(sb.toString());
}