Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

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

Prototype

public static final NumberFormat getInstance() 

Source Link

Document

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

Usage

From source file:com.autentia.tnt.bean.admin.ProjectBean.java

public String getCostPerProject() {
    BigDecimal total = project.getCostPerProject();
    String totalCost = null;//ww w  .  ja  v  a 2  s . c  o  m

    NumberFormat format = NumberFormat.getInstance();
    format.setMaximumFractionDigits(2);
    totalCost = format.format(total.doubleValue());

    return totalCost;
}

From source file:com.android.ddmuilib.HeapPanel.java

private static String fractionalPercent(long num, long denom) {
    double val = (double) num / (double) denom;
    val *= 100;/*from w w  w.  ja  v a2s  . c  o  m*/

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(2);
    nf.setMaximumFractionDigits(2);
    return nf.format(val) + "%";
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.StackedBar.java

/**
 * Inherited by IChart.//from  w  w  w  .  j av a2 s  . c om
 * 
 * @param chartTitle the chart title
 * @param dataset the dataset
 * 
 * @return the j free chart
 */

public JFreeChart createChart(DatasetMap datasets) {

    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    logger.debug("Taken Dataset");

    logger.debug("Get plot orientaton");
    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }

    logger.debug("Call Chart Creation");
    JFreeChart chart = ChartFactory.createStackedBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // the plot orientation
            false, // legend
            true, // tooltips
            false // urls
    );
    logger.debug("Chart Created");

    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(color);
    plot.setRangeGridlinePaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);

    logger.debug("set renderer");
    StackedBarRenderer renderer = (StackedBarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setBaseItemLabelsVisible(true);

    if (percentageValue)
        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("#,##.#%")));
    else if (makePercentage)
        renderer.setRenderAsPercentages(true);

    /*
    else
       renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
     */
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    logger.debug("Calling Url Generation");

    MyCategoryUrlGenerator mycatUrl = null;
    if (rootUrl != null) {
        logger.debug("Set MycatUrl");
        mycatUrl = new MyCategoryUrlGenerator(rootUrl);

        mycatUrl.setDocument_composition(document_composition);
        mycatUrl.setCategoryUrlLabel(categoryUrlName);
        mycatUrl.setSerieUrlLabel(serieUrlname);
    }
    if (mycatUrl != null)
        renderer.setItemURLGenerator(mycatUrl);

    logger.debug("Text Title");

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    logger.debug("Style Labels");

    Color colorSubInvisibleTitle = Color.decode("#FFFFFF");
    StyleLabel styleSubSubTitle = new StyleLabel("Arial", 12, colorSubInvisibleTitle);
    TextTitle subsubTitle = setStyleTitle("", styleSubSubTitle);
    chart.addSubtitle(subsubTitle);
    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    logger.debug("Axis creation");
    // set the range axis to display integers only...

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    if (makePercentage)
        rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    else
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setNumberFormatOverride(nf);

    if (rangeAxisLocation != null) {
        if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
        } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
        }
    }

    renderer.setDrawBarOutline(false);

    logger.debug("Set series color");

    int seriesN = dataset.getRowCount();
    if (orderColorVector != null && orderColorVector.size() > 0) {
        logger.debug("color serie by SERIES_ORDER_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            if (orderColorVector.get(i) != null) {
                Color color = orderColorVector.get(i);
                renderer.setSeriesPaint(i, color);
            }
        }
    } else if (colorMap != null) {
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);

            // if serie has been rinominated I must search with the new name!
            String nameToSearchWith = (seriesLabelsMap != null && seriesLabelsMap.containsKey(serieName))
                    ? seriesLabelsMap.get(serieName).toString()
                    : serieName;

            Color color = (Color) colorMap.get(nameToSearchWith);
            if (color != null) {
                renderer.setSeriesPaint(i, color);
                renderer.setSeriesItemLabelFont(i,
                        new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            }
        }
    }

    logger.debug("If cumulative set series paint " + cumulative);

    if (cumulative) {
        int row = dataset.getRowIndex("CUMULATIVE");
        if (row != -1) {
            if (color != null)
                renderer.setSeriesPaint(row, color);
            else
                renderer.setSeriesPaint(row, Color.WHITE);
        }
    }

    MyStandardCategoryItemLabelGenerator generator = null;
    logger.debug("Are there addition labels " + additionalLabels);
    logger.debug("Are there value labels " + showValueLabels);

    if (showValueLabels) {
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        if (valueLabelsPosition.equalsIgnoreCase("inside")) {
            renderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            renderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
        } else {
            renderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
            renderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
        }
    } else if (additionalLabels) {

        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
        logger.debug("generator set");

        double orient = (-Math.PI / 2.0);
        logger.debug("add labels style");
        if (styleValueLabels.getOrientation() != null
                && styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
            orient = 0.0;
        }
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        logger.debug("add labels style set");

        renderer.setBaseItemLabelGenerator(generator);
        renderer.setBaseItemLabelsVisible(true);
        //vertical labels          
        renderer.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        renderer.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));

        logger.debug("end of add labels ");

    }

    logger.debug("domain axis");

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0));
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    //opacizzazione colori
    if (!cumulative)
        plot.setForegroundAlpha(0.6f);
    if (legend == true)
        drawLegend(chart);

    logger.debug("OUT");
    return chart;

}

