Example usage for java.lang Long MIN_VALUE

List of usage examples for java.lang Long MIN_VALUE

Introduction

In this page you can find the example usage for java.lang Long MIN_VALUE.

Prototype

long MIN_VALUE

To view the source code for java.lang Long MIN_VALUE.

Click Source Link

Document

A constant holding the minimum value a long can have, -263.

Usage

From source file:com.projity.pm.task.NormalTask.java

/**
 * Offset the given date by the duration of the remaining duration.
 *//*from   ww  w  .  j a  v  a  2 s. c  o m*/
public long calcOffsetFrom(long startDate, long dependencyDate, boolean ahead, boolean remainingOnly,
        boolean useSooner) {

    //      This is a task based implementation- for parents dont use their assignments
    if (isWbsParent()) {
        long d = remainingOnly ? Duration.millis(getRemainingDuration()) : getDurationMillis();
        if (!ahead)
            d = -d;
        return getEffectiveWorkCalendar().add(startDate, d, useSooner);
    }
    //
    //
    //      This is an assignment based implementation

    Iterator i = getAssignments().iterator();
    long result;
    Assignment assignment;
    if (startDate < 0)
        result = ahead ? Long.MIN_VALUE : 0;
    else
        result = ahead ? 0 : Long.MAX_VALUE;
    while (i.hasNext()) {
        assignment = (Assignment) i.next();
        long offsetDate = assignment.calcOffsetFrom(startDate, dependencyDate, ahead, remainingOnly, useSooner);
        result = ahead ? Math.max(result, offsetDate) : Math.min(result, offsetDate);
    }
    return result;
}

From source file:org.apache.noggit.JSONParser.java

public void testNumbers() throws IOException {
        err("[00]");
        err("[003]");
        err("[00.3]");
        err("[1e1.1]");
        err("[+1]");
        err("[NaN]");
        err("[Infinity]");
        err("[--1]");

        String lmin = "-9223372036854775808";
        String lminNot = "-9223372036854775809";
        String lmax = "9223372036854775807";
        String lmaxNot = "9223372036854775808";

        String bignum = "12345678987654321357975312468642099775533112244668800152637485960987654321";

        parse("[0,1,-1,543,-876]", new Object[] { a, o(0), o(1), o(-1), o(543), o(-876), A, e });
        parse("[-0]", new Object[] { a, o(0), A, e });

        parse("[" + lmin + "," + lmax + "]", new Object[] { a, o(Long.MIN_VALUE), o(Long.MAX_VALUE), A, e });

        parse("[" + bignum + "]", new Object[] { a, bn(bignum), A, e });
        parse("[" + "-" + bignum + "]", new Object[] { a, bn("-" + bignum), A, e });

        parse("[" + lminNot + "]", new Object[] { a, bn(lminNot), A, e });
        parse("[" + lmaxNot + "]", new Object[] { a, bn(lmaxNot), A, e });

        parse("[" + lminNot + "," + lmaxNot + "]", new Object[] { a, bn(lminNot), bn(lmaxNot), A, e });

        // bignum many digits on either side of decimal
        String t = bignum + "." + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        err(t + ".1"); // extra decimal
        err("-" + t + ".1");

        // bignum exponent w/o fraction
        t = "1" + "e+" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = "1" + "E+" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = "1" + "e" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = "1" + "E" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = "1" + "e-" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = "1" + "E-" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });

        t = bignum + "e+" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = bignum + "E-" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        t = bignum + "e" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });

        t = bignum + "." + bignum + "e" + bignum;
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });

        err("[1E]");
        err("[1E-]");
        err("[1E+]");
        err("[1E+.3]");
        err("[1E+0.3]");
        err("[1E+1e+3]");
        err("[" + bignum + "e" + "]");
        err("[" + bignum + "e-" + "]");
        err("[" + bignum + "e+" + "]");
        err("[" + bignum + "." + bignum + "." + bignum + "]");

        double[] vals = new double[] { 0, 0.1, 1.1, Double.MAX_VALUE, Double.MIN_VALUE,
                2.2250738585072014E-308, /* Double.MIN_NORMAL */
        };/*from   w w w.  j  av  a  2s  .c  o  m*/
        for (int i = 0; i < vals.length; i++) {
            double d = vals[i];
            parse("[" + d + "," + -d + "]", new Object[] { a, o(d), o(-d), A, e });
        }

        // MIN_NORMAL has the max number of digits (23), so check that
        // adding an extra digit causes BIGNUM to be returned.
        t = "2.2250738585072014E-308" + "0";
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
        // check it works with a leading zero too
        t = "0.2250738585072014E-308" + "0";
        parse("[" + t + "," + "-" + t + "]", new Object[] { a, bn(t), bn("-" + t), A, e });
    }

