List of usage examples for java.lang Number toString
public String toString()
From source file:org.mule.util.NumberUtils.java
@SuppressWarnings("unchecked") public static <T extends Number> T convertNumberToTargetClass(Number number, Class<T> targetClass) throws IllegalArgumentException { if (targetClass.isInstance(number)) { return (T) number; } else if (targetClass.equals(Byte.class)) { long value = number.longValue(); if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { raiseOverflowException(number, targetClass); }/* w w w .j a va 2 s .co m*/ return (T) new Byte(number.byteValue()); } else if (targetClass.equals(Short.class)) { long value = number.longValue(); if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { raiseOverflowException(number, targetClass); } return (T) new Short(number.shortValue()); } else if (targetClass.equals(Integer.class)) { long value = number.longValue(); if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { raiseOverflowException(number, targetClass); } return (T) new Integer(number.intValue()); } else if (targetClass.equals(Long.class)) { return (T) new Long(number.longValue()); } else if (targetClass.equals(BigInteger.class)) { if (number instanceof BigDecimal) { // do not lose precision - use BigDecimal's own conversion return (T) ((BigDecimal) number).toBigInteger(); } else { // original value is not a Big* number - use standard long conversion return (T) BigInteger.valueOf(number.longValue()); } } else if (targetClass.equals(Float.class)) { return (T) new Float(number.floatValue()); } else if (targetClass.equals(Double.class)) { return (T) new Double(number.doubleValue()); } else if (targetClass.equals(BigDecimal.class)) { // always use BigDecimal(String) here to avoid unpredictability of // BigDecimal(double) // (see BigDecimal javadoc for details) return (T) new BigDecimal(number.toString()); } else { throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]"); } }
From source file:com.fluidops.iwb.server.SparqlServlet.java
/** * Handle legacy aggregation of tuple queries. Prints the aggregated result as CSV! * // ww w .java2 s .c o m * Condition: tuple query + parameter "input" and "output" are set * * Also deals with (optional) parameter "datasets" * * This method MUST return true, if SPARQL processing shall continue. If legacy code * is applied, results may be written to the outputstream directly (and false is returned) * * @param res * @param req * @return * true if the standard SPARQL processing should continue, false otherwise * @throws QueryEvaluationException * @throws IOException */ private boolean handleAggregationLegacy(TupleQueryResult res, HttpServletRequest req, ReadDataManager queryDM, OutputStream outputStream) throws QueryEvaluationException, IOException { String input = req.getParameter("input"); String output = req.getParameter("output"); // check the condition if (StringUtil.isNullOrEmpty(input) || StringUtil.isNullOrEmpty(output)) return true; String datasets = req.getParameter("datasets"); String aggregation = req.getParameter("aggregation"); String[] outputs = output.split(","); AggregationType aggType = AggregationType.NONE; // DEFAULT if (aggregation != null) { if (aggregation.equals("COUNT")) aggType = AggregationType.COUNT; else if (aggregation.equals("SUM")) aggType = AggregationType.SUM; else if (aggregation.equals("NONE")) aggType = AggregationType.NONE; else if (aggregation.equals("AVG")) aggType = AggregationType.AVG; } Map<Value, Vector<Number>> valueMap; if (datasets == null) { valueMap = queryDM.aggregateQueryResult(res, aggType, input, outputs); } else { // special handling: we must first group by the values // of the datasets parameter before aggregating; this // processing scheme supports only a single output variable String[] splittedDatasets = datasets.split(","); valueMap = queryDM.aggregateQueryResultWrtDatasets(res, aggType, input, outputs[0], splittedDatasets); } // We need to sort the input again, as the order gets lost when accessing the valueMap Set<Value> keySet = valueMap.keySet(); SortedSet<Value> sortedSet = new TreeSet<Value>(new ValueComparator()); sortedSet.addAll(keySet); // need to write at least one space, as empty results cause errors in charts if (sortedSet.isEmpty()) outputStream.write(" ".getBytes("UTF-8")); for (Value val : sortedSet) { Vector<Number> vals = valueMap.get(val); outputStream.write(val.stringValue().getBytes("UTF-8")); for (int i = 0; i < vals.size(); i++) { Number n = vals.elementAt(i); if (n == null || n.toString() == null) outputStream.write(";".getBytes("UTF-8")); else outputStream.write((";" + n.toString()).getBytes("UTF-8")); } outputStream.write("\n".getBytes("UTF-8")); } return false; }
From source file:de.undercouch.bson4jackson.BsonParser.java
@Override public BigDecimal getDecimalValue() throws IOException, JsonParseException { Number n = getNumberValue(); if (n == null) { return null; }/*from ww w . ja v a2s . c o m*/ if (n instanceof Byte || n instanceof Integer || n instanceof Long || n instanceof Short) { return BigDecimal.valueOf(n.longValue()); } else if (n instanceof Double || n instanceof Float) { return BigDecimal.valueOf(n.doubleValue()); } return new BigDecimal(n.toString()); }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java
public <T extends ObjectType> String getVersionAttempt(Class<T> type, String oid, OperationResult result) throws ObjectNotFoundException, SchemaException { LOGGER_PERFORMANCE.debug("> get version {}, oid={}", type.getSimpleName(), oid); String version = null;//from ww w .j ava2 s. com Session session = null; try { session = baseHelper.beginReadOnlyTransaction(); Query query = session.getNamedQuery("getVersion"); query.setParameter("oid", oid); Number versionLong = (Number) query.uniqueResult(); if (versionLong == null) { throw new ObjectNotFoundException( "Object '" + type.getSimpleName() + "' with oid '" + oid + "' was not found."); } version = versionLong.toString(); session.getTransaction().commit(); } catch (RuntimeException ex) { baseHelper.handleGeneralRuntimeException(ex, session, result); } finally { baseHelper.cleanupSessionAndResult(session, result); } return version; }
From source file:org.apache.velocity.tools.generic.MathTool.java
/** * Takes the original argument(s) and returns the resulting value as * an instance of the best matching type (Integer, Long, or Double). * If either an argument or the result is not an integer (i.e. has no * decimal when rendered) the result will be returned as a Double. * If not and the result is < -2147483648 or > 2147483647, then a * Long will be returned. Otherwise, an Integer will be returned. *//*from ww w. j a v a 2 s. co m*/ protected Number matchType(Number in1, Number in2, double out) { //NOTE: if we just checked class types, we could miss custom // extensions of java.lang.Number, and if we only checked // the mathematical value, $math.div('3.0', 1) would render // as '3'. To get the expected result, we check what we're // concerned about: the rendered string. // first check if the result is a whole number boolean isWhole = (Math.rint(out) == out); if (isWhole) { // assume that 1st arg is not null, // check for floating points String in = in1.toString(); isWhole = (in.indexOf('.') < 0); // if we don't have a decimal yet but do have a second arg if (isWhole && in2 != null) { in = in2.toString(); isWhole = (in.indexOf('.') < 0); } } if (!isWhole) { return new Double(out); } else if (out > Integer.MAX_VALUE || out < Integer.MIN_VALUE) { return new Long((long) out); } else { return new Integer((int) out); } }
From source file:de.undercouch.bson4jackson.BsonParser.java
@Override public BigInteger getBigIntegerValue() throws IOException, JsonParseException { Number n = getNumberValue(); if (n == null) { return null; }// w w w. j av a2s . c o m if (n instanceof Byte || n instanceof Integer || n instanceof Long || n instanceof Short) { return BigInteger.valueOf(n.longValue()); } else if (n instanceof Double || n instanceof Float) { return BigDecimal.valueOf(n.doubleValue()).toBigInteger(); } return new BigInteger(n.toString()); }
From source file:edu.ku.brc.af.ui.forms.validation.ValFormattedTextFieldSingle.java
/** * @param value//from w ww . java 2 s. c om * @return */ protected UIValidatable.ErrorType validateNumeric(final String value) { Class<?> cls = formatter.getDataClass(); try { if (cls == BigDecimal.class) { if (bdValidator == null) { bdValidator = CurrencyValidator.getInstance(); } Number maxVal = formatter.getMaxValue(); Number minVal = formatter.getMinValue(); BigDecimal fooAmount = bdValidator.validate(value, Locale.getDefault()); // XXX FINAL RELEASE if (fooAmount == null) { // error...not a valid currency amount return UIValidatable.ErrorType.Error; } if (!bdValidator.minValue(fooAmount, minVal) || !bdValidator.maxValue(fooAmount, maxVal)) { // valid...in the specified range return UIValidatable.ErrorType.Error; } return UIValidatable.ErrorType.Valid; } else { try { if (cls == Long.class) { Number num = numIntFormatter.parse(value); Long val = Long.valueOf(num.toString()); return !isMinMaxOK(val) ? UIValidatable.ErrorType.Error : UIValidatable.ErrorType.Valid; } else if (cls == Integer.class) { Number num = numIntFormatter.parse(value); Integer val = Integer.valueOf(num.toString()); return !isMinMaxOK(val) ? UIValidatable.ErrorType.Error : UIValidatable.ErrorType.Valid; } else if (cls == Short.class) { Number num = numIntFormatter.parse(value); Short val = Short.valueOf(num.toString()); return !isMinMaxOK(val) ? UIValidatable.ErrorType.Error : UIValidatable.ErrorType.Valid; } else if (cls == Byte.class) { Number num = numIntFormatter.parse(value); Byte val = Byte.valueOf(num.toString()); return !isMinMaxOK(val) ? UIValidatable.ErrorType.Error : UIValidatable.ErrorType.Valid; } else if (cls == Double.class) { Number num = numberFormatter.parse(value); Double val = Double.valueOf(num.toString()); return !isMinMaxOK(val) ? UIValidatable.ErrorType.Error : UIValidatable.ErrorType.Valid; } else if (cls == Float.class) { Number num = numberFormatter.parse(value); Float val = Float.valueOf(num.toString()); return !isMinMaxOK(val) ? UIValidatable.ErrorType.Error : UIValidatable.ErrorType.Valid; } else { throw new RuntimeException("Missing case for numeric class [" + cls.getName() + "]"); } } catch (NumberFormatException fex) { return UIValidatable.ErrorType.Error; } } } catch (Exception ex) { } return UIValidatable.ErrorType.Error; }
From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java
protected Number scaleNumber(Number number, Number scale) { Number scaledNumber = number; if ((number != null) && (scale != null) && !scale.equals(1) && !scale.equals(0)) { int startingSignificantDigits = 0; if (!(number instanceof Integer)) { int indexOfDecimalPoint = number.toString().indexOf("."); if (indexOfDecimalPoint >= 0) { String fractionalPart = number.toString().substring(indexOfDecimalPoint + 1); if ((fractionalPart.length() > 1) || Integer.parseInt(fractionalPart) > 0) { startingSignificantDigits = fractionalPart.length(); }//from ww w. ja v a 2 s . co m } } int preferredSignificantDigits = Math.max(2, Math.min(startingSignificantDigits, 6)); scaledNumber = number.doubleValue() / scale.doubleValue(); int scaledSignificantDigits = 0; int indexOfDecimalPoint = scaledNumber.toString().indexOf("."); String fractionalPart = scaledNumber.toString().substring(indexOfDecimalPoint + 1); if ((fractionalPart.length() > 1) || Integer.parseInt(fractionalPart) > 0) { scaledSignificantDigits = fractionalPart.length(); } if (scaledSignificantDigits > preferredSignificantDigits) { double multiplier = Math.pow(10, preferredSignificantDigits); scaledNumber = Math.round(scaledNumber.doubleValue() * multiplier) / multiplier; } } return scaledNumber; }
From source file:org.breizhbeans.thrift.tools.thriftmongobridge.protocol.TBSONUnstackedProtocol.java
private void writeNumber(Number v) throws TException { try {//from w w w . j a v a2s . c o m ThriftFieldMetadata thriftFieldMetadata = peekWriteField(); String key = thriftFieldMetadata.tfield.name; //System.out.println("write " + key + " " + v); ThriftIO thriftIO = threadSafeSIOStack.get().peek(); //specific map treatment for the map key if (thriftIO.map && thriftIO.key == null) { thriftIO.key = v.toString(); } else if (thriftIO.map) { thriftIO.mongoIO.put(thriftIO.key, v); thriftIO.key = null; } else if (thriftIO.list) { ((BasicDBList) thriftIO.mongoIO).add(v); } else { thriftIO.mongoIO.put(key, v); } } catch (Exception e) { throw new TException(e); } }
From source file:name.livitski.databag.cli.Launcher.java
protected void listVersions() throws DBException { String fileNameOption = optionValue(HISTORY_COMMAND); Number fileId = getFileId();//from w w w. j a va2 s . c om if (null == fileNameOption && null == fileId) throw new IllegalArgumentException("Please select a file to list its versions"); PrintStream out = getOutputStream(); SharedFiles query = new SharedFiles(db, getConfiguration()); Cursor<SharedFileInfo> fileList = null; Cursor<SharedFileInfo.Version> versionList = null; try { if (null == fileId) { File path = new File(fileNameOption); log().info("Applying " + query.getEffectiveFilterSpec()); fileList = query.listAllFilesRelatedToPath(path); } else { SharedFileInfo file = query.fileWithId(fileId); if (null != file && null != fileNameOption) { File path = file.getPathInReplica(); if (!fileNameOption.equals(path.getPath())) { log().warning("File # " + fileId + " with name '" + path + "' does not match the requested path: " + fileNameOption); file = null; } } fileList = null == file ? new EmptyCursor<SharedFileInfo>() : new SingletonCursor<SharedFileInfo>(file); } int deletedCount = 0; int renamedCount = 0; boolean exists = false; for (SharedFileInfo file; null != (file = fileList.next());) { fileId = file.getId(); if (null != fileNameOption && !fileNameOption.equals(file.getPathInReplica().getPath())) { renamedCount++; if (null == file.getDeleted()) out.printf(HISTORY_HEADER_REQUIRED_PREFIX + "(versions that had name '%s') ===%n", fileId, file.getPathInReplica(), fileNameOption); else out.printf( HISTORY_HEADER_REQUIRED_PREFIX + ", deleted on %tF %3$tT (versions that had name '%s') ===%n", fileId, file.getPathInReplica(), file.getDeleted(), fileNameOption); } else if (null == file.getDeleted()) { exists = true; out.printf(HISTORY_HEADER_REQUIRED_PREFIX + " ===%n", fileId, file.getPathInReplica()); } else { deletedCount++; out.printf(HISTORY_HEADER_REQUIRED_PREFIX + ", deleted on %tF %3$tT ===%n", fileId, file.getPathInReplica(), file.getDeleted()); } versionList = file.findVersions(null == fileNameOption ? null : new File(fileNameOption)); boolean wasAny = false; for (SharedFileInfo.Version v; null != (v = versionList.next());) { if (!wasAny) { out.println(); out.println("Version: Id Parent Size Timestamp"); wasAny = true; } Number base = v.getBaseVersionId(); out.printf("%-10s%11d%11s%20s %tF %5$tT%n", v.isCurrent() ? "(current)" : "", v.getId(), null == base ? "(none)" : base.toString(), v.isDeletionMark() ? "(deleted)" : v.getSize(), v.getModifiedTime()); } versionList.close(); versionList = null; } out.printf("%nFound %s existing, %d renamed, and %d deleted file(s)%n", exists ? "1" : "no", renamedCount, deletedCount); } finally { if (null != fileList) { try { fileList.close(); } catch (Exception ex) { log().log(Level.FINE, "Could not close " + fileList, ex); } } if (null != versionList) { try { versionList.close(); } catch (Exception ex) { log().log(Level.FINE, "Could not close " + versionList, ex); } } try { query.close(); } catch (Exception ex) { log().log(Level.FINE, "Could not close the storage query service", ex); } } }