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() 

Source Link

Document

Constructs a new formatter.

Usage

From source file:com.bluexml.xforms.generator.FormGeneratorsManager.java

/**
 * Provides a unique id for the set of search operators defined in a search field. If an
 * equivalent set already exists, its id is returned. Otherwise, the new set is registered with
 * a new id that's returned./*from w  w  w . jav  a2 s .  c  om*/
 * 
 * @param searchField
 * @return the id, a zero padded sequence number starting from 1
 */
public String getSearchOperatorsListId(SearchField searchField) {
    String resultId;

    // get list of operators and default operator
    SearchFieldDataBean sfDataBean = getSearchFieldDataBean(searchField);

    // test whether the list already exists
    resultId = testOperatorList(sfDataBean.listOp);

    // if so, return the id
    if (resultId != null) {
        return resultId;
    }
    // if not, register the list and return its id
    Formatter formatter = new Formatter();
    resultId = formatter.format("%06d", operatorsEnumsMap.keySet().size() + 1).toString();
    operatorsEnumsMap.put(resultId, sfDataBean.listOp);
    return resultId;
}

From source file:fll.scheduler.TournamentSchedule.java

private void outputPerformanceSchedule(final Document detailedSchedules) throws DocumentException {
    final SortedMap<PerformanceTime, TeamScheduleInfo> performanceTimes = new TreeMap<PerformanceTime, TeamScheduleInfo>();
    for (int round = 0; round < getNumberOfRounds(); ++round) {
        for (final TeamScheduleInfo si : _schedule) {
            performanceTimes.put(si.getPerf(round), si);
        }//from   ww w .j a v  a2 s  .co m
    }

    // list of teams staying around to even up the teams
    final List<TeamScheduleInfo> teamsStaying = new LinkedList<TeamScheduleInfo>();

    final PdfPTable table = PdfUtils.createTable(7);
    table.setWidths(new float[] { 2, 1, 3, 3, 2, 2, 2 });

    final PdfPCell tournamentCell = PdfUtils.createHeaderCell("Tournament: " + getName() + " Performance");
    tournamentCell.setColspan(7);
    table.addCell(tournamentCell);

    table.addCell(PdfUtils.createHeaderCell(TEAM_NUMBER_HEADER));
    table.addCell(PdfUtils.createHeaderCell(DIVISION_HEADER));
    table.addCell(PdfUtils.createHeaderCell(ORGANIZATION_HEADER));
    table.addCell(PdfUtils.createHeaderCell(TEAM_NAME_HEADER));
    table.addCell(PdfUtils.createHeaderCell("Time"));
    table.addCell(PdfUtils.createHeaderCell("Table"));
    table.addCell(PdfUtils.createHeaderCell("Round"));
    table.setHeaderRows(1);

    for (final Map.Entry<PerformanceTime, TeamScheduleInfo> entry : performanceTimes.entrySet()) {
        final PerformanceTime performance = entry.getKey();
        final TeamScheduleInfo si = entry.getValue();
        final int round = si.computeRound(performance);

        // check if team needs to stay and color the cell magenta if they do
        final BaseColor backgroundColor;
        if (null != checkIfTeamNeedsToStay(si, round)) {
            teamsStaying.add(si);
            backgroundColor = BaseColor.MAGENTA;
        } else {
            backgroundColor = null;
        }

        table.addCell(PdfUtils.createCell(String.valueOf(si.getTeamNumber())));
        table.addCell(PdfUtils.createCell(si.getAwardGroup()));
        table.addCell(PdfUtils.createCell(si.getOrganization()));
        table.addCell(PdfUtils.createCell(si.getTeamName()));
        table.addCell(PdfUtils.createCell(formatTime(si.getPerfTime(round)), backgroundColor));
        table.addCell(PdfUtils.createCell(si.getPerfTableColor(round) + " " + si.getPerfTableSide(round),
                backgroundColor));
        table.addCell(PdfUtils.createCell(String.valueOf(round + 1)));
    }

    detailedSchedules.add(table);

    // output teams staying
    if (!teamsStaying.isEmpty()) {
        final String formatString = "Team %d will please stay at the table and compete again - score will not count.";
        final PdfPTable stayingTable = PdfUtils.createTable(1);
        for (final TeamScheduleInfo si : teamsStaying) {
            stayingTable.addCell(PdfUtils.createCell(
                    new Formatter().format(formatString, si.getTeamNumber()).toString(), BaseColor.MAGENTA));
        }
        detailedSchedules.add(stayingTable);

    }

    detailedSchedules.add(Chunk.NEXTPAGE);
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private void parse(String str, TimeZoneMap tzmap) throws ServiceException {
    try {/*from ww  w . j  a v a2s  .  co m*/
        int numByParts = 0;
        for (String tok : str.split("\\s*;\\s*")) {
            String[] s = tok.split("\\s*=\\s*");
            if (s.length != 2) {
                if (ZimbraLog.calendar.isDebugEnabled())
                    ZimbraLog.calendar.debug(
                            new Formatter().format("Parse error for recur: \"%s\" at token \"%s\"", str, tok));
                continue;
            }

            String rhs = s[1];
            // MS Exchange can add invalid spaces in RRULE part values.  Get rid of them.  (see bug 25169)
            rhs = rhs.replaceAll("\\s+", "");

            try {
                switch (Tokens.valueOf(s[0])) {
                case FREQ:
                    mFreq = Frequency.valueOf(rhs);
                    break;
                case UNTIL:
                    ParsedDateTime until = ParsedDateTime.parse(rhs, tzmap);
                    if (until != null) {
                        // RFC2445 4.3.10 Recurrence Rule:
                        // "If specified as a date-time value, then it MUST
                        // be specified in an UTC time format."
                        if (until.hasTime())
                            until.toUTC();
                        mUntil = until;
                    }
                    break;
                case COUNT:
                    mCount = Integer.parseInt(rhs);
                    break;
                case INTERVAL:
                    mInterval = Integer.parseInt(rhs);
                    break;
                case BYSECOND:
                    ++numByParts;
                    parseIntList(rhs, mBySecondList, 0, 59, false);
                    break;
                case BYMINUTE:
                    ++numByParts;
                    parseIntList(rhs, mByMinuteList, 0, 59, false);
                    break;
                case BYHOUR:
                    ++numByParts;
                    parseIntList(rhs, mByHourList, 0, 23, false);
                    break;
                case BYDAY:
                    ++numByParts;
                    parseByDayList(rhs, mByDayList);
                    break;
                case BYMONTHDAY:
                    ++numByParts;
                    parseIntList(rhs, mByMonthDayList, -31, 31, true);
                    break;
                case BYYEARDAY:
                    ++numByParts;
                    parseIntList(rhs, mByYearDayList, -366, 366, true);
                    break;
                case BYWEEKNO:
                    ++numByParts;
                    parseIntList(rhs, mByWeekNoList, -53, 53, true);
                    break;
                case BYMONTH:
                    ++numByParts;
                    parseIntList(rhs, mByMonthList, 1, 12, false);
                    break;
                case BYSETPOS:
                    ++numByParts;
                    parseIntList(rhs, mBySetPosList, Integer.MIN_VALUE, Integer.MAX_VALUE, true);
                    break;
                case WKST:
                    mWkSt = ZWeekDay.valueOf(rhs);
                    break;
                }
            } catch (IllegalArgumentException e) {
                ZimbraLog.calendar.warn("Skipping RECUR token: \"%s\" in Recur \"%s\" due to parse error", s[0],
                        str, e);
            }
        }
        // Convert monthly BYDAY+BYSETPOS combo into simpler BYDAY format.  (bug 35568, 59771)
        // e.g. "BYDAY=TU;BYSETPOS=3" becomes "BYDAY=3TU".
        // This is done only in a very specific case, when all of the following conditions are met:
        // 1) recurrence is monthly
        // 2) BYDAY has exactly one element
        // 3) the BYDAY element has no ordinal
        // 4) BYSETPOS has exactly one element
        // 5) there is no other BYxxx part
        if (numByParts == 2 && Frequency.MONTHLY.equals(mFreq) && mByDayList.size() == 1
                && mByDayList.get(0).mOrdinal == 0 && mBySetPosList.size() == 1) {
            mByDayList.get(0).mOrdinal = mBySetPosList.get(0);
            mBySetPosList.clear();
        }
    } catch (ParseException e) {
        throw ServiceException.FAILURE("Parse error for recur \"" + str + "\"", e);
    }
}

From source file:fll.scheduler.TournamentSchedule.java

/**
 * Compute the general schedule and return it as a string
 *//*from www .j a  v a 2s  . c o m*/
public String computeGeneralSchedule() {
    LocalTime minPerf = null;
    LocalTime maxPerf = null;
    // division -> date
    final Map<String, LocalTime> minSubjectiveTimes = new HashMap<>();
    final Map<String, LocalTime> maxSubjectiveTimes = new HashMap<>();

    for (final TeamScheduleInfo si : _schedule) {
        final String judgingStation = si.getJudgingGroup();
        for (final SubjectiveTime stime : si.getSubjectiveTimes()) {
            final LocalTime currentMin = minSubjectiveTimes.get(judgingStation);
            if (null == currentMin) {
                minSubjectiveTimes.put(judgingStation, stime.getTime());
            } else {
                if (stime.getTime().isBefore(currentMin)) {
                    minSubjectiveTimes.put(judgingStation, stime.getTime());
                }
            }
            final LocalTime currentMax = maxSubjectiveTimes.get(judgingStation);
            if (null == currentMax) {
                maxSubjectiveTimes.put(judgingStation, stime.getTime());
            } else {
                if (stime.getTime().isAfter(currentMax)) {
                    maxSubjectiveTimes.put(judgingStation, stime.getTime());
                }
            }

        }

        for (int i = 0; i < getNumberOfRounds(); ++i) {
            if (null != si.getPerfTime(i)) {
                if (null == minPerf || si.getPerfTime(i).isBefore(minPerf)) {
                    minPerf = si.getPerfTime(i);
                }

                if (null == maxPerf || si.getPerfTime(i).isAfter(maxPerf)) {
                    maxPerf = si.getPerfTime(i);
                }
            }
        }

    }

    // print out the general schedule
    final Formatter output = new Formatter();
    final Set<String> stations = new HashSet<String>();
    stations.addAll(minSubjectiveTimes.keySet());
    stations.addAll(maxSubjectiveTimes.keySet());
    for (final String station : stations) {
        final LocalTime earliestStart = minSubjectiveTimes.get(station);
        final LocalTime latestStart = maxSubjectiveTimes.get(station);
        final Duration subjectiveDuration = Duration.ofMinutes(SolverParams.DEFAULT_SUBJECTIVE_MINUTES);
        final LocalTime latestEnd = latestStart.plus(subjectiveDuration);

        output.format(
                "Subjective times for judging station %s: %s - %s (assumes default subjective time of %d minutes)%n",
                station, formatTime(earliestStart), formatTime(latestEnd),
                SolverParams.DEFAULT_SUBJECTIVE_MINUTES);
    }
    if (null != minPerf && null != maxPerf) {
        final Duration performanceDuration = Duration.ofMinutes(SolverParams.DEFAULT_PERFORMANCE_MINUTES);
        final LocalTime performanceEnd = maxPerf.plus(performanceDuration);

        output.format("Performance times: %s - %s (assumes default performance time of %d minutes)%n",
                formatTime(minPerf), formatTime(performanceEnd), SolverParams.DEFAULT_PERFORMANCE_MINUTES);
    }
    return output.toString();
}

From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java

private List getAllTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List ticks = new java.util.ArrayList();

    //get lower bound value:
    double lowerBoundVal = getRange().getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }//w  ww.  ja  v  a 2  s.co m
    //get upper bound value
    double upperBoundVal = getRange().getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    if (iBegCount == iEndCount && iBegCount > 0 && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    int numberOfGrids = 0;
    int numberOfTicks = 0;
    NumberTick lastTick = null;
    double tickVal;
    String tickLabel;
    //        tickVal = lowerBoundVal;
    //        
    //        tickLabel = Long.toString((long) Math.rint(tickVal));
    //        ticks.add(new NumberTick(new Double(tickVal), tickLabel,
    //              TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, 0.0));
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each tick with a label to be displayed
        int jEndCount = 10;
        if (i == iEndCount) {
            //                jEndCount = 1;
        }

        for (int j = 0; j < jEndCount; j++) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use
                tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
                //first tick of group; create label text
                if (this.log10TickLabelsFlag) {
                    //if flag then
                    tickLabel = "10^" + i; //create "log10"-type label
                } else { //not "log10"-type label
                    if (this.expTickLabelsFlag) {
                        //if flag then
                        tickLabel = "1e" + i; //create "1e#"-type label
                    } else { //not "1e#"-type label
                        if (i >= 0) { // if positive exponent then
                                      // make integer
                            NumberFormat format = getNumberFormatOverride();
                            if (format != null) {
                                tickLabel = format.format(tickVal);
                            } else {
                                tickLabel = Long.toString((long) Math.rint(tickVal));
                            }
                        } else {
                            //negative exponent; create fractional value
                            //set exact number of fractional digits to
                            // be shown:
                            this.numberFormatterObj.setMaximumFractionDigits(-i);
                            //create tick label:
                            tickLabel = this.numberFormatterObj.format(tickVal);
                        }
                    }
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j;
                } //decrement to do 1.0 tick now
                tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (!zeroTickFlag) { // did not do zero tick last
                                     // iteration
                    if (i > iBegCount && i < iEndCount && Math.abs(tickVal - 1.0) < 0.0001) {
                        // not first or last tick on graph and value
                        // is 1.0
                        tickVal = 0.0; //change value to 0.0
                        zeroTickFlag = true; //indicate zero tick
                        tickLabel = "0"; //create label for tick
                    } else {
                        //first or last tick on graph or value is 1.0
                        //create label for tick:
                        tickLabel = createTickLabel(tickVal, i);
                    }
                } else { // not first tick of group
                    tickLabel = createTickLabel(tickVal, i);
                }
            }

            if (tickVal > upperBoundVal) {
                if (lastTick != null) {
                    String lastTickText = lastTick.getText();
                    if (lastTickText == null || lastTickText.trim().length() == 0) {
                        ticks.remove(lastTick);
                        ticks.add(new NumberTick(lastTick.getValue(),
                                createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(),
                                lastTick.getRotationAnchor(), lastTick.getAngle()));
                    }
                }
                if (ticks.size() < 2) {
                    double definition = Math.abs(lowerBoundVal - upperBoundVal);
                    int numberOfDigits = 0;
                    if (definition >= 1)
                        numberOfDigits = 0;
                    else {
                        numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
                    }
                    tickVal = lowerBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                    tickVal = upperBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                }
                return ticks; //if past highest data value then exit method
            }

            if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = -Math.PI / 2.0;
                    } else {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                    } else {
                        anchor = TextAnchor.CENTER_LEFT;
                        rotationAnchor = TextAnchor.CENTER_LEFT;
                    }
                }
                //create tick object and add to list:
                lastTick = new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle);
                ticks.add(lastTick);
                if (tickLabel != null && tickLabel.trim().length() > 0)
                    numberOfTicks++;
                numberOfGrids++;
            }
        }
    }
    if (ticks.size() < 2) {
        double definition = Math.abs(lowerBoundVal - upperBoundVal);
        int numberOfDigits = 0;
        if (definition >= 1)
            numberOfDigits = 0;
        else {
            numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
        }
        tickVal = lowerBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
        tickVal = upperBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
    }
    return ticks;
}