From source file:org.alfresco.opencmis.CMISTest.java

/**
 * Test for MNT-9089// w  ww .  j  av  a  2 s .co  m
 */
@Test
public void testIntegerBoudaries() throws Exception {
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

    try {
        final FileInfo fileInfo = transactionService.getRetryingTransactionHelper()
                .doInTransaction(new RetryingTransactionCallback<FileInfo>() {
                    @Override
                    public FileInfo execute() throws Throwable {
                        NodeRef companyHomeNodeRef = repositoryHelper.getCompanyHome();

                        QName testIntTypeQName = QName.createQName("http://testCMISIntegersModel/1.0/",
                                "testintegerstype");

                        String folderName = GUID.generate();
                        FileInfo folderInfo = fileFolderService.create(companyHomeNodeRef, folderName,
                                ContentModel.TYPE_FOLDER);
                        nodeService.setProperty(folderInfo.getNodeRef(), ContentModel.PROP_NAME, folderName);
                        assertNotNull(folderInfo);

                        String docName = GUID.generate();
                        FileInfo fileInfo = fileFolderService.create(folderInfo.getNodeRef(), docName,
                                testIntTypeQName);
                        assertNotNull(fileInfo);
                        nodeService.setProperty(fileInfo.getNodeRef(), ContentModel.PROP_NAME, docName);

                        return fileInfo;
                    }
                });

        // get repository id
        withCmisService(new CmisServiceCallback<Void>() {
            @Override
            public Void execute(CmisService cmisService) {
                List<RepositoryInfo> repositories = cmisService.getRepositoryInfos(null);
                assertTrue(repositories.size() > 0);
                RepositoryInfo repo = repositories.get(0);
                String repositoryId = repo.getId();

                String objectIdStr = fileInfo.getNodeRef().toString();

                TypeDefinition typeDef = cmisService.getTypeDefinition(repositoryId, "D:tcim:testintegerstype",
                        null);

                PropertyIntegerDefinitionImpl intNoBoundsTypeDef = (PropertyIntegerDefinitionImpl) typeDef
                        .getPropertyDefinitions().get("tcim:int");
                PropertyIntegerDefinitionImpl longNoBoundsTypeDef = (PropertyIntegerDefinitionImpl) typeDef
                        .getPropertyDefinitions().get("tcim:long");

                PropertyIntegerDefinitionImpl intWithBoundsTypeDef = (PropertyIntegerDefinitionImpl) typeDef
                        .getPropertyDefinitions().get("tcim:intwithbounds");
                PropertyIntegerDefinitionImpl longWithBoundsTypeDef = (PropertyIntegerDefinitionImpl) typeDef
                        .getPropertyDefinitions().get("tcim:longwithbounds");

                BigInteger minInteger = BigInteger.valueOf(Integer.MIN_VALUE);
                BigInteger maxInteger = BigInteger.valueOf(Integer.MAX_VALUE);

                BigInteger minLong = BigInteger.valueOf(Long.MIN_VALUE);
                BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE);

                // test for default boundaries
                assertTrue(intNoBoundsTypeDef.getMinValue().equals(minInteger));
                assertTrue(intNoBoundsTypeDef.getMaxValue().equals(maxInteger));

                assertTrue(longNoBoundsTypeDef.getMinValue().equals(minLong));
                assertTrue(longNoBoundsTypeDef.getMaxValue().equals(maxLong));

                // test for pre-defined boundaries
                assertTrue(intWithBoundsTypeDef.getMinValue().equals(BigInteger.valueOf(-10L)));
                assertTrue(intWithBoundsTypeDef.getMaxValue().equals(BigInteger.valueOf(10L)));

                assertTrue(longWithBoundsTypeDef.getMinValue().equals(BigInteger.valueOf(-10L)));
                assertTrue(longWithBoundsTypeDef.getMaxValue().equals(BigInteger.valueOf(10L)));

                try // try to overfloat long without boundaries
                {
                    BigInteger aValue = BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(1L));
                    setProperiesToObject(cmisService, repositoryId, objectIdStr, "tcim:long", aValue);
                    fail();
                } catch (Exception e) {
                    assertTrue(e instanceof CmisConstraintException);
                }

                try // try to overfloat int without boundaries
                {
                    BigInteger aValue = BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.valueOf(1L));
                    setProperiesToObject(cmisService, repositoryId, objectIdStr, "tcim:int", aValue);
                    fail();
                } catch (Exception e) {
                    assertTrue(e instanceof CmisConstraintException);
                }

                try // try to overfloat int with boundaries
                {
                    BigInteger aValue = BigInteger.valueOf(11l);
                    setProperiesToObject(cmisService, repositoryId, objectIdStr, "tcim:intwithbounds", aValue);
                    fail();
                } catch (Exception e) {
                    assertTrue(e instanceof CmisConstraintException);
                }

                try // try to overfloat long with boundaries
                {
                    BigInteger aValue = BigInteger.valueOf(11l);
                    setProperiesToObject(cmisService, repositoryId, objectIdStr, "tcim:longwithbounds", aValue);
                    fail();
                } catch (Exception e) {
                    assertTrue(e instanceof CmisConstraintException);
                }

                return null;
            }
        }, CmisVersion.CMIS_1_0);
    } catch (Exception e) {
        fail(e.getMessage());
    } finally {
        AuthenticationUtil.popAuthentication();
    }
}

