List of usage examples for java.text NumberFormat getNumberInstance
public static NumberFormat getNumberInstance(Locale inLocale)
From source file:org.jboss.dashboard.ui.taglib.formatter.Formatter.java
/** * Given an object it returns a string representation. */// ww w. j a va 2s. c o m public String formatObject(Object obj) { if (obj == null) return null; if (obj instanceof String) { return (String) obj; } if (obj instanceof Number) { if (numberFormat == null) numberFormat = NumberFormat.getNumberInstance(getLocale()); return numberFormat.format(obj); } if (obj instanceof Date) { if (dateTimeFormat == null) dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()); String dateStr = dateTimeFormat.format(obj); if (dateStr.indexOf("/") == 1) dateStr = "0" + dateStr; return dateStr; } return null; }
From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java
public NumberFormat getNumberFormat() { // FIXME generate format by user logged return NumberFormat.getNumberInstance(Constants.DEF_LOCALE_NUMBER); }
From source file:net.sf.jasperreports.functions.standard.TextFunctions.java
private DecimalFormat getDecimalFormat() { return (DecimalFormat) NumberFormat.getNumberInstance(getReportLocale()); }
From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java
public BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { if (clientApplicationLocale == null) { final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final String defaultMessage = new StringBuilder( "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.") .toString();//from w w w . j a v a 2 s . c om final ApiParameterError error = ApiParameterError .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } try { BigDecimal number = null; if (StringUtils.isNotBlank(numericalValueFormatted)) { String source = numericalValueFormatted.trim(); final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale); final DecimalFormat df = (DecimalFormat) format; final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); // http://bugs.sun.com/view_bug.do?bug_id=4510618 final char groupingSeparator = symbols.getGroupingSeparator(); if (groupingSeparator == '\u00a0') { source = source.replaceAll(" ", Character.toString('\u00a0')); } final NumberFormatter numberFormatter = new NumberFormatter(); final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue())); } return number; } catch (final ParseException e) { final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.invalid.decimal.format", "The parameter " + parameterName + " has value: " + numericalValueFormatted + " which is invalid decimal value for provided locale of [" + clientApplicationLocale.toString() + "].", parameterName, numericalValueFormatted, clientApplicationLocale); error.setValue(numericalValueFormatted); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } }
From source file:net.sf.jasperreports.chartthemes.spring.AegeanChartTheme.java
@Override protected JFreeChart createThermometerChart() throws JRException { JRThermometerPlot jrPlot = (JRThermometerPlot) getPlot(); // Create the plot that will hold the thermometer. ThermometerPlot chartPlot = new ThermometerPlot((ValueDataset) getDataset()); ChartUtil chartUtil = ChartUtil.getInstance(getChartContext().getJasperReportsContext()); // setting localized range axis formatters chartPlot.getRangeAxis().setStandardTickUnits(chartUtil.createIntegerTickUnits(getLocale())); // Build a chart around this plot JFreeChart jfreeChart = new JFreeChart(evaluateTextExpression(getChart().getTitleExpression()), null, chartPlot, getChart().getShowLegend() == null ? false : getChart().getShowLegend()); // Set the generic options configureChart(jfreeChart, getPlot()); jfreeChart.setBackgroundPaint(ChartThemesConstants.TRANSPARENT_PAINT); jfreeChart.setBorderVisible(false);/*from w w w .j a v a 2 s . c o m*/ Range range = convertRange(jrPlot.getDataRange()); if (range != null) { // Set the boundary of the thermomoter chartPlot.setLowerBound(range.getLowerBound()); chartPlot.setUpperBound(range.getUpperBound()); } chartPlot.setGap(0); // Units can only be Fahrenheit, Celsius or none, so turn off for now. chartPlot.setUnits(ThermometerPlot.UNITS_NONE); // Set the color of the mercury. Only used when the value is outside of // any defined ranges. @SuppressWarnings("unchecked") List<Paint> seriesPaints = (List<Paint>) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.SERIES_COLORS); Paint paint = jrPlot.getMercuryColor(); if (paint != null) { chartPlot.setUseSubrangePaint(false); } else { //it has no effect, but is kept for backward compatibility reasons paint = seriesPaints.get(0); } chartPlot.setMercuryPaint(paint); chartPlot.setThermometerPaint(THERMOMETER_COLOR); chartPlot.setThermometerStroke(new BasicStroke(2f)); chartPlot.setOutlineVisible(false); chartPlot.setValueFont(chartPlot.getValueFont().deriveFont(Font.BOLD)); // localizing the default format, can be overridden by display.getMask() chartPlot.setValueFormat(NumberFormat.getNumberInstance(getLocale())); // Set the formatting of the value display JRValueDisplay display = jrPlot.getValueDisplay(); if (display != null) { if (display.getColor() != null) { chartPlot.setValuePaint(display.getColor()); } if (display.getMask() != null) { chartPlot.setValueFormat( new DecimalFormat(display.getMask(), DecimalFormatSymbols.getInstance(getLocale()))); } if (display.getFont() != null) { // chartPlot.setValueFont(JRFontUtil.getAwtFont(display.getFont()).deriveFont(Font.BOLD)); } } // Set the location of where the value is displayed // Set the location of where the value is displayed ValueLocationEnum valueLocation = jrPlot.getValueLocationValue(); switch (valueLocation) { case NONE: chartPlot.setValueLocation(ThermometerPlot.NONE); break; case LEFT: chartPlot.setValueLocation(ThermometerPlot.LEFT); break; case RIGHT: chartPlot.setValueLocation(ThermometerPlot.RIGHT); break; case BULB: default: chartPlot.setValueLocation(ThermometerPlot.BULB); break; } // Define the three ranges range = convertRange(jrPlot.getLowRange()); if (range != null) { chartPlot.setSubrangeInfo(2, range.getLowerBound(), range.getUpperBound()); } range = convertRange(jrPlot.getMediumRange()); if (range != null) { chartPlot.setSubrangeInfo(1, range.getLowerBound(), range.getUpperBound()); } range = convertRange(jrPlot.getHighRange()); if (range != null) { chartPlot.setSubrangeInfo(0, range.getLowerBound(), range.getUpperBound()); } return jfreeChart; }
From source file:com.searchbox.collection.oppfin.TopicCollection.java
public ItemProcessor<JSONObject, FieldMap> callProcessor() { return new ItemProcessor<JSONObject, FieldMap>() { public FieldMap process(JSONObject callObject) throws IOException { /**//from w w w . j a v a2 s . com * Sample Call object { "CallIdentifier":{ * "FileName":"h2020-msca-itn-2014", * "CallId":"H2020-MSCA-ITN-2014", "Status":"OPEN" }, "Title": * "MARIE SKAODOWSKA-CURIE ACTION: INNOVATIVE TRAINING NETWORKS * (ITN)", "FrameworkProgramme":"H2020", * "SpecificProgrammeLevel1Names":["EU.1."], * "SpecificProgrammeLevel2Names":["EU.1.3."], * "SpecificProgrammeNames":["EU.1.3.1."], * "MainSpecificProgrammeLevel1Name":"EU.1.", * "MainSpecificProgrammeLevel1Description":"Excellent Science", * "SP_color":"EU_1", "PublicationDate":1386716400000, * "DeadlineDate":1397055600000, "CallDetails":{ * "AdditionalInfo":"", "LatestInfo":{ * "ApprovalDate":1391177582681, "Content": "The submission * session is now available for: * MSCA-ITN-2014-EID(MSCA-ITN-EID), * MSCA-ITN-2014-EJD(MSCA-ITN-EJD),MSCA-ITN-2014-ETN(MSCA-ITN-ETN)" * } }, "TotalIndicativeBudget":"405,180,000", "Theme":[], * "Type":"Fixed call", "Category":"CALL_FOR_PROPOSALS" } */ // Populating useful variables JSONObject callIdentifierObject = (JSONObject) callObject.get("CallIdentifier"); String callIdentifier = (String) callIdentifierObject.get("CallId"); String callFileName = (String) callIdentifierObject.get("FileName"); FieldMap doc = new FieldMap(); doc.put("callId", callIdentifier); doc.put("callFileName", callFileName); doc.put("callTitle", (String) callObject.get("Title")); doc.put("callDocType", "Call H2020"); doc.put("callProgramme", "H2020"); doc.put("callProgrammeDescription", (String) callObject.get("MainSpecificProgrammeLevel1Description")); //TODO: add debug String strDate = (String) callObject.get("PublicationDate"); if (strDate.matches("\\d*")) { strDate = df.format(new Date(Long.valueOf(strDate))); } else { SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy"); try { Date varDate = dateFormat.parse(strDate); strDate = df.format(varDate); } catch (Exception e) { LOGGER.error("ParseException : " + e.getLocalizedMessage()); } } // LOGGER.error("==============>PublicationDate : " + strDate); // LOGGER.info(callObject.toJSONString()); doc.put("callPublication", strDate); // We get the deadline from the topic. Do not push multiple (else cannot // sort) // doc.put("callDeadline", df.format(new Date((Long) // callObject.get("PublicationDate")))); doc.put("callFrameworkProgramme", (String) callObject.get("FrameworkProgramme")); doc.put("callType", (String) callObject.get("Type")); doc.put("callCategory", (String) callObject.get("Category")); // Indicative budget needs to be parsed using US locale // ("TotalIndicativeBudget":"405,180,000") if (callObject.get("TotalIndicativeBudget") != null) { try { Long num = (Long) NumberFormat.getNumberInstance(java.util.Locale.US) .parse((String) callObject.get("TotalIndicativeBudget")); doc.put("callTotalBudget", num); } catch (ParseException e) { LOGGER.error("ParseException : " + e.getLocalizedMessage()); } } // Using data from CallIdentifier object doc.put("callStatus", (String) callIdentifierObject.get("Status")); if (LOGGER.isDebugEnabled()) { for (String key : doc.keySet()) { LOGGER.debug("field: {}\t{}", key, doc.get(key)); } } return doc; } }; }
From source file:de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel.java
/** * Formats the given number using the wiki's locale. * /*from w w w .j a va2 s . c o m*/ * Note: Currently, the English locale is always used. * * @param rawNumber * whether the raw number should be returned * @param number * the number * * @return the formatted number */ public String formatStatisticNumber(boolean rawNumber, Number number) { if (rawNumber) { return number.toString(); } else { // TODO: use locale from Wiki NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); nf.setGroupingUsed(true); return nf.format(number); } }
From source file:com.nuvolect.deepdive.probe.DecompileApk.java
/** * Build a new DEX file excluding classes in the OPTIMIZED_CLASS_EXCLUSION file * @return// w ww. j a va2s . c o m */ private JSONObject optimizeDex() { final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LogUtil.log(LogUtil.LogType.DECOMPILE, "Uncaught exception: " + e.toString()); m_progressStream.putStream("Uncaught exception: " + t.getName()); m_progressStream.putStream("Uncaught exception: " + e.toString()); } }; m_optimize_dex_time = System.currentTimeMillis(); // Save start time for tracking m_optimizeDexThread = new Thread(m_threadGroup, new Runnable() { @Override public void run() { m_progressStream = new ProgressStream( new OmniFile(m_volumeId, m_appFolderPath + DEX_OPTIMIZATION_LOG_FILE)); m_progressStream .putStream("Optimizing classes, reference: " + OPTIMIZED_CLASSES_EXCLUSION_FILENAME); Scanner s = null; try { OmniFile omniFile = new OmniFile(m_volumeId, m_appFolderPath + OPTIMIZED_CLASSES_EXCLUSION_FILENAME); s = new Scanner(omniFile.getStdFile()); while (s.hasNext()) { String excludeClass = s.next(); ignoredLibs.add(excludeClass); m_progressStream.putStream("Exclude class: " + excludeClass); } } catch (Exception e) { LogUtil.logException(LogUtil.LogType.DECOMPILE, e); } if (s != null) s.close(); ArrayList<OmniFile> dexFiles = new ArrayList<>(); for (String fileName : m_dexFileNames) { OmniFile dexFile = new OmniFile(m_volumeId, m_appFolderPath + fileName + ".dex"); if (dexFile.exists() && dexFile.isFile()) { dexFiles.add(dexFile);// Keep track for summary List<ClassDef> classes = new ArrayList<>(); m_progressStream.putStream("Processing: " + fileName + ".dex"); org.jf.dexlib2.iface.DexFile memoryDexFile = null; try { memoryDexFile = DexFileFactory.loadDexFile(dexFile.getStdFile(), Opcodes.forApi(19)); } catch (Exception e) { m_progressStream.putStream("The app DEX file cannot be decompiled."); LogUtil.logException(LogUtil.LogType.DECOMPILE, e); continue; } int excludedClassCount = 0; Set<? extends ClassDef> origClassSet = memoryDexFile.getClasses(); memoryDexFile = null; // Release memory for (org.jf.dexlib2.iface.ClassDef classDef : origClassSet) { final String currentClass = classDef.getType(); if (isIgnored(currentClass)) { ++excludedClassCount; m_progressStream.putStream("Excluded class: " + currentClass); } else { m_progressStream.putStream("Included class: " + currentClass); classes.add(classDef); } } origClassSet = null; // Release memory m_progressStream.putStream("Excluded classes #" + excludedClassCount); m_progressStream.putStream("Included classes #" + classes.size()); m_progressStream.putStream("Rebuilding immutable dex: " + fileName + ".dex"); if (classes.size() > 0) { DexFile optDexFile = new ImmutableDexFile(Opcodes.forApi(19), classes); classes = null; // Release memory try { if (dexFile.delete()) m_progressStream.putStream("Fat DEX file delete success: " + dexFile.getName()); else m_progressStream.putStream("Fat DEX file delete FAILED: " + dexFile.getName()); DexPool.writeTo(dexFile.getStdFile().getAbsolutePath(), optDexFile); String size = NumberFormat.getNumberInstance(Locale.US).format(dexFile.length()); m_progressStream.putStream( "Optimized DEX file created: " + dexFile.getName() + ", size: " + size); } catch (IOException e) { m_progressStream.putStream("DEX IOException, write error: " + dexFile.getName()); LogUtil.logException(LogUtil.LogType.DECOMPILE, e); } catch (Exception e) { m_progressStream.putStream("DEX Exception, write error: " + dexFile.getName()); LogUtil.logException(LogUtil.LogType.DECOMPILE, e); } optDexFile = null; // release memory } else { m_progressStream .putStream("All classes excluded, DEX file not needed: " + dexFile.getName()); m_progressStream.putStream("Deleting: " + dexFile.getName()); dexFile.delete(); } } } for (OmniFile f : dexFiles) { if (f.exists()) { String formatted_count = String.format(Locale.US, "%,d", f.length()) + " bytes"; m_progressStream.putStream("DEX optimized: " + f.getName() + ": " + formatted_count); } else { m_progressStream.putStream("DEX deleted: " + f.getName() + ", all classes excluded"); } } dexFiles = new ArrayList<>();// Release memory m_progressStream .putStream("Optimize DEX complete: " + TimeUtil.deltaTimeHrMinSec(m_optimize_dex_time)); m_progressStream.close(); m_optimize_dex_time = 0; } }, UNZIP_APK_THREAD, STACK_SIZE); m_optimizeDexThread.setPriority(Thread.MAX_PRIORITY); m_optimizeDexThread.setUncaughtExceptionHandler(uncaughtExceptionHandler); m_optimizeDexThread.start(); return new JSONObject(); }
From source file:lineage2.gameserver.handler.admincommands.impl.AdminEditChar.java
/** * Method showCharacterList./*from w w w. jav a 2 s .c o m*/ * @param activeChar Player * @param player Player */ public static void showCharacterList(Player activeChar, Player player) { if (player == null) { GameObject target = activeChar.getTarget(); if ((target != null) && target.isPlayer()) { player = (Player) target; } else { return; } } else { activeChar.setTarget(player); } String clanName = "No Clan"; if (player.getClan() != null) { clanName = player.getClan().getName() + "/" + player.getClan().getLevel(); } NumberFormat df = NumberFormat.getNumberInstance(Locale.ENGLISH); df.setMaximumFractionDigits(4); df.setMinimumFractionDigits(1); NpcHtmlMessage adminReply = new NpcHtmlMessage(5); StringBuilder replyMSG = new StringBuilder("<html><body>"); replyMSG.append("<table width=260><tr>"); replyMSG.append( "<td width=40><button value=\"Main\" action=\"bypass -h admin_admin\" width=40 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append("<td width=180><center>Character Selection Menu</center></td>"); replyMSG.append( "<td width=40><button value=\"Back\" action=\"bypass -h admin_show_characters 0\" width=40 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append("</tr></table><br>"); replyMSG.append("<table width=270>"); replyMSG.append("<tr><td width=100>Account/IP:</td><td>" + player.getAccountName() + "/" + player.getIP() + "</td></tr>"); replyMSG.append("<tr><td width=100>Name/Level:</td><td>" + player.getName() + "/" + player.getLevel() + "</td></tr>"); replyMSG.append( "<tr><td width=100>Class/Id:</td><td>" + HtmlUtils.htmlClassName(player.getClassId().getId()) + "/" + player.getClassId().getId() + "</td></tr>"); replyMSG.append("<tr><td width=100>Clan/Level:</td><td>" + clanName + "</td></tr>"); replyMSG.append( "<tr><td width=100>Exp/Sp:</td><td>" + player.getExp() + "/" + player.getSp() + "</td></tr>"); replyMSG.append("<tr><td width=100>Cur/Max Hp:</td><td>" + (int) player.getCurrentHp() + "/" + player.getMaxHp() + "</td></tr>"); replyMSG.append("<tr><td width=100>Cur/Max Mp:</td><td>" + (int) player.getCurrentMp() + "/" + player.getMaxMp() + "</td></tr>"); replyMSG.append("<tr><td width=100>Cur/Max Load:</td><td>" + player.getCurrentLoad() + "/" + player.getMaxLoad() + "</td></tr>"); replyMSG.append("<tr><td width=100>Patk/Matk:</td><td>" + player.getPAtk(null) + "/" + player.getMAtk(null, null) + "</td></tr>"); replyMSG.append("<tr><td width=100>Pdef/Mdef:</td><td>" + player.getPDef(null) + "/" + player.getMDef(null, null) + "</td></tr>"); replyMSG.append("<tr><td width=100>PAtkSpd/MAtkSpd:</td><td>" + player.getPAtkSpd() + "/" + player.getMAtkSpd() + "</td></tr>"); replyMSG.append("<tr><td width=100>Acc/Evas:</td><td>" + player.getAccuracy() + "/" + player.getEvasionRate(null) + "</td></tr>"); replyMSG.append("<tr><td width=100>Crit/MCrit:</td><td>" + player.getCriticalHit(null, null) + "/" + df.format(player.getMagicCriticalRate(null, null)) + "%</td></tr>"); replyMSG.append("<tr><td width=100>CritDmg/MCritDmg:</td><td>" + player.getCriticalDmg(null, null) + "/" + player.getMagicCriticalDmg(null, null) + "</td></tr>"); replyMSG.append("<tr><td width=100>Walk/Run:</td><td>" + player.getWalkSpeed() + "/" + player.getRunSpeed() + "</td></tr>"); replyMSG.append("<tr><td width=100>Karma/Fame:</td><td>" + player.getKarma() + "/" + player.getFame() + "</td></tr>"); replyMSG.append("<tr><td width=100>PvP/PK:</td><td>" + player.getPvpKills() + "/" + player.getPkKills() + "</td></tr>"); replyMSG.append("<tr><td width=100>Coordinates:</td><td>" + player.getX() + "," + player.getY() + "," + player.getZ() + "</td></tr>"); replyMSG.append("<tr><td width=100>Direction:</td><td>" + PositionUtils.getDirectionTo(player, activeChar) + "</td></tr>"); replyMSG.append("</table><br>"); replyMSG.append("<table<tr>"); replyMSG.append( "<td><button value=\"Skills\" action=\"bypass -h admin_show_skills\" width=80 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append( "<td><button value=\"Effects\" action=\"bypass -h admin_show_effects\" width=80 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append( "<td><button value=\"Actions\" action=\"bypass -h admin_character_actions\" width=80 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append("</tr><tr>"); replyMSG.append( "<td><button value=\"Stats\" action=\"bypass -h admin_edit_character\" width=80 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append( "<td><button value=\"Exp & Sp\" action=\"bypass -h admin_add_exp_sp_to_character\" width=80 height=15 back=\"L2UI_CT1.Button_DF_Down\" fore=\"L2UI_CT1.Button_DF\"></td>"); replyMSG.append("<td></td>"); replyMSG.append("</tr></table></body></html>"); adminReply.setHtml(replyMSG.toString()); activeChar.sendPacket(adminReply); }