From source file:com.zimbra.cs.mailbox.calendar.ZRecur.java

private void parseIntList(String str, List<Integer> list, int min, int max, boolean signed) {
    for (String s : str.split("\\s*,\\s*"))
        try {/* w  w  w  .jav  a  2s. c  om*/
            int readInt;
            if (signed)
                readInt = parseSignedInt(s);
            else
                readInt = parseUnsignedInt(s);
            if (readInt >= min && readInt <= max) {
                list.add(readInt);
            }
        } catch (Exception e) {
            ZimbraLog.calendar.debug(new Formatter().format(
                    "Skipping unparsable Recur int list entry: \"%s\" in parameter list: \"%s\"", s, str));
        }
    Collections.sort(list);
}

From source file:org.smilec.smile.student.CourseList.java

private String createwinnerhtml() {
    String return_html = "";

    String header1 = "<html><head></head><body><P></P><font face=\"helvetica\">";
    String header2 = "<center><Strong>" + getString(R.string.winner_title) + "</Strong></center><br>";
    String body1 = "<P></P>*** " + getString(R.string.quiz_score) + " ***<br>";
    String body2 = getString(R.string.h_score) + ":" + high_score + "<br>";
    String body3 = getString(R.string.name) + ":<br>";
    String mid_html = "";
    for (int i = 0; i < score_winner_name.size(); i++) {
        String name = score_winner_name.get(i);
        mid_html = mid_html + name + "<br>";
    }//from ww  w.j  a v a 2 s. c  o  m

    String body4 = "<P></P>";
    String body5 = "*** " + getString(R.string.rating_score_title) + " ***<br>";
    Formatter f = new Formatter();
    String avg = f.format(new String("%4.2f"), high_rating).toString();
    String body6 = getString(R.string.h_avg_rating) + " :" + avg + "<br>";
    String body7 = getString(R.string.name) + " :<br>";
    String next_html = "";
    for (int i = 0; i < rating_winner_name.size(); i++) {
        String r_name = rating_winner_name.get(i);
        next_html = next_html + r_name + "<br>";

    }
    String end = "</font></body></html>";

    return_html = header1 + getHTMLTagForUTF8() + header2 + body1 + body2 + body3 + mid_html + body4 + body5
            + body6 + body7 + next_html + end;

    return return_html;
}

