List of usage examples for java.text NumberFormat getNumberInstance
public static NumberFormat getNumberInstance(Locale inLocale)
From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java
/** * convert a localized value into its XML Schema datatype representation. If the value given cannot be parsed with * the locale in betterForm context the default locale (US) will be used as fallback. This can be convenient for * user-agents that do not pass a localized value back. * * @param value the value to convert/*from ww w .j a v a 2s .c o m*/ * @return converted value that can be used to update instance data and match the Schema datatype lexical space * @throws java.text.ParseException in case the incoming string cannot be converted into a Schema datatype representation */ protected String delocaliseValue(String value) throws XFormsException, ParseException { if (value == null || value.equals("")) { return value; } if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N).equals("true")) { Locale locale = (Locale) getModel().getContainer().getProcessor().getContext() .get(XFormsProcessorImpl.BETTERFORM_LOCALE); XFormsProcessorImpl processor = this.model.getContainer().getProcessor(); if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":float") || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":decimal") || processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":double")) { NumberFormat formatter = NumberFormat.getNumberInstance(locale); formatter.setMaximumFractionDigits(Double.SIZE); BigDecimal number; try { number = strictParse(value, locale); } catch (ParseException e) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } catch (NumberFormatException nfe) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } catch (InputMismatchException ime) { LOGGER.warn("value: '" + value + "' could not be parsed for locale: " + locale); return value; } return number.toPlainString(); } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":date")) { DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); Date d = null; try { d = df.parse(value); } catch (ParseException e) { //try the default locale - else fail with ParseException df = new SimpleDateFormat("yyyy-MM-dd"); df.setLenient(false); d = df.parse(value); } df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(d); } else if (processor.hasControlType(this.id, NamespaceConstants.XMLSCHEMA_PREFIX + ":dateTime")) { String timezone = ""; // int position = ; if (value.contains("GMT")) { timezone = value.substring(value.indexOf("GMT") + 3, value.length()); } else if (value.contains("+")) { timezone = value.substring(value.indexOf("+"), value.length()); } else if (value.contains("Z")) { timezone = "Z"; } DateFormat sf = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale); Date d = null; try { d = sf.parse(value); } catch (ParseException e) { //try the default locale - else fail with ParseException sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); d = null; d = sf.parse(value); } sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String converted = sf.format(d); if (!timezone.equals("")) { return converted + timezone; } return converted; } } return value; }
From source file:org.languagetool.dev.dumpcheck.SentenceSourceChecker.java
private void run(File propFile, Set<String> disabledRules, String langCode, List<String> fileNames, String[] ruleIds, String[] additionalCategoryIds, int maxSentences, int maxErrors, File languageModelDir, File word2vecModelDir, File neuralNetworkModelDir, Pattern filter) throws IOException { Language lang = Languages.getLanguageForShortCode(langCode); MultiThreadedJLanguageTool languageTool = new MultiThreadedJLanguageTool(lang); languageTool.setCleanOverlappingMatches(false); if (languageModelDir != null) { languageTool.activateLanguageModelRules(languageModelDir); }//from w w w .j a v a2 s. c o m if (word2vecModelDir != null) { languageTool.activateWord2VecModelRules(word2vecModelDir); } if (neuralNetworkModelDir != null) { languageTool.activateNeuralNetworkRules(neuralNetworkModelDir); } if (ruleIds != null) { enableOnlySpecifiedRules(ruleIds, languageTool); } else { applyRuleDeactivation(languageTool, disabledRules); } if (filter != null) { System.out.println( "*** NOTE: only sentences that match regular expression '" + filter + "' will be checked"); } activateAdditionalCategories(additionalCategoryIds, languageTool); disableSpellingRules(languageTool); System.out.println("Working on: " + StringUtils.join(fileNames, ", ")); System.out.println("Sentence limit: " + (maxSentences > 0 ? maxSentences : "no limit")); System.out.println("Error limit: " + (maxErrors > 0 ? maxErrors : "no limit")); //System.out.println("Version: " + JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ")"); ResultHandler resultHandler = null; int ruleMatchCount = 0; int sentenceCount = 0; try { if (propFile != null) { resultHandler = new DatabaseHandler(propFile, maxSentences, maxErrors); } else { //resultHandler = new CompactStdoutHandler(maxSentences, maxErrors); resultHandler = new StdoutHandler(maxSentences, maxErrors); } MixingSentenceSource mixingSource = MixingSentenceSource.create(fileNames, lang, filter); while (mixingSource.hasNext()) { Sentence sentence = mixingSource.next(); try { List<RuleMatch> matches = languageTool.check(sentence.getText()); resultHandler.handleResult(sentence, matches, lang); sentenceCount++; if (sentenceCount % 5000 == 0) { System.err.printf("%s sentences checked...\n", NumberFormat.getNumberInstance(Locale.US).format(sentenceCount)); } ruleMatchCount += matches.size(); } catch (DocumentLimitReachedException | ErrorLimitReachedException e) { throw e; } catch (Exception e) { throw new RuntimeException( "Check failed on sentence: " + StringUtils.abbreviate(sentence.getText(), 250), e); } } } catch (DocumentLimitReachedException | ErrorLimitReachedException e) { System.out.println(getClass().getSimpleName() + ": " + e); } finally { languageTool.shutdown(); if (resultHandler != null) { float matchesPerSentence = (float) ruleMatchCount / sentenceCount; System.out.printf(lang + ": %d total matches\n", ruleMatchCount); System.out.printf(lang + ": %.2f rule matches per sentence\n", matchesPerSentence); try { resultHandler.close(); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:com.commander4j.util.JUtility.java
public static BigDecimal stringToBigDecimal(String str) { BigDecimal result;//from w ww . ja v a 2s .c o m NumberFormat nf; nf = NumberFormat.getNumberInstance(Locale.getDefault()); try { Number myNumber = nf.parse(str); Double dbl = myNumber.doubleValue(); result = BigDecimal.valueOf(dbl); str = String.valueOf(dbl); } catch (ParseException e) { final Logger logger = Logger.getLogger(JUtility.class); logger.error(e.getMessage()); str = "0"; result = new BigDecimal("0"); } // result = new BigDecimal(str); return result; }
From source file:org.pentaho.reporting.libraries.formula.typing.DefaultTypeRegistry.java
public String convertToText(final Type type1, final Object value) throws EvaluationException { if (value == null) { return ""; }// w w w . j a v a 2 s . c o m // already converted or compatible if (type1.isFlagSet(Type.TEXT_TYPE)) { // no need to check whatever it is a String return computeStringValue(value); } if (type1.isFlagSet(Type.LOGICAL_TYPE)) { if (value instanceof Boolean) { final Boolean b = (Boolean) value; if (Boolean.TRUE.equals(b)) { return "TRUE"; } else { return "FALSE"; } } else { throw TypeConversionException.getInstance(); } } // 2 types of numeric : numbers and dates if (type1.isFlagSet(Type.NUMERIC_TYPE)) { final LocalizationContext localizationContext = context.getLocalizationContext(); if (type1.isFlagSet(Type.DATETIME_TYPE) || type1.isFlagSet(Type.DATE_TYPE) || type1.isFlagSet(Type.TIME_TYPE)) { final Date d = convertToDate(type1, value); final List dateFormats = localizationContext.getDateFormats(type1); if (dateFormats != null && dateFormats.size() >= 1) { final DateFormat format = (DateFormat) dateFormats.get(0); return format.format(d); } else { // fallback return DateFormat .getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, localizationContext.getLocale()) .format(d); } } else { try { final Number n = convertToNumber(type1, value); final List<NumberFormat> numberFormats = localizationContext.getNumberFormats(); if (numberFormats.isEmpty()) { // use the canonical format .. return NumberFormat.getNumberInstance(localizationContext.getLocale()).format(n); } else { numberFormats.get(0).format(n); } } catch (EvaluationException nfe) { // ignore .. } } } return computeStringValue(value); }
From source file:com.android.settings.localepicker.LocaleDragAndDropAdapter.java
public void updateLocalesWhenAnimationStops(final LocaleList localeList) { if (localeList.equals(mLocalesToSetNext)) { return;//from ww w.j a v a2s . c o m } // This will only update the Settings application to make things feel more responsive, // the system will be updated later, when animation stopped. LocaleList.setDefault(localeList); mLocalesToSetNext = localeList; final RecyclerView.ItemAnimator itemAnimator = mParentView.getItemAnimator(); itemAnimator.isRunning(new RecyclerView.ItemAnimator.ItemAnimatorFinishedListener() { @Override public void onAnimationsFinished() { if (mLocalesToSetNext == null || mLocalesToSetNext.equals(mLocalesSetLast)) { // All animations finished, but the locale list did not change return; } LocalePicker.updateLocales(mLocalesToSetNext); mLocalesSetLast = mLocalesToSetNext; mLocalesToSetNext = null; mNumberFormatter = NumberFormat.getNumberInstance(Locale.getDefault()); } }); }
From source file:com.mycompany.jpegrenamer.MetaDataReader.java
public Map<String, String> getExifMetadata(final File jpegImageFile) throws ImageReadException, IOException, ImageWriteException { Map<String, String> res = new HashMap<>(); Map<String, String> location = new HashMap(); ;//from w w w . j a v a2s . co m // note that metadata might be null if no metadata is found. final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile); boolean isClassOk = metadata instanceof JpegImageMetadata; if (!isClassOk || (null == metadata)) { return res; } final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (jpegMetadata == null) { logger.info("File does not contain metadata - " + jpegImageFile.getCanonicalPath()); return res; } String dateOfCaptureString = getTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME); SimpleDateFormat sdf = new SimpleDateFormat("''yyyy:MM:dd hh:mm:ss''"); Date dateOfCapture = null; try { dateOfCapture = sdf.parse(dateOfCaptureString); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss", Locale.ENGLISH); res.put("date", df.format(dateOfCapture)); } catch (ParseException ex) { logger.error("", ex); } // s = getTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME); printTagValue(jpegMetadata, TiffTagConstants.TIFF_TAG_DATE_TIME); printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL); printTagValue(jpegMetadata, ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED); printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF); printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE); printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF); printTagValue(jpegMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE); if (null != jpegMetadata) { // note that exif might be null if no Exif metadata is found. final TiffImageMetadata exif = jpegMetadata.getExif(); //logger.info(jpegMetadata.toString()); if (null != exif) { //logger.info(exif.toString()); final TiffImageMetadata.GPSInfo gpsInfo = exif.getGPS(); if (null != gpsInfo) { final String gpsDescription = gpsInfo.toString(); final double longitude = gpsInfo.getLongitudeAsDegreesEast(); final double latitude = gpsInfo.getLatitudeAsDegreesNorth(); logger.info(" " + "GPS Description: " + gpsDescription); logger.info(" " + "GPS Longitude (Degrees East): " + longitude); logger.info(" " + "GPS Latitude (Degrees North): " + latitude); try { Locale fmtLocale = Locale.US; NumberFormat formatter = NumberFormat.getNumberInstance(fmtLocale); formatter.setGroupingUsed(false); location = getAddressByGpsCoordinates(formatter.format(latitude), formatter.format(longitude)); if (location != null) { res.putAll(location); } } catch (MalformedURLException ex) { logger.error("", ex); } catch (org.json.simple.parser.ParseException ex) { logger.error("", ex); } logger.info(" " + location); } // more specific example of how to manually access GPS values final TiffField gpsLatitudeRefField = jpegMetadata .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF); final TiffField gpsLatitudeField = jpegMetadata .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LATITUDE); final TiffField gpsLongitudeRefField = jpegMetadata .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF); final TiffField gpsLongitudeField = jpegMetadata .findEXIFValueWithExactMatch(GpsTagConstants.GPS_TAG_GPS_LONGITUDE); if (gpsLatitudeRefField != null && gpsLatitudeField != null && gpsLongitudeRefField != null && gpsLongitudeField != null) { // all of these values are strings. final String gpsLatitudeRef = (String) gpsLatitudeRefField.getValue(); final RationalNumber[] gpsLatitude = (RationalNumber[]) (gpsLatitudeField.getValue()); final String gpsLongitudeRef = (String) gpsLongitudeRefField.getValue(); final RationalNumber[] gpsLongitude = (RationalNumber[]) gpsLongitudeField.getValue(); final RationalNumber gpsLatitudeDegrees = gpsLatitude[0]; final RationalNumber gpsLatitudeMinutes = gpsLatitude[1]; final RationalNumber gpsLatitudeSeconds = gpsLatitude[2]; final RationalNumber gpsLongitudeDegrees = gpsLongitude[0]; final RationalNumber gpsLongitudeMinutes = gpsLongitude[1]; final RationalNumber gpsLongitudeSeconds = gpsLongitude[2]; // This will format the gps info like so: // // gpsLatitude: 8 degrees, 40 minutes, 42.2 seconds S // gpsLongitude: 115 degrees, 26 minutes, 21.8 seconds E logger.info(" " + "GPS Latitude: " + gpsLatitudeDegrees.toDisplayString() + " degrees, " + gpsLatitudeMinutes.toDisplayString() + " minutes, " + gpsLatitudeSeconds.toDisplayString() + " seconds " + gpsLatitudeRef); logger.info(" " + "GPS Longitude: " + gpsLongitudeDegrees.toDisplayString() + " degrees, " + gpsLongitudeMinutes.toDisplayString() + " minutes, " + gpsLongitudeSeconds.toDisplayString() + " seconds " + gpsLongitudeRef); } logger.info(""); final List<ImageMetadata.ImageMetadataItem> items = jpegMetadata.getItems(); for (int i = 0; i < items.size(); i++) { final ImageMetadata.ImageMetadataItem item = items.get(i); // logger.info(" " + "item: " + item); } logger.info(""); } } return res; }
From source file:de.iteratec.iteraplan.presentation.tags.IteratecWriteTag.java
/** * Format value according to specified format string (as tag attribute or as string from message * resources) or to current user locale. * /* w w w.j a v a 2 s.com*/ * @param valueToFormat * value to process and convert to String * @exception JspException * if a JSP exception has occurred */ protected String formatValue(Object valueToFormat) throws JspException { Format format = null; Object value = valueToFormat; Locale locale = UserContext.getCurrentLocale(); boolean formatStrFromResources = false; String formatString = null; // Return String object as is. if (value instanceof String) { return (String) value; } else { // Prepare format object for numeric values. if (value instanceof Number) { if ((value instanceof Byte) || (value instanceof Short) || (value instanceof Integer) || (value instanceof Long) || (value instanceof BigInteger)) { formatString = MessageAccess.getStringOrNull(INT_FORMAT_KEY, locale); } else if ((value instanceof Float) || (value instanceof Double) || (value instanceof BigDecimal)) { formatString = MessageAccess.getStringOrNull(FLOAT_FORMAT_KEY, locale); } if (formatString != null) { formatStrFromResources = true; try { format = NumberFormat.getNumberInstance(locale); if (formatStrFromResources) { ((DecimalFormat) format).applyLocalizedPattern(formatString); } else { ((DecimalFormat) format).applyPattern(formatString); } } catch (IllegalArgumentException _e) { JspException e = new JspException("Wrong format string: " + formatString, _e); throw e; } } } else if (value instanceof Date) { formatString = MessageAccess.getStringOrNull(DATE_FORMAT_KEY, locale); if (formatString != null) { formatStrFromResources = true; if (formatStrFromResources) { format = new SimpleDateFormat(formatString, locale); } else { format = new SimpleDateFormat(formatString); // NOPMD this is the last fallback, so // locale-less is intended } } } } if (format != null) { return format.format(value); } else { return value.toString(); } }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.OverlaidStackedBarLine.java
public JFreeChart createChart(DatasetMap datasets) { // create the first renderer... CategoryPlot plot = new CategoryPlot(); NumberFormat nf = NumberFormat.getNumberInstance(locale); NumberAxis rangeAxis = new NumberAxis(getValueLabel()); rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis.setLabelPaint(styleXaxesLabels.getColor()); rangeAxis// w ww .j av a2 s .c o m .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor()); rangeAxis.setNumberFormatOverride(nf); plot.setRangeAxis(rangeAxis); if (rangeIntegerValues == true) { rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } CategoryAxis domainAxis = new CategoryAxis(getCategoryLabel()); 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()); plot.setDomainAxis(domainAxis); plot.setOrientation(PlotOrientation.VERTICAL); plot.setRangeGridlinesVisible(true); plot.setDomainGridlinesVisible(true); DefaultCategoryDataset datasetBar = (DefaultCategoryDataset) datasets.getDatasets().get("stackedbar"); //I create one bar renderer and one line MyStandardCategoryItemLabelGenerator generator = null; if (additionalLabels) { generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance()); } if (useBars) { CategoryItemRenderer barRenderer = new StackedBarRenderer(); if (maxBarWidth != null) { ((BarRenderer) barRenderer).setMaximumBarWidth(maxBarWidth.doubleValue()); } if (additionalLabels) { barRenderer.setBaseItemLabelGenerator(generator); double orient = (-Math.PI / 2.0); if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) { orient = 0.0; } barRenderer.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); barRenderer.setBaseItemLabelPaint(styleValueLabels.getColor()); barRenderer.setBaseItemLabelsVisible(true); barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); barRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); } if (colorMap != null) { for (Iterator iterator = datasetBar.getRowKeys().iterator(); iterator.hasNext();) { String serName = (String) iterator.next(); String labelName = ""; int index = -1; if (seriesCaptions != null && seriesCaptions.size() > 0) { labelName = serName; serName = (String) seriesCaptions.get(serName); index = datasetBar.getRowIndex(labelName); } else index = datasetBar.getRowIndex(serName); Color color = (Color) colorMap.get(serName); if (color != null) { barRenderer.setSeriesPaint(index, color); } } } // add tooltip if enabled if (enableToolTips) { MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips, seriesTooltip, categoriesTooltip, seriesCaptions); barRenderer.setToolTipGenerator(generatorToolTip); } //defines url for drill boolean document_composition = false; if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION)) document_composition = true; logger.debug("Calling Url Generation"); MyCategoryUrlGenerator mycatUrl = null; if (super.rootUrl != null) { logger.debug("Set MycatUrl"); mycatUrl = new MyCategoryUrlGenerator(super.rootUrl); mycatUrl.setDocument_composition(document_composition); mycatUrl.setCategoryUrlLabel(super.categoryUrlName); mycatUrl.setSerieUrlLabel(super.serieUrlname); mycatUrl.setDrillDocTitle(drillDocTitle); mycatUrl.setTarget(target); } if (mycatUrl != null) { barRenderer.setItemURLGenerator(mycatUrl); } plot.setDataset(1, datasetBar); plot.setRenderer(1, barRenderer); } if (useLines) { LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer(); //lineRenderer.setShapesFilled(false); lineRenderer.setShapesFilled(true); if (additionalLabels) { lineRenderer.setBaseItemLabelGenerator(generator); lineRenderer.setBaseItemLabelFont( new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize())); lineRenderer.setBaseItemLabelPaint(defaultLabelsStyle.getColor()); lineRenderer.setBaseItemLabelsVisible(true); } DefaultCategoryDataset datasetLine = (DefaultCategoryDataset) datasets.getDatasets().get("line"); if (enableToolTips) { MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips, seriesTooltip, categoriesTooltip, seriesCaptions); lineRenderer.setToolTipGenerator(generatorToolTip); } if (colorMap != null) { for (Iterator iterator = datasetLine.getRowKeys().iterator(); iterator.hasNext();) { String serName = (String) iterator.next(); String labelName = ""; int index = -1; if (seriesCaptions != null && seriesCaptions.size() > 0) { labelName = serName; serName = (String) seriesCaptions.get(serName); index = datasetLine.getRowIndex(labelName); } else index = datasetLine.getRowIndex(serName); Color color = (Color) colorMap.get(serName); if (color != null) { lineRenderer.setSeriesPaint(index, color); } } } plot.setDataset(0, datasetLine); plot.setRenderer(0, lineRenderer); } if (secondAxis) { NumberAxis na = new NumberAxis(secondAxisLabel); na.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); na.setLabelPaint(styleXaxesLabels.getColor()); na.setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); na.setTickLabelPaint(styleXaxesLabels.getColor()); na.setUpperMargin(0.10); if (rangeIntegerValues == true) { na.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } na.setNumberFormatOverride(nf); plot.setRangeAxis(1, na); plot.mapDatasetToRangeAxis(0, 1); } //plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45); JFreeChart chart = new JFreeChart(plot); TextTitle title = setStyleTitle(name, styleTitle); chart.setTitle(title); if (subName != null && !subName.equals("")) { TextTitle subTitle = setStyleTitle(subName, styleSubTitle); chart.addSubtitle(subTitle); } chart.setBackgroundPaint(Color.white); if (legend == true) drawLegend(chart); return chart; }
From source file:net.sourceforge.fenixedu.presentationTier.renderers.inquiries.InquiryGroupResultsResumeRenderer.java
private void renderColoredTable(int absoluteScaleSize, QuestionResultsSummaryBean questionResultsSummaryBean, HtmlTableRow row, HtmlTableCell medianCell, int medianClass) { HtmlText medianText = new HtmlText("<b>" + questionResultsSummaryBean.getMedian().getValue() + "</b>"); medianText.setEscaped(false);//w ww . ja v a2s . c om medianCell.setBody(medianText); medianCell.setClasses("x" + medianClass); int colClassesIter = absoluteScaleSize; for (InquiryResult inquiryResult : questionResultsSummaryBean.getAbsoluteScaleValues()) { HtmlTableCell absoluteValueCell = row.createCell(); absoluteValueCell.setBody(new HtmlText(inquiryResult.getValue())); absoluteValueCell.setClasses("x" + colClassesIter); colClassesIter--; } HtmlTableCell scaleCells = row.createCell(); final HtmlTable scaleTable = new HtmlTable(); scaleCells.setBody(scaleTable); HtmlTableRow scaleRow = scaleTable.createRow(); NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault()); numberFormat.setMaximumFractionDigits(2); String div = "<div class=\"graph-bar-1" + questionResultsSummaryBean.getScaleValues().size() + "-"; double scaleProportion = 100.0 / questionResultsSummaryBean.getScaleValues().size(); int iter = 1; int firstCell = 1; for (InquiryResult inquiryResult : questionResultsSummaryBean.getScaleValues()) { HtmlTableCell scaleCell = scaleRow.createCell(); Double value = Double.valueOf(inquiryResult.getValue()) * 100.0; int roundedValue = (int) StrictMath.round(value); String extraBarClass = ""; if (iter == firstCell) { if (roundedValue != 0) { extraBarClass = " first-bar"; } else { firstCell++; } } String finalDiv = div + iter + extraBarClass + "\">" + roundedValue + "%</div>"; if ((roundedValue / scaleProportion) <= proportionBar) { finalDiv = div + iter + extraBarClass + "\"></div>"; } HtmlText divText = new HtmlText(finalDiv); divText.setEscaped(false); scaleCell.setBody(divText); scaleCell.setStyle(roundedValue != 0 ? "width: " + roundedValue + "%;" : "display: none;"); iter++; } setLastBarCellClass(scaleRow); }
From source file:com.wellsandwhistles.android.redditsp.fragments.PostListingFragment.java
private void onSubredditReceived() { final String subtitle; if (mPostListingURL.getOrder() == null || mPostListingURL.getOrder() == PostSort.HOT) { if (mSubreddit.subscribers == null) { subtitle = getString(R.string.header_subscriber_count_unknown); } else {/* w w w . j a v a 2 s . c om*/ subtitle = getContext().getString(R.string.header_subscriber_count, NumberFormat.getNumberInstance(Locale.getDefault()).format(mSubreddit.subscribers)); } } else { subtitle = mPostListingURL.humanReadableUrl(); } getActivity().runOnUiThread(new Runnable() { @Override public void run() { setHeader(StringEscapeUtils.unescapeHtml4(mSubreddit.title), subtitle); getActivity().invalidateOptionsMenu(); } }); }