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:net.sf.jasperreports.functions.standard.MathFunctions.java

private static Number fixNumberReturnType(Number returnValue, Number... numbers) {
    if (haveSameType(Integer.class, numbers))
        return returnValue.intValue();
    if (haveSameType(Long.class, numbers))
        return returnValue.longValue();
    if (haveSameType(Float.class, numbers))
        return returnValue.floatValue();
    return returnValue.doubleValue();
}

From source file:NumberUtils.java

/**
 * Answers the signum function of the given number
 * (i.e., <code>-1</code> if it is negative, <code>0</code>
 * if it is zero and <code>1</code> if it is positive).
 *
 * @param number/*from  ww  w  .java  2 s.com*/
 * @return int
 * @throws ArithmeticException The given number is <code>null</code> or 'not a number'.
 */
public static int signum(Number number) throws ArithmeticException {
    if (number == null || isNaN(number))
        throw new ArithmeticException("Argument must not be null or NaN.");

    if (isLongCompatible(number)) {
        long value = number.longValue();
        return value < 0 ? -1 : value == 0 ? 0 : 1;
    } else if (number instanceof BigInteger)
        return ((BigInteger) number).signum();
    else if (number instanceof BigDecimal)
        return ((BigDecimal) number).signum();
    else { // => isDoubleCompatible(number) or unknown Number type
        double value = number.doubleValue();
        return value < 0 ? -1 : value == 0 ? 0 : 1;
    }
}

From source file:goal.tools.Run.java

/**
 * @param args// w ww.  j av a2s.  c  o  m
 * @throws ParseException
 * @throws ParserException
 * @throws FileNotFoundException
 * @throws GOALRunFailedException 
 * @throws InvalidEmotionConfigFile 
 * @throws Exception
 */
public static void run(String... args) throws GOALRunFailedException, ParseException, FileNotFoundException,
        ParserException, InvalidEmotionConfigFile {
    // Get start time.
    long startTime = System.nanoTime();

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    /*
     * Handle general options.
     */
    if (cmd.hasOption(OPTION_HELP)) {
        showHelp();
        return;
    }

    if (cmd.hasOption(OPTION_LICENSE)) {
        showLicense();
        return;
    }

    if (cmd.hasOption(OPTION_VERSION)) {
        showVersion();
        return;
    }

    // Verbose makes other verbose options irrelevant.
    if (cmd.hasOption(OPTION_VERBOSE_SHORT)) {
        Loggers.addConsoleLogger();
    } else {
        if (cmd.hasOption(OPTION_VERBOSE_INFO)) {
            Loggers.getInfoLogger().addConsoleLogger();
        }

        if (cmd.hasOption(OPTION_VERBOSE_WARNING)) {
            Loggers.getWarningLogger().addConsoleLogger();
        }

        if (cmd.hasOption(OPTION_VERBOSE_PARSER)) {
            Loggers.getParserLogger().addConsoleLogger();
        }
    }

    final boolean debuggerOutput = cmd.hasOption(OPTION_DEBUG);

    final Messaging messaging;
    final String host;
    if (cmd.hasOption(OPTION_RMI_MESSAGING)) {
        messaging = new RmiMessaging();
        host = cmd.getOptionValue(OPTION_RMI_MESSAGING);
    } else {
        messaging = new LocalMessaging();
        host = "localhost";
    }

    /*
     * Run .mas2g files.
     */
    List<File> masFiles = parseFileArguments(cmd.getArgs(),
            new MASProgramFilter(cmd.hasOption(OPTION_RECURSIVE)));

    BatchRun repeatedBatchRun = new BatchRun(masFiles);
    repeatedBatchRun.setDebuggerOutput(debuggerOutput);

    if (cmd.hasOption(OPTION_REPEATS)) {
        Number repeats = (Number) cmd.getParsedOptionValue(OPTION_REPEATS);
        repeatedBatchRun.setRepeats(repeats.longValue());
    }
    if (cmd.hasOption(OPTION_TIMEOUT)) {
        Number timeout = (Number) cmd.getParsedOptionValue(OPTION_TIMEOUT);
        repeatedBatchRun.setTimeout(timeout.longValue());
    }

    repeatedBatchRun.setMessagingHost(host);
    repeatedBatchRun.setMessaging(messaging);

    repeatedBatchRun.run();

    /*
     * Run .test2g files.
     */
    List<File> testFiles = parseFileArguments(cmd.getArgs(),
            new UnitTestFilter(cmd.hasOption(OPTION_RECURSIVE)));
    List<UnitTestResult> results = new ArrayList<>(testFiles.size());

    for (File unitTestFile : testFiles) {
        UnitTest unitTest = PlatformManager.createNew().parseUnitTestFile(unitTestFile);
        UnitTestRun testRun = new UnitTestRun(unitTest);
        UnitTestRunResultInspector inspector = new UnitTestRunResultInspector(unitTest);
        testRun.setDebuggerOutput(debuggerOutput);
        testRun.setMessaging(messaging);
        testRun.setResultInspector(inspector);
        testRun.setMessagingHost(host);
        testRun.run();
        results.add(inspector.getResults());

    }

    UnitTestResultFormatter formatter = new UnitTestResultFormatter();
    int passed = 0;
    for (UnitTestResult result : results) {
        System.out.println(formatter.visit(result));
        if (result.isPassed()) {
            passed += 1;
        }
    }

    Loggers.removeConsoleLogger();

    if (!results.isEmpty()) {
        System.out.println(
                "Tests: " + results.size() + " passed: " + passed + " failed: " + (results.size() - passed));
    }

    // Get elapsed time.
    long elapsedTime = (System.nanoTime() - startTime) / 1000000;
    System.out.println("Took " + elapsedTime + " milliseconds to run jobs.");
}

