List of usage examples for java.lang Byte Byte
@Deprecated(since = "9") public Byte(String s) throws NumberFormatException
From source file:javadz.beanutils.converters.NumberConverter.java
/** * Convert any Number object to the specified type for this * <i>Converter</i>./*from www . ja v a 2 s .c o m*/ * <p> * This method handles conversion to the following types: * <ul> * <li><code>java.lang.Byte</code></li> * <li><code>java.lang.Short</code></li> * <li><code>java.lang.Integer</code></li> * <li><code>java.lang.Long</code></li> * <li><code>java.lang.Float</code></li> * <li><code>java.lang.Double</code></li> * <li><code>java.math.BigDecimal</code></li> * <li><code>java.math.BigInteger</code></li> * </ul> * @param sourceType The type being converted from * @param targetType The Number type to convert to * @param value The Number to convert. * * @return The converted value. */ private Number toNumber(Class sourceType, Class targetType, Number value) { // Correct Number type already if (targetType.equals(value.getClass())) { return value; } // Byte if (targetType.equals(Byte.class)) { long longValue = value.longValue(); if (longValue > Byte.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Byte.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Byte(value.byteValue()); } // Short if (targetType.equals(Short.class)) { long longValue = value.longValue(); if (longValue > Short.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Short.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Short(value.shortValue()); } // Integer if (targetType.equals(Integer.class)) { long longValue = value.longValue(); if (longValue > Integer.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Integer.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Integer(value.intValue()); } // Long if (targetType.equals(Long.class)) { return new Long(value.longValue()); } // Float if (targetType.equals(Float.class)) { if (value.doubleValue() > Float.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } return new Float(value.floatValue()); } // Double if (targetType.equals(Double.class)) { return new Double(value.doubleValue()); } // BigDecimal if (targetType.equals(BigDecimal.class)) { if (value instanceof Float || value instanceof Double) { return new BigDecimal(value.toString()); } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else { return BigDecimal.valueOf(value.longValue()); } } // BigInteger if (targetType.equals(BigInteger.class)) { if (value instanceof BigDecimal) { return ((BigDecimal) value).toBigInteger(); } else { return BigInteger.valueOf(value.longValue()); } } String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'"; if (log().isWarnEnabled()) { log().warn(" " + msg); } throw new ConversionException(msg); }
From source file:com.appglu.impl.CrudTemplateTest.java
@Test public void readAllDataTypes() { mockServer.expect(requestTo("http://localhost/appglu/v1/tables/data_types/1?expand_relationships=false")) .andExpect(method(HttpMethod.GET)).andRespond(withSuccess() .body(compactedJson("data/crud_read_all_data_types")).headers(responseHeaders)); Row row = crudOperations.read("data_types", 1); String string = new String("a very long string for test"); Assert.assertEquals(new Boolean(true), row.getBoolean("boolean")); Assert.assertEquals(new Short((short) 1), row.getShort("short")); Assert.assertEquals(new Byte((byte) 2), row.getByte("byte")); Assert.assertEquals(string, new String(row.getByteArray("byteArray"))); Assert.assertEquals(new Float(1.5f), row.getFloat("float")); Assert.assertEquals(new Double(1.5f), row.getDouble("float")); Assert.assertEquals(new Double(7.5d), row.getDouble("double")); Assert.assertEquals(new Integer(10), row.getInt("integer")); Assert.assertEquals(new Long(10), row.getLong("integer")); Assert.assertEquals(new Long(21474836475L), row.getLong("long")); Assert.assertEquals(new BigInteger("10"), row.getBigInteger("integer")); Assert.assertEquals(new BigInteger("21474836475"), row.getBigInteger("long")); Assert.assertEquals(new BigInteger("9223372036854775807123"), row.getBigInteger("bigInteger")); Assert.assertEquals(string, row.getString("string")); Assert.assertEquals("2010-01-15T12:10:00+0000", DateUtils.formatDatetime(row.getDate("datetime"))); Assert.assertEquals("1970-01-01T12:10:00+0000", DateUtils.formatDatetime(row.getDate("time"))); Assert.assertEquals("2010-01-15T00:00:00+0000", DateUtils.formatDatetime(row.getDate("date"))); mockServer.verify();//from w w w . j a va 2s .c o m }
From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java
/** * Convert a string to a primitive type. * @param object String/*ww w. j av a2s. com*/ * @param toType destination class * @return wrapper */ protected Object convertStringToPrimitive(Object object, Class toType) { toType = TypeUtils.wrapPrimitive(toType); if (toType == Boolean.class) { return Boolean.valueOf((String) object); } if (toType == Character.class) { return new Character(((String) object).charAt(0)); } if (toType == Byte.class) { return new Byte((String) object); } if (toType == Short.class) { if ("".equals(object)) return null; else return new Short((String) object); } if (toType == Integer.class) { if ("".equals(object)) return null; else return new Integer((String) object); } if (toType == Long.class) { if ("".equals(object)) return null; else return new Long((String) object); } if (toType == Float.class) { if ("".equals(object)) return null; else return new Float((String) object); } if (toType == Double.class) { if ("".equals(object)) return null; else return new Double((String) object); } return null; }
From source file:HexFormat.java
/** * Parse a hex number into a Number object. Hexadecimal numbers may be * indicated with a leading character designation of '0x'. If up to 1 byte * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed, * return a Short. If more than 2 and up to 4 bytes are parsed, return an * Integer. If more than 4 and up to 8 bytes are parsed, return a Long. * /* ww w. j a va2s . c o m*/ * @param text * a hexadecimal number * @param parsePosition * position to start parsing from * @return return an integer form of Number object if parse is successful; * <CODE>null</CODE> otherwise * * @since 1.0 */ public Number parse(String text, ParsePosition parsePosition) { boolean skipWhitespace = true; int startIndex, nibbles; // remove whitespace StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex()); for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) { if (skipWhitespace && Character.isWhitespace(c)) { // skip whitespace continue; } break; } // skip a leading hex designation of the characters '0x' if (text.regionMatches(iter.getIndex(), "0x", 0, 2)) { parsePosition.setIndex(iter.getIndex() + 2); } else { parsePosition.setIndex(iter.getIndex()); } startIndex = parsePosition.getIndex(); Number result = (Number) parseObject(text, parsePosition); if (result == null) { return (result); } nibbles = parsePosition.getIndex() - startIndex; if (nibbles <= 2) { result = new Byte(result.byteValue()); } else if (nibbles <= 4) { result = new Short(result.shortValue()); } else if (nibbles <= 8) { result = new Integer(result.intValue()); } else if (nibbles <= 16) { result = new Long(result.longValue()); } return (result); }
From source file:org.objectstyle.cayenne.dataview.DataTypeSpec.java
public Object fromDataType(Class untypedValueClass, DataTypeEnum dataType, Object typedValue) { if (typedValue == null) return null; Class dataTypeClass = getJavaClass(dataType); // Validate.isTrue(typedValue.getClass().equals(dataTypeClass)); if (untypedValueClass == null) return typedValue; if (ClassUtils.isAssignable(dataTypeClass, untypedValueClass)) return typedValue; String strTypedValue = null;/* w ww . j ava 2 s . c o m*/ boolean isStringTypedValue; Number numTypedValue = null; boolean isNumberTypedValue; Boolean boolTypedValue = null; boolean isBooleanTypedValue; Date dateTypedValue = null; boolean isDateTypedValue; if (isStringTypedValue = typedValue instanceof String) strTypedValue = (String) typedValue; if (isNumberTypedValue = typedValue instanceof Number) numTypedValue = (Number) typedValue; if (isBooleanTypedValue = typedValue instanceof Boolean) boolTypedValue = (Boolean) typedValue; if (isDateTypedValue = typedValue instanceof Date) dateTypedValue = (Date) typedValue; Object v = null; if (String.class.equals(untypedValueClass)) { v = ObjectUtils.toString(typedValue); } else if (BigDecimal.class.equals(untypedValueClass)) { if (isStringTypedValue) v = NumberUtils.createBigDecimal(strTypedValue); else if (isNumberTypedValue) v = new BigDecimal(numTypedValue.doubleValue()); else if (isBooleanTypedValue) v = new BigDecimal(BooleanUtils.toInteger(boolTypedValue.booleanValue())); else if (isDateTypedValue) v = new BigDecimal(dateTypedValue.getTime()); } else if (Boolean.class.equals(untypedValueClass)) { if (isStringTypedValue) v = BooleanUtils.toBooleanObject(strTypedValue); else if (isNumberTypedValue) v = BooleanUtils.toBooleanObject(numTypedValue.intValue()); else if (isDateTypedValue) v = BooleanUtils.toBooleanObject((int) dateTypedValue.getTime()); } else if (Byte.class.equals(untypedValueClass)) { if (isStringTypedValue) v = Byte.valueOf(strTypedValue); else if (isNumberTypedValue) v = new Byte(numTypedValue.byteValue()); else if (isBooleanTypedValue) v = new Byte((byte) BooleanUtils.toInteger(boolTypedValue.booleanValue())); else if (isDateTypedValue) v = new Byte((byte) dateTypedValue.getTime()); } else if (byte[].class.equals(untypedValueClass)) { if (isStringTypedValue) v = strTypedValue.getBytes(); } else if (Double.class.equals(untypedValueClass)) { if (isStringTypedValue) v = NumberUtils.createDouble(strTypedValue); else if (isNumberTypedValue) v = new Double(numTypedValue.doubleValue()); else if (isBooleanTypedValue) v = new Double(BooleanUtils.toInteger(boolTypedValue.booleanValue())); else if (isDateTypedValue) v = new Double(dateTypedValue.getTime()); } else if (Float.class.equals(untypedValueClass)) { if (isStringTypedValue) v = NumberUtils.createFloat(strTypedValue); else if (isNumberTypedValue) v = new Float(numTypedValue.floatValue()); else if (isBooleanTypedValue) v = new Float(BooleanUtils.toInteger(boolTypedValue.booleanValue())); else if (isDateTypedValue) v = new Float(dateTypedValue.getTime()); } else if (Integer.class.equals(untypedValueClass)) { if (isStringTypedValue) v = NumberUtils.createInteger(strTypedValue); else if (isNumberTypedValue) v = new Integer(numTypedValue.intValue()); else if (isBooleanTypedValue) v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue()); else if (isDateTypedValue) v = new Integer((int) dateTypedValue.getTime()); } else if (Long.class.equals(untypedValueClass)) { if (isStringTypedValue) v = NumberUtils.createLong(strTypedValue); else if (isNumberTypedValue) v = new Long(numTypedValue.longValue()); else if (isBooleanTypedValue) v = new Long(BooleanUtils.toInteger(boolTypedValue.booleanValue())); else if (isDateTypedValue) v = new Long(dateTypedValue.getTime()); } else if (java.sql.Date.class.equals(untypedValueClass)) { if (isNumberTypedValue) v = new java.sql.Date(numTypedValue.longValue()); else if (isDateTypedValue) v = new java.sql.Date(dateTypedValue.getTime()); } else if (java.sql.Time.class.equals(untypedValueClass)) { if (isNumberTypedValue) v = new java.sql.Time(numTypedValue.longValue()); else if (isDateTypedValue) v = new java.sql.Time(dateTypedValue.getTime()); } else if (java.sql.Timestamp.class.equals(untypedValueClass)) { if (isNumberTypedValue) v = new java.sql.Timestamp(numTypedValue.longValue()); else if (isDateTypedValue) v = new java.sql.Timestamp(dateTypedValue.getTime()); } else if (Date.class.equals(untypedValueClass)) { if (isNumberTypedValue) v = new Date(numTypedValue.longValue()); } return v; }
From source file:org.floggy.synchronization.jme.core.impl.JSONSerializationManagerTest.java
/** * DOCUMENT ME!/*from w w w . jav a 2s .c om*/ * * @throws Exception DOCUMENT ME! */ public void testSendByteNotNull() throws Exception { JSONStringer stringer = new JSONStringer(); String name = "firstName"; Byte value = new Byte((byte) 12); stringer.object(); JSONSerializationManager.send(name, value, stringer); stringer.endObject(); String expected = "{\"" + name + "\":" + value + "}"; assertEquals(expected, stringer.toString()); }
From source file:com.jilk.ros.rosbridge.implementation.JSON.java
public static Object convertJSONPrimitiveToPrimitive(Object o, Class c) { Object result = o;/*from w w w . ja v a 2s.c o m*/ if (c.isPrimitive() || Number.class.isAssignableFrom(c)) { if (c.equals(double.class) || c.equals(Double.class)) result = new Double(((Number) o).doubleValue()); else if (c.equals(float.class) || c.equals(Float.class)) result = new Float(((Number) o).floatValue()); else if (c.equals(long.class) || c.equals(Long.class)) result = new Long(((Number) o).longValue()); else if (int.class.equals(c) || c.equals(Integer.class)) result = new Integer(((Number) o).intValue()); else if (c.equals(short.class) || c.equals(Short.class)) result = new Short(((Number) o).shortValue()); else if (c.equals(byte.class) || c.equals(Byte.class)) result = new Byte(((Number) o).byteValue()); } return result; }
From source file:edu.utah.further.core.api.collections.ArrayUtil.java
/** * Print a matrix in a grid format.// ww w. ja v a 2s.c o m * * @param matrix * data matrix * @param separator * entry separator * @param labels * column labels. If <code>null</code>, ignored * @param columnSize * size of each column (not including the separator) * @return textual representation of the matrix */ public static String toString(final byte[][] matrix, final String separator, final String[] labels, final int columnSize) { final String labelFormat = "%-" + columnSize + "s"; final String entryFormat = "%-" + columnSize + "d"; final StringBuilder builder = StringUtil.newStringBuilder(); final int columnDimension = matrix[0].length; if (labels != null) { for (int j = 0; j < matrix[0].length; j++) { builder.append(String.format(labelFormat, labels[j])); builder.append(separator); } } builder.append(Strings.NEW_LINE_STRING); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { builder.append(String.format(entryFormat, new Byte(matrix[i][j]))); // builder.append(matrix[i][j]); if (j < columnDimension - 1) { builder.append(separator); } } builder.append(Strings.NEW_LINE_STRING); } return builder.toString(); }
From source file:com.itelis.worker.dev.template.service.JRXmlDataSource.java
protected Object convertNumber(Number number, Class valueClass) throws JRException { Number value = null;//w w w . j av a2s.c om if (valueClass.equals(Byte.class)) { value = new Byte(number.byteValue()); } else if (valueClass.equals(Short.class)) { value = new Short(number.shortValue()); } else if (valueClass.equals(Integer.class)) { value = new Integer(number.intValue()); } else if (valueClass.equals(Long.class)) { value = new Long(number.longValue()); } else if (valueClass.equals(Float.class)) { value = new Float(number.floatValue()); } else if (valueClass.equals(Double.class)) { value = new Double(number.doubleValue()); } else if (valueClass.equals(BigInteger.class)) { value = BigInteger.valueOf(number.longValue()); } else if (valueClass.equals(BigDecimal.class)) { value = new BigDecimal(Double.toString(number.doubleValue())); } else { throw new JRException("Unknown number class " + valueClass.getName()); } return value; }
From source file:org.openmrs.module.spreadsheetimport.SpreadsheetImportUtil.java
public static File importTemplate(SpreadsheetImportTemplate template, MultipartFile file, String sheetName, List<String> messages, boolean rollbackTransaction) throws Exception { if (file.isEmpty()) { messages.add("file must not be empty"); return null; }// w w w . j a va 2 s . com // Open file Workbook wb = WorkbookFactory.create(file.getInputStream()); Sheet sheet; if (!StringUtils.hasText(sheetName)) { sheet = wb.getSheetAt(0); } else { sheet = wb.getSheet(sheetName); } // Header row Row firstRow = sheet.getRow(0); if (firstRow == null) { messages.add("Spreadsheet header row must not be null"); return null; } List<String> columnNames = new Vector<String>(); for (Cell cell : firstRow) { columnNames.add(cell.getStringCellValue()); } if (log.isDebugEnabled()) { log.debug("Column names: " + columnNames.toString()); } // Required column names List<String> columnNamesOnlyInTemplate = new Vector<String>(); columnNamesOnlyInTemplate.addAll(template.getColumnNamesAsList()); columnNamesOnlyInTemplate.removeAll(columnNames); if (columnNamesOnlyInTemplate.isEmpty() == false) { messages.add("required column names not present: " + toString(columnNamesOnlyInTemplate)); return null; } // Extra column names? List<String> columnNamesOnlyInSheet = new Vector<String>(); columnNamesOnlyInSheet.addAll(columnNames); columnNamesOnlyInSheet.removeAll(template.getColumnNamesAsList()); if (columnNamesOnlyInSheet.isEmpty() == false) { messages.add( "Extra column names present, these will not be processed: " + toString(columnNamesOnlyInSheet)); } // Process rows boolean skipThisRow = true; for (Row row : sheet) { if (skipThisRow == true) { skipThisRow = false; } else { boolean rowHasData = false; Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData = template .getMapOfUniqueImportToColumnSetSortedByImportIdx(); for (UniqueImport uniqueImport : rowData.keySet()) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { int idx = columnNames.indexOf(column.getName()); Cell cell = row.getCell(idx); Object value = null; // check for empty cell (new Encounter) if (cell == null) { rowHasData = true; column.setValue(""); continue; } switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: value = new Boolean(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: value = new Byte(cell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { java.util.Date date = cell.getDateCellValue(); value = "'" + new java.sql.Timestamp(date.getTime()).toString() + "'"; } else { value = cell.getNumericCellValue(); } break; case Cell.CELL_TYPE_STRING: // Escape for SQL value = "'" + cell.getRichStringCellValue() + "'"; break; } if (value != null) { rowHasData = true; column.setValue(value); } else column.setValue(""); } } for (UniqueImport uniqueImport : rowData.keySet()) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); boolean isFirst = true; for (SpreadsheetImportTemplateColumn column : columnSet) { if (isFirst) { // Should be same for all columns in unique import // System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size()); if (column.getColumnPrespecifiedValues().size() > 0) { Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column .getColumnPrespecifiedValues(); for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) { // System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue()); } } } } } if (rowHasData) { Exception exception = null; try { DatabaseBackend.validateData(rowData); String encounterId = DatabaseBackend.importData(rowData, rollbackTransaction); if (encounterId != null) { for (UniqueImport uniqueImport : rowData.keySet()) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { if ("encounter".equals(column.getTableName())) { int idx = columnNames.indexOf(column.getName()); Cell cell = row.getCell(idx); if (cell == null) cell = row.createCell(idx); cell.setCellValue(encounterId); } } } } } catch (SpreadsheetImportTemplateValidationException e) { messages.add("Validation failed: " + e.getMessage()); return null; } catch (SpreadsheetImportDuplicateValueException e) { messages.add("found duplicate value for column " + e.getColumn().getName() + " with value " + e.getColumn().getValue()); return null; } catch (SpreadsheetImportSQLSyntaxException e) { messages.add("SQL syntax error: \"" + e.getSqlErrorMessage() + "\".<br/>Attempted SQL Statement: \"" + e.getSqlStatement() + "\""); return null; } catch (Exception e) { exception = e; } if (exception != null) { throw exception; } } } } // write back Excel file to a temp location File returnFile = File.createTempFile("sim", ".xls"); FileOutputStream fos = new FileOutputStream(returnFile); wb.write(fos); fos.close(); return returnFile; }