Example usage for java.lang Number longValue

List of usage examples for java.lang Number longValue

Introduction

In this page you can find the example usage for java.lang Number longValue.

Prototype

public abstract long longValue();

Source Link

Document

Returns the value of the specified number as a long .

Usage

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a long primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)//from   w  w w  . j  a  v a 2  s . co m
 *@return the converted Long value.
 */
public static Long formatLong(String value, Locale locale) {
    Long result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) {
                result = new Long(num.longValue());
            }
        }
    }

    return result;
}

From source file:com.nextep.datadesigner.vcs.services.VersionHelper.java

/**
 * Executes the specified revision-check query for the given element id. The return boolean
 * indicates whether the revision number fetched from the database through the given query
 * matches the expected revision number.
 * /*from w w  w . j  a  v a  2s  . co  m*/
 * @param query SQL query which can retrieve the revision number from its ID
 * @param id unique ID of element to check the revision
 * @param expectedRevision expected revision number
 * @return <code>true</code> if the expected revision number matches the repository revision
 *         number, else <code>false</code>
 */
private static boolean queryIsUpToDate(String query, long id, long expectedRevision) {
    final Session session = HibernateUtil.getInstance().getSandBoxSession();
    session.flush();
    session.clear();
    SQLQuery sqlQuery = session.createSQLQuery(query);
    sqlQuery.setLong(0, id);
    Number revision = (Number) sqlQuery.uniqueResult();
    return revision == null || (revision != null && revision.longValue() == expectedRevision);
}

From source file:com.sunchenbin.store.feilong.servlet.http.ResponseUtil.java

/**
 * Down load data.// w  w  w.  java  2s . co m
 *
 * @param saveFileName
 *            the save file name
 * @param inputStream
 *            the input stream
 * @param contentLength
 *            the content length
 * @param request
 *            the request
 * @param response
 *            the response
 */
private static void downLoadData(String saveFileName, InputStream inputStream, Number contentLength,
        HttpServletRequest request, HttpServletResponse response) {
    Date beginDate = new Date();

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("begin download~~,saveFileName:[{}],contentLength:[{}]", saveFileName,
                FileUtil.formatSize(contentLength.longValue()));
    }
    try {
        OutputStream outputStream = response.getOutputStream();

        //? 
        //inputStream.read(buffer);
        //outputStream = new BufferedOutputStream(response.getOutputStream());
        //outputStream.write(buffer);

        IOWriteUtil.write(inputStream, outputStream);
        if (LOGGER.isInfoEnabled()) {
            Date endDate = new Date();
            LOGGER.info("end download,saveFileName:[{}],contentLength:[{}],time use:[{}]", saveFileName,
                    FileUtil.formatSize(contentLength.longValue()),
                    DateExtensionUtil.getIntervalForView(beginDate, endDate));
        }
    } catch (IOException e) {
        /*
         * ?  ClientAbortException  ????? 
         * ?? ??
         * ???????
         * ? KILL? ?? ClientAbortException
         */
        //ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
        final String exceptionName = e.getClass().getName();

        if (StringUtil.contains(exceptionName, "ClientAbortException")
                || StringUtil.contains(e.getMessage(), "ClientAbortException")) {
            LOGGER.warn(
                    "[ClientAbortException],maybe user use Thunder soft or abort client soft download,exceptionName:[{}],exception message:[{}] ,request User-Agent:[{}]",
                    exceptionName, e.getMessage(), RequestUtil.getHeaderUserAgent(request));
        } else {
            LOGGER.error("[download exception],exception name: " + exceptionName, e);
            throw new UncheckedIOException(e);
        }
    }
}

From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a long primitive.
 * /*from   w  ww . j  av a2s  . co m*/
 * @param value
 *            The value validation is being performed on.
 * @param locale
 *            The locale to use to parse the number (system default if null)
 * @return the converted Long value.
 */
public static Long formatLong(String value, Locale locale) {
    Long result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) {
                result = Long.valueOf(num.longValue());
            }
        }
    }

    return result;
}

