Example usage for java.text NumberFormat getNumberInstance

List of usage examples for java.text NumberFormat getNumberInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getNumberInstance.

Prototype

public static final NumberFormat getNumberInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:org.jfree.chart.demo.JFreeChartDemoBase.java

/**
 * Creates and returns a sample pie chart.
 *
 * @return a sample pie chart.//from   www  .  j a va  2  s.com
 */
public JFreeChart createPieChartTwo() {

    // create a default chart based on some sample data...
    final String title = this.resources.getString("pie.pie2.title");
    final CategoryDataset data = DemoDatasetFactory.createCategoryDataset();
    final Comparable category = (Comparable) data.getColumnKeys().get(1);
    final PieDataset extracted = DatasetUtilities.createPieDatasetForColumn(data, category);
    final JFreeChart chart = ChartFactory.createPieChart(title, extracted, true, true, false);

    // then customise it a little...
    chart.setBackgroundPaint(Color.lightGray);
    final PiePlot pie = (PiePlot) chart.getPlot();
    pie.setLabelGenerator(new StandardPieItemLabelGenerator("{0} = {2}", NumberFormat.getNumberInstance(),
            NumberFormat.getPercentInstance()));
    pie.setBackgroundImage(JFreeChart.INFO.getLogo());
    pie.setBackgroundPaint(Color.white);
    pie.setBackgroundAlpha(0.6f);
    pie.setForegroundAlpha(0.75f);
    return chart;

}

From source file:org.kalypso.ogc.sensor.tableview.swing.tablemodel.ObservationTableModel.java

/**
 * Exports the contents of the model/*from   w  w  w. j  ava2 s .  c om*/
 */
public void dump(final String separator, final BufferedWriter writer) throws IOException {
    if (m_sharedModel.isEmpty())
        return;

    final Object checkObject = m_sharedModel.first();

    // will be used for formating the various columns
    final Format[] nf = new Format[m_columns.size() + 1];

    // find appropriate format for shared column (Attention: can still be null)
    if (checkObject instanceof Date)
        nf[0] = TimeseriesUtils.getDateFormat();
    else if (checkObject instanceof Integer)
        nf[0] = NumberFormat.getIntegerInstance();
    else if (checkObject instanceof Number)
        nf[0] = NumberFormat.getNumberInstance();

    // dump header and fetch numberformats
    writer.write(m_sharedAxis.getName());
    if (nf[0] instanceof DateFormat) {
        final DateFormat df = (DateFormat) nf[0];
        final TimeZone timeZone = df.getTimeZone();
        if (timeZone != null) {
            writer.write(" ("); //$NON-NLS-1$
            writer.write(timeZone.getID());
            writer.write(")"); //$NON-NLS-1$
        }
    }

    int col = 1;
    for (final Object element : m_columns) {
        final TableViewColumn tvc = (TableViewColumn) element;

        nf[col] = TimeseriesUtils.getNumberFormat(tvc.getFormat());

        writer.write(separator);
        writer.write(tvc.getName());

        col++;
    }

    writer.newLine();

    // dump values
    int row = 0;
    for (final Object key : m_sharedModel) {
        writer.write(nf[0] == null ? key.toString() : nf[0].format(key));

        col = 1;
        for (; col < getColumnCount(); col++) {
            final Object value = getValueAt(row, col);

            writer.write(separator);

            if (nf[col] != null && value != null)
                writer.write(nf[col].format(value));
            else
                writer.write(""); //$NON-NLS-1$
        }

        writer.newLine();
        row++;
    }
}

From source file:Converter.java

ConversionPanel(Converter myController, String myTitle, Unit[] myUnits, ConverterRangeModel myModel) {
    if (MULTICOLORED) {
        setOpaque(true);//from w  ww  .ja  va2 s  .com
        setBackground(new Color(0, 255, 255));
    }
    setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(myTitle),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    // Save arguments in instance variables.
    controller = myController;
    units = myUnits;
    title = myTitle;
    sliderModel = myModel;

    // Create the text field format, and then the text field.
    numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMaximumFractionDigits(2);
    NumberFormatter formatter = new NumberFormatter(numberFormat);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);// seems to be a no-op --
    // aha -- it changes the value property but doesn't cause the result to
    // be parsed (that happens on focus loss/return, I think).
    //
    textField = new JFormattedTextField(formatter);
    textField.setColumns(10);
    textField.setValue(new Double(sliderModel.getDoubleValue()));
    textField.addPropertyChangeListener(this);

    // Add the combo box.
    unitChooser = new JComboBox();
    for (int i = 0; i < units.length; i++) { // Populate it.
        unitChooser.addItem(units[i].description);
    }
    unitChooser.setSelectedIndex(0);
    sliderModel.setMultiplier(units[0].multiplier);
    unitChooser.addActionListener(this);

    // Add the slider.
    slider = new JSlider(sliderModel);
    sliderModel.addChangeListener(this);

    // Make the text field/slider group a fixed size
    // to make stacked ConversionPanels nicely aligned.
    JPanel unitGroup = new JPanel() {
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(150, super.getPreferredSize().height);
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }
    };
    unitGroup.setLayout(new BoxLayout(unitGroup, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        unitGroup.setOpaque(true);
        unitGroup.setBackground(new Color(0, 0, 255));
    }
    unitGroup.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
    unitGroup.add(textField);
    unitGroup.add(slider);

    // Create a subpanel so the combo box isn't too tall
    // and is sufficiently wide.
    JPanel chooserPanel = new JPanel();
    chooserPanel.setLayout(new BoxLayout(chooserPanel, BoxLayout.PAGE_AXIS));
    if (MULTICOLORED) {
        chooserPanel.setOpaque(true);
        chooserPanel.setBackground(new Color(255, 0, 255));
    }
    chooserPanel.add(unitChooser);
    chooserPanel.add(Box.createHorizontalStrut(100));

    // Put everything together.
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
    add(unitGroup);
    add(chooserPanel);
    unitGroup.setAlignmentY(TOP_ALIGNMENT);
    chooserPanel.setAlignmentY(TOP_ALIGNMENT);
}

From source file:voldemort.store.readonly.fetcher.HdfsFetcher.java

/**
 * Function to copy a file from the given filesystem with a checksum of type
 * 'checkSumType' computed and returned. In case an error occurs during such
 * a copy, we do a retry for a maximum of NUM_RETRIES
 * /*from  ww  w.  j a v  a  2 s  . c  om*/
 * @param fs Filesystem used to copy the file
 * @param source Source path of the file to copy
 * @param dest Destination path of the file on the local machine
 * @param stats Stats for measuring the transfer progress
 * @param checkSumType Type of the Checksum to be computed for this file
 * @return A Checksum (generator) of type checkSumType which contains the
 *         computed checksum of the copied file
 * @throws IOException
 */