From source file:com.peterbochs.instrument.InstrumentPanel.java

private void setMarkerMaxAndMinSize() {
    long smallestSegmentStart = Long.MAX_VALUE;
    long largestSegmentEnd = Long.MIN_VALUE;
    for (int x = JmpSocketServer.jmpDataVector.size() - 1, counter = 0; x >= 0
            && counter <= MAX_NUMBER_OF_VERTEX; x--, counter++) {
        JmpData jumpData = JmpSocketServer.jmpDataVector.get(x);
        if (jumpData.segmentStart < smallestSegmentStart) {
            smallestSegmentStart = jumpData.segmentStart;
        }/*from   w  ww  .  j  a  v  a2  s.  c om*/
        if (jumpData.segmentEnd > largestSegmentEnd) {
            largestSegmentEnd = jumpData.segmentEnd;
        }
    }
    graphComponent.markerOffset = smallestSegmentStart;
    graphComponent.markerEnd = largestSegmentEnd;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils.NumberObject}
 *//*w w w .jav  a 2s  .co  m*/
@SuppressWarnings("unchecked")
@Test
public void NumberObjectTest() {
    try {
        Class<?> numberObject = ClassLoader.getSystemClassLoader()
                .loadClass(NumberUtils.class.getName() + "$NumberObject");

        Constructor<?> c = numberObject.getDeclaredConstructor(Class.class);
        c.setAccessible(true);

        Method ofType = numberObject.getMethod("of", Class.class);
        ofType.setAccessible(true);

        Method ofN = numberObject.getMethod("of", Number.class);
        ofN.setAccessible(true);

        Method parsable = numberObject.getDeclaredMethod("parsable", Number.class);
        parsable.setAccessible(true);

        Method contains = numberObject.getDeclaredMethod("contains", Number.class);
        contains.setAccessible(true);

        Method valueOf = numberObject.getDeclaredMethod("valueOf", Number.class);
        valueOf.setAccessible(true);

        for (Class<?> type : NUMBERS) {
            Object o = c.newInstance(type);
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            Object numob = ofType.invoke(null, type);
            assertEquals("ofType: " + type.getSimpleName(), o, numob);
            Number n = null;
            if (!type.isPrimitive()) {
                if (ClassUtils.isPrimitiveWrapper(type)) {
                    n = (Number) ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                            .invoke(null, "1");
                } else {
                    n = (Number) type.getField("ONE").get(null);
                }
                if (type.equals(byte.class))
                    assertEquals("ofN: 1: " + type.getSimpleName(), o, ofN.invoke(null, n));
            }
            assertEquals("parsable: -1: " + type.getSimpleName(), true, parsable.invoke(numob, -1));
            assertEquals("parsable: 0: " + type.getSimpleName(), true, parsable.invoke(numob, 0));
            assertEquals("parsable: 1: " + type.getSimpleName(), true, parsable.invoke(numob, 1));

            assertEquals("parsable: null: " + type.getSimpleName(), !type.isPrimitive(),
                    parsable.invoke(numob, (Number) null));

            Object expected = ObjectUtils.isAny(wrapper, Float.class, Double.class, BigDecimal.class,
                    BigInteger.class);
            assertEquals("parsable: Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE));
            assertEquals("parsable: Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.toBigInteger()));
            assertEquals("parsable: Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.POSITIVE_INFINITY));
            assertEquals("parsable: Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT));
            assertEquals("parsable: Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.toBigInteger()));
            assertEquals("parsable: -Infinity: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Double: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate()));
            assertEquals("parsable: -Infinity: Double: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_DOUBLE.negate().toBigInteger()));
            assertEquals("parsable: -Infinity: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NEGATIVE_INFINITY));
            assertEquals("parsable: -Infinity: Float: BigDecimal: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate()));
            assertEquals("parsable: -Infinity: Float: BigInteger: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, INFINITY_FLOAT.negate().toBigInteger()));

            expected = ObjectUtils.isAny(wrapper, Float.class, Double.class);
            assertEquals("parsable: NaN: Float: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Float.NaN));
            assertEquals("parsable: NaN: Double: " + type.getSimpleName(), expected,
                    parsable.invoke(numob, Double.NaN));

            if (Byte.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Short.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getByte(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getByte(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Short.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 1234.56f));
            }
            if (Short.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Integer.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getShort(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getShort(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Integer.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 12345.6f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 123456.789f));
            }
            if (Integer.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MIN_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Long.MAX_VALUE));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123456.789f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getInt(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getInt(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MIN_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Long.MAX_VALUE));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456d));
            }
            if (Long.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("parsable: fraction: " + type.getSimpleName(), false,
                        parsable.invoke(numob, 123.456f));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MIN_VALUE").getLong(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getLong(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MIN_VALUE).pow(2)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, BigInteger.valueOf(Long.MAX_VALUE).pow(2)));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123456.789f));
                assertEquals("contains: overflow: fraction: " + type.getSimpleName(), false,
                        contains.invoke(numob, 12345678912345678912.3456f));
            }
            if (Float.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, -Double.MAX_VALUE));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), false,
                        parsable.invoke(numob, Double.MAX_VALUE));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getFloat(null)));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, -Double.MAX_VALUE));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, Double.MAX_VALUE));
            }
            if (Double.class.equals(wrapper)) {
                assertEquals("parsable: contains: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: contains: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("parsable: overflow: min: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("parsable: overflow: max: " + type.getSimpleName(), true,
                        parsable.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));

                assertEquals("contains: min: " + type.getSimpleName(), true,
                        contains.invoke(numob, -wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: max: " + type.getSimpleName(), true,
                        contains.invoke(numob, wrapper.getField("MAX_VALUE").getDouble(null)));
                assertEquals("contains: overflow: min: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN).negate()));
                assertEquals("contains: overflow: max: " + type.getSimpleName(), false,
                        contains.invoke(numob, INFINITY_DOUBLE.multiply(BigDecimal.TEN)));
            }
            if (!ClassUtils.isPrimitiveWrapper(wrapper)) {
                assertEquals("parsable: fraction: " + type.getSimpleName(), BigDecimal.class.equals(type),
                        parsable.invoke(numob, 123.456f));
                assertEquals("contains: fraction: " + type.getSimpleName(), true,
                        contains.invoke(numob, 123.456f));
            }

            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "123");
            } else {
                expected = new BigDecimal("123");
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            for (Class<?> valueType : OBJECTS) {
                if (ClassUtils.isPrimitiveWrapper(valueType)) {
                    n = (Number) valueType.getMethod("valueOf", String.class).invoke(null, "123");
                } else {
                    n = new BigDecimal("123");
                    if (BigInteger.class.equals(valueType))
                        n = ((BigDecimal) n).toBigInteger();
                }
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                        expected, valueOf.invoke(numob, n));
                assertEquals(
                        "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: "
                                + type.getSimpleName(),
                        expected.getClass(), valueOf.invoke(numob, n).getClass());
            }

            n = 123.456f;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Float) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = 1.23456789E-6d;
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, n.toString());
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null,
                        Integer.toString(((Double) n).intValue()));
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: " + n + " (" + n.getClass().getSimpleName() + "): " + type.getSimpleName(),
                    expected, valueOf.invoke(numob, n));
            assertEquals(
                    "valueOf: " + n + " (" + n.getClass().getSimpleName() + "): class: " + type.getSimpleName(),
                    expected.getClass(), valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2);
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: " + type.getSimpleName(), expected, valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());

            n = INFINITY_DOUBLE.pow(2).negate();
            if (ObjectUtils.isAny(wrapper, Float.class, Double.class)) {
                expected = wrapper.getField("NEGATIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MIN_VALUE").get(null);
            } else {
                expected = new BigDecimal(n.toString());
                if (BigInteger.class.equals(wrapper))
                    expected = ((BigDecimal) expected).toBigInteger();
            }
            assertEquals("valueOf: Huge: negative: " + type.getSimpleName(), expected,
                    valueOf.invoke(numob, n));
            assertEquals("valueOf: Huge: negative: class: " + type.getSimpleName(), expected.getClass(),
                    valueOf.invoke(numob, n).getClass());
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}

