You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@olingo.apache.org by tb...@apache.org on 2013/12/20 16:18:09 UTC
[07/12] [OLINGO-83] Refactoring of 'annotation-processor-*' modules
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationInMemoryDs.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationInMemoryDs.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationInMemoryDs.java
new file mode 100644
index 0000000..b389fa4
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationInMemoryDs.java
@@ -0,0 +1,384 @@
+/**
+ * *****************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
+ * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
+ * License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
+ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations under the License.
+ *****************************************************************************
+ */
+package org.apache.olingo.odata2.annotation.processor.core.datasource;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper;
+import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper.AnnotatedNavInfo;
+import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper.ODataAnnotationException;
+import org.apache.olingo.odata2.annotation.processor.core.util.ClassHelper;
+import org.apache.olingo.odata2.api.annotation.edm.EdmMediaResourceContent;
+import org.apache.olingo.odata2.api.annotation.edm.EdmMediaResourceMimeType;
+import org.apache.olingo.odata2.api.annotation.edm.EdmNavigationProperty;
+import org.apache.olingo.odata2.api.edm.EdmEntitySet;
+import org.apache.olingo.odata2.api.edm.EdmException;
+import org.apache.olingo.odata2.api.edm.EdmFunctionImport;
+import org.apache.olingo.odata2.api.edm.EdmMultiplicity;
+import org.apache.olingo.odata2.api.exception.ODataApplicationException;
+import org.apache.olingo.odata2.api.exception.ODataException;
+import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
+import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
+import org.apache.olingo.odata2.core.exception.ODataRuntimeException;
+
+public class AnnotationInMemoryDs implements DataSource {
+
+ private static final AnnotationHelper ANNOTATION_HELPER = new AnnotationHelper();
+ private final Map<String, DataStore<Object>> dataStores = new HashMap<String, DataStore<Object>>();
+ private final boolean persistInMemory;
+
+ public AnnotationInMemoryDs(Collection<Class<?>> annotatedClasses) throws ODataException {
+ this(annotatedClasses, true);
+ }
+
+ public AnnotationInMemoryDs(Collection<Class<?>> annotatedClasses, boolean persistInMemory) throws ODataException {
+ this.persistInMemory = persistInMemory;
+ init(annotatedClasses);
+ }
+
+ public AnnotationInMemoryDs(final String packageToScan) throws ODataException {
+ this(packageToScan, true);
+ }
+
+ public AnnotationInMemoryDs(final String packageToScan, final boolean persistInMemory) throws ODataException {
+ this.persistInMemory = persistInMemory;
+ List<Class<?>> foundClasses = ClassHelper.loadClasses(packageToScan, new ClassHelper.ClassValidator() {
+ @Override
+ public boolean isClassValid(final Class<?> c) {
+ return null != c.getAnnotation(org.apache.olingo.odata2.api.annotation.edm.EdmEntitySet.class);
+ }
+ });
+
+ init(foundClasses);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void init(final Collection<Class<?>> annotatedClasses) throws ODataException {
+ try {
+ for (Class<?> clz : annotatedClasses) {
+ DataStore<Object> dhs = (DataStore<Object>) DataStore.createInMemory(clz, persistInMemory);
+ String entitySetName = ANNOTATION_HELPER.extractEntitySetName(clz);
+ dataStores.put(entitySetName, dhs);
+ }
+ } catch (DataStore.DataStoreException e) {
+ throw new ODataException("Error in DataStore initilization with message: " + e.getMessage(), e);
+ }
+ }
+
+ public <T> DataStore<T> getDataStore(final Class<T> clazz) {
+ String entitySetName = ANNOTATION_HELPER.extractEntitySetName(clazz);
+ return (DataStore<T>) dataStores.get(entitySetName);
+ }
+
+ @Override
+ public List<?> readData(final EdmEntitySet entitySet) throws ODataNotImplementedException,
+ ODataNotFoundException, EdmException, ODataApplicationException {
+
+ DataStore<Object> holder = getDataStore(entitySet);
+ if (holder != null) {
+ return new ArrayList<Object>(holder.read());
+ }
+
+ throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
+ }
+
+ @Override
+ public Object readData(final EdmEntitySet entitySet, final Map<String, Object> keys)
+ throws ODataNotFoundException, EdmException, ODataApplicationException {
+
+ DataStore<Object> store = getDataStore(entitySet);
+ if (store != null) {
+ Object keyInstance = store.createInstance();
+ ANNOTATION_HELPER.setKeyFields(keyInstance, keys);
+
+ Object result = store.read(keyInstance);
+ if (result != null) {
+ return result;
+ }
+ }
+
+ throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
+ }
+
+ @Override
+ public Object readData(final EdmFunctionImport function, final Map<String, Object> parameters,
+ final Map<String, Object> keys)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+ throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
+ }
+
+ @Override
+ public Object readRelatedData(final EdmEntitySet sourceEntitySet, final Object sourceData,
+ final EdmEntitySet targetEntitySet,
+ final Map<String, Object> targetKeys)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+
+ DataStore<?> sourceStore = dataStores.get(sourceEntitySet.getName());
+ DataStore<?> targetStore = dataStores.get(targetEntitySet.getName());
+
+ AnnotatedNavInfo navInfo = ANNOTATION_HELPER.getCommonNavigationInfo(
+ sourceStore.getDataTypeClass(), targetStore.getDataTypeClass());
+ Field sourceField = navInfo.getFromField();
+ if (sourceField == null) {
+ throw new ODataRuntimeException("Missing source field for related data (sourceStore='" + sourceStore
+ + "', targetStore='" + targetStore + "').");
+ }
+
+ Object navigationInstance = getValue(sourceField, sourceData);
+ List<Object> resultData = new ArrayList<Object>();
+ for (Object targetInstance : targetStore.read()) {
+ if (navigationInstance instanceof Collection) {
+ for (Object object : (Collection<?>) navigationInstance) {
+ if (targetStore.isKeyEqualChecked(targetInstance, object)) {
+ resultData.add(targetInstance);
+ }
+ }
+ } else if (targetStore.isKeyEqualChecked(targetInstance, navigationInstance)) {
+ resultData.add(targetInstance);
+ }
+ }
+
+ if (navInfo.getToMultiplicity() == EdmMultiplicity.MANY) {
+ if (targetKeys.isEmpty()) {
+ return resultData;
+ } else {
+ Object keyInstance = targetStore.createInstance();
+ ANNOTATION_HELPER.setKeyFields(keyInstance, targetKeys);
+ for (Object result : resultData) {
+ if (targetStore.isKeyEqualChecked(result, keyInstance)) {
+ return result;
+ }
+ }
+ return null;
+ }
+ } else {
+ if (resultData.isEmpty()) {
+ return null;
+ }
+ return resultData.get(0);
+ }
+ }
+
+ @Override
+ public BinaryData readBinaryData(final EdmEntitySet entitySet, final Object mediaLinkEntryData)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+
+ Object data = ANNOTATION_HELPER.getValueForField(mediaLinkEntryData, EdmMediaResourceContent.class);
+ Object mimeType = ANNOTATION_HELPER.getValueForField(mediaLinkEntryData, EdmMediaResourceMimeType.class);
+
+ if(data == null && mimeType == null) {
+ DataStore<Object> dataStore = getDataStore(entitySet);
+ Object readEntry = dataStore.read(mediaLinkEntryData);
+ if(readEntry != null) {
+ data = ANNOTATION_HELPER.getValueForField(readEntry, EdmMediaResourceContent.class);
+ mimeType = ANNOTATION_HELPER.getValueForField(readEntry, EdmMediaResourceMimeType.class);
+ }
+ }
+
+ return new BinaryData((byte[]) data, String.valueOf(mimeType));
+ }
+
+ @Override
+ public Object newDataObject(final EdmEntitySet entitySet)
+ throws ODataNotImplementedException, EdmException, ODataApplicationException {
+
+ DataStore<Object> dataStore = getDataStore(entitySet);
+ if (dataStore != null) {
+ return dataStore.createInstance();
+ }
+
+ throw new ODataRuntimeException("No DataStore found for entitySet with name: " + entitySet.getName());
+ }
+
+ @Override
+ public void writeBinaryData(final EdmEntitySet entitySet, final Object mediaEntityInstance,
+ final BinaryData binaryData)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+
+ try {
+ DataStore<Object> dataStore = getDataStore(entitySet);
+ Object readEntry = dataStore.read(mediaEntityInstance);
+ if(readEntry == null) {
+ throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
+ } else {
+ ANNOTATION_HELPER.setValueForAnnotatedField(
+ mediaEntityInstance, EdmMediaResourceContent.class, binaryData.getData());
+ ANNOTATION_HELPER.setValueForAnnotatedField(
+ mediaEntityInstance, EdmMediaResourceMimeType.class, binaryData.getMimeType());
+ }
+ } catch (ODataAnnotationException e) {
+ throw new ODataRuntimeException("Invalid media resource annotation at entity set '" + entitySet.getName()
+ + "' with message '" + e.getMessage() + "'.", e);
+ }
+ }
+
+ /**
+ * <p>Updates a single data object identified by the specified entity set and key fields of
+ * the data object.</p>
+ * @param entitySet the {@link EdmEntitySet} the object must correspond to
+ * @param data the data object of the new entity
+ * @return updated data object instance
+ * @throws org.apache.olingo.odata2.api.exception.ODataNotImplementedException
+ * @throws org.apache.olingo.odata2.api.edm.EdmException
+ * @throws org.apache.olingo.odata2.api.exception.ODataApplicationException
+ */
+ public Object updateData(final EdmEntitySet entitySet, final Object data)
+ throws ODataNotImplementedException, EdmException, ODataApplicationException {
+
+ DataStore<Object> dataStore = getDataStore(entitySet);
+ return dataStore.update(data);
+ }
+
+ @Override
+ public void deleteData(final EdmEntitySet entitySet, final Map<String, Object> keys)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+ DataStore<Object> dataStore = getDataStore(entitySet);
+ Object keyInstance = dataStore.createInstance();
+ ANNOTATION_HELPER.setKeyFields(keyInstance, keys);
+ dataStore.delete(keyInstance);
+ }
+
+ @Override
+ public void createData(final EdmEntitySet entitySet, final Object data)
+ throws ODataNotImplementedException, EdmException, ODataApplicationException {
+
+ DataStore<Object> dataStore = getDataStore(entitySet);
+ dataStore.create(data);
+ }
+
+ @Override
+ public void deleteRelation(final EdmEntitySet sourceEntitySet, final Object sourceData,
+ final EdmEntitySet targetEntitySet,
+ final Map<String, Object> targetKeys)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+ throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
+ }
+
+ @Override
+ public void writeRelation(final EdmEntitySet sourceEntitySet, final Object sourceEntity,
+ final EdmEntitySet targetEntitySet,
+ final Map<String, Object> targetEntityValues)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
+ // get common data
+ DataStore<Object> sourceStore = dataStores.get(sourceEntitySet.getName());
+ DataStore<Object> targetStore = dataStores.get(targetEntitySet.getName());
+
+ AnnotatedNavInfo commonNavInfo = ANNOTATION_HELPER.getCommonNavigationInfo(
+ sourceStore.getDataTypeClass(), targetStore.getDataTypeClass());
+
+ // get and validate source fields
+ Field sourceField = commonNavInfo.getFromField();
+ if (sourceField == null) {
+ throw new ODataRuntimeException("Missing source field for related data (sourceStore='" + sourceStore
+ + "', targetStore='" + targetStore + "').");
+ }
+
+ // get related target entity
+ Object targetEntity = targetStore.createInstance();
+ ANNOTATION_HELPER.setKeyFields(targetEntity, targetEntityValues);
+ targetEntity = targetStore.read(targetEntity);
+
+ // set at source
+ setValueAtNavigationField(sourceEntity, sourceField, targetEntity);
+ // set at target
+ Field targetField = commonNavInfo.getToField();
+ if (targetField != null) {
+ setValueAtNavigationField(targetEntity, targetField, sourceEntity);
+ }
+ }
+
+ /**
+ * Set (Multiplicity != *) or add (Multiplicity == *) <code>value</code> at <code>field</code>
+ * of <code>instance</code>.
+ *
+ * @param instance
+ * @param field
+ * @param value
+ * @throws EdmException
+ */
+ private void setValueAtNavigationField(final Object instance, final Field field, final Object value)
+ throws EdmException {
+ Class<?> fieldTypeClass = field.getType();
+ if (Collection.class.isAssignableFrom(fieldTypeClass)) {
+ @SuppressWarnings("unchecked")
+ Collection<Object> collection = (Collection<Object>) ANNOTATION_HELPER.getValueForField(
+ instance, field.getName(), EdmNavigationProperty.class);
+ if (collection == null) {
+ collection = new ArrayList<Object>();
+ setValue(instance, field, collection);
+ }
+ collection.add(value);
+ } else if (fieldTypeClass.isArray()) {
+ throw new ODataRuntimeException("Write relations for internal used arrays is not supported.");
+ } else {
+ setValue(instance, field, value);
+ }
+ }
+
+ /**
+ * Returns corresponding DataStore for EdmEntitySet or if no data store is registered an
+ * ODataRuntimeException is thrown.
+ * Never returns NULL.
+ *
+ * @param entitySet for which the corresponding DataStore is returned
+ * @return a DataStore object
+ * @throws EdmException
+ * @throws ODataRuntimeException if no DataStore is found
+ */
+ private DataStore<Object> getDataStore(final EdmEntitySet entitySet) throws EdmException {
+ final String name = entitySet.getName();
+ DataStore<Object> dataStore = dataStores.get(name);
+ if (dataStore == null) {
+ throw new ODataRuntimeException("No DataStore found for entity set '" + entitySet + "'.");
+ }
+ return dataStore;
+ }
+
+ private Object getValue(final Field field, final Object instance) {
+ try {
+ boolean access = field.isAccessible();
+ field.setAccessible(true);
+ Object value = field.get(instance);
+ field.setAccessible(access);
+ return value;
+ } catch (IllegalArgumentException e) {
+ throw new ODataRuntimeException("Error for getting value of field '"
+ + field + "' at instance '" + instance + "'.", e);
+ } catch (IllegalAccessException e) {
+ throw new ODataRuntimeException("Error for getting value of field '"
+ + field + "' at instance '" + instance + "'.", e);
+ }
+ }
+
+ private void setValue(final Object instance, final Field field, final Object value) {
+ try {
+ boolean access = field.isAccessible();
+ field.setAccessible(true);
+ field.set(instance, value);
+ field.setAccessible(access);
+ } catch (IllegalArgumentException e) {
+ throw new ODataRuntimeException("Error for setting value of field: '"
+ + field + "' at instance: '" + instance + "'.", e);
+ } catch (IllegalAccessException e) {
+ throw new ODataRuntimeException("Error for setting value of field: '"
+ + field + "' at instance: '" + instance + "'.", e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationValueAccess.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationValueAccess.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationValueAccess.java
new file mode 100644
index 0000000..b685ec8
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/AnnotationValueAccess.java
@@ -0,0 +1,108 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ ******************************************************************************/
+package org.apache.olingo.odata2.annotation.processor.core.datasource;
+
+import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper;
+import org.apache.olingo.odata2.api.edm.EdmMapping;
+import org.apache.olingo.odata2.api.edm.EdmProperty;
+import org.apache.olingo.odata2.api.exception.ODataException;
+import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
+
+/**
+ *
+ */
+public class AnnotationValueAccess implements ValueAccess {
+ private final AnnotationHelper annotationHelper = new AnnotationHelper();
+
+ /**
+ * Retrieves the value of an EDM property for the given data object.
+ * @param data the Java data object
+ * @param property the requested {@link EdmProperty}
+ * @return the requested property value
+ */
+ @Override
+ public <T> Object getPropertyValue(final T data, final EdmProperty property) throws ODataException {
+ if (data == null) {
+ return null;
+ } else if (annotationHelper.isEdmAnnotated(data)) {
+ return annotationHelper.getValueForProperty(data, property.getName());
+ }
+ throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
+ }
+
+ /**
+ * Sets the value of an EDM property for the given data object.
+ * @param data the Java data object
+ * @param property the {@link EdmProperty}
+ * @param value the new value of the property
+ */
+ @Override
+ public <T, V> void setPropertyValue(final T data, final EdmProperty property, final V value) throws ODataException {
+ if (annotationHelper.isEdmAnnotated(data)) {
+ annotationHelper.setValueForProperty(data, property.getName(), value);
+ } else {
+ throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
+ }
+ }
+
+ /**
+ * Retrieves the Java type of an EDM property for the given data object.
+ * @param data the Java data object
+ * @param property the requested {@link EdmProperty}
+ * @return the requested Java type
+ */
+ @Override
+ public <T> Class<?> getPropertyType(final T data, final EdmProperty property) throws ODataException {
+ if (annotationHelper.isEdmAnnotated(data)) {
+ Class<?> fieldType = annotationHelper.getFieldTypeForProperty(data, property.getName());
+ if (fieldType == null) {
+ throw new ODataException("No field type found for property " + property);
+ }
+ return fieldType;
+ }
+ throw new ODataNotImplementedException(ODataNotImplementedException.COMMON);
+ }
+
+ /**
+ * Retrieves the value defined by a mapping object for the given data object.
+ * @param data the Java data object
+ * @param mapping the requested {@link EdmMapping}
+ * @return the requested value
+ */
+ @Override
+ public <T> Object getMappingValue(final T data, final EdmMapping mapping) throws ODataException {
+ if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) {
+ return annotationHelper.getValueForProperty(data, mapping.getMediaResourceMimeTypeKey());
+ }
+ return null;
+ }
+
+ /**
+ * Sets the value defined by a mapping object for the given data object.
+ * @param data the Java data object
+ * @param mapping the {@link EdmMapping}
+ * @param value the new value
+ */
+ @Override
+ public <T, V> void setMappingValue(final T data, final EdmMapping mapping, final V value) throws ODataException {
+ if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) {
+ annotationHelper.setValueForProperty(data, mapping.getMediaResourceMimeTypeKey(), value);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/BeanPropertyAccess.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/BeanPropertyAccess.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/BeanPropertyAccess.java
new file mode 100644
index 0000000..290b99f
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/BeanPropertyAccess.java
@@ -0,0 +1,185 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ ******************************************************************************/
+package org.apache.olingo.odata2.annotation.processor.core.datasource;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+
+import org.apache.olingo.odata2.api.edm.EdmException;
+import org.apache.olingo.odata2.api.edm.EdmMapping;
+import org.apache.olingo.odata2.api.edm.EdmProperty;
+import org.apache.olingo.odata2.api.edm.EdmSimpleTypeKind;
+import org.apache.olingo.odata2.api.exception.ODataException;
+import org.apache.olingo.odata2.api.exception.ODataHttpException;
+import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
+
+/**
+ * Data access.
+ */
+public class BeanPropertyAccess implements ValueAccess {
+
+ @Override
+ public <T> Object getPropertyValue(final T data, final EdmProperty property) throws ODataException {
+ return getValue(data, getGetterMethodName(property));
+ }
+
+ @Override
+ public <T, V> void setPropertyValue(final T data, final EdmProperty property, final V value) throws ODataException {
+ final String methodName = getSetterMethodName(getGetterMethodName(property));
+ if (methodName != null) {
+ setValue(data, methodName, value);
+ }
+ }
+
+ @Override
+ public <T> Class<?> getPropertyType(final T data, final EdmProperty property) throws ODataException {
+ return getType(data, getGetterMethodName(property));
+ }
+
+ @Override
+ public <T> Object getMappingValue(final T data, final EdmMapping mapping) throws ODataException {
+ if (mapping != null && mapping.getMimeType() != null) {
+ return getValue(data, mapping.getMimeType());
+ }
+ return null;
+ }
+
+ @Override
+ public <T, V> void setMappingValue(final T data, final EdmMapping mapping, final V value) throws ODataException {
+ if (mapping != null && mapping.getMimeType() != null) {
+ setValue(data, getSetterMethodName(mapping.getMimeType()), value);
+ }
+ }
+
+ private String getGetterMethodName(final EdmProperty property) throws EdmException {
+ final String prefix = isBooleanProperty(property) ? "is" : "get";
+ final String defaultMethodName = prefix + property.getName();
+ return property.getMapping() == null || property.getMapping().getInternalName() == null ?
+ defaultMethodName : property.getMapping().getInternalName();
+ }
+
+ private boolean isBooleanProperty(final EdmProperty property) throws EdmException {
+ return property.isSimple()
+ && property.getType() == EdmSimpleTypeKind.Boolean.getEdmSimpleTypeInstance();
+ }
+
+ private String getSetterMethodName(final String getterMethodName) {
+ return getterMethodName.contains(".") ?
+ null : getterMethodName.replaceFirst("^is", "set").replaceFirst("^get", "set");
+ }
+
+ private <T> Object getValue(final T data, final String methodName) throws ODataNotFoundException {
+ Object dataObject = data;
+
+ for (final String method : methodName.split("\\.", -1)) {
+ if (dataObject != null) {
+ try {
+ dataObject = dataObject.getClass().getMethod(method).invoke(dataObject);
+ } catch (SecurityException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ } catch (NoSuchMethodException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ } catch (IllegalArgumentException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ } catch (IllegalAccessException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ } catch (InvocationTargetException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ }
+ }
+ }
+
+ return dataObject;
+ }
+
+ private <T, V> void setValue(final T data, final String methodName, final V value)
+ throws ODataNotFoundException {
+ try {
+ boolean found = false;
+ for (final Method method : Arrays.asList(data.getClass().getMethods())) {
+ if (method.getName().equals(methodName)) {
+ found = true;
+ final Class<?> type = method.getParameterTypes()[0];
+ if (value == null) {
+ if (type.equals(byte.class) || type.equals(short.class) || type.equals(int.class)
+ || type.equals(long.class) || type.equals(char.class)) {
+ method.invoke(data, 0);
+ } else if (type.equals(float.class) || type.equals(double.class)) {
+ method.invoke(data, 0.0);
+ } else if (type.equals(boolean.class)) {
+ method.invoke(data, false);
+ } else {
+ method.invoke(data, value);
+ }
+ } else {
+ method.invoke(data, value);
+ }
+ break;
+ }
+ }
+ if (!found) {
+ throw new ODataNotFoundException(null);
+ }
+ } catch (SecurityException e) {
+ throw new ODataNotFoundException(null, e);
+ } catch (IllegalArgumentException e) {
+ throw new ODataNotFoundException(null, e);
+ } catch (IllegalAccessException e) {
+ throw new ODataNotFoundException(null, e);
+ } catch (InvocationTargetException e) {
+ throw new ODataNotFoundException(null, e);
+ }
+ }
+
+ private <T> Class<?> getType(final T data, final String methodName) throws ODataNotFoundException {
+ if (data == null) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON);
+ }
+
+ Class<?> type = data.getClass();
+ for (final String method : methodName.split("\\.", -1)) {
+ try {
+ type = type.getMethod(method).getReturnType();
+ if (type.isPrimitive()) {
+ if (type == boolean.class) {
+ type = Boolean.class;
+ } else if (type == byte.class) {
+ type = Byte.class;
+ } else if (type == short.class) {
+ type = Short.class;
+ } else if (type == int.class) {
+ type = Integer.class;
+ } else if (type == long.class) {
+ type = Long.class;
+ } else if (type == float.class) {
+ type = Float.class;
+ } else if (type == double.class) {
+ type = Double.class;
+ }
+ }
+ } catch (final SecurityException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ } catch (final NoSuchMethodException e) {
+ throw new ODataNotFoundException(ODataHttpException.COMMON, e);
+ }
+ }
+ return type;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataSource.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataSource.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataSource.java
new file mode 100644
index 0000000..e23f5f3
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataSource.java
@@ -0,0 +1,200 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ ******************************************************************************/
+package org.apache.olingo.odata2.annotation.processor.core.datasource;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.olingo.odata2.api.edm.EdmEntitySet;
+import org.apache.olingo.odata2.api.edm.EdmException;
+import org.apache.olingo.odata2.api.edm.EdmFunctionImport;
+import org.apache.olingo.odata2.api.exception.ODataApplicationException;
+import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
+import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
+
+/**
+ * <p>This interface is intended to make it easier to implement an OData
+ * service in cases where all data for each entity set can be provided as a {@link List} of objects from which all
+ * properties described in the
+ * Entity Data Model can be retrieved and set.</p>
+ * <p>By obeying these restrictions, data-source implementations get the
+ * following advantages:
+ * <ul>
+ * <li>All system query options can be handled centrally.</li>
+ * <li>Following navigation paths must only be done step by step.</li>
+ * </ul>
+ * </p>
+ *
+ */
+public interface DataSource {
+
+ /**
+ * Retrieves the whole data list for the specified entity set.
+ * @param entitySet the requested {@link EdmEntitySet}
+ * @return the requested data list
+ */
+ List<?> readData(EdmEntitySet entitySet) throws ODataNotImplementedException, ODataNotFoundException, EdmException,
+ ODataApplicationException;
+
+ /**
+ * Retrieves a single data object for the specified entity set and key.
+ * @param entitySet the requested {@link EdmEntitySet}
+ * @param keys the entity key as map of key names to key values
+ * @return the requested data object
+ */
+ Object readData(EdmEntitySet entitySet, Map<String, Object> keys) throws ODataNotImplementedException,
+ ODataNotFoundException, EdmException, ODataApplicationException;
+
+ /**
+ * <p>Retrieves data for the specified function import and key.</p>
+ * <p>This method is called also for function imports that have defined in
+ * their metadata an other HTTP method than <code>GET</code>.</p>
+ * @param function the requested {@link EdmFunctionImport}
+ * @param parameters the parameters of the function import
+ * as map of parameter names to parameter values
+ * @param keys the key of the returned entity set, as map of key names to key values,
+ * if the return type of the function import is a collection of entities
+ * (optional)
+ * @return the requested data object, either a list or a single object;
+ * if the function import's return type is of type <code>Binary</code>,
+ * the returned object(s) must be of type {@link BinaryData}
+ */
+ Object readData(EdmFunctionImport function, Map<String, Object> parameters, Map<String, Object> keys)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException;
+
+ /**
+ * <p>Retrieves related data for the specified source data, entity set, and key.</p>
+ * <p>If the underlying association of the EDM is specified to have target
+ * multiplicity '*' and no target key is given, this method returns a list of
+ * related data, otherwise it returns a single data object.</p>
+ * @param sourceEntitySet the {@link EdmEntitySet} of the source entity
+ * @param sourceData the data object of the source entity
+ * @param targetEntitySet the requested target {@link EdmEntitySet}
+ * @param targetKeys the key of the target entity as map of key names to key values
+ * (optional)
+ * @return the requested releated data object, either a list or a single object
+ */
+ Object readRelatedData(EdmEntitySet sourceEntitySet, Object sourceData, EdmEntitySet targetEntitySet,
+ Map<String, Object> targetKeys) throws ODataNotImplementedException, ODataNotFoundException, EdmException,
+ ODataApplicationException;
+
+ /**
+ * Retrieves the binary data and the MIME type for the media resource
+ * associated to the specified media-link entry.
+ * @param entitySet the {@link EdmEntitySet} of the media-link entry
+ * @param mediaLinkEntryData the data object of the media-link entry
+ * @return the binary data and the MIME type of the media resource
+ */
+ BinaryData readBinaryData(EdmEntitySet entitySet, Object mediaLinkEntryData) throws ODataNotImplementedException,
+ ODataNotFoundException, EdmException, ODataApplicationException;
+
+ /**
+ * <p>Creates and returns a new instance of the requested data-object type.</p>
+ * <p>This instance must not be part of the corresponding list and should
+ * have empty content, apart from the key and other mandatory properties.
+ * However, intermediate objects to access complex properties must not be
+ * <code>null</code>.</p>
+ * @param entitySet the {@link EdmEntitySet} the object must correspond to
+ * @return the new data object
+ */
+ Object newDataObject(EdmEntitySet entitySet) throws ODataNotImplementedException, EdmException,
+ ODataApplicationException;
+
+ /**
+ * Writes the binary data for the media resource associated to the
+ * specified media-link entry.
+ * @param entitySet the {@link EdmEntitySet} of the media-link entry
+ * @param mediaLinkEntryData the data object of the media-link entry
+ * @param binaryData the binary data of the media resource along with
+ * the MIME type of the binary data
+ */
+ void writeBinaryData(EdmEntitySet entitySet, Object mediaLinkEntryData, BinaryData binaryData)
+ throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException;
+
+ /**
+ * Deletes a single data object identified by the specified entity set and key.
+ * @param entitySet the {@link EdmEntitySet} of the entity to be deleted
+ * @param keys the entity key as map of key names to key values
+ */
+ void deleteData(EdmEntitySet entitySet, Map<String, Object> keys) throws ODataNotImplementedException,
+ ODataNotFoundException, EdmException, ODataApplicationException;
+
+ /**
+ * <p>Inserts an instance into the entity list of the specified entity set.</p>
+ * <p>If {@link #newDataObject} has not set the key and other mandatory
+ * properties already, this method must set them before inserting the
+ * instance into the list.</p>
+ * @param entitySet the {@link EdmEntitySet} the object must correspond to
+ * @param data the data object of the new entity
+ */
+ void createData(EdmEntitySet entitySet, Object data) throws ODataNotImplementedException, EdmException,
+ ODataApplicationException;
+
+ /**
+ * Deletes the relation from the specified source data to a target entity
+ * specified by entity set and key.
+ * @param sourceEntitySet the {@link EdmEntitySet} of the source entity
+ * @param sourceData the data object of the source entity
+ * @param targetEntitySet the {@link EdmEntitySet} of the target entity
+ * @param targetKeys the key of the target entity as map of key names to key values
+ * (optional)
+ */
+ void deleteRelation(EdmEntitySet sourceEntitySet, Object sourceData, EdmEntitySet targetEntitySet,
+ Map<String, Object> targetKeys) throws ODataNotImplementedException, ODataNotFoundException, EdmException,
+ ODataApplicationException;
+
+ /**
+ * Writes a relation from the specified source data to a target entity
+ * specified by entity set and key.
+ * @param sourceEntitySet the {@link EdmEntitySet} of the source entity
+ * @param sourceData the data object of the source entity
+ * @param targetEntitySet the {@link EdmEntitySet} of the relation target
+ * @param targetKeys the key of the target entity as map of key names to key values
+ */
+ void writeRelation(EdmEntitySet sourceEntitySet, Object sourceData, EdmEntitySet targetEntitySet,
+ Map<String, Object> targetKeys) throws ODataNotImplementedException, ODataNotFoundException, EdmException,
+ ODataApplicationException;
+
+ /**
+ * Container to store binary data (as byte array) and the associated MIME type.
+ */
+ public class BinaryData {
+ private final byte[] data;
+ private final String mimeType;
+
+ public BinaryData(final byte[] data, final String mimeType) {
+ this.data = data;
+ this.mimeType = mimeType;
+ }
+
+ public byte[] getData() {
+ return data;
+ }
+
+ public String getMimeType() {
+ return mimeType;
+ }
+
+ @Override
+ public String toString() {
+ return "data=" + Arrays.toString(data) + ", mimeType=" + mimeType;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataStore.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataStore.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataStore.java
new file mode 100644
index 0000000..57b3d8c
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/DataStore.java
@@ -0,0 +1,294 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ ******************************************************************************/
+package org.apache.olingo.odata2.annotation.processor.core.datasource;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper;
+import org.apache.olingo.odata2.annotation.processor.core.util.ClassHelper;
+import org.apache.olingo.odata2.api.annotation.edm.EdmKey;
+import org.apache.olingo.odata2.api.exception.ODataApplicationException;
+import org.apache.olingo.odata2.core.exception.ODataRuntimeException;
+
+/**
+ *
+ */
+public class DataStore<T> {
+
+ private static final AnnotationHelper ANNOTATION_HELPER = new AnnotationHelper();
+ private final Map<KeyElement, T> dataStore;
+ private final Class<T> dataTypeClass;
+ private final KeyAccess keyAccess;
+
+ private static class InMemoryDataStore {
+ private static final Map<Class<?>, DataStore<?>> c2ds = new HashMap<Class<?>, DataStore<?>>();
+
+ @SuppressWarnings("unchecked")
+ static synchronized DataStore<?> getInstance(final Class<?> clz, final boolean createNewInstance)
+ throws DataStoreException {
+ DataStore<?> ds = c2ds.get(clz);
+ if (createNewInstance || ds == null) {
+ ds = new DataStore<Object>((Class<Object>) clz);
+ c2ds.put(clz, ds);
+ }
+ return ds;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> DataStore<T> createInMemory(final Class<T> clazz) throws DataStoreException {
+ return (DataStore<T>) InMemoryDataStore.getInstance(clazz, true);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> DataStore<T> createInMemory(final Class<T> clazz, final boolean keepExisting)
+ throws DataStoreException {
+ return (DataStore<T>) InMemoryDataStore.getInstance(clazz, !keepExisting);
+ }
+
+ private DataStore(final Map<KeyElement, T> wrapStore, final Class<T> clz) throws DataStoreException {
+ dataStore = Collections.synchronizedMap(wrapStore);
+ dataTypeClass = clz;
+ keyAccess = new KeyAccess(clz);
+ }
+
+ private DataStore(final Class<T> clz) throws DataStoreException {
+ this(new HashMap<KeyElement, T>(), clz);
+ }
+
+ public Class<T> getDataTypeClass() {
+ return dataTypeClass;
+ }
+
+ public String getEntityTypeName() {
+ return ANNOTATION_HELPER.extractEntityTypeName(dataTypeClass);
+ }
+
+ public T createInstance() {
+ try {
+ return dataTypeClass.newInstance();
+ } catch (InstantiationException e) {
+ throw new ODataRuntimeException("Unable to create instance of class '" + dataTypeClass + "'.", e);
+ } catch (IllegalAccessException e) {
+ throw new ODataRuntimeException("Unable to create instance of class '" + dataTypeClass + "'.", e);
+ }
+ }
+
+ public T read(final T obj) {
+ KeyElement objKeys = getKeys(obj);
+ return dataStore.get(objKeys);
+ }
+
+ public Collection<T> read() {
+ return Collections.unmodifiableCollection(dataStore.values());
+ }
+
+ public T create(final T object) throws DataStoreException {
+ KeyElement keyElement = getKeys(object);
+ return create(object, keyElement);
+ }
+
+ private T create(final T object, final KeyElement keyElement) throws DataStoreException {
+ synchronized (dataStore) {
+ if (keyElement.keyValuesMissing() || dataStore.containsKey(keyElement)) {
+ KeyElement newKey = createSetAndGetKeys(object);
+ return this.create(object, newKey);
+ }
+ dataStore.put(keyElement, object);
+ }
+ return object;
+ }
+
+ public T update(final T object) {
+ KeyElement keyElement = getKeys(object);
+ synchronized (dataStore) {
+ dataStore.remove(keyElement);
+ dataStore.put(keyElement, object);
+ }
+ return object;
+ }
+
+ public T delete(final T object) {
+ KeyElement keyElement = getKeys(object);
+ synchronized (dataStore) {
+ return dataStore.remove(keyElement);
+ }
+ }
+
+ /**
+ * Are the key values equal for both instances.
+ * If all compared key values are <code>null</code> this also means equal.
+ *
+ * @param first first instance to check for key equal
+ * @param second second instance to check for key equal
+ * @return <code>true</code> if object instance have equal keys set.
+ */
+ public boolean isKeyEqual(final T first, final T second) {
+ KeyElement firstKeys = getKeys(first);
+ KeyElement secondKeys = getKeys(second);
+
+ return firstKeys.equals(secondKeys);
+ }
+
+ /**
+ * Are the key values equal for both instances.
+ * If all compared key values are <code>null</code> this also means equal.
+ * Before object (keys) are compared it is validated that both object instance are NOT null
+ * and that both are from the same class as this {@link DataStore} (see {@link #dataTypeClass}).
+ * For the equal check on {@link #dataTypeClass} instances without validation see
+ * {@link #isKeyEqual(Object, Object)}.
+ *
+ * @param first first instance to check for key equal
+ * @param second second instance to check for key equal
+ * @return <code>true</code> if object instance have equal keys set.
+ */
+ @SuppressWarnings("unchecked")
+ public boolean isKeyEqualChecked(Object first, Object second) throws DataStoreException {
+ if(first == null || second == null) {
+ throw new DataStoreException("Tried to compare null values which is not allowed.");
+ } else if(first.getClass() != dataTypeClass) {
+ throw new DataStoreException("First value is no instance from required class '" + dataTypeClass + "'.");
+ } else if(second.getClass() != dataTypeClass) {
+ throw new DataStoreException("Second value is no instance from required class '" + dataTypeClass + "'.");
+ }
+
+ return isKeyEqual((T) first, (T) second);
+ }
+
+
+ private class KeyElement {
+ private int cachedHashCode = 42;
+ private final List<Object> keyValues;
+
+ public KeyElement(final int size) {
+ keyValues = new ArrayList<Object>(size);
+ }
+
+ private void addValue(final Object keyValue) {
+ keyValues.add(keyValue);
+ cachedHashCode = 89 * cachedHashCode + (keyValue != null ? keyValue.hashCode() : 0);
+ }
+
+ boolean keyValuesMissing() {
+ return keyValues.contains(null);
+ }
+
+ @Override
+ public int hashCode() {
+ return cachedHashCode;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ @SuppressWarnings("unchecked")
+ final KeyElement other = (KeyElement) obj;
+ if (this.keyValues != other.keyValues && (this.keyValues == null || !this.keyValues.equals(other.keyValues))) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "KeyElement{" + "cachedHashCode=" + cachedHashCode + ", keyValues=" + keyValues + '}';
+ }
+ }
+
+ private class KeyAccess {
+ final List<Field> keyFields;
+ final AtomicInteger idCounter = new AtomicInteger(1);
+
+ KeyAccess(final Class<?> clazz) throws DataStoreException {
+ keyFields = ANNOTATION_HELPER.getAnnotatedFields(clazz, EdmKey.class);
+ if (keyFields.isEmpty()) {
+ throw new DataStoreException("No EdmKey annotated fields found for class " + clazz);
+ }
+ }
+
+ KeyElement getKeyValues(final T object) {
+ KeyElement keyElement = new KeyElement(keyFields.size());
+ for (Field field : keyFields) {
+ Object keyValue = ClassHelper.getFieldValue(object, field);
+ keyElement.addValue(keyValue);
+ }
+
+ return keyElement;
+ }
+
+ KeyElement createSetAndGetKeys(final T object) throws DataStoreException {
+ KeyElement keyElement = new KeyElement(keyFields.size());
+ for (Field field : keyFields) {
+ Object key = createKey(field);
+ ClassHelper.setFieldValue(object, field, key);
+ keyElement.addValue(key);
+ }
+
+ return keyElement;
+ }
+
+ private Object createKey(final Field field) {
+ Class<?> type = field.getType();
+
+ if (type == String.class) {
+ return String.valueOf(idCounter.getAndIncrement());
+ } else if (type == Integer.class || type == int.class) {
+ return Integer.valueOf(idCounter.getAndIncrement());
+ } else if (type == Long.class || type == long.class) {
+ return Long.valueOf(idCounter.getAndIncrement());
+ }
+
+ throw new UnsupportedOperationException("Automated key generation for type '" + type
+ + "' is not supported (caused on field '" + field + "').");
+ }
+ }
+
+ private KeyElement getKeys(final T object) {
+ return keyAccess.getKeyValues(object);
+ }
+
+ private KeyElement createSetAndGetKeys(final T object) throws DataStoreException {
+ return keyAccess.createSetAndGetKeys(object);
+ }
+
+ public static class DataStoreException extends ODataApplicationException {
+ private static final long serialVersionUID = 42L;
+
+ public DataStoreException(final String message) {
+ this(message, null);
+ }
+
+ public DataStoreException(final String message, final Throwable cause) {
+ super(message, Locale.ENGLISH, cause);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/ValueAccess.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/ValueAccess.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/ValueAccess.java
new file mode 100644
index 0000000..d91d65c
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/datasource/ValueAccess.java
@@ -0,0 +1,69 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ ******************************************************************************/
+package org.apache.olingo.odata2.annotation.processor.core.datasource;
+
+import org.apache.olingo.odata2.api.edm.EdmMapping;
+import org.apache.olingo.odata2.api.edm.EdmProperty;
+import org.apache.olingo.odata2.api.exception.ODataException;
+
+/**
+ * This interface is intended to access values in a Java object.
+ */
+public interface ValueAccess {
+
+ /**
+ * Retrieves the value of an EDM property for the given data object.
+ * @param data the Java data object
+ * @param property the requested {@link EdmProperty}
+ * @return the requested property value
+ */
+ public <T> Object getPropertyValue(final T data, final EdmProperty property) throws ODataException;
+
+ /**
+ * Sets the value of an EDM property for the given data object.
+ * @param data the Java data object
+ * @param property the {@link EdmProperty}
+ * @param value the new value of the property
+ */
+ public <T, V> void setPropertyValue(T data, final EdmProperty property, final V value) throws ODataException;
+
+ /**
+ * Retrieves the Java type of an EDM property for the given data object.
+ * @param data the Java data object
+ * @param property the requested {@link EdmProperty}
+ * @return the requested Java type
+ */
+ public <T> Class<?> getPropertyType(final T data, final EdmProperty property) throws ODataException;
+
+ /**
+ * Retrieves the value defined by a mapping object for the given data object.
+ * @param data the Java data object
+ * @param mapping the requested {@link EdmMapping}
+ * @return the requested value
+ */
+ public <T> Object getMappingValue(final T data, final EdmMapping mapping) throws ODataException;
+
+ /**
+ * Sets the value defined by a mapping object for the given data object.
+ * @param data the Java data object
+ * @param mapping the {@link EdmMapping}
+ * @param value the new value
+ */
+ public <T, V> void setMappingValue(T data, final EdmMapping mapping, final V value) throws ODataException;
+}
http://git-wip-us.apache.org/repos/asf/incubator-olingo-odata2/blob/3bd59050/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/edm/AnnotationEdmProvider.java
----------------------------------------------------------------------
diff --git a/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/edm/AnnotationEdmProvider.java b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/edm/AnnotationEdmProvider.java
new file mode 100644
index 0000000..7247e5c
--- /dev/null
+++ b/odata2-annotation-processor/annotation-processor-core/src/main/java/org/apache/olingo/odata2/annotation/processor/core/edm/AnnotationEdmProvider.java
@@ -0,0 +1,769 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ ******************************************************************************/
+package org.apache.olingo.odata2.annotation.processor.core.edm;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.olingo.odata2.annotation.processor.core.util.AnnotationHelper;
+import org.apache.olingo.odata2.annotation.processor.core.util.ClassHelper;
+import org.apache.olingo.odata2.api.annotation.edm.EdmComplexType;
+import org.apache.olingo.odata2.api.annotation.edm.EdmEntitySet;
+import org.apache.olingo.odata2.api.annotation.edm.EdmEntityType;
+import org.apache.olingo.odata2.api.annotation.edm.EdmKey;
+import org.apache.olingo.odata2.api.annotation.edm.EdmMediaResourceContent;
+import org.apache.olingo.odata2.api.annotation.edm.EdmNavigationProperty;
+import org.apache.olingo.odata2.api.annotation.edm.EdmProperty;
+import org.apache.olingo.odata2.api.annotation.edm.EdmType;
+import org.apache.olingo.odata2.api.edm.EdmMultiplicity;
+import org.apache.olingo.odata2.api.edm.FullQualifiedName;
+import org.apache.olingo.odata2.api.edm.provider.AnnotationAttribute;
+import org.apache.olingo.odata2.api.edm.provider.AnnotationElement;
+import org.apache.olingo.odata2.api.edm.provider.Association;
+import org.apache.olingo.odata2.api.edm.provider.AssociationEnd;
+import org.apache.olingo.odata2.api.edm.provider.AssociationSet;
+import org.apache.olingo.odata2.api.edm.provider.AssociationSetEnd;
+import org.apache.olingo.odata2.api.edm.provider.ComplexProperty;
+import org.apache.olingo.odata2.api.edm.provider.ComplexType;
+import org.apache.olingo.odata2.api.edm.provider.EdmProvider;
+import org.apache.olingo.odata2.api.edm.provider.EntityContainer;
+import org.apache.olingo.odata2.api.edm.provider.EntityContainerInfo;
+import org.apache.olingo.odata2.api.edm.provider.EntitySet;
+import org.apache.olingo.odata2.api.edm.provider.EntityType;
+import org.apache.olingo.odata2.api.edm.provider.FunctionImport;
+import org.apache.olingo.odata2.api.edm.provider.Key;
+import org.apache.olingo.odata2.api.edm.provider.NavigationProperty;
+import org.apache.olingo.odata2.api.edm.provider.Property;
+import org.apache.olingo.odata2.api.edm.provider.PropertyRef;
+import org.apache.olingo.odata2.api.edm.provider.Schema;
+import org.apache.olingo.odata2.api.edm.provider.SimpleProperty;
+import org.apache.olingo.odata2.api.edm.provider.Using;
+import org.apache.olingo.odata2.api.exception.ODataException;
+import org.apache.olingo.odata2.core.exception.ODataRuntimeException;
+
+/**
+ * Provider for the entity data model used in the reference scenario
+ *
+ */
+public class AnnotationEdmProvider extends EdmProvider {
+
+ private static final AnnotationHelper ANNOTATION_HELPER = new AnnotationHelper();
+
+ private final List<Class<?>> annotatedClasses;
+ private final Map<String, EntityContainer> name2Container = new HashMap<String, EntityContainer>();
+ private final Map<String, ContainerBuilder> containerName2ContainerBuilder = new HashMap<String, ContainerBuilder>();
+ private final Map<String, Schema> namespace2Schema = new HashMap<String, Schema>();
+ private EntityContainer defaultContainer;
+
+ public AnnotationEdmProvider(final Collection<Class<?>> annotatedClasses) {
+
+ this.annotatedClasses = new ArrayList<Class<?>>(annotatedClasses.size());
+ for (Class<?> aClass : annotatedClasses) {
+ if (ANNOTATION_HELPER.isEdmAnnotated(aClass)) {
+ this.annotatedClasses.add(aClass);
+ }
+ }
+
+ init();
+ }
+
+ public AnnotationEdmProvider(final String packageToScan) {
+ annotatedClasses = ClassHelper.loadClasses(packageToScan, new ClassHelper.ClassValidator() {
+ @Override
+ public boolean isClassValid(final Class<?> c) {
+ return ANNOTATION_HELPER.isEdmAnnotated(c);
+ }
+ });
+
+ init();
+ }
+
+ private void init() {
+ for (Class<?> aClass : annotatedClasses) {
+ updateSchema(aClass);
+ handleEntityContainer(aClass);
+ }
+
+ finish();
+ }
+
+ @Override
+ public Association getAssociation(final FullQualifiedName edmFQName) throws ODataException {
+ Schema schema = namespace2Schema.get(edmFQName.getNamespace());
+ if (schema != null) {
+ List<Association> associations = schema.getAssociations();
+ for (Association association : associations) {
+ if (association.getName().equals(edmFQName.getName())) {
+ return association;
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association,
+ final String sourceEntitySetName, final String sourceEntitySetRole) throws ODataException {
+ EntityContainer container = name2Container.get(entityContainer);
+ if (container != null) {
+ List<AssociationSet> associations = container.getAssociationSets();
+ for (AssociationSet associationSet : associations) {
+ if (associationSet.getAssociation().equals(association)) {
+ final AssociationSetEnd endOne = associationSet.getEnd1();
+ if (endOne.getRole().equals(sourceEntitySetRole)
+ && endOne.getEntitySet().equals(sourceEntitySetName)) {
+ return associationSet;
+ }
+ final AssociationSetEnd endTwo = associationSet.getEnd2();
+ if (endTwo.getRole().equals(sourceEntitySetRole)
+ && endTwo.getEntitySet().equals(sourceEntitySetName)) {
+ return associationSet;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public ComplexType getComplexType(final FullQualifiedName edmFQName) throws ODataException {
+ Schema schema = namespace2Schema.get(edmFQName.getNamespace());
+ if (schema != null) {
+ List<ComplexType> complexTypes = schema.getComplexTypes();
+ for (ComplexType complexType : complexTypes) {
+ if (complexType.getName().equals(edmFQName.getName())) {
+ return complexType;
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public EntityContainerInfo getEntityContainerInfo(final String name) throws ODataException {
+ EntityContainer container = name2Container.get(name);
+ if (container == null) {
+ // use default container (if set)
+ container = defaultContainer;
+ }
+ if (container != null) {
+ EntityContainerInfo info = new EntityContainerInfo();
+ info.setName(container.getName());
+ info.setDefaultEntityContainer(container.isDefaultEntityContainer());
+ info.setExtendz(container.getExtendz());
+ info.setAnnotationAttributes(container.getAnnotationAttributes());
+ info.setAnnotationElements(container.getAnnotationElements());
+
+ return info;
+ }
+
+ return null;
+ }
+
+ @Override
+ public EntitySet getEntitySet(final String entityContainer, final String name) throws ODataException {
+ EntityContainer container = name2Container.get(entityContainer);
+ if (container != null) {
+ List<EntitySet> entitySets = container.getEntitySets();
+ for (EntitySet entitySet : entitySets) {
+ if (entitySet.getName().equals(name)) {
+ return entitySet;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public EntityType getEntityType(final FullQualifiedName edmFQName) throws ODataException {
+ Schema schema = namespace2Schema.get(edmFQName.getNamespace());
+ if (schema != null) {
+ List<EntityType> complexTypes = schema.getEntityTypes();
+ for (EntityType complexType : complexTypes) {
+ if (complexType.getName().equals(edmFQName.getName())) {
+ return complexType;
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public FunctionImport getFunctionImport(final String entityContainer, final String name) throws ODataException {
+ EntityContainer container = name2Container.get(entityContainer);
+ if (container != null) {
+ List<FunctionImport> functionImports = container.getFunctionImports();
+ for (FunctionImport functionImport : functionImports) {
+ if (functionImport.getName().equals(name)) {
+ return functionImport;
+ }
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public List<Schema> getSchemas() throws ODataException {
+ return new ArrayList<Schema>(namespace2Schema.values());
+ }
+
+ //
+ //
+ //
+ private Map<String, SchemaBuilder> namespace2SchemaBuilder = new HashMap<String, SchemaBuilder>();
+
+ private void updateSchema(final Class<?> aClass) {
+ EdmEntityType et = aClass.getAnnotation(EdmEntityType.class);
+ if (et != null) {
+ updateSchema(aClass, et);
+ }
+ EdmComplexType ect = aClass.getAnnotation(EdmComplexType.class);
+ if (ect != null) {
+ updateSchema(aClass, ect);
+ }
+ }
+
+ private void updateSchema(final Class<?> aClass, final EdmEntityType et) {
+ SchemaBuilder b = getSchemaBuilder(et.namespace(), aClass);
+ TypeBuilder typeBuilder = TypeBuilder.init(et, aClass);
+ b.addEntityType(typeBuilder.buildEntityType());
+ b.addAssociations(typeBuilder.buildAssociations());
+ }
+
+ private SchemaBuilder getSchemaBuilder(final String namespace, final Class<?> aClass) {
+ String usedNamespace = namespace;
+ if (usedNamespace.isEmpty()) {
+ usedNamespace = ANNOTATION_HELPER.getCanonicalNamespace(aClass);
+ }
+ SchemaBuilder builder = namespace2SchemaBuilder.get(usedNamespace);
+ if (builder == null) {
+ builder = SchemaBuilder.init(usedNamespace);
+ namespace2SchemaBuilder.put(usedNamespace, builder);
+ }
+ return builder;
+ }
+
+ private void updateSchema(final Class<?> aClass, final EdmComplexType et) {
+ SchemaBuilder b = getSchemaBuilder(et.namespace(), aClass);
+ TypeBuilder typeBuilder = TypeBuilder.init(et, aClass);
+ b.addComplexType(typeBuilder.buildComplexType());
+ }
+
+ private void handleEntityContainer(final Class<?> aClass) {
+ EdmEntityType entityType = aClass.getAnnotation(EdmEntityType.class);
+ if (entityType != null) {
+ FullQualifiedName typeName = createFqnForEntityType(aClass, entityType);
+ String containerName = ANNOTATION_HELPER.extractContainerName(aClass);
+ ContainerBuilder builder = containerName2ContainerBuilder.get(containerName);
+ if (builder == null) {
+ builder = ContainerBuilder.init(typeName.getNamespace(), containerName);
+ containerName2ContainerBuilder.put(containerName, builder);
+ }
+ EdmEntitySet entitySet = aClass.getAnnotation(EdmEntitySet.class);
+ if (entitySet != null) {
+ builder.addEntitySet(createEntitySet(typeName, aClass));
+ }
+ }
+ }
+
+ private EntitySet createEntitySet(final FullQualifiedName typeName, final Class<?> entitySetClass) {
+ String entitySetName = ANNOTATION_HELPER.extractEntitySetName(entitySetClass);
+ return new EntitySet().setName(entitySetName).setEntityType(typeName);
+ }
+
+ private FullQualifiedName createFqnForEntityType(final Class<?> annotatedClass, final EdmEntityType entityType) {
+ return ANNOTATION_HELPER.extractEntityTypeFqn(annotatedClass);
+ }
+
+ private void finish() {
+ //
+ Collection<ContainerBuilder> containers = containerName2ContainerBuilder.values();
+ for (ContainerBuilder containerBuilder : containers) {
+ SchemaBuilder schemaBuilder = namespace2SchemaBuilder.get(containerBuilder.getNamespace());
+ containerBuilder.addAssociationSets(schemaBuilder.name2Associations.values());
+ final EntityContainer container = containerBuilder.build();
+ schemaBuilder.addEntityContainer(container);
+ name2Container.put(container.getName(), container);
+ if (container.isDefaultEntityContainer()) {
+ defaultContainer = container;
+ }
+ }
+ //
+ Collection<SchemaBuilder> schemaBuilders = namespace2SchemaBuilder.values();
+ for (SchemaBuilder schemaBuilder : schemaBuilders) {
+ final Schema schema = schemaBuilder.build();
+ namespace2Schema.put(schema.getNamespace(), schema);
+ }
+ }
+
+ //
+ //
+ //
+ static class TypeBuilder {
+
+ final private String namespace;
+ final private String name;
+ private boolean isAbstract = false;
+ private boolean isMediaResource = false;
+ private FullQualifiedName baseEntityType = null;
+ private final List<PropertyRef> keyProperties = new ArrayList<PropertyRef>();
+ private final List<Property> properties = new ArrayList<Property>();
+ private final List<NavigationProperty> navProperties = new ArrayList<NavigationProperty>();
+ private final List<Association> associations = new ArrayList<Association>();
+
+ public TypeBuilder(final FullQualifiedName fqn) {
+ namespace = fqn.getNamespace();
+ name = fqn.getName();
+ }
+
+ public static TypeBuilder init(final EdmEntityType entity, final Class<?> aClass) {
+ return new TypeBuilder(ANNOTATION_HELPER.extractEntityTypeFqn(entity, aClass)).withClass(aClass);
+ }
+
+ public static TypeBuilder init(final EdmComplexType entity, final Class<?> aClass) {
+ return new TypeBuilder(ANNOTATION_HELPER.extractComplexTypeFqn(entity, aClass)).withClass(aClass);
+ }
+
+ private TypeBuilder withClass(final Class<?> aClass) {
+ baseEntityType = createBaseEntityFqn(aClass);
+
+ if (Modifier.isAbstract(aClass.getModifiers())) {
+ isAbstract = true;
+ }
+
+ Field[] fields = aClass.getDeclaredFields();
+ for (Field field : fields) {
+ EdmProperty ep = field.getAnnotation(EdmProperty.class);
+ if (ep != null) {
+ properties.add(createProperty(ep, field, namespace));
+ EdmKey eti = field.getAnnotation(EdmKey.class);
+ if (eti != null) {
+ keyProperties.add(createKeyProperty(ep, field));
+ }
+ }
+ EdmNavigationProperty enp = field.getAnnotation(EdmNavigationProperty.class);
+ if (enp != null) {
+ final NavigationProperty navProperty = createNavigationProperty(namespace, enp, field);
+ navProperties.add(navProperty);
+ Association association = createAssociation(field, navProperty);
+ associations.add(association);
+ }
+ EdmMediaResourceContent emrc = field.getAnnotation(EdmMediaResourceContent.class);
+ if (emrc != null) {
+ isMediaResource = true;
+ }
+ }
+
+ return this;
+ }
+
+ public TypeBuilder addProperty(final PropertyRef property) {
+ keyProperties.add(property);
+ return this;
+ }
+
+ public TypeBuilder addProperty(final Property property) {
+ properties.add(property);
+ return this;
+ }
+
+ public TypeBuilder addNavigationProperty(final NavigationProperty property) {
+ navProperties.add(property);
+ return this;
+ }
+
+ public TypeBuilder setAbstract(final boolean isAbstract) {
+ this.isAbstract = isAbstract;
+ return this;
+ }
+
+ public ComplexType buildComplexType() {
+ ComplexType complexType = new ComplexType();
+ if (baseEntityType != null) {
+ complexType.setBaseType(baseEntityType);
+ }
+ return complexType.setName(name).setProperties(properties);
+ }
+
+ public EntityType buildEntityType() {
+ EntityType entityType = new EntityType();
+ if (baseEntityType != null) {
+ entityType.setBaseType(baseEntityType);
+ }
+ if (!keyProperties.isEmpty()) {
+ entityType.setKey(new Key().setKeys(keyProperties));
+ }
+ if (!navProperties.isEmpty()) {
+ entityType.setNavigationProperties(navProperties);
+ }
+ return entityType.setName(name)
+ .setAbstract(isAbstract)
+ .setHasStream(isMediaResource)
+ .setProperties(properties);
+ }
+
+ public Collection<Association> buildAssociations() {
+ return Collections.unmodifiableCollection(associations);
+ }
+
+ private PropertyRef createKeyProperty(final EdmProperty et, final Field field) {
+ PropertyRef keyProperty = new PropertyRef();
+ String entityName = et.name();
+ if (entityName.isEmpty()) {
+ entityName = getCanonicalName(field);
+ }
+ return keyProperty.setName(entityName);
+ }
+
+ private Property createProperty(final EdmProperty ep, final Field field, final String defaultNamespace) {
+ if (isAnnotatedEntity(field.getType())) {
+ return createComplexProperty(field, defaultNamespace);
+ } else {
+ return createSimpleProperty(ep, field);
+ }
+ }
+
+ private Property createSimpleProperty(final EdmProperty ep, final Field field) {
+ SimpleProperty sp = new SimpleProperty();
+ String entityName = ANNOTATION_HELPER.getPropertyName(field);
+ sp.setName(entityName);
+ //
+ EdmType type = ep.type();
+ if (type == EdmType.NULL) {
+ type = getEdmType(field.getType());
+ }
+ sp.setType(ANNOTATION_HELPER.mapTypeKind(type));
+
+ return sp;
+ }
+
+ private Property createComplexProperty(final Field field, final String defaultNamespace) {
+ ComplexProperty cp = new ComplexProperty();
+ // settings from property
+ String entityName = ANNOTATION_HELPER.getPropertyName(field);
+ cp.setName(entityName);
+
+ // settings from related complex entity
+ EdmComplexType ece = field.getType().getAnnotation(EdmComplexType.class);
+ String complexEntityNamespace = ece.namespace();
+ if (complexEntityNamespace.isEmpty()) {
+ complexEntityNamespace = defaultNamespace;
+ }
+ cp.setType(new FullQualifiedName(complexEntityNamespace, ece.name()));
+
+ return cp;
+ }
+
+ private NavigationProperty createNavigationProperty(final String namespace, final EdmNavigationProperty enp,
+ final Field field) {
+ NavigationProperty navProp = new NavigationProperty();
+ navProp.setName(ANNOTATION_HELPER.getPropertyName(field));
+ String fromRole = ANNOTATION_HELPER.extractFromRoleName(enp, field);
+ navProp.setFromRole(fromRole);
+
+ String toRole = ANNOTATION_HELPER.extractToRoleName(enp, field);
+ navProp.setToRole(toRole);
+
+ String relationshipName = ANNOTATION_HELPER.extractRelationshipName(enp, field);
+ navProp.setRelationship(new FullQualifiedName(namespace, relationshipName));
+
+ return navProp;
+ }
+
+// private EdmSimpleTypeKind getEdmSimpleType(Class<?> type) {
+// if (type == String.class) {
+// return EdmType.String;
+// } else if (type == boolean.class || type == Boolean.class) {
+// return EdmType.Boolean;
+// } else if (type == byte.class || type == Byte.class) {
+// return EdmType.SByte;
+// } else if (type == short.class || type == Short.class) {
+// return EdmType.Int16;
+// } else if (type == int.class || type == Integer.class) {
+// return EdmType.Int32;
+// } else if (type == long.class || type == Long.class) {
+// return EdmType.Int64;
+// } else if (type == double.class || type == Double.class) {
+// return EdmType.Double;
+// } else if (type == float.class || type == Float.class) {
+// return EdmType.Single;
+// } else if (type == BigInteger.class || type == BigDecimal.class) {
+// return EdmType.Decimal;
+// } else if (type == Byte[].class || type == byte[].class) {
+// return EdmType.Binary;
+// } else if (type == Date.class) {
+// return EdmType.DateTime;
+// } else if (type == Calendar.class) {
+// return EdmType.DateTimeOffset;
+// } else if (type == UUID.class) {
+// return EdmType.Guid;
+// } else {
+// throw new UnsupportedOperationException("Not yet supported type '" + type + "'.");
+// }
+// }
+
+ private EdmType getEdmType(final Class<?> type) {
+ if (type == String.class) {
+ return EdmType.STRING;
+ } else if (type == boolean.class || type == Boolean.class) {
+ return EdmType.BOOLEAN;
+ } else if (type == byte.class || type == Byte.class) {
+ return EdmType.SBYTE;
+ } else if (type == short.class || type == Short.class) {
+ return EdmType.INT16;
+ } else if (type == int.class || type == Integer.class) {
+ return EdmType.INT32;
+ } else if (type == long.class || type == Long.class) {
+ return EdmType.INT64;
+ } else if (type == double.class || type == Double.class) {
+ return EdmType.DOUBLE;
+ } else if (type == float.class || type == Float.class) {
+ return EdmType.SINGLE;
+ } else if (type == BigInteger.class || type == BigDecimal.class) {
+ return EdmType.DECIMAL;
+ } else if (type == Byte[].class || type == byte[].class) {
+ return EdmType.BINARY;
+ } else if (type == Date.class) {
+ return EdmType.DATE_TIME;
+ } else if (type == Calendar.class) {
+ return EdmType.DATE_TIME_OFFSET;
+ } else if (type == UUID.class) {
+ return EdmType.GUID;
+ } else {
+ throw new UnsupportedOperationException("Not yet supported type '" + type + "'.");
+ }
+ }
+
+ private Class<?> checkForBaseEntityClass(final Class<?> aClass) {
+ Class<?> superClass = aClass.getSuperclass();
+ if (superClass == Object.class) {
+ return null;
+ } else {
+ EdmEntityType edmEntity = superClass.getAnnotation(EdmEntityType.class);
+ if (edmEntity == null) {
+ return checkForBaseEntityClass(superClass);
+ } else {
+ return superClass;
+ }
+ }
+ }
+
+ private FullQualifiedName createBaseEntityFqn(final Class<?> aClass) {
+ Class<?> baseEntityClass = checkForBaseEntityClass(aClass);
+ if (baseEntityClass == null) {
+ return null;
+ }
+ return ANNOTATION_HELPER.extractEntityTypeFqn(baseEntityClass);
+ }
+
+ private Association createAssociation(final Field field, final NavigationProperty navProperty) {
+ Association association = new Association();
+ EdmNavigationProperty navigation = field.getAnnotation(EdmNavigationProperty.class);
+
+ AssociationEnd fromEnd = new AssociationEnd();
+ fromEnd.setRole(navProperty.getFromRole());
+ String typeName = ANNOTATION_HELPER.extractEntityTypeName(field.getDeclaringClass());
+ fromEnd.setType(new FullQualifiedName(namespace, typeName));
+ fromEnd.setMultiplicity(EdmMultiplicity.ONE);
+ association.setEnd1(fromEnd);
+
+ AssociationEnd toEnd = new AssociationEnd();
+ toEnd.setRole(navProperty.getToRole());
+ String toTypeName = ANNOTATION_HELPER.extractEntitTypeName(navigation, field);
+ toEnd.setType(new FullQualifiedName(namespace, toTypeName));
+ toEnd.setMultiplicity(ANNOTATION_HELPER.getMultiplicity(navigation, field));
+ association.setEnd2(toEnd);
+
+ String associationName = navProperty.getRelationship().getName();
+ association.setName(associationName);
+ return association;
+ }
+
+ private String getCanonicalName(final Field field) {
+ return ANNOTATION_HELPER.getCanonicalName(field);
+ }
+
+ private boolean isAnnotatedEntity(final Class<?> clazz) {
+ return ANNOTATION_HELPER.isEdmTypeAnnotated(clazz);
+ }
+ }
+
+ static class SchemaBuilder {
+
+ final private String namespace;
+ // private String alias;
+ private final List<Using> usings = new ArrayList<Using>();
+ private final List<EntityType> entityTypes = new ArrayList<EntityType>();
+ private final List<ComplexType> complexTypes = new ArrayList<ComplexType>();
+ private final Map<String, Association> name2Associations = new HashMap<String, Association>();
+ private final List<EntityContainer> entityContainers = new ArrayList<EntityContainer>();
+ private final List<AnnotationAttribute> annotationAttributes = new ArrayList<AnnotationAttribute>();
+ private final List<AnnotationElement> annotationElements = new ArrayList<AnnotationElement>();
+
+ private SchemaBuilder(final String namespace) {
+ this.namespace = namespace;
+ }
+
+ public static SchemaBuilder init(final String namespace) {
+ return new SchemaBuilder(namespace);
+ }
+
+ public SchemaBuilder addEntityType(final EntityType type) {
+ entityTypes.add(type);
+ return this;
+ }
+
+ public SchemaBuilder addEntityContainer(final EntityContainer container) {
+ entityContainers.add(container);
+ return this;
+ }
+
+ public SchemaBuilder addComplexType(final ComplexType createEntityType) {
+ complexTypes.add(createEntityType);
+ return this;
+ }
+
+ public void addAssociations(final Collection<Association> associations) {
+ for (Association association : associations) {
+ final String relationshipName = association.getName();
+ if (name2Associations.containsKey(relationshipName)) {
+ association = mergeAssociations(name2Associations.get(relationshipName), association);
+ }
+ name2Associations.put(relationshipName, association);
+ }
+ }
+
+ private Association mergeAssociations(final Association associationOne, final Association associationTwo) {
+ AssociationEnd oneEnd1 = associationOne.getEnd1();
+ AssociationEnd oneEnd2 = associationOne.getEnd2();
+ AssociationEnd twoEnd1 = associationTwo.getEnd1();
+ AssociationEnd twoEnd2 = associationTwo.getEnd2();
+ AssociationEnd[] oneEnds = new AssociationEnd[] { oneEnd1, oneEnd2 };
+
+ for (AssociationEnd associationEnd : oneEnds) {
+ if (associationEnd.getRole().equals(twoEnd1.getRole())) {
+ if (twoEnd1.getMultiplicity() == EdmMultiplicity.MANY) {
+ associationEnd.setMultiplicity(EdmMultiplicity.MANY);
+ }
+ } else if (associationEnd.getRole().equals(twoEnd2.getRole())) {
+ if (twoEnd2.getMultiplicity() == EdmMultiplicity.MANY) {
+ associationEnd.setMultiplicity(EdmMultiplicity.MANY);
+ }
+ }
+ }
+
+ return associationOne;
+ }
+
+ public Schema build() {
+ Schema s = new Schema();
+ s.setUsings(usings);
+ s.setEntityTypes(entityTypes);
+ s.setComplexTypes(complexTypes);
+ s.setAssociations(new ArrayList<Association>(name2Associations.values()));
+ s.setEntityContainers(entityContainers);
+ s.setAnnotationAttributes(annotationAttributes);
+ s.setAnnotationElements(annotationElements);
+ s.setNamespace(namespace);
+ return s;
+ }
+ }
+
+ private static class ContainerBuilder {
+
+ final private String name;
+ final private String namespace;
+ private boolean defaultContainer = true;
+ private final List<EntitySet> entitySets = new ArrayList<EntitySet>();
+ private final List<AssociationSet> associationSets = new ArrayList<AssociationSet>();
+ private final List<FunctionImport> functionImports = new ArrayList<FunctionImport>();
+
+ // private Documentation documentation;
+
+ private ContainerBuilder(final String namespace, final String containerName) {
+ this.namespace = namespace;
+ name = containerName;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+
+ public static ContainerBuilder init(final String namespace, final String containerName) {
+ return new ContainerBuilder(namespace, containerName);
+ }
+
+ public ContainerBuilder addEntitySet(final EntitySet entitySet) {
+ entitySets.add(entitySet);
+ return this;
+ }
+
+ public void addAssociationSets(final Collection<Association> associations) {
+ for (Association association : associations) {
+ AssociationSet as = new AssociationSet();
+ as.setName(association.getName());
+ FullQualifiedName asAssociationFqn = new FullQualifiedName(namespace, association.getName());
+ as.setAssociation(asAssociationFqn);
+
+ AssociationSetEnd asEnd1 = new AssociationSetEnd();
+ asEnd1.setEntitySet(getEntitySetName(association.getEnd1()));
+ asEnd1.setRole(association.getEnd1().getRole());
+ as.setEnd1(asEnd1);
+
+ AssociationSetEnd asEnd2 = new AssociationSetEnd();
+ asEnd2.setEntitySet(getEntitySetName(association.getEnd2()));
+ asEnd2.setRole(association.getEnd2().getRole());
+ as.setEnd2(asEnd2);
+
+ associationSets.add(as);
+ }
+ }
+
+ public EntityContainer build() {
+ EntityContainer ec = new EntityContainer();
+ ec.setName(name);
+ ec.setDefaultEntityContainer(defaultContainer);
+ ec.setEntitySets(entitySets);
+ ec.setAssociationSets(associationSets);
+ ec.setFunctionImports(functionImports);
+ return ec;
+ }
+
+ private String getEntitySetName(final AssociationEnd end) {
+ for (EntitySet entitySet : entitySets) {
+ if (entitySet.getEntityType().equals(end.getType())) {
+ return entitySet.getName();
+ }
+ }
+ throw new ODataRuntimeException("No entity set found for " + end.getType());
+ }
+ }
+}