From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java

private List getAllTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    // TODO Auto-generated method stub
    List ticks = new java.util.ArrayList();
    Range range = getRange();/* ww  w . ja  va  2 s. c o m*/

    //get lower bound value:
    double lowerBoundVal = range.getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }

    //get upper bound value
    double upperBoundVal = range.getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    //        if (iBegCount == iEndCount && iBegCount >= 0
    if (iBegCount == iEndCount && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    int numberOfGrids = 0;
    int numberOfTicks = 0;
    NumberTick lastTick = null;

    double currentTickValue;
    String tickLabel;
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each power of 10 value; create ten ticks
        for (int j = 0; j < 10; ++j) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use; create numeric value for tick
                currentTickValue = Math.pow(10, i) + (Math.pow(10, i) * j);
                if (this.expTickLabelsFlag || (i < 0 && currentTickValue > 0.0 && currentTickValue < 1.0)) {
                    //showing "1e#"-style ticks or negative exponent
                    // generating tick value between 0 & 1; show fewer
                    //first tick of series, or not too small a value and
                    // one of first 3 ticks, or last tick to be displayed
                    // set exact number of fractional digits to be shown
                    // (no effect if showing "1e#"-style ticks):
                    this.numberFormatterObj.setMaximumFractionDigits(-i);
                    //create tick label (force use of fmt obj):
                    tickLabel = makeTickLabel(currentTickValue, true);
                } else { //tick value not between 0 & 1
                         //show tick label if it's the first or last in
                         // the set, or if it's 1-5; beyond that show
                         // fewer as the values get larger:
                    tickLabel = makeTickLabel(currentTickValue);
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j; //decrement to do 1.0 tick now
                } //calculate power-of-ten value for tick:
                currentTickValue = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (!zeroTickFlag) { // did not do zero tick last iteration
                    if (Math.abs(currentTickValue - 1.0) < 0.0001 && lowerBoundVal <= 0.0
                            && upperBoundVal >= 0.0) {
                        //tick value is 1.0 and 0.0 is within data range
                        currentTickValue = 0.0; //set tick value to zero
                        zeroTickFlag = true; //indicate zero tick
                    }
                } else { //did zero tick last iteration
                    zeroTickFlag = false; //clear flag
                } //create tick label string:
                //show tick label if "1e#"-style and it's one
                // of the first two, if it's the first or last
                // in the set, or if it's 1-5; beyond that
                // show fewer as the values get larger:
                tickLabel = makeTickLabel(currentTickValue);
            }

            if (currentTickValue > upperBoundVal) {
                if (lastTick != null) {
                    String lastTickText = lastTick.getText();
                    if (lastTickText == null || lastTickText.trim().length() == 0) {
                        ticks.remove(lastTick);
                        ticks.add(new NumberTick(lastTick.getValue(),
                                createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(),
                                lastTick.getRotationAnchor(), lastTick.getAngle()));
                    }
                }
                if (ticks.size() < 2) {
                    double definition = Math.abs(lowerBoundVal - upperBoundVal);
                    int numberOfDigits = 0;
                    if (definition >= 1)
                        numberOfDigits = 0;
                    else {
                        numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
                    }
                    if (definition < 2 * Math.pow(10, -numberOfDigits)) {
                        numberOfDigits++;
                    }
                    double tickVal;
                    tickVal = lowerBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER,
                            TextAnchor.TOP_CENTER, 0.0));
                    tickVal = upperBoundVal;
                    if (definition > 1) {
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    } else {
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    }
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER,
                            TextAnchor.TOP_CENTER, 0.0));
                }
                return ticks; // if past highest data value then exit
                              // method
            }

            if (currentTickValue >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    anchor = TextAnchor.CENTER_RIGHT;
                    rotationAnchor = TextAnchor.CENTER_RIGHT;
                    if (edge == RectangleEdge.TOP) {
                        angle = Math.PI / 2.0;
                    } else {
                        angle = -Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.TOP) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    } else {
                        anchor = TextAnchor.TOP_CENTER;
                        rotationAnchor = TextAnchor.TOP_CENTER;
                    }
                }

                lastTick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor,
                        angle);
                ticks.add(lastTick);
                if (tickLabel != null && tickLabel.trim().length() > 0)
                    numberOfTicks++;
                numberOfGrids++;
            }
        }
    }
    if (ticks.size() < 2) {
        double definition = Math.abs(lowerBoundVal - upperBoundVal);
        int numberOfDigits = 0;
        if (definition >= 1)
            numberOfDigits = 0;
        else {
            numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
        }
        double tickVal;
        tickVal = lowerBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER,
                0.0));
        tickVal = upperBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.TOP_CENTER, TextAnchor.TOP_CENTER,
                0.0));
    }
    return ticks;
}