From source file:io.warp10.continuum.gts.GTSHelper.java

/**
 * Apply a mapper on a GeoTimeSerie instance and produce a new
 * GTS instance with the result of the mapper application.
 * //from w w  w . j a  v a  2  s  .  c  o m
 * @param gts GTS instance to apply the mapper on
 * @param mapper Mapper Function to use
 * @param prewindow Number of ticks or time interval to consider BEFORE each tick for which the computation is done.
 *                  If number is 0, don't consider any ticks prior to the current one.
 *                  If number is > 0, consider that many ticks prior to the current one.
 *                  If number is < 0, consider that number negated of microseconds prior to the current tick.
 *                  A delta comparison from the previous value will need a prewindow of 1 (1 tick before the current one).   *                  
 * @param postwindow Same meaning as 'prewindow' but for the interval AFTER each tick.
 * @param occurrences Number of times to apply map, 0 means apply it for each tick. This is useful for some computations like
 *                    sums where the only result that might matter is that of the latest tick
 * @param reversed Compute ticks backwards, starting from most recent one
 * @param step How many ticks to move the sliding window after each mapper application (>=1)
 * @param overrideTick If true, use the tick returned by the mapper instead of the current tick. This may lead to duplicate ticks, need to run DEDUP.
 *                    
 * @return A new GTS instance with the result of the Mapper.
 */
