List of usage examples for java.text NumberFormat getNumberInstance
public static NumberFormat getNumberInstance(Locale inLocale)
From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java
/** * Checks if the value can safely be converted to a long primitive. * //from w w w. jav a 2 s. com * @param value * The value validation is being performed on. * @param locale * The locale to use to parse the number (system default if null) * @return the converted Long value. */ public static Long formatLong(String value, Locale locale) { Long result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) { result = Long.valueOf(num.longValue()); } } } return result; }
From source file:cross.io.xml.FragmentXMLSerializer.java
/** * @param name/*w w w . j a va 2 s. c om*/ * @param dims * @param data * @return */ private Array handleData(final String name, final Dimension[] dims, final Element data, final Range[] ranges) { EvalTools.notNull(dims, this); final String dec = new String(Base64.decode(data.getText(), Base64.GZIP)); final StreamTokenizer st = new StreamTokenizer(new StringReader(dec)); final NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); final int[] shape = new int[dims.length]; int d = 0; for (final Dimension dim : dims) { shape[d++] = dim.getLength(); } Array a = null; IndexIterator idx = null; int tok = -1; // log.info("DataType of array: {}", // dt.getPrimitiveClassType().getName()); Mode m = Mode.UNDEF; Object o = null; try { while ((tok = st.nextToken()) != StreamTokenizer.TT_EOL) { if (tok == StreamTokenizer.TT_WORD) { if (m == Mode.UNDEF) { try { o = nf.parse(st.sval); if (o instanceof Double) { m = Mode.DOUBLE; a = Array.factory(DataType.DOUBLE, shape); } else if (o instanceof Float) { m = Mode.FLOAT; a = Array.factory(DataType.FLOAT, shape); } else if (o instanceof Long) { m = Mode.LONG; a = Array.factory(DataType.LONG, shape); } else if (o instanceof Integer) { m = Mode.INTEGER; a = Array.factory(DataType.INT, shape); } else if (o instanceof Byte) { m = Mode.BYTE; a = Array.factory(DataType.BYTE, shape); } else if (o instanceof Short) { m = Mode.SHORT; a = Array.factory(DataType.SHORT, shape); } } catch (final ParseException pe) { if (st.sval.equalsIgnoreCase("true") || st.sval.equalsIgnoreCase("false")) { m = Mode.BOOLEAN; a = Array.factory(DataType.BOOLEAN, shape); } else { m = Mode.STRING; a = Array.factory(DataType.STRING, shape); } } } else { if (idx == null) { idx = a.getIndexIterator(); } switch (m) { case DOUBLE: { idx.setDoubleNext((Double) o); break; } case FLOAT: { idx.setFloatNext((Float) o); break; } case INTEGER: { idx.setIntNext((Integer) o); break; } case LONG: { idx.setLongNext((Long) o); break; } case BYTE: { idx.setByteNext((Byte) o); break; } case SHORT: { idx.setShortNext((Short) o); break; } case BOOLEAN: { idx.setBooleanNext(Boolean.parseBoolean(st.sval)); break; } case STRING: { idx.setObjectNext(st.sval); break; } case OBJECT: { throw new IllegalArgumentException("Could not handle type"); } } } } } } catch (final IOException e) { log.warn("Could not read data for {}", name); } if (a != null && ranges != null && ranges.length != 0) { try { return a.section(Arrays.asList(ranges)); } catch (InvalidRangeException ex) { log.warn("Invalid range while trying to subset array: ", ex); } } return a; }
From source file:richtercloud.document.scanner.gui.OCRPanel.java
/** * Creates new form OCRResultPanel// w ww . j a va 2 s. c o m * @param reflectionFormPanelMap A map with references to the * {@link ReflectionFormPanel} for each entity class which is manipulated by * the context menu items */ public OCRPanel(Set<Class<?>> entityClasses, Map<Class<?>, ReflectionFormPanel<?>> reflectionFormPanelMap, Map<Class<? extends JComponent>, ValueSetter<?, ?>> valueSetterMapping, EntityManager entityManager, MessageHandler messageHandler, ReflectionFormBuilder reflectionFormBuilder, DocumentScannerConf documentScannerConf) { this.initComponents(); if (messageHandler == null) { throw new IllegalArgumentException("messageHandler mustn't be null"); } this.messageHandler = messageHandler; if (documentScannerConf == null) { throw new IllegalArgumentException("documentScannerConf mustn't be " + "null"); } this.documentScannerConf = documentScannerConf; List<Class<?>> entityClassesSort = EntityPanel.sortEntityClasses(entityClasses); for (Class<?> entityClass : entityClassesSort) { ReflectionFormPanel<?> reflectionFormPanel = reflectionFormPanelMap.get(entityClass); if (reflectionFormPanel == null) { throw new IllegalArgumentException( String.format("entityClass %s has no %s mapped in reflectionFormPanelMap", entityClass, ReflectionFormPanel.class)); } String className; ClassInfo classInfo = entityClass.getAnnotation(ClassInfo.class); if (classInfo != null) { className = classInfo.name(); } else { className = entityClass.getSimpleName(); } JMenu entityClassMenu = new JMenu(className); List<Field> relevantFields = reflectionFormBuilder.getFieldRetriever() .retrieveRelevantFields(entityClass); for (Field relevantField : relevantFields) { String fieldName; FieldInfo fieldInfo = relevantField.getAnnotation(FieldInfo.class); if (fieldInfo != null) { fieldName = fieldInfo.name(); } else { fieldName = relevantField.getName(); } JMenuItem relevantFieldMenuItem = new JMenuItem(fieldName); relevantFieldMenuItem.addActionListener( new FieldActionListener(reflectionFormPanel, relevantField, valueSetterMapping)); entityClassMenu.add(relevantFieldMenuItem); } this.oCRResultPopupPasteIntoMenu.add(entityClassMenu); } Map<String, Pair<NumberFormat, Set<Locale>>> numberFormats = new HashMap<>(); Map<String, Pair<NumberFormat, Set<Locale>>> percentFormats = new HashMap<>(); Map<String, Pair<NumberFormat, Set<Locale>>> currencyFormats = new HashMap<>(); Iterator<Locale> localeIterator = new ArrayList<>(Arrays.asList(Locale.getAvailableLocales())).iterator(); Locale firstLocale = localeIterator.next(); String numberString = NumberFormat.getNumberInstance(firstLocale).format(FORMAT_VALUE); String percentString = NumberFormat.getPercentInstance(firstLocale).format(FORMAT_VALUE); String currencyString = NumberFormat.getCurrencyInstance(firstLocale).format(FORMAT_VALUE); numberFormats.put(numberString, new ImmutablePair<NumberFormat, Set<Locale>>( NumberFormat.getNumberInstance(firstLocale), new HashSet<>(Arrays.asList(firstLocale)))); percentFormats.put(percentString, new ImmutablePair<NumberFormat, Set<Locale>>( NumberFormat.getPercentInstance(firstLocale), new HashSet<>(Arrays.asList(firstLocale)))); currencyFormats.put(currencyString, new ImmutablePair<NumberFormat, Set<Locale>>( NumberFormat.getCurrencyInstance(firstLocale), new HashSet<>(Arrays.asList(firstLocale)))); while (localeIterator.hasNext()) { Locale locale = localeIterator.next(); numberString = NumberFormat.getNumberInstance(locale).format(FORMAT_VALUE); percentString = NumberFormat.getPercentInstance(locale).format(FORMAT_VALUE); currencyString = NumberFormat.getCurrencyInstance(locale).format(FORMAT_VALUE); Pair<NumberFormat, Set<Locale>> numberFormatsPair = numberFormats.get(numberString); if (numberFormatsPair == null) { numberFormatsPair = new ImmutablePair<NumberFormat, Set<Locale>>( NumberFormat.getNumberInstance(locale), new HashSet<Locale>()); numberFormats.put(numberString, numberFormatsPair); } Set<Locale> numberFormatsLocales = numberFormatsPair.getValue(); numberFormatsLocales.add(locale); Pair<NumberFormat, Set<Locale>> percentFormatsPair = percentFormats.get(percentString); if (percentFormatsPair == null) { percentFormatsPair = new ImmutablePair<NumberFormat, Set<Locale>>( NumberFormat.getPercentInstance(locale), new HashSet<Locale>()); percentFormats.put(percentString, percentFormatsPair); } Set<Locale> percentFormatsLocales = percentFormatsPair.getValue(); percentFormatsLocales.add(locale); Pair<NumberFormat, Set<Locale>> currencyFormatsPair = currencyFormats.get(currencyString); if (currencyFormatsPair == null) { currencyFormatsPair = new ImmutablePair<NumberFormat, Set<Locale>>( NumberFormat.getCurrencyInstance(locale), new HashSet<Locale>()); currencyFormats.put(currencyString, currencyFormatsPair); } Set<Locale> currencyFormatsLocales = currencyFormatsPair.getValue(); currencyFormatsLocales.add(locale); } for (Map.Entry<String, Pair<NumberFormat, Set<Locale>>> numberFormat : numberFormats.entrySet()) { JRadioButtonMenuItem menuItem = new NumberFormatMenuItem(numberFormat.getValue().getKey()); numberFormatPopup.add(menuItem); numberFormatPopupButtonGroup.add(menuItem); if (numberFormat.getValue().getValue().contains(this.documentScannerConf.getLocale())) { menuItem.setSelected(true); } } for (Map.Entry<String, Pair<NumberFormat, Set<Locale>>> percentFormat : percentFormats.entrySet()) { JRadioButtonMenuItem menuItem = new NumberFormatMenuItem(percentFormat.getValue().getKey()); percentFormatPopup.add(menuItem); percentFormatPopupButtonGroup.add(menuItem); if (percentFormat.getValue().getValue().contains(this.documentScannerConf.getLocale())) { menuItem.setSelected(true); } } for (Map.Entry<String, Pair<NumberFormat, Set<Locale>>> currencyFormat : currencyFormats.entrySet()) { JRadioButtonMenuItem menuItem = new NumberFormatMenuItem(currencyFormat.getValue().getKey()); currencyFormatPopup.add(menuItem); currencyFormatPopupButtonGroup.add(menuItem); if (currencyFormat.getValue().getValue().contains(this.documentScannerConf.getLocale())) { menuItem.setSelected(true); } } }
From source file:eu.planets_project.pp.plato.massmigration.MassMigrationRunner.java
public void run() { sourceDir = new File(setup.getSourcePath()); resultDir = new File(setup.getResultPath()); if (!sourceDir.exists() || !sourceDir.isDirectory() || !sourceDir.canRead()) { setup.getStatus().setStatus(MassMigrationStatus.FAILED); throw new IllegalArgumentException("Cannot read from source directory: " + setup.getSourcePath()); }/*from w ww. j a v a2 s .co m*/ File currentResultdir = new File(resultDir, setup.getName() + "-" + System.nanoTime()); setup.setLastResultPath(currentResultdir.getAbsolutePath()); if (!currentResultdir.mkdirs()) { setup.getStatus().setStatus(MassMigrationStatus.FAILED); throw new IllegalArgumentException("Cannot write to result directory: " + setup.getSourcePath()); } try { File[] list = sourceDir.listFiles(new FileDirectoryFilter()); List<String> array = new ArrayList<String>(); for (int i = 0; i < list.length; i++) { array.add(list[i].getName()); } inputFiles = array.toArray(new String[] {}); java.util.Arrays.sort(inputFiles, String.CASE_INSENSITIVE_ORDER); Map<String, String> alternativesPaths = new HashMap<String, String>(); // create directories for each alternative for (MassMigrationExperiment exp : setup.getExperiments()) { String altPath = FileUtils.makeFilename(makeUniqueActionName(exp.getAction())); File dir = new File(currentResultdir, altPath); if (dir.mkdir()) { // add this path only if it can be created alternativesPaths.put(exp.getAction().getShortname(), dir.getAbsolutePath()); } } setup.getStatus().setNumOfSamples(inputFiles.length); setup.getStatus().setNumOfTools(setup.getExperiments().size()); int current = 0; for (String filename : inputFiles) { File file = new File(sourceDir + File.separator + filename); current++; int currentTool = 0; setup.getStatus().setCurrentSample(current); try { byte[] data = FileUtils.getBytesFromFile(file); /* * migrate this file with every migration service, so we have to load it only once */ for (MassMigrationExperiment exp : setup.getExperiments()) { currentTool++; setup.getStatus().setCurrentTool(currentTool); MigrationResult result = runExperiment(exp, file.getName(), data); if ((result != null) && (result.isSuccessful())) { // store migration result String altPath = alternativesPaths.get(exp.getAction().getShortname()); if (altPath != null) { File mResult = new File(altPath, file.getName() + "." + result.getTargetFormat().getDefaultExtension()); OutputStream out = new BufferedOutputStream(new FileOutputStream(mResult)); out.write(result.getMigratedObject().getData().getData()); out.close(); } } } } catch (IOException ioe) { log.error("Could not load file: " + file.getAbsolutePath(), ioe); } catch (Exception e) { log.error( "Exception while running experiment on file " + file.getAbsolutePath() + e.getMessage(), e); } } /* * Calculation finished - collect result values and export them for further calculations */ Locale locale = Locale.getDefault(); NumberFormat format = NumberFormat.getNumberInstance(locale); //new DecimalFormat("##########.##"); ToolExperience toolExp = null; List<String> allProperties = new ArrayList<String>(); Map<String, DetailedExperimentInfo> accumulatedAvg = new HashMap<String, DetailedExperimentInfo>(); for (MassMigrationExperiment e : setup.getExperiments()) { /* calculate average per experiment */ /* put measurements of sample files to toolExp */ toolExp = MeasurementStatistics.generateToolExperience(e.getResult()); /* get calculated average per property */ DetailedExperimentInfo average = MeasurementStatistics.getAverage(toolExp); accumulatedAvg.put(e.getAction().getShortname(), average); e.getAverages().clear(); e.getAverages().put(average); /* a list of all properties to iterate over the values */ allProperties.clear(); allProperties.addAll(toolExp.getMeasurements().keySet()); Collections.sort(allProperties); /* * write all measurements of this experiment to a file */ String statistics = FileUtils.makeFilename(makeUniqueActionName(e.getAction())); File statisticsFile = new File(currentResultdir, statistics + ".csv"); try { BufferedWriter out = new BufferedWriter(new FileWriter(statisticsFile)); StringBuffer header = new StringBuffer(); header.append("sample"); for (String key : allProperties) { header.append(CSV_SEPARATOR).append(key); } /* write header */ out.append(header); out.newLine(); List<String> keySet = new ArrayList<String>(e.getResult().keySet()); String[] toSort = keySet.toArray(new String[] {}); java.util.Arrays.sort(toSort, String.CASE_INSENSITIVE_ORDER); /* write measured values for all samples */ for (int i = 0; i < toSort.length; i++) { String sample = toSort[i]; /* 1. column: sample name */ out.append(sample); /* followed by all properties */ DetailedExperimentInfo info = e.getResult().get(sample); for (String prop : allProperties) { out.append(CSV_SEPARATOR); Measurement m = info.getMeasurements().get(prop); if (m != null) { if (m.getValue() instanceof INumericValue) { /* */ double value = ((INumericValue) m.getValue()).value(); out.append(format.format(value)); } else out.append(m.getValue().toString()); } } out.newLine(); } /* write header again */ out.append(header); out.newLine(); /* and write calculated average */ out.append("average"); for (String key : allProperties) { out.append(CSV_SEPARATOR); Measurement m = e.getAverages().getMeasurements().get(key); if (m != null) { if (m.getValue() instanceof INumericValue) { double value = ((INumericValue) m.getValue()).value(); out.append(format.format(value)); } else out.append(m.getValue().toString()); } } out.newLine(); out.append("startupTime"); out.append(CSV_SEPARATOR); try { out.append(Double.toString(toolExp.getStartupTime())); } catch (Exception ex) { log.error("Error in calculating the startup time (linear regression): " + ex.getMessage()); out.append("Err"); } out.newLine(); out.close(); } catch (IOException e1) { log.error("Could not write statistics for: " + statistics, e1); } } /* * and write accumulated values */ File statisticsFile = new File(currentResultdir, "accumulated.csv"); allProperties.clear(); allProperties.add(MigrationResult.MIGRES_ELAPSED_TIME_PER_MB); allProperties.add(MigrationResult.MIGRES_USED_TIME_PER_MB); allProperties.add(MigrationResult.MIGRES_ELAPSED_TIME); allProperties.add(MigrationResult.MIGRES_USED_TIME); //... try { BufferedWriter out = new BufferedWriter(new FileWriter(statisticsFile)); /* write machine info */ if (toolExp != null) { // use machine info of last experiment! for (String prop : toolExp.getMeasurements().keySet()) { if (prop.startsWith("machine:")) { out.append(prop).append(CSV_SEPARATOR).append(toolExp.getMeasurements().get(prop) .getList().get(0).getValue().getFormattedValue()); out.newLine(); } } out.newLine(); } /* write header */ out.append("tool"); for (String key : allProperties) { out.append(CSV_SEPARATOR).append(key); } out.newLine(); /* write averaged values for all actions */ for (String action : accumulatedAvg.keySet()) { /* 1. column: action name */ out.append(action); /* followed by all properties */ DetailedExperimentInfo average = accumulatedAvg.get(action); for (String prop : allProperties) { out.append(CSV_SEPARATOR); Measurement m = average.getMeasurements().get(prop); if (m != null) { if (m.getValue() instanceof INumericValue) { /* */ double value = ((INumericValue) m.getValue()).value(); out.append(format.format(value)); } else out.append(m.getValue().toString()); } } out.newLine(); } out.newLine(); out.close(); } catch (IOException e1) { log.error("Could not write accumulated statistics.", e1); } setup.getStatus().setStatus(MassMigrationStatus.FINISHED); } catch (RuntimeException e) { setup.getStatus().setStatus(MassMigrationStatus.FAILED); log.error("Massmigration failed.", e); } }
From source file:it.AsynchronousIssueRestClientTest.java
@Test public void testTransitionWithNumericCustomFieldPolishLocale() throws Exception { final double newValue = 123.45; final FieldInput fieldInput; if (IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER) { fieldInput = new FieldInput(NUMERIC_CUSTOMFIELD_ID, newValue); } else {/*from ww w. ja v a 2 s .c o m*/ fieldInput = new FieldInput(NUMERIC_CUSTOMFIELD_ID, NumberFormat.getNumberInstance(new Locale("pl")).format(newValue)); } assertTransitionWithNumericCustomField(fieldInput, newValue); }
From source file:org.apache.cocoon.template.instruction.FormatNumber.java
private NumberFormat createFormatter(Locale loc, String type) throws Exception { NumberFormat formatter = null; if ((type == null) || NUMBER.equalsIgnoreCase(type)) { formatter = NumberFormat.getNumberInstance(loc); } else if (CURRENCY.equalsIgnoreCase(type)) { formatter = NumberFormat.getCurrencyInstance(loc); } else if (PERCENT.equalsIgnoreCase(type)) { formatter = NumberFormat.getPercentInstance(loc); } else {// w ww.j av a 2 s . co m throw new IllegalArgumentException( "Invalid type: \"" + type + "\": should be \"number\" or \"currency\" or \"percent\""); } return formatter; }
From source file:com.amagi82.kerbalspaceapp.MissionPlanner.java
private void refreshDeltaV() { totalDeltaV = 0;/*from w ww . ja v a2 s .c o m*/ for (int i = 0; i < missionData.size(); i++) { int takeoffDeltaV = 0, transferDeltaV = 0, landingDeltaV = 0; if (missionData.get(i).getIconStatus() == 3) { takeoffDeltaV = OrbitalMechanics.getToOrbit(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(), missionData.get(i).getOrbitAltitude()); } if (missionData.get(i).getLanding()) { landingDeltaV = OrbitalMechanics.getLandingDeltaV(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(), missionData.get(i).getOrbitAltitude()); } if (missionData.get(i).getToOrbit() && missionData.get(i).getLanding()) { takeoffDeltaV = OrbitalMechanics.getToOrbit(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(), missionData.get(i).getOrbitAltitude()); } if (i != 0) { transferDeltaV = OrbitalMechanics.getTransferDeltaV(missionData.get(i - 1).getPlanetId(), missionData.get(i).getPlanetId(), missionData.get(i - 1).getOrbitAltitude(), missionData.get(i).getOrbitAltitude()); } totalDeltaV = totalDeltaV + takeoffDeltaV + transferDeltaV + landingDeltaV; } String value = NumberFormat.getNumberInstance(Locale.getDefault()).format(totalDeltaV); tvTotalDeltaV.setText(value + " m/s"); }
From source file:it.AsynchronousIssueRestClientTest.java
@Test public void testTransitionWithNumericCustomFieldEnglishLocale() throws Exception { setUser1();/*from www . j a v a2s .c om*/ final double newValue = 123.45; final FieldInput fieldInput = new FieldInput(NUMERIC_CUSTOMFIELD_ID, NumberFormat.getNumberInstance(new Locale("pl")).format(newValue)); assertErrorCode(Response.Status.BAD_REQUEST, IntegrationTestUtil.TESTING_JIRA_5_OR_NEWER ? "Operation value must be a number" : ("'" + fieldInput.getValue() + "' is an invalid number"), new Runnable() { @Override public void run() { assertTransitionWithNumericCustomField(fieldInput, newValue); } }); final FieldInput fieldInput2 = new FieldInput(NUMERIC_CUSTOMFIELD_ID, newValue); // this will be serialized always with "." according to JSL assertTransitionWithNumericCustomField(fieldInput2, newValue); }
From source file:gr.abiss.calipso.wicket.components.formfields.FieldSummaryHelper.java
public Object parse(String value, Locale locale) { Object o = null;/*from ww w . ja v a2 s . c o m*/ if (StringUtils.isNotEmpty(type)) { try { if (type.equalsIgnoreCase(TYPE_INTEGER) || type.equalsIgnoreCase(TYPE_DECIMAL)) { o = NumberFormat.getNumberInstance(locale).parseObject(value); } if (type.equalsIgnoreCase(TYPE_DATE)) { o = this.format.parseObject(value); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (o == null) { o = value; } //logger.info("parse "+value +" returns " +o +" ("+o.getClass()+") with locale "+locale+" for type: "+type+" and label: "+this.label); return o; }
From source file:DecimalFormatDemo.java
/** Reformats the input number and displays result. */ public void reformat() { try {// w w w . ja v a2 s . c om NumberFormat nf = NumberFormat.getNumberInstance(availableLocales.getCurrent()); DecimalFormat df = (DecimalFormat) nf; df.applyPattern(currentPattern); result.setForeground(Color.black); result.setText(df.format(currentNumber)); } catch (IllegalArgumentException iae) { result.setForeground(Color.red); result.setText("Illegal Pattern: " + iae.getMessage()); } }