Search in sources :

Example 1 with DateTime

use of org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime in project legend-pure by finos.

the class TestNewInstance method testTimeWithWrongStrictTimeType.

@Test
public void testTimeWithWrongStrictTimeType() {
    compileTestSource("testModel.pure", "Class A\n" + "{\n" + "    prop:StrictTime[1];\n" + "}");
    PureCompilationException e = Assert.assertThrows(PureCompilationException.class, () -> compileTestSource("testFunc.pure", "function testFunc():A[1]\n" + "{\n" + "    ^A(prop=%2014-02-07T07:03:01)\n" + "}"));
    assertPureException(PureCompilationException.class, "Type Error: DateTime not a subtype of StrictTime", "testFunc.pure", 3, 12, 3, 12, 3, 12, e);
}
Also used : PureCompilationException(org.finos.legend.pure.m4.exception.PureCompilationException) Test(org.junit.Test)

Example 2 with DateTime

use of org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime in project legend-pure by finos.

the class CompiledSupport method newDate.

public static DateTime newDate(long year, long month, long day, long hour, long minute, Number second, SourceInformation sourceInformation) {
    int secondInt;
    String subsecond = null;
    if ((second instanceof Integer) || (second instanceof Long) || (second instanceof BigInteger)) {
        // TODO check if the number is too large for an int
        secondInt = second.intValue();
    } else if ((second instanceof Float) || (second instanceof Double)) {
        secondInt = second.intValue();
        String string = BigDecimal.valueOf(second.doubleValue()).toPlainString();
        int index = string.indexOf('.');
        subsecond = (index == -1) ? "0" : string.substring(index + 1);
    } else if (second instanceof BigDecimal) {
        secondInt = second.intValue();
        String string = ((BigDecimal) second).toPlainString();
        int index = string.indexOf('.');
        if (index != -1) {
            subsecond = string.substring(index + 1);
        }
    } else {
        throw new PureExecutionException(sourceInformation, "Unhandled number: " + second);
    }
    try {
        return (subsecond == null) ? DateFunctions.newPureDate((int) year, (int) month, (int) day, (int) hour, (int) minute, secondInt) : DateFunctions.newPureDate((int) year, (int) month, (int) day, (int) hour, (int) minute, secondInt, subsecond);
    } catch (Exception e) {
        throw new PureExecutionException(sourceInformation, e.getMessage());
    }
}
Also used : BigInteger(java.math.BigInteger) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) BigInteger(java.math.BigInteger) BigDecimal(java.math.BigDecimal) PureAssertFailException(org.finos.legend.pure.m3.exception.PureAssertFailException) InvalidFunctionDescriptorException(org.finos.legend.pure.m3.navigation.function.InvalidFunctionDescriptorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PureJavaCompileException(org.finos.legend.pure.runtime.java.compiled.compiler.PureJavaCompileException) PureException(org.finos.legend.pure.m4.exception.PureException) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) ParseException(org.json.simple.parser.ParseException) NoSuchElementException(java.util.NoSuchElementException)

Example 3 with DateTime

use of org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime in project legend-pure by finos.

the class FromJson method execute.