public static List<GeoTimeSerie> map(GeoTimeSerie gts, WarpScriptMapperFunction mapper, long prewindow,
        long postwindow, long occurrences, boolean reversed, int step, boolean overrideTick)
        throws WarpScriptException {

    //
    // Make sure step is positive
    //

    if (step <= 0) {
        step = 1;
    }

    List<GeoTimeSerie> results = new ArrayList<GeoTimeSerie>();

    //
    // Clone gts
    //

    GeoTimeSerie mapped = gts.clone();

    //
    // Do nothing if there are no values and gts was not bucketized
    //

    if (0 == mapped.values && !isBucketized(mapped)) {
        results.add(mapped);
        return results;
    }

    // Sort ticks
    sort(mapped, reversed);
    // Retrieve ticks if GTS is not bucketized.        
    long[] ticks = isBucketized(gts) ? null : Arrays.copyOf(mapped.ticks, gts.values);

    // Clear clone
    GTSHelper.clear(mapped);

    int idx = 0;
    // Number of ticks for which to run the mapper
    int nticks = null != ticks ? ticks.length : mapped.bucketcount;

    // Call getLabels once so we don't waste CPU cycles, this will create a clone of the labels map
    Map<String, String> labels = gts.getLabels();

    long tick = 0;

    GeoTimeSerie subgts = null;

    boolean hasOccurrences = (0 != occurrences);

    Map<String, GeoTimeSerie> multipleMapped = new TreeMap<String, GeoTimeSerie>();

    boolean hasSingleResult = false;

    while (idx < nticks) {

        if (hasOccurrences && 0 == occurrences) {
            break;
        }

        if (reversed) {
            tick = null != ticks ? ticks[idx] : mapped.lastbucket - idx * mapped.bucketspan;
        } else {
            tick = null != ticks ? ticks[idx]
                    : mapped.lastbucket - (mapped.bucketcount - 1 - idx) * mapped.bucketspan;
        }

        //
        // Determine start/stop timestamp for extracting subserie
        //

        long start = tick;
        long stop = tick;

        if (prewindow < 0) {
            start = tick + prewindow;
        } else if (prewindow > 0) {
            // window is a number of ticks
            if (null == ticks) {
                start = prewindow <= mapped.bucketcount ? tick - prewindow * mapped.bucketspan : Long.MIN_VALUE;
            } else {
                if (reversed) {
                    start = idx + prewindow < ticks.length ? (ticks[idx + (int) prewindow]) : Long.MIN_VALUE;
                } else {
                    start = idx - prewindow >= 0 ? (ticks[idx - (int) prewindow]) : Long.MIN_VALUE;
                }
            }
        }

        if (postwindow < 0) {
            stop = tick - postwindow;
        } else if (postwindow > 0) {
            // window is a number of ticks
            if (null == ticks) {
                stop = postwindow <= mapped.bucketcount ? tick + postwindow * mapped.bucketspan
                        : Long.MAX_VALUE;
            } else {
                if (reversed) {
                    stop = idx - postwindow >= 0 ? (ticks[idx - (int) postwindow]) : Long.MAX_VALUE;
                } else {
                    stop = idx + postwindow < ticks.length ? (ticks[idx + (int) postwindow]) : Long.MAX_VALUE;
                }
            }
        }

        //
        // Extract values 
        //

        subgts = GTSHelper.subSerie(gts, start, stop, false, false, subgts);

        //
        // Mapper functions have 8 parameters
        //
        // tick: timestamp we're computing the value for
        // names: array of names (for reducer compatibility)
        // labels: array of labels (for reducer compatibility)
        // ticks: array of ticks being aggregated
        // locations: array of locations being aggregated
        // elevations: array of elevations being aggregated
        // values: array of values being aggregated
        // window: An array with the window parameters [ prewindow, postwindow, start, stop, tick index ] on which the mapper runs
        //
        // 'window' nullity should be checked prior to using to allow mappers to be used as reducers.
        //
        // They return an array of 4 values:
        //
        // timestamp, location, elevation, value
        //
        // timestamp: an indication relative to timestamp (may be the timestamp at which the returned value was observed).
        //            it is usually not used (the returned value will be set at 'tick') but must be present.
        // location: location associated with the returned value
        // elevation: elevation associated with the returned value
        // value: computed value
        //

        Object[] parms = new Object[8];

        int i = 0;
        parms[i++] = tick;

        //
        // All arrays are allocated each time, so we don't risk
        // having a rogue mapper modify them.
        //

        parms[i++] = new String[subgts.values];
        Arrays.fill((Object[]) parms[i - 1], gts.getName());

        parms[i++] = new Map[subgts.values];
        Arrays.fill((Object[]) parms[i - 1], labels);

        parms[i++] = subgts.values > 0 ? Arrays.copyOf(subgts.ticks, subgts.values) : new long[0];
        if (null != subgts.locations) {
            parms[i++] = subgts.values > 0 ? Arrays.copyOf(subgts.locations, subgts.values) : new long[0];
        } else {
            if (subgts.values > 0) {
                parms[i++] = new long[subgts.values];
                Arrays.fill((long[]) parms[i - 1], GeoTimeSerie.NO_LOCATION);
            } else {
                parms[i++] = new long[0];
            }
        }
        if (null != subgts.elevations) {
            parms[i++] = subgts.values > 0 ? Arrays.copyOf(subgts.elevations, subgts.values) : new long[0];
        } else {
            if (subgts.values > 0) {
                parms[i++] = new long[subgts.values];
                Arrays.fill((long[]) parms[i - 1], GeoTimeSerie.NO_ELEVATION);
            } else {
                parms[i++] = new long[0];
            }
        }
        parms[i++] = new Object[subgts.values];

        int tickidx = -1;

        for (int j = 0; j < subgts.values; j++) {
            ((Object[]) parms[6])[j] = valueAtIndex(subgts, j);
            if (-1 == tickidx && tick == tickAtIndex(subgts, j)) {
                tickidx = j;
            }
        }

        parms[i++] = new long[] { prewindow, postwindow, start, stop, tickidx };

        Object mapResult = mapper.apply(parms);

        if (mapResult instanceof Map) {
            for (Entry<Object, Object> entry : ((Map<Object, Object>) mapResult).entrySet()) {
                GeoTimeSerie mgts = multipleMapped.get(entry.getKey().toString());
                if (null == mgts) {
                    mgts = mapped.cloneEmpty();

                    mgts.setName(entry.getKey().toString());
                    multipleMapped.put(entry.getKey().toString(), mgts);
                }

                Object[] result = (Object[]) entry.getValue();
                if (null != result[3]) {
                    GTSHelper.setValue(mgts, overrideTick ? (long) result[0] : tick, (long) result[1],
                            (long) result[2], result[3], false);
                }
            }
        } else {
            Object[] result = (Object[]) mapResult;

            //
            // Set value if it was not null. Don't overwrite, we scan ticks only once
            //

            hasSingleResult = true;

            if (null != result[3]) {
                GTSHelper.setValue(mapped, overrideTick ? (long) result[0] : tick, (long) result[1],
                        (long) result[2], result[3], false);
            }
        }

        idx += step;
        occurrences--;
    }

    if (hasSingleResult) {
        results.add(mapped);
    }

    if (!multipleMapped.isEmpty()) {
        results.addAll(multipleMapped.values());
    }

    return results;
}

