Search in sources :

Example 1 with ObjectFactory

use of org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory 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 2 with ObjectFactory

use of org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory in project legend-pure by finos.

the class JsonClassDeserialization method apply.

@Override
public T apply(Object input, ConversionContext context) {
    if (input instanceof JSONObject) {
        JsonDeserializationContext deserializationContext = (JsonDeserializationContext) context;
        ObjectFactory objectFactory = deserializationContext.getObjectFactory();
        JSONObject jsonObject = (JSONObject) input;
        Map<String, RichIterable<?>> propertyKeyValues = this.keyValueProperties(jsonObject, deserializationContext);
        try {
            return (T) objectFactory.newObject(this.clazz, propertyKeyValues);
        } catch (PureExecutionException e) {
            throw new PureExecutionException(deserializationContext.getSourceInformation(), "Could not create new instance of " + this.pureTypeAsString() + ": \n" + e.getInfo());
        }
    } else {
        // Currently this should be ignored.
        return null;
    }
}
Also used : RichIterable(org.eclipse.collections.api.RichIterable) JSONObject(org.json.simple.JSONObject) ObjectFactory(org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException)

Example 3 with ObjectFactory

use of org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory in project legend-pure by finos.

the class JsonNativeImplementation method _fromJson.

public static <T> T _fromJson(String json, Class<T> clazz, String _typeKeyName, boolean _failOnUnknownProperties, SourceInformation si, ExecutionSupport es, ConstraintsOverride constraintsHandler, RichIterable<? extends Pair<? extends String, ? extends String>> _typeLookup) {
    java.lang.Class c;
    String targetClassName = null;
    try {
        targetClassName = JavaPackageAndImportBuilder.platformJavaPackage() + ".Root_" + platform_pure_corefunctions_meta.Root_meta_pure_functions_meta_elementToPath_PackageableElement_1__String_1__String_1_(clazz, "_", es);
        c = ((CompiledExecutionSupport) es).getClassLoader().loadClass(targetClassName);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unable to find  class " + targetClassName, e);
    }
    Map<String, Class> typeLookup = new HashMap<String, Class>();
    for (Pair<? extends String, ? extends String> pair : _typeLookup) {
        typeLookup.put(pair._first(), ((CompiledExecutionSupport) es).getMetadataAccessor().getClass("Root::" + pair._second()));
    }
    return (T) JsonDeserializer.fromJson(json, (Class<? extends Any>) clazz, new JsonDeserializationContext(new JsonDeserializationCache(), si, ((CompiledExecutionSupport) es).getProcessorSupport(), _typeKeyName, typeLookup, _failOnUnknownProperties, new ObjectFactory() {

        public <U extends Any> U newObject(Class<U> clazz, Map<String, RichIterable<?>> properties) {
            FastList<KeyValue> keyValues = new FastList<>();
            for (Map.Entry<String, RichIterable<?>> property : properties.entrySet()) {
                KeyValue keyValue = new Root_meta_pure_functions_lang_KeyValue_Impl("Anonymous");
                keyValue._key(property.getKey());
                for (Object value : property.getValue()) {
                    keyValue._valueAdd(value);
                }
                keyValues.add(keyValue);
            }
            U result = (U) Pure.newObject(clazz, keyValues, null, null, null, null, null, null, es);
            result._elementOverride(constraintsHandler);
            return (U) handleValidation(true, result, si, es);
        }

        public <T extends Any> T newUnitInstance(CoreInstance propertyType, String unitTypeString, Number unitValue) throws Exception {
            CoreInstance unitRetrieved = ((CompiledExecutionSupport) es).getProcessorSupport().package_getByUserPath(unitTypeString);
            if (!((CompiledExecutionSupport) es).getProcessorSupport().type_subTypeOf(unitRetrieved, propertyType)) {
                throw new PureExecutionException("Cannot match unit type: " + unitTypeString + " as subtype of type: " + PackageableElement.getUserPathForPackageableElement(propertyType));
            }
            String unitClassName = UnitProcessor.convertToJavaCompatibleClassName(JavaPackageAndImportBuilder.buildImplUnitInstanceClassNameFromType(unitRetrieved));
            java.lang.Class c = ((CompiledExecutionSupport) es).getClassLoader().loadClass("org.finos.legend.pure.generated." + unitClassName);
            java.lang.Class[] paramClasses = new java.lang.Class[] { String.class, ExecutionSupport.class };
            Method method = c.getMethod("_val", Number.class);
            Object classInstance = c.getConstructor(paramClasses).newInstance("Anonymous_NoCounter", es);
            method.invoke(classInstance, unitValue);
            return (T) classInstance;
        }
    }));
}
Also used : KeyValue(org.finos.legend.pure.m3.coreinstance.meta.pure.functions.lang.KeyValue) HashMap(java.util.HashMap) Any(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Any) JsonDeserializationContext(org.finos.legend.pure.runtime.java.extension.external.json.shared.JsonDeserializationContext) ObjectFactory(org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) FastList(org.eclipse.collections.impl.list.mutable.FastList) Root_meta_pure_functions_lang_KeyValue_Impl(org.finos.legend.pure.generated.Root_meta_pure_functions_lang_KeyValue_Impl) Method(java.lang.reflect.Method) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) RichIterable(org.eclipse.collections.api.RichIterable) JsonDeserializationCache(org.finos.legend.pure.runtime.java.extension.external.json.shared.JsonDeserializationCache) CompiledExecutionSupport(org.finos.legend.pure.runtime.java.compiled.execution.CompiledExecutionSupport) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) Class(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class)