From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java

public String getNodeContentInfo(AlfrescoTransaction transaction, String nodeId) {
    if (StringUtils.trimToNull(nodeId) == null) {
        return "";
    }//ww  w  . j  av  a 2  s.  c o m
    String request;
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("nodeId", nodeId);

    try {
        request = requestString(transaction, parameters, MsgId.INT_WEBSCRIPT_OPCODE_NODE_INFO);
    } catch (ServletException e) {
        e.printStackTrace();
        return null;
    }

    if (StringUtils.trimToNull(request) == null) {
        return "";
    }

    String result;
    String[] infos = request.split(","); // <- see the webscript for the actual format
    String nodeName = infos[0]; // the node name
    long size = Long.parseLong(infos[1]); // the content's size
    if (size > 0) {
        String sizeUnit = "";
        Formatter formatter = new Formatter();
        String sizeBytes = formatter.format("%,d", size).toString();
        char multiplier = getFileSizeUnit(size);
        if (multiplier != 'b') {
            sizeUnit = " (" + getFileSizeShortReadable(size, multiplier) + ")";
        } else {
            //
        }
        result = MsgPool.getMsg(MsgId.MSG_UPLOAD_CONTENT_REPO_FORMAT, nodeName, sizeBytes, sizeUnit, nodeId);
    } else {
        result = MsgPool.getMsg(MsgId.MSG_UPLOAD_CONTENT_NO_CONTENT);
    }
    // result += " " + result;
    return result;
}

From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java

/**
 * Returns a "short" version of the given file size using the appropriate
 * multiplier, and/*from w w w.java  2s  .  com*/
 * formatted with a fixed number (see the format) of decimal places. <br/>
 * Examples: 1024 bytes => 1.00 KB, 7 614 525 bytes => 7.26 MB
 * 
 * @param transferred
 * @param unit
 * @return
 */
private static String getFileSizeShortReadable(long transferred, char unit) {
    float res = transferred;
    String unitStr = "B";
    switch (unit) {
    case 'k':
    case 'K':
        res = (float) transferred / (float) (1024);
        unitStr = "KB";
        break;
    case 'm':
    case 'M':
        res = (float) transferred / (float) (1024 * 1024);
        unitStr = "MB";
        break;
    case 'g':
    case 'G':
        res = (float) transferred / (float) (1024 * 1024 * 1024);
        unitStr = "GB";
        break;
    }
    Formatter formatter = new Formatter();
    return formatter.format("%,.2f", res) + " " + unitStr;
}