List of usage examples for java.text NumberFormat parse
public Number parse(String source) throws ParseException
From source file:op.tools.SYSTools.java
public static BigDecimal parseDecimal(String test) { NumberFormat nf = DecimalFormat.getNumberInstance(); test = assimilateDecimalSeparators(test); Number num;/* www . jav a 2 s .c o m*/ try { num = nf.parse(test); } catch (Exception ex) { num = null; } BigDecimal wert = null; if (num != null) { if (num instanceof Long) { wert = new BigDecimal(num.longValue()); } else if (num instanceof Double) { wert = new BigDecimal(num.doubleValue()); } else if (num instanceof BigDecimal) { wert = (BigDecimal) num; } else { wert = null; } } return wert; }
From source file:op.tools.SYSTools.java
public static BigDecimal parseCurrency(String test) { NumberFormat nf = DecimalFormat.getCurrencyInstance(); test = assimilateDecimalSeparators(test); Number num;//w w w .ja va 2 s .c o m try { num = nf.parse(test); } catch (ParseException ex) { try { String test1 = test + " " + SYSConst.eurosymbol; num = nf.parse(test1); } catch (ParseException ex1) { num = null; } } BigDecimal betrag = null; if (num != null) { if (num instanceof Long) { betrag = new BigDecimal(num.longValue()); } else if (num instanceof Double) { betrag = new BigDecimal(num.doubleValue()); } else if (num instanceof BigDecimal) { betrag = (BigDecimal) num; } else { betrag = null; } } return betrag; }
From source file:org.openmicroscopy.shoola.agents.measurement.view.ObjectInspector.java
/** * Safe method to parse text into double value * //from w w w .j a va 2s.com * @param text * The text to convert to double * @return The parsed double value or 1 if input is invalid or < 1 */ private double parseDouble(String text) { double result = 1; NumberFormat nf = NumberFormat.getInstance(); if (StringUtils.isNotBlank(text)) { try { result = nf.parse(text).doubleValue(); } catch (ParseException e) { } if (result < 1) { result = 1; } } return result; }
From source file:org.polymap.p4.data.importer.refine.csv.CSVFileImporter.java
@Override protected synchronized TypedContent typedContent() { if (csvTypedContent == null) { List<TypedColumn> columnsWithType = Lists.newArrayList(); for (Column column : originalColumns()) { columnsWithType.add(new TypedColumn(column.getName())); }// w w w .j a v a 2s. c o m // in CSV all cells are strings only, so type guess its value // String is the default in all cases List<RefineRow> rows = Lists.newArrayList(); for (Row originalRow : originalRows()) { int i = 0; RefineRow row = new RefineRow(); rows.add(row); for (Cell cell : originalRow.cells) { TypedColumn column = columnsWithType.get(i); if (cell == null || cell.value == null || cell.value.toString().trim().equals("") || (column.type() != null && column.type().isAssignableFrom(String.class))) { // seems to be empty or a string was found in the same column // earlier row.add(new RefineCell(cell)); } else { // guess the type, fallback in any error case is String // log.info( "guessing " + cell.value.toString() ); GuessedType guessedType = TypeGuesser.guess(cell.value.toString()); if (guessedType.type().equals(Type.Decimal)) { try { // convert to number NumberFormat formatter = DecimalFormat .getInstance(guessedType.locale() != null ? guessedType.locale() : Polymap.getSessionLocale()); Object guessedValue = formatter.parse(cell.value.toString().trim()); if (column.type() == null || !column.type().isAssignableFrom(Double.class)) { // dont overwrite a double, with a long column.setType(guessedValue.getClass()); } column.addLocale(guessedType.locale()); row.add(new RefineCell(cell, guessedValue)); } catch (ParseException e) { // default to string column.setType(String.class); row.add(new RefineCell(cell)); throw new RuntimeException(e); } } else { // defaults to string log.info("Setting string in column " + column.name() + " because of '" + cell.value.toString() + "'"); column.setType(String.class); row.add(new RefineCell(cell)); } } i++; } } columnsWithType.stream().filter(c -> c.type() == null).forEach(c -> c.setType(String.class)); csvTypedContent = new TypedContent(columnsWithType, rows); } return csvTypedContent; }
From source file:org.apache.ambari.server.serveraction.kerberos.MITKerberosOperationHandler.java
/** * Retrieves the current key number assigned to the identity identified by the specified principal * * @param principal a String declaring the principal to look up * @return an Integer declaring the current key number * @throws KerberosKDCConnectionException if a connection to the KDC cannot be made * @throws KerberosAdminAuthenticationException if the administrator credentials fail to authenticate * @throws KerberosRealmException if the realm does not map to a KDC * @throws KerberosOperationException if an unexpected error occurred */// ww w . ja va 2 s .c o m private Integer getKeyNumber(String principal) throws KerberosOperationException { if (!isOpen()) { throw new KerberosOperationException("This operation handler has not been opened"); } if (StringUtils.isEmpty(principal)) { throw new KerberosOperationException( "Failed to get key number for principal - no principal specified"); } else { // Create the kdamin query: get_principal <principal> ShellCommandUtil.Result result = invokeKAdmin(String.format("get_principal %s", principal)); String stdOut = result.getStdout(); if (stdOut == null) { String message = String.format( "Failed to get key number for %s:\n\tExitCode: %s\n\tSTDOUT: NULL\n\tSTDERR: %s", principal, result.getExitCode(), result.getStderr()); LOG.warn(message); throw new KerberosOperationException(message); } Matcher matcher = PATTERN_GET_KEY_NUMBER.matcher(stdOut); if (matcher.matches()) { NumberFormat numberFormat = NumberFormat.getIntegerInstance(); String keyNumber = matcher.group(1); numberFormat.setGroupingUsed(false); try { Number number = numberFormat.parse(keyNumber); return (number == null) ? 0 : number.intValue(); } catch (ParseException e) { String message = String.format( "Failed to get key number for %s - invalid key number value (%s):\n\tExitCode: %s\n\tSTDOUT: NULL\n\tSTDERR: %s", principal, keyNumber, result.getExitCode(), result.getStderr()); LOG.warn(message); throw new KerberosOperationException(message); } } else { String message = String.format( "Failed to get key number for %s - unexpected STDOUT data:\n\tExitCode: %s\n\tSTDOUT: NULL\n\tSTDERR: %s", principal, result.getExitCode(), result.getStderr()); LOG.warn(message); throw new KerberosOperationException(message); } } }
From source file:com.mgmtp.perfload.perfalyzer.util.PerfAlyzerUtils.java
/** * Reads a semicolon-delimited CSV file into a map of lists series values. Values for each * column are return as list of lists in the map, the key being the column header. * //from w ww .java 2 s . c o m * @param file * the file * @param charset * the character set to read the file * @param numberFormat * the number format for formatting the column values * @param columnNames * the columns to consider * * @return an immutable map of lists of series values */ public static Map<String, List<SeriesPoint>> readDataFile(final File file, final Charset charset, final NumberFormat numberFormat, final Set<String> columnNames) throws IOException { final StrTokenizer tokenizer = StrTokenizer.getCSVInstance(); tokenizer.setDelimiterChar(';'); return readLines(file, charset, new LineProcessor<Map<String, List<SeriesPoint>>>() { private String[] headers; private final Map<String, List<SeriesPoint>> result = newHashMapWithExpectedSize(4); private int colCount; @Override public boolean processLine(final String line) throws IOException { try { tokenizer.reset(line); String[] tokens = tokenizer.getTokenArray(); if (headers == null) { headers = tokens; colCount = tokens.length; } else { Integer counter = Integer.valueOf(tokens[0]); for (int i = 1; i < colCount; ++i) { String header = headers[i]; if (columnNames.contains(header)) { List<SeriesPoint> colValues = result.get(header); if (colValues == null) { colValues = newArrayListWithExpectedSize(50); result.put(header, colValues); } colValues.add(new SeriesPoint(counter, numberFormat.parse(tokens[i]))); } } } return true; } catch (ParseException ex) { throw new IOException("Error parsing number in file: " + file, ex); } } @Override public Map<String, List<SeriesPoint>> getResult() { return ImmutableMap.copyOf(result); } }); }
From source file:org.marketcetera.marketdata.yahoo.YahooFeedEventTranslator.java
/** * Gets the Quote data (price, size). Checks if the quote data is from a new * response / subsequent response by checking the cache for the particular event (bid / ask). * Returns the QuoteDataAction (quote details and the new action to perform for the response). * * @param inSymbol a <code>String</code> value * @param inPrice a <code>String</code> value * @param inSize a <code>String</code> value * @param quoteDataEventMap a <code>Map<String,QuoteData></code> value * @param handle a <code>String</code> value * @return a <code>QuoteDataAction</code> value *///ww w . j a v a 2s . co m private QuoteDataAction getQuoteDataAction(String inSymbol, String inPrice, String inSize, Map<String, QuoteData> quoteDataEventMap, String handle) { BigDecimal price; BigDecimal size; NumberFormat numberFormat = SHARED_NUMBER_FORMAT.get(); boolean parsedState = true; QuoteAction action = null; try { Number number = numberFormat.parse(inPrice); price = BigDecimal.valueOf(number.doubleValue()); } catch (ParseException e) { price = BigDecimal.valueOf(0); parsedState = false; } try { Number number = numberFormat.parse(inSize); size = BigDecimal.valueOf(number.doubleValue()); } catch (ParseException e) { size = BigDecimal.valueOf(0); parsedState = false; } QuoteData currentQuoteData = new QuoteData(price, size, inSymbol); QuoteDataAction quoteDataAction = new QuoteDataAction(currentQuoteData); QuoteData cachedData = quoteDataEventMap.get(handle); if (cachedData == null) { if (parsedState) { action = QuoteAction.ADD; quoteDataEventMap.put(handle, currentQuoteData); } else { //need to check whether to send delete action for the first request. action = QuoteAction.DELETE; quoteDataEventMap.put(handle, null); } } else if (QUOTE_DATA_COMPARATOR.compare(currentQuoteData, cachedData) != 0) { if (parsedState) { action = QuoteAction.CHANGE; quoteDataEventMap.put(handle, currentQuoteData); } else { action = QuoteAction.DELETE; quoteDataEventMap.put(handle, null); } } quoteDataAction.setQuoteAction(action); return quoteDataAction; }
From source file:com.glaf.dts.transform.MxTransformThread.java
@SuppressWarnings("unchecked") public void run() { logger.debug(taskId + "----------------execution-----------------"); TransformTask task = transformTaskService.getTransformTask(taskId); if (task != null) { if (task.getStatus() == 9 || task.getRetryTimes() > 3) { return; }// w w w. j av a2 s .c o m task.setStartTime(new java.util.Date()); task.setRetryTimes(task.getRetryTimes() + 1); task.setStatus(1); transformTaskService.save(task); } List<TableModel> resultList = new java.util.ArrayList<TableModel>(); Map<String, Object> singleDataMap = new HashMap<String, Object>(); Connection conn = null; PreparedStatement psmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; boolean success = true; long start = System.currentTimeMillis(); logger.debug("start:" + DateUtils.getDateTime(new java.util.Date())); try { Database database = getDatabaseService().getDatabaseById(queryDefinition.getDatabaseId()); if (database != null) { conn = DBConnectionFactory.getConnection(database.getName()); } else { conn = DBConnectionFactory.getConnection(); } logger.debug("conn:" + conn.toString()); String sql = queryDefinition.getSql(); sql = QueryUtils.replaceSQLVars(sql); List<Object> values = null; if (paramMap != null) { SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, paramMap); sql = sqlExecutor.getSql(); values = (List<Object>) sqlExecutor.getParameter(); } logger.debug("--------------execute query----------------------"); logger.debug(queryDefinition.getTitle()); logger.debug("::sql::" + sql); psmt = conn.prepareStatement(sql); if (values != null && !values.isEmpty()) { JdbcUtils.fillStatement(psmt, values); logger.debug("::values::" + values); } List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); rs = psmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { int sqlType = rsmd.getColumnType(i); ColumnDefinition column = new ColumnDefinition(); column.setColumnName(rsmd.getColumnName(i)); column.setColumnLabel(rsmd.getColumnLabel(i)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(i)); column.setScale(rsmd.getScale(i)); columns.add(column); } Set<String> cols = new HashSet<String>(); while (rs.next()) { int index = 0; TableModel rowModel = new TableModel(); ColumnModel cell01 = new ColumnModel(); cell01.setColumnName("ID"); cell01.setType("String"); rowModel.addColumn(cell01); rowModel.setIdColumn(cell01); cols.add(cell01.getColumnName()); ColumnModel cell04 = new ColumnModel(); cell04.setColumnName("AGGREGATIONKEY"); cell04.setType("String"); rowModel.addColumn(cell04); cols.add(cell04.getColumnName()); Iterator<ColumnDefinition> iterator = columns.iterator(); while (iterator.hasNext()) { ColumnDefinition column = iterator.next(); /** * ???? */ if (cols.contains(column.getColumnName())) { continue; } ColumnModel cell = new ColumnModel(); String columnName = column.getColumnName(); String javaType = column.getJavaType(); cell.setColumnName(columnName); cell.setType(javaType); index = index + 1; if ("String".equals(javaType)) { String value = rs.getString(columnName); cell.setStringValue(value); cell.setValue(value); } else if ("Integer".equals(javaType)) { try { Integer value = rs.getInt(columnName); cell.setIntValue(value); cell.setValue(value); } catch (Exception e) { String str = rs.getString(columnName); logger.error("integer:" + str); str = StringTools.replace(str, "$", ""); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setIntValue(num.intValue()); cell.setValue(cell.getIntValue()); logger.debug("?:" + num.intValue()); } } else if ("Long".equals(javaType)) { try { Long value = rs.getLong(columnName); cell.setLongValue(value); cell.setValue(value); } catch (Exception e) { String str = rs.getString(columnName); logger.error("long:" + str); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setLongValue(num.longValue()); cell.setValue(cell.getLongValue()); logger.debug("?:" + num.longValue()); } } else if ("Double".equals(javaType)) { try { Double d = rs.getDouble(columnName); cell.setDoubleValue(d); cell.setValue(d); } catch (Exception e) { String str = rs.getString(columnName); logger.error("double:" + str); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setDoubleValue(num.doubleValue()); cell.setValue(cell.getDoubleValue()); logger.debug("?:" + num.doubleValue()); } } else if ("Boolean".equals(javaType)) { Boolean value = rs.getBoolean(columnName); cell.setBooleanValue(value); cell.setValue(value); } else if ("Date".equals(javaType)) { Date value = rs.getTimestamp(columnName); cell.setDateValue(value); cell.setValue(value); } else { String value = rs.getString(columnName); cell.setStringValue(value); cell.setValue(value); } rowModel.addColumn(cell); if (resultList.isEmpty()) { singleDataMap.put(column.getColumnLabel(), cell.getValue()); } } resultList.add(rowModel); } logger.debug("--------------------resultList size:" + resultList.size()); } catch (Exception ex) { success = false; ex.printStackTrace(); logger.error(ex); throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(psmt); JdbcUtils.close(conn); if (!success) { if (task != null) { task.setStatus(2); transformTaskService.save(task); } } } logger.debug("--------------execute mybatis save----------------------"); try { if (!StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")) { TransformTable tbl = new TransformTable(); tbl.createOrAlterTable(tableDefinition); } List<ColumnDefinition> columns = DBUtils.getColumnDefinitions(tableDefinition.getTableName()); if (columns != null && !columns.isEmpty()) { tableDefinition.setColumns(columns); } if (resultList != null && !resultList.isEmpty() && tableDefinition.getTableName() != null && tableDefinition.getAggregationKeys() != null) { logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag()); logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn()); /** * ???? */ if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C") && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn()) && resultList.size() == 1) { logger.debug("?dataMap?:" + singleDataMap); logger.debug("AggregationKeys:" + tableDefinition.getAggregationKeys()); ColumnDefinition idField = columnMap.get(tableDefinition.getAggregationKeys().toLowerCase()); ColumnDefinition field = columnMap.get(queryDefinition.getRotatingColumn().toLowerCase()); logger.debug("idField:" + idField); logger.debug("field:" + field); if (idField != null && field != null) { String javaType = field.getJavaType(); List<TableModel> list = new ArrayList<TableModel>(); Set<Entry<String, Object>> entrySet = singleDataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); if (key == null || value == null) { continue; } TableModel tableModel = new TableModel(); tableModel.setTableName(queryDefinition.getTargetTableName()); ColumnModel cell = new ColumnModel(); cell.setColumnName(queryDefinition.getRotatingColumn()); cell.setType(javaType); // logger.debug(cell.getColumnName()+"->"+javaType); if ("String".equals(javaType)) { cell.setStringValue(ParamUtils.getString(singleDataMap, key)); cell.setValue(cell.getStringValue()); } else if ("Integer".equals(javaType)) { cell.setIntValue(ParamUtils.getInt(singleDataMap, key)); cell.setValue(cell.getIntValue()); } else if ("Long".equals(javaType)) { cell.setLongValue(ParamUtils.getLong(singleDataMap, key)); cell.setValue(cell.getLongValue()); } else if ("Double".equals(javaType)) { cell.setDoubleValue(ParamUtils.getDouble(singleDataMap, key)); cell.setValue(cell.getDoubleValue()); } else if ("Date".equals(javaType)) { cell.setDateValue(ParamUtils.getDate(singleDataMap, key)); cell.setValue(cell.getDateValue()); } else { cell.setValue(value); } tableModel.addColumn(cell); ColumnModel idColumn = new ColumnModel(); idColumn.setColumnName(tableDefinition.getAggregationKeys()); idColumn.setJavaType(idField.getJavaType()); idColumn.setValue(key); tableModel.setIdColumn(idColumn); list.add(tableModel); } logger.debug("update datalist:" + list); tableDataService.updateTableData(list); } } else { tableDataService.saveAll(tableDefinition, null, resultList); } } resultList.clear(); resultList = null; long time = System.currentTimeMillis() - start; if (task != null) { task.setEndTime(new java.util.Date()); task.setStatus(9); task.setDuration(time); } logger.debug("execute time(ms)--------------------------" + time); } catch (Exception ex) { if (task != null) { task.setStatus(2); } ex.printStackTrace(); logger.error(ex); throw new RuntimeException(ex); } finally { if (task != null) { transformTaskService.save(task); if (task.getStatus() != 9) { this.run(); } } } }
From source file:sv1djg.hamutils.dxcc.DXCCEntitiesReader.java
private void readCountryFile() { // the country file used is taken from http://www.country-files.com/cty/ // the appropriate version is for Aether log ///*from ww w . j a v a 2 s . c o m*/ // example entries // SV,Greece,236,EU,20,28,39.78,-21.78,-2.0,J4 SV SW SX SY SZ =SV9DRU/1; // field #1 -> prefix // field #2 -> country name // field #3 -> entity code (not needed) // field #4 -> continent (not needed) // field #5 -> CQ Zone (not needed) // field #6 -> ITU Zone (not needed) // field #7 -> latitude (+ for north, - for south) // field #8 -> longitude(+ for west, - for east) // field #9 -> time diff (not needed) // field #10 -> additional prefixes for this country // // we need fields 1,2,4,7,8 // field 8 normally should be negated try { // Open the file (it is embedded in the jar) InputStream fstream = getClass().getResourceAsStream(_countriesFile); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader countriesReader = new BufferedReader(new InputStreamReader(in), 65535); NumberFormat format = NumberFormat.getInstance(Locale.US); String countryEntry = countriesReader.readLine(); while (countryEntry != null) { String[] countryDetails = StringUtils.split(countryEntry, ","); if (countryDetails != null && countryDetails.length >= 9) { DXCCEntity dxccEntity = new DXCCEntity(); dxccEntity.prefix = countryDetails[0]; dxccEntity.countryName = countryDetails[1]; dxccEntity.continent = countryDetails[3]; dxccEntity.latitude = format.parse(countryDetails[6]).doubleValue(); dxccEntity.longitude = -format.parse(countryDetails[7]).doubleValue(); _dxccList.add(dxccEntity); } countryEntry = countriesReader.readLine(); } countriesReader.close(); } catch (Throwable e) { e.printStackTrace(); } }
From source file:org.ut.biolab.medsavant.client.view.genetics.charts.SummaryChart.java
private JPopupMenu createPopup(final Chart chart) { JPopupMenu menu = new JPopupMenu(); //Filter by selections JMenuItem filter1Item = new JMenuItem("Filter by Selection" + (mapGenerator.isNumeric() ? "" : "(s)")); filter1Item.addActionListener(new ActionListener() { @Override//from w w w .j av a 2s . co m public void actionPerformed(ActionEvent e) { ThreadController.getInstance().cancelWorkers(pageName); boolean isGender = mapGenerator.getName().equalsIgnoreCase(BasicPatientColumns.GENDER.getAlias()); try { List<String> values = new ArrayList<String>(); ListSelectionModel selectionModel = chart.getSelectionsForModel(chart.getModel(0)); QueryViewController qvc = SearchBar.getInstance().getQueryViewController(); for (int i = selectionModel.getMinSelectionIndex(); i <= selectionModel .getMaxSelectionIndex(); i++) { if (selectionModel.isSelectedIndex(i)) { String v = ((ChartPoint) chart.getModel().getPoint(i)).getHighlight().name(); values.add(v); if (mapGenerator.isNumeric() && !isGender) { double low = 0; double high = 0; String[] s = v.split(" - "); if (s.length < 2) { LOG.error("Invalid range detected for numeric condition " + mapGenerator.getName() + " val=" + v); } NumberFormat format = NumberFormat.getInstance(); low = format.parse(s[0]).doubleValue(); high = format.parse(s[1]).doubleValue(); QueryUtils.addNumericQuery(chartName, low, high, false); } } } if (values.isEmpty()) { return; } if (!mapGenerator.isNumeric() || isGender) { QueryUtils.addMultiStringQuery(chartName, values); } } catch (Exception ex) { ClientMiscUtils.reportError("Error filtering by selection: %s", ex); } } }); menu.add(filter1Item); return menu; }