List of usage examples for java.lang Byte parseByte
public static byte parseByte(String s) throws NumberFormatException
From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java
/** * Deserial the xml to object accord to the give model class. * * @param partitionKey/* ww w . j a v a 2s. c o m*/ * @param rowKey * @param eTag * @param timestamp * @param values * @return Instance of the given model class. */ private ITableServiceEntity createObjectByModelClass(String partitionKey, String rowKey, String eTag, String timestamp, List<ICloudTableColumn> values) { ITableServiceEntity newInstance = instanceModel(partitionKey, rowKey, eTag, timestamp, values); if (newInstance == null) { return null; } // Copy Field if (values != null && !values.isEmpty()) { for (ICloudTableColumn column : values) { Field field = null; try { field = newInstance.getClass().getDeclaredField(column.getName()); } catch (NoSuchFieldException e) { continue; } if (field == null) { continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) && Modifier.isFinal(modifier) && Modifier.isStatic(modifier)) { if (getModelClass() != null) { Logger.debug(MessageFormat.format( "{0} class {1} is a static final field. Can not set data to it.", getModelClass().getClass(), field.getName())); } continue; } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } ETableColumnType type = column.getType(); String value = column.getValue(); if (value == null) { continue; } else { try { if (type == null) { setStringOrObjectField(newInstance, column, field, value); } else if (type.equals(ETableColumnType.TYPE_BINARY)) { field.set(newInstance, Base64.decode(value)); } else if (type.equals(ETableColumnType.TYPE_BOOL)) { field.setBoolean(newInstance, Boolean.parseBoolean(value)); } else if (type.equals(ETableColumnType.TYPE_DATE_TIME)) { field.set(newInstance, Utilities.tryGetDateTimeFromTableEntry(value)); } else if (type.equals(ETableColumnType.TYPE_DOUBLE)) { field.setDouble(newInstance, Double.parseDouble(value)); } else if (type.equals(ETableColumnType.TYPE_GUID)) { Guid guid = new Guid(); try { Field valueField = guid.getClass().getDeclaredField("value"); boolean accessiable = valueField.isAccessible(); if (!accessible) { valueField.setAccessible(true); } valueField.set(guid, value); valueField.setAccessible(accessiable); field.set(newInstance, guid); } catch (NoSuchFieldException e) { Logger.error(e.getMessage(), e); } } else if (type.equals(ETableColumnType.TYPE_INT)) { try { field.setInt(newInstance, Integer.parseInt(value)); } catch (Exception e) { field.setByte(newInstance, Byte.parseByte(value)); } } else if (type.equals(ETableColumnType.TYPE_LONG)) { field.setLong(newInstance, Long.parseLong(value)); } else if (type.equals(ETableColumnType.TYPE_STRING)) { setStringOrObjectField(newInstance, column, field, value); } } catch (Exception e) { Logger.error( MessageFormat.format("{0} class filed {1} set failed.", getModelClass(), value), e); } } // revert aaccessible field.setAccessible(accessible); } } return newInstance; }
From source file:org.ariose.util.SMPPSender.java
/** * Prompts the user to enter a byte value for a parameter. *//* w ww . j a v a 2 s . c o m*/ private byte getParam(String prompt, byte defaultValue) { return Byte.parseByte(getParam(prompt, Byte.toString(defaultValue))); }
From source file:com.hzc.framework.ssh.controller.WebUtil.java
/** * ?????bean<br/>//www. java 2s .c o m * ??? * * @param <T> * @throws ValidationException */ public static <T> T packBean(Class<T> c) throws RuntimeException { try { HttpServletRequest request = ActionContext.getReq(); T newInstance = c.newInstance(); Field[] fields = c.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); String value = request.getParameter(name); Class<?> type = field.getType(); if (type.isArray()) {//?string file Class<?> componentType = type.getComponentType(); if (componentType == String.class) { String[] values = request.getParameterValues(name); // if (null == value || "".equals(value)) continue; // String[] split = value.split(","); field.set(newInstance, values); } else if (componentType == File.class) { ServletContext servletContext = getServletContext(); File file = new File(servletContext.getRealPath("upload")); if (!file.exists()) file.mkdir(); MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(), MAX_POST_SIZE, "UTF-8", new DefaultFileRenamePolicy()); Enumeration files = multi.getFileNames(); List<File> fileList = new ArrayList<File>(); if (files.hasMoreElements()) { File f = multi.getFile((String) files.nextElement()); fileList.add(f); } field.set(newInstance, fileList.toArray(new File[] {})); } } // else if (type == File.class) {//? // ServletContext servletContext = getServletContext(); // File file = new File(servletContext.getRealPath("upload")); // if (!file.exists()) // file.mkdir(); // MultipartRequest multi = // new MultipartRequest(request, file.getAbsolutePath(), 10 * 1024 * 1024, "UTF-8", new DefaultFileRenamePolicy()); // Enumeration files = multi.getFileNames(); // if (files.hasMoreElements()) { // field.set(newInstance, multi.getFile((String) files.nextElement())); // } // } // ? validation(field, name, value); if (null == value || "".equals(value.trim())) { continue; } if (type == Long.class) { field.set(newInstance, Long.parseLong(value)); } else if (type == String.class) { field.set(newInstance, value); } else if (type == Byte.class) { field.set(newInstance, Byte.parseByte(value)); } else if (type == Integer.class) { field.set(newInstance, Integer.parseInt(value)); } else if (type == Character.class) { field.set(newInstance, value.charAt(0)); } else if (type == Boolean.class) { field.set(newInstance, Boolean.parseBoolean(value)); } else if (type == Double.class) { field.set(newInstance, Double.parseDouble(value)); } else if (type == Float.class) { field.set(newInstance, Float.parseFloat(value)); } else if (type == Date.class) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); field.set(newInstance, sdf.parse(value)); } } return newInstance; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.openxdata.server.sms.FormSmsParser.java
/** * Gets a list of questions which have been answered. * //from w w w. j av a 2 s . co m * @param formData the form data. * @param ids * @return list of answered questions */ private Vector<QuestionData> getAnsweredQuestions(org.openxdata.model.FormData formData, Vector<Byte> ids) { Vector<QuestionData> qtns = new Vector<QuestionData>(); for (byte i = 0; i < ids.size(); i++) { QuestionData questionData = formData.getQuestion(Byte.parseByte(ids.elementAt(i).toString())); if (questionData.isAnswered()) qtns.add(questionData); } return qtns; }
From source file:org.eclipse.kapua.app.console.server.GwtDeviceManagementServiceImpl.java
private Object getObjectValue(GwtConfigParameter gwtConfigParam, String strValue) { Object objValue = null;/*from www . j a v a 2 s .c o m*/ if (strValue != null) { GwtConfigParameterType gwtType = gwtConfigParam.getType(); switch (gwtType) { case LONG: objValue = Long.parseLong(strValue); break; case DOUBLE: objValue = Double.parseDouble(strValue); break; case FLOAT: objValue = Float.parseFloat(strValue); break; case INTEGER: objValue = Integer.parseInt(strValue); break; case SHORT: objValue = Short.parseShort(strValue); break; case BYTE: objValue = Byte.parseByte(strValue); break; case BOOLEAN: objValue = Boolean.parseBoolean(strValue); break; case PASSWORD: objValue = new Password(strValue); break; case CHAR: objValue = Character.valueOf(strValue.charAt(0)); break; case STRING: objValue = strValue; break; } } return objValue; }
From source file:com.gemstone.gemfire.management.internal.cli.functions.DataCommandFunction.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private Object getClassObject(String string, String klassString) throws ClassNotFoundException, IllegalArgumentException { if (klassString == null || klassString.isEmpty()) return string; else {//from www. j a v a2s.com Object o = null; Class klass = ClassPathLoader.getLatest().forName(klassString); if (klass.equals(String.class)) return string; if (JsonUtil.isPrimitiveOrWrapper(klass)) { try { if (klass.equals(Byte.class)) { o = Byte.parseByte(string); return o; } else if (klass.equals(Short.class)) { o = Short.parseShort(string); return o; } else if (klass.equals(Integer.class)) { o = Integer.parseInt(string); return o; } else if (klass.equals(Long.class)) { o = Long.parseLong(string); return o; } else if (klass.equals(Double.class)) { o = Double.parseDouble(string); return o; } else if (klass.equals(Boolean.class)) { o = Boolean.parseBoolean(string); return o; } else if (klass.equals(Float.class)) { o = Float.parseFloat(string); return o; } return o; } catch (NumberFormatException e) { throw new IllegalArgumentException( "Failed to convert input key to " + klassString + " Msg : " + e.getMessage()); } } try { o = getObjectFromJson(string, klass); return o; } catch (IllegalArgumentException e) { throw e; } } }
From source file:org.ariose.util.SMPPSender.java
/** * Loads configuration parameters from the file with the given name. Sets * private variable to the loaded values. *///from ww w .j a va2 s . c o m public void setPropertiesFromConfig(GmlcConfiguration config) throws Exception { log.info("Setting default parameters..."); byte ton; byte npi; String addr; String bindMode; int rcvTimeout; operatorName = config.getOperatorname(); shortCode = config.getShortcode(); ipAddress = config.getIpaddress(); // CommonFunctions.checkNull("ipAddress", ipAddress); try { port = Integer.parseInt(config.getPort()); } catch (Exception e) { throw new Exception("Cannot send sms..port is not configured properly"); } // port = getIntProperty("port", port); systemId = config.getSystemid();// properties.getProperty("system-id"); password = config.getPassword();// properties.getProperty("password"); try { ton = Byte.parseByte(config.getAddrton()); } catch (Exception e) { ton = Byte.parseByte(Byte.toString(addressRange.getTon())); } try { npi = Byte.parseByte(config.getAddrnpi()); } catch (Exception e) { npi = Byte.parseByte(Byte.toString(addressRange.getNpi())); } if (config.getAddressrange() != null) addr = config.getAddressrange(); else addr = addressRange.getAddressRange(); // ton = getByteProperty("addr-ton", addressRange.getTon()); // npi = getByteProperty("addr-npi", addressRange.getNpi()); // addr = properties.getProperty("address-range", addressRange // .getAddressRange()); addressRange.setTon(ton); addressRange.setNpi(npi); try { addressRange.setAddressRange(addr); } catch (WrongLengthOfStringException e) { log.error("The length of address-range parameter is wrong."); } try { ton = Byte.parseByte(config.getSourceton()); } catch (Exception e) { ton = Byte.parseByte(Byte.toString(sourceAddress.getTon())); } try { npi = Byte.parseByte(config.getSourcenpi()); } catch (Exception e) { npi = Byte.parseByte(Byte.toString(sourceAddress.getNpi())); } // ton = getByteProperty("source-ton", sourceAddress.getTon()); // npi = getByteProperty("source-npi", sourceAddress.getNpi()); if (config.getSourceaddress() != null) addr = config.getSourceaddress(); else addr = sourceAddress.getAddress(); // addr = properties.getProperty("source-address", sourceAddress // .getAddress()); setAddressParameter("source-address", sourceAddress, ton, npi, addr); try { ton = Byte.parseByte(config.getDestinationton()); } catch (Exception e) { ton = Byte.parseByte(Byte.toString(destAddress.getTon())); } try { npi = Byte.parseByte(config.getDestinationnpi()); } catch (Exception e) { npi = Byte.parseByte(Byte.toString(destAddress.getNpi())); } // ton = getByteProperty("source-ton", sourceAddress.getTon()); // npi = getByteProperty("source-npi", sourceAddress.getNpi()); if (config.getDestinationaddress() != null) addr = config.getDestinationaddress(); else addr = destAddress.getAddress(); // ton = getByteProperty("destination-ton", destAddress.getTon()); // npi = getByteProperty("destination-npi", destAddress.getNpi()); // addr = properties.getProperty("destination-address", destAddress // .getAddress()); setAddressParameter("destination-address", destAddress, ton, npi, addr); if (config.getServicetype() != null) serviceType = config.getServicetype(); if (config.getSystemtype() != null) systemType = config.getSystemtype(); if (config.getBindmode() != null) bindMode = config.getBindmode(); else bindMode = bindOption; // serviceType = properties.getProperty("service-type", serviceType); // systemType = properties.getProperty("system-type", systemType); // bindMode = properties.getProperty("bind-mode", bindOption); if (bindMode.equalsIgnoreCase("transmitter")) { bindMode = "t"; } else if (bindMode.equalsIgnoreCase("receiver")) { bindMode = "r"; } else if (bindMode.equalsIgnoreCase("transciever")) { bindMode = "tr"; } else if (!bindMode.equalsIgnoreCase("t") && !bindMode.equalsIgnoreCase("r") && !bindMode.equalsIgnoreCase("tr")) { log.info("The value of bind-mode parameter in " + "the database gmlc_configuration table is wrong. " + "Setting the default as t"); bindMode = "t"; } bindOption = bindMode; // receive timeout in the cfg file is in seconds, we need milliseconds // also conversion from -1 which indicates infinite blocking // in the cfg file to Data.RECEIVE_BLOCKING which indicates infinite // blocking in the library is needed. if (receiveTimeout == Data.RECEIVE_BLOCKING) { rcvTimeout = -1; } else { rcvTimeout = ((int) receiveTimeout) / 1000; } if (config.getReceivetimeout() != null) rcvTimeout = Integer.parseInt(config.getReceivetimeout()); // rcvTimeout = getIntProperty("receive-timeout", rcvTimeout); if (rcvTimeout == -1) { receiveTimeout = Data.RECEIVE_BLOCKING; } else { receiveTimeout = rcvTimeout * 1000; } /* * scheduleDeliveryTime validityPeriod shortMessage numberOfDestination * messageId esmClass protocolId priorityFlag registeredDelivery * replaceIfPresentFlag dataCoding smDefaultMsgId */ }
From source file:paulscode.android.mupen64plusae.GalleryActivity.java
void refreshGrid() { final ConfigFile config = new ConfigFile(mGlobalPrefs.romInfoCache_cfg); final String query = mSearchQuery.toLowerCase(Locale.US); String[] searches = null;//w w w .j ava2 s . c om if (query.length() > 0) searches = query.split(" "); List<GalleryItem> items = new ArrayList<>(); List<GalleryItem> recentItems = null; int currentTime = 0; if (mGlobalPrefs.isRecentShown) { recentItems = new ArrayList<>(); currentTime = (int) (new Date().getTime() / 1000); } for (final String md5 : config.keySet()) { if (!ConfigFile.SECTIONLESS_NAME.equals(md5)) { final ConfigSection section = config.get(md5); String goodName; if (mGlobalPrefs.isFullNameShown || !section.keySet().contains("baseName")) goodName = section.get("goodName"); else goodName = section.get("baseName"); boolean matchesSearch = true; if (searches != null && searches.length > 0) { // Make sure the ROM name contains every token in the query final String lowerName = goodName.toLowerCase(Locale.US); for (final String search : searches) { if (search.length() > 0 && !lowerName.contains(search)) { matchesSearch = false; break; } } } if (matchesSearch) { final String romPath = config.get(md5, "romPath"); String zipPath = config.get(md5, "zipPath"); final String artFullPath = config.get(md5, "artPath"); String artPath = new File(artFullPath).getName(); artPath = mGlobalPrefs.coverArtDir + "/" + artPath; String crc = config.get(md5, "crc"); String headerName = config.get(md5, "headerName"); final String countryCodeString = config.get(md5, "countryCode"); byte countryCode = 0; //We can't really do much if the rompath is null if (romPath != null) { if (countryCodeString != null) { countryCode = Byte.parseByte(countryCodeString); } final String lastPlayedStr = config.get(md5, "lastPlayed"); String extracted = config.get(md5, "extracted"); if (zipPath == null || crc == null || headerName == null || countryCodeString == null || extracted == null) { final File file = new File(romPath); final RomHeader header = new RomHeader(file); zipPath = ""; crc = header.crc; headerName = header.name; countryCode = header.countryCode; extracted = "false"; config.put(md5, "zipPath", zipPath); config.put(md5, "crc", crc); config.put(md5, "headerName", headerName); config.put(md5, "countryCode", Byte.toString(countryCode)); config.put(md5, "extracted", extracted); } int lastPlayed = 0; if (lastPlayedStr != null) lastPlayed = Integer.parseInt(lastPlayedStr); final GalleryItem item = new GalleryItem(this, md5, crc, headerName, countryCode, goodName, romPath, zipPath, extracted.equals("true"), artPath, lastPlayed); items.add(item); if (mGlobalPrefs.isRecentShown && currentTime - item.lastPlayed <= 60 * 60 * 24 * 7) // 7 // days { recentItems.add(item); } // Delete any old files that already exist inside a zip // file else if (!zipPath.equals("") && extracted.equals("true")) { final File deleteFile = new File(romPath); deleteFile.delete(); config.put(md5, "extracted", "false"); } } } } } config.save(); Collections.sort(items, new GalleryItem.NameComparator()); if (recentItems != null) Collections.sort(recentItems, new GalleryItem.RecentlyPlayedComparator()); List<GalleryItem> combinedItems = items; if (mGlobalPrefs.isRecentShown && recentItems.size() > 0) { combinedItems = new ArrayList<>(); combinedItems.add(new GalleryItem(this, getString(R.string.galleryRecentlyPlayed))); combinedItems.addAll(recentItems); combinedItems.add(new GalleryItem(this, getString(R.string.galleryLibrary))); combinedItems.addAll(items); items = combinedItems; } mGalleryItems = items; mGridView.setAdapter(new GalleryItem.Adapter(this, items)); // Allow the headings to take up the entire width of the layout final List<GalleryItem> finalItems = items; final GridLayoutManager layoutManager = new GridLayoutManagerBetterScrolling(this, galleryColumns); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // Headings will take up every span (column) in the grid if (finalItems.get(position).isHeading) return galleryColumns; // Games will fit in a single column return 1; } }); mGridView.setLayoutManager(layoutManager); }
From source file:com.lottery.gui.MainLotteryForm.java
private void btnAddNumberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddNumberActionPerformed try {//from www .j a va 2 s. c om Integer number = Integer.parseInt(inputNumberTf.getText()); if (inputNumbers.contains(number)) { JOptionPane.showMessageDialog(this, "Number has already existed!"); return; } if (number > LotteryUtils.MAX_BALL_VALUE || number < LotteryUtils.MIN_BALL_VALUE) { JOptionPane.showMessageDialog(this, "Invalid range (" + LotteryUtils.MIN_BALL_VALUE + " - " + LotteryUtils.MAX_BALL_VALUE + ")!"); return; } JLabel numberLbl = new JLabel(number + ""); numberLbl.setOpaque(true); //numberLbl.setMinimumSize(new Dimension(100, 100)); // numberLbl.setPreferredSize(new Dimension(400, 100)); // numberLbl.setBackground(Color.white); numberLbl.setForeground(Color.red); setFont(numberLbl.getFont().deriveFont(150f)); numberLbl.setFont(new Font("Serif", Font.PLAIN, 30)); int numberOfInput = inputNumbers.size(); int row = numberOfInput / NO_NUMBER_PER_ROW; int col = numberOfInput % NO_NUMBER_PER_ROW; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = col; c.gridy = row; c.weightx = 0.5; ballNumbersPanel.add(numberLbl, c); lbNumbers.add(numberLbl); inputNumbers.add(number); ballNumbersPanel.revalidate(); ballNumbersPanel.repaint(); inputNumberTf.setText(""); inputNumberTf.requestFocusInWindow(); // // check if has winner // Date today = LotteryUtils.getNextDate(new Date()); // if (dbTicketTables.isEmpty()) { // dbTicketTables = ticketTableService.getByDate(today); // } totalDrawedNumbers++; checkCanAddNumber(); if (inputNumbers.size() < LotteryUtils.MAX_BALLS_PER_LINE) { return; } winTicketTables.addAll(LotteryUtils.getWinnerByLine(dbTicketTables, inputNumbers)); if (winTicketTables.size() > 0) { // update table list view refreshWinnerTable(); // JOptionPane.showMessageDialog(this, "Number of winner: " + winTicketTables.size()); } // check if has full table, then stop game if (totalDrawedNumbers >= (LotteryUtils.MAX_BALLS_PER_LINE * LotteryUtils.NO_LINES_PER_TABLE)) { Iterator<TicketTable> iter = winTicketTables.iterator(); while (iter.hasNext()) { TicketTable tmp = iter.next(); if (tmp.getWinType() == TicketTable.FULL_TABLE) { JOptionPane.showMessageDialog(this, "Got winner with full table!"); // save draw results, update ticket_table winner DrawResult drawResult = new DrawResult(); drawResult.setDrawDate(LotteryUtils.getDate(ftfDrawDate.getText().trim())); drawResult.setDrawBalls(StringUtils.join(inputNumbers, LotteryUtils.BALLS_SEPARATOR)); drawResult.setRound(Byte.parseByte((String) cbbRound.getSelectedItem())); drawResultService.updateWinner(drawResult, winTicketTables); restartGame(); return; } } } } catch (NumberFormatException ex) { LOGGER.error("Invalid number!: ", ex); JOptionPane.showMessageDialog(this, "Invalid number!"); } catch (ParseException ex) { LOGGER.error("Cant parse date", ex); JOptionPane.showMessageDialog(this, "Cant save result!"); } }
From source file:org.dasein.persist.PersistentCache.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype) throws PersistenceException { LookupDelegate delegate = getLookupDelegate(fieldName); if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) { throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid."); }/*from w ww .j ava 2 s. c o m*/ try { if (toType.equals(String.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof String)) { dataStoreValue = dataStoreValue.toString(); } } else if (Enum.class.isAssignableFrom(toType)) { if (dataStoreValue != null) { Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString()); dataStoreValue = e; } } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) { if (dataStoreValue == null) { dataStoreValue = false; } else if (!(dataStoreValue instanceof Boolean)) { if (Number.class.isAssignableFrom(dataStoreValue.getClass())) { dataStoreValue = (((Number) dataStoreValue).intValue() != 0); } else { dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true") || dataStoreValue.toString().trim().equalsIgnoreCase("y")); } } } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class) || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class) || toType.equals(float.class) || toType.equals(double.class)) { if (dataStoreValue == null) { if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) { dataStoreValue = 0; } else if (toType.equals(float.class) || toType.equals(double.class)) { dataStoreValue = 0.0f; } } else if (toType.equals(Number.class)) { if (!(dataStoreValue instanceof Number)) { if (dataStoreValue instanceof String) { try { dataStoreValue = Double.parseDouble((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException("Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } } else if (toType.equals(Integer.class) || toType.equals(int.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Integer)) { dataStoreValue = ((Number) dataStoreValue).intValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Integer.parseInt((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Long.class) || toType.equals(long.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Long)) { dataStoreValue = ((Number) dataStoreValue).longValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Long.parseLong((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Byte.class) || toType.equals(byte.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Byte)) { dataStoreValue = ((Number) dataStoreValue).byteValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Byte.parseByte((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Short.class) || toType.equals(short.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Short)) { dataStoreValue = ((Number) dataStoreValue).shortValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Short.parseShort((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Double.class) || toType.equals(double.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Double)) { dataStoreValue = ((Number) dataStoreValue).doubleValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Double.parseDouble((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Float.class) || toType.equals(float.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof Float)) { dataStoreValue = ((Number) dataStoreValue).floatValue(); } } else if (dataStoreValue instanceof String) { try { dataStoreValue = Float.parseFloat((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(BigDecimal.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof BigDecimal)) { if (dataStoreValue instanceof BigInteger) { dataStoreValue = new BigDecimal((BigInteger) dataStoreValue); } else { dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue()); } } } else if (dataStoreValue instanceof String) { try { dataStoreValue = new BigDecimal((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0)); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(BigInteger.class)) { if (dataStoreValue instanceof Number) { if (!(dataStoreValue instanceof BigInteger)) { if (dataStoreValue instanceof BigDecimal) { dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger(); } else { dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue()); } } } else if (dataStoreValue instanceof String) { try { dataStoreValue = new BigDecimal((String) dataStoreValue); } catch (NumberFormatException e) { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue instanceof Boolean) { dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0)); } else { throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (dataStoreValue != null) { logger.error("Type of dataStoreValue=" + dataStoreValue.getClass()); throw new PersistenceException( "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue); } } else if (toType.equals(Locale.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) { String[] parts = dataStoreValue.toString().split("_"); if (parts != null && parts.length > 1) { dataStoreValue = new Locale(parts[0], parts[1]); } else { dataStoreValue = new Locale(parts[0]); } } } else if (Measured.class.isAssignableFrom(toType)) { if (dataStoreValue != null && ptype != null) { if (Number.class.isAssignableFrom(dataStoreValue.getClass())) { Constructor<? extends Measured> constructor = null; double value = ((Number) dataStoreValue).doubleValue(); for (Constructor<?> c : toType.getDeclaredConstructors()) { Class[] args = c.getParameterTypes(); if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0]) && UnitOfMeasure.class.isAssignableFrom(args[1])) { constructor = (Constructor<? extends Measured>) c; break; } } if (constructor == null) { throw new PersistenceException("Unable to map with no proper constructor"); } dataStoreValue = constructor.newInstance(value, ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance()); } else if (!(dataStoreValue instanceof Measured)) { try { dataStoreValue = Double.parseDouble(dataStoreValue.toString()); } catch (NumberFormatException e) { Method method = null; for (Method m : toType.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) { if (m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(String.class)) { method = m; break; } } } if (method == null) { throw new PersistenceException("Don't know how to map " + dataStoreValue + " to " + toType + "<" + ptype + ">"); } dataStoreValue = method.invoke(null, dataStoreValue.toString()); } } // just because we converted it to a measured object above doesn't mean // we have the unit of measure right if (dataStoreValue instanceof Measured) { UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]) .newInstance(); if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) { dataStoreValue = ((Measured) dataStoreValue).convertTo( (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance()); } } } } else if (toType.equals(UUID.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) { dataStoreValue = UUID.fromString(dataStoreValue.toString()); } } else if (toType.equals(TimeZone.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) { dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString()); } } else if (toType.equals(Currency.class)) { if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) { dataStoreValue = Currency.getInstance(dataStoreValue.toString()); } } else if (toType.isArray()) { Class<?> t = toType.getComponentType(); if (dataStoreValue == null) { dataStoreValue = Array.newInstance(t, 0); } else if (dataStoreValue instanceof JSONArray) { JSONArray arr = (JSONArray) dataStoreValue; if (long.class.isAssignableFrom(t)) { long[] replacement = (long[]) Array.newInstance(long.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (int.class.isAssignableFrom(t)) { int[] replacement = (int[]) Array.newInstance(int.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (float.class.isAssignableFrom(t)) { float[] replacement = (float[]) Array.newInstance(float.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (double.class.isAssignableFrom(t)) { double[] replacement = (double[]) Array.newInstance(double.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else if (boolean.class.isAssignableFrom(t)) { boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } else { Object[] replacement = (Object[]) Array.newInstance(t, arr.length()); for (int i = 0; i < arr.length(); i++) { replacement[i] = mapValue(fieldName, arr.get(i), t, null); } dataStoreValue = replacement; } } else if (!dataStoreValue.getClass().isArray()) { logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to " + toType.getName()); logger.error("Value of " + fieldName + "=" + dataStoreValue); throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName()); } } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) { Annotation[] alist = toType.getDeclaredAnnotations(); boolean autoJSON = false; for (Annotation a : alist) { if (a instanceof AutoJSON) { autoJSON = true; } } if (autoJSON) { dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue); } else { try { Method m = toType.getDeclaredMethod("valueOf", JSONObject.class); dataStoreValue = m.invoke(null, dataStoreValue); } catch (NoSuchMethodException ignore) { try { Method m = toType.getDeclaredMethod("valueOf", String.class); if (m != null) { dataStoreValue = m.invoke(null, dataStoreValue.toString()); } else { throw new PersistenceException( "No valueOf() field in " + toType + " for mapping " + fieldName); } } catch (NoSuchMethodException e) { throw new PersistenceException("No valueOf() field in " + toType + " for mapping " + fieldName + " with " + dataStoreValue + ": (" + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")"); } } } } } catch (Exception e) { String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage(); logger.error(err, e); throw new PersistenceException(); } return dataStoreValue; }