Search in sources :

Example 6 with DataTemplate

use of com.linkedin.data.template.DataTemplate in project rest.li by linkedin.

the class TestClientBuilders method checkRequestIsReadOnly.

@SuppressWarnings("unchecked")
private void checkRequestIsReadOnly(final Request<?> request) {
    final Set<PathSpec> fields = request.getFields();
    if (fields != null) {
        checkReadOnlyOperation(new Runnable() {

            @Override
            public void run() {
                fields.add(new PathSpec("abc"));
            }
        });
    }
    checkReadOnlyOperation(new Runnable() {

        @Override
        public void run() {
            request.getHeaders().put("abc", "abc");
        }
    });
    final RecordTemplate input = request.getInputRecord();
    if (input != null) {
        checkReadOnlyOperation(new Runnable() {

            @Override
            public void run() {
                input.data().put("abc", "abc");
            }
        });
    }
    final Map<String, Object> pathKeys = request.getPathKeys();
    if (pathKeys != null) {
        checkReadOnlyOperation(new Runnable() {

            @Override
            public void run() {
                pathKeys.put("abc", "abc");
            }
        });
        final List<Object> keysToEdit = new ArrayList<>();
        for (Object key : pathKeys.values()) {
            if (key instanceof CompoundKey || key instanceof ComplexResourceKey) {
                keysToEdit.add(key);
            } else {
                Assert.assertTrue(isPrimitiveOrEnum(key));
            }
        }
        for (final Object keytoEdit : keysToEdit) {
            checkReadOnlyOperation(new Runnable() {

                @Override
                public void run() {
                    if (keytoEdit instanceof ComplexResourceKey) {
                        ((ComplexResourceKey) keytoEdit).getKey().data().put("abc", "abc");
                    } else if (keytoEdit instanceof CompoundKey) {
                        ((CompoundKey) keytoEdit).append("abc", "abc");
                    }
                }
            });
        }
        Collection<Object> queryParamObjects = request.getQueryParamsObjects().values();
        List<Object> readOnlyTargets = new ArrayList<>();
        for (Object queryParamObject : queryParamObjects) {
            collectReadOnlyQueryParamObjectTargets(queryParamObject, readOnlyTargets);
        }
        for (final Object readOnlyTarget : readOnlyTargets) {
            checkReadOnlyOperation(new Runnable() {

                @Override
                public void run() {
                    if (readOnlyTarget instanceof DataTemplate) {
                        Object data = ((DataTemplate) readOnlyTarget).data();
                        if (data instanceof DataMap) {
                            ((DataMap) data).put("abc", "abc");
                        } else if (data instanceof DataList) {
                            ((DataList) data).add("abc");
                        }
                    } else if (readOnlyTarget instanceof CompoundKey) {
                        ((CompoundKey) readOnlyTarget).append("abc", "abc");
                    } else if (readOnlyTarget instanceof ComplexResourceKey) {
                        ((ComplexResourceKey) readOnlyTarget).getKey().data().put("abc", "abc");
                    } else if (readOnlyTarget instanceof List || readOnlyTarget instanceof Set) {
                        ((Collection<Object>) readOnlyTarget).add("abc");
                    }
                }
            });
        }
    }
}
Also used : EnumSet(java.util.EnumSet) Set(java.util.Set) HashSet(java.util.HashSet) CompoundKey(com.linkedin.restli.common.CompoundKey) DataTemplate(com.linkedin.data.template.DataTemplate) ArrayList(java.util.ArrayList) ByteString(com.linkedin.data.ByteString) PathSpec(com.linkedin.data.schema.PathSpec) DataMap(com.linkedin.data.DataMap) DataList(com.linkedin.data.DataList) RecordTemplate(com.linkedin.data.template.RecordTemplate) DynamicRecordTemplate(com.linkedin.data.template.DynamicRecordTemplate) ComplexResourceKey(com.linkedin.restli.common.ComplexResourceKey) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) DataList(com.linkedin.data.DataList)

Example 7 with DataTemplate

use of com.linkedin.data.template.DataTemplate in project rest.li by linkedin.

the class TestRecord method testField.