From source file:net.yck.wkrdb.common.shared.PropertyConverter.java

/**
 * Convert the specified object into a Long.
 *
 * @param value//from  w  w  w.j  a  va2s  .  c o m
 *            the value to convert
 * @return the converted value
 * @throws ConversionException
 *             thrown if the value cannot be converted to a Long
 */
public static Long toLong(Object value) throws ConversionException {
    Number n = toNumber(value, Long.class);
    if (n instanceof Long) {
        return (Long) n;
    } else {
        return n.longValue();
    }
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a long primitive.
 * // w ww  . j  a v a 2 s. c om
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Long value.
 */
public static Long formatLong(String value, Locale locale) {
    Long result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) {
                result = new Long(num.longValue());
            }
        }
    }

    return result;
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

@SuppressWarnings("squid:S3776")
private static Object convertPrimitiveValue(String value, Class<?> type) throws ParseException {
    if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)) {
        return value.toLowerCase().trim().equals("true");
    } else {/*from   ww w  .  j  a v a 2 s.c  o m*/
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        Number num = numberFormat.parse(value);
        if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
            return num.byteValue();
        } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
            return num.doubleValue();
        } else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
            return num.floatValue();
        } else if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
            return num.intValue();
        } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
            return num.longValue();
        } else if (type.equals(Short.class) || type.equals(Short.TYPE)) {
            return num.shortValue();
        } else {
            return null;
        }
    }
}

From source file:Main.java

/**
 * convert value to given type./*from   w ww.ja  v  a 2 s  .c  o  m*/
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:org.red5.server.service.ConversionUtils.java

/**
 * Convert number to primitive wrapper like Boolean or Float
 * @param num               Number to conver
 * @param wrapper           Primitive wrapper type
 * @return                  Converted object
 *//*from   w w w  .  j a v a  2  s  . c  o  m*/
public static Object convertNumberToWrapper(Number num, Class<?> wrapper) {
    //XXX Paul: Using valueOf will reduce object creation
    if (wrapper.equals(String.class)) {
        return num.toString();
    } else if (wrapper.equals(Boolean.class)) {
        return Boolean.valueOf(num.intValue() == 1);
    } else if (wrapper.equals(Double.class)) {
        return Double.valueOf(num.doubleValue());
    } else if (wrapper.equals(Long.class)) {
        return Long.valueOf(num.longValue());
    } else if (wrapper.equals(Float.class)) {
        return Float.valueOf(num.floatValue());
    } else if (wrapper.equals(Integer.class)) {
        return Integer.valueOf(num.intValue());
    } else if (wrapper.equals(Short.class)) {
        return Short.valueOf(num.shortValue());
    } else if (wrapper.equals(Byte.class)) {
        return Byte.valueOf(num.byteValue());
    }
    throw new ConversionException("Unable to convert number to: " + wrapper);
}