@Override
public CoreInstance execute(ListIterable<? extends CoreInstance> params, final Stack<MutableMap<String, CoreInstance>> resolvedTypeParameters, final Stack<MutableMap<String, CoreInstance>> resolvedMultiplicityParameters, final VariableContext variableContext, final CoreInstance functionExpressionToUseInStack, final Profiler profiler, final InstantiationContext instantiationContext, final ExecutionSupport executionSupport, final Context context, final ProcessorSupport processorSupport) throws PureExecutionException {
    final SourceInformation si = functionExpressionToUseInStack.getSourceInformation();
    Class startingClass = (Class) Instance.getValueForMetaPropertyToOneResolved(params.get(1), M3Properties.values, processorSupport);
    CoreInstance config = Instance.getValueForMetaPropertyToOneResolved(params.get(2), M3Properties.values, processorSupport);
    String typeKeyName = ((StringCoreInstance) config.getValueForMetaPropertyToOne("typeKeyName")).getValue();
    Map<String, Class> keyLookup = new UnifiedMap<String, Class>();
    for (CoreInstance o : config.getValueForMetaPropertyToMany("typeLookup")) {
        keyLookup.put(o.getValueForMetaPropertyToOne("first").getName(), (Class) _Package.getByUserPath(o.getValueForMetaPropertyToOne("second").getName(), functionExecution.getProcessorSupport()));
    }
    Boolean failOnUnknownProperties = ((BooleanCoreInstance) config.getValueForMetaPropertyToOne("failOnUnknownProperties")).getValue();
    final ConstraintsOverride constraintsOverride = (ConstraintsOverride) config.getValueForMetaPropertyToOne("constraintsHandler");
    String jsonText = PrimitiveUtilities.getStringValue(Instance.getValueForMetaPropertyToOneResolved(params.get(0), M3Properties.values, processorSupport));
    return JsonDeserializer.fromJson(jsonText, startingClass, new JsonDeserializationContext(new JsonDeserializationCache(), si, processorSupport, typeKeyName, keyLookup, failOnUnknownProperties, new ObjectFactory() {

        @Override
        public <T extends Any> T newObject(Class<T> clazz, Map<String, RichIterable<?>> properties) {
            CoreInstance instance = FromJson.this.repository.newEphemeralAnonymousCoreInstance(functionExpressionToUseInStack.getSourceInformation(), clazz);
            for (Entry<String, RichIterable<?>> eachKeyValue : properties.entrySet()) {
                FastList<CoreInstance> values = new FastList<>();
                for (Object eachValue : eachKeyValue.getValue()) {
                    if (eachValue instanceof String) {
                        values.add(FromJson.this.repository.newStringCoreInstance((String) eachValue));
                    } else if (eachValue instanceof Boolean) {
                        values.add(FromJson.this.repository.newBooleanCoreInstance((Boolean) eachValue));
                    } else if (eachValue instanceof Integer) {
                        values.add(FromJson.this.repository.newIntegerCoreInstance((int) eachValue));
                    } else if (eachValue instanceof Long) {
                        values.add(FromJson.this.repository.newIntegerCoreInstance((long) eachValue));
                    } else if (eachValue instanceof BigDecimal) {
                        values.add(FromJson.this.repository.newDecimalCoreInstance((BigDecimal) eachValue));
                    } else if (eachValue instanceof Double || eachValue instanceof Number) {
                        values.add(FromJson.this.repository.newFloatCoreInstance(BigDecimal.valueOf((Double) eachValue)));
                    } else if (eachValue instanceof Year || eachValue instanceof YearMonth) {
                        values.add(FromJson.this.repository.newDateCoreInstance((PureDate) eachValue));
                    } else if (eachValue instanceof StrictDate) {
                        values.add(FromJson.this.repository.newStrictDateCoreInstance((PureDate) eachValue));
                    } else if (eachValue instanceof DateTime || eachValue instanceof LatestDate || eachValue instanceof PureDate) {
                        values.add(FromJson.this.repository.newDateTimeCoreInstance((PureDate) eachValue));
                    } else if (eachValue instanceof InstanceValue) {
                        InstanceValue asInstanceValue = (InstanceValue) eachValue;
                        if (Measure.isUnitOrMeasureInstance(asInstanceValue, processorSupport)) {
                            values.add(asInstanceValue);
                        } else {
                            values.add((CoreInstance) asInstanceValue._values().getFirst());
                        }
                    } else if (eachValue instanceof EnumInstance) {
                        values.add((CoreInstance) eachValue);
                    } else {
                        throw new PureExecutionException(si, "Unknown type from output of JsonDeserializer for property: " + eachKeyValue.getKey());
                    }
                }
                Instance.setValuesForProperty(instance, eachKeyValue.getKey(), values, processorSupport);
            }
            DeserializationUtils.replaceReverseProperties(instance, processorSupport, si);
            CoreInstance override = processorSupport.newAnonymousCoreInstance(si, M3Paths.ConstraintsGetterOverride);
            if (constraintsOverride != null) {
                Instance.addValueToProperty(override, M3Properties.constraintsManager, constraintsOverride._constraintsManager(), processorSupport);
                Instance.addValueToProperty(instance, M3Properties.elementOverride, override, processorSupport);
            }
            CoreInstance value = ValueSpecificationBootstrap.wrapValueSpecification(instance, true, processorSupport);
            return (T) DefaultConstraintHandler.handleConstraints(clazz, value, si, functionExecution, resolvedTypeParameters, resolvedMultiplicityParameters, variableContext, functionExpressionToUseInStack, profiler, instantiationContext, executionSupport);
        }

        public <T extends Any> T newUnitInstance(CoreInstance propertyType, String unitTypeString, Number unitValue) {
            CoreInstance retrievedUnit = processorSupport.package_getByUserPath(unitTypeString);
            if (!processorSupport.type_subTypeOf(retrievedUnit, propertyType)) {
                throw new PureExecutionException("Cannot match unit type: " + unitTypeString + " as subtype of type: " + PackageableElement.getUserPathForPackageableElement(propertyType));
            }
            FastList<CoreInstance> params = new FastList<>();
            params.add(ValueSpecificationBootstrap.wrapValueSpecification(retrievedUnit, false, processorSupport));
            params.add(NumericUtilities.toPureNumberValueExpression(unitValue, false, repository, processorSupport));
            return (T) new NewUnit(repository, functionExecution).execute(params, resolvedTypeParameters, resolvedMultiplicityParameters, variableContext, functionExpressionToUseInStack, profiler, instantiationContext, executionSupport, context, processorSupport);
        }
    }));
}
Also used : UnifiedMap(org.eclipse.collections.impl.map.mutable.UnifiedMap) ConstraintsOverride(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride) InstanceValue(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.valuespecification.InstanceValue) Any(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Any) StrictDate(org.finos.legend.pure.m4.coreinstance.primitive.date.StrictDate) DateTime(org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime) NewUnit(org.finos.legend.pure.runtime.java.interpreted.natives.core.lang.NewUnit) JsonDeserializationContext(org.finos.legend.pure.runtime.java.extension.external.json.shared.JsonDeserializationContext) ObjectFactory(org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory) EnumInstance(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.EnumInstance) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) FastList(org.eclipse.collections.impl.list.mutable.FastList) PureDate(org.finos.legend.pure.m4.coreinstance.primitive.date.PureDate) StringCoreInstance(org.finos.legend.pure.m4.coreinstance.primitive.StringCoreInstance) LatestDate(org.finos.legend.pure.m4.coreinstance.primitive.date.LatestDate) SourceInformation(org.finos.legend.pure.m4.coreinstance.SourceInformation) BigDecimal(java.math.BigDecimal) BooleanCoreInstance(org.finos.legend.pure.m4.coreinstance.primitive.BooleanCoreInstance) RichIterable(org.eclipse.collections.api.RichIterable) JsonDeserializationCache(org.finos.legend.pure.runtime.java.extension.external.json.shared.JsonDeserializationCache) Year(org.finos.legend.pure.m4.coreinstance.primitive.date.Year) YearMonth(org.finos.legend.pure.m4.coreinstance.primitive.date.YearMonth) StringCoreInstance(org.finos.legend.pure.m4.coreinstance.primitive.StringCoreInstance) BooleanCoreInstance(org.finos.legend.pure.m4.coreinstance.primitive.BooleanCoreInstance) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) Class(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class) Map(java.util.Map) UnifiedMap(org.eclipse.collections.impl.map.mutable.UnifiedMap) MutableMap(org.eclipse.collections.api.map.MutableMap) ConstraintsOverride(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride)

