Search in sources :

Example 1 with ConstraintsOverride

use of org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride 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 ConstraintsOverride

use of org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride in project legend-pure by finos.

the class ClassJsonFactoryProcessor method processClass.

public static void processClass(final CoreInstance classGenericType, ProcessorContext processorContext) {
    final ProcessorSupport processorSupport = processorContext.getSupport();
    MutableList<StringJavaSource> classes = processorContext.getClasses();
    MutableSet<CoreInstance> processedClasses = processorContext.getProcessedClasses(ClassJsonFactoryProcessor.class);
    CoreInstance _class = Instance.getValueForMetaPropertyToOneResolved(classGenericType, M3Properties.rawType, processorSupport);
    if (!processedClasses.contains(_class) && !processorSupport.instance_instanceOf(_class, M3Paths.DataType)) {
        processedClasses.add(_class);
        final String className = TypeProcessor.javaInterfaceForType(_class);
        final String thisClassName = className;
        final String userDefinedClassName = PackageableElement.getUserPathForPackageableElement(_class);
        String typeParams = typeParameters(_class);
        // Factory to create objects from Json
        if (shouldGenerate(className)) {
            classes.add(StringJavaSource.newStringJavaSource(JavaPackageAndImportBuilder.buildPackageForPackageableElement(_class), className + "_JsonFactory", imports + "public class " + className + "_JsonFactory" + (typeParams.isEmpty() ? "" : "<" + typeParams + ">\n") + "{\n" + ("\n\n    public static " + className + " fromJson(final org.json.simple.JSONObject json, final MetadataAccessor md, final ClassLoader classLoader, SourceInformation si, final String typeKey, final boolean failOnUnknownProperties, final org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride constraintsOverride, final ExecutionSupport es, final String parentClass) {\n" + "         final " + className + "_Impl result = new " + className + "_Impl(\"Anonymous_NoCounter\");\n" + "         final String pureClassName=\"" + userDefinedClassName + "\";\n" + "         MutableSet<String> notFound = UnifiedSet.newSet(json.keySet());\n" + "         notFound.remove(typeKey);\n") + processorSupport.class_getSimpleProperties(_class).select(new Predicate<CoreInstance>() {

                @Override
                public boolean accept(CoreInstance property) {
                    String name = Instance.getValueForMetaPropertyToOneResolved(property, M3Properties.name, processorSupport).getName();
                    return !M3Properties.elementOverride.equals(name) && !M3Properties.getterOverrideToOne.equals(name) && !M3Properties.getterOverrideToMany.equals(name) && !"classifierGenericType".equals(name) && !M3Properties.hiddenPayload.equals(name) && !M3Properties.constraintsManager.equals(name);
                }
            }).collect(new Function<CoreInstance, Object>() {

                @Override
                public Object valueOf(CoreInstance property) {
                    CoreInstance resolved = Instance.getValueForMetaPropertyToOneResolved(property, M3Properties.name, processorSupport);
                    String name = resolved.getName();
                    CoreInstance multiplicity = Instance.getValueForMetaPropertyToOneResolved(property, M3Properties.multiplicity, processorSupport);
                    CoreInstance returnType = getPropertyResolvedReturnType(classGenericType, property, processorSupport);
                    String typeObject = TypeProcessor.typeToJavaObjectSingle(returnType, false, processorSupport);
                    CoreInstance rawType = Instance.getValueForMetaPropertyToOneResolved(returnType, M3Properties.rawType, processorSupport);
                    String classFullName = rawType == null ? null : PackageableElement.getSystemPathForPackageableElement(rawType, "::");
                    String classFullUserPath = rawType == null ? null : PackageableElement.getUserPathForPackageableElement(rawType);
                    String classFullName2 = rawType == null ? null : TypeProcessor.javaInterfaceNameForType(rawType);
                    boolean isToOne = Multiplicity.isToOne(multiplicity, false);
                    String assignment = "if(res != null)\n" + "{\n" + "result._" + name + (isToOne ? "" : "Add") + "((" + typeObject + ")res);\n" + "}\n";
                    return "\n" + "           notFound.remove(\"" + name + "\");\n" + "           if(" + associationCycleConditionCode(classFullName2, "parentClass", processorSupport, property) + ")\n" + "           {\n" + "               try\n" + "               {\n" + "                   Object propertyValue = json.get(\"" + MilestoningFunctions.getSourceEdgePointPropertyName(resolved.getName()) + "\");\n" + "                   Class __" + name + "Type = " + typeObject + ".class;\n" + "                   if (propertyValue instanceof org.json.simple.JSONArray )\n" + "                   {\n" + "                       org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) propertyValue;\n" + (shouldPerformMultiplicityChecks(className) ? multiplicityCheckCode("jsonArray", property, processorSupport) : "") + "                       for (Object jsonElement : jsonArray)\n" + "                       {\n" + (shouldGenerate(typeObject) ? "                           if (jsonElement instanceof org.json.simple.JSONObject)\n" + "                           {\n" + "                               org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonElement;\n" + "                               __" + name + "Type = Pure.fromJsonResolveType(jsonObject, \"" + classFullName + "\", " + typeObject + ".class, md, typeKey, classLoader);\n" + "                               Object res = JsonParserHelper.fromJson(jsonElement, __" + name + "Type, \"" + classFullName2 + "\", \"" + classFullUserPath + "\", md, classLoader, si, typeKey, failOnUnknownProperties, constraintsOverride, es, \"" + thisClassName + "\");\n" + "                               " + assignment + "                           }\n" + "                           else\n" + "                           {\n" : "                           {\n") + "                               Object res = JsonParserHelper.fromJson(jsonElement, __" + name + "Type, \"" + classFullName2 + "\", \"" + classFullUserPath + "\", md, classLoader, si, typeKey, failOnUnknownProperties, constraintsOverride, es, \"" + thisClassName + "\");\n" + "                               " + assignment + "                           }\n" + "                       }\n" + "                   }\n" + "                   else\n" + "                   {\n" + (shouldPerformMultiplicityChecks(className) ? multiplicityCheckCode("propertyValue", property, processorSupport) : "") + (shouldGenerate(typeObject) ? "                       if (propertyValue instanceof org.json.simple.JSONObject)\n" + "                       {\n" + "                           org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) propertyValue;\n" + "                           __" + name + "Type = Pure.fromJsonResolveType(jsonObject , \"" + classFullName + "\", " + typeObject + ".class, md, typeKey, classLoader);\n" + "                       }\n" : "") + "                       Object res = JsonParserHelper.fromJson(propertyValue, __" + name + "Type, \"" + classFullName2 + "\", \"" + classFullUserPath + "\", md, classLoader, si, typeKey, failOnUnknownProperties, constraintsOverride, es, \"" + thisClassName + "\");\n" + "                       " + assignment + "                   }\n" + "               }\n" + "               catch (PureException e)\n" + "               {\n" + "                   throw new PureCompiledExecutionException(si, \"Error populating property '" + name + "' on class '" + userDefinedClassName + "': \" + e.getInfo());\n" + "               } \n" + "               catch (Exception e)\n" + "               {\n" + "                   e.printStackTrace();\n" + "                   throw new PureCompiledExecutionException(si, \"Error populating property '" + name + "' on class '" + userDefinedClassName + "'\", e);\n" + "               }\n" + "           }\n";
                }
            }).makeString("") + "\n          if(failOnUnknownProperties && !notFound.isEmpty())\n" + "          {\n" + "              String errMsg = (notFound.size() == 1 ? \"Property \" : \"Properties \") + notFound.makeString(\"'\", \"', '\" , \"'\") + \" can't be found in class \" + pureClassName;\n" + "              throw new PureCompiledExecutionException(si, errMsg, null);\n" + "          }\n" + "          result._elementOverride(constraintsOverride);\n" + "          return result;\n" + "    }\n" + "} "));
        }
    }
}
Also used : Function(org.eclipse.collections.api.block.function.Function) ProcessorSupport(org.finos.legend.pure.m3.navigation.ProcessorSupport) StringJavaSource(org.finos.legend.pure.runtime.java.compiled.compiler.StringJavaSource) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance)