private void testField(RecordTemplate record, String fieldName, final Object value) {
    Class<?> valueClass = value.getClass();
    TestDataTemplateUtil.FieldInfo fieldInfo = TestDataTemplateUtil.fieldInfo(record, fieldName);
    String getterPrefix = fieldInfo.getFieldClass() == Boolean.class ? "is" : "get";
    String getMethodName = TestDataTemplateUtil.methodName(getterPrefix, fieldName);
    String setMethodName = TestDataTemplateUtil.methodName("set", fieldName);
    String hasMethodName = TestDataTemplateUtil.methodName("has", fieldName);
    String removeMethodName = TestDataTemplateUtil.methodName("remove", fieldName);
    Class<? extends RecordTemplate> recordClass = record.getClass();
    DataMap dataMap = record.data();
    boolean isOptional = fieldInfo.getField().getOptional();
    try {
        Method getMethod = recordClass.getMethod(getMethodName);
        Method getModeMethod = recordClass.getMethod(getMethodName, GetMode.class);
        Method setMethod = recordClass.getMethod(setMethodName, valueClass);
        Method setModeMethod = recordClass.getMethod(setMethodName, valueClass, SetMode.class);
        Method hasMethod = recordClass.getMethod(hasMethodName);
        Method removeMethod = recordClass.getMethod(removeMethodName);
        Object prevValue;
        // fields
        TestDataTemplateUtil.assertPresentInFields(recordClass, fieldName);
        // has
        if (dataMap.containsKey(fieldName)) {
            assertTrue((Boolean) hasMethod.invoke(record));
            prevValue = getMethod.invoke(record);
        } else {
            assertFalse((Boolean) hasMethod.invoke(record));
            prevValue = null;
        }
        // set
        Object result = setMethod.invoke(record, value);
        assertSame(result, record);
        // has with field present
        assertTrue((Boolean) hasMethod.invoke(record));
        // get with field present
        result = getMethod.invoke(record);
        if (value instanceof DataTemplate || value instanceof Enum) {
            assertSame(result, value);
        } else {
            assertEquals(result, value);
        }
        // GetMode.NULL, GetMode.DEFAULT, GetMode.STRICT with field present
        assertSame(getModeMethod.invoke(record, GetMode.NULL), result);
        assertSame(getModeMethod.invoke(record, GetMode.DEFAULT), result);
        assertSame(getModeMethod.invoke(record, GetMode.STRICT), result);
        // remove
        removeMethod.invoke(record);
        // has with field absent
        assertFalse((Boolean) hasMethod.invoke(record));
        assertNull(getModeMethod.invoke(record, GetMode.NULL));
        // GetMode.NULL with field absent
        result = getModeMethod.invoke(record, GetMode.NULL);
        assertNull(result);
        // GetMode.DEFAULT with field absent
        Object defaultValue = getModeMethod.invoke(record, GetMode.DEFAULT);
        Object defaultValueFromSchema = fieldInfo.getField().getDefault();
        assertEquals(defaultValue == null, defaultValueFromSchema == null);
        if (defaultValue != null) {
            if (defaultValue instanceof DataTemplate) {
                assertEquals(((DataTemplate) defaultValue).data(), defaultValueFromSchema);
            } else if (defaultValue instanceof Enum) {
                assertEquals(defaultValue.toString(), defaultValueFromSchema);
            } else {
                assertSame(defaultValue, defaultValueFromSchema);
            }
        }
        // GetMode.STRICT with field absent
        boolean expectRequiredFieldNotFoundException = (!isOptional && defaultValue == null);
        try {
            result = getModeMethod.invoke(record, GetMode.STRICT);
            assertFalse(expectRequiredFieldNotFoundException);
            assertSame(result, defaultValue);
        } catch (InvocationTargetException exc) {
            assertTrue(expectRequiredFieldNotFoundException);
            assertTrue(exc.getTargetException() instanceof RequiredFieldNotPresentException);
        }
        // SetMode.IGNORE_NULL
        setModeMethod.invoke(record, value, SetMode.IGNORE_NULL);
        assertSame(getMethod.invoke(record), value);
        setModeMethod.invoke(record, null, SetMode.IGNORE_NULL);
        assertSame(getMethod.invoke(record), value);
        // SetMode.REMOVE_IF_NULL
        removeMethod.invoke(record);
        setModeMethod.invoke(record, value, SetMode.REMOVE_IF_NULL);
        assertSame(getMethod.invoke(record), value);
        setModeMethod.invoke(record, null, SetMode.REMOVE_IF_NULL);
        assertFalse((Boolean) hasMethod.invoke(record));
        // SetMode.REMOVE_OPTIONAL_IF_NULL
        removeMethod.invoke(record);
        setModeMethod.invoke(record, value, SetMode.REMOVE_OPTIONAL_IF_NULL);
        assertSame(getMethod.invoke(record), value);
        try {
            setModeMethod.invoke(record, null, SetMode.REMOVE_OPTIONAL_IF_NULL);
            assertTrue(isOptional);
            assertFalse((Boolean) hasMethod.invoke(record));
        } catch (InvocationTargetException exc) {
            assertFalse(isOptional);
            assertTrue(exc.getTargetException() instanceof IllegalArgumentException);
        }
        // SetMode.DISALLOW_NULL
        try {
            setModeMethod.invoke(record, null, SetMode.DISALLOW_NULL);
        } catch (InvocationTargetException exc) {
            assertTrue(exc.getTargetException() instanceof NullPointerException);
        }
        // restore original value
        if (prevValue != null) {
            result = setMethod.invoke(record, prevValue);
            assertSame(result, record);
            assertTrue((Boolean) hasMethod.invoke(record));
            assertEquals(getMethod.invoke(record), prevValue);
        }
    } catch (IllegalAccessException exc) {
        fail("Unexpected exception", exc);
    } catch (InvocationTargetException exc) {
        fail("Unexpected exception", exc);
    } catch (NoSuchMethodException exc) {
        fail("Unexpected exception", exc);
    }
}
Also used : RequiredFieldNotPresentException(com.linkedin.data.template.RequiredFieldNotPresentException) TestDataTemplateUtil(com.linkedin.data.template.TestDataTemplateUtil) DataTemplate(com.linkedin.data.template.DataTemplate) ByteString(com.linkedin.data.ByteString) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) DataMap(com.linkedin.data.DataMap)