Example 4 with DateTime

use of org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime in project legend-pure by finos.

the class JsonDeserializationCache method constructPrimitiveConversions.

@Override
protected Map<PrimitiveConversion.PurePrimitive, PrimitiveConversion<?, ?>> constructPrimitiveConversions() {
    Map<PrimitiveConversion.PurePrimitive, PrimitiveConversion<?, ?>> primitiveConverters = new HashMap<>();
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.Integer, PrimitiveConversion.noOpConversion(Long.class, "Integer", true));
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.String, PrimitiveConversion.noOpConversion(String.class, "String", true));
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.Number, PrimitiveConversion.noOpConversion(Number.class, "Number", true));
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.Boolean, PrimitiveConversion.noOpConversion(Boolean.class, "Boolean", true));
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.Float, new PrimitiveConversion<Number, Double>() {

        @Override
        public Double apply(Number value, ConversionContext context) {
            return value.doubleValue();
        }

        @Override
        public String pureTypeAsString() {
            return "Number";
        }
    });
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.Decimal, new PrimitiveConversion<Number, BigDecimal>() {

        @Override
        public BigDecimal apply(Number value, ConversionContext context) {
            return new BigDecimal(value.toString());
        }

        @Override
        public String pureTypeAsString() {
            return "Number";
        }
    });
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.Date, new PrimitiveConversion<String, PureDate>() {

        @Override
        public PureDate apply(String value, ConversionContext context) {
            return DateFunctions.parsePureDate(value);
        }

        @Override
        public String pureTypeAsString() {
            return "Date";
        }
    });
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.DateTime, new PrimitiveConversion<String, DateTime>() {

        @Override
        public DateTime apply(String value, ConversionContext context) {
            return (DateTime) DateFunctions.parsePureDate(value);
        }

        @Override
        public String pureTypeAsString() {
            return "DateTime";
        }
    });
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.StrictDate, new PrimitiveConversion<String, PureDate>() {

        @Override
        public PureDate apply(String value, ConversionContext context) {
            return DateFunctions.parsePureDate(value);
        }

        @Override
        public String pureTypeAsString() {
            return "StrictDate";
        }
    });
    primitiveConverters.put(PrimitiveConversion.PurePrimitive.LatestDate, new PrimitiveConversion<String, LatestDate>() {

        @Override
        public LatestDate apply(String value, ConversionContext context) {
            return LatestDate.instance;
        }

        @Override
        public String pureTypeAsString() {
            return "LatestDate";
        }
    });
    return primitiveConverters;
}
Also used : ConversionContext(org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ConversionContext) HashMap(java.util.HashMap) PureDate(org.finos.legend.pure.m4.coreinstance.primitive.date.PureDate) LatestDate(org.finos.legend.pure.m4.coreinstance.primitive.date.LatestDate) PrimitiveConversion(org.finos.legend.pure.runtime.java.extension.external.shared.conversion.PrimitiveConversion) BigDecimal(java.math.BigDecimal) DateTime(org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime)