From source file:org.nuxeo.ecm.core.repository.jcr.DocumentPartWriter.java

/**
 * Writes the primitive property into the given parent node.
 *
 * @param parent/*from  ww  w .  ja va 2  s. co  m*/
 * @param prop
 * @throws Exception
 */
@SuppressWarnings({ "ObjectEquality" })
public static void writePrimitiveProperty(Node parent, Property prop) throws Exception {
    SimpleType type = ((SimpleType) prop.getType()).getPrimitiveType();
    if (type == StringType.INSTANCE) {
        parent.setProperty(prop.getName(), (String) prop.getValue());
    } else if (type == LongType.INSTANCE || type == IntegerType.INSTANCE) {
        Number value = (Number) prop.getValue();
        long v = value == null ? 0 : value.longValue();
        parent.setProperty(prop.getName(), v);
    } else if (type == DoubleType.INSTANCE) {
        Number value = (Number) prop.getValue();
        double v = value == null ? 0 : value.doubleValue();
        parent.setProperty(prop.getName(), v);
    } else if (type == DateType.INSTANCE) {
        parent.setProperty(prop.getName(), (Calendar) prop.getValue());
    } else if (type == BooleanType.INSTANCE) {
        Boolean value = (Boolean) prop.getValue();
        boolean v = value == null ? false : value.booleanValue();
        parent.setProperty(prop.getName(), v);
    } else if (type == BinaryType.INSTANCE) {
        InputStream in = (InputStream) prop.getValue();
        try {
            parent.setProperty(prop.getName(), in);
        } finally {
            in.close();
        }
    }
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules:/*from ww w .ja v  a  2  s.  c  om*/
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:org.flycraft.vkontakteapi.model.ParseUtils.java

/**
 * Parses object with follow rules:/*ww  w  . j a v  a 2  s  . com*/
 * <p/>
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 * arrays of primitive types, {@link java.lang.String}s and {@link org.flycraft.vkontakteapi.model.VKApiModel}s,
 * list implementation line {@link org.flycraft.vkontakteapi.model.VKList}, {@link org.flycraft.vkontakteapi.model.VKAttachments.VKApiAttachment} or {@link org.flycraft.vkontakteapi.model.VKPhotoSizes},
 * {@link org.flycraft.vkontakteapi.model.VKApiModel}s.
 * <p/>
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T>    type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules:/*from  w w  w .j  a va 2 s  .co  m*/
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.ning.metrics.serialization.event.SmileEnvelopeEvent.java

private static void addToTree(ObjectNode root, String name, Object value) {
    /* could wrap everything as POJONode, but that's bit inefficient;
     * so let's handle some known cases.
     * (in reality, I doubt there could ever be non-scalars, FWIW, since
     * downstream systems expect simple key/value data)
     *///from w w w  .  j  a  v a  2s .  c  o m
    if (value instanceof String) {
        root.put(name, (String) value);
        return;
    }
    if (value instanceof Number) {
        Number num = (Number) value;
        if (value instanceof Integer) {
            root.put(name, num.intValue());
        } else if (value instanceof Long) {
            root.put(name, num.longValue());
        } else if (value instanceof Double) {
            root.put(name, num.doubleValue());
        } else {
            root.putPOJO(name, num);
        }
    } else if (value == Boolean.TRUE) {
        root.put(name, true);
    } else if (value == Boolean.FALSE) {
        root.put(name, false);
    } else { // most likely Date
        root.putPOJO(name, value);
    }
}

From source file:NumberUtils.java

/**
 * Converts the given number to a <code>Long</code> (by using <code>longValue()</code>).
 *
 * @param number//  w  w w . ja  v a2 s . co  m
 * @return java.lang.Long
 * @throws IllegalArgumentException The given number is 'not a number' or infinite.
 */
public static Long toLong(Number number) throws IllegalArgumentException {
    if (number == null || number instanceof Long)
        return (Long) number;
    if (isNaN(number) || isInfinite(number))
        throw new IllegalArgumentException("Argument must not be NaN or infinite.");
    return new Long(number.longValue());
}

From source file:NumberUtils.java

/**
 * Convert the given number into an instance of the given target class.
 * @param number the number to convert/* w  ww.  j av a2 s  .  c om*/
 * @param targetClass the target class to convert to
 * @return the converted number
 * @throws IllegalArgumentException if the target class is not supported
 * (i.e. not a standard Number subclass as included in the JDK)
 * @see java.lang.Byte
 * @see java.lang.Short
 * @see java.lang.Integer
 * @see java.lang.Long
 * @see java.math.BigInteger
 * @see java.lang.Float
 * @see java.lang.Double
 * @see java.math.BigDecimal
 */
public static Number convertNumberToTargetClass(Number number, Class<?> targetClass)
        throws IllegalArgumentException {

    //   Assert.notNull(number, "Number must not be null");
    //   Assert.notNull(targetClass, "Target class must not be null");

    if (targetClass.isInstance(number)) {
        return number;
    } else if (targetClass.equals(Byte.class)) {
        long value = number.longValue();
        if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return new Byte(number.byteValue());
    } else if (targetClass.equals(Short.class)) {
        long value = number.longValue();
        if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return new Short(number.shortValue());
    } else if (targetClass.equals(Integer.class)) {
        long value = number.longValue();
        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
            raiseOverflowException(number, targetClass);
        }
        return new Integer(number.intValue());
    } else if (targetClass.equals(Long.class)) {
        return new Long(number.longValue());
    } else if (targetClass.equals(Float.class)) {
        return new Float(number.floatValue());
    } else if (targetClass.equals(Double.class)) {
        return new Double(number.doubleValue());
    } else if (targetClass.equals(BigInteger.class)) {
        return BigInteger.valueOf(number.longValue());
    } else if (targetClass.equals(BigDecimal.class)) {
        // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
        // (see BigDecimal javadoc for details)
        return new BigDecimal(number.toString());
    } else {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type ["
                + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
    }
}