Example 8 with DataTemplate

use of com.linkedin.data.template.DataTemplate in project rest.li by linkedin.

the class TestUnion method testTypeValue.

private static <T extends UnionTemplate> void testTypeValue(Class<T> unionClass, String type, Object typeValue) {
    try {
        // constructor with argument
        Constructor<T> ctor = unionClass.getDeclaredConstructor(Object.class);
        DataMap dataMap = new DataMap();
        if (typeValue instanceof DataTemplate) {
            DataTemplate<?> dataTemplate = (DataTemplate<?>) typeValue;
            dataMap.put(dataTemplate.schema().getUnionMemberKey(), dataTemplate.data());
        } else if (typeValue instanceof Enum) {
            String key = DataTemplateUtil.getSchema(typeValue.getClass()).getUnionMemberKey();
            dataMap.put(key, typeValue.toString());
        } else {
            dataMap.put(type, typeValue);
        }
        T unionFromCtor = ctor.newInstance(dataMap);
        testTypeValue(unionFromCtor, type, typeValue);
        // constructor with no argument followed by set
        String setTypeMethodName = TestDataTemplateUtil.methodName("set", type);
        Method setMethod = unionClass.getMethod(setTypeMethodName, typeValue.getClass());
        T unionToSet = unionClass.getConstructor().newInstance();
        setMethod.invoke(unionToSet, typeValue);
        testTypeValue(unionToSet, type, typeValue);
        // create method
        Method createMethod = unionClass.getMethod("create", typeValue.getClass());
        @SuppressWarnings("unchecked") T unionFromCreate = (T) createMethod.invoke(null, typeValue);
        testTypeValue(unionFromCreate, type, typeValue);
    } catch (IllegalAccessException ex) {
        throw new IllegalStateException(ex);
    } catch (InvocationTargetException ex) {
        throw new IllegalStateException(ex);
    } catch (InstantiationException ex) {
        throw new IllegalStateException(ex);
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException(ex);
    }
}
Also used : DataTemplate(com.linkedin.data.template.DataTemplate) ByteString(com.linkedin.data.ByteString) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) DataMap(com.linkedin.data.DataMap)

Aggregations

DataTemplate (com.linkedin.data.template.DataTemplate)8 ByteString (com.linkedin.data.ByteString)5 DataMap (com.linkedin.data.DataMap)5 DataList (com.linkedin.data.DataList)4 ArrayDataSchema (com.linkedin.data.schema.ArrayDataSchema)3 DataSchema (com.linkedin.data.schema.DataSchema)2 ValidationOptions (com.linkedin.data.schema.validation.ValidationOptions)2 RecordTemplate (com.linkedin.data.template.RecordTemplate)2 TemplateRuntimeException (com.linkedin.data.template.TemplateRuntimeException)2 RoutingException (com.linkedin.restli.server.RoutingException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 JacksonDataCodec (com.linkedin.data.codec.JacksonDataCodec)1 DataSchemaLocation (com.linkedin.data.schema.DataSchemaLocation)1 DataSchemaUtil.getDataClassFromSchema (com.linkedin.data.schema.DataSchemaUtil.getDataClassFromSchema)1 NamedDataSchema (com.linkedin.data.schema.NamedDataSchema)1 PathSpec (com.linkedin.data.schema.PathSpec)1 ValidateDataAgainstSchema (com.linkedin.data.schema.validation.ValidateDataAgainstSchema)1 ValidationResult (com.linkedin.data.schema.validation.ValidationResult)1 AbstractArrayTemplate (com.linkedin.data.template.AbstractArrayTemplate)1