List of usage examples for java.lang Byte parseByte
public static byte parseByte(String s) throws NumberFormatException
From source file:org.tupelo_schneck.electric.Options.java
/** Returns true if program should continue */ public boolean parseOptions(String[] args) throws IOException { // create the parser CommandLineParser parser = new GnuParser(); CommandLine cmd = null;//from www. j a v a2s. com FileConfig config = null; OptionWrapper options = null; boolean showUsageAndExit = false; boolean listSerialPortsAndExit = false; boolean hasDbFilename = true; try { // parse the command line arguments cmd = parser.parse(this, args); } catch (ParseException exp) { // oops, something went wrong System.err.println(exp.getMessage()); showUsageAndExit = true; } if (cmd == null) { showUsageAndExit = true; } else { try { if (cmd.hasOption("config-file")) { String optionFileName = cmd.getOptionValue("config-file"); try { config = new FileConfig(optionFileName); } catch (IOException exp) { System.err.println(exp.getMessage()); showUsageAndExit = true; } } options = new OptionWrapper(cmd, config); hasDbFilename = true; if (options.hasOption("database-directory", "d")) { dbFilename = options.getOptionValue("database-directory", "d"); } else if (cmd.getArgs().length == 1) { dbFilename = cmd.getArgs()[0]; } else { hasDbFilename = false; } if (config == null && hasDbFilename) { File defaultConfigFile = new File(dbFilename, ITS_ELECTRIC_PROPERTIES); if (defaultConfigFile.exists()) { try { config = new FileConfig(defaultConfigFile.getAbsolutePath()); } catch (IOException exp) { System.err.println(exp.getMessage()); showUsageAndExit = true; } options = new OptionWrapper(cmd, config); } } if (options.hasOption("no-serve", null)) { serve = !optionalBoolean(options, "no-serve", null, false); } if (options.hasOption("no-record", null)) { record = !optionalBoolean(options, "no-record", null, false); } boolean recordChanged = false; boolean serveChanged = false; if (options.hasOption("time-zone", null)) { String input = options.getOptionValue("time-zone", null); input = convertISO8601TimeZone(input); recordTimeZone = TimeZone.getTimeZone(input); serveTimeZone = TimeZone.getTimeZone(input); recordChanged = true; serveChanged = true; } if (options.hasOption("serve-time-zone", null)) { String input = options.getOptionValue("serve-time-zone", null); input = convertISO8601TimeZone(input); serveTimeZone = TimeZone.getTimeZone(input); serveChanged = true; } if (options.hasOption("ted-no-dst", null)) { if (optionalBoolean(options, "ted-no-dst", null, false)) { int offset = serveTimeZone.getRawOffset(); boolean negative = offset < 0; if (negative) offset = -offset; int hours = offset / 3600000; offset = offset - 3600000 * hours; int minutes = offset / 60000; String input = "GMT" + (negative ? "-" : "+") + (hours < 10 ? "0" : "") + hours + (minutes < 10 ? "0" : "") + minutes; recordTimeZone = TimeZone.getTimeZone(input); recordChanged = true; } } if (options.hasOption("record-time-zone", null)) { String input = options.getOptionValue("record-time-zone", null); input = convertISO8601TimeZone(input); recordTimeZone = TimeZone.getTimeZone(input); recordChanged = true; } if (recordChanged) log.info("Record Time Zone: " + TimeZone.getCanonicalID(recordTimeZone.getID()) + ", " + recordTimeZone.getDisplayName()); if (serveChanged) log.info("Serve Time Zone: " + TimeZone.getCanonicalID(serveTimeZone.getID()) + ", " + serveTimeZone.getDisplayName()); if (options.hasOption("export", null)) { serve = false; record = false; export = true; String[] vals = options.getOptionValues("export", null); startTime = Util.timestampFromUserInput(vals[0], false, serveTimeZone); endTime = Util.timestampFromUserInput(vals[1], true, serveTimeZone); resolution = Integer.parseInt(vals[2]); } if (options.hasOption("export-style", null)) { exportByMTU = !options.getOptionValue("export-style", null).trim().toLowerCase() .equals("timestamp"); } if (options.hasOption("delete-until", null)) { deleteUntil = Util.timestampFromUserInput(options.getOptionValue("delete-until", null), false, serveTimeZone); } if (options.hasOption("port", "p")) { String val = options.getOptionValue("port", "p"); if (val.equals("none")) { serve = false; } else { port = Integer.parseInt(val); if (port <= 0) showUsageAndExit = true; } } if (options.hasOption("gateway-url", "g")) { tedOptions = true; gatewayURL = options.getOptionValue("gateway-url", "g"); if (gatewayURL.equals("none")) record = false; } if (options.hasOption("mtus", "m")) { tedOptions = true; mtus = Byte.parseByte(options.getOptionValue("mtus", "m")); if (mtus <= 0 || mtus > 4) showUsageAndExit = true; } if (options.hasOption("username", "u")) { tedOptions = true; username = options.getOptionValue("username", "u"); } if (options.hasOption("num-points", "n")) { numDataPoints = Integer.parseInt(options.getOptionValue("num-points", "n")); if (numDataPoints <= 0) showUsageAndExit = true; } if (options.hasOption("max-points", "x")) { maxDataPoints = Integer.parseInt(options.getOptionValue("max-points", "x")); if (maxDataPoints <= 0) showUsageAndExit = true; } if (options.hasOption("import-interval", "i")) { tedOptions = true; importInterval = Integer.parseInt(options.getOptionValue("import-interval", "i")); if (importInterval < 0) showUsageAndExit = true; } if (options.hasOption("import-overlap", "o")) { tedOptions = true; importOverlap = Integer.parseInt(options.getOptionValue("import-overlap", "o")); if (importOverlap < 0) showUsageAndExit = true; } if (options.hasOption("long-import-interval", "e")) { tedOptions = true; longImportInterval = Integer.parseInt(options.getOptionValue("long-import-interval", "e")); if (longImportInterval < 0) showUsageAndExit = true; } if (options.hasOption("server-log", "l")) { serverLogFilename = options.getOptionValue("server-log", "l"); } if (options.hasOption("voltage", "v")) { tedOptions = true; voltage = optionalBoolean(options, "voltage", "v", false); } if (options.hasOption("volt-ampere-import-interval", "k")) { tedOptions = true; double value = Double.parseDouble(options.getOptionValue("volt-ampere-import-interval", "k")); voltAmpereImportIntervalMS = (long) (1000 * value); if (voltAmpereImportIntervalMS < 0) showUsageAndExit = true; } if (options.hasOption("volt-ampere-threads", null)) { tedOptions = true; kvaThreads = Integer.parseInt(options.getOptionValue("volt-ampere-threads", null)); if (kvaThreads < 0) showUsageAndExit = true; } if (options.hasOption("cc-port-name", null)) { ccOptions = true; ccPortName = options.getOptionValue("cc-port-name", null); } if (options.hasOption("cc-max-sensor", null)) { ccOptions = true; ccMaxSensor = Integer.parseInt(options.getOptionValue("cc-max-sensor", null)); } if (options.hasOption("cc-separate-clamps", null)) { ccOptions = true; ccSumClamps = !optionalBoolean(options, "cc-separate-clamps", null, false); } if (options.hasOption("cc-num-clamps", null)) { ccOptions = true; ccNumberOfClamps = Integer.parseInt(options.getOptionValue("cc-num-clamps", null)); } if (options.hasOption("help", "h")) { showUsageAndExit = true; } if (options.hasOption("cc-list-serial-ports", null)) { listSerialPortsAndExit = true; } } catch (NumberFormatException e) { System.err.println(e.getMessage()); showUsageAndExit = true; } } if (!hasDbFilename && !listSerialPortsAndExit) { showUsageAndExit = true; } else if (!serve && !record && !export && deleteUntil == 0 && !listSerialPortsAndExit) { showUsageAndExit = true; } if (ccOptions && tedOptions) { System.out.println("Cannot combine TED and Current Cost options."); showUsageAndExit = true; } else if (ccOptions && ccPortName == null) { System.out.println("Current Cost use requires --cc-port-name."); showUsageAndExit = true; } if (showUsageAndExit) { showUsage(); return false; } else if (listSerialPortsAndExit) { CurrentCostImporter.printSerialPortNames(); return false; } else { if (record && username != null) { readAndProcessPassword(); } confirmDeleteUntil(); return true; } }
From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java
/** * Check that an input string is loadable as a certain SPARQL data type, and tweak it if necessary. * Throws exception if not.//from w ww. j a v a 2 s. c o m * Expects to only get the last part of the type, e.g. "float" */ @SuppressWarnings("deprecation") public static String validateDataType(String input, String expectedSparqlGraphType) throws Exception { // from the XSD data types: // string | boolean | decimal | int | integer | negativeInteger | nonNegativeInteger | // positiveInteger | nonPositiveInteger | long | float | double | duration | // dateTime | time | date | unsignedByte | unsignedInt | anySimpleType | // gYearMonth | gYear | gMonthDay; // added for the runtimeConstraint: // NODE_URI /** * Please keep the wiki up to date * https://github.com/ge-semtk/semtk/wiki/Ingestion-type-handling */ String ret = input; if (expectedSparqlGraphType.equalsIgnoreCase("string")) { } else if (expectedSparqlGraphType.equalsIgnoreCase("boolean")) { try { Boolean.parseBoolean(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("decimal")) { try { Double.parseDouble(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("int")) { try { Integer.parseInt(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("integer")) { try { Integer.parseInt(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("negativeInteger")) { try { int test = Integer.parseInt(input); if (test >= 0) { throw new Exception("value in model is negative integer. non-negative integer given as input"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("nonNegativeInteger")) { try { int test = Integer.parseInt(input); if (test < 0) { throw new Exception("value in model is nonnegative integer. negative integer given as input"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("positiveInteger")) { try { int test = Integer.parseInt(input); if (test <= 0) { throw new Exception("value in model is positive integer. integer <= 0 given as input"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("nonPositiveInteger")) { try { int test = Integer.parseInt(input); if (test > 0) { throw new Exception("value in model is nonpositive integer. integer > 0 given as input"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("long")) { try { long test = Long.parseLong(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("float")) { try { float test = Float.parseFloat(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("double")) { try { double test = Double.parseDouble(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("duration")) { // not sure how to check this one. this might not match the expectation from SADL try { Duration.parse(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("dateTime")) { try { return Utility.getSPARQLDateTimeString(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("time")) { try { Time.parse(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("date")) { try { return Utility.getSPARQLDateString(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("unsignedByte")) { try { Byte.parseByte(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("unsignedint")) { try { Integer.parseUnsignedInt(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("anySimpleType")) { // do nothing. } else if (expectedSparqlGraphType.equalsIgnoreCase("gYearMonth")) { try { String[] all = input.split("-"); // check them all if (all.length != 2) { throw new Exception("year-month did not have two parts."); } if (all[0].length() != 4 && all[1].length() != 2) { throw new Exception("year-month format was wrong. " + input + " given was not YYYY-MM"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("gYear")) { try { if (input.length() != 4) { throw new Exception("year-month format was wrong. " + input + " given was not YYYY-MM"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("gMonthDay")) { try { String[] all = input.split("-"); // check them all if (all.length != 2) { throw new Exception("month-day did not have two parts."); } if (all[0].length() != 2 && all[1].length() != 2) { throw new Exception("month-day format was wrong. " + input + " given was not MM-dd"); } } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause:" + e.getMessage()); } } else if (expectedSparqlGraphType.equalsIgnoreCase("NODE_URI")) { try { // check that this looks like a URI URI uri = new URI(input); } catch (Exception e) { throw new Exception("attempt to use value \"" + input + "\" as type \"" + expectedSparqlGraphType + "\" failed. assumed cause: " + e.getMessage()); } } else { // assume it is cool for now. } return ret; }
From source file:com.hzc.framework.ssh.controller.WebUtil.java
/** * jsonp?/*from ww w . j ava2 s . c o m*/ * + ? * * @param path * @param ufc * @return * @throws Exception */ public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc, final ProgressListener pl) throws RuntimeException { try { HttpServletRequest request = getReq(); // final HttpSession session = getSession(); ServletContext servletContext = getServletContext(); File file = new File(servletContext.getRealPath(path)); if (!file.exists()) file.mkdir(); DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); upload.setProgressListener(pl); List<FileItem> fileItems = upload.parseRequest(request); T obj = c.newInstance(); Field[] declaredFields = c.getDeclaredFields(); for (FileItem item : fileItems) { if (!item.isFormField()) { String name = item.getName(); String type = item.getContentType(); if (StringUtils.isNotBlank(name)) { File f = new File(file + File.separator + name); item.write(f); ufc.file(obj, f, name, name, item.getSize(), type); // ???? } } else { String name = item.getFieldName(); // ??,?? for (Field field : declaredFields) { field.setAccessible(true); String fieldName = field.getName(); if (name.equals(fieldName)) { String value = item.getString("UTF-8"); if (null == value) { continue; } Class<?> type = field.getType(); if (type == Long.class) { field.set(obj, Long.parseLong(value)); } else if (type == String.class) { field.set(obj, value); } else if (type == Byte.class) { field.set(obj, Byte.parseByte(value)); } else if (type == Integer.class) { field.set(obj, Integer.parseInt(value)); } else if (type == Character.class) { field.set(obj, value.charAt(0)); } else if (type == Boolean.class) { field.set(obj, Boolean.parseBoolean(value)); } else if (type == Double.class) { field.set(obj, Double.parseDouble(value)); } else if (type == Float.class) { field.set(obj, Float.parseFloat(value)); } } } } } return obj; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.axis2.databinding.utils.ConverterUtil.java
public static byte convertToByte(String s) { if ((s == null) || s.equals("")) { return Byte.MIN_VALUE; }/*from w w w. jav a 2 s . c om*/ return Byte.parseByte(s); }
From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java
/** * Parses the.//from w ww . ja v a 2s .c om * * @param <T> the generic type * @param cls the cls * @param value the value * @return the t * @throws java.text.ParseException the parse exception */ @SuppressWarnings("unchecked") public static <T> T parse(Class<T> cls, String value) throws ParseException { if (cls.isEnum()) { final Map<Class<?>, Map<String, String>> member = SCHEMA_TO_ENUM_DICTIONARIES.getMember(); String val = value; final Map<String, String> stringToEnumDict = member.get(cls); if (stringToEnumDict != null) { final String strEnumName = stringToEnumDict.get(value); if (strEnumName != null) { val = strEnumName; } } for (T o : cls.getEnumConstants()) { if (o.toString().equals(val)) { return o; } } return null; } else if (Number.class.isAssignableFrom(cls)) { if (Double.class.isAssignableFrom(cls)) { return (T) ((Double) Double.parseDouble(value)); } else if (Integer.class.isAssignableFrom(cls)) { return (T) ((Integer) Integer.parseInt(value)); } else if (Long.class.isAssignableFrom(cls)) { return (T) ((Long) Long.parseLong(value)); } else if (Float.class.isAssignableFrom(cls)) { return (T) ((Float) Float.parseFloat(value)); } else if (Byte.class.isAssignableFrom(cls)) { return (T) ((Byte) Byte.parseByte(value)); } else if (Short.class.isAssignableFrom(cls)) { return (T) ((Short) Short.parseShort(value)); } else if (BigInteger.class.isAssignableFrom(cls)) { return (T) (new BigInteger(value)); } else if (BigDecimal.class.isAssignableFrom(cls)) { return (T) (new BigDecimal(value)); } } else if (Date.class.isAssignableFrom(cls)) { DateFormat df = createDateFormat(XML_SCHEMA_DATE_TIME_FORMAT); return (T) df.parse(value); } else if (Boolean.class.isAssignableFrom(cls)) { return (T) ((Boolean) Boolean.parseBoolean(value)); } else if (String.class.isAssignableFrom(cls)) { return (T) value; } return null; }
From source file:weave.servlets.WeaveServlet.java
/** * Tries to convert value to the given type. * @param value The value to cast to a new type. * @param type The desired type.//from ww w.jav a 2 s . c o m * @return The value, which may have been cast as the new type. */ protected Object cast(Object value, Class<?> type) throws RemoteException { if (type.isInstance(value)) return value; try { if (value == null) // null -> NaN { if (type == double.class || type == Double.class) value = Double.NaN; else if (type == float.class || type == Float.class) value = Float.NaN; return value; } if (value instanceof Map) // Map -> Java Bean { Object bean = type.newInstance(); for (Field field : type.getFields()) { Object fieldValue = ((Map<?, ?>) value).get(field.getName()); fieldValue = cast(fieldValue, field.getType()); field.set(bean, fieldValue); } return bean; } if (type.isArray()) // ? -> T[] { if (value instanceof String) // String -> String[] value = CSVParser.defaultParser.parseCSVRow((String) value, true); if (value instanceof List) // List -> Object[] value = ((List<?>) value).toArray(); if (value.getClass().isArray()) // T1[] -> T2[] { int n = Array.getLength(value); Class<?> itemType = type.getComponentType(); Object output = Array.newInstance(itemType, n); while (n-- > 0) Array.set(output, n, cast(Array.get(value, n), itemType)); return output; } } if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection> { value = cast(value, Object[].class); // ? -> Object[] if (value.getClass().isArray()) // T1[] -> Vector<T2> { int n = Array.getLength(value); List<Object> output = new Vector<Object>(n); TypeVariable<?>[] itemTypes = type.getTypeParameters(); Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null; while (n-- > 0) { Object item = Array.get(value, n); if (itemType != null) item = cast(item, itemType); // T1 -> T2 output.set(n, item); } return output; } } if (value instanceof String) // String -> ? { String string = (String) value; // String -> primitive if (type == char.class || type == Character.class) return string.charAt(0); if (type == byte.class || type == Byte.class) return Byte.parseByte(string); if (type == long.class || type == Long.class) return Long.parseLong(string); if (type == int.class || type == Integer.class) return Integer.parseInt(string); if (type == short.class || type == Short.class) return Short.parseShort(string); if (type == float.class || type == Float.class) return Float.parseFloat(string); if (type == double.class || type == Double.class) return Double.parseDouble(string); if (type == boolean.class || type == Boolean.class) return string.equalsIgnoreCase("true"); if (type == InputStream.class) // String -> InputStream { try { return new ByteArrayInputStream(string.getBytes("UTF-8")); } catch (Exception e) { return null; } } } if (value instanceof Number) // Number -> primitive { Number number = (Number) value; if (type == byte.class || type == Byte.class) return number.byteValue(); if (type == long.class || type == Long.class) return number.longValue(); if (type == int.class || type == Integer.class) return number.intValue(); if (type == short.class || type == Short.class) return number.shortValue(); if (type == float.class || type == Float.class) return number.floatValue(); if (type == double.class || type == Double.class) return number.doubleValue(); if (type == char.class || type == Character.class) return Character.toChars(number.intValue())[0]; if (type == boolean.class || type == Boolean.class) return !Double.isNaN(number.doubleValue()) && number.intValue() != 0; } } catch (Exception e) { throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(), type.getSimpleName()), e); } // Return original value if not handled above. // Primitives and their Object equivalents will cast automatically. return value; }
From source file:edu.ku.brc.ui.UIHelper.java
/** * Converts a String to the class that is passed in. * @param dataStr the data string to be converted * @param cls the class that the string is to be converted t * @return the data object// ww w. java2 s .c o m */ public static <T> Object convertDataFromString(final String dataStr, final Class<T> cls) { try { //log.debug("Trying to convertDataFromString dataStr [" + dataStr + "] of class[" + cls + "]"); if (cls == Integer.class) { return StringUtils.isNotEmpty(dataStr) ? Integer.parseInt(dataStr) : null; } else if (cls == BigInteger.class) { return StringUtils.isNotEmpty(dataStr) ? BigInteger.valueOf(Long.parseLong(dataStr)) : null; } else if (cls == Float.class) { return StringUtils.isNotEmpty(dataStr) ? Float.parseFloat(dataStr) : null; } else if (cls == Double.class) { return StringUtils.isNotEmpty(dataStr) ? Double.parseDouble(dataStr) : null; } else if (cls == BigDecimal.class) { //System.out.println(BigDecimal.valueOf(Double.parseDouble(dataStr))); return StringUtils.isNotEmpty(dataStr) ? BigDecimal.valueOf(Double.parseDouble(dataStr)) : null; } else if (cls == Long.class) { return StringUtils.isNotEmpty(dataStr) ? Long.parseLong(dataStr) : null; } else if (cls == Short.class) { return StringUtils.isNotEmpty(dataStr) ? Short.parseShort(dataStr) : null; } else if (cls == Byte.class) { return StringUtils.isNotEmpty(dataStr) ? Byte.parseByte(dataStr) : null; } else if (cls == Calendar.class) { return StringUtils.isNotEmpty(dataStr) ? getCalendar(dataStr, scrDateFormat) : null; } else if (cls == Date.class) { return StringUtils.isNotEmpty(dataStr) ? getDate(dataStr, scrDateFormat) : null; } else if (cls == Timestamp.class) { return StringUtils.isNotEmpty(dataStr) ? getDate(dataStr, scrDateFormat) : null; } else if (cls == String.class) { return dataStr; } else { log.error("Unsupported type for conversion[" + cls.getSimpleName() + "]"); } } catch (Exception ex) { } return null; }
From source file:SignificantFigures.java
/** * Returns the value of this number as a byte. * * @return the numeric value represented by this object after conversion to type byte. * @throws NumberFormatException if this number cannot be converted to a byte. * * @since ostermillerutils 1.00.00/*from w w w . ja v a 2 s . c o m*/ */ @Override public byte byteValue() throws NumberFormatException { return Byte.parseByte(original); }
From source file:org.breizhbeans.thrift.tools.thriftmongobridge.protocol.TBSONProtocol.java
private Object getCurrentFieldValue(byte ttype) { Context context = peekContext(); if (context instanceof StructContext && ((StructContext) context).fieldsStack.isEmpty() == false) { String fieldName = ((StructContext) context).fieldsStack.peek(); // Extracts the dbobject Object fieldReaded = context.dbObject.get(fieldName); return fieldReaded; } else if (context instanceof ListContext) { return ((ListContext) context).next(); } else if (context instanceof MapContext) { // IF YOU READ A KEY YOU MUST CONVERT THE STRING INTO NUMBER if (((MapContext) context).isNextKey()) { switch (ttype) { case TType.BYTE: return Byte.parseByte((String) ((MapContext) context).next()); case TType.I32: case TType.I16: return Integer.parseInt((String) ((MapContext) context).next()); case TType.I64: return Long.parseLong((String) ((MapContext) context).next()); case TType.DOUBLE: return Double.parseDouble((String) ((MapContext) context).next()); }/* w w w .jav a2 s .c o m*/ } return ((MapContext) context).next(); } return null; }
From source file:org.openxdata.server.sms.FormSmsParser.java
/** * Get the skip logic error messages in a filled form. (eg pregnant males) * /* w w w . j av a2s .c o m*/ * @param formData the form data to validate. * @param ruleRequiredQtns a list of questions which become required after rule firing. * @return a comma separated list of validation error messages if any, else null. */ @SuppressWarnings("unchecked") private String getSkipErrorMsg(org.openxdata.model.FormData formData, Vector<QuestionData> ruleRequiredQtns) { String sErrors = null; //Check if form has any questions. Vector<PageData> pages = formData.getPages(); if (pages == null || pages.size() == 0) { sErrors = MSG_FORM_HAS_NO_QUESTIONS; return sErrors; } //Check if form has any skip rules. Vector<SkipRule> rules = formData.getDef().getSkipRules(); if (rules == null) return sErrors; //Deal with the user supplied validation rules for (int index = 0; index < rules.size(); index++) { SkipRule rule = (SkipRule) rules.elementAt(index); Vector<QuestionData> answeredQtns = getAnsweredQuestions(formData, rule.getActionTargets()); rule.fire(formData); //Get the question text of the first condition. This could be improved with a user supplied skip logic error message, in future. String qtnText = formData.getQuestion(((Condition) rule.getConditions().elementAt(0)).getQuestionId()) .getText(); boolean mandatoryRule = (rule.getAction() & OpenXdataConstants.ACTION_MAKE_MANDATORY) != 0; Vector<Byte> ids = rule.getActionTargets(); for (byte i = 0; i < ids.size(); i++) { QuestionData questionData = formData.getQuestion(Byte.parseByte(ids.elementAt(i).toString())); //Check if the user answered a question they were supposed to skip. if (!questionData.isAnswered() && answeredQtns.contains(questionData)) sErrors = addErrorMsg(sErrors, MSG_DUE_TO_ANSWER_FOR + " " + qtnText + ", " + MSG_NO_ANSWER_EXPECTED_FOR + " " + questionData.getDef().getText()); //Check is the user has not answered a question which has become required after an answer to some other question. if (mandatoryRule && questionData.getDef().isMandatory() && !questionData.isAnswered()) sErrors = addErrorMsg(sErrors, MSG_DUE_TO_ANSWER_FOR + " " + qtnText + ", " + MSG_NO_ANSWER_EXPECTED_FOR + " " + questionData.getDef().getText()); if (mandatoryRule) ruleRequiredQtns.add(questionData); } } return sErrors; }