From source file:com.android.deskclock.Utils.java

/**
 * @param id Resource id of the plural/*from www .j a v  a 2  s .c o  m*/
 * @param quantity integer value
 * @return string with properly localized numbers
 */
public static String getNumberFormattedQuantityString(Context context, int id, int quantity) {
    final String localizedQuantity = NumberFormat.getInstance().format(quantity);
    return context.getResources().getQuantityString(id, quantity, localizedQuantity);
}

From source file:com.ah.be.admin.adminOperateImpl.BeOperateHMCentOSImpl.java

public static List<BeCAFileInfo> getCAFileInfoList(String strDomainName) {
    try {//  www.  jav  a2s . c  om
        File oFileTmp = new File(BeAdminCentOSTools.AH_CERTIFICAT_PFEFIX + strDomainName
                + BeAdminCentOSTools.AH_CERTIFICATE_HOME);

        List<File> oFileInfoList = HmBeOsUtil.getFilesFromFolder(oFileTmp, false);

        List<BeCAFileInfo> oFileList = new ArrayList<BeCAFileInfo>();

        if (null == oFileInfoList) {
            return null;
        }

        for (File oTmp : oFileInfoList) {
            String strFileName = oTmp.getName();

            if (strFileName.endsWith(BeAdminCentOSTools.AH_NMS_HM_CSR_TAIL)
                    || strFileName.endsWith(BeAdminCentOSTools.AH_NMS_HM_PSD_TAIL)
                    || strFileName.endsWith(BeAdminCentOSTools.AH_NMS_HM_SRL_TAIL)
                    || strFileName.endsWith("conf")) {
                continue;
            }

            SimpleDateFormat stmp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String strFileTime = stmp.format(new Date(oTmp.lastModified()));

            double dFileSize = oTmp.length();

            NumberFormat nbf = NumberFormat.getInstance();

            nbf.setMaximumFractionDigits(2);

            nbf.setMaximumFractionDigits(2);

            String strFileSize = nbf.format(dFileSize / 1024);

            BeCAFileInfo oFileInfo = new BeCAFileInfo();

            oFileInfo.setFileName(strFileName);

            oFileInfo.setFileSize(strFileSize);

            oFileInfo.setCreateTime(strFileTime);

            oFileInfo.setDomainName(strDomainName);

            oFileList.add(oFileInfo);
        }

        return oFileList;
    } catch (Exception ex) {
        // add debug log
        DebugUtil.adminDebugWarn("BeOperateHMCentOSImpl.getCAFileInfoList() catch exception", ex);

        return null;
    }
}

From source file:com.aol.framework.helper.report.CustomizedReporter.java