Example 5 with DateTime

use of org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime in project legend-pure by finos.

the class AbstractTestNow method testNow.

@Test
public void testNow() {
    compileTestSource("function test::nowWrapper():DateTime[1] { meta::pure::functions::date::now() }");
    long tolerance = 100;
    long before = System.currentTimeMillis();
    CoreInstance result = execute("test::nowWrapper():DateTime[1]");
    long after = System.currentTimeMillis();
    for (int i = 0; ((after - before) > tolerance) && (i < 10); i++) {
        before = System.currentTimeMillis();
        result = execute("test::nowWrapper():DateTime[1]");
        after = System.currentTimeMillis();
    }
    if ((after - before) > tolerance) {
        throw new RuntimeException("Could not get valid test, total duration (" + (after - before) + "ms) was greater than tolerance (" + tolerance + "ms)");
    }
    CoreInstance date = Instance.getValueForMetaPropertyToOneResolved(result, M3Properties.values, processorSupport);
    PureDate pureDate = PrimitiveUtilities.getDateValue(date);
    // Check that the date has millisecond precision
    Assert.assertTrue(pureDate.hasSubsecond());
    Assert.assertEquals(3, pureDate.getSubsecond().length());
    // Compare with before and after epoch millis
    long actual = pureDate.getCalendar().getTimeInMillis();
    Assert.assertTrue("Expected actual (" + pureDate + ") to be between " + Instant.ofEpochMilli(before) + " and " + Instant.ofEpochMilli(after), (before <= actual) && (actual <= after));
}
Also used : CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) PureDate(org.finos.legend.pure.m4.coreinstance.primitive.date.PureDate) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)4 BigDecimal (java.math.BigDecimal)3 CoreInstance (org.finos.legend.pure.m4.coreinstance.CoreInstance)3 PureDate (org.finos.legend.pure.m4.coreinstance.primitive.date.PureDate)3 PureExecutionException (org.finos.legend.pure.m3.exception.PureExecutionException)2 DateTime (org.finos.legend.pure.m4.coreinstance.primitive.date.DateTime)2 LatestDate (org.finos.legend.pure.m4.coreinstance.primitive.date.LatestDate)2 PureCompilationException (org.finos.legend.pure.m4.exception.PureCompilationException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 BigInteger (java.math.BigInteger)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 NoSuchElementException (java.util.NoSuchElementException)1 RichIterable (org.eclipse.collections.api.RichIterable)1 MutableMap (org.eclipse.collections.api.map.MutableMap)1 FastList (org.eclipse.collections.impl.list.mutable.FastList)1 UnifiedMap (org.eclipse.collections.impl.map.mutable.UnifiedMap)1 Any (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Any)1 Class (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class)1 ConstraintsOverride (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride)1