From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convert(Class toType, Object value) {
    if ("".equals(value)) {
        value = null;// w ww.  java 2 s.  co  m
    }
    // If we do not want a collection, but the value is one, use the first value
    if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray())
            && (value.getClass().isArray() || value instanceof Collection)) {
        final Iterator it = IteratorUtils.getIterator(value);
        if (!it.hasNext()) {
            value = null;
        } else {
            value = it.next();
        }
    }

    // Check for null values
    if (value == null) {
        if (toType.isPrimitive()) {
            // On primitives, use the default value
            if (toType == Boolean.TYPE) {
                value = Boolean.FALSE;
            } else if (toType == Character.TYPE) {
                value = '\0';
            } else {
                value = 0;
            }
        } else {
            // For objects, return null
            return null;
        }
    }

    // Check if the value is already of the expected type
    if (toType.isInstance(value)) {
        return value;
    }

    // If the class is primitive, use the wrapper, so we have an easier work of testing instances
    if (toType.isPrimitive()) {
        toType = ClassUtils.primitiveToWrapper(toType);
    }

    // Convert to well-known types
    if (String.class.isAssignableFrom(toType)) {
        if (value instanceof Entity) {
            final Long entityId = ((Entity) value).getId();
            return entityId == null ? null : entityId.toString();
        }
        return value.toString();
    } else if (Number.class.isAssignableFrom(toType)) {
        if (!(value instanceof Number)) {
            if (value instanceof String) {
                value = new BigDecimal((String) value);
            } else if (value instanceof Date) {
                value = ((Date) value).getTime();
            } else if (value instanceof Calendar) {
                value = ((Calendar) value).getTimeInMillis();
            } else if (value instanceof Entity) {
                value = ((Entity) value).getId();
                if (value == null) {
                    return null;
                }
            } else {
                throw new ConversionException("Invalid number: " + value);
            }
        }
        final Number number = (Number) value;
        if (Byte.class.isAssignableFrom(toType)) {
            return number.byteValue();
        } else if (Short.class.isAssignableFrom(toType)) {
            return number.shortValue();
        } else if (Integer.class.isAssignableFrom(toType)) {
            return number.intValue();
        } else if (Long.class.isAssignableFrom(toType)) {
            return number.longValue();
        } else if (Float.class.isAssignableFrom(toType)) {
            return number.floatValue();
        } else if (Double.class.isAssignableFrom(toType)) {
            return number.doubleValue();
        } else if (BigInteger.class.isAssignableFrom(toType)) {
            return new BigInteger(number.toString());
        } else if (BigDecimal.class.isAssignableFrom(toType)) {
            return new BigDecimal(number.toString());
        }
    } else if (Boolean.class.isAssignableFrom(toType)) {
        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if ("on".equalsIgnoreCase(value.toString())) {
            return true;
        } else {
            return Boolean.parseBoolean(value.toString());
        }
    } else if (Character.class.isAssignableFrom(toType)) {
        final String str = value.toString();
        return (str.length() == 0) ? null : str.charAt(0);
    } else if (Calendar.class.isAssignableFrom(toType)) {
        if (value instanceof Date) {
            final Calendar cal = new GregorianCalendar();
            cal.setTime((Date) value);
            return cal;
        }
    } else if (Date.class.isAssignableFrom(toType)) {
        if (value instanceof Calendar) {
            final long millis = ((Calendar) value).getTimeInMillis();
            try {
                return ConstructorUtils.invokeConstructor(toType, millis);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    } else if (Enum.class.isAssignableFrom(toType)) {
        Object ret;
        try {
            ret = Enum.valueOf(toType, value.toString());
        } catch (final Exception e) {
            ret = null;
        }
        if (ret == null) {
            Object[] possible;
            try {
                possible = (Object[]) toType.getMethod("values").invoke(null);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Couldn't invoke the 'values' method for enum " + toType.getName());
            }
            if (StringValuedEnum.class.isAssignableFrom(toType)) {
                final String test = coerce(String.class, value);
                for (final Object item : possible) {
                    if (((StringValuedEnum) item).getValue().equals(test)) {
                        ret = item;
                        break;
                    }
                }
            } else if (IntValuedEnum.class.isAssignableFrom(toType)) {
                final int test = coerce(Integer.TYPE, value);
                for (final Object item : possible) {
                    if (((IntValuedEnum) item).getValue() == test) {
                        ret = item;
                        break;
                    }
                }
            } else {
                throw new ConversionException("Invalid enum: " + value);
            }
        }
        return ret;
    } else if (Entity.class.isAssignableFrom(toType)) {
        final Long id = coerce(Long.class, value);
        return EntityHelper.reference(toType, id);
    } else if (Locale.class.isAssignableFrom(toType)) {
        return LocaleConverter.instance().valueOf(value.toString());
    } else if (Collection.class.isAssignableFrom(toType)) {
        final Collection collection = (Collection) ClassHelper.instantiate(toType);
        final Iterator iterator = IteratorUtils.getIterator(value);
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
        return collection;
    } else if (toType.isArray()) {
        final Collection collection = coerceCollection(toType.getComponentType(), value);
        final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size());
        return collection.toArray(array);
    }

    // We don't know how to convert the value
    throw new ConversionException("Cannot coerce value to: " + toType.getName());
}