Example 3 with ConstraintsOverride

use of org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride 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 ConstraintsOverride

use of org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride in project legend-pure by finos.

the class JsonParserHelper method fromJson.

@SuppressWarnings("unused")
public static <T> T fromJson(Object value, Class<T> resultType, String fullClassName, String fullUserPath, MetadataAccessor metadata, ClassLoader classLoader, SourceInformation si, String typeKey, boolean failOnUnknownProperties, ConstraintsOverride constraintsOverride, ExecutionSupport es, String parentClass) {
    if (value == null) {
        return null;
    }
    // Is value a Primitive type?
    if (String.class.equals(resultType)) {
        typeCheck(value, String.class, fullClassName, si);
        return (T) jsonToString(value);
    }
    if (Integer.class.equals(resultType)) {
        typeCheck(value, Integer.class, fullClassName, si);
        return (T) jsonToInteger(value);
    }
    if (Long.class.equals(resultType)) {
        typeCheck(value, Long.class, fullClassName, si);
        return (T) jsonToLong(value);
    }
    if (Boolean.class.equals(resultType)) {
        typeCheck(value, Boolean.class, fullClassName, si);
        return (T) jsonToBoolean(value);
    }
    if (Double.class.equals(resultType)) {
        typeCheck(value, Number.class, fullClassName, si);
        return (T) jsonToDouble(value);
    }
    // Is value a Date ?
    if (PureDate.class.isAssignableFrom(resultType)) {
        typeCheck(value, String.class, fullClassName, si);
        return (T) DateFunctions.parsePureDate((String) value);
    }
    if (DateTime.class.isAssignableFrom(resultType)) {
        typeCheck(value, String.class, fullClassName, si);
        return (T) DateFunctions.parsePureDate((String) value);
    }
    // Is value an Enum type?
    try {
        if (getPureEnumParent(resultType).isAssignableFrom(resultType)) {
            typeCheck(value, String.class, fullClassName, si);
            String enumString = (String) value;
            int dotIndex = enumString.lastIndexOf('.');
            String enumName;
            String enumerationFullUserPath = fullUserPath;
            if (dotIndex == -1) {
                enumName = enumString;
            } else {
                enumName = enumString.substring(dotIndex + 1);
                enumerationFullUserPath = enumString.substring(0, dotIndex);
                if (!fullClassName.regionMatches(5, enumerationFullUserPath.replace("::", "_"), 0, fullClassName.length() - 5)) {
                    throw new PureExecutionException(si, "Expected enum of type " + fullClassName + "; got: " + enumString);
                }
            }
            T result = (T) metadata.getEnum(enumerationFullUserPath, enumName);
            if (result == null) {
                throw new PureExecutionException(si, "Unknown enum: " + fullClassName + "." + enumName);
            }
            return result;
        }
    } catch (NullPointerException e) {
        System.out.println("Unable to read the value of [" + value + "] because of NullPointerException");
        return null;
    }
    if (!(value instanceof JSONObject)) {
        // Currently this should be ignored.
        return null;
    }
    JSONObject jsonObject = (JSONObject) value;
    try {
        Class<?> implementationClass = resolveFactoryClass(resultType);
        T instance = (T) MethodUtils.invokeExactStaticMethod(implementationClass, "fromJson", new Object[] { value, metadata, classLoader, si, typeKey, failOnUnknownProperties, constraintsOverride, es, parentClass }, new Class[] { JSONObject.class, MetadataAccessor.class, ClassLoader.class, SourceInformation.class, String.class, boolean.class, ConstraintsOverride.class, ExecutionSupport.class, String.class });
        return instance;
    } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException e) {
        throw new RuntimeException("Unable to call fromJson() method", e);
    } catch (InvocationTargetException e) {
        Throwable targetException = e.getTargetException();
        if (targetException instanceof RuntimeException) {
            throw (RuntimeException) targetException;
        }
        throw new RuntimeException("Error calling fromJSON() method", e);
    }
}
Also used : PureExecutionException(org.finos.legend.pure.m3.exception.PureExecutionException) ConstraintsOverride(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride) SourceInformation(org.finos.legend.pure.m4.coreinstance.SourceInformation) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONObject(org.json.simple.JSONObject) MetadataAccessor(org.finos.legend.pure.runtime.java.compiled.metadata.MetadataAccessor) ExecutionSupport(org.finos.legend.pure.m3.execution.ExecutionSupport) JSONObject(org.json.simple.JSONObject)