Example 4 with ObjectFactory

use of org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory in project legend-pure by finos.

the class JsonUnitDeserialization method apply.

@Override
public T apply(Object value, ConversionContext context) {
    String unitTypeString;
    Number unitTypeExponent;
    boolean isComposite;
    JSONArray unitsJsonArray;
    try {
        unitsJsonArray = (JSONArray) ((JSONObject) value).get(this.unitKeyName);
        unitTypeString = ((JSONObject) unitsJsonArray.get(0)).get("unitId").toString();
        unitTypeExponent = (Number) ((JSONObject) unitsJsonArray.get(0)).get("exponentValue");
    } catch (Exception e) {
        throw new PureExecutionException("Mal-formatted Json for unit.");
    }
    isComposite = 1 != unitsJsonArray.size();
    if (isComposite) {
        throw new PureExecutionException("Currently composite units are not supported.");
    }
    if (!Long.valueOf(1).equals(unitTypeExponent)) {
        throw new PureExecutionException("Currently non-one exponent for unit is not supported. Got: " + unitTypeExponent.toString() + ".");
    }
    Number unitValue;
    try {
        unitValue = (Number) ((JSONObject) value).get(this.valueKeyName);
    } catch (ClassCastException cce) {
        throw new PureExecutionException("Value from unitValue field must be of Number type, getting " + ((JSONObject) value).get(this.valueKeyName).getClass().getName() + " type instead.");
    }
    JsonDeserializationContext deserializationContext = (JsonDeserializationContext) context;
    ObjectFactory objectFactory = deserializationContext.getObjectFactory();
    try {
        return (T) objectFactory.newUnitInstance(this.type, unitTypeString, unitValue);
    } catch (Exception e) {
        throw new PureExecutionException(deserializationContext.getSourceInformation(), "Could not create new instance of " + this.pureTypeAsString());
    }
}
Also used : JSONObject(org.json.simple.JSONObject) ObjectFactory(org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) JSONArray(org.json.simple.JSONArray) PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException)

Aggregations

PureExecutionException (org.finos.legend.pure.m3.exception.PureExecutionException)4 ObjectFactory (org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory)4 RichIterable (org.eclipse.collections.api.RichIterable)3 FastList (org.eclipse.collections.impl.list.mutable.FastList)2 Any (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Any)2 Class (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class)2 CoreInstance (org.finos.legend.pure.m4.coreinstance.CoreInstance)2 JsonDeserializationCache (org.finos.legend.pure.runtime.java.extension.external.json.shared.JsonDeserializationCache)2 JsonDeserializationContext (org.finos.legend.pure.runtime.java.extension.external.json.shared.JsonDeserializationContext)2 JSONObject (org.json.simple.JSONObject)2 Method (java.lang.reflect.Method)1 BigDecimal (java.math.BigDecimal)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 MutableMap (org.eclipse.collections.api.map.MutableMap)1 UnifiedMap (org.eclipse.collections.impl.map.mutable.UnifiedMap)1 Root_meta_pure_functions_lang_KeyValue_Impl (org.finos.legend.pure.generated.Root_meta_pure_functions_lang_KeyValue_Impl)1 KeyValue (org.finos.legend.pure.m3.coreinstance.meta.pure.functions.lang.KeyValue)1 ConstraintsOverride (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride)1 EnumInstance (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.EnumInstance)1