synchronized private void generateModuleOverallTestReport(String testName, String moduleVar,
        List<ISuite> suites, String newFileName) throws Exception {
    StringBuilder moduleResults = new StringBuilder();

    final PrintWriter pw = TestHelper.createFileWriter(TestHelper.customReportDir + newFileName);

    startHtmlPage(pw);/*from  ww  w .  jav  a2 s  .  c  o m*/

    pw.println("<button class=\"sexybutton sexysimple sexylarge sexyblack\" onClick=\"location.href='"
            + TestHelper.customizedReportFileLink//customized-test-run-report.html+
            + "'\"><span class=\"prev\">Back to Overall Execution Summary</span></button>");
    pw.println("<br/><br/><br/><fieldset><legend><b>Testwise Overall Execution Details</b></legend><br/>"
            + "<table class=\"details\" cellspacing=0 cellpadding=0><tr><td><b>Module Name: </b></td><td>"
            + moduleVar + "</td></tr></table></fieldset><br/><br/>");

    moduleResults
            .append("<table id=\"myTable\" width=\"100%\" cellspacing=0 cellpadding=0 class=\"tablesorter\">");
    moduleResults.append("<thead><tr><th>Test Name</th> " +
    //"<th>Module</th> <th>Group</th>"+
            "<th>Browser</th> <th>Version</th> <th>OS</th>"
            + "<th>Node IP</th><th># Passed</th> <th># Failed</th> <th># Warning</th> <th># Skipped</th>"
            + "<th># Total</th> <th>Success Rate</th> </tr> </thead> <tbody>");

    int totalPassedMethods = 0;
    int totalFailedMethods = 0;
    int totalAutomationErrors = 0;
    int totalSkippedMethods = 0;

    String passPercentage = "";

    String suiteName = "";
    ITestContext overview = null;
    try {
        for (ISuite suite : suites) {
            suiteName = suite.getName();
            TestHelper.logger.info(">> " + suiteName + " <<");
            Map<String, ISuiteResult> tests = suite.getResults();

            for (ISuiteResult r : tests.values()) {
                overview = r.getTestContext();
                testName = overview.getName();

                totalPassedMethods = overview.getPassedTests().getAllMethods().size();
                totalFailedMethods = overview.getFailedTests().getAllMethods().size();
                totalAutomationErrors = overview.getFailedButWithinSuccessPercentageTests().getAllMethods()
                        .size();
                totalSkippedMethods = overview.getSkippedTests().getAllMethods().size();

                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(2);
                nf.setGroupingUsed(true);

                passPercentage = getPercentage(nf, totalPassedMethods, totalPassedMethods + totalFailedMethods);

                String includedModule = "";
                String includedGroup = "";

                ITestNGMethod[] allTestMethods = overview.getAllTestMethods();
                for (ITestNGMethod testngMethod : allTestMethods) {
                    String[] modules = testngMethod.getGroups();
                    for (String module : modules) {
                        for (String moduleName : TestHelper.MODULES) {
                            if (module.equalsIgnoreCase(moduleName)) {
                                if (!(includedModule.contains(module))) {
                                    includedModule = includedModule + " " + module;
                                }
                            }
                        }
                        for (String groupName : TestHelper.TEST_GROUPS) {
                            if (module.equalsIgnoreCase(groupName)) {
                                if (!(includedGroup.contains(module))) {
                                    includedGroup = includedGroup + " " + module;
                                }
                            }
                        }
                    }
                }

                String[] nodeInfo = getNodeInfo(overview, testName);

                String browser = nodeInfo[1];
                String browser_version = nodeInfo[2];
                String platform = nodeInfo[0];
                String nodeIp = nodeInfo[3];

                if (platform == null || platform.trim().length() == 0) {
                    platform = "N/A";
                }

                if (browser_version == null || browser_version.trim().length() == 0) {
                    browser_version = "N/A";
                }

                if (browser == null || browser.trim().length() == 0) {
                    browser = "N/A";
                }

                if (browser.equalsIgnoreCase("firefox")) {
                    browser = "Firefox";
                } else if (browser.equalsIgnoreCase("chrome")) {
                    browser = "Chrome";
                } else if (browser.equalsIgnoreCase("internet explorer")) {
                    browser = "IE";
                }

                if (platform.equalsIgnoreCase("xp")) {
                    platform = "XP";
                } else if (platform.equalsIgnoreCase("windows7")) {
                    platform = "Win 7";
                } else if (platform.equalsIgnoreCase("mac")) {
                    platform = "Mac";
                } else {

                }

                if (includedModule.equalsIgnoreCase(moduleVar)) {
                    String fileName = testName + "-customized-report.html";

                    if (nodeIp == null || nodeIp.trim().length() == 0) {
                        nodeIp = "?";
                    }

                    try {
                        generateModuleWiseTestReport(testName, suites, fileName, moduleVar, nodeIp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    String passCount = "";
                    String failCount = "";
                    String automationErrorCount = "";
                    String skipCount = "";

                    if (totalPassedMethods > 0) {
                        passCount = "<td bgcolor=\"" + passColor + "\"><font color=\"white\"><b>"
                                + totalPassedMethods + "</b></font></td>";
                    } else {
                        passCount = "<td>" + totalPassedMethods + "</td>";
                    }

                    if (totalFailedMethods > 0) {
                        failCount = "<td bgcolor=\"" + failColor + "\"><font color=\"white\"><b>"
                                + totalFailedMethods + "</b></font></td>";
                    } else {
                        failCount = "<td>" + totalFailedMethods + "</td>";
                    }
                    if (totalAutomationErrors > 0) {
                        automationErrorCount = "<td bgcolor=\"" + warnColor + "\"><font color=\"white\"><b>"
                                + totalAutomationErrors + "</b></font></td>";
                    } else {
                        automationErrorCount = "<td>" + totalAutomationErrors + "</td>";
                    }
                    if (totalSkippedMethods > 0) {
                        skipCount = "<td bgcolor=\"" + skipColor + "\"><font color=\"white\"><b>"
                                + totalSkippedMethods + "</b></font></td>";
                    } else {
                        skipCount = "<td>" + totalSkippedMethods + "</td>";
                    }

                    moduleResults.append(
                            "<tr><td><b><a href=\"" + fileName + "\">" + testName + "</a></b></td>" + "<td>"
                            //+ includedModule + "</td><td>" + includedGroup + "</td><td>" 
                                    + browser + "</td><td>" + browser_version + "</td><td>" + platform
                                    + "</td><td>" + nodeIp + "</td>" + passCount + failCount
                                    + automationErrorCount + skipCount + "</td><td>"
                                    + (totalPassedMethods + totalFailedMethods + +totalAutomationErrors
                                            + totalSkippedMethods)
                                    + "</td><td><font color=\"" + passPercentageColor + "\"><b>"
                                    + passPercentage + " %" + "</b></font></td></tr>");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();//"Exception in report!!!: "+e);
    }

    moduleResults.append("</tbody></table>");
    pw.println(moduleResults);
    endHtmlPage(pw);
    pw.flush();
    pw.close();
}

From source file:ViewProj.java

public void init() {
    setLayout(new BorderLayout());

    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);/*from  www. j ava  2 s. c o  m*/

    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    JPanel canvasPanel = new JPanel();
    GridBagLayout gridbag = new GridBagLayout();
    canvasPanel.setLayout(gridbag);

    canvas = new Canvas3D(config);
    canvas.setSize(400, 400);

    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.gridwidth = 2;
    constraints.gridheight = 2;
    constraints.insets = new Insets(5, 5, 5, 5);
    constraints.fill = GridBagConstraints.BOTH;
    gridbag.setConstraints(canvas, constraints);
    canvasPanel.add(canvas);

    constraints.fill = GridBagConstraints.REMAINDER;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.gridx = 2;
    constraints.gridy = 0;
    urCanvas = new Canvas3D(config);
    urCanvas.setSize(200, 200);
    gridbag.setConstraints(urCanvas, constraints);
    canvasPanel.add(urCanvas);

    constraints.gridx = 2;
    constraints.gridy = 1;
    lrCanvas = new Canvas3D(config);
    lrCanvas.setSize(200, 200);
    gridbag.setConstraints(lrCanvas, constraints);
    canvasPanel.add(lrCanvas);

    add(canvasPanel, BorderLayout.NORTH);

    SimpleUniverse u = new SimpleUniverse(canvas);
    urUniverse = new SimpleUniverse(urCanvas);
    lrUniverse = new SimpleUniverse(lrCanvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= offScreenScale;
        dim.height *= offScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);

        urOffScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        sOn = urCanvas.getScreen3D();
        sOff = urOffScreenCanvas.getScreen3D();
        dim = sOn.getSize();
        dim.width *= urOffScreenScale;
        dim.height *= urOffScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * urOffScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * urOffScreenScale);

        // attach the offscreen canvas to the view
        urUniverse.getViewer().getView().addCanvas3D(urOffScreenCanvas);

        lrOffScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        sOn = lrCanvas.getScreen3D();
        sOff = lrOffScreenCanvas.getScreen3D();
        dim = sOn.getSize();
        dim.width *= lrOffScreenScale;
        dim.height *= lrOffScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * lrOffScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * lrOffScreenScale);

        // attach the offscreen canvas to the view
        lrUniverse.getViewer().getView().addCanvas3D(lrOffScreenCanvas);
    }

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    viewingPlatform = u.getViewingPlatform();
    viewingPlatform.setNominalViewingTransform();

    view = u.getViewer().getView();
    view.setFrontClipPolicy(View.VIRTUAL_EYE);
    view.setBackClipPolicy(View.VIRTUAL_EYE);
    view.setFrontClipDistance(frontClipDist);
    view.setBackClipDistance(backClipDist);

    u.addBranchGraph(scene);

    // init the clipGridPts arrays
    for (int i = 0; i < maxClipGridPts; i++) {
        clipGridPtsVW[i] = new Point3f();
        clipGridPtsProj[i] = new Point3f();
    }

    // init the circlePts arrays
    for (int i = 0; i < numCirclePts; i++) {
        circlePtsVW[i] = new Point3f();
        circlePtsProj[i] = new Point3f();
    }

    // setup the ur canvas
    urScene = createVWorldViewSG();
    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    urUniverse.getViewingPlatform().setNominalViewingTransform();
    View urView = urUniverse.getViewer().getView();
    urView.setProjectionPolicy(View.PARALLEL_PROJECTION);
    urUniverse.addBranchGraph(urScene);
    // set up the background on a separate BG so that it can stay there
    // when we replace the scene SG
    Background urBgWhite = new Background(white);
    urBgWhite.setApplicationBounds(infiniteBounds);
    BranchGroup urBackBG = new BranchGroup();
    urBackBG.addChild(urBgWhite);
    urUniverse.addBranchGraph(urBackBG);

    // setup the lr canvas
    lrScene = createProjViewSG();
    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    lrUniverse.getViewingPlatform().setNominalViewingTransform();
    View lrView = lrUniverse.getViewer().getView();
    lrView.setProjectionPolicy(View.PARALLEL_PROJECTION);
    lrUniverse.addBranchGraph(lrScene);
    // set up the background on a separate BG so that it can stay there
    // when we replace the scene SG
    Background lrBgWhite = new Background(white);
    lrBgWhite.setApplicationBounds(infiniteBounds);
    BranchGroup lrBackBG = new BranchGroup();
    lrBackBG.addChild(lrBgWhite);
    lrUniverse.addBranchGraph(lrBackBG);

    // set up the sliders
    JPanel guiPanel = new JPanel();
    guiPanel.setLayout(new GridLayout(0, 2));
    FloatLabelJSlider dynamicSlider = new FloatLabelJSlider("Dynamic Offset", 0.1f, 0.0f, 2.0f, dynamicOffset);
    dynamicSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            dynamicOffset = e.getValue();
            solidPa.setPolygonOffsetFactor(dynamicOffset);
        }
    });
    guiPanel.add(dynamicSlider);

    LogFloatLabelJSlider staticSlider = new LogFloatLabelJSlider("Static Offset", 0.1f, 10000.0f, staticOffset);
    staticSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            staticOffset = e.getValue();
            solidPa.setPolygonOffset(staticOffset);
        }
    });
    guiPanel.add(staticSlider);

    // These are declared final here so they can be changed by the
    // listener routines below.
    LogFloatLabelJSlider frontClipSlider = new LogFloatLabelJSlider("Front Clip Distance", 0.001f, 10.0f,
            frontClipDist);
    final LogFloatLabelJSlider backClipSlider = new LogFloatLabelJSlider("Back Clip Distance", 1.0f, 10000.0f,
            backClipDist);
    final LogFloatLabelJSlider backClipRatioSlider = new LogFloatLabelJSlider("Back Clip Ratio", 1.0f, 10000.0f,
            backClipRatio);

    frontClipSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            frontClipDist = e.getValue();
            view.setFrontClipDistance(frontClipDist);
            backClipRatio = backClipDist / frontClipDist;
            backClipRatioSlider.setValue(backClipRatio);
            updateViewWindows();
        }
    });
    guiPanel.add(frontClipSlider);

    backClipSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            backClipDist = e.getValue();
            backClipRatio = backClipDist / frontClipDist;
            backClipRatioSlider.setValue(backClipRatio);
            view.setBackClipDistance(backClipDist);
            updateViewWindows();
        }
    });
    guiPanel.add(backClipSlider);

    backClipRatioSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            backClipRatio = e.getValue();
            backClipDist = backClipRatio * frontClipDist;
            backClipSlider.setValue(backClipDist);
            updateViewWindows();
        }
    });
    guiPanel.add(backClipRatioSlider);
    FloatLabelJSlider innerSphereSlider = new FloatLabelJSlider("Inner Sphere Scale", 0.001f, 0.90f, 1.0f,
            innerScale);
    innerSphereSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            innerScale = e.getValue();
            updateInnerScale();
        }
    });
    guiPanel.add(innerSphereSlider);

    JButton mainSnap = new JButton(snapImageString);
    mainSnap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Point loc = canvas.getLocationOnScreen();
            offScreenCanvas.setOffScreenLocation(loc);
            Dimension dim = canvas.getSize();
            dim.width *= offScreenScale;
            dim.height *= offScreenScale;
            nf.setMinimumIntegerDigits(3);
            offScreenCanvas.snapImageFile(outFileBase + nf.format(outFileSeq++), dim.width, dim.height);
            nf.setMinimumIntegerDigits(0);
        }
    });
    guiPanel.add(mainSnap);

    JButton urSnap = new JButton(urSnapImageString);
    urSnap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Snap UR");
            Point loc = urCanvas.getLocationOnScreen();
            urOffScreenCanvas.setOffScreenLocation(loc);
            Dimension dim = urCanvas.getSize();
            dim.width *= urOffScreenScale;
            dim.height *= urOffScreenScale;
            nf.setMinimumIntegerDigits(3);
            urOffScreenCanvas.snapImageFile(urOutFileBase + nf.format(urOutFileSeq++), dim.width, dim.height);
            nf.setMinimumIntegerDigits(0);
        }
    });
    guiPanel.add(urSnap);

    JButton lrSnap = new JButton(lrSnapImageString);
    lrSnap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Snap LR");
            Point loc = lrCanvas.getLocationOnScreen();
            lrOffScreenCanvas.setOffScreenLocation(loc);
            Dimension dim = lrCanvas.getSize();
            dim.width *= lrOffScreenScale;
            dim.height *= lrOffScreenScale;
            nf.setMinimumIntegerDigits(3);
            lrOffScreenCanvas.snapImageFile(lrOutFileBase + nf.format(lrOutFileSeq++), dim.width, dim.height);
            nf.setMinimumIntegerDigits(0);
        }
    });
    guiPanel.add(lrSnap);
    add(guiPanel, BorderLayout.SOUTH);
}

