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);
}
}));
}
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" + "} "));
}
}
}
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;
}
}));
}
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);
}
}
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);
}
Aggregations