From source file:com.sonymobile.android.media.internal.ISOBMFFParser.java

@Override
public long getLong(String key) {
    if (mMetaDataValues.containsKey(key)) {
        Long val = (Long) (mMetaDataValues.get(key));
        return val.longValue();
    }//  ww  w. j a  v a  2 s .  c  om
    return Long.MIN_VALUE;
}

From source file:io.warp10.continuum.gts.GTSHelper.java

/**
 * Return the last tick in the GTS instance.
 * /*from  w  ww .j av  a 2s.  c  o  m*/
 * @param gts GeoTimeSerie to return the last tick for.
 * 
 * @return The last tick or Long.MIN_VALUE if 'gts' is not bucketized and has no values.
 */
public static long lasttick(GeoTimeSerie gts) {
    if (isBucketized(gts)) {
        return gts.lastbucket;
    } else {
        long lasttick = Long.MIN_VALUE;

        if (gts.sorted && gts.values > 0) {
            if (!gts.reversed) {
                lasttick = gts.ticks[gts.values - 1];
            } else {
                lasttick = gts.ticks[0];
            }
        } else {
            for (int i = 0; i < gts.values; i++) {
                if (gts.ticks[i] > lasttick) {
                    lasttick = gts.ticks[i];
                }
            }
        }

        return lasttick;
    }
}