From source file:mx.edu.um.mateo.activos.web.ActivoController.java

@RequestMapping("/dia")
public String dia(Model modelo, @RequestParam(required = false) Integer anio) throws ParseException {
    log.debug("Reporte DIA para el anio {}", anio);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);/*from www  .  j a  v a  2 s  .  c  o m*/
    if (anio != null) {
        Map<String, Object> params = activoDao.reporteDIA(anio, ambiente.obtieneUsuario());
        modelo.addAllAttributes(params);
        modelo.addAttribute("anio", anio);
        modelo.addAttribute("year", nf.format(anio));
    } else {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, -1);
        int year = cal.get(Calendar.YEAR);
        modelo.addAttribute("anio", year);
        modelo.addAttribute("year", nf.format(year));
    }
    return "activoFijo/activo/dia";
}

From source file:de.tor.tribes.ui.views.DSWorkbenchFarmManager.java

private void showOverallStatus() {
    int farmCount = 0;
    int attacks = 0;
    int hauledWood = 0;
    int hauledClay = 0;
    int hauledIron = 0;
    int woodPerHour = 0;
    int clayPerHour = 0;
    int ironPerHour = 0;

    for (ManageableType type : FarmManager.getSingleton().getAllElements()) {
        FarmInformation info = (FarmInformation) type;
        attacks += info.getAttackCount();
        hauledWood += info.getHauledWood();
        hauledClay += info.getHauledClay();
        hauledIron += info.getHauledIron();
        woodPerHour += BuildingSettings.calculateResourcesPerHour(info.getWoodLevel());
        clayPerHour += BuildingSettings.calculateResourcesPerHour(info.getClayLevel());
        ironPerHour += BuildingSettings.calculateResourcesPerHour(info.getIronLevel());
        farmCount++;/*  w  w w. j av  a2s.c  o  m*/
    }

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);
    int overall = hauledWood + hauledClay + hauledIron;
    StringBuilder b = new StringBuilder();
    b.append("<html>");
    b.append(nf.format(farmCount));
    b.append(" Farmen<br>");
    b.append("Resourcenproduktion pro Stunde (Summe)<br>");
    b.append("<ul>");
    b.append("<li>");
    b.append("Holz: ").append(nf.format(woodPerHour)).append("</li>");
    b.append("<li>");
    b.append("Lehm: ").append(nf.format(clayPerHour)).append("</li>");
    b.append("<li>");
    b.append("Eisen: ").append(nf.format(ironPerHour)).append("</li>");
    b.append("</ul>");
    b.append(nf.format(attacks));
    b.append(" durchgef&uuml;hrte Angriffe<br>");
    b.append(nf.format(hauledWood + hauledClay + hauledIron));
    b.append(" gepl&uuml;nderte Rohstoffe (&#216; ").append(nf.format(overall / attacks)).append(")<br>");
    b.append("<ul>");
    b.append("<li>");
    b.append(nf.format(hauledWood));
    b.append(" Holz (&#216; ").append(nf.format(hauledWood / attacks)).append(")</li>");
    b.append("<li>");
    b.append(nf.format(hauledClay));
    b.append(" Lehm (&#216; ").append(nf.format(hauledClay / attacks)).append(")</li>");
    b.append("<li>");
    b.append(nf.format(hauledIron));
    b.append(" Eisen (&#216; ").append(nf.format(hauledIron / attacks)).append(")</li>");
    b.append("</ul></html>");
    JOptionPaneHelper.showInformationBox(this, b.toString(), "Status");
}