private CheckSum copyFileWithCheckSum(FileSystem fs, Path source, File dest, CopyStats stats,
        CheckSumType checkSumType) throws Throwable {
    CheckSum fileCheckSumGenerator = null;
    logger.debug("Starting copy of " + source + " to " + dest);
    FSDataInputStream input = null;
    OutputStream output = null;

    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        boolean success = true;
        long totalBytesRead = 0;
        boolean fsOpened = false;
        try {

            // Create a per file checksum generator
            if (checkSumType != null) {
                fileCheckSumGenerator = CheckSum.getInstance(checkSumType);
            }

            logger.info("Attempt " + attempt + " at copy of " + source + " to " + dest);

            input = fs.open(source);
            fsOpened = true;

            output = new BufferedOutputStream(new FileOutputStream(dest));
            byte[] buffer = new byte[bufferSize];
            while (true) {
                int read = input.read(buffer);
                if (read < 0) {
                    break;
                } else {
                    output.write(buffer, 0, read);
                }

                // Update the per file checksum
                if (fileCheckSumGenerator != null) {
                    fileCheckSumGenerator.update(buffer, 0, read);
                }

                // Check if we need to throttle the fetch
                if (throttler != null) {
                    throttler.maybeThrottle(read);
                }

                stats.recordBytes(read);
                totalBytesRead += read;
                if (stats.getBytesSinceLastReport() > reportingIntervalBytes) {
                    NumberFormat format = NumberFormat.getNumberInstance();
                    format.setMaximumFractionDigits(2);
                    logger.info(stats.getTotalBytesCopied() / (1024 * 1024) + " MB copied at "
                            + format.format(stats.getBytesPerSecond() / (1024 * 1024)) + " MB/sec - "
                            + format.format(stats.getPercentCopied()) + " % complete, destination:" + dest);
                    if (this.status != null) {
                        this.status.setStatus(stats.getTotalBytesCopied() / (1024 * 1024) + " MB copied at "
                                + format.format(stats.getBytesPerSecond() / (1024 * 1024)) + " MB/sec - "
                                + format.format(stats.getPercentCopied()) + " % complete, destination:" + dest);
                    }
                    stats.reset();
                }
            }
            logger.info("Completed copy of " + source + " to " + dest);

        } catch (Throwable te) {
            success = false;
            if (!fsOpened) {
                logger.error("Error while opening the file stream to " + source, te);
            } else {
                logger.error("Error while copying file " + source + " after " + totalBytesRead + " bytes.", te);
            }
            if (te.getCause() != null) {
                logger.error("Cause of error ", te.getCause());
            }
            te.printStackTrace();

            if (attempt < maxAttempts - 1) {
                logger.info("Will retry copying after " + retryDelayMs + " ms");
                sleepForRetryDelayMs();
            } else {
                logger.info("Fetcher giving up copy after " + maxAttempts + " attempts");
                throw te;
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
            if (success) {
                break;
            }
        }
        logger.debug("Completed copy of " + source + " to " + dest);
    }
    return fileCheckSumGenerator;
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

private void showCaloriesBurnt() {
    try {/*from w  w  w  .  j  a  v a 2 s . c  om*/
        Number numWeight = NumberFormat.getInstance().parse(weightString);
        weightInt = numWeight.floatValue();
        float caloriesBurntInt = (((showElapsedTime()) * weightInt) * 8);
        caloriesBurntInt = caloriesBurntInt / 1000;
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumFractionDigits(4);
        formatter.setMaximumFractionDigits(4);
        String finalBurn = formatter.format(caloriesBurntInt);
        mCaloriesBurnt.setText(finalBurn);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opencastproject.videosegmenter.impl.VideoSegmenterServiceImpl.java

/**
 * Returns the segments for the movie accessible through the frame grabbing control.
 * /*from w  w  w .j a v  a2 s  . c  o  m*/
 * @param video
 *          the mpeg-7 video representation
 * @param dsh
 *          the data source handler
 * @return the list of segments
 * @throws IOException
 *           if accessing a frame fails
 * @throws VideoSegmenterException
 *           if segmentation of the video fails
 */
protected List<Segment> segment(Video video, FrameGrabber dsh) throws IOException, VideoSegmenterException {
    List<Segment> segments = new ArrayList<Segment>();

    int t = 1;
    int lastStableImageTime = 0;
    long startOfSegment = 0;
    int currentSceneStabilityCount = 1;
    boolean sceneChangeImminent = true;
    boolean luckyPunchRecovery = false;
    int segmentCount = 1;
    BufferedImage previousImage = null;
    BufferedImage lastStableImage = null;
    BlockingQueue<Buffer> bufferQueue = new ArrayBlockingQueue<Buffer>(stabilityThreshold + 1);
    long durationInSeconds = video.getMediaTime().getMediaDuration().getDurationInMilliseconds() / 1000;
    Segment contentSegment = video.getTemporalDecomposition().createSegment("segment-" + segmentCount);
    ImageComparator icomp = new ImageComparator(changesThreshold);

    // icomp.setStatistics(true);
    // String imagesPath = PathSupport.concat(new String[] {
    // System.getProperty("java.io.tmpdir"),
    // "videosegments",
    // video.getMediaLocator().getMediaURI().toString().replaceAll("\\W", "-")
    // });
    // icomp.saveImagesTo(new File(imagesPath));

    Buffer buf = dsh.getBuffer();
    while (t < durationInSeconds && buf != null && !buf.isEOM()) {
        BufferedImage bufferedImage = ImageUtils.createImage(buf);
        if (bufferedImage == null)
            throw new VideoSegmenterException("Unable to extract image at time " + t);

        logger.trace("Analyzing video at {} s", t);

        // Compare the new image with our previous sample
        boolean differsFromPreviousImage = icomp.isDifferent(previousImage, bufferedImage, t);

        // We found an image that is different compared to the previous one. Let's see if this image remains stable
        // for some time (STABILITY_THRESHOLD) so we can declare a new scene
        if (differsFromPreviousImage) {
            logger.debug("Found differing image at {} seconds", t);

            // If this is the result of a lucky punch (looking ahead STABILITY_THRESHOLD seconds), then we should
            // really start over an make sure we get the correct beginning of the new scene
            if (!sceneChangeImminent && t - lastStableImageTime > 1) {
                luckyPunchRecovery = true;
                previousImage = lastStableImage;
                bufferQueue.add(buf);
                t = lastStableImageTime;
            } else {
                lastStableImageTime = t - 1;
                lastStableImage = previousImage;
                previousImage = bufferedImage;
                currentSceneStabilityCount = 1;
                t++;
            }
            sceneChangeImminent = true;
        }

        // We are looking ahead and everyhting seems to be fine.
        else if (!sceneChangeImminent) {
            fillLookAheadBuffer(bufferQueue, buf, dsh);
            lastStableImageTime = t;
            t += stabilityThreshold;
            previousImage = bufferedImage;
            lastStableImage = bufferedImage;
        }

        // Seems to be the same image. If we have just recently detected a new scene, let's see if we are able to
        // confirm that this is scene is stable (>= STABILITY_THRESHOLD)
        else if (currentSceneStabilityCount < stabilityThreshold) {
            currentSceneStabilityCount++;
            previousImage = bufferedImage;
            t++;
        }

        // Did we find a new scene?
        else if (currentSceneStabilityCount == stabilityThreshold) {
            lastStableImageTime = t;

            long endOfSegment = t - stabilityThreshold - 1;
            long durationms = (endOfSegment - startOfSegment) * 1000L;

            // Create a new segment if this wasn't the first one
            if (endOfSegment > stabilityThreshold) {
                contentSegment.setMediaTime(new MediaRelTimeImpl(startOfSegment * 1000L, durationms));
                contentSegment = video.getTemporalDecomposition().createSegment("segment-" + ++segmentCount);
                segments.add(contentSegment);
                startOfSegment = endOfSegment;
            }

            // After finding a new segment, likelihood of a stable image is good, let's take a look ahead. Since
            // a processor can't seek, we need to store the buffers in between, in case we need to come back.
            fillLookAheadBuffer(bufferQueue, buf, dsh);
            t += stabilityThreshold;
            previousImage = bufferedImage;
            lastStableImage = bufferedImage;
            currentSceneStabilityCount++;
            sceneChangeImminent = false;
            logger.info("Found new scene at {} s", startOfSegment);
        }

        // Did we find a new scene by looking ahead?
        else if (sceneChangeImminent) {
            // We found a scene change by looking ahead. Now we want to get to the exact position
            lastStableImageTime = t;
            previousImage = bufferedImage;
            lastStableImage = bufferedImage;
            currentSceneStabilityCount++;
            t++;
        }

        // Nothing special, business as usual
        else {
            // If things look stable, then let's look ahead as much as possible without loosing information (which is
            // equal to looking ahead STABILITY_THRESHOLD seconds.
            lastStableImageTime = t;
            fillLookAheadBuffer(bufferQueue, buf, dsh);
            t += stabilityThreshold;
            lastStableImage = bufferedImage;
            previousImage = bufferedImage;
        }

        if (luckyPunchRecovery) {
            buf = bufferQueue.poll();
            luckyPunchRecovery = !bufferQueue.isEmpty();
        } else
            buf = dsh.getBuffer();
    }

    // Finish off the last segment
    long startOfSegmentms = startOfSegment * 1000L;
    long durationms = ((long) durationInSeconds - startOfSegment) * 1000;
    contentSegment.setMediaTime(new MediaRelTimeImpl(startOfSegmentms, durationms));
    segments.add(contentSegment);

    // Print summary
    if (icomp.hasStatistics()) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        logger.info("Image comparison finished with an average change of {}% in {} comparisons",
                nf.format(icomp.getAvgChange()), icomp.getComparisons());
    }

    // Cleanup
    if (icomp.getSavedImagesDirectory() != null) {
        FileUtils.deleteQuietly(icomp.getSavedImagesDirectory());
    }

    return segments;
}

From source file:l2r.gameserver.handler.voicecommands.impl.RandomCommands.java

public boolean useVoicedCommand(String command, Player activeChar, String args) {
    if (command.equalsIgnoreCase("smsreward")) {
        if (activeChar.getPremiumItemList().isEmpty()) {
            activeChar.sendPacket(Msg.THERE_ARE_NO_MORE_VITAMIN_ITEMS_TO_BE_FOUND);
            return true;
        }/*ww  w . j  a  v a  2  s .  c o  m*/

        activeChar.sendPacket(new ExGetPremiumItemList(activeChar));
    } else if (command.equalsIgnoreCase("gearscore") && activeChar.isGM()) {
        int gearScore = Util.getGearPoints(activeChar);
        activeChar.sendMessage(new CustomMessage(
                "l2r.gameserver.handler.voicecommands.impl.randomcommands.message1", activeChar, gearScore));
    } else if (command.equalsIgnoreCase("sc")
            || command.equalsIgnoreCase("scinfo") && Config.ENABLE_SC_INFO_COMMAND) {
        int page = 1;
        if (args != null && !args.isEmpty() && NumberUtils.isNumber(args))
            page = Integer.parseInt(args);

        int blockforvisual = 0;
        int all = 0;
        boolean pagereached = false;

        StringBuilder html = new StringBuilder();
        html.append("<html><title>Soul Crystal Information</title><body><table height=350>");

        for (NpcTemplate tmpl : NpcHolder.getInstance().getAll()) {
            if (tmpl != null && !tmpl.getAbsorbInfo().isEmpty()) {
                boolean nameAppended = false;
                for (AbsorbInfo ai : tmpl.getAbsorbInfo()) {
                    if (ai == null || ai.getMaxLevel() <= 10)
                        continue;

                    all++;
                    if (page == 1 && blockforvisual > 10)
                        continue;
                    if (!pagereached && all > page * 10)
                        continue;
                    if (!pagereached && all <= (page - 1) * 10)
                        continue;

                    blockforvisual++;

                    if (!nameAppended) {
                        html.append("<tr><td><font color=\"07AE23\">").append(tmpl.getName())
                                .append("</font></td></tr>");
                        nameAppended = true;
                    }

                    int chance = ai.getChance();

                    if (Config.LEVEL_UP_CRY_EXTRA_CHANCE > 0)
                        chance += Config.LEVEL_UP_CRY_EXTRA_CHANCE;

                    if (chance > 100)
                        chance = 100;

                    html.append("<tr><td><table><tr><td width=80>[")
                            .append(ai.getMinLevel() == ai.getMaxLevel() ? ai.getMinLevel()
                                    : (ai.getMinLevel() + "-" + ai.getMaxLevel()))
                            .append("]</td><td width=200>").append(getAbsorbType(ai.getAbsorbType()))
                            .append("</td><td width=50>").append(chance)
                            .append("%</td></tr></table></td></tr>");
                }
            }
        }

        int totalPages = (int) Math.round(all / 10.0 + 1);

        if (page > totalPages)
            return false;

        if (page == 1) {

            html.append("<tr><td width=210>&nbsp;</td>");
            html.append("<td width=50><button value=\">>\" action=\"bypass -h user_sc " + (page + 1)
                    + "\" width=60 height=20 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td></tr>");
        } else if (page > 1)
            if (totalPages == page) {
                html.append("<tr><td width=210>&nbsp;</td>");
                html.append("<td width=50><button value=\"<<\" action=\"bypass -h user_sc " + (page - 1)
                        + "\" width=60 height=20 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td></tr>");
            } else {
                html.append("<tr><td width=210><button value=\"<<\" action=\"bypass -h user_sc " + (page - 1)
                        + "\" width=60 height=20 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>");
                html.append("<td width=50><button value=\">>\" action=\"bypass -h user_sc " + (page + 1)
                        + "\" width=60 height=20 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td></tr>");
            }

        html.append("</table></body></html>");
        activeChar.sendPacket(new NpcHtmlMessage(0).setHtml(html.toString()));
    } else if (command.equalsIgnoreCase("findparty")
            || command.equalsIgnoreCase("fp") && Config.PARTY_SEARCH_COMMANDS) {
        if (activeChar.isInParty() && !activeChar.getParty().isLeader(activeChar)) {
            activeChar.sendMessage(new CustomMessage(
                    "l2r.gameserver.handler.voicecommands.impl.randomcommands.message2", activeChar));
            return false;
        }

        if (!activeChar.canOverrideCond(PcCondOverride.CHAT_CONDITIONS)
                && !activeChar.antiFlood.canFindParty()) {
            activeChar.sendChatMessage(0, ChatType.PARTY.ordinal(), "FINDPARTY",
                    "Anti flood protection. Please try again later.");
            return false;
        }

        if (activeChar.isInJail()) {
            activeChar.sendMessage(new CustomMessage(
                    "l2r.gameserver.handler.voicecommands.impl.randomcommands.message3", activeChar));
            return false;
        }

        int currmembers = activeChar.getParty() != null ? activeChar.getParty().size() : 0;
        if (args == null || args.isEmpty()) {
            if (NexusEvents.isInEvent(activeChar)) {
                for (Player player : GameObjectsStorage.getAllPlayersForIterate())
                    if (!player.isInBlockList(activeChar.getName()) && !player.isInParty()
                            && !player.isInOfflineMode() && !player.isInOlympiadMode()
                            && activeChar.getEventInfo().getTeamId() == player.getEventInfo().getTeamId())
                        player.sendPacket(
                                new Say2(activeChar.getObjectId(), ChatType.BATTLEFIELD, activeChar.getName(),
                                        "   Type=1    ID=" + activeChar.getObjectId()
                                                + " Color=0    Underline=0    Title=VENT]Free slots ("
                                                + currmembers + "/9) "));
            } else {
                for (Player player : GameObjectsStorage.getAllPlayersForIterate())
                    if (!player.isInBlockList(activeChar.getName()) && !player.isInParty()
                            && !player.isInOfflineMode() && !player.isInOlympiadMode()
                            && !player.getVarB("findparty"))
                        player.sendPacket(
                                new Say2(activeChar.getObjectId(), ChatType.PARTY, activeChar.getName(),
                                        "   Type=1    ID=" + activeChar.getObjectId()
                                                + " Color=0    Underline=0    Title=ARTY]Free slots ("
                                                + currmembers + "/9) "));
            }
        } else {
            for (String s : Config.TRADE_WORDS)
                if (args.contains(s)) {
                    activeChar.sendChatMessage(0, ChatType.PARTY.ordinal(), "FINDPARTY",
                            "Dont use party find command for trade!");
                    return false;
                }

            if (args.length() > 22)
                args = args.substring(0, 22);

            if (NexusEvents.isInEvent(activeChar)) {
                for (Player player : GameObjectsStorage.getAllPlayersForIterate())
                    if (!player.isInBlockList(activeChar.getName()) && !player.isInParty()
                            && !player.isInOfflineMode() && !player.isInOlympiadMode()
                            && activeChar.getEventInfo().getTeamId() == player.getEventInfo().getTeamId())
                        player.sendPacket(
                                new Say2(activeChar.getObjectId(), ChatType.BATTLEFIELD, activeChar.getName(),
                                        "   Type=1    ID=" + activeChar.getObjectId()
                                                + " Color=0    Underline=0    Title=VENT]Free slots ("
                                                + currmembers + "/9)  for " + args + ""));
            } else {
                for (Player player : GameObjectsStorage.getAllPlayersForIterate())
                    if (!player.isInBlockList(activeChar.getName()) && !player.isInParty()
                            && !player.isInOfflineMode() && !player.isInOlympiadMode()
                            && !player.getVarB("findparty"))
                        player.sendPacket(
                                new Say2(activeChar.getObjectId(), ChatType.PARTY, activeChar.getName(),
                                        "   Type=1    ID=" + activeChar.getObjectId()
                                                + " Color=0    Underline=0    Title=ARTY]Free slots ("
                                                + currmembers + "/9)  for " + args + ""));
            }
        }

        activeChar.setPartyFindValid(true);
    } else if (command.equalsIgnoreCase("report")) //TODO: Config ...
    {
        String htmlreport = HtmCache.getInstance().getNotNull("command/report.htm", activeChar);

        if (args == null || args == "" || args.isEmpty()) {
            NpcHtmlMessage html = new NpcHtmlMessage(0);
            html.setHtml(htmlreport);
            html.replace("%reported%",
                    activeChar.getTarget() == null ? "Please select target to report or type his name."
                            : activeChar.getTarget().isPlayer() ? activeChar.getTarget().getName()
                                    : "You can report only players.");
            activeChar.sendPacket(html);
            return false;
        }

        String[] paramSplit = args.split(" ");
        if (paramSplit[0].equalsIgnoreCase("Bot") && paramSplit.length != 1) {
            activeChar.sendMessage(new CustomMessage(
                    "l2r.gameserver.handler.voicecommands.impl.randomcommands.message4", activeChar));
            return false;
        }

        StringBuilder sb = new StringBuilder();
        for (String other : paramSplit) {
            other = other.replace("Bot", "");
            other = other.replace("Abuse", "");
            other = other.replace("FakeShop", "");
            other = other.replace("\n", " ");

            sb.append(other + " ");
        }

        String fullMsg = sb.toString();

        if (fullMsg.length() > 150) {
            activeChar.sendMessage(
                    "You have exceeded maximum allowed characters for report. Maximum lenght: 150 characters.");
            return false;
        }

        botReportcommand(activeChar, paramSplit[0], sb.toString());
    } else if (command.equalsIgnoreCase("referral") && Config.ENABLE_REFERRAL_SYSTEM) {
        CharacterEmails.showReferralHtml(activeChar);
    } else if (command.equalsIgnoreCase("help") && Config.ENABLE_HELP_COMMAND) {
        String html = HtmCache.getInstance().getNotNull(Config.BBS_HOME_DIR + "pages/help.htm", activeChar);
        ShowBoard.separateAndSend(html, activeChar);
    } else if (command.equalsIgnoreCase("npcspawn") && Config.ENABLE_NPCSPAWN_COMMAND) {
        if (args == null || args == "" || args.isEmpty()) {
            String msg = showClanhallNpcSpawnWindow(activeChar);
            if (msg != null)
                activeChar.sendMessage(msg);

            return true;
        }

        String[] paramSplit = args.split(" ");
        if (paramSplit.length != 2)
            activeChar.sendMessage(new CustomMessage(
                    "l2r.gameserver.handler.voicecommands.impl.randomcommands.message5", activeChar));
        else {
            if (paramSplit[0].equalsIgnoreCase("spawn")) {
                String npcId = paramSplit[1];
                if (Util.isDigit(npcId)) {
                    String msg = spawnClanhallNpc(activeChar, Integer.parseInt(npcId));
                    if (msg != null)
                        activeChar.sendMessage(msg);
                }
            } else if (paramSplit[0].equalsIgnoreCase("unspawn")) {
                String npcObjId = paramSplit[1];
                if (Util.isDigit(npcObjId)) {
                    String msg = unspawnClanhallNpc(activeChar, Integer.parseInt(npcObjId));
                    if (msg != null)
                        activeChar.sendMessage(msg);
                }
            }
        }
    } else if (command.equalsIgnoreCase("whereis") && Config.ENABLE_WHEREIS_COMMAND)
        return whereis(command, activeChar, args);
    else if (command.equalsIgnoreCase("combinetalismans") || command.equalsIgnoreCase("talisman")
            || command.equalsIgnoreCase("ct") && Config.ENABLE_COMBINE_TALISMAN_COMMAND) {
        try {
            // TalismanId, List<TalismansWithThisId>
            Map<Integer, List<ItemInstance>> talismans = new FastMap<>();

            for (ItemInstance item : activeChar.getInventory().getItems()) {
                if (item == null || !item.isShadowItem()) // Talismans are shadow items.
                    continue;

                int itemId = item.getItemId();
                // Get only the talismans.
                if (!Util.contains(TALISMAN_IDS, itemId))
                    continue;

                if (!talismans.containsKey(itemId))
                    talismans.put(itemId, new FastTable<ItemInstance>());

                talismans.get(itemId).add(item);
            }
            activeChar.sendMessage("----------------------------------------------------");
            activeChar.sendMessage(new CustomMessage(
                    "l2r.gameserver.handler.voicecommands.impl.randomcommands.message6", activeChar));

            // Now same talismans are under 1 list. Loop this list to combine them.
            for (Entry<Integer, List<ItemInstance>> n3 : talismans.entrySet()) {
                List<ItemInstance> sameTalismans = n3.getValue();
                if (sameTalismans.size() <= 1) // We need at least 2 talismans.
                    continue;

                List<ItemInstance> talismansToCharge = new FastTable<>(); // The talisman(s) that isnt(arent) going to be destroyed, but charged.

                // First, find the equipped talisman, it is with charge priority.
                for (ItemInstance talisman : sameTalismans) {
                    if (talisman.isEquipped()) {
                        talismansToCharge.add(talisman); // Add to the chargable talismans.
                        sameTalismans.remove(talisman); // and remove it from the list, because we will loop it again and we dont want that item there.
                    }
                }

                if (talismansToCharge.isEmpty())
                    talismansToCharge.add(sameTalismans.remove(0));

                // Second loop, charge the talismans.
                int index = 0;
                ItemInstance lastTalisman = null;
                for (ItemInstance talisman : sameTalismans) {
                    if (index >= talismansToCharge.size())
                        index = 0;

                    ItemInstance talismanToCharge = talismansToCharge.get(index++);
                    int chargeMana = talisman.getLifeTime() + talismanToCharge.getLifeTime();
                    if (activeChar.getInventory().destroyItem(talisman))
                        talismanToCharge.setLifeTime(chargeMana);

                    lastTalisman = talismanToCharge;
                }

                if (lastTalisman != null) {
                    if (lastTalisman.getJdbcState().isSavable()) {
                        lastTalisman.save();
                    } else {
                        lastTalisman.setJdbcState(JdbcEntityState.UPDATED);
                        lastTalisman.update();
                    }

                    activeChar.sendMessage(new CustomMessage(
                            "l2r.gameserver.handler.voicecommands.impl.randomcommands.message8", activeChar,
                            lastTalisman.getName()));
                    InventoryUpdate iu = new InventoryUpdate().addModifiedItem(lastTalisman);
                    activeChar.sendPacket(iu);
                }
            }

            activeChar.sendMessage("----------------------------------------------------");
        } catch (Exception e) {
            activeChar.sendMessage(
                    new CustomMessage("l2r.gameserver.handler.voicecommands.impl.randomcommands.message9",
                            activeChar, TimeUtils.getDateString(new Date(System.currentTimeMillis()))));
            _log.warn("Error while combining talismans: ", e);
        }
    } else if (command.equalsIgnoreCase("openatod")
            || command.equalsIgnoreCase("oatod") && Config.ENABLE_OPENATOD_COMMAND) {
        if (args == null)
            activeChar.sendMessage(new CustomMessage(
                    "l2r.gameserver.handler.voicecommands.impl.randomcommands.message10", activeChar));
        else {
            int num = 0;
            try {
                num = Integer.parseInt(args);
            } catch (NumberFormatException nfe) {
                activeChar.sendMessage(new CustomMessage(
                        "l2r.gameserver.handler.voicecommands.impl.randomcommands.message11", activeChar));
                return false;
            }

            if (num == 0)
                return false;
            else if (activeChar.getInventory().getCountOf(9599) >= num) {
                int a = 0, b = 0, c = 0, d = 0, rnd;
                for (int i = 0; i < num; i++) {
                    rnd = Rnd.get(100);
                    // 40% Chance for hidden first page
                    if (rnd <= 99 && rnd > 59)
                        a++;
                    // 50% chance for hidden second page
                    else if (rnd <= 59 && rnd > 9)
                        b++;
                    else if (rnd <= 9)
                        c++;
                    else
                        d++;
                }
                if (activeChar.getInventory().destroyItemByItemId(9599, a + b + c + d)) {
                    if (a > 0)
                        Functions.addItem(activeChar, 9600, a, true);
                    //activeChar.getInventory().addItem(9600, a);
                    if (b > 0)
                        Functions.addItem(activeChar, 9601, b, true);
                    //activeChar.getInventory().addItem(9601, b);
                    if (c > 0)
                        Functions.addItem(activeChar, 9602, c, true);
                    //activeChar.getInventory().addItem(9602, c);
                    activeChar.sendMessage(new CustomMessage(
                            "l2r.gameserver.handler.voicecommands.impl.randomcommands.message12", activeChar,
                            d));
                } else
                    activeChar.sendMessage(new CustomMessage(
                            "l2r.gameserver.handler.voicecommands.impl.randomcommands.message13", activeChar));
            } else
                activeChar.sendMessage(new CustomMessage(
                        "l2r.gameserver.handler.voicecommands.impl.randomcommands.message14", activeChar));
        }
    } else if (Config.ENABLE_TRADELIST_VOICE && command.equalsIgnoreCase("tradelist")) {
        TradesHandler.display(activeChar, args);
    } else if (command.equalsIgnoreCase("exp") && Config.ENABLE_EXP_COMMAND) {
        NumberFormat df = NumberFormat.getNumberInstance();
        df.setMaximumFractionDigits(2);

        if (activeChar.getLevel() >= (activeChar.isSubClassActive() ? Experience.getMaxSubLevel()
                : Experience.getMaxLevel()))
            show("Maximum level!", activeChar);
        else {
            long exp = Experience.LEVEL[activeChar.getLevel() + 1] - activeChar.getExp();
            double count = 0;
            String ret = "Exp left: " + exp;
            if (count > 0)
                ret += "<br>Monsters left: " + df.format(count);
            show(ret, activeChar);
        }
    }

    return true;
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String getByteCount(long bytes) {
    return NumberFormat.getNumberInstance().format(bytes);
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private void renderChartInfo() {
    HashMap<Object, Marker> marks = new HashMap<>();
    DefaultPieDataset dataset = buildDataset(marks);

    JFreeChart chart = ChartFactory.createPieChart(null, // chart title
            dataset, // data
            true, // include legend
            true, false);//from ww w.j a  va2  s. c  o  m
    chart.setBackgroundPaint(null);
    //chart.setBorderStroke(null);
    chart.setBorderVisible(false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    // plot.setBackgroundPaint(null);
    //  plot.setShadowPaint(null);

    for (Object o : marks.keySet()) {
        if (iCurrentView == ID_ALLY_CHART) {
            Ally a = (Ally) o;
            plot.setSectionPaint(a.getTag(), marks.get(a).getMarkerColor());
        } else {
            Tribe t = (Tribe) o;
            plot.setSectionPaint(t.getName(), marks.get(t).getMarkerColor());
        }
    }
    //plot.setCircular(true);
    //  plot.setMaximumLabelWidth(30.0);
    /*
        * plot.setLabelGenerator(new StandardPieSectionLabelGenerator( "{0} = {2}", NumberFormat.getNumberInstance(),
        * NumberFormat.getPercentInstance()));
        */
    //   chart.getLegend().setVerticalAlignment(VerticalAlignment.CENTER);
    //  chart.getLegend().setPosition(RectangleEdge.RIGHT);
    // plot.setMaximumLabelWidth(20.0);
    plot.setLabelGenerator(null);
    plot.setBackgroundPaint(Constants.DS_BACK);
    /*
     * plot.setInteriorGap(0.0); plot.setLabelGap(0.0);
     */
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

    /*
     * plot.getL plot.setLabelFont(g2d.getFont().deriveFont(10.0f));
     */

    //plot.setLabelGenerator(null);

    //plot.setMaximumLabelWidth(30.0);
    //plot.getLabelDistributor().distributeLabels(10.0, 20.0);
    //chart.draw(g2d, new Rectangle2D.Float(20, 20, 100, 100));

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    plot.setOutlineVisible(false);
    mChartImage = chart.createBufferedImage(getWidth(), getHeight());
    //chart.draw(g2d, new Rectangle2D.Float(50, 50, 400, 400));
    //g2d.drawImage(bi, 30, 30, null);

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

    //bi = chart.createBufferedImage(240, 240);
    // g2d.drawImage(bi, 30, 30, null);
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private Map<String, Object> createTimeseries(String userPrincipalName, DataSeriesSource dss,
        List<Filter> filters, GroupingImpl group, String timeResolution, Integer prepull,
        String graphTimeSeriesUrl, final Collection<Record> records, final List<Dimension> accumulations,
        final List<Dimension> timeseriesDenominators, String detectorClass, boolean includeDetails,
        boolean displayIntervalEndDate, GraphDataInterface graphData, TimeZone clientTimezone) {

    Map<String, Object> result = new HashMap<String, Object>();
    Map<String, ResolutionHandler> resolutionHandlers = null;
    result.put("success", false);
    try {//w w w  .j a v  a  2 s .  c  om
        GroupingDimension grpdim = dss.getGroupingDimension(group.getId());
        resolutionHandlers = grpdim.getResolutionsMap();
        String dateFieldName = group.getId();
        Date startDate = null;
        Date endDate = null;
        if (grpdim != null
                && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) {
            for (Filter f : filters) {
                if (f instanceof OneArgOpFilter) {
                    OneArgOpFilter of = (OneArgOpFilter) f;
                    if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains(">="))) {
                        startDate = (Date) of.getArguments().get(0);
                    } else if (of.getFilterId().equalsIgnoreCase(grpdim.getId())
                            && (of.getSqlSnippet("").contains("<="))) {
                        endDate = (Date) of.getArguments().get(0);
                    }
                }
            }
        }
        //union accumulations to get all results
        List<Dimension> dimensions = new ArrayList<Dimension>(
                ControllerUtils.unionDimensions(accumulations, timeseriesDenominators));

        int timeOffsetMillies = 0;
        String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false");
        if (timezoneEnabledString.equalsIgnoreCase("true")) {
            timeOffsetMillies = (clientTimezone.getRawOffset() - clientTimezone.getDSTSavings())
                    - (TimeZone.getDefault().getRawOffset() - TimeZone.getDefault().getDSTSavings());
        }
        Calendar startDayCal = Calendar.getInstance(clientTimezone);
        startDayCal.setTime(startDate);
        startDayCal.add(Calendar.MILLISECOND, timeOffsetMillies);

        //get data grouped by group dimension
        List<AccumPoint> points = extractAccumulationPoints(userPrincipalName, dss, records,
                startDayCal.getTime(), endDate, dimensions, group, resolutionHandlers);
        if (points.size() > 0) {
            DateFormat dateFormat = getDateFormat(timeResolution); //dateFormat.setTimeZone(timezone);
            DateFormat tmpDateFormat = (DateFormat) dateFormat.clone();
            tmpDateFormat.setTimeZone(clientTimezone);

            // number format for level
            NumberFormat numFormat3 = NumberFormat.getNumberInstance();
            numFormat3.setMinimumFractionDigits(0);
            numFormat3.setMaximumFractionDigits(3);

            // number format for expected count
            NumberFormat numFormat1 = NumberFormat.getNumberInstance();
            numFormat1.setMinimumFractionDigits(0);
            numFormat1.setMaximumFractionDigits(1);

            Calendar cal = new GregorianCalendar();
            cal.setTime(startDayCal.getTime());
            //offset start date to match prepull offset
            if (timeResolution.equals("weekly")) {
                cal.add(Calendar.DATE, (7 * prepull));
            } else if (timeResolution.equals("daily")) {
                cal.add(Calendar.DATE, prepull);
            }
            Date queryStartDate = cal.getTime();

            //-- Handles Denominator Types -- //
            double[] divisors = new double[points.size()];
            double multiplier = 1.0;
            boolean percentBased = false;
            String yAxisLabel = messageSource.getDataSourceMessage("graph.count", dss);

            boolean isDetectionDetector = !NoDetectorDetector.class.getName().equalsIgnoreCase(detectorClass);

            //if there is a denominator we need to further manipulate the data
            if (timeseriesDenominators != null && !timeseriesDenominators.isEmpty()) {
                // divisor is the sum of timeseriesDenominators
                divisors = totalSeriesValues(points, timeseriesDenominators);
                multiplier = 100.0;
                percentBased = true;
                yAxisLabel = messageSource.getDataSourceMessage("graph.percent", dss);
            } else {
                //the query is for total counts
                Arrays.fill(divisors, 1.0);
            }

            double[][] allCounts = new double[accumulations.size()][];
            int[][] allColors = new int[accumulations.size()][];
            String[][] allAltTexts = new String[accumulations.size()][];
            String[] dates = new String[] { "" };
            double[][] allExpecteds = new double[accumulations.size()][];
            double[][] allLevels = new double[accumulations.size()][];
            String[][] allLineSetURLs = new String[accumulations.size()][];
            String[][] allSwitchInfo = new String[accumulations.size()][];
            String[] lineSetLabels = new String[accumulations.size()];
            boolean[] displayAlerts = new boolean[accumulations.size()];

            //get all results
            Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
            Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);
            Collection<String> accIds = ControllerUtils.getDimensionIdsFromCollection(dss.getAccumulations());
            //remove extra accumulations in the result set using string ids
            dimIds.removeAll(accIds);

            //for each accumulation we run detection and gather results
            int aIndex = 0;
            for (Dimension accumulation : accumulations) {
                String accumId = accumulation.getId();

                // use display name if it has one, otherwise translate its ID
                String accumIdTranslated = accumulation.getDisplayName();
                if (accumIdTranslated == null) {
                    accumIdTranslated = messageSource.getDataSourceMessage(accumulation.getId(), dss);
                }

                TemporalDetectorInterface TDI = (TemporalDetectorInterface) DetectorHelper
                        .createObject(detectorClass);
                TemporalDetectorSimpleDataObject TDDO = new TemporalDetectorSimpleDataObject();

                int[] colors;
                double[] counts;
                String[] altTexts;
                double[] expecteds;
                double[] levels;
                String[] switchInfo;
                String[] urls;

                //pull the counts from the accum array points
                double[] seriesDoubleArray = generateSeriesValues(points, accumId);

                //run divisor before detection
                for (int i = 0; i < seriesDoubleArray.length; i++) {
                    double div = divisors[i];
                    if (div == 0) {
                        seriesDoubleArray[i] = 0.0;
                    } else {
                        seriesDoubleArray[i] = (seriesDoubleArray[i] / div) * multiplier;
                    }
                }

                //run detection
                TDDO.setCounts(seriesDoubleArray);
                TDDO.setStartDate(startDate);
                TDDO.setTimeResolution(timeResolution);

                try {
                    TDI.runDetector(TDDO);
                } catch (Exception e) {
                    String errorMessage = "Failure to create Timeseries";
                    if (e.getMessage() != null) {
                        errorMessage = errorMessage + ":<BR>" + e.getMessage();
                    }
                    result.put("message", errorMessage);
                    result.put("success", false);
                    return result;
                }

                TDDO.cropStartup(prepull);
                counts = TDDO.getCounts();
                int tddoLength = counts.length;

                if (!DAILY.equalsIgnoreCase(timeResolution)) {
                    //toggle between start date and end date
                    //TDDO.setDates(getOurDates(startDate, endDate, tddoLength, timeResolution));
                    TDDO.setDates(getOurDates(queryStartDate, endDate, tddoLength, timeResolution,
                            displayIntervalEndDate));
                }
                double[] tcolors = TDDO.getColors();

                Date[] tdates = TDDO.getDates();
                altTexts = TDDO.getAltTexts();
                expecteds = TDDO.getExpecteds();
                levels = TDDO.getLevels();
                switchInfo = TDDO.getSwitchInfo();
                colors = new int[tddoLength];
                dates = new String[tddoLength];
                urls = new String[tddoLength];

                //add the accumId for the current series
                dimIds.add(accumId);

                StringBuilder jsCall = new StringBuilder();
                jsCall.append("javascript:OE.report.datasource.showDetails({");
                jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
                //specify results
                jsCall.append(",results:[")
                        .append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")).append(']');
                //specify accumId
                jsCall.append(",accumId:'").append(accumId).append("'");

                addJavaScriptFilters(jsCall, filters, dateFieldName);

                //this builds urls and hover texts
                int startDay = getWeekStartDay(resolutionHandlers);

                Calendar c = Calendar.getInstance(clientTimezone);

                //               Calendar curr = Calendar.getInstance();
                for (int i = 0; i < tddoLength; i++) {
                    colors[i] = (int) tcolors[i];

                    // For a time series data point, set time to be current server time
                    // This will allow us to convert this data point date object to be request timezone date
                    c.setTime(tdates[i]);
                    c.add(Calendar.MILLISECOND, timeOffsetMillies);

                    if (timeResolution.equals(WEEKLY)) {
                        dates[i] = dateFormatWeekPart.format(tdates[i]) + "-W"
                                + PgSqlDateHelper.getWeekOfYear(startDay, c) + "-"
                                + PgSqlDateHelper.getYear(startDay, c);
                    } else {
                        dates[i] = tmpDateFormat.format(c.getTime());
                    }

                    altTexts[i] = "(" + accumIdTranslated + ") " + // Accum
                            "Date: " + dates[i] + // Date
                            ", Level: " + numFormat3.format(levels[i]) + // Level
                            ", Count: " + ((int) counts[i]) + // Count
                            ", Expected: " + numFormat1.format(expecteds[i]); // Expected

                    if (switchInfo != null) {
                        altTexts[i] += ", Switch: " + switchInfo[i] + ", ";
                    }

                    // build the click through url
                    StringBuilder tmp = new StringBuilder(jsCall.toString());

                    // add the date field with start and end dates from the data point
                    if (!DAILY.equalsIgnoreCase(timeResolution)) {
                        Calendar timeSet = Calendar.getInstance(clientTimezone);
                        timeSet.setTime(tdates[i]);

                        if (WEEKLY.equalsIgnoreCase(timeResolution)) {
                            timeSet.set(Calendar.DAY_OF_WEEK, startDay + 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.add(Calendar.DAY_OF_YEAR, 6);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (MONTHLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            timeSet.add(Calendar.MONTH, 1);
                            timeSet.add(Calendar.DAY_OF_YEAR, -1);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            // set first day of month
                            timeSet.set(Calendar.DAY_OF_MONTH, 1);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        } else if (YEARLY.equalsIgnoreCase(timeResolution)) {
                            // Compute last day of month
                            timeSet.set(Calendar.DATE, 31);
                            timeSet.add(Calendar.MONTH, Calendar.DECEMBER);
                            tmp.append(",").append(dateFieldName).append("_end:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                            timeSet.set(Calendar.DATE, 1);
                            timeSet.add(Calendar.MONTH, Calendar.JANUARY);
                            tmp.append(",").append(dateFieldName).append("_start:'")
                                    .append(timeSet.getTimeInMillis()).append("'");
                        }
                    } else {
                        // compute end date for individual data points based on the selected resolution
                        //                     detailsPointEndDate = computeEndDate(tdates[i],timeResolution);
                        // add the date field with start and end dates from the data point
                        tmp.append(",").append(dateFieldName).append("_start:'").append(tdates[i].getTime())
                                .append("'");
                        tmp.append(",").append(dateFieldName).append("_end:'").append(tdates[i].getTime())
                                .append("'");
                    }
                    tmp.append("});");
                    urls[i] = tmp.toString();
                }

                allCounts[aIndex] = counts;
                allColors[aIndex] = colors;
                allAltTexts[aIndex] = altTexts;
                allExpecteds[aIndex] = expecteds;
                allLevels[aIndex] = levels;
                allLineSetURLs[aIndex] = urls;
                allSwitchInfo[aIndex] = switchInfo;
                lineSetLabels[aIndex] = accumIdTranslated;
                displayAlerts[aIndex] = isDetectionDetector;
                aIndex++;

                //remove the accumId for the next series
                dimIds.remove(accumId);
            }

            GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
            GraphController gc = getGraphController(null, hndl, userPrincipalName);
            //TODO figure out why I (hodancj1) added this to be accumulation size ~Feb 2012
            // gc.setMaxLegendItems(accumulations.size());

            graphData.setShowSingleAlertLegends(isDetectionDetector);
            graphData.setCounts(allCounts);
            graphData.setColors(allColors);
            graphData.setAltTexts(allAltTexts);
            graphData.setXLabels(dates);
            graphData.setExpecteds(allExpecteds);
            graphData.setLevels(allLevels);
            graphData.setLineSetURLs(allLineSetURLs);
            graphData.setLineSetLabels(lineSetLabels);
            graphData.setDisplayAlerts(displayAlerts);
            // graphData.setDisplaySeverityAlerts(displayAlerts);
            graphData.setPercentBased(percentBased);

            graphData.setXAxisLabel(messageSource.getDataSourceMessage(group.getResolution(), dss));
            graphData.setYAxisLabel(yAxisLabel);

            int maxLabels = graphData.getGraphWidth() / 30;
            graphData.setMaxLabeledCategoryTicks(Math.min(maxLabels, allCounts[0].length));

            StringBuffer sb = new StringBuffer();
            GraphObject graph = gc.writeTimeSeriesGraph(sb, graphData, true, true, false, graphTimeSeriesUrl);

            result.put("html", sb.toString());

            //added to build method calls from javascript
            Map<String, Object> graphConfig = new HashMap<String, Object>();
            graphConfig.put("address", graphTimeSeriesUrl);
            graphConfig.put("graphDataId", graph.getGraphDataId());
            graphConfig.put("imageMapName", graph.getImageMapName());

            graphConfig.put("graphTitle", graphData.getGraphTitle());
            graphConfig.put("xAxisLabel", graphData.getXAxisLabel());
            graphConfig.put("yAxisLabel", graphData.getYAxisLabel());
            graphConfig.put("xLabels", graphData.getXLabels());
            graphConfig.put("graphWidth", graphData.getGraphWidth());
            graphConfig.put("graphHeight", graphData.getGraphHeight());

            graphConfig.put("yAxisMin", graph.getYAxisMin());
            graphConfig.put("yAxisMax", graph.getYAxisMax());

            // fix invalid JSON coming from GraphController
            String dataSeriesJson = graph.getDataSeriesJSON().replaceFirst("\\{", "")
                    // remove trailing "}"
                    .substring(0, graph.getDataSeriesJSON().length() - 2);

            // read malformed JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonFactory jsonFactory = mapper.getJsonFactory()
                    .configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
                    .configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            JsonParser jsonParser = jsonFactory.createJsonParser(dataSeriesJson);

            // array of String -> Object maps
            TypeReference<Map<String, Object>[]> dataSeriesType = new TypeReference<Map<String, Object>[]>() {
            };

            // write JSON as Map so that it can be serialized properly back to JSON
            Map<String, Object>[] seriesMap = mapper.readValue(jsonParser, dataSeriesType);
            graphConfig.put("dataSeriesJSON", seriesMap);

            if (includeDetails) {
                int totalPoints = 0;
                List<HashMap<String, Object>> details = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> detail;
                for (int i = 0; i < allCounts.length; i++) {
                    for (int j = 0; j < allCounts[i].length; j++) {
                        totalPoints++;
                        detail = new HashMap<String, Object>();
                        detail.put("Date", dates[j]);
                        detail.put("Series", lineSetLabels[i]);
                        detail.put("Level", allLevels[i][j]);
                        detail.put("Count", allCounts[i][j]);
                        if (!ArrayUtils.isEmpty(allExpecteds[i])) {
                            detail.put("Expected", allExpecteds[i][j]);
                        }
                        if (!ArrayUtils.isEmpty(allSwitchInfo[i])) {
                            detail.put("Switch", allSwitchInfo[i][j]);
                        }
                        detail.put("Color", allColors[i][j]);
                        details.add(detail);
                    }
                }
                result.put("detailsTotalRows", totalPoints);
                result.put("details", details);
            }
            result.put("graphConfiguration", graphConfig);
            result.put("success", true);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("<h2>" + messageSource.getDataSourceMessage("graph.nodataline1", dss) + "</h2>");
            sb.append("<p>" + messageSource.getDataSourceMessage("graph.nodataline2", dss) + "</p>");
            result.put("html", sb.toString());
            result.put("success", true);
        }
    } catch (Exception e) {
        log.error("Failure to create Timeseries", e);
    }
    return result;
}