From source file:io.warp10.continuum.gts.GTSHelper.java

public static Map<Map<String, String>, List<GeoTimeSerie>> reduceUnflattened(WarpScriptReducerFunction reducer,
        Collection<GeoTimeSerie> series, Collection<String> bylabels) throws WarpScriptException {
    ///*  w  w  w  . j a v a2s  .c o m*/
    // Partition the GTS instances using the given labels
    //

    Map<Map<String, String>, List<GeoTimeSerie>> partitions = partition(series, bylabels);

    Map<Map<String, String>, List<GeoTimeSerie>> results = new LinkedHashMap<Map<String, String>, List<GeoTimeSerie>>();

    for (Map<String, String> partitionLabels : partitions.keySet()) {
        boolean singleGTSResult = false;

        List<GeoTimeSerie> partitionSeries = partitions.get(partitionLabels);

        //
        // Extract labels and common labels
        //

        Map[] partlabels = new Map[partitionSeries.size() + 1];

        for (int i = 0; i < partitionSeries.size(); i++) {
            partlabels[i] = partitionSeries.get(i).getLabels();
        }

        partlabels[partitionSeries.size()] = Collections.unmodifiableMap(partitionLabels);

        //
        // Determine if result should be bucketized or not.
        // Result will be bucketized if all GTS instances in the partition are
        // bucketized, have the same bucketspan and have congruent lastbucket values
        //

        long endbucket = Long.MIN_VALUE;
        long startbucket = Long.MAX_VALUE;
        long lastbucket = Long.MIN_VALUE;
        long bucketspan = 0L;

        for (GeoTimeSerie gts : partitionSeries) {
            // One GTS instance is not bucketized, result won't be either
            if (!isBucketized(gts)) {
                bucketspan = 0L;
                break;
            }
            if (0L == bucketspan) {
                bucketspan = gts.bucketspan;
            } else if (bucketspan != gts.bucketspan) {
                // GTS has a bucketspan which differs from the previous one,
                // so result won't be bucketized.
                bucketspan = 0L;
                break;
            }
            if (Long.MIN_VALUE == lastbucket) {
                lastbucket = gts.lastbucket;
            }
            if (lastbucket % bucketspan != gts.lastbucket % gts.bucketspan) {
                // GTS has a lastbucket value which is not congruent to the other
                // lastbucket values, so result GTS won't be bucketized.
                bucketspan = 0L;
                break;
            }
            //
            // Update start/end bucket
            //

            if (gts.lastbucket > endbucket) {
                endbucket = gts.lastbucket;
            }
            if (gts.lastbucket - gts.bucketcount * gts.bucketspan < startbucket) {
                startbucket = gts.lastbucket - gts.bucketcount * gts.bucketspan;
            }
        }

        //
        // Determine bucketcount if result is to be bucketized
        // startbucket is the end of the first bucket not considered
        //

        int bucketcount = 0;

        if (0L != bucketspan) {
            bucketcount = (int) ((endbucket - startbucket) / bucketspan);
        }

        //
        // Create target GTS
        //

        GeoTimeSerie result;

        if (0L != bucketspan) {
            result = new GeoTimeSerie(lastbucket, bucketcount, bucketspan, 0);
        } else {
            result = new GeoTimeSerie();
        }

        result.setName("");
        result.setLabels(partitionLabels);

        //
        // Sort all series in the partition so we can scan their ticks in order
        //

        for (GeoTimeSerie gts : partitionSeries) {
            sort(gts, false);
        }

        Map<String, GeoTimeSerie> multipleResults = new TreeMap<String, GeoTimeSerie>();

        //
        // Initialize indices for each serie
        //

        int[] idx = new int[partitionSeries.size()];

        //
        // Initialize names/labels/location/elevation/value arrays
        //

        long[] ticks = new long[idx.length];
        String[] names = new String[idx.length];
        // Allocate 1 more slot for labels so we can store the common labels at the end of the array
        Map<String, String>[] lbls = Arrays.copyOf(partlabels, partlabels.length);

        long[] locations = new long[idx.length];
        long[] elevations = new long[idx.length];
        Object[] values = new Object[idx.length];

        //
        // Reducers have 7 parameters (similar to those of binary ops and mappers)
        //
        // tick for which value is computed
        // array of ticks
        // array of names
        // array of labels
        // array of locations
        // array of elevations
        // array of values
        //

        Object[] params = new Object[7];

        while (true) {
            //
            // Determine the tick span at the given indices
            //

            long smallest = Long.MAX_VALUE;

            for (int i = 0; i < idx.length; i++) {
                GeoTimeSerie gts = partitionSeries.get(i);
                if (idx[i] < gts.values) {
                    if (gts.ticks[idx[i]] < smallest) {
                        smallest = gts.ticks[idx[i]];
                    }
                }
            }

            //
            // No smallest tick, this means we've exhausted all values
            //

            if (Long.MAX_VALUE == smallest) {
                break;
            }

            //
            // Now fill the locations/elevations/values arrays for all GTS
            // instances whose current tick is 'smallest'
            //

            for (int i = 0; i < idx.length; i++) {
                GeoTimeSerie gts = partitionSeries.get(i);
                if (idx[i] < gts.values && smallest == gts.ticks[idx[i]]) {
                    ticks[i] = smallest;
                    names[i] = gts.getName();
                    //if (null == lbls[i]) {
                    //  lbls[i] = gts.getLabels();
                    //}
                    locations[i] = null != gts.locations ? gts.locations[idx[i]] : GeoTimeSerie.NO_LOCATION;
                    elevations[i] = null != gts.elevations ? gts.elevations[idx[i]] : GeoTimeSerie.NO_ELEVATION;
                    values[i] = GTSHelper.valueAtIndex(gts, idx[i]);
                    // Advance idx[i] since it was the smallest tick.
                    idx[i]++;
                } else {
                    ticks[i] = Long.MIN_VALUE;
                    names[i] = gts.getName();
                    //if (null == lbls[i]) {
                    //  lbls[i] = gts.getLabels();
                    //}
                    locations[i] = GeoTimeSerie.NO_LOCATION;
                    elevations[i] = GeoTimeSerie.NO_ELEVATION;
                    values[i] = null;
                }
            }

            //
            // Call the reducer for the current tick
            //
            // Return value will be an array [tick, location, elevation, value]
            //

            // TODO(hbs): extend reducers to use a window instead of a single value when reducing.
            //            ticks/locations/elevations/values would be arrays of arrays and an 8th param
            //            could contain the values.

            params[0] = smallest;
            params[1] = names;
            params[2] = lbls;
            params[3] = ticks;
            params[4] = locations;
            params[5] = elevations;
            params[6] = values;

            Object reducerResult = reducer.apply(params);

            if (reducerResult instanceof Map) {
                for (Entry<Object, Object> entry : ((Map<Object, Object>) reducerResult).entrySet()) {
                    GeoTimeSerie gts = multipleResults.get(entry.getKey().toString());
                    if (null == gts) {
                        if (0L != bucketspan) {
                            gts = new GeoTimeSerie(lastbucket, bucketcount, bucketspan, 0);
                        } else {
                            gts = new GeoTimeSerie();
                        }

                        gts.setName(entry.getKey().toString());
                        gts.setLabels(partitionLabels);
                        multipleResults.put(entry.getKey().toString(), gts);
                    }

                    Object[] reduced = (Object[]) entry.getValue();

                    if (null != reduced[3]) {
                        GTSHelper.setValue(gts, smallest, (long) reduced[1], (long) reduced[2], reduced[3],
                                false);
                    }
                }
            } else {
                Object[] reduced = (Object[]) reducerResult;
                singleGTSResult = true;
                if (null != reduced[3]) {
                    GTSHelper.setValue(result, smallest, (long) reduced[1], (long) reduced[2], reduced[3],
                            false);
                }
            }

        }

        if (!results.containsKey(partitionLabels)) {
            results.put(partitionLabels, new ArrayList<GeoTimeSerie>());
        }

        if (singleGTSResult) {
            results.get(partitionLabels).add(result);
        }

        if (!multipleResults.isEmpty()) {
            results.get(partitionLabels).addAll(multipleResults.values());
        }
    }

    return results;
}