From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java

@Override
public ItemBean getItem(ItemBean itemBean, String viewPK, EntityModel entityModel, boolean staging,
        String language) throws ServiceException {
    try {/*from  www . ja  v  a  2s . co m*/
        String dateFormat = "yyyy-MM-dd"; //$NON-NLS-1$
        String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$

        String dataCluster = getCurrentDataCluster(staging);
        String dataModel = getCurrentDataModel();
        String concept = itemBean.getConcept();
        // get item
        WSDataClusterPK wsDataClusterPK = new WSDataClusterPK(dataCluster);
        String[] ids = CommonUtil.extractIdWithDots(entityModel.getKeys(), itemBean.getIds());

        // parse schema firstly, then use element declaration (DataModelHelper.getEleDecl)
        DataModelHelper.parseSchema(dataModel, concept, entityModel, LocalUser.getLocalUser().getRoles());

        WSItem wsItem = CommonUtil.getPort()
                .getItem(new WSGetItem(new WSItemPK(wsDataClusterPK, itemBean.getConcept(), ids)));
        itemBean.setItemXml(wsItem.getContent());
        extractUsingTransformerThroughView(concept, viewPK, ids, dataModel, dataCluster,
                DataModelHelper.getEleDecl(), itemBean);
        itemBean.set("time", wsItem.getInsertionTime()); //$NON-NLS-1$
        if (wsItem.getTaskId() != null && !"".equals(wsItem.getTaskId()) //$NON-NLS-1$
                && !"null".equals(wsItem.getTaskId())) { //$NON-NLS-1$
            itemBean.setTaskId(wsItem.getTaskId());
        }

        SimpleDateFormat sdf = null;
        Map<String, String[]> formatMap = this.checkDisplayFormat(entityModel, language);
        Set<String> keySet = formatMap.keySet();
        for (String key : keySet) {
            String[] value = formatMap.get(key);
            org.dom4j.Document doc = org.talend.mdm.webapp.base.server.util.XmlUtil
                    .parseText(itemBean.getItemXml());
            TypeModel tm = entityModel.getMetaDataTypes().get(key);
            String xpath = tm.getXpath();
            org.dom4j.Node node = null;
            if (!key.equals(xpath)) {
                Namespace namespace = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$//$NON-NLS-2$
                List<?> nodeList = doc.selectNodes(xpath);
                if (nodeList != null && nodeList.size() > 0) {
                    for (int i = 0; i < nodeList.size(); i++) {
                        org.dom4j.Element current = (org.dom4j.Element) nodeList.get(i);
                        String realType = current.getParent()
                                .attributeValue(new QName("type", namespace, "xsi:type")); //$NON-NLS-1$ //$NON-NLS-2$
                        if (key.replaceAll(":" + realType, "").equals(xpath)) { //$NON-NLS-1$//$NON-NLS-2$
                            node = current;
                            break;
                        }
                    }
                }
            } else {
                node = doc.selectSingleNode(key);
            }

            if (node != null && itemBean.getOriginalMap() != null) {
                String dataText = node.getText();

                if (dataText != null) {
                    if (dataText.trim().length() != 0) {
                        if (dateTypeNames.contains(tm.getType().getBaseTypeName())) {
                            if (value[1].equalsIgnoreCase("DATE")) { //$NON-NLS-1$
                                sdf = new SimpleDateFormat(dateFormat, java.util.Locale.ENGLISH);
                            } else if (value[1].equalsIgnoreCase("DATETIME")) { //$NON-NLS-1$
                                sdf = new SimpleDateFormat(dateTimeFormat, java.util.Locale.ENGLISH);
                            }

                            try {
                                Date date = sdf.parse(dataText.trim());
                                itemBean.getOriginalMap().put(key, date);
                                Calendar calendar = Calendar.getInstance();
                                calendar.setTime(date);
                                String formatValue = com.amalto.webapp.core.util.Util.formatDate(value[0],
                                        calendar);
                                itemBean.getFormateMap().put(key, formatValue);
                            } catch (Exception e) {
                                itemBean.getOriginalMap().remove(key);
                                itemBean.getFormateMap().remove(key);
                            }
                        } else if (numberTypeNames.contains(tm.getType().getBaseTypeName())) {
                            try {
                                NumberFormat nf = NumberFormat.getInstance();
                                Number num = nf.parse(dataText.trim());
                                String formatValue = ""; //$NON-NLS-1$
                                if (tm.getType().getBaseTypeName()
                                        .equals(DataTypeConstants.DOUBLE.getBaseTypeName())) {
                                    formatValue = String.format(value[0], num.doubleValue()).trim();
                                } else if (tm.getType().getBaseTypeName()
                                        .equals(DataTypeConstants.FLOAT.getBaseTypeName())) {
                                    formatValue = String.format(value[0], num.floatValue()).trim();
                                } else if (tm.getType().getBaseTypeName()
                                        .equals(DataTypeConstants.DECIMAL.getBaseTypeName())) {
                                    formatValue = String.format(value[0], new BigDecimal(dataText.trim()))
                                            .trim();
                                } else {
                                    formatValue = String.format(value[0], num).trim();
                                }
                                itemBean.getOriginalMap().put(key, num);
                                itemBean.getFormateMap().put(key, formatValue);
                            } catch (Exception e) {
                                itemBean.getOriginalMap().remove(key);
                                itemBean.getFormateMap().remove(key);
                            }
                        }
                    }
                }
            }
        }

        // dynamic Assemble
        dynamicAssemble(itemBean, entityModel, language);

        return itemBean;
    } catch (WebBaseException e) {
        throw new ServiceException(BASEMESSAGE.getMessage(new Locale(language), e.getMessage(), e.getArgs()));
    } catch (Exception exception) {
        String errorMessage;
        if (CoreException.class.isInstance(exception.getCause())) {
            CoreException webCoreException = (CoreException) exception.getCause();
            errorMessage = getErrorMessageFromWebCoreException(webCoreException, itemBean.getConcept(),
                    itemBean.getIds(), new Locale(language));
        } else {
            errorMessage = exception.getLocalizedMessage();
        }
        LOG.error(errorMessage, exception);
        throw new ServiceException(errorMessage);
    }
}