Example 5 with ConstraintsOverride

use of org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride in project legend-pure by finos.

the class Pure method handleValidation.

public static Object handleValidation(boolean goDeep, Object input, SourceInformation si, ExecutionSupport es) {
    if (!(input instanceof Any)) {
        return input;
    }
    Any returnObject = (Any) input;
    ElementOverride elementOverride = returnObject._elementOverride();
    if (elementOverride instanceof ConstraintsOverride) {
        ConstraintsOverride constraintsOverride = (ConstraintsOverride) elementOverride;
        if (constraintsOverride._constraintsManager() != null) {
            return CompiledSupport.executeFunction(constraintsOverride._constraintsManager(), new Class[] { Object.class }, new Object[] { input }, es);
        }
    }
    return CompiledSupport.validate(goDeep, returnObject, si, es);
}
Also used : ConstraintsOverride(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride) Any(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Any) ElementOverride(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ElementOverride)

Aggregations

Any (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Any)3 ConstraintsOverride (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.ConstraintsOverride)3 PureExecutionException (org.finos.legend.pure.m3.exception.PureExecutionException)3 CoreInstance (org.finos.legend.pure.m4.coreinstance.CoreInstance)3 RichIterable (org.eclipse.collections.api.RichIterable)2 FastList (org.eclipse.collections.impl.list.mutable.FastList)2 Class (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class)2 SourceInformation (org.finos.legend.pure.m4.coreinstance.SourceInformation)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 ObjectFactory (org.finos.legend.pure.runtime.java.extension.external.shared.conversion.ObjectFactory)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 BigDecimal (java.math.BigDecimal)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Function (org.eclipse.collections.api.block.function.Function)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