List of usage examples for java.lang Float valueOf
@HotSpotIntrinsicCandidate public static Float valueOf(float f)
From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java
/** * Retrieve a JDBC column value from a ResultSet, using the specified value type. * <p>Uses the specifically typed ResultSet accessor methods, falling back to * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types. * <p>Note that the returned value may not be assignable to the specified * required type, in case of an unknown type. Calling code needs to deal * with this case appropriately, e.g. throwing a corresponding exception. * @param rs is the ResultSet holding the data * @param index is the column index//w w w . ja v a2s . co m * @param requiredType the required value type (may be <code>null</code>) * @return the value object * @throws SQLException if thrown by the JDBC API */ public static Object getResultSetValue(ResultSet rs, int index, Class requiredType) throws SQLException { if (requiredType == null) { return getResultSetValue(rs, index); } Object value = null; boolean wasNullCheck = false; // Explicitly extract typed value, as far as possible. if (String.class.equals(requiredType)) { value = rs.getString(index); } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) { value = Boolean.valueOf(rs.getBoolean(index)); wasNullCheck = true; } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) { value = Byte.valueOf(rs.getByte(index)); wasNullCheck = true; } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) { value = Short.valueOf(rs.getShort(index)); wasNullCheck = true; } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) { value = Integer.valueOf(rs.getInt(index)); wasNullCheck = true; } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) { value = Long.valueOf(rs.getLong(index)); wasNullCheck = true; } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) { value = Float.valueOf(rs.getFloat(index)); wasNullCheck = true; } else if (double.class.equals(requiredType) || Double.class.equals(requiredType) || Number.class.equals(requiredType)) { value = Double.valueOf(rs.getDouble(index)); wasNullCheck = true; } else if (byte[].class.equals(requiredType)) { value = rs.getBytes(index); } else if (java.sql.Date.class.equals(requiredType)) { value = rs.getDate(index); } else if (java.sql.Time.class.equals(requiredType)) { value = rs.getTime(index); } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) { value = rs.getTimestamp(index); } else if (BigDecimal.class.equals(requiredType)) { value = rs.getBigDecimal(index); } else if (Blob.class.equals(requiredType)) { value = rs.getBlob(index); } else if (Clob.class.equals(requiredType)) { value = rs.getClob(index); } else { // Some unknown type desired -> rely on getObject. value = getResultSetValue(rs, index); } // Perform was-null check if demanded (for results that the // JDBC driver returns as primitives). if (wasNullCheck && value != null && rs.wasNull()) { value = null; } return value; }
From source file:strat.mining.multipool.stats.builder.WaffleStatsBuilder.java
private AddressStats updateAddressStats(Address address, Date refreshDate) throws Exception { LOGGER.debug("Update addressStats for Waffle address {}.", address.getAddress()); long start = System.currentTimeMillis(); strat.mining.multipool.stats.jersey.model.waffle.AddressStats rawAddressStats = waffleRestClient .getAddressStats(address.getAddress()); AddressStats result = null;//from ww w . j av a 2 s . c o m if (rawAddressStats != null && StringUtils.isEmpty(rawAddressStats.getError())) { result = new AddressStats(); result.setAddressId(address.getId()); result.setBalance( rawAddressStats.getBalances() == null || rawAddressStats.getBalances().getConfirmed() == null ? 0 : rawAddressStats.getBalances().getConfirmed().floatValue()); result.setUnexchanged( rawAddressStats.getBalances() == null || rawAddressStats.getBalances().getUnconverted() == null ? 0 : rawAddressStats.getBalances().getUnconverted().floatValue()); result.setPaidout( rawAddressStats.getBalances() == null || rawAddressStats.getBalances().getSent() == null ? 0 : rawAddressStats.getBalances().getSent().floatValue()); result.setHashRate( rawAddressStats.getHash_rate() == null ? 0 : rawAddressStats.getHash_rate().floatValue()); result.setRefreshTime(refreshDate); List<WorkerStats> workersStats = new ArrayList<>(); if (CollectionUtils.isNotEmpty(rawAddressStats.getWorker_hashrates())) { Calendar calendar = GregorianCalendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -7); for (Worker_hashrates workerHasrate : rawAddressStats.getWorker_hashrates()) { // Keep the worker stats only if it has been seen in the 7 // previous days Date lastSeen = new Date(workerHasrate.getLast_seen().longValue() * 1000); if (lastSeen.after(calendar.getTime())) { WorkerStats worker = new WorkerStats(); if (workerHasrate.getUsername() != null) { worker.setUsername(workerHasrate.getUsername()); worker.setHashrate(workerHasrate.getHashrate() == null ? 0 : workerHasrate.getHashrate().floatValue()); worker.setStaleRate(workerHasrate.getStalerate() == null ? 0 : workerHasrate.getStalerate().floatValue()); workersStats.add(worker); } } } } result.setWorkerStats(workersStats); addressStatsDao.insertAddressStats(result); Transaction lastTransaction = transactionDao.getLastTransaction(address.getId()); SimpleDateFormat dateFormat = new SimpleDateFormat(PAYEMENT_DATE_PATTERN); if (CollectionUtils.isNotEmpty(rawAddressStats.getRecent_payments())) { for (Recent_payments payement : rawAddressStats.getRecent_payments()) { Date payementDate = dateFormat.parse(payement.getTime()); if (lastTransaction == null || lastTransaction.getDate().before(payementDate)) { Transaction transaction = new Transaction(); transaction.setAddressId(address.getId()); transaction .setAmount(payement.getAmount() == null ? 0 : Float.valueOf(payement.getAmount())); transaction.setDate(payementDate); transaction.setTransactionId(payement.getTxn()); transactionDao.insertTransaction(transaction); } else { // When all last transactions are inserted, just break break; } } } } else { throw new Exception( rawAddressStats == null ? "Unable to retrieve Waffle raw stats for address " + address : rawAddressStats.getError()); } PERF_LOGGER.debug("Waffle address {} updated in {} ms.", address.getAddress(), System.currentTimeMillis() - start); return result; }
From source file:de.tuberlin.uebb.jbop.optimizer.controlflow.ConstantIfInliner.java
private Number calculateOparator(final AbstractInsnNode node1, final Number op1, final Number op2) { Number newNumber = op1;//ww w. ja v a2 s . com if (isCompare(node1)) { switch (node1.getOpcode()) { case Opcodes.DCMPG: case Opcodes.DCMPL: newNumber = Double.valueOf(op2.doubleValue() - op1.doubleValue()); break; case Opcodes.FCMPG: case Opcodes.FCMPL: newNumber = Float.valueOf(op2.floatValue() - op1.floatValue()); break; case Opcodes.LCMP: newNumber = Long.valueOf(op2.longValue() - op1.longValue()); break; default: newNumber = op1; } } return newNumber; }
From source file:net.creativeparkour.GameManager.java
static void enable(Plugin plugin) { joueurs.clear();// w ww .j a v a 2 s.c o m maps.clear(); dossier_maps = new File(plugin.getDataFolder(), "/Maps"); dossier_temps = new File(plugin.getDataFolder(), "/Times"); fichier_exclusions_temps = new File(plugin.getDataFolder(), "deleted times.yml"); exclusions_temps = YamlConfiguration.loadConfiguration(fichier_exclusions_temps); // Cration de la version 2 des fichiers maps File fichier_maps = new File(plugin.getDataFolder(), "maps.yml"); if (!dossier_maps.exists() && fichier_maps.exists()) { YamlConfiguration configMaps = YamlConfiguration.loadConfiguration(fichier_maps); Bukkit.getLogger().info(Config.prefix(false) + "Converting maps from v1 to v2..."); boolean termine = false; for (int i = 0; !termine; i++) { if (configMaps.getString(i + ".state") == null) { termine = true; } else { World w = Bukkit.getWorld(configMaps.getString(i + ".world")); Set<UUID> invites = new HashSet<UUID>(); for (int i1 = 0; configMaps.getList(i + ".contributors") != null && i1 < configMaps.getList(i + ".contributors").size(); i1++) { invites.add(UUID.fromString((String) configMaps.getList(i + ".contributors").get(i1))); } if (w != null) { CPMap map = new CPMap(i, configMaps.getString(i + ".uuid"), CPMapState.valueOf(configMaps.getString(i + ".state").toUpperCase()), w, w.getBlockAt(configMaps.getInt(i + ".location min.x"), configMaps.getInt(i + ".location min.y"), configMaps.getInt(i + ".location min.z")), w.getBlockAt(configMaps.getInt(i + ".location max.x"), configMaps.getInt(i + ".location max.y"), configMaps.getInt(i + ".location max.z")), configMaps.getString(i + ".name"), UUID.fromString(configMaps.getString(i + ".creator")), invites, configMaps.getBoolean(i + ".pinned")); map.sauvegarder(); } } } fichier_maps .renameTo(new File(plugin.getDataFolder(), "maps (deprecated, see the new Maps folder).yml")); } dossier_maps.mkdirs(); // Chargement des maps for (File f : getFichiersMaps()) { YamlConfiguration yml = YamlConfiguration.loadConfiguration(f); if (yml.getString("world") != null) { World w = Bukkit.getWorld(yml.getString("world")); if (w != null) { Set<UUID> invites = new HashSet<UUID>(); for (int i1 = 0; yml.getList("contributors") != null && i1 < yml.getList("contributors").size(); i1++) { invites.add(UUID.fromString((String) yml.getList("contributors").get(i1))); } List<BlocSpecial> blocsSpeciaux = new ArrayList<BlocSpecial>(); ConfigurationSection ymlBS = yml.getConfigurationSection("special blocks"); if (ymlBS != null) { for (String key : ymlBS.getKeys(false)) { String type = ymlBS.getString(key + ".t"); Map<Character, Integer> c = CPUtils.parseCoordinates(key); Block bloc = w.getBlockAt(c.get('x'), c.get('y'), c.get('z')); if (type.equalsIgnoreCase(BlocDepart.getType())) // Dparts { blocsSpeciaux.add(new BlocDepart(bloc)); } else if (type.equalsIgnoreCase(BlocArrivee.getType())) // Arrives { blocsSpeciaux.add(new BlocArrivee(bloc)); } else if (type.equalsIgnoreCase(BlocCheckpoint.getType())) // Checkpoints { blocsSpeciaux.add(new BlocCheckpoint(bloc, (byte) ymlBS.getInt(key + ".dir"), ymlBS.getString(key + ".prop"))); } else if (type.equalsIgnoreCase(BlocEffet.getType())) // Effets { blocsSpeciaux.add(new BlocEffet(bloc, ymlBS.getString(key + ".effect"), ymlBS.getInt(key + ".duration"), ymlBS.getInt(key + ".amplifier"))); } else if (type.equalsIgnoreCase(BlocGive.getType())) // Gives { blocsSpeciaux.add(new BlocGive(bloc, ymlBS.getString(key + ".type"), ymlBS.getString(key + ".action"))); } else if (type.equalsIgnoreCase(BlocMort.getType())) // Morts { blocsSpeciaux.add(new BlocMort(bloc)); } else if (type.equalsIgnoreCase(BlocTP.getType())) // TP { blocsSpeciaux.add(new BlocTP(bloc, new Location(w, ymlBS.getDouble(key + ".x"), ymlBS.getDouble(key + ".y"), ymlBS.getDouble(key + ".z")))); } } } int id = yml.getInt("id"); float difficulty = -1; float quality = -1; try { difficulty = Float.valueOf(yml.getString("difficulty")); quality = Float.valueOf(yml.getString("quality")); } catch (Exception e) { // Rien } CPMap m = new CPMap(id, yml.getString("uuid"), CPMapState.valueOf(yml.getString("state").toUpperCase()), w, w.getBlockAt(yml.getInt("location min.x"), yml.getInt("location min.y"), yml.getInt("location min.z")), w.getBlockAt(yml.getInt("location max.x"), Math.min(yml.getInt("location max.y"), 126), yml.getInt("location max.z")), yml.getString("name"), UUID.fromString(yml.getString("creator")), invites, yml.getBoolean("pinned"), new BlocSpawn(w.getBlockAt(yml.getInt("spawn.x"), yml.getInt("spawn.y"), yml.getInt("spawn.z")), (byte) yml.getInt("spawn.dir")), blocsSpeciaux, yml.getInt("death height"), yml.getBoolean("sneak allowed", true), yml.getBoolean("deadly lava", false), yml.getBoolean("deadly water", false), yml.getBoolean("interactions allowed", true), yml.getStringList("ratings"), difficulty, quality, yml.getBoolean("force no plates")); maps.put(id, m); m.placerOuRetirerPlaques(); // Rgnration du contour s'il n'est pas l aux coordonnes min if (m.getMinLoc().getRelative(BlockFace.DOWN).getType() != Material.BEDROCK || m.getMinLoc().getRelative(BlockFace.NORTH).getType() != Material.BARRIER || m.getMinLoc().getRelative(BlockFace.WEST).getType() != Material.BARRIER) { Bukkit.getLogger().info(Config.prefix(false) + "Regenerating outline for the map \"" + m.getName() + "\"..."); new RemplisseurBlocs( genererContours(w, m.getMinLoc().getX(), m.getMinLoc().getY(), m.getMinLoc().getZ(), m.getMaxLoc().getX(), m.getMaxLoc().getY(), m.getMaxLoc().getZ()), w).runTaskTimer(CreativeParkour.getPlugin(), 20, 1); } } } } File fichier_temps = new File(plugin.getDataFolder(), "times.yml"); YamlConfiguration temps = YamlConfiguration.loadConfiguration(fichier_temps); // Cration de la version 2 du fichier des temps if (!fichier_temps.exists() && !dossier_temps.exists()) { File ancien_temps = new File(plugin.getDataFolder(), "players_times.yml"); if (ancien_temps.exists()) { Bukkit.getLogger().info(Config.prefix(false) + "Converting times from v1 to v2..."); YamlConfiguration ancienTemps = YamlConfiguration.loadConfiguration(ancien_temps); // Conversion des temps des secondes aux ticks et remplissage du nouveau fichier for (int i = 0; i < maps.size(); i++) // IDs des maps { for (int j = 0; ancienTemps.contains(i + "." + j + ".player"); j++) // Pour chaque joueur (de 0 x) { if (ancienTemps.contains(i + "." + j + ".time")) { ancienTemps.set(i + "." + j + ".ticks", ancienTemps.getInt(i + "." + j + ".time") * 20); ancienTemps.set(i + "." + j + ".time", null); } // Ajout du temps dans le nouveau fichier temps.set(i + ".map name", maps.get(i).getName()); temps.set(i + ".map uuid", maps.get(i).getUUID().toString()); String uuidJoueur = ancienTemps.getString(i + "." + j + ".player"); temps.set(i + ".times." + uuidJoueur + ".ticks", ancienTemps.getInt(i + "." + j + ".ticks")); temps.set(i + ".times." + uuidJoueur + ".player name", NameManager.getNomAvecUUID(UUID.fromString(uuidJoueur))); temps.set(i + ".times." + uuidJoueur + ".real milliseconds", ancienTemps.getInt(i + "." + j + ".ticks") * 50); } } // Sauvegarde try { temps.save(fichier_temps); } catch (IOException e) { Bukkit.getLogger().warning("An error occured while loading file 'CreativeParkour/times.yml'"); e.printStackTrace(); } ancien_temps.renameTo(new File(plugin.getDataFolder(), "players_times (deprecated).yml")); } } // Cration de la version 3 des fichiers temps if (!dossier_temps.exists() && fichier_temps.exists()) { Bukkit.getLogger().info(Config.prefix(false) + "Converting times from v2 to v3..."); // Cration d'objets Temps et sauvegerde de ceux-ci for (CPMap map : maps.values()) // IDs des maps { if (temps.contains(map.getId() + ".map uuid")) { ConfigurationSection csTemps = temps.getConfigurationSection(map.getId() + ".times"); Set<String> keys = csTemps.getKeys(false); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String uuidJ = it.next(); CPTime t = new CPTime(UUID.fromString(uuidJ), map, csTemps.getInt(uuidJ + ".ticks")); t.ajouterCheckpoints(csTemps.get(uuidJ + ".checkpoints")); t.realMilliseconds = csTemps.getLong(uuidJ + ".real milliseconds"); t.sauvegarder(new Date(csTemps.getLong(uuidJ + ".date"))); } } } fichier_temps .renameTo(new File(plugin.getDataFolder(), "times (deprecated, see the new Times folder).yml")); } dossier_temps.mkdirs(); String s = new String(); if (maps.size() != 1) { s = "s"; } Bukkit.getLogger().info(Config.prefix(false) + maps.size() + " CreativeParkour map" + s + " loaded."); // Blocs interdits if (!Config.getConfig().getBoolean("map creation.allow redstone")) { blocsInterdits.add(Material.REDSTONE_BLOCK); blocsInterdits.add(Material.REDSTONE_WIRE); blocsInterdits.add(Material.REDSTONE_COMPARATOR_OFF); blocsInterdits.add(Material.REDSTONE_COMPARATOR_ON); blocsInterdits.add(Material.DIODE_BLOCK_OFF); blocsInterdits.add(Material.DIODE_BLOCK_ON); blocsInterdits.add(Material.WOOD_PLATE); blocsInterdits.add(Material.STONE_PLATE); blocsInterdits.add(Material.IRON_PLATE); blocsInterdits.add(Material.GOLD_PLATE); blocsInterdits.add(Material.TRIPWIRE_HOOK); blocsInterdits.add(Material.DAYLIGHT_DETECTOR); blocsInterdits.add(Material.DAYLIGHT_DETECTOR_INVERTED); blocsInterdits.add(Material.REDSTONE_TORCH_ON); blocsInterdits.add(Material.REDSTONE_TORCH_OFF); blocsInterdits.add(Material.STONE_BUTTON); blocsInterdits.add(Material.WOOD_BUTTON); blocsInterdits.add(Material.LEVER); blocsInterdits.add(Material.DETECTOR_RAIL); try { blocsInterdits.add(Material.OBSERVER); } catch (NoSuchFieldError e) { // Rien } } if (!Config.getConfig().getBoolean("map creation.allow fluids")) { blocsInterdits.add(Material.WATER); blocsInterdits.add(Material.STATIONARY_WATER); blocsInterdits.add(Material.LAVA); blocsInterdits.add(Material.STATIONARY_LAVA); blocsInterdits.add(Material.ICE); } blocsInterdits.add(Material.TNT); blocsInterdits.add(Material.MOB_SPAWNER); blocsInterdits.add(Material.MONSTER_EGGS); blocsInterdits.add(Material.DRAGON_EGG); blocsInterdits.add(Material.ENDER_CHEST); blocsInterdits.add(Material.COMMAND); blocsInterdits.add(Material.PORTAL); blocsInterdits.add(Material.ENDER_PORTAL); exceptionsOPs.add(Material.COMMAND); try { blocsInterdits.add(Material.COMMAND_CHAIN); blocsInterdits.add(Material.COMMAND_REPEATING); blocsInterdits.add(Material.END_GATEWAY); exceptionsOPs.add(Material.COMMAND_CHAIN); exceptionsOPs.add(Material.COMMAND_REPEATING); } catch (NoSuchFieldError e) { // Rien } // Tlchargement des maps tlchargeables if (Config.online()) { Bukkit.getScheduler().runTaskLater(CreativeParkour.getPlugin(), new Runnable() { public void run() { synchroWeb(); } }, 500); // 25 secondes } // Programmation de la vidange mmoire if (Config.getConfig().getInt("memory dump interval") > 0) { int intervalle = Config.getConfig().getInt("memory dump interval") * 60 * 20; Bukkit.getScheduler().runTaskTimer(CreativeParkour.getPlugin(), new Runnable() { public void run() { vidangeMemoire(); } }, intervalle, intervalle); } RewardManager.enable(); PlayerProfiles.enable(); // Rintgration s'il y a des joueurs dans les maps Object[] onlinePlayers = Bukkit.getOnlinePlayers().toArray(); for (int i = 0; i < onlinePlayers.length; i++) { reintegrerMapOuQuitter((Player) onlinePlayers[i], false); } }
From source file:org.zenoss.zep.dao.impl.ConfigDaoImpl.java
private static Object valueFromString(FieldDescriptor field, Builder builder, String strValue) throws ZepException { if (field.isRepeated()) { throw new ZepException("Repeated field not supported"); }/*from w w w.j a v a2s . co m*/ switch (field.getJavaType()) { case BOOLEAN: return Boolean.valueOf(strValue); case BYTE_STRING: try { return ByteString.copyFrom(Base64.decodeBase64(strValue.getBytes("US-ASCII"))); } catch (UnsupportedEncodingException e) { // This exception should never happen - US-ASCII always exists in JVM throw new RuntimeException(e.getLocalizedMessage(), e); } case DOUBLE: return Double.valueOf(strValue); case ENUM: return field.getEnumType().findValueByNumber(Integer.valueOf(strValue)); case FLOAT: return Float.valueOf(strValue); case INT: return Integer.valueOf(strValue); case LONG: return Long.valueOf(strValue); case MESSAGE: try { return JsonFormat.merge(strValue, builder.newBuilderForField(field)); } catch (IOException e) { throw new ZepException(e.getLocalizedMessage(), e); } case STRING: return strValue; default: throw new ZepException("Unsupported type: " + field.getType()); } }
From source file:de.tuberlin.uebb.jbop.optimizer.arithmetic.ArithmeticExpressionInterpreter.java
private AbstractInsnNode handleSub(final int opcode, final Number one, final Number two) { final Number number; switch (opcode) { case ISUB:/* ww w .j a v a2 s. c om*/ number = Integer.valueOf(one.intValue() - two.intValue()); break; case DSUB: number = Double.valueOf(one.doubleValue() - two.doubleValue()); break; case FSUB: number = Float.valueOf(one.floatValue() - two.floatValue()); break; case LSUB: number = Long.valueOf(one.longValue() - two.longValue()); break; default: return null; } return NodeHelper.getInsnNodeFor(number); }
From source file:dk.dma.ais.abnormal.analyzer.analysis.SuddenSpeedChangeAnalysis.java
/** * Evaluate whether this track has kept its speed below SPEED_LOW_MARK * for a sustained period of at least SPEED_SUSTAIN_SECS seconds. * * Based on the vessel's own reported SOG. * * @param track/* www. ja v a 2 s . c om*/ * @return */ private boolean isSustainedReportedSpeedDecrease(Track track) { Optional<Float> maxSog = track.getTrackingReports().stream() .filter(tr -> tr.getTimestamp() >= track.getTimeOfLastPositionReport() - SPEED_SUSTAIN_SECS * 1000) .map(tr -> Float.valueOf(tr.getSpeedOverGround())).max(Comparator.<Float>naturalOrder()); return maxSog.isPresent() ? maxSog.get() <= SPEED_LOW_MARK : false; }
From source file:org.geowebcache.layer.MetaTile.java
/** * Extracts a single tile from the metatile. * /* ww w.j a v a2 s . c o m*/ * @param minX * left pixel index to crop the meta tile at * @param minY * top pixel index to crop the meta tile at * @param tileWidth * width of the tile * @param tileHeight * height of the tile * @return a rendered image of the specified meta tile region */ public RenderedImage createTile(final int minX, final int minY, final int tileWidth, final int tileHeight) { // do a crop, and then turn it into a buffered image so that we can release // the image chain RenderedOp cropped = CropDescriptor.create(metaTileImage, Float.valueOf(minX), Float.valueOf(minY), Float.valueOf(tileWidth), Float.valueOf(tileHeight), NO_CACHE); if (nativeAccelAvailable()) { log.trace("created cropped tile"); return cropped; } log.trace("native accel not available, returning buffered image"); BufferedImage tile = cropped.getAsBufferedImage(); disposePlanarImageChain(cropped, new HashSet<PlanarImage>()); return tile; }
From source file:com.github.fcannizzaro.resourcer.Resourcer.java
/** * Parse values xml files//from ww w . ja v a 2s .co m */ private static void findValues() { values = new HashMap<>(); File dir = new File(PATH_BASE + VALUES_DIR); if (!dir.isDirectory()) return; File[] files = dir.listFiles(); if (files == null) return; for (File file : files) // only *.xml files if (file.getName().matches(".*\\.xml$")) { Document doc = FileUtils.readXML(file.getAbsolutePath()); if (doc == null) return; Element ele = doc.getDocumentElement(); for (String element : elements) { NodeList list = ele.getElementsByTagName(element); if (values.get(element) == null) values.put(element, new HashMap<>()); for (int j = 0; j < list.getLength(); j++) { Element node = (Element) list.item(j); String value = node.getFirstChild().getNodeValue(); Object valueDefined = value; switch (element) { case INTEGER: valueDefined = Integer.valueOf(value); break; case DOUBLE: valueDefined = Double.valueOf(value); break; case FLOAT: valueDefined = Float.valueOf(value); break; case BOOLEAN: valueDefined = Boolean.valueOf(value); break; case LONG: valueDefined = Long.valueOf(value); break; case COLOR: if (value.matches("@color/.*")) { try { Class<?> c = Class.forName("com.github.fcannizzaro.material.Colors"); Object colors = c.getDeclaredField(value.replace("@color/", "")).get(c); Method asColor = c.getMethod("asColor"); valueDefined = asColor.invoke(colors); } catch (Exception e) { System.out.println("ERROR Resourcer - Cannot bind " + value); } } else valueDefined = Color.decode(value); break; } values.get(node.getNodeName()).put(node.getAttribute("name"), valueDefined); } } } }
From source file:net.sf.jasperreports.olap.JROlapDataSource.java
/** * Convert the value of the data type of the Field * @param jrField the Field whose type has to be converted * @return value of field in the requested type * *//* w w w . j a v a 2 s . c om*/ @Override public Object getFieldValue(JRField jrField) throws JRException { Class<?> valueClass = jrField.getValueClass(); Object value = fieldValues.get(jrField.getName()); try { /* * Everything in the result is a string, apart from Member */ if (valueClass.equals(mondrian.olap.Member.class)) { if (!(value instanceof mondrian.olap.Member)) { throw new JRException(EXCEPTION_MESSAGE_KEY_OLAP_CANNOT_CONVERT_FIELD_TYPE, new Object[] { jrField.getName(), value.getClass(), valueClass.getName() }); } return value; } /* * Convert the rest from String */ String fieldValue = (String) value; if (fieldValue == null) { return null; } if (Number.class.isAssignableFrom(valueClass)) { fieldValue = fieldValue.trim(); } if (fieldValue.length() == 0) { fieldValue = "0"; } if (valueClass.equals(String.class)) { return fieldValue; } else if (valueClass.equals(Boolean.class)) { return fieldValue.equalsIgnoreCase("true"); } else if (valueClass.equals(Byte.class)) { return Byte.valueOf(fieldValue); } else if (valueClass.equals(Integer.class)) { return Integer.valueOf(fieldValue); } else if (valueClass.equals(Long.class)) { return Long.valueOf(fieldValue); } else if (valueClass.equals(Short.class)) { return Short.valueOf(fieldValue); } else if (valueClass.equals(Double.class)) { return Double.valueOf(fieldValue); } else if (valueClass.equals(Float.class)) { return Float.valueOf(fieldValue); } else if (valueClass.equals(java.math.BigDecimal.class)) { return new java.math.BigDecimal(fieldValue); } else if (valueClass.equals(java.util.Date.class)) { return dateFormat.parse(fieldValue); } else if (valueClass.equals(java.sql.Timestamp.class)) { return new java.sql.Timestamp(dateFormat.parse(fieldValue).getTime()); } else if (valueClass.equals(java.sql.Time.class)) { return new java.sql.Time(dateFormat.parse(fieldValue).getTime()); } else if (valueClass.equals(java.lang.Number.class)) { return Double.valueOf(fieldValue); } else { throw new JRException(EXCEPTION_MESSAGE_KEY_OLAP_CANNOT_CONVERT_STRING_VALUE_TYPE, new Object[] { jrField.getName(), fieldValue, fieldValues.get(jrField.getName()).getClass(), valueClass.getName() }); } } catch (Exception e) { throw new JRException(EXCEPTION_MESSAGE_KEY_OLAP_FIELD_VALUE_NOT_RETRIEVED, new Object[] { jrField.getName(), valueClass.getName() }, e); } }