src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
EdmEntityTypeImplProv extends EdmStructuralTypeImplProv implements EdmEntityType { @Override public List<EdmProperty> getKeyProperties() throws EdmException { if (edmKeyProperties == null) { if (edmBaseType != null) { return ((EdmEntityType) edmBaseType).getKeyProperties(); } if (keyProperties == null) { keyProperties = new HashMap<String, EdmProperty>(); edmKeyProperties = new ArrayList<EdmProperty>(); for (String keyPropertyName : getKeyPropertyNames()) { final EdmTyped edmProperty = getProperty(keyPropertyName); if (edmProperty != null && edmProperty instanceof EdmProperty) { keyProperties.put(keyPropertyName, (EdmProperty) edmProperty); edmKeyProperties.add((EdmProperty) edmProperty); } else { throw new EdmException(EdmException.COMMON); } } } } return edmKeyProperties; } EdmEntityTypeImplProv(final EdmImplProv edm, final EntityType entityType, final String namespace); @Override List<String> getKeyPropertyNames(); @Override List<EdmProperty> getKeyProperties(); @Override boolean hasStream(); @Override EdmCustomizableFeedMappings getCustomizableFeedMappings(); @Override List<String> getNavigationPropertyNames(); @Override EdmEntityType getBaseType(); @Override EdmAnnotations getAnnotations(); }
@Test public void getKeyProperties() throws Exception { List<EdmProperty> keyProperties = edmEntityType.getKeyProperties(); assertNotNull(keyProperties); assertEquals("Id", keyProperties.get(0).getName()); } @Test public void getKeyPropertiesWithBaseType() throws Exception { List<EdmProperty> keyProperties = edmEntityTypeWithBaseType.getKeyProperties(); assertNotNull(keyProperties); assertEquals("Id", keyProperties.get(0).getName()); }
EdmEntityTypeImplProv extends EdmStructuralTypeImplProv implements EdmEntityType { @Override public List<String> getKeyPropertyNames() throws EdmException { if (edmKeyPropertyNames == null) { if (edmBaseType != null) { return ((EdmEntityType) edmBaseType).getKeyPropertyNames(); } edmKeyPropertyNames = new ArrayList<String>(); if (entityType.getKey() != null) { for (final PropertyRef keyProperty : entityType.getKey().getKeys()) { edmKeyPropertyNames.add(keyProperty.getName()); } } else { throw new EdmException(EdmException.COMMON); } } return edmKeyPropertyNames; } EdmEntityTypeImplProv(final EdmImplProv edm, final EntityType entityType, final String namespace); @Override List<String> getKeyPropertyNames(); @Override List<EdmProperty> getKeyProperties(); @Override boolean hasStream(); @Override EdmCustomizableFeedMappings getCustomizableFeedMappings(); @Override List<String> getNavigationPropertyNames(); @Override EdmEntityType getBaseType(); @Override EdmAnnotations getAnnotations(); }
@Test public void getKeyPropertiesNames() throws Exception { List<String> keyProperties = edmEntityType.getKeyPropertyNames(); assertNotNull(keyProperties); assertTrue(keyProperties.contains("Id")); List<String> properties = edmEntityType.getPropertyNames(); assertNotNull(properties); assertTrue(properties.contains("Id")); } @Test public void getKeyPropertiesNamesWithBaseType() throws Exception { List<String> keyProperties = edmEntityTypeWithBaseType.getKeyPropertyNames(); assertNotNull(keyProperties); assertTrue(keyProperties.contains("Id")); }
EdmEntityTypeImplProv extends EdmStructuralTypeImplProv implements EdmEntityType { @Override public List<String> getNavigationPropertyNames() throws EdmException { if (edmNavigationPropertyNames == null) { edmNavigationPropertyNames = new ArrayList<String>(); if (edmBaseType != null) { edmNavigationPropertyNames.addAll(((EdmEntityType) edmBaseType).getNavigationPropertyNames()); } if (entityType.getNavigationProperties() != null) { for (final NavigationProperty navigationProperty : entityType.getNavigationProperties()) { edmNavigationPropertyNames.add(navigationProperty.getName()); } } } return edmNavigationPropertyNames; } EdmEntityTypeImplProv(final EdmImplProv edm, final EntityType entityType, final String namespace); @Override List<String> getKeyPropertyNames(); @Override List<EdmProperty> getKeyProperties(); @Override boolean hasStream(); @Override EdmCustomizableFeedMappings getCustomizableFeedMappings(); @Override List<String> getNavigationPropertyNames(); @Override EdmEntityType getBaseType(); @Override EdmAnnotations getAnnotations(); }
@Test public void getNavProperties() throws Exception { List<String> navProperties = edmEntityType.getNavigationPropertyNames(); assertNotNull(navProperties); assertTrue(navProperties.contains("fooBarNav")); } @Test public void getNavPropertiesWithBaseType() throws Exception { List<String> navProperties = edmEntityTypeWithBaseType.getNavigationPropertyNames(); assertNotNull(navProperties); assertTrue(navProperties.contains("barBaseNav")); }
EdmEntityTypeImplProv extends EdmStructuralTypeImplProv implements EdmEntityType { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(entityType.getAnnotationAttributes(), entityType.getAnnotationElements()); } EdmEntityTypeImplProv(final EdmImplProv edm, final EntityType entityType, final String namespace); @Override List<String> getKeyPropertyNames(); @Override List<EdmProperty> getKeyProperties(); @Override boolean hasStream(); @Override EdmCustomizableFeedMappings getCustomizableFeedMappings(); @Override List<String> getNavigationPropertyNames(); @Override EdmEntityType getBaseType(); @Override EdmAnnotations getAnnotations(); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = edmEntityType; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmNavigationPropertyImplProv extends EdmTypedImplProv implements EdmNavigationProperty, EdmAnnotatable { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(navigationProperty.getAnnotationAttributes(), navigationProperty.getAnnotationElements()); } EdmNavigationPropertyImplProv(final EdmImplProv edm, final NavigationProperty property); @Override EdmType getType(); @Override EdmMultiplicity getMultiplicity(); @Override EdmAssociation getRelationship(); @Override String getFromRole(); @Override String getToRole(); @Override EdmAnnotations getAnnotations(); @Override EdmMapping getMapping(); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = navPropertyProvider; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmAssociationSetImplProv extends EdmNamedImplProv implements EdmAssociationSet, EdmAnnotatable { @Override public EdmAssociationSetEnd getEnd(final String role) throws EdmException { AssociationSetEnd end; if (associationSet.getEnd1().getRole().equals(role)) { end = associationSet.getEnd1(); } else if (associationSet.getEnd2().getRole().equals(role)) { end = associationSet.getEnd2(); } else { return null; } EdmEntitySet entitySet = edmEntityContainer.getEntitySet(end.getEntitySet()); if (entitySet == null) { throw new EdmException(EdmException.COMMON); } return new EdmAssociationSetEndImplProv(end, entitySet); } EdmAssociationSetImplProv(final EdmImplProv edm, final AssociationSet associationSet, final EdmEntityContainer edmEntityContainer); @Override EdmAssociation getAssociation(); @Override EdmAssociationSetEnd getEnd(final String role); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void testAssociationSet() throws Exception { EdmAssociationSet associationSet = edmAssociationSet; assertEquals("associationSetName", associationSet.getName()); assertEquals("end1Role", associationSet.getEnd("end1Role").getRole()); assertEquals(null, associationSet.getEnd("endWrongRole")); } @Test(expected = EdmException.class) public void testAssociationSetNoEntity() throws Exception { EdmAssociationSet associationSet = edmAssociationSet; associationSet.getEnd("end2Role"); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public boolean isMappingModelExists() { return mappingModelExists; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testIsMappingModelExists() { assertTrue(objJPAEdmMappingModelServiceTest.isMappingModelExists()); }
Team { public boolean isScrumTeam() { return isScrumTeam; } Team(final int id, final String name); String getId(); String getName(); void setName(final String name); boolean isScrumTeam(); void setScrumTeam(final boolean isScrumTeam); List<Employee> getEmployees(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); }
@Test public void testIsScrumTeam() { Team team1 = new Team(1, null); team1.setScrumTeam(true); assertTrue(team1.isScrumTeam()); }
EdmAssociationSetImplProv extends EdmNamedImplProv implements EdmAssociationSet, EdmAnnotatable { @Override public EdmAssociation getAssociation() throws EdmException { EdmAssociation association = edm.getAssociation(associationSet.getAssociation().getNamespace(), associationSet.getAssociation().getName()); if (association == null) { throw new EdmException(EdmException.COMMON); } return association; } EdmAssociationSetImplProv(final EdmImplProv edm, final AssociationSet associationSet, final EdmEntityContainer edmEntityContainer); @Override EdmAssociation getAssociation(); @Override EdmAssociationSetEnd getEnd(final String role); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void testAssociationExists() throws Exception { EdmAssociationSet associationSet = edmAssociationSet; assertNotNull(associationSet.getAssociation()); }
EdmAssociationSetImplProv extends EdmNamedImplProv implements EdmAssociationSet, EdmAnnotatable { @Override public EdmEntityContainer getEntityContainer() throws EdmException { return edmEntityContainer; } EdmAssociationSetImplProv(final EdmImplProv edm, final AssociationSet associationSet, final EdmEntityContainer edmEntityContainer); @Override EdmAssociation getAssociation(); @Override EdmAssociationSetEnd getEnd(final String role); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void testEntityContainer() throws Exception { EdmAssociationSet associationSet = edmAssociationSet; assertNotNull(associationSet.getEntityContainer()); }
EdmAssociationSetImplProv extends EdmNamedImplProv implements EdmAssociationSet, EdmAnnotatable { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(associationSet.getAnnotationAttributes(), associationSet.getAnnotationElements()); } EdmAssociationSetImplProv(final EdmImplProv edm, final AssociationSet associationSet, final EdmEntityContainer edmEntityContainer); @Override EdmAssociation getAssociation(); @Override EdmAssociationSetEnd getEnd(final String role); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = (EdmAnnotatable) edmAssociationSet; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmFunctionImportImplProv extends EdmNamedImplProv implements EdmFunctionImport, EdmAnnotatable { @Override public String getHttpMethod() throws EdmException { return functionImport.getHttpMethod(); } EdmFunctionImportImplProv(final EdmImplProv edm, final FunctionImport functionImport, final EdmEntityContainer edmEntityContainer); @Override EdmParameter getParameter(final String name); @Override List<String> getParameterNames(); @Override EdmEntitySet getEntitySet(); @Override String getHttpMethod(); @Override EdmTyped getReturnType(); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); @Override EdmMapping getMapping(); }
@Test public void functionImport() throws Exception { assertEquals("foo", edmFunctionImport.getName()); assertEquals(HttpMethods.GET, edmFunctionImport.getHttpMethod()); }
EdmFunctionImportImplProv extends EdmNamedImplProv implements EdmFunctionImport, EdmAnnotatable { @Override public EdmEntityContainer getEntityContainer() throws EdmException { return edmEntityContainer; } EdmFunctionImportImplProv(final EdmImplProv edm, final FunctionImport functionImport, final EdmEntityContainer edmEntityContainer); @Override EdmParameter getParameter(final String name); @Override List<String> getParameterNames(); @Override EdmEntitySet getEntitySet(); @Override String getHttpMethod(); @Override EdmTyped getReturnType(); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); @Override EdmMapping getMapping(); }
@Test public void containerName() throws Exception { assertEquals(edmEntityContainer, edmFunctionImport.getEntityContainer()); }
EdmFunctionImportImplProv extends EdmNamedImplProv implements EdmFunctionImport, EdmAnnotatable { @Override public EdmTyped getReturnType() throws EdmException { final ReturnType returnType = functionImport.getReturnType(); return new EdmTypedImplProv(edm, functionImport.getName(), returnType.getTypeName(), returnType.getMultiplicity()); } EdmFunctionImportImplProv(final EdmImplProv edm, final FunctionImport functionImport, final EdmEntityContainer edmEntityContainer); @Override EdmParameter getParameter(final String name); @Override List<String> getParameterNames(); @Override EdmEntitySet getEntitySet(); @Override String getHttpMethod(); @Override EdmTyped getReturnType(); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); @Override EdmMapping getMapping(); }
@Test public void returnType() throws Exception { EdmTyped returnType = edmFunctionImport.getReturnType(); assertNotNull(returnType); assertEquals(EdmSimpleTypeKind.String.getFullQualifiedName().getName(), returnType.getType().getName()); assertEquals(EdmMultiplicity.ONE, returnType.getMultiplicity()); }
EdmFunctionImportImplProv extends EdmNamedImplProv implements EdmFunctionImport, EdmAnnotatable { @Override public EdmEntitySet getEntitySet() throws EdmException { return edmEntityContainer.getEntitySet(functionImport.getEntitySet()); } EdmFunctionImportImplProv(final EdmImplProv edm, final FunctionImport functionImport, final EdmEntityContainer edmEntityContainer); @Override EdmParameter getParameter(final String name); @Override List<String> getParameterNames(); @Override EdmEntitySet getEntitySet(); @Override String getHttpMethod(); @Override EdmTyped getReturnType(); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); @Override EdmMapping getMapping(); }
@Test public void entitySet() throws Exception { EdmEntitySet entitySet = edmFunctionImport.getEntitySet(); assertNotNull(entitySet); assertEquals("fooEntitySet", entitySet.getName()); assertEquals(edmEntityContainer.getEntitySet("fooEntitySet"), entitySet); }
EdmFunctionImportImplProv extends EdmNamedImplProv implements EdmFunctionImport, EdmAnnotatable { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(functionImport.getAnnotationAttributes(), functionImport.getAnnotationElements()); } EdmFunctionImportImplProv(final EdmImplProv edm, final FunctionImport functionImport, final EdmEntityContainer edmEntityContainer); @Override EdmParameter getParameter(final String name); @Override List<String> getParameterNames(); @Override EdmEntitySet getEntitySet(); @Override String getHttpMethod(); @Override EdmTyped getReturnType(); @Override EdmEntityContainer getEntityContainer(); @Override EdmAnnotations getAnnotations(); @Override EdmMapping getMapping(); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = edmFunctionImport; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmAssociationImplProv extends EdmNamedImplProv implements EdmAssociation, EdmAnnotatable { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(association.getAnnotationAttributes(), association.getAnnotationElements()); } EdmAssociationImplProv(final EdmImplProv edm, final Association association, final String namespace); @Override String getNamespace(); @Override EdmTypeKind getKind(); @Override EdmAssociationEnd getEnd(final String role); @Override EdmAnnotations getAnnotations(); EdmMultiplicity getEndMultiplicity(final String role); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = associationProv; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmEntityContainerImplProv implements EdmEntityContainer, EdmAnnotatable { @Override public String getName() throws EdmException { return entityContainer.getName(); } EdmEntityContainerImplProv(final EdmImplProv edm, final EntityContainerInfo entityContainer); @Override String getName(); @Override EdmEntitySet getEntitySet(final String name); @Override EdmFunctionImport getFunctionImport(final String name); @Override EdmAssociationSet getAssociationSet(final EdmEntitySet sourceEntitySet, final EdmNavigationProperty navigationProperty); @Override boolean isDefaultEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void testEntityContainerName() throws EdmException { assertEquals("Container1", edmEntityContainer.getName()); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public JPAEdmMappingModel getJPAEdmMappingModel() { return mappingModel; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testGetJPAEdmMappingModel() { assertNotNull(objJPAEdmMappingModelServiceTest.getJPAEdmMappingModel()); }
EdmEntityContainerImplProv implements EdmEntityContainer, EdmAnnotatable { @Override public EdmEntitySet getEntitySet(final String name) throws EdmException { EdmEntitySet edmEntitySet = edmEntitySets.get(name); if (edmEntitySet != null) { return edmEntitySet; } EntitySet entitySet; try { entitySet = edm.edmProvider.getEntitySet(entityContainer.getName(), name); } catch (ODataException e) { throw new EdmException(EdmException.PROVIDERPROBLEM, e); } if (entitySet != null) { edmEntitySet = createEntitySet(entitySet); edmEntitySets.put(name, edmEntitySet); } else if (edmExtendedEntityContainer != null) { edmEntitySet = edmExtendedEntityContainer.getEntitySet(name); if (edmEntitySet != null) { edmEntitySets.put(name, edmEntitySet); } } return edmEntitySet; } EdmEntityContainerImplProv(final EdmImplProv edm, final EntityContainerInfo entityContainer); @Override String getName(); @Override EdmEntitySet getEntitySet(final String name); @Override EdmFunctionImport getFunctionImport(final String name); @Override EdmAssociationSet getAssociationSet(final EdmEntitySet sourceEntitySet, final EdmNavigationProperty navigationProperty); @Override boolean isDefaultEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void testEntitySetCache() throws EdmException { assertEquals(edmEntityContainer.getEntitySet("foo"), edmEntityContainer.getEntitySet("foo")); assertNotSame(edmEntityContainer.getEntitySet("foo"), edmEntityContainer.getEntitySet("bar")); }
EdmEntityContainerImplProv implements EdmEntityContainer, EdmAnnotatable { @Override public EdmFunctionImport getFunctionImport(final String name) throws EdmException { EdmFunctionImport edmFunctionImport = edmFunctionImports.get(name); if (edmFunctionImport != null) { return edmFunctionImport; } FunctionImport functionImport; try { functionImport = edm.edmProvider.getFunctionImport(entityContainer.getName(), name); } catch (ODataException e) { throw new EdmException(EdmException.PROVIDERPROBLEM, e); } if (functionImport != null) { edmFunctionImport = createFunctionImport(functionImport); edmFunctionImports.put(name, edmFunctionImport); } else if (edmExtendedEntityContainer != null) { edmFunctionImport = edmExtendedEntityContainer.getFunctionImport(name); if (edmFunctionImport != null) { edmFunctionImports.put(name, edmFunctionImport); } } return edmFunctionImport; } EdmEntityContainerImplProv(final EdmImplProv edm, final EntityContainerInfo entityContainer); @Override String getName(); @Override EdmEntitySet getEntitySet(final String name); @Override EdmFunctionImport getFunctionImport(final String name); @Override EdmAssociationSet getAssociationSet(final EdmEntitySet sourceEntitySet, final EdmNavigationProperty navigationProperty); @Override boolean isDefaultEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void testFunctionImportCache() throws EdmException { assertEquals(edmEntityContainer.getFunctionImport("foo"), edmEntityContainer.getFunctionImport("foo")); assertNotSame(edmEntityContainer.getFunctionImport("foo"), edmEntityContainer.getFunctionImport("bar")); }
EdmEntityContainerImplProv implements EdmEntityContainer, EdmAnnotatable { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(entityContainer.getAnnotationAttributes(), entityContainer.getAnnotationElements()); } EdmEntityContainerImplProv(final EdmImplProv edm, final EntityContainerInfo entityContainer); @Override String getName(); @Override EdmEntitySet getEntitySet(final String name); @Override EdmFunctionImport getFunctionImport(final String name); @Override EdmAssociationSet getAssociationSet(final EdmEntitySet sourceEntitySet, final EdmNavigationProperty navigationProperty); @Override boolean isDefaultEntityContainer(); @Override EdmAnnotations getAnnotations(); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = edmEntityContainer; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmAssociationEndImplProv implements EdmAssociationEnd, EdmAnnotatable { @Override public EdmEntityType getEntityType() throws EdmException { final FullQualifiedName type = associationEnd.getType(); EdmEntityType entityType = edm.getEntityType(type.getNamespace(), type.getName()); if (entityType == null) { throw new EdmException(EdmException.COMMON); } return entityType; } EdmAssociationEndImplProv(final EdmImplProv edm, final AssociationEnd associationEnd); @Override String getRole(); @Override EdmEntityType getEntityType(); @Override EdmMultiplicity getMultiplicity(); @Override EdmAnnotations getAnnotations(); }
@Test(expected = EdmException.class) public void testAssociationEntityType() throws Exception { EdmAssociationEnd associationEnd = associationEndProv; associationEnd.getEntityType(); }
EdmAssociationEndImplProv implements EdmAssociationEnd, EdmAnnotatable { @Override public EdmAnnotations getAnnotations() throws EdmException { return new EdmAnnotationsImplProv(associationEnd.getAnnotationAttributes(), associationEnd.getAnnotationElements()); } EdmAssociationEndImplProv(final EdmImplProv edm, final AssociationEnd associationEnd); @Override String getRole(); @Override EdmEntityType getEntityType(); @Override EdmMultiplicity getMultiplicity(); @Override EdmAnnotations getAnnotations(); }
@Test public void getAnnotations() throws Exception { EdmAnnotatable annotatable = associationEndProv; EdmAnnotations annotations = annotatable.getAnnotations(); assertNull(annotations.getAnnotationAttributes()); assertNull(annotations.getAnnotationElements()); }
EdmImpl implements Edm { @Override public EdmEntityType getEntityType(final String namespace, final String name) throws EdmException { FullQualifiedName fqName = new FullQualifiedName(namespace, name); if (edmEntityTypes.containsKey(fqName)) { return edmEntityTypes.get(fqName); } EdmEntityType edmEntityType = null; try { edmEntityType = createEntityType(fqName); if (edmEntityType != null) { edmEntityTypes.put(fqName, edmEntityType); } } catch (ODataException e) { throw new EdmException(EdmException.COMMON, e); } return edmEntityType; } EdmImpl(final EdmServiceMetadata edmServiceMetadata); @Override EdmEntityContainer getEntityContainer(final String name); @Override EdmEntityType getEntityType(final String namespace, final String name); @Override EdmComplexType getComplexType(final String namespace, final String name); @Override EdmAssociation getAssociation(final String namespace, final String name); @Override EdmServiceMetadata getServiceMetadata(); @Override EdmEntityContainer getDefaultEntityContainer(); }
@Test public void testEntityTypeCache() throws EdmException { assertEquals(edm.getEntityType("foo", "bar"), edm.getEntityType("foo", "bar")); assertNotSame(edm.getEntityType("foo", "bar"), edm.getEntityType("bar", "foo")); }
EdmImpl implements Edm { @Override public EdmComplexType getComplexType(final String namespace, final String name) throws EdmException { FullQualifiedName fqName = new FullQualifiedName(namespace, name); if (edmComplexTypes.containsKey(fqName)) { return edmComplexTypes.get(fqName); } EdmComplexType edmComplexType = null; try { edmComplexType = createComplexType(fqName); if (edmComplexType != null) { edmComplexTypes.put(fqName, edmComplexType); } } catch (ODataException e) { throw new EdmException(EdmException.COMMON, e); } return edmComplexType; } EdmImpl(final EdmServiceMetadata edmServiceMetadata); @Override EdmEntityContainer getEntityContainer(final String name); @Override EdmEntityType getEntityType(final String namespace, final String name); @Override EdmComplexType getComplexType(final String namespace, final String name); @Override EdmAssociation getAssociation(final String namespace, final String name); @Override EdmServiceMetadata getServiceMetadata(); @Override EdmEntityContainer getDefaultEntityContainer(); }
@Test public void testComplexTypeCache() throws EdmException { assertEquals(edm.getComplexType("foo", "bar"), edm.getComplexType("foo", "bar")); assertNotSame(edm.getComplexType("foo", "bar"), edm.getComplexType("bar", "foo")); }
EdmImpl implements Edm { @Override public EdmAssociation getAssociation(final String namespace, final String name) throws EdmException { FullQualifiedName fqName = new FullQualifiedName(namespace, name); if (edmAssociations.containsKey(fqName)) { return edmAssociations.get(fqName); } EdmAssociation edmAssociation = null; try { edmAssociation = createAssociation(fqName); if (edmAssociation != null) { edmAssociations.put(fqName, edmAssociation); } } catch (ODataException e) { throw new EdmException(EdmException.COMMON, e); } return edmAssociation; } EdmImpl(final EdmServiceMetadata edmServiceMetadata); @Override EdmEntityContainer getEntityContainer(final String name); @Override EdmEntityType getEntityType(final String namespace, final String name); @Override EdmComplexType getComplexType(final String namespace, final String name); @Override EdmAssociation getAssociation(final String namespace, final String name); @Override EdmServiceMetadata getServiceMetadata(); @Override EdmEntityContainer getDefaultEntityContainer(); }
@Test public void testAssociationCache() throws EdmException { assertEquals(edm.getAssociation("foo", "bar"), edm.getAssociation("foo", "bar")); assertNotSame(edm.getAssociation("foo", "bar"), edm.getAssociation("bar", "foo")); }
EdmParser { public DataServices readMetadata(final XMLStreamReader reader, final boolean validate) throws EntityProviderException { try { initialize(); DataServices dataServices = new DataServices(); List<Schema> schemas = new ArrayList<Schema>(); while (reader.hasNext() && !(reader.isEndElement() && Edm.NAMESPACE_EDMX_2007_06.equals(reader.getNamespaceURI()) && EdmParserConstants.EDM_DATA_SERVICES.equals(reader.getLocalName()))) { reader.next(); if (reader.isStartElement()) { extractNamespaces(reader); if (EdmParserConstants.EDM_SCHEMA.equals(reader.getLocalName())) { schemas.add(readSchema(reader)); } else if (EdmParserConstants.EDM_DATA_SERVICES.equals(reader .getLocalName())) { dataServices.setDataServiceVersion(reader.getAttributeValue(Edm.NAMESPACE_M_2007_08, "DataServiceVersion")); } } } if (validate) { validate(); } dataServices.setSchemas(schemas); reader.close(); return dataServices; } catch (XMLStreamException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } DataServices readMetadata(final XMLStreamReader reader, final boolean validate); }
@Test public void test() throws XMLStreamException, EntityProviderException { int i = 0; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); DataServices result = parser.readMetadata(reader, true); assertEquals("2.0", result.getDataServiceVersion()); for (Schema schema : result.getSchemas()) { assertEquals(NAMESPACE, schema.getNamespace()); assertEquals(1, schema.getEntityTypes().size()); assertEquals("Employee", schema.getEntityTypes().get(0).getName()); assertEquals(Boolean.TRUE, schema.getEntityTypes().get(0).isHasStream()); for (PropertyRef propertyRef : schema.getEntityTypes().get(0).getKey().getKeys()) { assertEquals("EmployeeId", propertyRef.getName()); } for (Property property : schema.getEntityTypes().get(0).getProperties()) { assertEquals(propertyNames[i], property.getName()); if ("Location".equals(property.getName())) { ComplexProperty cProperty = (ComplexProperty) property; assertEquals(NAMESPACE, cProperty.getType().getNamespace()); assertEquals("c_Location", cProperty.getType().getName()); } else if ("EmployeeName".equals(property.getName())) { assertNotNull(property.getCustomizableFeedMappings()); assertEquals("SyndicationTitle", property.getCustomizableFeedMappings().getFcTargetPath()); assertNull(property.getCustomizableFeedMappings().getFcContentKind()); } i++; } assertEquals(1, schema.getComplexTypes().size()); assertEquals("c_Location", schema.getComplexTypes().get(0).getName()); } } @Test public void testBaseType() throws XMLStreamException, EntityProviderException { int i = 0; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithBaseType); DataServices result = parser.readMetadata(reader, true); assertEquals("2.0", result.getDataServiceVersion()); for (Schema schema : result.getSchemas()) { assertEquals(NAMESPACE, schema.getNamespace()); assertEquals(2, schema.getEntityTypes().size()); assertEquals("Employee", schema.getEntityTypes().get(0).getName()); for (PropertyRef propertyRef : schema.getEntityTypes().get(0).getKey().getKeys()) { assertEquals("EmployeeId", propertyRef.getName()); } for (Property property : schema.getEntityTypes().get(0).getProperties()) { assertEquals(propertyNames[i], property.getName()); i++; } } } @Test public void testComplexTypeWithBaseType() throws XMLStreamException, EntityProviderException { final String xml = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" Alias=\"RS\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[2] + "\" Type=\"RefScenario.c_Location\" Nullable=\"false\"/>" + "</EntityType>" + "<ComplexType Name=\"c_BaseType_for_Location\" Abstract=\"true\">" + "<Property Name=\"Country\" Type=\"Edm.String\"/>" + "</ComplexType>" + "<ComplexType Name=\"c_Location\" BaseType=\"RefScenario.c_BaseType_for_Location\">" + "</ComplexType>" + "<ComplexType Name=\"c_Other_Location\" BaseType=\"RS.c_BaseType_for_Location\">" + "</ComplexType>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); DataServices result = parser.readMetadata(reader, true); assertEquals("2.0", result.getDataServiceVersion()); for (Schema schema : result.getSchemas()) { for (ComplexType complexType : schema.getComplexTypes()) { if ("c_Location".equals(complexType.getName())) { assertNotNull(complexType.getBaseType()); assertTrue(!complexType.isAbstract()); assertEquals("c_BaseType_for_Location", complexType.getBaseType().getName()); assertEquals("RefScenario", complexType.getBaseType().getNamespace()); } else if ("c_Other_Location".equals(complexType.getName())) { assertNotNull(complexType.getBaseType()); assertTrue(!complexType.isAbstract()); assertEquals("c_BaseType_for_Location", complexType.getBaseType().getName()); assertEquals("RS", complexType.getBaseType().getNamespace()); } else if ("c_BaseType_for_Location".equals(complexType.getName())) { assertNotNull(complexType.isAbstract()); assertTrue(complexType.isAbstract()); } else { assertTrue(false); } } } } @Test(expected = EntityProviderException.class) public void testComplexTypeWithInvalidBaseType() throws XMLStreamException, EntityProviderException { final String xml = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[2] + "\" Type=\"RefScenario.c_Location\" Nullable=\"false\"/>" + "</EntityType>" + "<ComplexType Name=\"c_BaseType_for_Location\" Abstract=\"true\">" + "<Property Name=\"Country\" Type=\"Edm.String\"/>" + "</ComplexType>" + "<ComplexType Name=\"c_Location\" BaseType=\"RefScenario.Employee\">" + "</ComplexType>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testComplexTypeWithInvalidBaseType2() throws XMLStreamException, EntityProviderException { final String xml = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[2] + "\" Type=\"RefScenario.c_Location\" Nullable=\"false\"/>" + "</EntityType>" + "<ComplexType Name=\"c_BaseType_for_Location\" Abstract=\"true\">" + "<Property Name=\"Country\" Type=\"Edm.String\"/>" + "</ComplexType>" + "<ComplexType Name=\"c_Location\" BaseType=\"c_BaseType_for_Location\">" + "</ComplexType>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); parser.readMetadata(reader, true); } @Test public void testAssociation() throws XMLStreamException, EntityProviderException { EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithAssociation); DataServices result = parser.readMetadata(reader, true); assertEquals("2.0", result.getDataServiceVersion()); for (Schema schema : result.getSchemas()) { for (EntityType entityType : schema.getEntityTypes()) { if ("Manager".equals(entityType.getName())) { assertEquals("RefScenario", entityType.getBaseType().getNamespace()); assertEquals("Employee", entityType.getBaseType().getName()); for (NavigationProperty navProperty : entityType.getNavigationProperties()) { assertEquals("r_Manager", navProperty.getFromRole()); assertEquals("r_Employees", navProperty.getToRole()); assertEquals("RefScenario", navProperty.getRelationship().getNamespace()); assertEquals(ASSOCIATION, navProperty.getRelationship().getName()); } } if ("Employee".equals(entityType.getName())) { for (NavigationProperty navProperty : entityType.getNavigationProperties()) { assertEquals("r_Employees", navProperty.getFromRole()); assertEquals("RefScenario", navProperty.getRelationship().getNamespace()); assertEquals(ASSOCIATION, navProperty.getRelationship().getName()); } } } for (Association association : schema.getAssociations()) { AssociationEnd end; assertEquals(ASSOCIATION, association.getName()); if ("Employee".equals(association.getEnd1().getType().getName())) { end = association.getEnd1(); } else { end = association.getEnd2(); } assertEquals(EdmMultiplicity.MANY, end.getMultiplicity()); assertEquals("r_Employees", end.getRole()); assertEquals(EdmAction.Cascade, end.getOnDelete().getAction()); } } } @Test public void testTwoSchemas() throws XMLStreamException, EntityProviderException { int i = 0; String schemasNs[] = { NAMESPACE, NAMESPACE2 }; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithTwoSchemas); DataServices result = parser.readMetadata(reader, true); assertEquals("2.0", result.getDataServiceVersion()); assertEquals(2, result.getSchemas().size()); for (Schema schema : result.getSchemas()) { assertEquals(schemasNs[i], schema.getNamespace()); assertEquals(1, schema.getEntityTypes().size()); i++; } } @Test public void testProperties() throws EntityProviderException, XMLStreamException { EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithTwoSchemas); DataServices result = parser.readMetadata(reader, true); for (Schema schema : result.getSchemas()) { for (EntityType entityType : schema.getEntityTypes()) { if ("Employee".equals(entityType.getName())) { for (Property property : entityType.getProperties()) { if (propertyNames[0].equals(property.getName())) { assertNotNull(property.getFacets()); assertEquals(Boolean.FALSE, property.getFacets().isNullable()); } else if (propertyNames[1].equals(property.getName())) { assertNull(property.getFacets()); } } } else if ("Photo".equals(entityType.getName())) { for (Property property : entityType.getProperties()) { SimpleProperty sProperty = (SimpleProperty) property; if ("Id".equals(property.getName())) { assertEquals(Boolean.FALSE, property.getFacets().isNullable()); assertEquals(EdmConcurrencyMode.Fixed, property.getFacets().getConcurrencyMode()); assertEquals(new Integer(MAX_LENGTH), property.getFacets().getMaxLength()); assertEquals(EdmSimpleTypeKind.Int32, sProperty.getType()); assertNull(property.getCustomizableFeedMappings()); } if ("Name".equals(property.getName())) { assertEquals(Boolean.TRUE, property.getFacets().isUnicode()); assertEquals(DEFAULT_VALUE, property.getFacets().getDefaultValue()); assertEquals(Boolean.FALSE, property.getFacets().isFixedLength()); assertEquals(EdmSimpleTypeKind.String, sProperty.getType()); assertNull(property.getCustomizableFeedMappings()); } if ("Содержание".equals(property.getName())) { assertEquals(FC_TARGET_PATH, property.getCustomizableFeedMappings().getFcTargetPath()); assertEquals(FC_NS_URI, property.getCustomizableFeedMappings().getFcNsUri()); assertEquals(FC_NS_PREFIX, property.getCustomizableFeedMappings().getFcNsPrefix()); assertEquals(FC_KEEP_IN_CONTENT, property.getCustomizableFeedMappings().isFcKeepInContent()); assertEquals(EdmContentKind.text, property.getCustomizableFeedMappings().getFcContentKind()); } if ("BinaryData".equals(property.getName())) { assertEquals(MIME_TYPE, property.getMimeType()); } } } } } } @Test public void testEntitySet() throws XMLStreamException, EntityProviderException { final String xmWithEntityContainer = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[1] + "\" Type=\"Edm.String\" m:FC_TargetPath=\"SyndicationTitle\"/>" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmWithEntityContainer); DataServices result = parser.readMetadata(reader, true); for (Schema schema : result.getSchemas()) { for (EntityContainer container : schema.getEntityContainers()) { assertEquals("Container1", container.getName()); assertEquals(Boolean.TRUE, container.isDefaultEntityContainer()); for (EntitySet entitySet : container.getEntitySets()) { assertEquals("Employees", entitySet.getName()); assertEquals("Employee", entitySet.getEntityType().getName()); assertEquals(NAMESPACE, entitySet.getEntityType().getNamespace()); } } } } @Test public void testAssociationSet() throws XMLStreamException, EntityProviderException { EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithAssociation); DataServices result = parser.readMetadata(reader, true); for (Schema schema : result.getSchemas()) { for (EntityContainer container : schema.getEntityContainers()) { assertEquals(NAMESPACE2, schema.getNamespace()); assertEquals("Container1", container.getName()); assertEquals(Boolean.TRUE, container.isDefaultEntityContainer()); for (AssociationSet assocSet : container.getAssociationSets()) { assertEquals(ASSOCIATION, assocSet.getName()); assertEquals(ASSOCIATION, assocSet.getAssociation().getName()); assertEquals(NAMESPACE, assocSet.getAssociation().getNamespace()); AssociationSetEnd end; if ("Employees".equals(assocSet.getEnd1().getEntitySet())) { end = assocSet.getEnd1(); } else { end = assocSet.getEnd2(); } assertEquals("r_Employees", end.getRole()); } } } } @Test public void testFunctionImport() throws XMLStreamException, EntityProviderException { final String xmWithEntityContainer = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[1] + "\" Type=\"Edm.String\" m:FC_TargetPath=\"SyndicationTitle\"/>" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "<FunctionImport Name=\"EmployeeSearch\" ReturnType=\"Collection(RefScenario.Employee)\" EntitySet=\"Employees\" m:HttpMethod=\"GET\">" + "<Parameter Name=\"q\" Type=\"Edm.String\" Nullable=\"true\" />" + "</FunctionImport>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmWithEntityContainer); DataServices result = parser.readMetadata(reader, true); for (Schema schema : result.getSchemas()) { for (EntityContainer container : schema.getEntityContainers()) { assertEquals("Container1", container.getName()); assertEquals(Boolean.TRUE, container.isDefaultEntityContainer()); for (FunctionImport functionImport : container.getFunctionImports()) { assertEquals("EmployeeSearch", functionImport.getName()); assertEquals("Employees", functionImport.getEntitySet()); assertEquals(NAMESPACE, functionImport.getReturnType().getTypeName().getNamespace()); assertEquals("Employee", functionImport.getReturnType().getTypeName().getName()); assertEquals(EdmMultiplicity.MANY, functionImport.getReturnType().getMultiplicity()); assertEquals("GET", functionImport.getHttpMethod()); for (FunctionImportParameter parameter : functionImport.getParameters()) { assertEquals("q", parameter.getName()); assertEquals(EdmSimpleTypeKind.String, parameter.getType()); assertEquals(Boolean.TRUE, parameter.getFacets().isNullable()); } } } } } @Test() public void testAlias() throws XMLStreamException, EntityProviderException { final String xml = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" Alias=\"RS\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RS.Employee\" m:HasStream=\"true\">" + "</EntityType>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); DataServices result = parser.readMetadata(reader, true); for (Schema schema : result.getSchemas()) { assertEquals("RS", schema.getAlias()); for (EntityType entityType : schema.getEntityTypes()) { if ("Manager".equals(entityType.getName())) { assertEquals("Employee", entityType.getBaseType().getName()); assertEquals("RS", entityType.getBaseType().getNamespace()); } } } } @Test(expected = EntityProviderException.class) public void testEntityTypeWithoutKeys() throws XMLStreamException, EntityProviderException { final String xmlWithoutKeys = "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "</EntityType>" + "</Schema>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithoutKeys); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testInvalidBaseType() throws XMLStreamException, EntityProviderException { final String xmlWithInvalidBaseType = "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Manager\" BaseType=\"Employee\" m:HasStream=\"true\">" + "</EntityType>" + "</Schema>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidBaseType); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testInvalidRole() throws XMLStreamException, EntityProviderException { final String xmlWithInvalidAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "<NavigationProperty Name=\"nm_Employees\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"Manager\" ToRole=\"Employees\" />" + "</EntityType>" + "<Association Name=\"ManagerEmployees\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociation); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testInvalidRelationship() throws XMLStreamException, EntityProviderException { final String xmlWithInvalidAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployee\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "</EntityType>" + "<Association Name=\"ManagerEmployees\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociation); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testMissingRelationship() throws Exception { final String xmlWithInvalidAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "</EntityType>" + "<Association Name=\"ManagerEmployees\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association></Schema></edmx:DataServices></edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociation); try { parser.readMetadata(reader, true); } catch (EntityProviderException e) { assertEquals(EntityProviderException.MISSING_ATTRIBUTE.getKey(), e.getMessageReference().getKey()); assertEquals(2, e.getMessageReference().getContent().size()); assertEquals("Relationship", e.getMessageReference().getContent().get(0)); assertEquals("NavigationProperty", e.getMessageReference().getContent().get(1)); throw e; } } @Test(expected = EntityProviderException.class) public void testMissingEntityType() throws Exception { final String xmlWithInvalidAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" />" + "</EntityContainer>" + "<Association Name=\"ManagerEmployees\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association></Schema></edmx:DataServices></edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociation); try { parser.readMetadata(reader, true); } catch (EntityProviderException e) { assertEquals(EntityProviderException.MISSING_ATTRIBUTE.getKey(), e.getMessageReference().getKey()); assertEquals(2, e.getMessageReference().getContent().size()); assertEquals("EntityType", e.getMessageReference().getContent().get(0)); assertEquals("EntitySet", e.getMessageReference().getContent().get(1)); throw e; } } @Test(expected = EntityProviderException.class) public void testMissingType() throws Exception { final String xmlWithInvalidAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "</EntityType>" + "<Association Name=\"ManagerEmployees\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association></Schema></edmx:DataServices></edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociation); try { parser.readMetadata(reader, true); } catch (EntityProviderException e) { assertEquals(EntityProviderException.MISSING_ATTRIBUTE.getKey(), e.getMessageReference().getKey()); assertEquals(2, e.getMessageReference().getContent().size()); assertEquals("Type", e.getMessageReference().getContent().get(0)); assertEquals("Property", e.getMessageReference().getContent().get(1)); throw e; } } @Test(expected = EntityProviderException.class) public void testMissingTypeAtAssociation() throws Exception { final String xmlWithInvalidAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "</EntityType>" + "<Association Name=\"ManagerEmployees\">" + "<End Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association></Schema></edmx:DataServices></edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociation); try { parser.readMetadata(reader, true); } catch (EntityProviderException e) { assertEquals(EntityProviderException.MISSING_ATTRIBUTE.getKey(), e.getMessageReference().getKey()); assertEquals(2, e.getMessageReference().getContent().size()); assertEquals("Type", e.getMessageReference().getContent().get(0)); assertEquals("End", e.getMessageReference().getContent().get(1)); throw e; } } @Test(expected = EntityProviderException.class) public void testMissingTypeAtFunctionImport() throws Exception { final String xml = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[1] + "\" Type=\"Edm.String\" m:FC_TargetPath=\"SyndicationTitle\"/>" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "<FunctionImport Name=\"EmployeeSearch\" ReturnType=\"Collection(RefScenario.Employee)\" EntitySet=\"Employees\" m:HttpMethod=\"GET\">" + "<Parameter Name=\"q\" Nullable=\"true\" />" + "</FunctionImport>" + "</EntityContainer></Schema></edmx:DataServices></edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); try { parser.readMetadata(reader, true); } catch (EntityProviderException e) { assertEquals(EntityProviderException.MISSING_ATTRIBUTE.getKey(), e.getMessageReference().getKey()); assertEquals(2, e.getMessageReference().getContent().size()); assertEquals("Type", e.getMessageReference().getContent().get(0)); assertEquals("Parameter", e.getMessageReference().getContent().get(1)); throw e; } } @Test(expected = EntityProviderException.class) public void testMissingAssociation() throws Exception { final String xmlWithAssociation = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "<AssociationSet Name=\"" + ASSOCIATION + "\">" + "<End EntitySet=\"Employees\" Role=\"r_Employees\"/>" + "</AssociationSet>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices></edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithAssociation); try { parser.readMetadata(reader, true); } catch (EntityProviderException e) { assertEquals(EntityProviderException.MISSING_ATTRIBUTE.getKey(), e.getMessageReference().getKey()); assertEquals(2, e.getMessageReference().getContent().size()); assertEquals("Association", e.getMessageReference().getContent().get(0)); assertEquals("AssociationSet", e.getMessageReference().getContent().get(1)); throw e; } } @Test(expected = EntityProviderException.class) public void testInvalidAssociation() throws XMLStreamException, EntityProviderException { final String xmlWithInvalidAssociationSet = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "<NavigationProperty Name=\"nm_Employees\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Manager\" ToRole=\"r_Employees\" />" + "</EntityType>" + "<Association Name=\"" + ASSOCIATION + "\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\">" + "<OnDelete Action=\"Cascade\"/>" + "</End>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "<EntitySet Name=\"Managers\" EntityType=\"RefScenario.Manager\"/>" + "<AssociationSet Name=\"" + ASSOCIATION + "\" Association=\"RefScenario2." + ASSOCIATION + "\">" + "<End EntitySet=\"Managers\" Role=\"r_Manager\"/>" + "<End EntitySet=\"Employees\" Role=\"r_Employees\"/>" + "</AssociationSet>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociationSet); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testInvalidAssociationEnd() throws XMLStreamException, EntityProviderException { final String employees = "r_Employees"; final String manager = "r_Manager"; final String xmlWithInvalidAssociationSetEnd = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"" + employees + "\" ToRole=\"" + manager + "\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "<NavigationProperty Name=\"nm_Employees\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"" + manager + "\" ToRole=\"" + employees + "\" />" + "</EntityType>" + "<Association Name=\"" + ASSOCIATION + "\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"" + employees + "1" + "\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"" + manager + "\"/>" + "</Association>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "<EntitySet Name=\"Managers\" EntityType=\"RefScenario.Manager\"/>" + "<AssociationSet Name=\"" + ASSOCIATION + "\" Association=\"RefScenario2." + ASSOCIATION + "\">" + "<End EntitySet=\"Managers\" Role=\"" + manager + "\"/>" + "<End EntitySet=\"Employees\" Role=\"" + employees + "\"/>" + "</AssociationSet>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociationSetEnd); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testInvalidAssociationEnd2() throws XMLStreamException, EntityProviderException { final String employees = "r_Employees"; final String manager = "r_Manager"; final String xmlWithInvalidAssociationSetEnd = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"" + employees + "\" ToRole=\"" + manager + "\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "<NavigationProperty Name=\"nm_Employees\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"" + manager + "\" ToRole=\"" + employees + "\" />" + "</EntityType>" + "<Association Name=\"" + ASSOCIATION + "\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"" + employees + "\"/>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"" + manager + "\"/>" + "</Association>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Employee\"/>" + "<EntitySet Name=\"Managers\" EntityType=\"RefScenario.Manager\"/>" + "<AssociationSet Name=\"" + ASSOCIATION + "\" Association=\"RefScenario2." + ASSOCIATION + "\">" + "<End EntitySet=\"Managers\" Role=\"" + manager + "\"/>" + "<End EntitySet=\"Managers\" Role=\"" + manager + "\"/>" + "</AssociationSet>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithInvalidAssociationSetEnd); parser.readMetadata(reader, true); } @Test(expected = EntityProviderException.class) public void testInvalidEntitySet() throws XMLStreamException, EntityProviderException { final String xmWithEntityContainer = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[1] + "\" Type=\"Edm.String\" m:FC_TargetPath=\"SyndicationTitle\"/>" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RefScenario.Mitarbeiter\"/>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmWithEntityContainer); parser.readMetadata(reader, true); } @Test public void testEntityTypeInOtherSchema() throws XMLStreamException, EntityProviderException { final String xmWithEntityContainer = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" m:HasStream=\"true\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Photos\" EntityType=\"" + NAMESPACE2 + ".Photo\"/>" + "</EntityContainer>" + "</Schema>" + "<Schema Namespace=\"" + NAMESPACE2 + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Photo\">" + "<Key><PropertyRef Name=\"Id\"/></Key>" + "<Property Name=\"Id\" Type=\"Edm.Int32\" Nullable=\"false\"/>" + "</EntityType>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmWithEntityContainer); DataServices result = parser.readMetadata(reader, true); assertEquals("2.0", result.getDataServiceVersion()); for (Schema schema : result.getSchemas()) { for (EntityContainer container : schema.getEntityContainers()) { assertEquals("Container1", container.getName()); for (EntitySet entitySet : container.getEntitySets()) { assertEquals(NAMESPACE2, entitySet.getEntityType().getNamespace()); assertEquals("Photo", entitySet.getEntityType().getName()); } } } } @Test public void scenarioTest() throws XMLStreamException, EntityProviderException { final String ASSOCIATION2 = "TeamEmployees"; final String xml = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" Alias=\"RS\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\">" + "<Key><PropertyRef Name=\"EmployeeId\"/></Key>" + "<Property Name=\"" + propertyNames[0] + "\" Type=\"Edm.String\" Nullable=\"false\"/>" + "<Property Name=\"" + propertyNames[2] + "\" Type=\"RefScenario.c_Location\" Nullable=\"false\"/>" + "<NavigationProperty Name=\"ne_Manager\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Manager\" />" + "<NavigationProperty Name=\"ne_Team\" Relationship=\"RefScenario.TeamEmployees\" FromRole=\"r_Employees\" ToRole=\"r_Team\" />" + "</EntityType>" + "<EntityType Name=\"Manager\" BaseType=\"RefScenario.Employee\" m:HasStream=\"true\">" + "<NavigationProperty Name=\"nm_Employees\" Relationship=\"RefScenario.ManagerEmployees\" FromRole=\"r_Manager\" ToRole=\"r_Employees\" />" + "</EntityType>" + "<EntityType Name=\"Team\">" + "<Key>" + "<PropertyRef Name=\"Id\"/>" + "</Key>" + "<NavigationProperty Name=\"nt_Employees\" Relationship=\"RefScenario.TeamEmployees\" FromRole=\"r_Team\" ToRole=\"r_Employees\" />" + "</EntityType>" + "<ComplexType Name=\"c_Location\">" + "<Property Name=\"Country\" Type=\"Edm.String\"/>" + "</ComplexType>" + "<Association Name=\"" + ASSOCIATION + "\">" + "<End Type=\"RS.Employee\" Multiplicity=\"*\" Role=\"r_Employees\">" + "<OnDelete Action=\"Cascade\"/>" + "</End>" + "<End Type=\"RefScenario.Manager\" Multiplicity=\"1\" Role=\"r_Manager\"/>" + "</Association>" + "<Association Name=\"" + ASSOCIATION2 + "\">" + "<End Type=\"RefScenario.Employee\" Multiplicity=\"*\" Role=\"r_Employees\"/>" + "<End Type=\"RefScenario.Team\" Multiplicity=\"1\" Role=\"r_Team\"/>" + "</Association>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Employees\" EntityType=\"RS.Employee\"/>" + "<EntitySet Name=\"Managers\" EntityType=\"RefScenario.Manager\"/>" + "<EntitySet Name=\"Teams\" EntityType=\"RefScenario.Team\"/>" + "<AssociationSet Name=\"" + ASSOCIATION + "\" Association=\"RefScenario." + ASSOCIATION + "\">" + "<End EntitySet=\"Managers\" Role=\"r_Manager\"/>" + "<End EntitySet=\"Employees\" Role=\"r_Employees\"/>" + "</AssociationSet>" + "<AssociationSet Name=\"" + ASSOCIATION2 + "\" Association=\"RefScenario." + ASSOCIATION2 + "\">" + "<End EntitySet=\"Teams\" Role=\"r_Team\"/>" + "<End EntitySet=\"Employees\" Role=\"r_Employees\"/>" + "</AssociationSet>" + "</EntityContainer>" + "</Schema>" + "<Schema Namespace=\"" + NAMESPACE2 + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Photo\">" + "<Key>" + "<PropertyRef Name=\"Id\"/>" + "<PropertyRef Name=\"Name\"/>" + "</Key>" + "<Property Name=\"Id\" Type=\"Edm.Int32\" Nullable=\"false\" ConcurrencyMode=\"Fixed\" MaxLength=\"" + MAX_LENGTH + "\"/>" + "<Property Name=\"Name\" Type=\"Edm.String\" Unicode=\"true\" DefaultValue=\"" + DEFAULT_VALUE + "\" FixedLength=\"false\"/>" + "<Property Name=\"BinaryData\" Type=\"Edm.Binary\" m:MimeType=\"" + MIME_TYPE + "\"/>" + "<Property Name=\"Содержание\" Type=\"Edm.String\" m:FC_TargetPath=\"" + FC_TARGET_PATH + "\" m:FC_NsUri=\"" + FC_NS_URI + "\"" + " m:FC_NsPrefix=\"" + FC_NS_PREFIX + "\" m:FC_KeepInContent=\"" + FC_KEEP_IN_CONTENT + "\" m:FC_ContentKind=\"text\" >" + "</Property>" + "</EntityType>" + "<EntityContainer Name=\"Container1\" m:IsDefaultEntityContainer=\"true\">" + "<EntitySet Name=\"Photos\" EntityType=\"RefScenario2.Photo\"/>" + "</EntityContainer>" + "</Schema>" + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xml); DataServices result = parser.readMetadata(reader, true); assertEquals(2, result.getSchemas().size()); for (Schema schema : result.getSchemas()) { if (NAMESPACE.equals(schema.getNamespace())) { assertEquals(3, schema.getEntityTypes().size()); assertEquals(1, schema.getComplexTypes().size()); assertEquals(2, schema.getAssociations().size()); assertEquals(1, schema.getEntityContainers().size()); } else if (NAMESPACE2.equals(schema.getNamespace())) { assertEquals(1, schema.getEntityTypes().size()); assertEquals(0, schema.getComplexTypes().size()); assertEquals(0, schema.getAssociations().size()); assertEquals(1, schema.getEntityContainers().size()); for (EntityType entityType : schema.getEntityTypes()) { assertEquals(2, entityType.getKey().getKeys().size()); } } } } @Test public void testRefScenario() throws Exception { EdmProvider testProvider = new EdmTestProvider(); ODataResponse response = EntityProvider.writeMetadata(testProvider.getSchemas(), null); String stream = StringHelper.inputStreamToString((InputStream) response.getEntity()); EdmParser parser = new EdmParser(); DataServices result = parser.readMetadata(createStreamReader(stream), true); ODataResponse response2 = EntityProvider.writeMetadata(result.getSchemas(), null); String streamAfterParse = StringHelper.inputStreamToString((InputStream) response2.getEntity()); assertEquals(stream, streamAfterParse); } @Test public void testAnnotations() throws XMLStreamException, EntityProviderException { final String xmlWithAnnotations = "<edmx:Edmx Version=\"1.0\" xmlns:edmx=\"" + Edm.NAMESPACE_EDMX_2007_06 + "\">" + "<edmx:DataServices m:DataServiceVersion=\"2.0\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Schema Namespace=\"" + NAMESPACE + "\" xmlns=\"" + Edm.NAMESPACE_EDM_2008_09 + "\">" + "<EntityType Name= \"Employee\" prefix1:href=\"http: + "<schemaElementTest3 rel=\"self\" pre:href=\"http: + "</edmx:DataServices>" + "</edmx:Edmx>"; EdmParser parser = new EdmParser(); XMLStreamReader reader = createStreamReader(xmlWithAnnotations); DataServices result = parser.readMetadata(reader, false); for (Schema schema : result.getSchemas()) { assertEquals(1, schema.getAnnotationElements().size()); for (AnnotationElement annoElement : schema.getAnnotationElements()) { for (AnnotationElement childAnnoElement : annoElement.getChildElements()) { if ("schemaElementTest2".equals(childAnnoElement.getName())) { assertEquals("prefix", childAnnoElement.getPrefix()); assertEquals("namespace", childAnnoElement.getNamespace()); assertEquals("text3", childAnnoElement.getText()); } else if ("schemaElementTest3".equals(childAnnoElement.getName())) { assertEquals("text4", childAnnoElement.getText()); assertEquals("rel", childAnnoElement.getAttributes().get(0).getName()); assertEquals("self", childAnnoElement.getAttributes().get(0).getText()); assertEquals("", childAnnoElement.getAttributes().get(0).getPrefix()); assertNull(childAnnoElement.getAttributes().get(0).getNamespace()); assertEquals("href", childAnnoElement.getAttributes().get(1).getName()); assertEquals("pre", childAnnoElement.getAttributes().get(1).getPrefix()); assertEquals("namespaceForAnno", childAnnoElement.getAttributes().get(1).getNamespace()); assertEquals("http: } else { throw new EntityProviderException(null, "xmlWithAnnotations"); } } } for (EntityType entityType : schema.getEntityTypes()) { assertEquals(1, entityType.getAnnotationAttributes().size()); AnnotationAttribute attr = entityType.getAnnotationAttributes().get(0); assertEquals("href", attr.getName()); assertEquals("prefix1", attr.getPrefix()); assertEquals("namespaceForAnno", attr.getNamespace()); assertEquals("http: for (Property property : entityType.getProperties()) { if ("EmployeeName".equals(property.getName())) { assertEquals(2, property.getAnnotationElements().size()); for (AnnotationElement anElement : property.getAnnotationElements()) { if ("propertyAnnoElement".equals(anElement.getName())) { assertEquals("text", anElement.getText()); } } for (AnnotationAttribute anAttribute : property.getAnnotationAttributes()) { assertEquals("annoName", anAttribute.getName()); assertEquals("annoPrefix", anAttribute.getPrefix()); assertEquals("annoText", anAttribute.getText()); assertEquals("http: } } } } } }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPAPersistenceUnit(final String persistenceUnitName) { JPAPersistenceUnitMapType persistenceUnit = mappingModel .getPersistenceUnit(); if (persistenceUnit.getName().equals(persistenceUnitName)) { return persistenceUnit.getEDMSchemaNamespace(); } return null; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPAPersistenceUnit() { assertEquals(PERSISTENCE_UNIT_NAME_EDM, objJPAEdmMappingModelServiceTest.mapJPAPersistenceUnit(PERSISTENCE_UNIT_NAME_JPA)); } @Test public void testMapJPAPersistenceUnitNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPAPersistenceUnit(PERSISTENCE_UNIT_NAME_EDM)); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPAEntityType(final String jpaEntityTypeName) { JPAEntityTypeMapType jpaEntityTypeMap = searchJPAEntityTypeMapType(jpaEntityTypeName); if (jpaEntityTypeMap != null) { return jpaEntityTypeMap.getEDMEntityType(); } else { return null; } } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPAEntityType() { assertEquals(ENTITY_TYPE_NAME_EDM, objJPAEdmMappingModelServiceTest.mapJPAEntityType(ENTITY_TYPE_NAME_JPA)); } @Test public void testMapJPAEntityTypeNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPAEntityType(ENTITY_TYPE_NAME_JPA_WRONG)); }
EdmxProvider extends EdmProvider { @Override public EntityType getEntityType(final FullQualifiedName edmFQName) throws ODataException { for (Schema schema : dataServices.getSchemas()) { if (schema.getNamespace().equals(edmFQName.getNamespace())) { for (EntityType entityType : schema.getEntityTypes()) { if (entityType.getName().equals(edmFQName.getName())) { return entityType; } } } } return null; } EdmxProvider parse(final InputStream in, final boolean validate); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testEntityType() throws EntityProviderException, ODataException, XMLStreamException { Edm edm = createEdm(); assertNotNull(edm); FullQualifiedName fqNameEmployee = new FullQualifiedName("RefScenario", "Employee"); EdmProvider testProvider = new EdmTestProvider(); EdmImplProv edmImpl = (EdmImplProv) edm; EntityType employee = edmImpl.getEdmProvider().getEntityType(fqNameEmployee); EntityType testEmployee = testProvider.getEntityType(fqNameEmployee); assertEquals(testEmployee.getName(), employee.getName()); assertEquals(testEmployee.isHasStream(), employee.isHasStream()); assertEquals(testEmployee.getProperties().size(), employee.getProperties().size()); assertEquals(testEmployee.getNavigationProperties().size(), employee.getNavigationProperties().size()); }
EdmxProvider extends EdmProvider { @Override public Association getAssociation(final FullQualifiedName edmFQName) throws ODataException { for (Schema schema : dataServices.getSchemas()) { if (schema.getNamespace().equals(edmFQName.getNamespace())) { for (Association association : schema.getAssociations()) { if (association.getName().equals(edmFQName.getName())) { return association; } } } } return null; } EdmxProvider parse(final InputStream in, final boolean validate); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testAssociation() throws EntityProviderException, ODataException, XMLStreamException { Edm edm = createEdm(); assertNotNull(edm); FullQualifiedName fqNameAssociation = new FullQualifiedName("RefScenario", "BuildingRooms"); EdmProvider testProvider = new EdmTestProvider(); EdmImplProv edmImpl = (EdmImplProv) edm; Association association = edmImpl.getEdmProvider().getAssociation(fqNameAssociation); Association testAssociation = testProvider.getAssociation(fqNameAssociation); assertEquals(testAssociation.getName(), association.getName()); assertEquals(testAssociation.getEnd1().getMultiplicity(), association.getEnd1().getMultiplicity()); assertEquals(testAssociation.getEnd2().getRole(), association.getEnd2().getRole()); assertEquals(testAssociation.getEnd1().getType(), association.getEnd1().getType()); }
EdmxProvider extends EdmProvider { @Override public List<Schema> getSchemas() throws ODataException { return dataServices.getSchemas(); } EdmxProvider parse(final InputStream in, final boolean validate); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testSchema() throws EntityProviderException, ODataException, XMLStreamException { EdmProvider testProvider = new EdmTestProvider(); Edm edm = createEdm(); assertNotNull(edm); EdmImplProv edmImpl = (EdmImplProv) edm; List<Schema> schemas = edmImpl.getEdmProvider().getSchemas(); List<Schema> testSchemas = testProvider.getSchemas(); assertEquals(testSchemas.size(), schemas.size()); if (!schemas.isEmpty() && !testSchemas.isEmpty()) { Schema schema = schemas.get(0); Schema testSchema = testSchemas.get(0); assertEquals(testSchema.getEntityContainers().size(), schema.getEntityContainers().size()); assertEquals(testSchema.getEntityTypes().size(), schema.getEntityTypes().size()); assertEquals(testSchema.getComplexTypes().size(), schema.getComplexTypes().size()); } }
EdmxProvider extends EdmProvider { @Override public EntityContainerInfo getEntityContainerInfo(final String name) throws ODataException { if (name != null) { for (Schema schema : dataServices.getSchemas()) { for (EntityContainer container : schema.getEntityContainers()) { if (container.getName().equals(name)) { return container; } } } } else { for (Schema schema : dataServices.getSchemas()) { for (EntityContainer container : schema.getEntityContainers()) { if (container.isDefaultEntityContainer()) { return container; } } } } return null; } EdmxProvider parse(final InputStream in, final boolean validate); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testContainer() throws EntityProviderException, ODataException, XMLStreamException { EdmProvider testProvider = new EdmTestProvider(); Edm edm = createEdm(); assertNotNull(edm); EdmImplProv edmImpl = (EdmImplProv) edm; EntityContainerInfo container = edmImpl.getEdmProvider().getEntityContainerInfo("Container2"); EntityContainerInfo testContainer = testProvider.getEntityContainerInfo("Container2"); assertEquals(testContainer.getName(), container.getName()); assertEquals(testContainer.isDefaultEntityContainer(), container.isDefaultEntityContainer()); container = edmImpl.getEdmProvider().getEntityContainerInfo(null); testContainer = testProvider.getEntityContainerInfo(null); assertNotNull(container); assertEquals(testContainer.getName(), container.getName()); assertEquals(testContainer.isDefaultEntityContainer(), container.isDefaultEntityContainer()); }
Encoder { public static String encode(final String value) { return encoder.encodeInternal(value); } private Encoder(final String unencoded); static String encode(final String value); }
@Test public void asciiCharacters() { final String s = "azAZ019"; assertEquals(s, Encoder.encode(s)); assertEquals(s, Encoder.encode(s)); } @Test public void asciiControl() { assertEquals("%08%09%0A%0D", Encoder.encode("\b\t\n\r")); } @Test public void unsafe() { assertEquals("%3C%3E%25%26", Encoder.encode("<>%&")); assertEquals("%22%5C%60%7B%7D%7C", Encoder.encode("\"\\`{}|")); } @Test public void rfc3986Unreserved() { assertEquals(RFC3986_UNRESERVED, Encoder.encode(RFC3986_UNRESERVED)); } @Test public void rfc3986GenDelims() { assertEquals("%3A%2F%3F%23%5B%5D%40", Encoder.encode(RFC3986_GEN_DELIMS)); } @Test public void rfc3986SubDelims() { assertEquals("%21%24%26'%28%29%2A%2B%2C%3B%3D", Encoder.encode(RFC3986_SUB_DELIMS)); } @Test public void rfc3986Reserved() { assertEquals("%3A%2F%3F%23%5B%5D%40%21%24%26'%28%29%2A%2B%2C%3B%3D", Encoder.encode(RFC3986_RESERVED)); } @Test public void unicodeCharacters() { assertEquals("%E2%82%AC", Encoder.encode("€")); assertEquals("%EF%B7%BC", Encoder.encode("\uFDFC")); } @Test public void charactersOutsideBmp() { final String s = String.valueOf(Character.toChars(0x1F603)); assertEquals("%F0%9F%98%83", Encoder.encode(s)); } @Test public void uriDecoding() throws URISyntaxException { final String decodedValue = RFC3986_UNRESERVED + RFC3986_RESERVED + "0..1..a..z..A..Z..@" + "\u2323\uFDFC" + String.valueOf(Character.toChars(0x1F603)); final String encodedPath = Encoder.encode(decodedValue) + "/" + Encoder.encode(decodedValue); final String encodedQuery = Encoder.encode(decodedValue); final URI uri = new URI("http: assertEquals(uri.getPath(), "/" + decodedValue + "/" + decodedValue); assertEquals(uri.getQuery(), decodedValue + "=" + decodedValue); assertEquals(uri.getRawPath(), "/" + encodedPath); assertEquals(uri.getRawQuery(), encodedQuery + "=" + encodedQuery); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPAEntitySet(final String jpaEntityTypeName) { JPAEntityTypeMapType jpaEntityTypeMap = searchJPAEntityTypeMapType(jpaEntityTypeName); if (jpaEntityTypeMap != null) { return jpaEntityTypeMap.getEDMEntitySet(); } else { return null; } } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPAEntitySet() { assertEquals(ENTITY_SET_NAME_EDM, objJPAEdmMappingModelServiceTest.mapJPAEntitySet(ENTITY_TYPE_NAME_JPA)); } @Test public void testMapJPAEntitySetNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPAEntitySet(ENTITY_TYPE_NAME_JPA_WRONG)); }
ContentType { public boolean isCompatible(final ContentType obj) { Boolean compatible = isEqualWithoutParameters(obj); if (compatible == null) { return true; } return compatible.booleanValue(); } private ContentType(final String type, final String subtype); private ContentType(final String type, final String subtype, final ODataFormat odataFormat); private ContentType(final String type, final String subtype, final ODataFormat odataFormat, final Map<String, String> parameters); static boolean isParseable(final String format); static ContentType create(final String type, final String subtype); static ContentType create(final String type, final String subtype, final Map<String, String> parameters); static ContentType create(final ContentType contentType, final String parameterKey, final String parameterValue); static ContentType create(final String format); static List<ContentType> create(final List<String> contentTypeStrings); static ContentType parse(final String format); ContentType receiveWithCharsetParameter(final String defaultCharset); boolean isContentTypeODataTextRelated(); String getType(); String getSubtype(); Map<String, String> getParameters(); @Override int hashCode(); @Override boolean equals(final Object obj); boolean isCompatible(final ContentType obj); String toContentTypeString(); @Override String toString(); ODataFormat getODataFormat(); ContentType match(final List<ContentType> toMatchContentTypes); ContentType matchCompatible(final List<ContentType> toMatchContentTypes); boolean hasCompatible(final List<ContentType> toMatchContentTypes); boolean hasMatch(final List<ContentType> toMatchContentTypes); int compareWildcardCounts(final ContentType otherContentType); boolean hasWildcard(); boolean isWildcard(); static List<ContentType> convert(final List<String> types); static boolean match(final String toMatch, final ContentType... matchExamples); static final String PARAMETER_CHARSET; static final String PARAMETER_ODATA; static final String PARAMETER_Q; static final String CHARSET_UTF_8; static final ContentType WILDCARD; static final ContentType APPLICATION_XML; static final ContentType APPLICATION_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML; static final ContentType APPLICATION_ATOM_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_ENTRY; static final ContentType APPLICATION_ATOM_XML_ENTRY_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_FEED; static final ContentType APPLICATION_ATOM_XML_FEED_CS_UTF_8; static final ContentType APPLICATION_ATOM_SVC; static final ContentType APPLICATION_ATOM_SVC_CS_UTF_8; static final ContentType APPLICATION_JSON; static final ContentType APPLICATION_JSON_ODATA_VERBOSE; static final ContentType APPLICATION_JSON_CS_UTF_8; static final ContentType APPLICATION_OCTET_STREAM; static final ContentType TEXT_PLAIN; static final ContentType TEXT_PLAIN_CS_UTF_8; static final ContentType MULTIPART_MIXED; }
@Test public void testMe() { MediaType t = new MediaType("*", "xml"); assertNotNull(t); assertTrue(t.isCompatible(new MediaType("app", "xml"))); }
ContentType { public static boolean isParseable(final String format) { try { return ContentType.create(format) != null; } catch (IllegalArgumentException e) { return false; } } private ContentType(final String type, final String subtype); private ContentType(final String type, final String subtype, final ODataFormat odataFormat); private ContentType(final String type, final String subtype, final ODataFormat odataFormat, final Map<String, String> parameters); static boolean isParseable(final String format); static ContentType create(final String type, final String subtype); static ContentType create(final String type, final String subtype, final Map<String, String> parameters); static ContentType create(final ContentType contentType, final String parameterKey, final String parameterValue); static ContentType create(final String format); static List<ContentType> create(final List<String> contentTypeStrings); static ContentType parse(final String format); ContentType receiveWithCharsetParameter(final String defaultCharset); boolean isContentTypeODataTextRelated(); String getType(); String getSubtype(); Map<String, String> getParameters(); @Override int hashCode(); @Override boolean equals(final Object obj); boolean isCompatible(final ContentType obj); String toContentTypeString(); @Override String toString(); ODataFormat getODataFormat(); ContentType match(final List<ContentType> toMatchContentTypes); ContentType matchCompatible(final List<ContentType> toMatchContentTypes); boolean hasCompatible(final List<ContentType> toMatchContentTypes); boolean hasMatch(final List<ContentType> toMatchContentTypes); int compareWildcardCounts(final ContentType otherContentType); boolean hasWildcard(); boolean isWildcard(); static List<ContentType> convert(final List<String> types); static boolean match(final String toMatch, final ContentType... matchExamples); static final String PARAMETER_CHARSET; static final String PARAMETER_ODATA; static final String PARAMETER_Q; static final String CHARSET_UTF_8; static final ContentType WILDCARD; static final ContentType APPLICATION_XML; static final ContentType APPLICATION_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML; static final ContentType APPLICATION_ATOM_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_ENTRY; static final ContentType APPLICATION_ATOM_XML_ENTRY_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_FEED; static final ContentType APPLICATION_ATOM_XML_FEED_CS_UTF_8; static final ContentType APPLICATION_ATOM_SVC; static final ContentType APPLICATION_ATOM_SVC_CS_UTF_8; static final ContentType APPLICATION_JSON; static final ContentType APPLICATION_JSON_ODATA_VERBOSE; static final ContentType APPLICATION_JSON_CS_UTF_8; static final ContentType APPLICATION_OCTET_STREAM; static final ContentType TEXT_PLAIN; static final ContentType TEXT_PLAIN_CS_UTF_8; static final ContentType MULTIPART_MIXED; }
@Test public void parseable() { assertTrue(ContentType.isParseable("application/xml")); assertTrue(ContentType.isParseable("text/plain")); assertTrue(ContentType.isParseable("application/atom+xml; charset=UTF-8")); assertFalse(ContentType.isParseable("application/ atom+xml; charset=UTF-8")); assertFalse(ContentType.isParseable("application /atom+xml; charset=UTF-8")); assertFalse(ContentType.isParseable("app/app/moreapp")); assertFalse(ContentType.isParseable(null)); }
ContentType { public static ContentType create(final String type, final String subtype) { return new ContentType(type, subtype, mapToODataFormat(type, subtype), null); } private ContentType(final String type, final String subtype); private ContentType(final String type, final String subtype, final ODataFormat odataFormat); private ContentType(final String type, final String subtype, final ODataFormat odataFormat, final Map<String, String> parameters); static boolean isParseable(final String format); static ContentType create(final String type, final String subtype); static ContentType create(final String type, final String subtype, final Map<String, String> parameters); static ContentType create(final ContentType contentType, final String parameterKey, final String parameterValue); static ContentType create(final String format); static List<ContentType> create(final List<String> contentTypeStrings); static ContentType parse(final String format); ContentType receiveWithCharsetParameter(final String defaultCharset); boolean isContentTypeODataTextRelated(); String getType(); String getSubtype(); Map<String, String> getParameters(); @Override int hashCode(); @Override boolean equals(final Object obj); boolean isCompatible(final ContentType obj); String toContentTypeString(); @Override String toString(); ODataFormat getODataFormat(); ContentType match(final List<ContentType> toMatchContentTypes); ContentType matchCompatible(final List<ContentType> toMatchContentTypes); boolean hasCompatible(final List<ContentType> toMatchContentTypes); boolean hasMatch(final List<ContentType> toMatchContentTypes); int compareWildcardCounts(final ContentType otherContentType); boolean hasWildcard(); boolean isWildcard(); static List<ContentType> convert(final List<String> types); static boolean match(final String toMatch, final ContentType... matchExamples); static final String PARAMETER_CHARSET; static final String PARAMETER_ODATA; static final String PARAMETER_Q; static final String CHARSET_UTF_8; static final ContentType WILDCARD; static final ContentType APPLICATION_XML; static final ContentType APPLICATION_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML; static final ContentType APPLICATION_ATOM_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_ENTRY; static final ContentType APPLICATION_ATOM_XML_ENTRY_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_FEED; static final ContentType APPLICATION_ATOM_XML_FEED_CS_UTF_8; static final ContentType APPLICATION_ATOM_SVC; static final ContentType APPLICATION_ATOM_SVC_CS_UTF_8; static final ContentType APPLICATION_JSON; static final ContentType APPLICATION_JSON_ODATA_VERBOSE; static final ContentType APPLICATION_JSON_CS_UTF_8; static final ContentType APPLICATION_OCTET_STREAM; static final ContentType TEXT_PLAIN; static final ContentType TEXT_PLAIN_CS_UTF_8; static final ContentType MULTIPART_MIXED; }
@Test(expected = IllegalArgumentException.class) public void testContentTypeCreationWildcardType() { ContentType.create("*", "subtype"); } @Test(expected = IllegalArgumentException.class) public void testContentTypeCreationWildcardTypeSingleFormat() { ContentType.create("*/subtype"); } @Test(expected = IllegalArgumentException.class) public void testContentTypeCreationFromStringsFail() { List<ContentType> types = ContentType.create(Arrays.asList("type/subtype", "application/xml", "application/json/FAIL;key=value")); assertEquals(3, types.size()); } @Test(expected = IllegalArgumentException.class) public void testFormatParserInvalidParameterWithSpaces() { ContentType.create("aaa/bbb;x= y;a"); } @Test(expected = IllegalArgumentException.class) public void testFormatParserInvalidParameterWithLineFeed() { ContentType.create("aaa/bbb;x=\ny;a"); } @Test(expected = IllegalArgumentException.class) public void testFormatParserInvalidParameterWithCarriageReturn() { ContentType.create("aaa/bbb;x=\ry;a"); } @Test(expected = IllegalArgumentException.class) public void testFormatParserInvalidParameterWithTabs() { ContentType.create("aaa/bbb;x=\ty;a"); } @Test(expected = IllegalArgumentException.class) public void testFormatParserInvalidParameterWithAllLws() { ContentType.create("aaa/bbb;x=\t \n \ry;a"); } @Test(expected = IllegalArgumentException.class) public void testFormatParserInvalidParameterWithAllLws2() { ContentType.create("aaa/bbb;x=\n \ry;a= \tbla "); } @Test public void testSimpleEqual() { ContentType t1 = ContentType.create("aaa/bbb"); ContentType t2 = ContentType.create("aaa/bbb"); assertEquals(t1, t2); } @Test(expected = IllegalArgumentException.class) public void testIllegalSubTypeWildcardSubtype() { ContentType t1 = ContentType.create("*/bbb"); assertNull(t1); }
ContentType { public boolean isWildcard() { return (MEDIA_TYPE_WILDCARD.equals(type) && MEDIA_TYPE_WILDCARD.equals(subtype)); } private ContentType(final String type, final String subtype); private ContentType(final String type, final String subtype, final ODataFormat odataFormat); private ContentType(final String type, final String subtype, final ODataFormat odataFormat, final Map<String, String> parameters); static boolean isParseable(final String format); static ContentType create(final String type, final String subtype); static ContentType create(final String type, final String subtype, final Map<String, String> parameters); static ContentType create(final ContentType contentType, final String parameterKey, final String parameterValue); static ContentType create(final String format); static List<ContentType> create(final List<String> contentTypeStrings); static ContentType parse(final String format); ContentType receiveWithCharsetParameter(final String defaultCharset); boolean isContentTypeODataTextRelated(); String getType(); String getSubtype(); Map<String, String> getParameters(); @Override int hashCode(); @Override boolean equals(final Object obj); boolean isCompatible(final ContentType obj); String toContentTypeString(); @Override String toString(); ODataFormat getODataFormat(); ContentType match(final List<ContentType> toMatchContentTypes); ContentType matchCompatible(final List<ContentType> toMatchContentTypes); boolean hasCompatible(final List<ContentType> toMatchContentTypes); boolean hasMatch(final List<ContentType> toMatchContentTypes); int compareWildcardCounts(final ContentType otherContentType); boolean hasWildcard(); boolean isWildcard(); static List<ContentType> convert(final List<String> types); static boolean match(final String toMatch, final ContentType... matchExamples); static final String PARAMETER_CHARSET; static final String PARAMETER_ODATA; static final String PARAMETER_Q; static final String CHARSET_UTF_8; static final ContentType WILDCARD; static final ContentType APPLICATION_XML; static final ContentType APPLICATION_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML; static final ContentType APPLICATION_ATOM_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_ENTRY; static final ContentType APPLICATION_ATOM_XML_ENTRY_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_FEED; static final ContentType APPLICATION_ATOM_XML_FEED_CS_UTF_8; static final ContentType APPLICATION_ATOM_SVC; static final ContentType APPLICATION_ATOM_SVC_CS_UTF_8; static final ContentType APPLICATION_JSON; static final ContentType APPLICATION_JSON_ODATA_VERBOSE; static final ContentType APPLICATION_JSON_CS_UTF_8; static final ContentType APPLICATION_OCTET_STREAM; static final ContentType TEXT_PLAIN; static final ContentType TEXT_PLAIN_CS_UTF_8; static final ContentType MULTIPART_MIXED; }
@Test public void testIsWildcard() { assertFalse(ContentType.create("aaa/bbb;x=y;a").isWildcard()); assertFalse(ContentType.create("aaa*;x=y;a").isWildcard()); assertTrue(ContentType.create("*/*").isWildcard()); }
ContentType { public boolean hasWildcard() { return (MEDIA_TYPE_WILDCARD.equals(type) || MEDIA_TYPE_WILDCARD.equals(subtype)); } private ContentType(final String type, final String subtype); private ContentType(final String type, final String subtype, final ODataFormat odataFormat); private ContentType(final String type, final String subtype, final ODataFormat odataFormat, final Map<String, String> parameters); static boolean isParseable(final String format); static ContentType create(final String type, final String subtype); static ContentType create(final String type, final String subtype, final Map<String, String> parameters); static ContentType create(final ContentType contentType, final String parameterKey, final String parameterValue); static ContentType create(final String format); static List<ContentType> create(final List<String> contentTypeStrings); static ContentType parse(final String format); ContentType receiveWithCharsetParameter(final String defaultCharset); boolean isContentTypeODataTextRelated(); String getType(); String getSubtype(); Map<String, String> getParameters(); @Override int hashCode(); @Override boolean equals(final Object obj); boolean isCompatible(final ContentType obj); String toContentTypeString(); @Override String toString(); ODataFormat getODataFormat(); ContentType match(final List<ContentType> toMatchContentTypes); ContentType matchCompatible(final List<ContentType> toMatchContentTypes); boolean hasCompatible(final List<ContentType> toMatchContentTypes); boolean hasMatch(final List<ContentType> toMatchContentTypes); int compareWildcardCounts(final ContentType otherContentType); boolean hasWildcard(); boolean isWildcard(); static List<ContentType> convert(final List<String> types); static boolean match(final String toMatch, final ContentType... matchExamples); static final String PARAMETER_CHARSET; static final String PARAMETER_ODATA; static final String PARAMETER_Q; static final String CHARSET_UTF_8; static final ContentType WILDCARD; static final ContentType APPLICATION_XML; static final ContentType APPLICATION_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML; static final ContentType APPLICATION_ATOM_XML_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_ENTRY; static final ContentType APPLICATION_ATOM_XML_ENTRY_CS_UTF_8; static final ContentType APPLICATION_ATOM_XML_FEED; static final ContentType APPLICATION_ATOM_XML_FEED_CS_UTF_8; static final ContentType APPLICATION_ATOM_SVC; static final ContentType APPLICATION_ATOM_SVC_CS_UTF_8; static final ContentType APPLICATION_JSON; static final ContentType APPLICATION_JSON_ODATA_VERBOSE; static final ContentType APPLICATION_JSON_CS_UTF_8; static final ContentType APPLICATION_OCTET_STREAM; static final ContentType TEXT_PLAIN; static final ContentType TEXT_PLAIN_CS_UTF_8; static final ContentType MULTIPART_MIXED; }
@Test public void testHasWildcard() { assertFalse(ContentType.create("aaa/bbb;x=y;a").hasWildcard()); assertTrue(ContentType.create("aaa*;x=y;a").hasWildcard()); assertTrue(ContentType.create("*/*").hasWildcard()); }
Decoder { public static String decode(final String value) throws IllegalArgumentException, NumberFormatException { if (value == null) { return value; } byte[] result = new byte[value.length()]; int position = 0; byte encodedPart = -2; for (final char c : value.toCharArray()) { if (c <= Byte.MAX_VALUE) { if (c == '%') { if (encodedPart == -2) { encodedPart = -1; } else { throw new IllegalArgumentException(); } } else if (encodedPart == -1) { encodedPart = (byte) c; } else if (encodedPart >= 0) { final int i = Integer.parseInt(String.valueOf(new char[] { (char) encodedPart, c }), 16); if (i >= 0) { result[position++] = (byte) i; } else { throw new NumberFormatException(); } encodedPart = -2; } else { result[position++] = (byte) c; } } else { throw new IllegalArgumentException(); } } if (encodedPart >= 0) { throw new IllegalArgumentException(); } try { return new String(result, 0, position, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } static String decode(final String value); }
@Test public void asciiCharacters() { assertNull(Decoder.decode(null)); String s = "azAZ019"; assertEquals(s, Decoder.decode(s)); s = "\"\\`{}|"; assertEquals(s, Decoder.decode(s)); } @Test public void asciiControl() { assertEquals("\u0000\b\t\n\r", Decoder.decode("%00%08%09%0a%0d")); } @Test public void asciiEncoded() { assertEquals("<>%&", Decoder.decode("%3c%3e%25%26")); assertEquals(":/?#[]@", Decoder.decode("%3a%2f%3f%23%5b%5d%40")); assertEquals(" !\"$'()*+,-.", Decoder.decode("%20%21%22%24%27%28%29%2A%2B%2C%2D%2E")); } @Test public void unicodeCharacters() { assertEquals("€", Decoder.decode("%E2%82%AC")); assertEquals("\uFDFC", Decoder.decode("%EF%B7%BC")); } @Test public void charactersOutsideBmp() { assertEquals(String.valueOf(Character.toChars(0x1F603)), Decoder.decode("%f0%9f%98%83")); } @Test(expected = IllegalArgumentException.class) public void wrongCharacter() { Decoder.decode("%20ä"); } @Test(expected = NumberFormatException.class) public void wrongPercentNumber() { Decoder.decode("%-3"); } @Test(expected = IllegalArgumentException.class) public void wrongPercentPercent() { Decoder.decode("%%a"); } @Test(expected = IllegalArgumentException.class) public void unfinishedPercent() { Decoder.decode("%a"); } @Test(expected = IllegalArgumentException.class) public void nullByte() { Decoder.decode("%\u0000ff"); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName) { JPAEntityTypeMapType jpaEntityTypeMap = searchJPAEntityTypeMapType(jpaEntityTypeName); if (jpaEntityTypeMap != null && jpaEntityTypeMap.getJPAAttributes() != null) { for (JPAAttribute jpaAttribute : jpaEntityTypeMap .getJPAAttributes().getJPAAttribute()) { if (jpaAttribute.getName().equals(jpaAttributeName)) { return jpaAttribute.getValue(); } } } return null; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPAAttribute() { assertEquals(ATTRIBUTE_NAME_EDM, objJPAEdmMappingModelServiceTest.mapJPAAttribute(ENTITY_TYPE_NAME_JPA, ATTRIBUTE_NAME_JPA)); } @Test public void testMapJPAAttributeNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPAAttribute(ENTITY_TYPE_NAME_JPA, ATTRIBUTE_NAME_JPA + "AA")); }
ODataDebugResponseWrapper { public ODataResponse wrapResponse() { try { return ODataResponse.status(HttpStatusCodes.OK) .entity(isJson ? wrapInJson(createParts()) : null) .contentHeader(isJson ? HttpContentType.APPLICATION_JSON : null) .build(); } catch (final ODataException e) { throw new ODataRuntimeException("Should not happen", e); } catch (final IOException e) { throw new ODataRuntimeException("Should not happen", e); } } ODataDebugResponseWrapper(final ODataContext context, final ODataResponse response, final UriInfo uriInfo, final Exception exception, final String debugValue); ODataResponse wrapResponse(); static final String ODATA_DEBUG_QUERY_PARAMETER; static final String ODATA_DEBUG_JSON; }
@Test public void minimal() throws Exception { final ODataContext context = mockContext(ODataHttpMethod.PUT); final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.NO_CONTENT, null, null); final ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String actualJson = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace(ODataHttpMethod.GET.name(), ODataHttpMethod.PUT.name()) .replace(Integer.toString(HttpStatusCodes.OK.getStatusCode()), Integer.toString(HttpStatusCodes.NO_CONTENT.getStatusCode())) .replace(HttpStatusCodes.OK.getInfo(), HttpStatusCodes.NO_CONTENT.getInfo()), actualJson); } @Test public void body() throws Exception { final ODataContext context = mockContext(ODataHttpMethod.GET); ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, "\"test\"", HttpContentType.APPLICATION_JSON); ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("{\"request", "{\"body\":\"test\",\"request") .replace("}}}", "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON + "\"}}}"), entity); wrappedResponse = mockResponse(HttpStatusCodes.OK, "test", HttpContentType.TEXT_PLAIN); response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("{\"request", "{\"body\":\"test\",\"request") .replace("}}}", "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.TEXT_PLAIN + "\"}}}"), entity); wrappedResponse = mockResponse(HttpStatusCodes.OK, null, "image/png"); when(wrappedResponse.getEntity()).thenReturn(new ByteArrayInputStream("test".getBytes())); response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("{\"request", "{\"body\":\"dGVzdA==\",\"request") .replace("}}}", "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"image/png\"}}}"), entity); } @Test public void headers() throws Exception { ODataContext context = mockContext(ODataHttpMethod.GET); Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(HttpContentType.APPLICATION_JSON)); when(context.getRequestHeaders()).thenReturn(headers); final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, HttpContentType.APPLICATION_JSON); final ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("},\"response", ",\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON + "\"}},\"response") .replace("}}}", "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON + "\"}}}"), entity); } @Test public void uri() throws Exception { final ODataContext context = mockContext(ODataHttpMethod.GET); final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null); UriInfo uriInfo = mock(UriInfo.class); final FilterExpression filter = UriParser.parseFilter(null, null, "true"); when(uriInfo.getFilter()).thenReturn(filter); final OrderByExpression orderBy = UriParser.parseOrderBy(null, null, "true"); when(uriInfo.getOrderBy()).thenReturn(orderBy); List<ArrayList<NavigationPropertySegment>> expand = new ArrayList<ArrayList<NavigationPropertySegment>>(); NavigationPropertySegment segment = mock(NavigationPropertySegment.class); EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class); when(navigationProperty.getName()).thenReturn("nav"); when(segment.getNavigationProperty()).thenReturn(navigationProperty); ArrayList<NavigationPropertySegment> segments = new ArrayList<NavigationPropertySegment>(); segments.add(segment); expand.add(segments); when(uriInfo.getExpand()).thenReturn(expand); SelectItem select1 = mock(SelectItem.class); SelectItem select2 = mock(SelectItem.class); EdmProperty property = mock(EdmProperty.class); when(property.getName()).thenReturn("property"); when(select1.getProperty()).thenReturn(property); when(select2.getProperty()).thenReturn(property); when(select2.getNavigationPropertySegments()).thenReturn(segments); when(uriInfo.getSelect()).thenReturn(Arrays.asList(select1, select2)); final ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, uriInfo, null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("}}}", "}},\"uri\":{\"filter\":{\"nodeType\":\"LITERAL\",\"type\":\"Edm.Boolean\",\"value\":\"true\"}," + "\"orderby\":{\"nodeType\":\"order collection\"," + "\"orders\":[{\"nodeType\":\"ORDER\",\"sortorder\":\"asc\"," + "\"expression\":{\"nodeType\":\"LITERAL\",\"type\":\"Edm.Boolean\",\"value\":\"true\"}}]}," + "\"expand/select\":{\"all\":false,\"properties\":[\"property\"]," + "\"links\":[{\"nav\":{\"all\":false,\"properties\":[\"property\"],\"links\":[]}}]}}}"), entity); } @Test public void uriWithException() throws Exception { final ODataContext context = mockContext(ODataHttpMethod.GET); final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null); UriInfo uriInfo = mock(UriInfo.class); FilterExpression filter = mock(FilterExpression.class); when(filter.getExpressionString()).thenReturn("wrong"); when(uriInfo.getFilter()).thenReturn(filter); ExpressionParserException exception = mock(ExpressionParserException.class); when(exception.getMessageReference()).thenReturn(ExpressionParserException.COMMON_ERROR); when(exception.getStackTrace()).thenReturn(new StackTraceElement[] { new StackTraceElement("class", "method", "file", 42) }); CommonExpression filterTree = mock(CommonExpression.class); when(filterTree.getUriLiteral()).thenReturn("wrong"); when(exception.getFilterTree()).thenReturn(filterTree); final ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, uriInfo, exception, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("}}}", "}},\"uri\":{\"error\":{\"filter\":\"wrong\"},\"filter\":null}," + "\"stacktrace\":{\"exceptions\":[{\"class\":\"" + exception.getClass().getName() + "\"," + "\"message\":\"Error while parsing a ODATA expression.\"," + "\"invocation\":{\"class\":\"class\",\"method\":\"method\",\"line\":42}}]," + "\"stacktrace\":[{\"class\":\"class\",\"method\":\"method\",\"line\":42}]}}"), entity); } @Test public void runtime() throws Exception { ODataContext context = mockContext(ODataHttpMethod.GET); List<RuntimeMeasurement> runtimeMeasurements = new ArrayList<RuntimeMeasurement>(); runtimeMeasurements.add(mockRuntimeMeasurement("method", 1000, 42000)); runtimeMeasurements.add(mockRuntimeMeasurement("inner", 2000, 5000)); runtimeMeasurements.add(mockRuntimeMeasurement("inner", 7000, 12000)); runtimeMeasurements.add(mockRuntimeMeasurement("inner", 13000, 16000)); runtimeMeasurements.add(mockRuntimeMeasurement("inner2", 14000, 15000)); runtimeMeasurements.add(mockRuntimeMeasurement("child", 17000, 21000)); runtimeMeasurements.add(mockRuntimeMeasurement("second", 45000, 99000)); when(context.getRuntimeMeasurements()).thenReturn(runtimeMeasurements); final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null); ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED.replace("}}}", "}},\"runtime\":[{\"class\":\"class\",\"method\":\"method\",\"duration\":41,\"memory\":3," + "\"children\":[{\"class\":\"class\",\"method\":\"inner\",\"duration\":8,\"memory\":6,\"children\":[]}," + "{\"class\":\"class\",\"method\":\"inner\",\"duration\":3,\"memory\":3,\"children\":[" + "{\"class\":\"class\",\"method\":\"inner2\",\"duration\":1,\"memory\":3,\"children\":[]}]}," + "{\"class\":\"class\",\"method\":\"child\",\"duration\":4,\"memory\":3,\"children\":[]}]}," + "{\"class\":\"class\",\"method\":\"second\",\"duration\":54,\"memory\":3,\"children\":[]}]}"), entity); } @Test public void exception() throws Exception { final ODataContext context = mockContext(ODataHttpMethod.GET); final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.BAD_REQUEST, null, null); ODataMessageException exception = mock(ODataMessageException.class); when(exception.getMessageReference()).thenReturn(ODataMessageException.COMMON); RuntimeException innerException = mock(RuntimeException.class); when(innerException.getLocalizedMessage()).thenReturn("error"); final StackTraceElement[] stackTrace = new StackTraceElement[] { new StackTraceElement("innerClass", "innerMethod", "innerFile", 99), new StackTraceElement("class", "method", "file", 42), new StackTraceElement("outerClass", "outerMethod", "outerFile", 11) }; when(innerException.getStackTrace()).thenReturn(stackTrace); when(exception.getCause()).thenReturn(innerException); when(exception.getStackTrace()).thenReturn(Arrays.copyOfRange(stackTrace, 1, 3)); final ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), exception, ODataDebugResponseWrapper.ODATA_DEBUG_JSON) .wrapResponse(); String entity = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertEquals(EXPECTED .replace(Integer.toString(HttpStatusCodes.OK.getStatusCode()), Integer.toString(HttpStatusCodes.BAD_REQUEST.getStatusCode())) .replace(HttpStatusCodes.OK.getInfo(), HttpStatusCodes.BAD_REQUEST.getInfo()) .replace("}}}", "}}," + "\"stacktrace\":{\"exceptions\":[{\"class\":\"" + exception.getClass().getName() + "\"," + "\"message\":\"Common exception\"," + "\"invocation\":{\"class\":\"class\",\"method\":\"method\",\"line\":42}}," + "{\"class\":\"" + innerException.getClass().getName() + "\",\"message\":\"error\"," + "\"invocation\":{\"class\":\"innerClass\",\"method\":\"innerMethod\",\"line\":99}}]," + "\"stacktrace\":[{\"class\":\"class\",\"method\":\"method\",\"line\":42}," + "{\"class\":\"outerClass\",\"method\":\"outerMethod\",\"line\":11}]}}"), entity); }
DebugInfoBody implements DebugInfo { @Override public void appendJson(final JsonStreamWriter jsonStreamWriter) throws IOException { final String contentType = response.getContentHeader(); if (contentType.startsWith("image/")) { if (response.getEntity() instanceof InputStream) { jsonStreamWriter.stringValueRaw(Base64.encodeBase64String(getBinaryFromInputStream((InputStream) response.getEntity()))); } else if (response.getEntity() instanceof String) { jsonStreamWriter.stringValueRaw(getContentString()); } else { throw new ClassCastException("Unsupported content entity class: " + response.getEntity().getClass().getName()); } } else if (contentType.startsWith(HttpContentType.APPLICATION_JSON)) { jsonStreamWriter.unquotedValue(getContentString()); } else { jsonStreamWriter.stringValue(getContentString()); } } DebugInfoBody(final ODataResponse response); @Override String getName(); @Override void appendJson(final JsonStreamWriter jsonStreamWriter); }
@Test public void jsonStringContent() throws Exception { ODataResponse response = mock(ODataResponse.class); when(response.getEntity()).thenReturn(STRING_CONTENT); when(response.getContentHeader()).thenReturn(HttpContentType.APPLICATION_OCTET_STREAM); assertEquals(STRING_CONTENT_JSON, appendJson(response)); when(response.getContentHeader()).thenReturn("image/png"); assertEquals(STRING_CONTENT_JSON, appendJson(response)); } @Test public void jsonInputStreamContent() throws Exception { ODataResponse response = mock(ODataResponse.class); ByteArrayInputStream in = new ByteArrayInputStream(STRING_CONTENT.getBytes()); when(response.getEntity()).thenReturn(in); when(response.getContentHeader()).thenReturn(HttpContentType.APPLICATION_OCTET_STREAM); assertEquals(STRING_CONTENT_JSON, appendJson(response)); in = new ByteArrayInputStream(STRING_CONTENT.getBytes()); when(response.getEntity()).thenReturn(in); when(response.getContentHeader()).thenReturn("image/png"); assertEquals("\"" + Base64.encodeBase64String(STRING_CONTENT.getBytes()) + "\"", appendJson(response)); } @Test(expected = ClassCastException.class) public void jsonUnsupportedContent() throws Exception { ODataResponse response = mock(ODataResponse.class); when(response.getEntity()).thenReturn(new Object()); when(response.getContentHeader()).thenReturn(HttpContentType.APPLICATION_OCTET_STREAM); appendJson(response); }
Dispatcher { public ODataResponse dispatch(final ODataHttpMethod method, final UriInfoImpl uriInfo, final InputStream content, final String requestContentType, final String contentType) throws ODataException { switch (uriInfo.getUriType()) { case URI0: if (method == ODataHttpMethod.GET) { return service.getServiceDocumentProcessor().readServiceDocument(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI1: case URI6B: switch (method) { case GET: return service.getEntitySetProcessor().readEntitySet(uriInfo, contentType); case POST: return service.getEntitySetProcessor().createEntity(uriInfo, content, requestContentType, contentType); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI2: switch (method) { case GET: return service.getEntityProcessor().readEntity(uriInfo, contentType); case PUT: return service.getEntityProcessor().updateEntity(uriInfo, content, requestContentType, false, contentType); case PATCH: case MERGE: return service.getEntityProcessor().updateEntity(uriInfo, content, requestContentType, true, contentType); case DELETE: return service.getEntityProcessor().deleteEntity(uriInfo, contentType); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI3: switch (method) { case GET: return service.getEntityComplexPropertyProcessor().readEntityComplexProperty(uriInfo, contentType); case PUT: return service.getEntityComplexPropertyProcessor().updateEntityComplexProperty(uriInfo, content, requestContentType, false, contentType); case PATCH: case MERGE: return service.getEntityComplexPropertyProcessor().updateEntityComplexProperty(uriInfo, content, requestContentType, true, contentType); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI4: case URI5: switch (method) { case GET: if (uriInfo.isValue()) { return service.getEntitySimplePropertyValueProcessor().readEntitySimplePropertyValue(uriInfo, contentType); } else { return service.getEntitySimplePropertyProcessor().readEntitySimpleProperty(uriInfo, contentType); } case PUT: case PATCH: case MERGE: if (uriInfo.isValue()) { return service.getEntitySimplePropertyValueProcessor().updateEntitySimplePropertyValue(uriInfo, content, requestContentType, contentType); } else { return service.getEntitySimplePropertyProcessor().updateEntitySimpleProperty(uriInfo, content, requestContentType, contentType); } case DELETE: if (uriInfo.isValue()) { return service.getEntitySimplePropertyValueProcessor().deleteEntitySimplePropertyValue(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI6A: switch (method) { case GET: return service.getEntityProcessor().readEntity(uriInfo, contentType); case PUT: case PATCH: case MERGE: case DELETE: throw new ODataBadRequestException(ODataBadRequestException.NOTSUPPORTED); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI7A: switch (method) { case GET: return service.getEntityLinkProcessor().readEntityLink(uriInfo, contentType); case PUT: case PATCH: case MERGE: return service.getEntityLinkProcessor().updateEntityLink(uriInfo, content, requestContentType, contentType); case DELETE: return service.getEntityLinkProcessor().deleteEntityLink(uriInfo, contentType); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI7B: switch (method) { case GET: return service.getEntityLinksProcessor().readEntityLinks(uriInfo, contentType); case POST: return service.getEntityLinksProcessor().createEntityLink(uriInfo, content, requestContentType, contentType); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI8: if (method == ODataHttpMethod.GET) { return service.getMetadataProcessor().readMetadata(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI9: if (method == ODataHttpMethod.POST) { BatchHandler handler = new BatchHandlerImpl(serviceFactory, service); return service.getBatchProcessor().executeBatch(handler, requestContentType, content); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI10: case URI11: case URI12: case URI13: return service.getFunctionImportProcessor().executeFunctionImport(uriInfo, contentType); case URI14: if (uriInfo.isValue()) { return service.getFunctionImportValueProcessor().executeFunctionImportValue(uriInfo, contentType); } else { return service.getFunctionImportProcessor().executeFunctionImport(uriInfo, contentType); } case URI15: if (method == ODataHttpMethod.GET) { return service.getEntitySetProcessor().countEntitySet(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI16: if (method == ODataHttpMethod.GET) { return service.getEntityProcessor().existsEntity(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI17: switch (method) { case GET: return service.getEntityMediaProcessor().readEntityMedia(uriInfo, contentType); case PUT: return service.getEntityMediaProcessor().updateEntityMedia(uriInfo, content, requestContentType, contentType); case DELETE: return service.getEntityMediaProcessor().deleteEntityMedia(uriInfo, contentType); default: throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI50A: if (method == ODataHttpMethod.GET) { return service.getEntityLinkProcessor().existsEntityLink(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } case URI50B: if (method == ODataHttpMethod.GET) { return service.getEntityLinksProcessor().countEntityLinks(uriInfo, contentType); } else { throw new ODataMethodNotAllowedException(ODataMethodNotAllowedException.DISPATCH); } default: throw new ODataRuntimeException("Unknown or not implemented URI type: " + uriInfo.getUriType()); } } Dispatcher(final ODataServiceFactory serviceFactory, final ODataService service); ODataResponse dispatch(final ODataHttpMethod method, final UriInfoImpl uriInfo, final InputStream content, final String requestContentType, final String contentType); }
@Test public void dispatch() throws Exception { checkDispatch(ODataHttpMethod.GET, UriType.URI0, "readServiceDocument"); checkDispatch(ODataHttpMethod.GET, UriType.URI1, "readEntitySet"); checkDispatch(ODataHttpMethod.POST, UriType.URI1, "createEntity"); checkDispatch(ODataHttpMethod.GET, UriType.URI2, "readEntity"); checkDispatch(ODataHttpMethod.PUT, UriType.URI2, "updateEntity"); checkDispatch(ODataHttpMethod.DELETE, UriType.URI2, "deleteEntity"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI2, "updateEntity"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI2, "updateEntity"); checkDispatch(ODataHttpMethod.GET, UriType.URI3, "readEntityComplexProperty"); checkDispatch(ODataHttpMethod.PUT, UriType.URI3, "updateEntityComplexProperty"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI3, "updateEntityComplexProperty"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI3, "updateEntityComplexProperty"); checkDispatch(ODataHttpMethod.GET, UriType.URI4, "readEntitySimpleProperty"); checkDispatch(ODataHttpMethod.PUT, UriType.URI4, "updateEntitySimpleProperty"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI4, "updateEntitySimpleProperty"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI4, "updateEntitySimpleProperty"); checkDispatch(ODataHttpMethod.GET, UriType.URI4, true, "readEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.PUT, UriType.URI4, true, "updateEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.DELETE, UriType.URI4, true, "deleteEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI4, true, "updateEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI4, true, "updateEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.GET, UriType.URI5, "readEntitySimpleProperty"); checkDispatch(ODataHttpMethod.PUT, UriType.URI5, "updateEntitySimpleProperty"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI5, "updateEntitySimpleProperty"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI5, "updateEntitySimpleProperty"); checkDispatch(ODataHttpMethod.GET, UriType.URI5, true, "readEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.PUT, UriType.URI5, true, "updateEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.DELETE, UriType.URI5, true, "deleteEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI5, true, "updateEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI5, true, "updateEntitySimplePropertyValue"); checkDispatch(ODataHttpMethod.GET, UriType.URI6A, "readEntity"); checkDispatch(ODataHttpMethod.GET, UriType.URI6B, "readEntitySet"); checkDispatch(ODataHttpMethod.POST, UriType.URI6B, "createEntity"); checkDispatch(ODataHttpMethod.GET, UriType.URI7A, "readEntityLink"); checkDispatch(ODataHttpMethod.PUT, UriType.URI7A, "updateEntityLink"); checkDispatch(ODataHttpMethod.DELETE, UriType.URI7A, "deleteEntityLink"); checkDispatch(ODataHttpMethod.PATCH, UriType.URI7A, "updateEntityLink"); checkDispatch(ODataHttpMethod.MERGE, UriType.URI7A, "updateEntityLink"); checkDispatch(ODataHttpMethod.GET, UriType.URI7B, "readEntityLinks"); checkDispatch(ODataHttpMethod.POST, UriType.URI7B, "createEntityLink"); checkDispatch(ODataHttpMethod.GET, UriType.URI8, "readMetadata"); checkDispatch(ODataHttpMethod.POST, UriType.URI9, "executeBatch"); checkDispatch(ODataHttpMethod.GET, UriType.URI10, "executeFunctionImport"); checkDispatch(ODataHttpMethod.GET, UriType.URI11, "executeFunctionImport"); checkDispatch(ODataHttpMethod.GET, UriType.URI12, "executeFunctionImport"); checkDispatch(ODataHttpMethod.GET, UriType.URI13, "executeFunctionImport"); checkDispatch(ODataHttpMethod.GET, UriType.URI14, "executeFunctionImport"); checkDispatch(ODataHttpMethod.GET, UriType.URI14, true, "executeFunctionImportValue"); checkDispatch(ODataHttpMethod.GET, UriType.URI15, "countEntitySet"); checkDispatch(ODataHttpMethod.GET, UriType.URI16, "existsEntity"); checkDispatch(ODataHttpMethod.GET, UriType.URI17, "readEntityMedia"); checkDispatch(ODataHttpMethod.PUT, UriType.URI17, "updateEntityMedia"); checkDispatch(ODataHttpMethod.DELETE, UriType.URI17, "deleteEntityMedia"); checkDispatch(ODataHttpMethod.GET, UriType.URI50A, "existsEntityLink"); checkDispatch(ODataHttpMethod.GET, UriType.URI50B, "countEntityLinks"); }
JsonStreamWriter { protected void escape(final String value) throws IOException { for (int i = 0; i < value.length(); i++) { final char c = value.charAt(i); switch (c) { case '\\': writer.append('\\').append(c); break; case '"': writer.append('\\').append(c); break; case '\b': writer.append('\\').append('b'); break; case '\t': writer.append('\\').append('t'); break; case '\n': writer.append('\\').append('n'); break; case '\f': writer.append('\\').append('f'); break; case '\r': writer.append('\\').append('r'); break; case '\u0000': case '\u0001': case '\u0002': case '\u0003': case '\u0004': case '\u0005': case '\u0006': case '\u0007': case '\u000B': case '\u000E': case '\u000F': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001A': case '\u001B': case '\u001C': case '\u001D': case '\u001E': case '\u001F': final int lastHexDigit = c % 0x10; writer.append('\\').append('u').append('0').append('0') .append(c >= '\u0010' ? '1' : '0') .append((char) ((lastHexDigit > 9 ? 'A' : '0') + lastHexDigit % 10)); break; default: writer.append(c); } } } JsonStreamWriter(final Writer writer); JsonStreamWriter beginObject(); JsonStreamWriter endObject(); JsonStreamWriter beginArray(); JsonStreamWriter endArray(); JsonStreamWriter name(final String name); JsonStreamWriter unquotedValue(final String value); JsonStreamWriter stringValueRaw(final String value); JsonStreamWriter stringValue(final String value); JsonStreamWriter namedStringValueRaw(final String name, final String value); JsonStreamWriter namedStringValue(final String name, final String value); JsonStreamWriter separator(); }
@Test public void escape() throws Exception { final String outsideBMP = String.valueOf(Character.toChars(0x1F603)); StringWriter writer = new StringWriter(); JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(writer); jsonStreamWriter.beginObject() .namedStringValue("normal", "abc / ? \u007F € \uFDFC").separator() .namedStringValue("outsideBMP", outsideBMP).separator() .namedStringValue("control", "\b\t\n\f\r\u0001\u000B\u0011\u001F " + "€ \uFDFC " + outsideBMP).separator() .namedStringValue("escaped", "\"\\") .endObject(); writer.flush(); assertEquals("{\"normal\":\"abc / ? \u007F € \uFDFC\"," + "\"outsideBMP\":\"\uD83D\uDE03\"," + "\"control\":\"\\b\\t\\n\\f\\r\\u0001\\u000B\\u0011\\u001F € \uFDFC \uD83D\uDE03\"," + "\"escaped\":\"\\\"\\\\\"}", writer.toString()); }
XmlPropertyConsumer { public Map<String, Object> readProperty(final XMLStreamReader reader, final EdmProperty property, final boolean merge) throws EntityProviderException { return readProperty(reader, property, merge, null); } Map<String, Object> readProperty(final XMLStreamReader reader, final EdmProperty property, final boolean merge); Map<String, Object> readProperty(final XMLStreamReader reader, final EdmProperty property, final boolean merge, final Map<String, Object> typeMappings); }
@Test public void readIntegerProperty() throws Exception { String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Age>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test public void readIntegerPropertyAsLong() throws Exception { String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Age>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); Map<String, Object> typeMappings = createTypeMappings("Age", Long.class); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false, typeMappings); assertEquals(Long.valueOf(67), resultMap.get("Age")); } @Test public void readIntegerPropertyWithNullMapping() throws Exception { String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Age>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); Map<String, Object> typeMappings = null; Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false, typeMappings); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test public void readIntegerPropertyWithEmptyMapping() throws Exception { String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Age>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); Map<String, Object> typeMappings = new HashMap<String, Object>(); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false, typeMappings); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test public void readStringProperty() throws Exception { String xml = "<EmployeeName xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">Max Mustermann</EmployeeName>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EmployeeName"); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertEquals("Max Mustermann", resultMap.get("EmployeeName")); } @Test public void readStringPropertyEmpty() throws Exception { final String xml = "<EmployeeName xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EmployeeName"); final Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertTrue(resultMap.containsKey("EmployeeName")); assertEquals("", resultMap.get("EmployeeName")); } @Test public void readStringPropertyNull() throws Exception { final String xml = "<EntryDate xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"true\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EntryDate"); final Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertTrue(resultMap.containsKey("EntryDate")); assertNull(resultMap.get("EntryDate")); } @Test public void readStringPropertyNullFalse() throws Exception { final String xml = "<EntryDate xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"false\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">1970-01-02T00:00:00</EntryDate>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EntryDate"); final Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertEquals(86400000L, ((Calendar) resultMap.get("EntryDate")).getTimeInMillis()); } @Test(expected = EntityProviderException.class) public void invalidSimplePropertyName() throws Exception { final String xml = "<Invalid xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Invalid>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test(expected = EntityProviderException.class) public void invalidNullAttribute() throws Exception { final String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"wrong\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test(expected = EntityProviderException.class) public void nullValueNotAllowed() throws Exception { final String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"true\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EdmFacets facets = mock(EdmFacets.class); when(facets.isNullable()).thenReturn(false); when(property.getFacets()).thenReturn(facets); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test @SuppressWarnings("unchecked") public void readComplexProperty() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"RefScenario.c_Location\">" + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); Map<String, Object> locationMap = (Map<String, Object>) resultMap.get("Location"); assertEquals("Germany", locationMap.get("Country")); Map<String, Object> cityMap = (Map<String, Object>) locationMap.get("City"); assertEquals("69124", cityMap.get("PostalCode")); assertEquals("Heidelberg", cityMap.get("CityName")); } @Test @SuppressWarnings("unchecked") public void readComplexPropertyWithLineBreaks() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"RefScenario.c_Location\">" + " " + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "\n" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>" + "\n \n "; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); Map<String, Object> locationMap = (Map<String, Object>) resultMap.get("Location"); assertEquals("Germany", locationMap.get("Country")); Map<String, Object> cityMap = (Map<String, Object>) locationMap.get("City"); assertEquals("69124", cityMap.get("PostalCode")); assertEquals("Heidelberg", cityMap.get("CityName")); } @Test(expected = EntityProviderException.class) public void readComplexPropertyInvalidMapping() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" type=\"RefScenario.c_Location\">" + "<Country>Germany</Country>" + "<City type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); try { Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false, createTypeMappings("Location", createTypeMappings("City", createTypeMappings("PostalCode", Integer.class)))); assertNotNull(resultMap); } catch (EntityProviderException e) { assertTrue(e.getCause() instanceof EdmSimpleTypeException); throw e; } } @Test @SuppressWarnings("unchecked") public void readComplexPropertyWithMappings() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"RefScenario.c_Location\">" + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + " <PostalCode>69124</PostalCode>" + " <CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); EdmProperty locationComplexProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); EdmProperty cityProperty = (EdmProperty) ((EdmComplexType) locationComplexProperty.getType()).getProperty("City"); EdmProperty postalCodeProperty = (EdmProperty) ((EdmComplexType) cityProperty.getType()).getProperty("PostalCode"); when(postalCodeProperty.getType()).thenReturn(EdmSimpleTypeKind.Int32.getEdmSimpleTypeInstance()); Map<String, Object> typeMappings = createTypeMappings("Location", createTypeMappings("City", createTypeMappings("CityName", String.class, "PostalCode", Long.class))); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, locationComplexProperty, false, typeMappings); Map<String, Object> locationMap = (Map<String, Object>) resultMap.get("Location"); assertEquals("Germany", locationMap.get("Country")); Map<String, Object> cityMap = (Map<String, Object>) locationMap.get("City"); assertEquals(Long.valueOf("69124"), cityMap.get("PostalCode")); assertEquals("Heidelberg", cityMap.get("CityName")); } @SuppressWarnings("unchecked") @Test public void readComplexPropertyWithNamespace() throws Exception { String xml = "<d:Location m:type=\"RefScenario.c_Location\" " + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\"" + " xmlns:d=\"" + Edm.NAMESPACE_D_2007_08 + "\">" + " <d:Country>Germany</d:Country>" + " <d:City m:type=\"RefScenario.c_City\">" + " <d:PostalCode>69124</d:PostalCode>" + " <d:CityName>Heidelberg</d:CityName>" + " </d:City>" + "</d:Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); Object prop = new XmlPropertyConsumer().readProperty(reader, property, false); Map<String, Object> resultMap = (Map<String, Object>) prop; Map<String, Object> locationMap = (Map<String, Object>) resultMap.get("Location"); assertEquals("Germany", locationMap.get("Country")); Map<String, Object> cityMap = (Map<String, Object>) locationMap.get("City"); assertEquals("69124", cityMap.get("PostalCode")); assertEquals("Heidelberg", cityMap.get("CityName")); } @Test(expected = EntityProviderException.class) public void readComplexPropertyWithInvalidChild() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"RefScenario.c_Location\">" + "<Invalid>Germany</Invalid>" + "<City m:type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test(expected = EntityProviderException.class) public void readComplexPropertyWithInvalidDeepChild() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"RefScenario.c_Location\">" + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + "<Invalid>69124</Invalid>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test(expected = EntityProviderException.class) public void readComplexPropertyWithInvalidName() throws Exception { String xml = "<Invalid xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"RefScenario.c_Location\">" + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Invalid>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test(expected = EntityProviderException.class) public void readComplexPropertyWithInvalidTypeAttribute() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" m:type=\"Invalid\">" + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test @SuppressWarnings("unchecked") public void readComplexPropertyWithoutTypeAttribute() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"" + " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<Country>Germany</Country>" + "<City m:type=\"RefScenario.c_City\">" + "<PostalCode>69124</PostalCode>" + "<CityName>Heidelberg</CityName>" + "</City>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); Map<String, Object> locationMap = (Map<String, Object>) resultMap.get("Location"); assertEquals("Germany", locationMap.get("Country")); Map<String, Object> cityMap = (Map<String, Object>) locationMap.get("City"); assertEquals("69124", cityMap.get("PostalCode")); assertEquals("Heidelberg", cityMap.get("CityName")); } @Test public void complexPropertyNull() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"true\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); final Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertTrue(resultMap.containsKey("Location")); assertNull(resultMap.get("Location")); } @Test(expected = EntityProviderException.class) public void complexPropertyNullValueNotAllowed() throws Exception { final String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"true\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); EdmFacets facets = mock(EdmFacets.class); when(facets.isNullable()).thenReturn(false); when(property.getFacets()).thenReturn(facets); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test(expected = EntityProviderException.class) public void complexPropertyNullWithContent() throws Exception { String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" m:null=\"true\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">" + "<City><PostalCode/><CityName/></City><Country>Germany</Country>" + "</Location>"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); new XmlPropertyConsumer().readProperty(reader, property, false); } @Test public void complexPropertyEmpty() throws Exception { final String xml = "<Location xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" />"; XMLStreamReader reader = createReaderForTest(xml, true); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location"); final Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false); assertNotNull(resultMap.get("Location")); @SuppressWarnings("unchecked") final Map<String, Object> innerMap = (Map<String, Object>) resultMap.get("Location"); assertTrue(innerMap.isEmpty()); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName) { JPAEntityTypeMapType jpaEntityTypeMap = searchJPAEntityTypeMapType(jpaEntityTypeName); if (jpaEntityTypeMap != null) { for (JPARelationship jpaRealtionship : jpaEntityTypeMap .getJPARelationships().getJPARelationship()) { if (jpaRealtionship.getName().equals(jpaRelationshipName)) { return jpaRealtionship.getValue(); } } } return null; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPARelationship() { assertEquals(RELATIONSHIP_NAME_EDM, objJPAEdmMappingModelServiceTest.mapJPARelationship(ENTITY_TYPE_NAME_JPA, RELATIONSHIP_NAME_JPA)); } @Test public void testMapJPARelationshipNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPARelationship(ENTITY_TYPE_NAME_JPA, RELATIONSHIP_NAME_JPA_WRONG)); }
Team { public List<Employee> getEmployees() { return employees; } Team(final int id, final String name); String getId(); String getName(); void setName(final String name); boolean isScrumTeam(); void setScrumTeam(final boolean isScrumTeam); List<Employee> getEmployees(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); }
@Test public void testEmployees() { Team team1 = new Team(1, VALUE_NAME); Employee employee1 = new Employee(1, null); Employee employee2 = new Employee(2, null); List<Employee> testList = Arrays.asList(employee1, employee2); team1.getEmployees().addAll(testList); for (Employee emp : testList) { emp.setTeam(team1); } assertEquals(testList, team1.getEmployees()); assertEquals(team1, employee1.getTeam()); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPAEmbeddableType(final String jpaEmbeddableTypeName) { JPAEmbeddableTypeMapType jpaEmbeddableType = searchJPAEmbeddableTypeMapType(jpaEmbeddableTypeName); if (jpaEmbeddableType != null) { return jpaEmbeddableType.getEDMComplexType(); } else { return null; } } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPAEmbeddableType() { assertEquals("SalesOrderLineItemKey", objJPAEdmMappingModelServiceTest.mapJPAEmbeddableType("SalesOrderItemKey")); } @Test public void testMapJPAEmbeddableTypeNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPAEmbeddableType(EMBEDDABLE_TYPE_NAME_JPA_WRONG)); }
JsonLinkConsumer { public String readLink(final JsonReader reader, final EdmEntitySet entitySet) throws EntityProviderException { try { String result; reader.beginObject(); String nextName = reader.nextName(); final boolean wrapped = FormatJson.D.equals(nextName); if (wrapped) { reader.beginObject(); nextName = reader.nextName(); } if (FormatJson.URI.equals(nextName) && reader.peek() == JsonToken.STRING) { result = reader.nextString(); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(FormatJson.D + " or " + FormatJson.URI).addContent(nextName)); } reader.endObject(); if (wrapped) { reader.endObject(); } reader.peek(); return result; } catch (final IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } catch (final IllegalStateException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } String readLink(final JsonReader reader, final EdmEntitySet entitySet); List<String> readLinks(final JsonReader reader, final EdmEntitySet entitySet); }
@Test public void linkWithD() throws Exception { final String link = "{\"d\":{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(link))); assertEquals("http: } @Test public void linkWithoutD() throws Exception { final String link = "{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(link))); assertEquals("http: } @Test(expected = EntityProviderException.class) public void invalidDoubleClosingBrackets() throws Exception { final String link = "{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(link))); new JsonLinkConsumer().readLink(reader, null); } @Test(expected = EntityProviderException.class) public void trailingGarbage() throws Exception { final String link = "{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(link))); new JsonLinkConsumer().readLink(reader, null); } @Test(expected = EntityProviderException.class) public void wrongTagName() throws Exception { final String link = "{\"URI\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(link))); new JsonLinkConsumer().readLink(reader, null); } @Test(expected = EntityProviderException.class) public void wrongValueType() throws Exception { final String link = "{\"uri\":false}"; JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(link))); new JsonLinkConsumer().readLink(reader, null); }
JsonLinkConsumer { public List<String> readLinks(final JsonReader reader, final EdmEntitySet entitySet) throws EntityProviderException { List<String> links = null; int openedObjects = 0; try { String nextName; if (reader.peek() == JsonToken.BEGIN_ARRAY) { nextName = FormatJson.RESULTS; } else { reader.beginObject(); openedObjects++; nextName = reader.nextName(); } if (FormatJson.D.equals(nextName)) { if (reader.peek() == JsonToken.BEGIN_ARRAY) { nextName = FormatJson.RESULTS; } else { reader.beginObject(); openedObjects++; nextName = reader.nextName(); } } FeedMetadataImpl feedMetadata = new FeedMetadataImpl(); if (FormatJson.COUNT.equals(nextName)) { JsonFeedConsumer.readInlineCount(reader, feedMetadata); nextName = reader.nextName(); } if (FormatJson.RESULTS.equals(nextName)) { links = readLinksArray(reader); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(FormatJson.RESULTS).addContent(nextName)); } if (reader.hasNext() && reader.peek() == JsonToken.NAME) { if (FormatJson.COUNT.equals(reader.nextName())) { JsonFeedConsumer.readInlineCount(reader, feedMetadata); } else { throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(FormatJson.COUNT).addContent(nextName)); } } for (; openedObjects > 0; openedObjects--) { reader.endObject(); } reader.peek(); } catch (final IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } catch (final IllegalStateException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } return links; } String readLink(final JsonReader reader, final EdmEntitySet entitySet); List<String> readLinks(final JsonReader reader, final EdmEntitySet entitySet); }
@Test public void linksWithD() throws Exception { final String links = "{\"d\":[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); assertEquals(Arrays.asList("http: } @Test public void linksWithoutD() throws Exception { final String links = "[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); assertEquals(Arrays.asList("http: } @Test public void linksEmpty() throws Exception { JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream("[]"))); assertEquals(Collections.emptyList(), new JsonLinkConsumer().readLinks(reader, null)); } @Test public void linksWithCount() throws Exception { final String links = "{\"__count\":\"5\",\"results\":[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); assertEquals(Arrays.asList("http: } @Test public void linksWithCountAtEnd() throws Exception { final String links = "{\"results\":[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); assertEquals(Arrays.asList("http: } @Test public void linksWithDAndResults() throws Exception { final String links = "{\"d\":{\"results\":[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); assertEquals(Arrays.asList("http: } @Test(expected = EntityProviderException.class) public void linksWrongResultsName() throws Exception { final String links = "{\"__results\":[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); } @Test(expected = EntityProviderException.class) public void linksWrongCountName() throws Exception { final String links = "{\"count\":\"5\",\"results\":[]}"; JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); } @Test(expected = EntityProviderException.class) public void linksWrongCountNameAtEnd() throws Exception { final String links = "{\"results\":[],\"count\":\"5\"}"; JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); } @Test(expected = EntityProviderException.class) public void linksWithoutResults() throws Exception { final String links = "{\"count\":\"42\"}"; JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); } @Test(expected = EntityProviderException.class) public void linksDoubleCount() throws Exception { final String links = "{\"__count\":\"5\",\"results\":[],\"__count\":\"42\"}"; JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); } @Test(expected = EntityProviderException.class) public void linksWrongUriName() throws Exception { final String links = "[{\"uri\":\"http: JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); } @Test(expected = EntityProviderException.class) public void linksWrongUriType() throws Exception { final String links = "[{\"uri\":false}]"; JsonReader reader = new JsonReader(new InputStreamReader(createContentAsStream(links))); new JsonLinkConsumer().readLinks(reader, null); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName) { JPAEmbeddableTypeMapType jpaEmbeddableType = searchJPAEmbeddableTypeMapType(jpaEmbeddableTypeName); if (jpaEmbeddableType != null && jpaEmbeddableType.getJPAAttributes() != null) { for (JPAAttribute jpaAttribute : jpaEmbeddableType .getJPAAttributes().getJPAAttribute()) { if (jpaAttribute.getName().equals(jpaAttributeName)) { return jpaAttribute.getValue(); } } } return null; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testMapJPAEmbeddableTypeAttribute() { assertEquals(EMBEDDABLE_ATTRIBUTE_NAME_EDM, objJPAEdmMappingModelServiceTest.mapJPAEmbeddableTypeAttribute(EMBEDDABLE_TYPE_NAME_JPA, EMBEDDABLE_ATTRIBUTE_NAME_JPA)); } @Test public void testMapJPAEmbeddableTypeAttributeNegative() { assertNull(objJPAEdmMappingModelServiceTest.mapJPAEmbeddableTypeAttribute(EMBEDDABLE_TYPE_NAME_JPA_WRONG, EMBEDDABLE_ATTRIBUTE_NAME_JPA)); }
XmlFeedConsumer { public ODataFeed readFeed(final XMLStreamReader reader, final EntityInfoAggregator eia, final EntityProviderReadProperties readProperties) throws EntityProviderException { try { reader.require(XMLStreamConstants.START_DOCUMENT, null, null); reader.nextTag(); reader.require(XMLStreamConstants.START_ELEMENT, Edm.NAMESPACE_ATOM_2005, FormatXml.ATOM_FEED); Map<String, String> foundPrefix2NamespaceUri = extractNamespacesFromTag(reader); foundPrefix2NamespaceUri.putAll(readProperties.getValidatedPrefixNamespaceUris()); checkAllMandatoryNamespacesAvailable(foundPrefix2NamespaceUri); EntityProviderReadProperties entryReadProperties = EntityProviderReadProperties.initFrom(readProperties).addValidatedPrefixes(foundPrefix2NamespaceUri).build(); return readFeedData(reader, eia, entryReadProperties); } catch (XMLStreamException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } ODataFeed readFeed(final XMLStreamReader reader, final EntityInfoAggregator eia, final EntityProviderReadProperties readProperties); }
@Test public void readEmployeesFeedWithInlineCountValid() throws Exception { String content = readFile("feed_employees_full.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false).build(); ODataFeed feed = xec.readFeed(entitySet, reqContent, consumerProperties); assertNotNull(feed); FeedMetadata feedMetadata = feed.getFeedMetadata(); assertNotNull(feedMetadata); int inlineCount = feedMetadata.getInlineCount(); assertNotNull(inlineCount); assertEquals(6, inlineCount); } @Test(expected = EntityProviderException.class) public void readEmployeesFeedWithInlineCountNegative() throws Exception { String content = readFile("feed_employees_full.xml").replace("<m:count>6</m:count>", "<m:count>-1</m:count>"); ; assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false).build(); try { xec.readFeed(entitySet, reqContent, consumerProperties); } catch (EntityProviderException e) { assertEquals(EntityProviderException.INLINECOUNT_INVALID, e.getMessageReference()); throw e; } Assert.fail("Exception expected"); } @Test(expected = EntityProviderException.class) public void readEmployeesFeedWithInlineCountLetters() throws Exception { String content = readFile("feed_employees_full.xml").replace("<m:count>6</m:count>", "<m:count>AAA</m:count>"); ; assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false).build(); try { xec.readFeed(entitySet, reqContent, consumerProperties); } catch (EntityProviderException e) { assertEquals(EntityProviderException.INLINECOUNT_INVALID, e.getMessageReference()); throw e; } Assert.fail("Exception expected"); }
XmlEntityConsumer { public ODataFeed readFeed(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties) throws EntityProviderException { XMLStreamReader reader = null; EntityProviderException cachedException = null; try { reader = createStaxReader(content); EntityInfoAggregator eia = EntityInfoAggregator.create(entitySet); XmlFeedConsumer xfc = new XmlFeedConsumer(); return xfc.readFeed(reader, eia, properties); } catch (EntityProviderException e) { cachedException = e; throw cachedException; } catch (XMLStreamException e) { cachedException = new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); throw cachedException; } finally { if (reader != null) { try { reader.close(); } catch (XMLStreamException e) { if (cachedException != null) { throw cachedException; } else { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } } } } XmlEntityConsumer(); ODataFeed readFeed(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); ODataEntry readEntry(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); Map<String, Object> readProperty(final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); String readLink(final EdmEntitySet entitySet, final Object content); List<String> readLinks(final EdmEntitySet entitySet, final Object content); }
@Test public void readDeltaLink() throws Exception { String content = readFile("feed_with_delta_link.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false).build(); ODataFeed feed = xec.readFeed(entitySet, reqContent, consumerProperties); assertNotNull(feed); FeedMetadata feedMetadata = feed.getFeedMetadata(); assertNotNull(feedMetadata); String deltaLink = feedMetadata.getDeltaLink(); assertNotNull(deltaLink); assertEquals("http: } @SuppressWarnings("unchecked") @Test public void testReadFeed() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); String content = readFile("feed_employees.xml"); InputStream contentAsStream = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataFeed feedResult = xec.readFeed(entitySet, contentAsStream, EntityProviderReadProperties.init().mergeSemantic(false).build()); FeedMetadata metadata = feedResult.getFeedMetadata(); assertNull(metadata.getInlineCount()); assertNull(metadata.getNextLink()); assertNull(metadata.getDeltaLink()); List<ODataEntry> entries = feedResult.getEntries(); assertEquals(6, entries.size()); ODataEntry firstEmployee = entries.get(0); Map<String, Object> properties = firstEmployee.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("Employees('1')/$value", properties.get("ImageUrl")); } @SuppressWarnings("unchecked") @Test public void testReadFeedWithInlineCountAndNextLink() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); String content = readFile("feed_employees_full.xml"); InputStream contentAsStream = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataFeed feedResult = xec.readFeed(entitySet, contentAsStream, EntityProviderReadProperties.init().mergeSemantic(false).build()); FeedMetadata metadata = feedResult.getFeedMetadata(); assertEquals(Integer.valueOf(6), metadata.getInlineCount()); assertEquals("http: assertNull(metadata.getDeltaLink()); List<ODataEntry> entries = feedResult.getEntries(); assertEquals(6, entries.size()); ODataEntry firstEmployee = entries.get(0); Map<String, Object> properties = firstEmployee.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("Employees('1')/$value", properties.get("ImageUrl")); }
XmlEntityConsumer { public ODataEntry readEntry(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties) throws EntityProviderException { XMLStreamReader reader = null; EntityProviderException cachedException = null; try { reader = createStaxReader(content); EntityInfoAggregator eia = EntityInfoAggregator.create(entitySet); return new XmlEntryConsumer().readEntry(reader, eia, properties); } catch (EntityProviderException e) { cachedException = e; throw cachedException; } catch (XMLStreamException e) { cachedException = new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); throw cachedException; } finally { if (reader != null) { try { reader.close(); } catch (XMLStreamException e) { if (cachedException != null) { throw cachedException; } else { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } } } } XmlEntityConsumer(); ODataFeed readFeed(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); ODataEntry readEntry(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); Map<String, Object> readProperty(final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); String readLink(final EdmEntitySet entitySet, final Object content); List<String> readLinks(final EdmEntitySet entitySet, final Object content); }
@Test public void readWithInlineContentAndCallback() throws Exception { String content = readFile("expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EmployeeCallback defaultCallback = new EmployeeCallback(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false) .callback(defaultCallback) .build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); assertNull(properties.get("nt_Employees")); final List<ODataEntry> employees = defaultCallback.employees; assertEquals(3, employees.size()); ODataEntry employeeNo2 = employees.get(1); Map<String, Object> employessNo2Props = employeeNo2.getProperties(); assertEquals("Frederic Fall", employessNo2Props.get("EmployeeName")); assertEquals("2", employessNo2Props.get("RoomId")); assertEquals(32, employessNo2Props.get("Age")); @SuppressWarnings("unchecked") Map<String, Object> emp2Location = (Map<String, Object>) employessNo2Props.get("Location"); @SuppressWarnings("unchecked") Map<String, Object> emp2City = (Map<String, Object>) emp2Location.get("City"); assertEquals("69190", emp2City.get("PostalCode")); assertEquals("Walldorf", emp2City.get("CityName")); } @Test public void readWithInlineContentAndCallback_DEFAULT() throws Exception { String content = readFile("expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); DefaultCallback defaultCallback = new DefaultCallback(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false) .callback(defaultCallback) .build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); assertNull(properties.get("nt_Employees")); ODataFeed employeesFeed = defaultCallback.asFeed("nt_Employees"); List<ODataEntry> employees = employeesFeed.getEntries(); assertEquals(3, employees.size()); ODataEntry employeeNo2 = employees.get(1); Map<String, Object> employessNo2Props = employeeNo2.getProperties(); assertEquals("Frederic Fall", employessNo2Props.get("EmployeeName")); assertEquals("2", employessNo2Props.get("RoomId")); assertEquals(32, employessNo2Props.get("Age")); @SuppressWarnings("unchecked") Map<String, Object> emp2Location = (Map<String, Object>) employessNo2Props.get("Location"); @SuppressWarnings("unchecked") Map<String, Object> emp2City = (Map<String, Object>) emp2Location.get("City"); assertEquals("69190", emp2City.get("PostalCode")); assertEquals("Walldorf", emp2City.get("CityName")); } @Test public void readInlineBuildingEntry() throws Exception { String content = readFile("expandedBuilding.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false).build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Room 1", properties.get("Name")); assertEquals((short) 1, properties.get("Seats")); assertEquals((short) 1, properties.get("Version")); ExpandSelectTreeNode expandTree = entry.getExpandSelectTree(); assertNotNull(expandTree); ODataEntry inlineBuilding = (ODataEntry) properties.get("nr_Building"); Map<String, Object> inlineBuildingProps = inlineBuilding.getProperties(); assertEquals("1", inlineBuildingProps.get("Id")); assertEquals("Building 1", inlineBuildingProps.get("Name")); assertNull(inlineBuildingProps.get("Image")); assertNull(inlineBuildingProps.get("nb_Rooms")); } @Test public void readWithInlineContent() throws Exception { String content = readFile("expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false).build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); ExpandSelectTreeNode expandTree = entry.getExpandSelectTree(); assertNotNull(expandTree); ODataFeed employeesFeed = (ODataFeed) properties.get("nt_Employees"); List<ODataEntry> employees = employeesFeed.getEntries(); assertEquals(3, employees.size()); ODataEntry employeeNo2 = employees.get(1); Map<String, Object> employessNo2Props = employeeNo2.getProperties(); assertEquals("Frederic Fall", employessNo2Props.get("EmployeeName")); assertEquals("2", employessNo2Props.get("RoomId")); assertEquals(32, employessNo2Props.get("Age")); @SuppressWarnings("unchecked") Map<String, Object> emp2Location = (Map<String, Object>) employessNo2Props.get("Location"); @SuppressWarnings("unchecked") Map<String, Object> emp2City = (Map<String, Object>) emp2Location.get("City"); assertEquals("69190", emp2City.get("PostalCode")); assertEquals("Walldorf", emp2City.get("CityName")); } @Test public void readWithDoubleInlineContent() throws Exception { String content = readFile("double_expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init().mergeSemantic(false).build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); ODataFeed employeesFeed = (ODataFeed) properties.get("nt_Employees"); List<ODataEntry> employees = employeesFeed.getEntries(); assertEquals(3, employees.size()); ODataEntry employeeNo2 = employees.get(1); Map<String, Object> employessNo2Props = employeeNo2.getProperties(); assertEquals("Frederic Fall", employessNo2Props.get("EmployeeName")); assertEquals("2", employessNo2Props.get("RoomId")); assertEquals(32, employessNo2Props.get("Age")); @SuppressWarnings("unchecked") Map<String, Object> emp2Location = (Map<String, Object>) employessNo2Props.get("Location"); @SuppressWarnings("unchecked") Map<String, Object> emp2City = (Map<String, Object>) emp2Location.get("City"); assertEquals("69190", emp2City.get("PostalCode")); assertEquals("Walldorf", emp2City.get("CityName")); ODataEntry inlinedTeam = (ODataEntry) employessNo2Props.get("ne_Team"); assertEquals("1", inlinedTeam.getProperties().get("Id")); assertEquals("Team 1", inlinedTeam.getProperties().get("Name")); } @Test @Ignore("Implementation doesn't support callback AND deep map") public void readWithDoubleInlineContentAndResendCallback() throws Exception { String content = readFile("double_expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); DefaultCallback callbackHandler = new DefaultCallback(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false) .callback(callbackHandler).build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); @SuppressWarnings("unchecked") List<ODataEntry> employees = (List<ODataEntry>) properties.get("nt_Employees"); assertEquals(3, employees.size()); ODataEntry employeeNo2 = employees.get(1); Map<String, Object> employessNo2Props = employeeNo2.getProperties(); assertEquals("Frederic Fall", employessNo2Props.get("EmployeeName")); assertEquals("2", employessNo2Props.get("RoomId")); assertEquals(32, employessNo2Props.get("Age")); @SuppressWarnings("unchecked") Map<String, Object> emp2Location = (Map<String, Object>) employessNo2Props.get("Location"); @SuppressWarnings("unchecked") Map<String, Object> emp2City = (Map<String, Object>) emp2Location.get("City"); assertEquals("69190", emp2City.get("PostalCode")); assertEquals("Walldorf", emp2City.get("CityName")); ODataEntry inlinedTeam = (ODataEntry) employessNo2Props.get("ne_Team"); assertEquals("1", inlinedTeam.getProperties().get("Id")); assertEquals("Team 1", inlinedTeam.getProperties().get("Name")); } @SuppressWarnings("unchecked") @Test public void readWithDoubleInlineContentAndCallback() throws Exception { String content = readFile("double_expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); DefaultCallback callbackHandler = new DefaultCallback(); EntityProviderReadProperties consumerProperties = EntityProviderReadProperties.init() .mergeSemantic(false) .callback(callbackHandler) .build(); ODataEntry entry = xec.readEntry(entitySet, reqContent, consumerProperties); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); ODataFeed employeesFeed = (ODataFeed) properties.get("nt_Employees"); assertNull(employeesFeed); employeesFeed = callbackHandler.asFeed("nt_Employees"); List<ODataEntry> employees = employeesFeed.getEntries(); assertEquals(3, employees.size()); ODataEntry employeeNo2 = employees.get(1); Map<String, Object> employessNo2Props = employeeNo2.getProperties(); assertEquals("Frederic Fall", employessNo2Props.get("EmployeeName")); assertEquals("2", employessNo2Props.get("RoomId")); assertEquals(32, employessNo2Props.get("Age")); Map<String, Object> emp2Location = (Map<String, Object>) employessNo2Props.get("Location"); Map<String, Object> emp2City = (Map<String, Object>) emp2Location.get("City"); assertEquals("69190", emp2City.get("PostalCode")); assertEquals("Walldorf", emp2City.get("CityName")); ODataEntry inlinedTeam = (ODataEntry) employessNo2Props.get("ne_Team"); assertNull(inlinedTeam); inlinedTeam = callbackHandler.asEntry("ne_Team"); assertEquals("1", inlinedTeam.getProperties().get("Id")); assertEquals("Team 1", inlinedTeam.getProperties().get("Name")); } @Test public void readWithInlineContentIgnored() throws Exception { String content = readFile("expanded_team.xml"); assertNotNull(content); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream reqContent = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry entry = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); assertEquals("Team 1", properties.get("Name")); assertEquals(Boolean.FALSE, properties.get("isScrumTeam")); } @Test public void readWithInlineContentEmployeeRoomEntry() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(EMPLOYEE_1_ROOM_XML); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry entry = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); ODataEntry room = (ODataEntry) properties.get("ne_Room"); Map<String, Object> roomProperties = room.getProperties(); assertEquals(4, roomProperties.size()); assertEquals("1", roomProperties.get("Id")); assertEquals("Room 1", roomProperties.get("Name")); assertEquals(Short.valueOf("1"), roomProperties.get("Seats")); assertEquals(Short.valueOf("1"), roomProperties.get("Version")); } @Test public void readWithInlineContentEmployeeRoomEntrySpecialXml() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(EMPLOYEE_1_ROOM_XML, true); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry entry = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); ODataEntry room = (ODataEntry) properties.get("ne_Room"); Map<String, Object> roomProperties = room.getProperties(); assertEquals(4, roomProperties.size()); assertEquals("1", roomProperties.get("Id")); assertEquals("Room 1", roomProperties.get("Name")); assertEquals(Short.valueOf("1"), roomProperties.get("Seats")); assertEquals(Short.valueOf("1"), roomProperties.get("Version")); } @Test public void readWithInlineContentEmployeeNullRoomEntry() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(EMPLOYEE_1_NULL_ROOM_XML); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry entry = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); ODataEntry room = (ODataEntry) properties.get("ne_Room"); assertNull(room); } @Test public void readWithInlineContentEmployeeNullRoomEntrySpecialXmlFormat() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream reqContent = createContentAsStream(EMPLOYEE_1_NULL_ROOM_XML, true); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry entry = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); ODataEntry room = (ODataEntry) properties.get("ne_Room"); assertNull(room); } @Test public void readWithInlineContentRoomNullEmployeesEntry() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(ROOM_1_NULL_EMPLOYEE_XML); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry entry = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(entry); Map<String, Object> properties = entry.getProperties(); assertEquals("1", properties.get("Id")); ODataEntry room = (ODataEntry) properties.get("ne_Employees"); assertNull(room); } @Test public void validationCaseInsensitiveXmlEncodingUtf8() throws Exception { String room = "<?xml version='1.0' encoding='uTf-8'?>" + "<entry xmlns=\"http: " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(room); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(result); assertEquals("1", result.getProperties().get("Id")); } @Test public void validationOfNamespacesSuccess() throws Exception { String roomWithValidNamespaces = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(roomWithValidNamespaces); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(result); } @Test public void validationOfDifferentNamespacesPrefixSuccess() throws Exception { String roomWithValidNamespaces = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " xmlns:meta=\"http: " xmlns:data=\"http: " xml:base=\"http: " meta:etag=\"W/&quot;1&quot;\">" + "" + " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <meta:properties>" + " <data:Id>1</data:Id>" + " <data:Seats>11</data:Seats>" + " <data:Name>Room 42</data:Name>" + " <data:Version>4711</data:Version>" + " </meta:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(roomWithValidNamespaces); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void validationOfUnknownPropertyOwnNamespaceSuccess() throws Exception { String roomWithValidNamespaces = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " xmlns:m=\"http: " xmlns:d=\"http: " xmlns:more=\"http: " xml:base=\"http: " m:etag=\"W/&quot;1&quot;\">" + "" + " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " <more:somePropertyToBeIgnored>ignore me</more:somePropertyToBeIgnored>" + " <d:Seats>11</d:Seats>" + " <d:Name>Room 42</d:Name>" + " <d:Version>4711</d:Version>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(roomWithValidNamespaces); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void validationOfUnknownPropertyDefaultNamespaceSuccess() throws Exception { String roomWithValidNamespaces = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <Id>1</Id>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(roomWithValidNamespaces); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(result); } @Test public void validationOfUnknownPropertyInlineNamespaceSuccess() throws Exception { String roomWithValidNamespaces = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " xmlns:m=\"http: " xmlns:d=\"http: " xml:base=\"http: " m:etag=\"W/&quot;1&quot;\">" + "" + " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " <more:somePropertyToBeIgnored xmlns:more=\"http: " <d:Seats>11</d:Seats>" + " <d:Name>Room 42</d:Name>" + " <d:Version>4711</d:Version>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(roomWithValidNamespaces); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void validationOfDoublePropertyDifferentNamespace() throws Exception { String room = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " xmlns:m=\"http: " xmlns:d=\"http: " xml:base=\"http: " m:etag=\"W/&quot;1&quot;\">" + "" + " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " <d:Seats>11</d:Seats>" + " <o:Name xmlns:o=\"http: " <d:Name>Room 42</d:Name>" + " <d:Version>4711</d:Version>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(room); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void validationOfDoublePropertyDifferentTagHierachy() throws Exception { String room = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " xmlns:m=\"http: " xmlns:d=\"http: " xml:base=\"http: " m:etag=\"W/&quot;1&quot;\">" + "" + " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " <d:Seats>11</d:Seats>" + " <SomeProp>" + " <Name>Room 42</Name>" + " </SomeProp>" + " <d:Name>Room 42</d:Name>" + " <d:Version>4711</d:Version>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(room); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void validationOfDoublePropertyDifferentTagHierachyD_Namespace() throws Exception { String room = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " xmlns:m=\"http: " xmlns:d=\"http: " xml:base=\"http: " m:etag=\"W/&quot;1&quot;\">" + "" + " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <d:Id>1</d:Id>" + " <d:Seats>11</d:Seats>" + " <SomeProp>" + " <d:Name>Room 42</d:Name>" + " </SomeProp>" + " <d:Name>Room 42</d:Name>" + " <d:Version>4711</d:Version>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(room); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void validationOfNamespacesMissingD_NamespaceAtKeyPropertyTag() throws Exception { String roomWithValidNamespaces = "<?xml version='1.0' encoding='UTF-8'?>" + "<entry xmlns=\"http: " <id>http: " <title type=\"text\">Room 1</title>" + " <updated>2013-01-11T13:50:50.541+01:00</updated>" + " <content type=\"application/xml\">" + " <m:properties>" + " <Id>1</Id>" + " <d:Seats>11</d:Seats>" + " <d:Name>Room 42</d:Name>" + " <d:Version>4711</d:Version>" + " </m:properties>" + " </content>" + "</entry>"; EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(roomWithValidNamespaces); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); assertNotNull(result); } @Test public void readEntryAtomProperties() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream contentBody = createContentAsStream(EMPLOYEE_1_XML); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(true).build()); EntryMetadata metadata = result.getMetadata(); assertEquals("http: assertEquals("W/\"1\"", metadata.getEtag()); List<String> associationUris = metadata.getAssociationUris("ne_Room"); assertEquals(1, associationUris.size()); assertEquals("Employees('1')/ne_Room", associationUris.get(0)); associationUris = metadata.getAssociationUris("ne_Manager"); assertEquals(1, associationUris.size()); assertEquals("Employees('1')/ne_Manager", associationUris.get(0)); associationUris = metadata.getAssociationUris("ne_Team"); assertEquals(1, associationUris.size()); assertEquals("Employees('1')/ne_Team", associationUris.get(0)); assertEquals(null, metadata.getUri()); MediaMetadata mm = result.getMediaMetadata(); assertEquals("Employees('1')/$value", mm.getSourceLink()); assertEquals("mmEtag", mm.getEtag()); assertEquals("application/octet-stream", mm.getContentType()); assertEquals("Employees('1')/$value", mm.getEditLink()); Map<String, Object> data = result.getProperties(); assertEquals(9, data.size()); assertEquals("1", data.get("EmployeeId")); assertEquals("Walter Winter", data.get("EmployeeName")); assertEquals("1", data.get("ManagerId")); assertEquals("1", data.get("RoomId")); assertEquals("1", data.get("TeamId")); } @Test public void readEntryLinks() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream contentBody = createContentAsStream(EMPLOYEE_1_XML); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(true).build()); List<String> associationUris = result.getMetadata().getAssociationUris("ne_Room"); assertEquals(1, associationUris.size()); assertEquals("Employees('1')/ne_Room", associationUris.get(0)); associationUris = result.getMetadata().getAssociationUris("ne_Manager"); assertEquals(1, associationUris.size()); assertEquals("Employees('1')/ne_Manager", associationUris.get(0)); associationUris = result.getMetadata().getAssociationUris("ne_Team"); assertEquals(1, associationUris.size()); assertEquals("Employees('1')/ne_Team", associationUris.get(0)); } @SuppressWarnings("unchecked") @Test public void testReadEntry() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream contentBody = createContentAsStream(EMPLOYEE_1_XML); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(false).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @SuppressWarnings("unchecked") @Test public void testReadEntryWithLargeProperty() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); String newName = StringHelper.generateData(81920); InputStream contentBody = createContentAsStream(EMPLOYEE_1_XML.replaceAll("Walter Winter", newName)); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(false).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals(newName, properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @Test @SuppressWarnings("unchecked") public void testReadEntryMissingKeyProperty() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream contentBody = createContentAsStream(EMPLOYEE_1_XML.replace("<d:EmployeeId>1</d:EmployeeId>", "")); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(false).build()); Map<String, Object> properties = result.getProperties(); assertEquals(8, properties.size()); assertNull(properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @Test public void readEntryNullProperty() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); final String content = EMPLOYEE_1_XML.replace("<d:EntryDate>1999-01-01T00:00:00</d:EntryDate>", "<d:EntryDate m:null='true' />"); InputStream contentBody = createContentAsStream(content); final ODataEntry result = new XmlEntityConsumer().readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(true).build()); final Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertTrue(properties.containsKey("EntryDate")); assertNull(properties.get("EntryDate")); } @Test(expected = EntityProviderException.class) public void readEntryTooManyValues() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); String content = EMPLOYEE_1_XML.replace("<d:Age>52</d:Age>", "<d:Age>52</d:Age><d:SomeUnknownTag>SomeUnknownValue</d:SomeUnknownTag>"); InputStream contentBody = createContentAsStream(content); try { new XmlEntityConsumer().readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(false).build()); } catch (EntityProviderException e) { assertEquals(EntityProviderException.INVALID_PROPERTY.getKey(), e.getMessageReference().getKey()); assertEquals("SomeUnknownTag", e.getMessageReference().getContent().get(0)); throw e; } } @SuppressWarnings("unchecked") @Test public void testReadEntryWithMerge() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); String content = EMPLOYEE_1_XML.replace("<d:Age>52</d:Age>", ""); InputStream contentBody = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(true).build()); Map<String, Object> properties = result.getProperties(); assertEquals(8, properties.size()); assertNull(properties.get("Age")); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @SuppressWarnings("unchecked") @Test public void testReadEntryWithMergeAndMappings() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); String content = EMPLOYEE_1_XML.replace("<d:Age>52</d:Age>", ""); InputStream contentBody = createContentAsStream(content); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(true).addTypeMappings( createTypeMappings("Age", Long.class, "EntryDate", Date.class)) .build()); Map<String, Object> properties = result.getProperties(); assertEquals(8, properties.size()); assertNull(properties.get("Age")); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(new Date(915148800000l), properties.get("EntryDate")); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @SuppressWarnings("unchecked") @Test public void testReadEntryRequest() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = createContentAsStream(EMPLOYEE_1_XML); ODataEntry result = xec.readEntry(entitySet, content, EntityProviderReadProperties.init().mergeSemantic(true).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @SuppressWarnings("unchecked") @Test public void testReadEntryRequestNullMapping() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = createContentAsStream(EMPLOYEE_1_XML); ODataEntry result = xec.readEntry(entitySet, content, EntityProviderReadProperties.init().mergeSemantic(true).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @SuppressWarnings("unchecked") @Test public void testReadEntryRequestEmptyMapping() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = createContentAsStream(EMPLOYEE_1_XML); ODataEntry result = xec.readEntry(entitySet, content, EntityProviderReadProperties.init().build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Integer.valueOf(52), properties.get("Age")); Calendar entryDate = (Calendar) properties.get("EntryDate"); assertEquals(915148800000L, entryDate.getTimeInMillis()); assertEquals(TimeZone.getTimeZone("GMT"), entryDate.getTimeZone()); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @Test(expected = EntityProviderException.class) public void testReadEntryRequestInvalidMapping() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = createContentAsStream(EMPLOYEE_1_XML); ODataEntry result = xec.readEntry(entitySet, content, EntityProviderReadProperties.init().mergeSemantic(true).addTypeMappings(createTypeMappings("EmployeeName", Integer.class)).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); } @Test public void testReadEntryRequestObjectMapping() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = createContentAsStream(EMPLOYEE_1_XML); ODataEntry result = xec.readEntry(entitySet, content, EntityProviderReadProperties.init().mergeSemantic(true).addTypeMappings(createTypeMappings("EmployeeName", Object.class)).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); Object o = properties.get("EmployeeName"); assertTrue(o instanceof String); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); } @SuppressWarnings("unchecked") @Test public void testReadEntryRequestWithMapping() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = createContentAsStream(EMPLOYEE_1_XML); ODataEntry result = xec.readEntry(entitySet, content, EntityProviderReadProperties.init().mergeSemantic(true).addTypeMappings( createTypeMappings("Age", Short.class, "Heidelberg", String.class, "EntryDate", Long.class)).build()); Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); assertEquals("1", properties.get("EmployeeId")); assertEquals("Walter Winter", properties.get("EmployeeName")); assertEquals("1", properties.get("ManagerId")); assertEquals("1", properties.get("RoomId")); assertEquals("1", properties.get("TeamId")); Map<String, Object> location = (Map<String, Object>) properties.get("Location"); assertEquals(2, location.size()); assertEquals("Germany", location.get("Country")); Map<String, Object> city = (Map<String, Object>) location.get("City"); assertEquals(2, city.size()); assertEquals("69124", city.get("PostalCode")); assertEquals("Heidelberg", city.get("CityName")); assertEquals(Short.valueOf("52"), properties.get("Age")); assertEquals(Long.valueOf(915148800000L), properties.get("EntryDate")); assertEquals("/SAP/PUBLIC/BC/NWDEMO_MODEL/IMAGES/male_1_WinterW.jpg", properties.get("ImageUrl")); } @Test public void readCustomizableFeedMappings() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"); InputStream reqContent = createContentAsStream(PHOTO_XML); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(false).build()); EntryMetadata entryMetadata = result.getMetadata(); assertEquals("http: Map<String, Object> data = result.getProperties(); assertEquals("Образ", data.get("Содержание")); assertEquals("Photo1", data.get("Name")); assertEquals("image/png", data.get("Type")); assertNull(data.get("ignore")); } @Test public void readCustomizableFeedMappingsWithMergeSemantic() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"); InputStream reqContent = createContentAsStream(PHOTO_XML); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); EntryMetadata entryMetadata = result.getMetadata(); assertEquals("http: Map<String, Object> data = result.getProperties(); assertEquals("Photo1", data.get("Name")); assertEquals("image/png", data.get("Type")); assertNull(data.get("Содержание")); assertNull(data.get("ignore")); } @Test public void readIncompleteEntry() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(ROOM_1_XML); final ODataEntry result = new XmlEntityConsumer().readEntry(entitySet, reqContent, EntityProviderReadProperties.init().build()); final EntryMetadata entryMetadata = result.getMetadata(); assertEquals("http: assertEquals("W/\"1\"", entryMetadata.getEtag()); assertNull(entryMetadata.getUri()); final MediaMetadata mediaMetadata = result.getMediaMetadata(); assertEquals(HttpContentType.APPLICATION_XML, mediaMetadata.getContentType()); assertNull(mediaMetadata.getSourceLink()); assertNull(mediaMetadata.getEditLink()); assertNull(mediaMetadata.getEtag()); final Map<String, Object> properties = result.getProperties(); assertEquals(1, properties.size()); assertEquals("1", properties.get("Id")); assertFalse(properties.containsKey("Seats")); } @Test public void readIncompleteEntryMerge() throws Exception { XmlEntityConsumer xec = new XmlEntityConsumer(); EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream reqContent = createContentAsStream(ROOM_1_XML); ODataEntry result = xec.readEntry(entitySet, reqContent, EntityProviderReadProperties.init().mergeSemantic(true).build()); EntryMetadata entryMetadata = result.getMetadata(); assertEquals("http: assertEquals("W/\"1\"", entryMetadata.getEtag()); assertEquals(null, entryMetadata.getUri()); MediaMetadata mediaMetadata = result.getMediaMetadata(); assertEquals("application/xml", mediaMetadata.getContentType()); assertEquals(null, mediaMetadata.getSourceLink()); assertEquals(null, mediaMetadata.getEditLink()); assertEquals(null, mediaMetadata.getEtag()); Map<String, Object> properties = result.getProperties(); assertEquals(1, properties.size()); assertEquals("1", properties.get("Id")); } @Test public void testReadSkipTag() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream contentBody = createContentAsStream(EMPLOYEE_1_XML .replace("<title type=\"text\">Walter Winter</title>", "<title type=\"text\"><title>Walter Winter</title></title>")); XmlEntityConsumer xec = new XmlEntityConsumer(); ODataEntry result = xec.readEntry(entitySet, contentBody, EntityProviderReadProperties.init().mergeSemantic(false).build()); String id = result.getMetadata().getId(); assertEquals("http: Map<String, Object> properties = result.getProperties(); assertEquals(9, properties.size()); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName) { JPAEntityTypeMapType type = searchJPAEntityTypeMapType(jpaEntityTypeName); if (type != null) { return type.isExclude(); } return false; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testCheckExclusionOfJPAEntityType() { assertTrue(!objJPAEdmMappingModelServiceTest.checkExclusionOfJPAEntityType(ENTITY_TYPE_NAME_JPA)); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName) { JPAEntityTypeMapType type = searchJPAEntityTypeMapType(jpaEntityTypeName); if (type != null && type.getJPAAttributes() != null) { for (JPAAttribute jpaAttribute : type.getJPAAttributes() .getJPAAttribute()) { if (jpaAttribute.getName().equals(jpaAttributeName)) { return jpaAttribute.isExclude(); } } } return false; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testCheckExclusionOfJPAAttributeType() { assertTrue(!objJPAEdmMappingModelServiceTest.checkExclusionOfJPAAttributeType(ENTITY_TYPE_NAME_JPA, ATTRIBUTE_NAME_JPA)); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName) { JPAEmbeddableTypeMapType type = searchJPAEmbeddableTypeMapType(jpaEmbeddableTypeName); if (type != null) { return type.isExclude(); } return false; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testCheckExclusionOfJPAEmbeddableType() { assertTrue(!objJPAEdmMappingModelServiceTest.checkExclusionOfJPAEmbeddableType(EMBEDDABLE_TYPE_2_NAME_JPA)); }
JPAEdmMappingModelService implements JPAEdmMappingModelAccess { @Override public boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName) { JPAEmbeddableTypeMapType type = searchJPAEmbeddableTypeMapType(jpaEmbeddableTypeName); if (type != null && type.getJPAAttributes() != null) { for (JPAAttribute jpaAttribute : type.getJPAAttributes() .getJPAAttribute()) { if (jpaAttribute.getName().equals(jpaAttributeName)) { return jpaAttribute.isExclude(); } } } return false; } JPAEdmMappingModelService(final ODataJPAContext ctx); @Override void loadMappingModel(); @Override boolean isMappingModelExists(); @Override JPAEdmMappingModel getJPAEdmMappingModel(); @Override String mapJPAPersistenceUnit(final String persistenceUnitName); @Override String mapJPAEntityType(final String jpaEntityTypeName); @Override String mapJPAEntitySet(final String jpaEntityTypeName); @Override String mapJPAAttribute(final String jpaEntityTypeName, final String jpaAttributeName); @Override String mapJPARelationship(final String jpaEntityTypeName, final String jpaRelationshipName); @Override String mapJPAEmbeddableType(final String jpaEmbeddableTypeName); @Override String mapJPAEmbeddableTypeAttribute(final String jpaEmbeddableTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEntityType(final String jpaEntityTypeName); @Override boolean checkExclusionOfJPAAttributeType(final String jpaEntityTypeName, final String jpaAttributeName); @Override boolean checkExclusionOfJPAEmbeddableType( final String jpaEmbeddableTypeName); @Override boolean checkExclusionOfJPAEmbeddableAttributeType( final String jpaEmbeddableTypeName, final String jpaAttributeName); }
@Test public void testCheckExclusionOfJPAEmbeddableAttributeType() { assertTrue(!objJPAEdmMappingModelServiceTest.checkExclusionOfJPAEmbeddableAttributeType(EMBEDDABLE_TYPE_NAME_JPA, EMBEDDABLE_ATTRIBUTE_NAME_JPA)); }
XmlEntityConsumer { public Map<String, Object> readProperty(final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties) throws EntityProviderException { XMLStreamReader reader = null; EntityProviderException cachedException = null; XmlPropertyConsumer xec = new XmlPropertyConsumer(); try { reader = createStaxReader(content); Map<String, Object> result = xec.readProperty(reader, edmProperty, properties.getMergeSemantic(), properties.getTypeMappings()); return result; } catch (XMLStreamException e) { cachedException = new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); throw cachedException; } finally { if (reader != null) { try { reader.close(); } catch (XMLStreamException e) { if (cachedException != null) { throw cachedException; } else { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } } } } XmlEntityConsumer(); ODataFeed readFeed(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); ODataEntry readEntry(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); Map<String, Object> readProperty(final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); String readLink(final EdmEntitySet entitySet, final Object content); List<String> readLinks(final EdmEntitySet entitySet, final Object content); }
@Test public void readProperty() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Age>"; InputStream content = createContentAsStream(xml); Map<String, Object> value = new XmlEntityConsumer().readProperty(property, content, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertEquals(Integer.valueOf(67), value.get("Age")); } @Test public void testReadIntegerPropertyAsLong() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">42</Age>"; InputStream content = createContentAsStream(xml); Map<String, Object> value = new XmlEntityConsumer().readProperty(property, content, EntityProviderReadProperties.init().mergeSemantic(true).addTypeMappings(createTypeMappings("Age", Long.class)).build()); assertEquals(Long.valueOf(42), value.get("Age")); }
XmlEntityConsumer { public Object readPropertyValue(final EdmProperty edmProperty, final InputStream content) throws EntityProviderException { return readPropertyValue(edmProperty, content, null); } XmlEntityConsumer(); ODataFeed readFeed(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); ODataEntry readEntry(final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); Map<String, Object> readProperty(final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content); Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); String readLink(final EdmEntitySet entitySet, final Object content); List<String> readLinks(final EdmEntitySet entitySet, final Object content); }
@Test public void readStringPropertyValue() throws Exception { String xml = "<EmployeeName xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">Max Mustermann</EmployeeName>"; InputStream content = createContentAsStream(xml); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EmployeeName"); Object result = new XmlEntityConsumer().readPropertyValue(property, content, String.class); assertEquals("Max Mustermann", result); } @Test public void readLargeStringPropertyValue() throws Exception { String name = StringHelper.generateData(77777); String xml = "<EmployeeName xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">" + name + "</EmployeeName>"; InputStream content = createContentAsStream(xml); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EmployeeName"); Object result = new XmlEntityConsumer().readPropertyValue(property, content, String.class); assertEquals(name, result); } @Test(expected = EntityProviderException.class) public void readStringPropertyValueWithInvalidMapping() throws Exception { String xml = "<EmployeeName xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">Max Mustermann</EmployeeName>"; InputStream content = createContentAsStream(xml); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EmployeeName"); new XmlEntityConsumer().readPropertyValue(property, content, Integer.class); } @Test(expected = EntityProviderException.class) public void readPropertyWrongNamespace() throws Exception { String xml = "<Age xmlns=\"" + Edm.NAMESPACE_M_2007_08 + "\">1</Age>"; InputStream content = createContentAsStream(xml); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); new XmlEntityConsumer().readPropertyValue(property, content, Integer.class); } @Test(expected = EntityProviderException.class) public void readPropertyWrongClosingNamespace() throws Exception { String xml = "<d:Age xmlns:d=\"" + Edm.NAMESPACE_D_2007_08 + "\" xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">1</m:Age>"; InputStream content = createContentAsStream(xml); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); new XmlEntityConsumer().readPropertyValue(property, content, Integer.class); }
XmlLinkConsumer { public String readLink(final XMLStreamReader reader, final EdmEntitySet entitySet) throws EntityProviderException { try { reader.next(); return readLink(reader); } catch (final XMLStreamException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } String readLink(final XMLStreamReader reader, final EdmEntitySet entitySet); List<String> readLinks(final XMLStreamReader reader, final EdmEntitySet entitySet); }
@Test public void readLink() throws Exception { XMLStreamReader reader = createReaderForTest(SINGLE_LINK, true); final String link = new XmlLinkConsumer().readLink(reader, null); assertEquals(SERVICE_ROOT + "Employees('6')", link); } @Test(expected = EntityProviderException.class) public void wrongNamespace() throws Exception { new XmlLinkConsumer().readLink(createReaderForTest(SINGLE_LINK.replace(Edm.NAMESPACE_D_2007_08, Edm.NAMESPACE_M_2007_08), true), null); } @Test(expected = EntityProviderException.class) public void xmlContent() throws Exception { final String xml = "<uri xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\"><uri>X</uri></uri>"; new XmlLinkConsumer().readLink(createReaderForTest(xml, true), null); }
ODataJPAEdmProvider extends EdmProvider { public ODataJPAContext getODataJPAContext() { return oDataJPAContext; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetODataJPAContext() { String pUnitName = edmProvider.getODataJPAContext() .getPersistenceUnitName(); assertEquals("salesorderprocessing", pUnitName); }
Room { public String getId() { return Integer.toString(id); } Room(final int id, final String name); String getId(); String getName(); void setName(final String name); void setSeats(final int seats); int getSeats(); void setVersion(final int version); int getVersion(); void setBuilding(final Building building); Building getBuilding(); List<Employee> getEmployees(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); }
@Test public void testId() { Room room1 = new Room(1, NAME); assertNotNull(room1.getId()); }
XmlLinkConsumer { public List<String> readLinks(final XMLStreamReader reader, final EdmEntitySet entitySet) throws EntityProviderException { try { List<String> links = new ArrayList<String>(); reader.next(); reader.require(XMLStreamConstants.START_ELEMENT, Edm.NAMESPACE_D_2007_08, FormatXml.D_LINKS); reader.nextTag(); while (!reader.isEndElement()) { if (reader.getLocalName().equals(FormatXml.M_COUNT)) { readTag(reader, Edm.NAMESPACE_M_2007_08, FormatXml.M_COUNT); } else { final String link = readLink(reader); links.add(link); } reader.nextTag(); } reader.require(XMLStreamConstants.END_ELEMENT, Edm.NAMESPACE_D_2007_08, FormatXml.D_LINKS); return links; } catch (final XMLStreamException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } String readLink(final XMLStreamReader reader, final EdmEntitySet entitySet); List<String> readLinks(final XMLStreamReader reader, final EdmEntitySet entitySet); }
@Test public void readLinks() throws Exception { XMLStreamReader reader = createReaderForTest(MANAGER_1_EMPLOYEES, true); final List<String> links = new XmlLinkConsumer().readLinks(reader, null); assertEquals(4, links.size()); assertEquals(SERVICE_ROOT + "Employees('1')", links.get(0)); assertEquals(SERVICE_ROOT + "Employees('2')", links.get(1)); assertEquals(SERVICE_ROOT + "Employees('3')", links.get(2)); assertEquals(SERVICE_ROOT + "Employees('6')", links.get(3)); } @Test public void readEmptyList() throws Exception { final String xml = "<?xml version=\"1.1\" encoding=\"UTF-8\"?>" + "<links xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\" />"; final List<String> links = new XmlLinkConsumer().readLinks(createReaderForTest(xml, true), null); assertNotNull(links); assertTrue(links.isEmpty()); } @Test public void withInlineCount() throws Exception { final String xml = "<links xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">" + "<m:count xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\">4</m:count>" + "<uri>" + SERVICE_ROOT + "Employees('5')</uri>" + "</links>"; final List<String> links = new XmlLinkConsumer().readLinks(createReaderForTest(xml, true), null); assertEquals(1, links.size()); }
JsonFeedConsumer { private void readFeed() throws IOException, EdmException, EntityProviderException { if (reader.peek() == JsonToken.BEGIN_ARRAY) { readArrayContent(); } else { reader.beginObject(); final String nextName = reader.nextName(); if (FormatJson.D.equals(nextName)) { if (reader.peek() == JsonToken.BEGIN_ARRAY) { readArrayContent(); } else { reader.beginObject(); readFeedContent(); reader.endObject(); } } else { handleName(nextName); readFeedContent(); } reader.endObject(); } } JsonFeedConsumer(final JsonReader reader, final EntityInfoAggregator eia, final EntityProviderReadProperties readProperties); ODataFeed readFeedStandalone(); }
@Test(expected = EntityProviderException.class) public void invalidDoubleClosingBrackets() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); String content = "{\"d\":{\"results\":[]}}}"; InputStream contentBody = createContentAsStream(content); JsonEntityConsumer xec = new JsonEntityConsumer(); xec.readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test public void emptyFeed() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); String content = "{\"d\":{\"results\":[]}}"; InputStream contentBody = createContentAsStream(content); JsonEntityConsumer xec = new JsonEntityConsumer(); ODataFeed feed = xec.readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); assertNotNull(feed); List<ODataEntry> entries = feed.getEntries(); assertNotNull(entries); assertEquals(0, entries.size()); FeedMetadata feedMetadata = feed.getFeedMetadata(); assertNotNull(feedMetadata); assertNull(feedMetadata.getInlineCount()); assertNull(feedMetadata.getNextLink()); } @Test public void emptyFeedWithoutDAndResults() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("[]"); final ODataFeed feed = new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); assertNotNull(feed); final List<ODataEntry> entries = feed.getEntries(); assertNotNull(entries); assertEquals(0, entries.size()); final FeedMetadata feedMetadata = feed.getFeedMetadata(); assertNotNull(feedMetadata); assertNull(feedMetadata.getInlineCount()); assertNull(feedMetadata.getNextLink()); } @Test public void emptyFeedWithoutResults() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":[]}"); final ODataFeed feed = new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); assertNotNull(feed); final List<ODataEntry> entries = feed.getEntries(); assertNotNull(entries); assertEquals(0, entries.size()); final FeedMetadata feedMetadata = feed.getFeedMetadata(); assertNotNull(feedMetadata); assertNull(feedMetadata.getInlineCount()); assertNull(feedMetadata.getNextLink()); } @Test(expected = EntityProviderException.class) public void resultsNotPresent() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void countButNoResults() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"__count\":\"1\"}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void wrongCountType() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"__count\":1,\"results\":[]}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void wrongCountContent() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"__count\":\"one\",\"results\":[]}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void negativeCount() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"__count\":\"-1\",\"results\":[]}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void wrongNextType() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"results\":[],\"__next\":false}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void wrongTag() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"__results\":null}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void doubleCount() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"__count\":\"1\",\"__count\":\"2\",\"results\":[]}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void doubleNext() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"results\":[],\"__next\":\"a\",\"__next\":\"b\"}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void doubleResults() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"results\":{\"results\":[]}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test(expected = EntityProviderException.class) public void doubleD() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); InputStream contentBody = createContentAsStream("{\"d\":{\"d\":[]}}"); new JsonEntityConsumer().readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); } @Test public void feedWithInlineCountAndNextAndDelta() throws Exception { EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); String content = "{\"d\":{\"__count\":\"3\",\"results\":[{\"__metadata\":{\"id\":\"http: assertNotNull(content); InputStream contentBody = createContentAsStream(content); JsonEntityConsumer xec = new JsonEntityConsumer(); ODataFeed feed = xec.readFeed(entitySet, contentBody, DEFAULT_PROPERTIES); assertNotNull(feed); List<ODataEntry> entries = feed.getEntries(); assertNotNull(entries); assertEquals(1, entries.size()); FeedMetadata feedMetadata = feed.getFeedMetadata(); assertNotNull(feedMetadata); assertEquals(Integer.valueOf(3), feedMetadata.getInlineCount()); assertEquals("Rooms?$skiptoken=98&$inlinecount=allpages", feedMetadata.getNextLink()); assertEquals("deltalink", feedMetadata.getDeltaLink()); }
ODataJPAEdmProvider extends EdmProvider { @Override public EntityContainerInfo getEntityContainerInfo(final String name) throws ODataException { if (entityContainerInfos.containsKey(name)) { return entityContainerInfos.get(name); } else { if (schemas == null) { getSchemas(); } List<EntityContainer> containerList = schemas.get(0).getEntityContainers(); if (containerList == null) { return null; } for (EntityContainer container : containerList) { if (name == null && container.isDefaultEntityContainer()) { entityContainerInfos.put(name, container); return container; } else if (name != null && name.equals(container.getName())) { return container; } } } return null; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetEntityContainerInfo() { String entityContainerName = null; EntityContainerInfo entityContainer = null; try { entityContainer = edmProvider .getEntityContainerInfo("salesorderprocessingContainer"); entityContainerName = entityContainer.getName(); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertEquals("salesorderprocessingContainer", entityContainerName); assertNotNull(entityContainer); } @Test public void testDefaultGetEntityContainerInfo() { String entityContainerName = null; EntityContainerInfo entityContainer = null; try { entityContainer = edmProvider .getEntityContainerInfo(null); entityContainerName = entityContainer.getName(); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertEquals("salesorderprocessingContainer", entityContainerName); assertNotNull(entityContainer); } @Test public void testGetEntityContainerInfoWithBuffer() { HashMap<String, EntityContainerInfo> entityContainerInfos = new HashMap<String, EntityContainerInfo>(); EntityContainerInfo entityContainer = new EntityContainerInfo(); entityContainer.setName("salesorderprocessingContainer"); entityContainerInfos.put("salesorderprocessingContainer", entityContainer); ODataJPAEdmProvider jpaEdmProv = new ODataJPAEdmProvider(); Class<?> claz = jpaEdmProv.getClass(); try { Field f = claz.getDeclaredField("entityContainerInfos"); f.setAccessible(true); f.set(jpaEdmProv, entityContainerInfos); assertEquals( entityContainer, jpaEdmProv .getEntityContainerInfo("salesorderprocessingContainer")); jpaEdmProv.getEntityContainerInfo("abc"); } catch (ODataJPAModelException e) { assertTrue(true); } catch (NoSuchFieldException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (SecurityException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalArgumentException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalAccessException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } }
JsonPropertyConsumer { protected Object readPropertyValue(final JsonReader reader, final EntityPropertyInfo entityPropertyInfo, final Object typeMapping) throws EntityProviderException { try { return entityPropertyInfo.isComplex() ? readComplexProperty(reader, (EntityComplexPropertyInfo) entityPropertyInfo, typeMapping) : readSimpleProperty(reader, entityPropertyInfo, typeMapping); } catch (final EdmException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } catch (final IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } Map<String, Object> readPropertyStandalone(final JsonReader reader, final EdmProperty property, final EntityProviderReadProperties readProperties); }
@Test public void simplePropertyOnOpenReader() throws Exception { String simplePropertyJson = "{\"Name\":\"Team 1\"}"; JsonReader reader = prepareReader(simplePropertyJson); EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams").getEntityType().getProperty("Name"); EntityPropertyInfo entityPropertyInfo = EntityInfoAggregator.create(edmProperty); reader.beginObject(); reader.nextName(); JsonPropertyConsumer jpc = new JsonPropertyConsumer(); Object value = jpc.readPropertyValue(reader, entityPropertyInfo, null); assertEquals("Team 1", value); } @Test public void complexPropertyOnOpenReader() throws Exception { final String complexPropertyJson = "{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}"; JsonReader reader = prepareReader(complexPropertyJson); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); EntityComplexPropertyInfo entityPropertyInfo = (EntityComplexPropertyInfo) EntityInfoAggregator.create(property); JsonPropertyConsumer jpc = new JsonPropertyConsumer(); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) jpc.readPropertyValue(reader, entityPropertyInfo, null); assertEquals(2, result.size()); assertEquals("Heidelberg", result.get("CityName")); assertEquals("69124", result.get("PostalCode")); } @Test public void complexPropertyOnOpenReaderWithNoMetadata() throws Exception { final String complexPropertyJson = "{\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}"; JsonReader reader = prepareReader(complexPropertyJson); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); EntityComplexPropertyInfo entityPropertyInfo = (EntityComplexPropertyInfo) EntityInfoAggregator.create(property); JsonPropertyConsumer jpc = new JsonPropertyConsumer(); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) jpc.readPropertyValue(reader, entityPropertyInfo, null); assertEquals(2, result.size()); assertEquals("Heidelberg", result.get("CityName")); assertEquals("69124", result.get("PostalCode")); } @Test public void deepComplexPropertyOnOpenReader() throws Exception { final String complexPropertyJson = "{\"__metadata\":{\"type\":\"RefScenario.c_Location\"},\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"},\"Country\":\"Germany\"}"; JsonReader reader = prepareReader(complexPropertyJson); EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees").getEntityType().getProperty("Location"); EntityComplexPropertyInfo entityPropertyInfo = (EntityComplexPropertyInfo) EntityInfoAggregator.create(edmProperty); JsonPropertyConsumer jpc = new JsonPropertyConsumer(); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) jpc.readPropertyValue(reader, entityPropertyInfo, null); assertEquals(2, result.size()); assertEquals("Germany", result.get("Country")); @SuppressWarnings("unchecked") Map<String, Object> innerResult = (Map<String, Object>) result.get("City"); assertEquals(2, innerResult.size()); assertEquals("Heidelberg", innerResult.get("CityName")); assertEquals("69124", innerResult.get("PostalCode")); } @Test(expected = EntityProviderException.class) public void complexPropertyMetadataInvalidTag() throws Exception { String complexPropertyJson = "{\"__metadata\":{\"invalid\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}"; JsonReader reader = prepareReader(complexPropertyJson); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); EntityComplexPropertyInfo entityPropertyInfo = (EntityComplexPropertyInfo) EntityInfoAggregator.create(property); new JsonPropertyConsumer().readPropertyValue(reader, entityPropertyInfo, null); } @Test(expected = EntityProviderException.class) public void complexPropertyMetadataInvalidTypeContent() throws Exception { String complexPropertyJson = "{\"__metadata\":{\"type\":\"Invalid\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}"; JsonReader reader = prepareReader(complexPropertyJson); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); EntityComplexPropertyInfo entityPropertyInfo = (EntityComplexPropertyInfo) EntityInfoAggregator.create(property); new JsonPropertyConsumer().readPropertyValue(reader, entityPropertyInfo, null); }
JsonPropertyConsumer { public Map<String, Object> readPropertyStandalone(final JsonReader reader, final EdmProperty property, final EntityProviderReadProperties readProperties) throws EntityProviderException { try { EntityPropertyInfo entityPropertyInfo = EntityInfoAggregator.create(property); Map<String, Object> typeMappings = readProperties == null ? null : readProperties.getTypeMappings(); Map<String, Object> result = new HashMap<String, Object>(); reader.beginObject(); String nextName = reader.nextName(); if (FormatJson.D.equals(nextName)) { reader.beginObject(); nextName = reader.nextName(); handleName(reader, typeMappings, entityPropertyInfo, result, nextName); reader.endObject(); } else { handleName(reader, typeMappings, entityPropertyInfo, result, nextName); } reader.endObject(); if (reader.peek() != JsonToken.END_DOCUMENT) { throw new EntityProviderException(EntityProviderException.END_DOCUMENT_EXPECTED.addContent(reader.peek().toString())); } return result; } catch (final IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } catch (final IllegalStateException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } Map<String, Object> readPropertyStandalone(final JsonReader reader, final EdmProperty property, final EntityProviderReadProperties readProperties); }
@Test public void veryLongStringStandalone() throws Exception { char[] chars = new char[32768]; Arrays.fill(chars, 0, 32768, 'a'); String propertyValue = new String(chars); String simplePropertyJson = "{\"d\":{\"Name\":\"" + propertyValue + "\"}}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Room").getProperty("Name"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); when(readProperties.getTypeMappings()).thenReturn(null); Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(propertyValue, resultMap.get("Name")); } @Test public void simplePropertyNull() throws Exception { JsonReader reader = prepareReader("{\"Name\":null}"); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Room").getProperty("Name"); final Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); assertTrue(resultMap.containsKey("Name")); assertNull(resultMap.get("Name")); } @Test(expected = EntityProviderException.class) public void simplePropertyNullValueNotAllowed() throws Exception { JsonReader reader = prepareReader("{\"Age\":null}"); EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EdmFacets facets = mock(EdmFacets.class); when(facets.isNullable()).thenReturn(false); when(property.getFacets()).thenReturn(facets); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); } @Test public void simplePropertyWithNullMappingStandalone() throws Exception { String simplePropertyJson = "{\"d\":{\"Age\":67}}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); when(readProperties.getTypeMappings()).thenReturn(null); Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test public void simplePropertyWithNullMappingStandaloneWithoutD() throws Exception { String simplePropertyJson = "{\"Age\":67}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); when(readProperties.getTypeMappings()).thenReturn(null); Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test public void simplePropertyWithEmptyMappingStandalone() throws Exception { String simplePropertyJson = "{\"d\":{\"Age\":67}}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); when(readProperties.getTypeMappings()).thenReturn(new HashMap<String, Object>()); Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test public void simplePropertyWithStringToLongMappingStandalone() throws Exception { String simplePropertyJson = "{\"d\":{\"Age\":67}}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); Map<String, Object> typeMappings = new HashMap<String, Object>(); typeMappings.put("Age", Long.class); when(readProperties.getTypeMappings()).thenReturn(typeMappings); Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(Long.valueOf(67), resultMap.get("Age")); } @Test public void simplePropertyWithStringToNullMappingStandalone() throws Exception { String simplePropertyJson = "{\"d\":{\"Age\":67}}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); Map<String, Object> typeMappings = new HashMap<String, Object>(); typeMappings.put("Age", null); when(readProperties.getTypeMappings()).thenReturn(typeMappings); Map<String, Object> resultMap = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(Integer.valueOf(67), resultMap.get("Age")); } @Test(expected = EntityProviderException.class) public void noContent() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); JsonReader reader = prepareReader("{}"); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); } @Test(expected = EntityProviderException.class) public void simplePropertyUnfinished() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); JsonReader reader = prepareReader("{\"Age\":67"); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); } @Test(expected = EntityProviderException.class) public void simplePropertInvalidName() throws Exception { String simplePropertyJson = "{\"d\":{\"Invalid\":67}}"; JsonReader reader = prepareReader(simplePropertyJson); final EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, null); } @Test public void complexPropertyWithStringToStringMappingStandalone() throws Exception { final String complexPropertyJson = "{\"d\":{\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}}}"; JsonReader reader = prepareReader(complexPropertyJson); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); Map<String, Object> innerMappings = new HashMap<String, Object>(); innerMappings.put("PostalCode", String.class); Map<String, Object> typeMappings = new HashMap<String, Object>(); typeMappings.put("City", innerMappings); when(readProperties.getTypeMappings()).thenReturn(typeMappings); Map<String, Object> result = new JsonPropertyConsumer().readPropertyStandalone(reader, property, readProperties); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> innerResult = (Map<String, Object>) result.get("City"); assertEquals("Heidelberg", innerResult.get("CityName")); assertEquals("69124", innerResult.get("PostalCode")); } @Test public void deepComplexPropertyWithStringToStringMappingStandalone() throws Exception { final String complexPropertyJson = "{\"d\":{\"Location\":{\"__metadata\":{\"type\":\"RefScenario.c_Location\"},\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"},\"Country\":\"Germany\"}}}"; JsonReader reader = prepareReader(complexPropertyJson); EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees").getEntityType().getProperty("Location"); EntityProviderReadProperties readProperties = mock(EntityProviderReadProperties.class); Map<String, Object> cityMappings = new HashMap<String, Object>(); cityMappings.put("PostalCode", String.class); Map<String, Object> locationMappings = new HashMap<String, Object>(); locationMappings.put("City", cityMappings); Map<String, Object> mappings = new HashMap<String, Object>(); mappings.put("Location", locationMappings); when(readProperties.getTypeMappings()).thenReturn(mappings); final Map<String, Object> result = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, readProperties); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> locationResult = (Map<String, Object>) result.get("Location"); assertEquals(2, locationResult.size()); assertEquals("Germany", locationResult.get("Country")); @SuppressWarnings("unchecked") Map<String, Object> innerResult = (Map<String, Object>) locationResult.get("City"); assertEquals(2, innerResult.size()); assertEquals("Heidelberg", innerResult.get("CityName")); assertEquals("69124", innerResult.get("PostalCode")); } @Test public void simplePropertyStandalone() throws Exception { String simplePropertyJson = "{\"d\":{\"Name\":\"Team 1\"}}"; EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams").getEntityType().getProperty("Name"); JsonReader reader = prepareReader(simplePropertyJson); Map<String, Object> result = new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, null); assertEquals("Team 1", result.get("Name")); } @Test public void complexPropertyStandalone() throws Exception { final String complexPropertyJson = "{\"d\":{\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}}}"; JsonReader reader = prepareReader(complexPropertyJson); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); final Map<String, Object> result = new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> innerResult = (Map<String, Object>) result.get("City"); assertEquals("Heidelberg", innerResult.get("CityName")); assertEquals("69124", innerResult.get("PostalCode")); } @Test public void deepComplexPropertyStandalone() throws Exception { final String complexPropertyJson = "{\"d\":{\"Location\":{\"__metadata\":{\"type\":\"RefScenario.c_Location\"},\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"},\"Country\":\"Germany\"}}}"; JsonReader reader = prepareReader(complexPropertyJson); EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees").getEntityType().getProperty("Location"); JsonPropertyConsumer jpc = new JsonPropertyConsumer(); Map<String, Object> result = jpc.readPropertyStandalone(reader, edmProperty, null); assertEquals(1, result.size()); @SuppressWarnings("unchecked") Map<String, Object> locationResult = (Map<String, Object>) result.get("Location"); assertEquals(2, locationResult.size()); assertEquals("Germany", locationResult.get("Country")); @SuppressWarnings("unchecked") Map<String, Object> innerResult = (Map<String, Object>) locationResult.get("City"); assertEquals(2, innerResult.size()); assertEquals("Heidelberg", innerResult.get("CityName")); assertEquals("69124", innerResult.get("PostalCode")); } @Test(expected = EntityProviderException.class) public void complexPropertyWithInvalidChild() throws Exception { String cityProperty = "{\"d\":{\"City\":{\"Invalid\":\"69124\",\"CityName\":\"Heidelberg\"}}}"; JsonReader reader = prepareReader(cityProperty); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); } @Test(expected = EntityProviderException.class) public void complexPropertyWithInvalidName() throws Exception { String cityProperty = "{\"d\":{\"Invalid\":{\"PostalCode\":\"69124\",\"CityName\":\"Heidelberg\"}}}"; JsonReader reader = prepareReader(cityProperty); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); } @Test public void complexPropertyNull() throws Exception { final String locationProperty = "{\"Location\":null}"; JsonReader reader = prepareReader(locationProperty); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees").getEntityType().getProperty("Location"); final Map<String, Object> propertyData = new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); assertNotNull(propertyData); assertEquals(1, propertyData.size()); assertTrue(propertyData.containsKey("Location")); assertNull(propertyData.get("Location")); } @Test(expected = EntityProviderException.class) public void complexPropertyNullValueNotAllowed() throws Exception { final String locationProperty = "{\"Location\":null}"; JsonReader reader = prepareReader(locationProperty); EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees").getEntityType().getProperty("Location"); EdmFacets facets = mock(EdmFacets.class); when(facets.isNullable()).thenReturn(false); when(property.getFacets()).thenReturn(facets); new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); } @Test public void complexPropertyEmpty() throws Exception { final String cityProperty = "{\"d\":{\"City\":{}}}"; JsonReader reader = prepareReader(cityProperty); final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getComplexType("RefScenario", "c_Location").getProperty("City"); final Map<String, Object> propertyData = new JsonPropertyConsumer().readPropertyStandalone(reader, property, null); assertNotNull(propertyData); assertEquals(1, propertyData.size()); assertNotNull(propertyData.get("City")); @SuppressWarnings("unchecked") final Map<String, Object> innerMap = (Map<String, Object>) propertyData.get("City"); assertTrue(innerMap.isEmpty()); } @Test(expected = EntityProviderException.class) public void invalidDoubleClosingBrackets() throws Exception { String simplePropertyJson = "{\"d\":{\"Name\":\"Team 1\"}}}"; EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams").getEntityType().getProperty("Name"); JsonReader reader = prepareReader(simplePropertyJson); new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, null); } @Test(expected = EntityProviderException.class) public void invalidDoubleClosingBracketsWithoutD() throws Exception { String simplePropertyJson = "{\"Name\":\"Team 1\"}}"; EdmProperty edmProperty = (EdmProperty) MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams").getEntityType().getProperty("Name"); JsonReader reader = prepareReader(simplePropertyJson); new JsonPropertyConsumer().readPropertyStandalone(reader, edmProperty, null); }
ODataJPAEdmProvider extends EdmProvider { @Override public EntityType getEntityType(final FullQualifiedName edmFQName) throws ODataException { String strEdmFQName = edmFQName.toString(); if (edmFQName != null) { if (entityTypes.containsKey(strEdmFQName)) { return entityTypes.get(strEdmFQName); } else if (schemas == null) { getSchemas(); } String entityTypeNamespace = edmFQName.getNamespace(); String entityTypeName = edmFQName.getName(); for (Schema schema : schemas) { String schemaNamespace = schema.getNamespace(); if (schemaNamespace.equals(entityTypeNamespace)) { if (schema.getEntityTypes() == null) { return null; } for (EntityType et : schema.getEntityTypes()) { if (et.getName().equals(entityTypeName)) { entityTypes.put(strEdmFQName, et); return et; } } } } } return null; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetEntityType() { FullQualifiedName entityTypeName = new FullQualifiedName( "salesorderprocessing", "SalesOrderHeader"); String entityName = null; try { entityName = edmProvider.getEntityType(entityTypeName).getName(); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertEquals("SalesOrderHeader", entityName); try { edmProvider .getEntityType(new FullQualifiedName("salesorder", "abc")); } catch (ODataException e) { assertTrue(true); } } @Test public void testGetEntityTypeWithBuffer() { HashMap<String, com.sap.core.odata.api.edm.provider.EntityType> entityTypes = new HashMap<String, com.sap.core.odata.api.edm.provider.EntityType>(); com.sap.core.odata.api.edm.provider.EntityType entity = new com.sap.core.odata.api.edm.provider.EntityType(); entity.setName("SalesOrderHeader"); entityTypes.put("salesorderprocessing" + "." + "SalesorderHeader", entity); ODataJPAEdmProvider jpaEdmProv = new ODataJPAEdmProvider(); Class<?> claz = jpaEdmProv.getClass(); Field f; try { f = claz.getDeclaredField("entityTypes"); f.setAccessible(true); f.set(jpaEdmProv, entityTypes); assertEquals(entity, jpaEdmProv.getEntityType(new FullQualifiedName( "salesorderprocessing", "SalesorderHeader"))); } catch (NoSuchFieldException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (SecurityException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalArgumentException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalAccessException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } try { jpaEdmProv.getEntityType(new FullQualifiedName("salesoprocessing", "abc")); } catch (ODataJPAModelException e) { assertTrue(true); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } }
ODataJPAEdmProvider extends EdmProvider { @Override public ComplexType getComplexType(final FullQualifiedName edmFQName) throws ODataException { if (edmFQName != null) { if (complexTypes.containsKey(edmFQName.toString())) { return complexTypes.get(edmFQName.toString()); } else if (schemas == null) { getSchemas(); } for (Schema schema : schemas) { if (schema.getNamespace().equals(edmFQName.getNamespace())) { if (schema.getComplexTypes() == null) { return null; } for (ComplexType ct : schema.getComplexTypes()) { if (ct.getName().equals(edmFQName.getName())) { complexTypes.put(edmFQName.toString(), ct); return ct; } } } } } return null; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetComplexType() { FullQualifiedName complexTypeName = new FullQualifiedName( "salesorderprocessing", "Address"); String nameStr = null; try { nameStr = edmProvider.getComplexType(complexTypeName).getName(); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertEquals("Address", nameStr); } @Test public void testgetComplexTypeWithBuffer() { HashMap<String, ComplexType> compTypes = new HashMap<String, ComplexType>(); ComplexType comp = new ComplexType(); comp.setName("Address"); compTypes.put("salesorderprocessing" + "." + "Address", comp); ODataJPAEdmProvider jpaEdmProv = new ODataJPAEdmProvider(); Class<?> claz = jpaEdmProv.getClass(); Field f; try { f = claz.getDeclaredField("complexTypes"); f.setAccessible(true); f.set(jpaEdmProv, compTypes); } catch (NoSuchFieldException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (SecurityException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalArgumentException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalAccessException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } try { assertEquals(comp, jpaEdmProv.getComplexType(new FullQualifiedName( "salesorderprocessing", "Address"))); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } try { jpaEdmProv.getComplexType(new FullQualifiedName("salesorderessing", "abc")); } catch (ODataJPAModelException e) { assertTrue(true); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } }
ODataJPAEdmProvider extends EdmProvider { @Override public Association getAssociation(final FullQualifiedName edmFQName) throws ODataException { if (edmFQName != null) { if (associations.containsKey(edmFQName.toString())) { return associations.get(edmFQName.toString()); } else if (schemas == null) { getSchemas(); } for (Schema schema : schemas) { if (schema.getNamespace().equals(edmFQName.getNamespace())) { if (schema.getAssociations() == null) { return null; } for (Association association : schema.getAssociations()) { if (association.getName().equals( edmFQName.getName())) { associations.put(edmFQName.toString(), association); return association; } } } } } return null; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetAssociationFullQualifiedName() { Association association = null; try { association = edmProvider.getAssociation(new FullQualifiedName( "salesorderprocessing", "SalesOrderHeader_SalesOrderItem")); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertNotNull(association); assertEquals("SalesOrderHeader_SalesOrderItem", association.getName()); } @Test public void testGetAssociationWithBuffer() { HashMap<String, Association> associations = new HashMap<String, Association>(); Association association = new Association(); association.setName("SalesOrderHeader_SalesOrderItem"); associations.put("salesorderprocessing" + "." + "SalesOrderHeader_SalesOrderItem", association); ODataJPAEdmProvider jpaEdmProv = new ODataJPAEdmProvider(); Class<?> claz = jpaEdmProv.getClass(); Field f; try { f = claz.getDeclaredField("associations"); f.setAccessible(true); f.set(jpaEdmProv, associations); assertEquals(association, jpaEdmProv.getAssociation(new FullQualifiedName( "salesorderprocessing", "SalesOrderHeader_SalesOrderItem"))); } catch (NoSuchFieldException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (SecurityException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalArgumentException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (IllegalAccessException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } try { jpaEdmProv.getAssociation(new FullQualifiedName( "salesorderprocessing", "abc")); } catch (ODataJPAModelException e) { assertTrue(true); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } }
XmlMetadataProducer { public static void writeMetadata(final DataServices metadata, final XMLStreamWriter xmlStreamWriter, Map<String, String> predefinedNamespaces) throws EntityProviderException { try { xmlStreamWriter.writeStartDocument(); xmlStreamWriter.setPrefix(Edm.PREFIX_EDMX, Edm.NAMESPACE_EDMX_2007_06); xmlStreamWriter.setPrefix(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08); xmlStreamWriter.setDefaultNamespace(Edm.NAMESPACE_EDM_2008_09); xmlStreamWriter.writeStartElement(Edm.NAMESPACE_EDMX_2007_06, "Edmx"); xmlStreamWriter.writeAttribute("Version", "1.0"); xmlStreamWriter.writeNamespace(Edm.PREFIX_EDMX, Edm.NAMESPACE_EDMX_2007_06); xmlStreamWriter.writeStartElement(Edm.NAMESPACE_EDMX_2007_06, "DataServices"); xmlStreamWriter.writeAttribute(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08, "DataServiceVersion", metadata.getDataServiceVersion()); xmlStreamWriter.writeNamespace(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08); if (predefinedNamespaces != null) { for (Map.Entry<String, String> entry : predefinedNamespaces.entrySet()) { xmlStreamWriter.writeNamespace(entry.getKey(), entry.getValue()); } } else { predefinedNamespaces = new HashMap<String, String>(); } Collection<Schema> schemas = metadata.getSchemas(); if (schemas != null) { for (Schema schema : schemas) { xmlStreamWriter.writeStartElement("Schema"); if (schema.getAlias() != null) { xmlStreamWriter.writeAttribute("Alias", schema.getAlias()); } xmlStreamWriter.writeAttribute("Namespace", schema.getNamespace()); xmlStreamWriter.writeDefaultNamespace(Edm.NAMESPACE_EDM_2008_09); writeAnnotationAttributes(schema.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); Collection<Using> usings = schema.getUsings(); if (usings != null) { for (Using using : usings) { xmlStreamWriter.writeStartElement("Using"); xmlStreamWriter.writeAttribute("Namespace", using.getNamespace()); xmlStreamWriter.writeAttribute("Alias", using.getAlias()); writeAnnotationAttributes(using.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(using.getDocumentation(), predefinedNamespaces, xmlStreamWriter); writeAnnotationElements(using.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } Collection<EntityType> entityTypes = schema.getEntityTypes(); if (entityTypes != null) { for (EntityType entityType : entityTypes) { xmlStreamWriter.writeStartElement("EntityType"); xmlStreamWriter.writeAttribute("Name", entityType.getName()); if (entityType.getBaseType() != null) { xmlStreamWriter.writeAttribute("BaseType", entityType.getBaseType().toString()); } if (entityType.isAbstract()) { xmlStreamWriter.writeAttribute("Abstract", "true"); } if (entityType.isHasStream()) { xmlStreamWriter.writeAttribute(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08, "HasStream", "true"); } writeCustomizableFeedMappings(entityType.getCustomizableFeedMappings(), xmlStreamWriter); writeAnnotationAttributes(entityType.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(entityType.getDocumentation(), predefinedNamespaces, xmlStreamWriter); Key key = entityType.getKey(); if (key != null) { xmlStreamWriter.writeStartElement("Key"); writeAnnotationAttributes(key.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); Collection<PropertyRef> propertyRefs = entityType.getKey().getKeys(); for (PropertyRef propertyRef : propertyRefs) { xmlStreamWriter.writeStartElement("PropertyRef"); writeAnnotationAttributes(propertyRef.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); xmlStreamWriter.writeAttribute("Name", propertyRef.getName()); writeAnnotationElements(propertyRef.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } writeAnnotationElements(key.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } Collection<Property> properties = entityType.getProperties(); if (properties != null) { writeProperties(properties, predefinedNamespaces, xmlStreamWriter); } Collection<NavigationProperty> navigationProperties = entityType.getNavigationProperties(); if (navigationProperties != null) { for (NavigationProperty navigationProperty : navigationProperties) { xmlStreamWriter.writeStartElement("NavigationProperty"); xmlStreamWriter.writeAttribute("Name", navigationProperty.getName()); xmlStreamWriter.writeAttribute("Relationship", navigationProperty.getRelationship().toString()); xmlStreamWriter.writeAttribute("FromRole", navigationProperty.getFromRole()); xmlStreamWriter.writeAttribute("ToRole", navigationProperty.getToRole()); writeAnnotationAttributes(navigationProperty.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(navigationProperty.getDocumentation(), predefinedNamespaces, xmlStreamWriter); writeAnnotationElements(navigationProperty.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } writeAnnotationElements(entityType.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } Collection<ComplexType> complexTypes = schema.getComplexTypes(); if (complexTypes != null) { for (ComplexType complexType : complexTypes) { xmlStreamWriter.writeStartElement("ComplexType"); xmlStreamWriter.writeAttribute("Name", complexType.getName()); if (complexType.getBaseType() != null) { xmlStreamWriter.writeAttribute("BaseType", complexType.getBaseType().toString()); } if (complexType.isAbstract()) { xmlStreamWriter.writeAttribute("Abstract", "true"); } writeAnnotationAttributes(complexType.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(complexType.getDocumentation(), predefinedNamespaces, xmlStreamWriter); Collection<Property> properties = complexType.getProperties(); if (properties != null) { writeProperties(properties, predefinedNamespaces, xmlStreamWriter); } writeAnnotationElements(complexType.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } Collection<Association> associations = schema.getAssociations(); if (associations != null) { for (Association association : associations) { xmlStreamWriter.writeStartElement("Association"); xmlStreamWriter.writeAttribute("Name", association.getName()); writeAnnotationAttributes(association.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(association.getDocumentation(), predefinedNamespaces, xmlStreamWriter); writeAssociationEnd(association.getEnd1(), predefinedNamespaces, xmlStreamWriter); writeAssociationEnd(association.getEnd2(), predefinedNamespaces, xmlStreamWriter); ReferentialConstraint referentialConstraint = association.getReferentialConstraint(); if (referentialConstraint != null) { xmlStreamWriter.writeStartElement("ReferentialConstraint"); writeAnnotationAttributes(referentialConstraint.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(referentialConstraint.getDocumentation(), predefinedNamespaces, xmlStreamWriter); ReferentialConstraintRole principal = referentialConstraint.getPrincipal(); xmlStreamWriter.writeStartElement("Principal"); xmlStreamWriter.writeAttribute("Role", principal.getRole()); writeAnnotationAttributes(principal.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); for (PropertyRef propertyRef : principal.getPropertyRefs()) { xmlStreamWriter.writeStartElement("PropertyRef"); xmlStreamWriter.writeAttribute("Name", propertyRef.getName()); xmlStreamWriter.writeEndElement(); } writeAnnotationElements(principal.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); ReferentialConstraintRole dependent = referentialConstraint.getDependent(); xmlStreamWriter.writeStartElement("Dependent"); xmlStreamWriter.writeAttribute("Role", dependent.getRole()); writeAnnotationAttributes(dependent.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); for (PropertyRef propertyRef : dependent.getPropertyRefs()) { xmlStreamWriter.writeStartElement("PropertyRef"); xmlStreamWriter.writeAttribute("Name", propertyRef.getName()); xmlStreamWriter.writeEndElement(); } writeAnnotationElements(dependent.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); writeAnnotationElements(referentialConstraint.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } writeAnnotationElements(association.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } Collection<EntityContainer> entityContainers = schema.getEntityContainers(); if (entityContainers != null) { for (EntityContainer entityContainer : entityContainers) { xmlStreamWriter.writeStartElement("EntityContainer"); xmlStreamWriter.writeAttribute("Name", entityContainer.getName()); if (entityContainer.getExtendz() != null) { xmlStreamWriter.writeAttribute("Extends", entityContainer.getExtendz()); } if (entityContainer.isDefaultEntityContainer()) { xmlStreamWriter.writeAttribute(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08, "IsDefaultEntityContainer", "true"); } writeAnnotationAttributes(entityContainer.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(entityContainer.getDocumentation(), predefinedNamespaces, xmlStreamWriter); Collection<EntitySet> entitySets = entityContainer.getEntitySets(); if (entitySets != null) { for (EntitySet entitySet : entitySets) { xmlStreamWriter.writeStartElement("EntitySet"); xmlStreamWriter.writeAttribute("Name", entitySet.getName()); xmlStreamWriter.writeAttribute("EntityType", entitySet.getEntityType().toString()); writeAnnotationAttributes(entitySet.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(entitySet.getDocumentation(), predefinedNamespaces, xmlStreamWriter); writeAnnotationElements(entitySet.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } Collection<AssociationSet> associationSets = entityContainer.getAssociationSets(); if (associationSets != null) { for (AssociationSet associationSet : associationSets) { xmlStreamWriter.writeStartElement("AssociationSet"); xmlStreamWriter.writeAttribute("Name", associationSet.getName()); xmlStreamWriter.writeAttribute("Association", associationSet.getAssociation().toString()); writeAnnotationAttributes(associationSet.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(associationSet.getDocumentation(), predefinedNamespaces, xmlStreamWriter); writeAssociationSetEnd(associationSet.getEnd1(), predefinedNamespaces, xmlStreamWriter); writeAssociationSetEnd(associationSet.getEnd2(), predefinedNamespaces, xmlStreamWriter); writeAnnotationElements(associationSet.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } Collection<FunctionImport> functionImports = entityContainer.getFunctionImports(); if (functionImports != null) { for (FunctionImport functionImport : functionImports) { xmlStreamWriter.writeStartElement("FunctionImport"); xmlStreamWriter.writeAttribute("Name", functionImport.getName()); if (functionImport.getReturnType() != null) { xmlStreamWriter.writeAttribute("ReturnType", functionImport.getReturnType().toString()); } if (functionImport.getEntitySet() != null) { xmlStreamWriter.writeAttribute("EntitySet", functionImport.getEntitySet()); } if (functionImport.getHttpMethod() != null) { xmlStreamWriter.writeAttribute(Edm.PREFIX_M, Edm.NAMESPACE_M_2007_08, "HttpMethod", functionImport.getHttpMethod()); } writeAnnotationAttributes(functionImport.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(functionImport.getDocumentation(), predefinedNamespaces, xmlStreamWriter); Collection<FunctionImportParameter> functionImportParameters = functionImport.getParameters(); if (functionImportParameters != null) { for (FunctionImportParameter functionImportParameter : functionImportParameters) { xmlStreamWriter.writeStartElement("Parameter"); xmlStreamWriter.writeAttribute("Name", functionImportParameter.getName()); xmlStreamWriter.writeAttribute("Type", functionImportParameter.getType().getFullQualifiedName().toString()); if (functionImportParameter.getMode() != null) { xmlStreamWriter.writeAttribute("Mode", functionImportParameter.getMode()); } writeFacets(xmlStreamWriter, functionImportParameter.getFacets()); writeAnnotationAttributes(functionImportParameter.getAnnotationAttributes(), predefinedNamespaces, null, xmlStreamWriter); writeDocumentation(functionImportParameter.getDocumentation(), predefinedNamespaces, xmlStreamWriter); writeAnnotationElements(functionImportParameter.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } writeAnnotationElements(functionImport.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } writeAnnotationElements(entityContainer.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } writeAnnotationElements(schema.getAnnotationElements(), predefinedNamespaces, xmlStreamWriter); xmlStreamWriter.writeEndElement(); } } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } catch (XMLStreamException e) { throw new EntityProviderException(EntityProviderException.COMMON, e); } catch (FactoryConfigurationError e) { throw new EntityProviderException(EntityProviderException.COMMON, e); } } static void writeMetadata(final DataServices metadata, final XMLStreamWriter xmlStreamWriter, Map<String, String> predefinedNamespaces); }
@Test public void writeValidMetadata() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationElement> annotationElements = new ArrayList<AnnotationElement>(); annotationElements.add(new AnnotationElement().setName("test").setText("hallo")); Schema schema = new Schema().setAnnotationElements(annotationElements); schema.setNamespace("http: schemas.add(schema); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:test", metadata); } @Test public void writeValidMetadata2() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationElement> childElements = new ArrayList<AnnotationElement>(); childElements.add(new AnnotationElement().setName("schemaElementTest2").setText("text2").setNamespace("namespace1")); List<AnnotationAttribute> elementAttributes = new ArrayList<AnnotationAttribute>(); elementAttributes.add(new AnnotationAttribute().setName("rel").setText("self")); elementAttributes.add(new AnnotationAttribute().setName("href").setText("http: List<AnnotationElement> element3List = new ArrayList<AnnotationElement>(); element3List.add(new AnnotationElement().setName("schemaElementTest4").setText("text4").setAttributes(elementAttributes)); childElements.add(new AnnotationElement().setName("schemaElementTest3").setText("text3").setPrefix("prefix").setNamespace("namespace2").setChildElements(element3List)); List<AnnotationElement> schemaElements = new ArrayList<AnnotationElement>(); schemaElements.add(new AnnotationElement().setName("schemaElementTest1").setText("text1").setChildElements(childElements)); schemaElements.add(new AnnotationElement().setName("test")); Schema schema = new Schema().setAnnotationElements(schemaElements); schema.setNamespace("http: schemas.add(schema); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: prefixMap.put("b", "namespace1"); prefixMap.put("prefix", "namespace2"); prefixMap.put("pre", "namespaceForAnno"); NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:test", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/b:schemaElementTest2", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/prefix:schemaElementTest3", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:schemaElementTest1/prefix:schemaElementTest3/a:schemaElementTest4[@rel=\"self\" and @pre:href=\"http: } @Test public void writeValidMetadata3() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationElement> annotationElements = new ArrayList<AnnotationElement>(); annotationElements.add(new AnnotationElement().setName("test").setText("hallo)")); Schema schema = new Schema().setAnnotationElements(annotationElements); schema.setNamespace("http: schemas.add(schema); List<PropertyRef> keys = new ArrayList<PropertyRef>(); keys.add(new PropertyRef().setName("Id")); Key key = new Key().setKeys(keys); List<Property> properties = new ArrayList<Property>(); properties.add(new SimpleProperty().setName("Id").setType(EdmSimpleTypeKind.String)); EntityType entityType = new EntityType().setName("testType").setKey(key).setProperties(properties); List<EntityType> entityTypes = new ArrayList<EntityType>(); entityTypes.add(entityType); schema.setEntityTypes(entityTypes); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:test", metadata); } @Test public void writeValidMetadata4() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationAttribute> attributesElement1 = new ArrayList<AnnotationAttribute>(); attributesElement1.add(new AnnotationAttribute().setName("rel").setText("self")); attributesElement1.add(new AnnotationAttribute().setName("href").setText("link")); List<AnnotationElement> schemaElements = new ArrayList<AnnotationElement>(); schemaElements.add(new AnnotationElement().setName("schemaElementTest1").setPrefix("atom").setNamespace("http: schemaElements.add(new AnnotationElement().setName("schemaElementTest2").setPrefix("atom").setNamespace("http: Schema schema = new Schema().setAnnotationElements(schemaElements); schema.setNamespace("http: schemas.add(schema); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: prefixMap.put("atom", "http: NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest1", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest2", metadata); } @Test public void writeValidMetadata5() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationAttribute> attributesElement1 = new ArrayList<AnnotationAttribute>(); attributesElement1.add(new AnnotationAttribute().setName("rel").setText("self").setPrefix("atom").setNamespace("http: attributesElement1.add(new AnnotationAttribute().setName("href").setText("link").setPrefix("atom").setNamespace("http: List<AnnotationElement> schemaElements = new ArrayList<AnnotationElement>(); schemaElements.add(new AnnotationElement().setName("schemaElementTest1").setPrefix("atom").setNamespace("http: schemaElements.add(new AnnotationElement().setName("schemaElementTest2").setPrefix("atom").setNamespace("http: Schema schema = new Schema().setAnnotationElements(schemaElements); schema.setNamespace("http: schemas.add(schema); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: prefixMap.put("atom", "http: NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest1", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest2", metadata); } @Test public void writeValidMetadata6() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationAttribute> attributesElement1 = new ArrayList<AnnotationAttribute>(); attributesElement1.add(new AnnotationAttribute().setName("rel").setText("self").setPrefix("atom").setNamespace("http: attributesElement1.add(new AnnotationAttribute().setName("href").setText("link").setPrefix("atom").setNamespace("http: List<AnnotationElement> elementElements = new ArrayList<AnnotationElement>(); elementElements.add(new AnnotationElement().setName("schemaElementTest2").setPrefix("atom").setNamespace("http: elementElements.add(new AnnotationElement().setName("schemaElementTest3").setPrefix("atom").setNamespace("http: List<AnnotationElement> schemaElements = new ArrayList<AnnotationElement>(); schemaElements.add(new AnnotationElement().setName("schemaElementTest1").setPrefix("atom").setNamespace("http: Schema schema = new Schema().setAnnotationElements(schemaElements); schema.setNamespace("http: schemas.add(schema); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: prefixMap.put("atom", "http: NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest1", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest1/atom:schemaElementTest2", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/atom:schemaElementTest1/atom:schemaElementTest3", metadata); } @Test(expected = Exception.class) public void writeInvalidMetadata() throws Exception { disableLogging(this.getClass()); List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationElement> annotationElements = new ArrayList<AnnotationElement>(); annotationElements.add(new AnnotationElement().setText("hallo")); Schema schema = new Schema().setAnnotationElements(annotationElements); schema.setNamespace("http: schemas.add(schema); DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null); } @Test public void writeWithPredefinedNamespaces() throws Exception { List<Schema> schemas = new ArrayList<Schema>(); List<AnnotationAttribute> attributesElement1 = new ArrayList<AnnotationAttribute>(); attributesElement1.add(new AnnotationAttribute().setName("rel").setText("self").setPrefix("sap").setNamespace("http: attributesElement1.add(new AnnotationAttribute().setName("href").setText("link").setPrefix("sap").setNamespace("http: List<AnnotationElement> elementElements = new ArrayList<AnnotationElement>(); elementElements.add(new AnnotationElement().setName("schemaElementTest2").setPrefix("sap").setNamespace("http: elementElements.add(new AnnotationElement().setName("schemaElementTest3").setPrefix("sap").setNamespace("http: List<AnnotationElement> schemaElements = new ArrayList<AnnotationElement>(); schemaElements.add(new AnnotationElement().setName("schemaElementTest1").setPrefix("sap").setNamespace("http: Schema schema = new Schema().setAnnotationElements(schemaElements); schema.setNamespace("http: schemas.add(schema); Map<String, String> predefinedNamespaces = new HashMap<String, String>(); predefinedNamespaces.put("sap", "http: DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20); OutputStreamWriter writer = null; CircleStreamBuffer csb = new CircleStreamBuffer(); writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8"); XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer); XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, predefinedNamespaces); String metadata = StringHelper.inputStreamToString(csb.getInputStream()); Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("edmx", "http: prefixMap.put("a", "http: prefixMap.put("sap", "http: NamespaceContext ctx = new SimpleNamespaceContext(prefixMap); XMLUnit.setXpathNamespaceContext(ctx); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/sap:schemaElementTest1", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/sap:schemaElementTest1/sap:schemaElementTest2", metadata); assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/sap:schemaElementTest1/sap:schemaElementTest3", metadata); }
ODataJPAEdmProvider extends EdmProvider { @Override public EntitySet getEntitySet(final String entityContainer, final String name) throws ODataException { EntitySet returnedSet = null; EntityContainer container = null; if (!entityContainerInfos.containsKey(entityContainer)) { container = (EntityContainer) getEntityContainerInfo(entityContainer); } else { container = (EntityContainer) entityContainerInfos .get(entityContainer); } if (container != null && name != null) { for (EntitySet es : container.getEntitySets()) { if (name.equals(es.getName())) { returnedSet = es; break; } } } return returnedSet; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetEntitySet() { String entitySetName = null; try { entitySetName = edmProvider.getEntitySet( "salesorderprocessingContainer", "SalesOrderHeaders") .getName(); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertEquals("SalesOrderHeaders", entitySetName); try { assertNull(edmProvider.getEntitySet("salesorderprocessing", "SalesOrderHeaders")); } catch (ODataException e) { assertTrue(true); } }
JsonServiceDocumentProducer { public static void writeServiceDocument(final Writer writer, final Edm edm) throws EntityProviderException { final EdmServiceMetadata serviceMetadata = edm.getServiceMetadata(); JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(writer); try { jsonStreamWriter.beginObject() .name(FormatJson.D) .beginObject() .name(FormatJson.ENTITY_SETS) .beginArray(); boolean first = true; for (EdmEntitySetInfo info : serviceMetadata.getEntitySetInfos()) { if (first) { first = false; } else { jsonStreamWriter.separator(); } jsonStreamWriter.stringValue(info.getEntitySetUri().toASCIIString()); } jsonStreamWriter.endArray() .endObject() .endObject(); } catch (final IOException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } catch (final ODataException e) { throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e); } } static void writeServiceDocument(final Writer writer, final Edm edm); }
@Test public void serviceDocumentEmpty() throws Exception { Edm edm = mock(Edm.class); EdmServiceMetadata metadata = mock(EdmServiceMetadata.class); when(edm.getServiceMetadata()).thenReturn(metadata); final ODataResponse response = new JsonEntityProvider().writeServiceDocument(edm, "http: assertNotNull(response); assertNotNull(response.getEntity()); assertEquals(HttpContentType.APPLICATION_JSON, response.getContentHeader()); assertEquals(ODataServiceVersion.V10, response.getHeader(ODataHttpHeaders.DATASERVICEVERSION)); final String json = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertNotNull(json); assertEquals("{\"d\":{\"EntitySets\":[]}}", json); } @Test public void serviceDocument() throws Exception { Edm edm = mock(Edm.class); EdmServiceMetadata metadata = mock(EdmServiceMetadata.class); EdmEntitySetInfo entitySetInfo1 = mock(EdmEntitySetInfo.class); when(entitySetInfo1.getEntitySetUri()).thenReturn(URI.create("EntitySet")); EdmEntitySetInfo entitySetInfo2 = mock(EdmEntitySetInfo.class); when(entitySetInfo2.getEntitySetUri()).thenReturn(URI.create("Container2.EntitySet2")); when(metadata.getEntitySetInfos()).thenReturn(Arrays.asList(entitySetInfo1, entitySetInfo2)); when(edm.getServiceMetadata()).thenReturn(metadata); final ODataResponse response = new JsonEntityProvider().writeServiceDocument(edm, "http: assertNotNull(response); assertNotNull(response.getEntity()); assertEquals(HttpContentType.APPLICATION_JSON, response.getContentHeader()); assertEquals(ODataServiceVersion.V10, response.getHeader(ODataHttpHeaders.DATASERVICEVERSION)); final String json = StringHelper.inputStreamToString((InputStream) response.getEntity()); assertNotNull(json); assertEquals("{\"d\":{\"EntitySets\":[\"EntitySet\",\"Container2.EntitySet2\"]}}", json); }
AtomServiceDocumentProducer { public void writeServiceDocument(final Writer writer) throws EntityProviderException { EdmServiceMetadata serviceMetadata = edm.getServiceMetadata(); try { XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); xmlStreamWriter.writeStartDocument(DEFAULT_CHARSET, XML_VERSION); xmlStreamWriter.setPrefix(Edm.PREFIX_XML, Edm.NAMESPACE_XML_1998); xmlStreamWriter.setPrefix(Edm.PREFIX_ATOM, Edm.NAMESPACE_ATOM_2005); xmlStreamWriter.setDefaultNamespace(Edm.NAMESPACE_APP_2007); xmlStreamWriter.writeStartElement(FormatXml.APP_SERVICE); xmlStreamWriter.writeAttribute(Edm.PREFIX_XML, Edm.NAMESPACE_XML_1998, FormatXml.XML_BASE, serviceRoot); xmlStreamWriter.writeDefaultNamespace(Edm.NAMESPACE_APP_2007); xmlStreamWriter.writeNamespace(Edm.PREFIX_ATOM, Edm.NAMESPACE_ATOM_2005); xmlStreamWriter.writeStartElement(FormatXml.APP_WORKSPACE); xmlStreamWriter.writeStartElement(Edm.NAMESPACE_ATOM_2005, FormatXml.ATOM_TITLE); xmlStreamWriter.writeCharacters(FormatXml.ATOM_TITLE_DEFAULT); xmlStreamWriter.writeEndElement(); List<EdmEntitySetInfo> entitySetInfos = serviceMetadata.getEntitySetInfos(); for (EdmEntitySetInfo info : entitySetInfos) { xmlStreamWriter.writeStartElement(FormatXml.APP_COLLECTION); xmlStreamWriter.writeAttribute(FormatXml.ATOM_HREF, info.getEntitySetUri().toASCIIString()); xmlStreamWriter.writeStartElement(Edm.NAMESPACE_ATOM_2005, FormatXml.ATOM_TITLE); xmlStreamWriter.writeCharacters(info.getEntitySetName()); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } catch (FactoryConfigurationError e) { throw new EntityProviderException(EntityProviderException.COMMON, e); } catch (XMLStreamException e) { throw new EntityProviderException(EntityProviderException.COMMON, e); } catch (ODataException e) { throw new EntityProviderException(EntityProviderException.COMMON, e); } } AtomServiceDocumentProducer(final Edm edm, final String serviceRoot); void writeServiceDocument(final Writer writer); }
@Test public void writeEmptyServiceDocumentOverRuntimeDelegate() throws Exception { ODataResponse response = EntityProvider.writeServiceDocument(HttpContentType.APPLICATION_ATOM_XML, edm, "http: String xmlString = verifyResponse(response); assertXpathExists("/a:service", xmlString); assertXpathExists("/a:service/a:workspace", xmlString); assertXpathExists("/a:service/a:workspace/atom:title", xmlString); assertXpathEvaluatesTo("Default", "/a:service/a:workspace/atom:title", xmlString); } @Test public void writeEmptyServiceDocument() throws Exception { ODataResponse response = new AtomEntityProvider().writeServiceDocument(edm, "http: String xmlString = verifyResponse(response); assertXpathExists("/a:service", xmlString); assertXpathExists("/a:service/a:workspace", xmlString); assertXpathExists("/a:service/a:workspace/atom:title", xmlString); assertXpathEvaluatesTo("Default", "/a:service/a:workspace/atom:title", xmlString); } @Test public void writeServiceDocumentWithOneEnitySetOneContainerOneSchema() throws Exception { List<EntitySet> entitySets = new ArrayList<EntitySet>(); entitySets.add(new EntitySet().setName("Employees")); List<EntityContainer> entityContainers = new ArrayList<EntityContainer>(); entityContainers.add(new EntityContainer().setDefaultEntityContainer(true).setName("Container").setEntitySets(entitySets)); schemas.add(new Schema().setEntityContainers(entityContainers)); ODataResponse response = new AtomEntityProvider().writeServiceDocument(edm, "http: String xmlString = verifyResponse(response); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); } @Test public void writeServiceDocumentWithOneEnitySetTwoContainersOneSchema() throws Exception { List<EntitySet> entitySets = new ArrayList<EntitySet>(); entitySets.add(new EntitySet().setName("Employees")); List<EntityContainer> entityContainers = new ArrayList<EntityContainer>(); entityContainers.add(new EntityContainer().setDefaultEntityContainer(true).setName("Container").setEntitySets(entitySets)); entityContainers.add(new EntityContainer().setDefaultEntityContainer(false).setName("Container2").setEntitySets(entitySets)); schemas.add(new Schema().setEntityContainers(entityContainers)); ODataResponse response = new AtomEntityProvider().writeServiceDocument(edm, "http: String xmlString = verifyResponse(response); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Container2.Employees']/atom:title", xmlString); } @Test public void writeServiceDocumentWithOneEnitySetTwoContainersTwoSchemas() throws Exception { List<EntitySet> entitySets = new ArrayList<EntitySet>(); entitySets.add(new EntitySet().setName("Employees")); List<EntityContainer> entityContainers = new ArrayList<EntityContainer>(); entityContainers.add(new EntityContainer().setDefaultEntityContainer(true).setName("Container").setEntitySets(entitySets)); entityContainers.add(new EntityContainer().setDefaultEntityContainer(false).setName("Container2").setEntitySets(entitySets)); List<EntityContainer> entityContainers2 = new ArrayList<EntityContainer>(); entityContainers2.add(new EntityContainer().setDefaultEntityContainer(false).setName("Container3").setEntitySets(entitySets)); entityContainers2.add(new EntityContainer().setDefaultEntityContainer(false).setName("Container4").setEntitySets(entitySets)); schemas.add(new Schema().setEntityContainers(entityContainers)); schemas.add(new Schema().setEntityContainers(entityContainers2)); ODataResponse response = new AtomEntityProvider().writeServiceDocument(edm, "http: String xmlString = verifyResponse(response); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Container2.Employees']/atom:title", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Container3.Employees']/atom:title", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']", xmlString); assertXpathExists("/a:service/a:workspace/a:collection[@href='Employees']/atom:title", xmlString); assertXpathEvaluatesTo("Employees", "/a:service/a:workspace/a:collection[@href='Container4.Employees']/atom:title", xmlString); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties) throws EntityProviderException { return create(contentType).readEntry(entitySet, content, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void readEntry() throws Exception { final String contentType = ContentType.APPLICATION_ATOM_XML_ENTRY.toContentTypeString(); final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"); InputStream content = new ByteArrayInputStream(EMPLOYEE_1_XML.getBytes("UTF-8")); final ODataEntry result = new ProviderFacadeImpl().readEntry(contentType, entitySet, content, EntityProviderReadProperties.init().mergeSemantic(true).build()); assertNotNull(result); assertFalse(result.containsInlineEntry()); assertNotNull(result.getExpandSelectTree()); assertTrue(result.getExpandSelectTree().isAll()); assertNotNull(result.getMetadata()); assertNull(result.getMetadata().getEtag()); assertNotNull(result.getMediaMetadata()); assertEquals(HttpContentType.APPLICATION_OCTET_STREAM, result.getMediaMetadata().getContentType()); assertNotNull(result.getProperties()); assertEquals(52, result.getProperties().get("Age")); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping) throws EntityProviderException { return create().readPropertyValue(edmProperty, content, typeMapping); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void readPropertyValue() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EntryDate"); InputStream content = new ByteArrayInputStream("2012-02-29T01:02:03".getBytes("UTF-8")); final Object result = new ProviderFacadeImpl().readPropertyValue(property, content, Long.class); assertEquals(1330477323000L, result); }
ODataJPAEdmProvider extends EdmProvider { @Override public AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole) throws ODataException { EntityContainer container = null; if (!entityContainerInfos.containsKey(entityContainer)) { container = (EntityContainer) getEntityContainerInfo(entityContainer); } else { container = (EntityContainer) entityContainerInfos .get(entityContainer); } if (container != null && association != null && container.getAssociationSets() != null) { for (AssociationSet as : container.getAssociationSets()) { if (association.equals(as.getAssociation())) { AssociationSetEnd end = as.getEnd1(); if (sourceEntitySetName.equals(end.getEntitySet()) && sourceEntitySetRole.equals(end.getRole())) { return as; } else { end = as.getEnd2(); if (sourceEntitySetName.equals(end.getEntitySet()) && sourceEntitySetRole.equals(end.getRole())) { return as; } } } } } return null; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetAssociationSet() { AssociationSet associationSet = null; try { associationSet = edmProvider.getAssociationSet( "salesorderprocessingContainer", new FullQualifiedName( "salesorderprocessing", "SalesOrderHeader_SalesOrderItem"), "SalesOrderHeaders", "SalesOrderHeader"); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertNotNull(associationSet); assertEquals("SalesOrderHeader_SalesOrderItemSet", associationSet.getName()); try { associationSet = edmProvider.getAssociationSet( "salesorderprocessingContainer", new FullQualifiedName( "salesorderprocessing", "SalesOrderHeader_SalesOrderItem"), "SalesOrderItems", "SalesOrderItem"); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertNotNull(associationSet); try { associationSet = edmProvider.getAssociationSet( "salesorderproceContainer", new FullQualifiedName( "salesorderprocessing", "SalesOrderHeader_SalesOrderItem"), "SalesOrderItems", "SalesOrderItem"); } catch (ODataException e) { assertTrue(true); } }
ProviderFacadeImpl implements EntityProviderInterface { @Override public Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties) throws EntityProviderException { return create(contentType).readProperty(edmProperty, content, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void readProperty() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age"); final String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">42</Age>"; InputStream content = new ByteArrayInputStream(xml.getBytes("UTF-8")); final Map<String, Object> result = new ProviderFacadeImpl().readProperty(HttpContentType.APPLICATION_XML, property, content, EntityProviderReadProperties.init().build()); assertFalse(result.isEmpty()); assertEquals(42, result.get("Age")); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content) throws EntityProviderException { return create(contentType).readLink(entitySet, content); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void readLink() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream content = new ByteArrayInputStream("{\"d\":{\"uri\":\"http: final String result = new ProviderFacadeImpl().readLink(HttpContentType.APPLICATION_JSON, entitySet, content); assertEquals("http: }
ProviderFacadeImpl implements EntityProviderInterface { @Override public List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content) throws EntityProviderException { return create(contentType).readLinks(entitySet, content); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void readLinks() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); InputStream content = new ByteArrayInputStream("{\"d\":{\"__count\":\"42\",\"results\":[{\"uri\":\"http: final List<String> result = new ProviderFacadeImpl().readLinks(HttpContentType.APPLICATION_JSON, entitySet, content); assertEquals(Arrays.asList("http: }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties) throws EntityProviderException { return create(contentType).writeFeed(entitySet, data, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeFeed() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); List<Map<String, Object>> propertiesList = new ArrayList<Map<String, Object>>(); final ODataResponse result = new ProviderFacadeImpl().writeFeed(HttpContentType.APPLICATION_JSON, entitySet, propertiesList, EntityProviderWriteProperties.serviceRoot(URI.create("http: assertEquals("{\"d\":{\"results\":[]}}", StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties) throws EntityProviderException { return create(contentType).writeEntry(entitySet, data, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeEntry() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams"); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("Id", "42"); final ODataResponse result = new ProviderFacadeImpl().writeEntry(HttpContentType.APPLICATION_JSON, entitySet, properties, EntityProviderWriteProperties.serviceRoot(URI.create("http: assertEquals("{\"d\":{\"__metadata\":{\"id\":\"http: + "\"uri\":\"http: + "\"Id\":\"42\",\"Name\":null,\"isScrumTeam\":null," + "\"nt_Employees\":{\"__deferred\":{\"uri\":\"http: StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value) throws EntityProviderException { return create(contentType).writeProperty(edmProperty, value); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeProperty() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EntryDate"); final ODataResponse result = new ProviderFacadeImpl().writeProperty(HttpContentType.APPLICATION_XML, property, 987654321000L); assertEquals(HttpContentType.APPLICATION_XML_UTF8, result.getContentHeader()); assertTrue(StringHelper.inputStreamToString((InputStream) result.getEntity()) .endsWith("\">2001-04-19T04:25:21</EntryDate>")); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties) throws EntityProviderException { return create(contentType).writeLink(entitySet, data, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeLink() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("Id", "42"); final ODataResponse result = new ProviderFacadeImpl().writeLink(HttpContentType.APPLICATION_JSON, entitySet, properties, EntityProviderWriteProperties.serviceRoot(URI.create("http: assertEquals("{\"d\":{\"uri\":\"http: StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties) throws EntityProviderException { return create(contentType).writeLinks(entitySet, data, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeLinks() throws Exception { final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("Id", "42"); List<Map<String, Object>> propertiesList = new ArrayList<Map<String, Object>>(); propertiesList.add(properties); propertiesList.add(properties); final ODataResponse result = new ProviderFacadeImpl().writeLinks(HttpContentType.APPLICATION_JSON, entitySet, propertiesList, EntityProviderWriteProperties.serviceRoot(URI.create("http: assertEquals("{\"d\":[{\"uri\":\"http: StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot) throws EntityProviderException { return create(contentType).writeServiceDocument(edm, serviceRoot); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeServiceDocument() throws Exception { final ODataResponse result = new ProviderFacadeImpl().writeServiceDocument(HttpContentType.APPLICATION_JSON, MockFacade.getMockEdm(), "root"); assertEquals("{\"d\":{\"EntitySets\":[]}}", StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value) throws EntityProviderException { return create().writePropertyValue(edmProperty, value); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writePropertyValue() throws Exception { final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("EntryDate"); final ODataResponse result = new ProviderFacadeImpl().writePropertyValue(property, 987654321000L); assertEquals(HttpContentType.TEXT_PLAIN_UTF8, result.getContentHeader()); assertEquals("2001-04-19T04:25:21", StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ODataJPAEdmProvider extends EdmProvider { @Override public FunctionImport getFunctionImport(final String entityContainer, final String name) throws ODataException { if (functionImports.containsKey(name)) { return functionImports.get(name); } EntityContainer container = null; if (!entityContainerInfos.containsKey(entityContainer)) { container = (EntityContainer) getEntityContainerInfo(entityContainer); } else { container = (EntityContainer) entityContainerInfos .get(entityContainer); } if (container != null && name != null) { if (container.getFunctionImports() == null) { return null; } for (FunctionImport fi : container.getFunctionImports()) { if (name.equals(fi.getName())) { functionImports.put(name, fi); return fi; } } } return null; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetFunctionImport() { String functionImportName = null; try { functionImportName = edmProvider.getFunctionImport( "salesorderprocessingContainer", "SalesOrder_FunctionImport1").getName(); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } assertEquals("SalesOrder_FunctionImport1", functionImportName); try { functionImportName = edmProvider.getFunctionImport( "salesorderprocessingContainer", "SalesOrder_FunctionImport1").getName(); } catch (ODataException e) { assertTrue(true); } try { assertNotNull(edmProvider.getFunctionImport( "salesorderprocessingContainer", "SalesOrder_FunctionImport1")); } catch (ODataException e) { e.printStackTrace(); } }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeText(final String value) throws EntityProviderException { return create().writeText(value); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeText() throws Exception { final ODataResponse result = new ProviderFacadeImpl().writeText("test"); assertEquals(HttpContentType.TEXT_PLAIN_UTF8, result.getContentHeader()); assertEquals("test", StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeBinary(final String mimeType, final byte[] data) throws EntityProviderException { return create().writeBinary(mimeType, data); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeBinary() throws Exception { final ODataResponse result = new ProviderFacadeImpl().writeBinary(HttpContentType.APPLICATION_OCTET_STREAM, new byte[] { 102, 111, 111 }); assertEquals(HttpContentType.APPLICATION_OCTET_STREAM, result.getContentHeader()); assertEquals("foo", StringHelper.inputStreamToString((InputStream) result.getEntity())); } @Test public void writeBinaryNoContent() throws Exception { final ODataResponse result = new ProviderFacadeImpl().writeBinary(HttpContentType.APPLICATION_OCTET_STREAM, null); assertNull(result.getEntity()); assertNull(result.getContentHeader()); assertEquals(HttpStatusCodes.NO_CONTENT, result.getStatus()); }
ProviderFacadeImpl implements EntityProviderInterface { @Override public ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties) throws EntityProviderException { return create(contentType).writeFunctionImport(functionImport, data, properties); } @Override ODataResponse writeErrorDocument(final ODataErrorContext context); @Override ODataResponse writeServiceDocument(final String contentType, final Edm edm, final String serviceRoot); @Override ODataResponse writePropertyValue(final EdmProperty edmProperty, final Object value); @Override ODataResponse writeText(final String value); @Override ODataResponse writeBinary(final String mimeType, final byte[] data); @Override ODataResponse writeFeed(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeEntry(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeProperty(final String contentType, final EdmProperty edmProperty, final Object value); @Override ODataResponse writeLink(final String contentType, final EdmEntitySet entitySet, final Map<String, Object> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeLinks(final String contentType, final EdmEntitySet entitySet, final List<Map<String, Object>> data, final EntityProviderWriteProperties properties); @Override ODataResponse writeFunctionImport(final String contentType, final EdmFunctionImport functionImport, final Object data, final EntityProviderWriteProperties properties); @Override ODataFeed readFeed(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override ODataEntry readEntry(final String contentType, final EdmEntitySet entitySet, final InputStream content, final EntityProviderReadProperties properties); @Override Map<String, Object> readProperty(final String contentType, final EdmProperty edmProperty, final InputStream content, final EntityProviderReadProperties properties); @Override Object readPropertyValue(final EdmProperty edmProperty, final InputStream content, final Class<?> typeMapping); @Override List<String> readLinks(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override String readLink(final String contentType, final EdmEntitySet entitySet, final InputStream content); @Override byte[] readBinary(final InputStream content); @Override ODataResponse writeMetadata(final List<Schema> schemas, final Map<String, String> predefinedNamespaces); @Override Edm readMetadata(final InputStream inputStream, final boolean validate); @Override ServiceDocument readServiceDocument(final InputStream serviceDocument, final String contentType); @Override List<BatchRequestPart> parseBatchRequest(final String contentType, final InputStream content, final EntityProviderBatchProperties properties); @Override ODataResponse writeBatchResponse(final List<BatchResponsePart> batchResponseParts); @Override InputStream writeBatchRequest(final List<BatchPart> batchParts, final String boundary); @Override List<BatchSingleResponse> parseBatchResponse(final String contentType, final InputStream content); }
@Test public void writeFunctionImport() throws Exception { final EdmFunctionImport function = MockFacade.getMockEdm().getDefaultEntityContainer().getFunctionImport("MaximalAge"); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("MaximalAge", 99); final ODataResponse result = new ProviderFacadeImpl().writeFunctionImport(HttpContentType.APPLICATION_JSON, function, properties, null); assertEquals("{\"d\":{\"MaximalAge\":99}}", StringHelper.inputStreamToString((InputStream) result.getEntity())); }
ODataSingleProcessorService implements ODataService { @Override public List<String> getSupportedContentTypes(final Class<? extends ODataProcessor> processorFeature) throws ODataException { List<String> result = new ArrayList<String>(); if (processor instanceof CustomContentType) { result.addAll(((CustomContentType) processor).getCustomContentTypes(processorFeature)); } if (processorFeature == BatchProcessor.class) { result.add(HttpContentType.WILDCARD); } else if (processorFeature == EntityProcessor.class) { result.add(HttpContentType.APPLICATION_ATOM_XML_ENTRY_UTF8); result.add(HttpContentType.APPLICATION_ATOM_XML_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8_VERBOSE); result.add(HttpContentType.APPLICATION_XML_UTF8); } else if (processorFeature == FunctionImportProcessor.class || processorFeature == EntityLinkProcessor.class || processorFeature == EntityLinksProcessor.class || processorFeature == EntitySimplePropertyProcessor.class || processorFeature == EntityComplexPropertyProcessor.class) { result.add(HttpContentType.APPLICATION_XML_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8_VERBOSE); } else if (processorFeature == EntityMediaProcessor.class || processorFeature == EntitySimplePropertyValueProcessor.class || processorFeature == FunctionImportValueProcessor.class) { result.add(HttpContentType.WILDCARD); } else if (processorFeature == EntitySetProcessor.class) { result.add(HttpContentType.APPLICATION_ATOM_XML_FEED_UTF8); result.add(HttpContentType.APPLICATION_ATOM_XML_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8_VERBOSE); result.add(HttpContentType.APPLICATION_XML_UTF8); } else if (processorFeature == MetadataProcessor.class) { result.add(HttpContentType.APPLICATION_XML_UTF8); } else if (processorFeature == ServiceDocumentProcessor.class) { result.add(HttpContentType.APPLICATION_ATOM_SVC_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8); result.add(HttpContentType.APPLICATION_JSON_UTF8_VERBOSE); result.add(HttpContentType.APPLICATION_XML_UTF8); } else { throw new ODataNotImplementedException(); } return result; } ODataSingleProcessorService(final EdmProvider provider, final ODataSingleProcessor processor); @Override String getVersion(); @Override Edm getEntityDataModel(); @Override MetadataProcessor getMetadataProcessor(); @Override ServiceDocumentProcessor getServiceDocumentProcessor(); @Override EntityProcessor getEntityProcessor(); @Override EntitySetProcessor getEntitySetProcessor(); @Override EntityComplexPropertyProcessor getEntityComplexPropertyProcessor(); @Override EntityLinkProcessor getEntityLinkProcessor(); @Override EntityLinksProcessor getEntityLinksProcessor(); @Override EntityMediaProcessor getEntityMediaProcessor(); @Override EntitySimplePropertyProcessor getEntitySimplePropertyProcessor(); @Override EntitySimplePropertyValueProcessor getEntitySimplePropertyValueProcessor(); @Override FunctionImportProcessor getFunctionImportProcessor(); @Override FunctionImportValueProcessor getFunctionImportValueProcessor(); @Override BatchProcessor getBatchProcessor(); @Override ODataProcessor getProcessor(); @Override List<String> getSupportedContentTypes(final Class<? extends ODataProcessor> processorFeature); }
@Test public void defaultSupportedContentTypesForEntitySet() throws Exception { List<String> types = service.getSupportedContentTypes(EntitySetProcessor.class); List<ContentType> convertedTypes = ContentType.convert(types); assertTrue(convertedTypes.contains(appendCharset(ContentType.APPLICATION_ATOM_XML))); assertTrue(convertedTypes.contains(appendCharset(ContentType.APPLICATION_ATOM_XML_FEED))); assertTrue(convertedTypes.contains(appendCharset(ContentType.APPLICATION_JSON))); } @Test public void defaultSupportedContentTypesForEntity() throws Exception { List<String> types = service.getSupportedContentTypes(EntityProcessor.class); List<ContentType> convertedTypes = ContentType.convert(types); assertTrue(convertedTypes.contains(appendCharset(ContentType.APPLICATION_ATOM_XML))); assertTrue(convertedTypes.contains(appendCharset(ContentType.APPLICATION_ATOM_XML_ENTRY))); assertTrue(convertedTypes.contains(appendCharset(ContentType.APPLICATION_JSON))); } @Test public void defaultSupportedContentTypesForServiceDocument() throws Exception { List<String> types = service.getSupportedContentTypes(ServiceDocumentProcessor.class); assertTrue(types.contains(APPLICATION_ATOM_SVC)); assertTrue(types.contains(APPLICATION_JSON)); } @Test public void defaultSupportedContentTypesForMetadata() throws Exception { List<String> types = service.getSupportedContentTypes(MetadataProcessor.class); assertTrue(types.contains(APPLICATION_XML)); } @Test public void defaultSupportedContentTypesForFunctionImport() throws Exception { List<String> types = service.getSupportedContentTypes(FunctionImportProcessor.class); assertTrue(types.contains(APPLICATION_XML)); assertTrue(types.contains(APPLICATION_JSON)); } @Test public void defaultSupportedContentTypesForEntityComplexProperty() throws Exception { List<String> types = service.getSupportedContentTypes(EntityComplexPropertyProcessor.class); assertTrue(types.contains(APPLICATION_XML)); assertTrue(types.contains(APPLICATION_JSON)); } @Test public void defaultSupportedContentTypesForEntitySimpleProperty() throws Exception { List<String> types = service.getSupportedContentTypes(EntitySimplePropertyProcessor.class); assertTrue(types.contains(APPLICATION_XML)); assertTrue(types.contains(APPLICATION_JSON)); } @Test public void defaultSupportedContentTypesForEntityLinks() throws Exception { List<String> types = service.getSupportedContentTypes(EntityLinksProcessor.class); assertTrue(types.contains(APPLICATION_XML)); assertTrue(types.contains(APPLICATION_JSON)); } @Test public void defaultSupportedContentTypesForEntityLink() throws Exception { ContentType ctGif = ContentType.create("image", "gif"); List<String> types = service.getSupportedContentTypes(EntityLinkProcessor.class); assertTrue(types.contains(APPLICATION_XML)); assertTrue(types.contains(APPLICATION_JSON)); assertFalse(types.contains(ctGif.toContentTypeString())); } @Test public void defaultSupportedContentTypesAndGifForEntityLink() throws Exception { String ctGif = ContentType.create("image", "gif").toContentTypeString(); when(((CustomContentType) processor).getCustomContentTypes(EntityLinkProcessor.class)).thenReturn(Arrays.asList(ctGif)); List<String> types = service.getSupportedContentTypes(EntityLinkProcessor.class); assertTrue(types.contains(ctGif)); } @Test public void defaultSupportedContentTypesForEntityMedia() throws Exception { List<String> types = service.getSupportedContentTypes(EntityMediaProcessor.class); assertTrue(types.contains(ContentType.WILDCARD.toContentTypeString())); } @Test public void defaultSupportedContentTypesForSimplePropertyValue() throws Exception { List<String> types = service.getSupportedContentTypes(EntitySimplePropertyValueProcessor.class); assertTrue(types.contains(ContentType.WILDCARD.toContentTypeString())); } @Test public void defaultSupportedContentTypesForFunctionImportValue() throws Exception { List<String> types = service.getSupportedContentTypes(FunctionImportValueProcessor.class); assertTrue(types.contains(ContentType.WILDCARD.toContentTypeString())); } @Test public void defaultSupportedContentTypesForBatch() throws Exception { List<String> types = service.getSupportedContentTypes(BatchProcessor.class); assertTrue(types.contains(ContentType.WILDCARD.toContentTypeString())); }
ODataJPAEdmProvider extends EdmProvider { @Override public List<Schema> getSchemas() throws ODataException { if (schemas == null && jpaEdmModel != null) { jpaEdmModel.getBuilder().build(); schemas = new ArrayList<Schema>(); schemas.add(jpaEdmModel.getEdmSchemaView().getEdmSchema()); } if (jpaEdmModel == null) { throw ODataJPAModelException.throwException( ODataJPAModelException.BUILDER_NULL, null); } return schemas; } ODataJPAEdmProvider(); ODataJPAEdmProvider(final ODataJPAContext oDataJPAContext); ODataJPAContext getODataJPAContext(); void setODataJPAContext(final ODataJPAContext jpaContext); @Override EntityContainerInfo getEntityContainerInfo(final String name); @Override EntityType getEntityType(final FullQualifiedName edmFQName); @Override ComplexType getComplexType(final FullQualifiedName edmFQName); @Override Association getAssociation(final FullQualifiedName edmFQName); @Override EntitySet getEntitySet(final String entityContainer, final String name); @Override AssociationSet getAssociationSet(final String entityContainer, final FullQualifiedName association, final String sourceEntitySetName, final String sourceEntitySetRole); @Override FunctionImport getFunctionImport(final String entityContainer, final String name); @Override List<Schema> getSchemas(); }
@Test public void testGetSchemas() { try { assertNotNull(edmProvider.getSchemas()); } catch (ODataException e) { fail(ODataJPATestConstants.EXCEPTION_MSG_PART_1 + e.getMessage() + ODataJPATestConstants.EXCEPTION_MSG_PART_2); } }
Room { public List<Employee> getEmployees() { return employees; } Room(final int id, final String name); String getId(); String getName(); void setName(final String name); void setSeats(final int seats); int getSeats(); void setVersion(final int version); int getVersion(); void setBuilding(final Building building); Building getBuilding(); List<Employee> getEmployees(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override String toString(); }
@Test public void testEmployees() { Employee employee1 = new Employee(1, null); Employee employee2 = new Employee(2, null); List<Employee> employeesList = Arrays.asList(employee1, employee2); Room room1 = new Room(1, null); room1.getEmployees().addAll(employeesList); employee1.setRoom(room1); employee2.setRoom(room1); assertEquals(employeesList, room1.getEmployees()); assertEquals(room1, employee1.getRoom()); }
JPQLSelectStatementBuilder extends JPQLStatementBuilder { @Override public JPQLStatement build() throws ODataJPARuntimeException { jpqlStatement = createStatement(createJPQLQuery()); return jpqlStatement; } JPQLSelectStatementBuilder(final JPQLContextView context); @Override JPQLStatement build(); }
@Test public void testBuildSimpleQuery() throws EdmException, ODataJPARuntimeException { OrderByExpression orderByExpression = EasyMock.createMock(OrderByExpression.class); JPQLSelectContext jpqlSelectContextImpl = createSelectContext(orderByExpression, null); jpqlSelectStatementBuilder = new JPQLSelectStatementBuilder(jpqlSelectContextImpl); assertEquals("SELECT E1 FROM SalesOrderHeader E1", jpqlSelectStatementBuilder.build().toString()); } @Test public void testBuildQueryWithOrderBy() throws EdmException, ODataJPARuntimeException { OrderByExpression orderByExpression = EasyMock.createMock(OrderByExpression.class); JPQLSelectContext jpqlSelectContextImpl = createSelectContext(orderByExpression, null); HashMap<String, String> orderByCollection = new HashMap<String, String>(); orderByCollection.put("E1.soID", "ASC"); orderByCollection.put("E1.buyerId", "DESC"); jpqlSelectContextImpl.setOrderByCollection(orderByCollection); jpqlSelectStatementBuilder = new JPQLSelectStatementBuilder(jpqlSelectContextImpl); assertEquals("SELECT E1 FROM SalesOrderHeader E1 ORDER BY E1.soID ASC , E1.buyerId DESC", jpqlSelectStatementBuilder.build().toString()); } @Test public void testBuildQueryWithFilter() throws EdmException, ODataJPARuntimeException { OrderByExpression orderByExpression = EasyMock.createMock(OrderByExpression.class); FilterExpression filterExpression = null; JPQLSelectContext jpqlSelectContextImpl = createSelectContext(orderByExpression, filterExpression); jpqlSelectContextImpl.setWhereExpression("E1.soID >= 1234"); jpqlSelectStatementBuilder = new JPQLSelectStatementBuilder(jpqlSelectContextImpl); assertEquals("SELECT E1 FROM SalesOrderHeader E1 WHERE E1.soID >= 1234", jpqlSelectStatementBuilder.build().toString()); }
JPQLJoinStatementBuilder extends JPQLStatementBuilder { @Override public JPQLStatement build() throws ODataJPARuntimeException { jpqlStatement = createStatement(createJPQLQuery()); return jpqlStatement; } JPQLJoinStatementBuilder(final JPQLContextView context); @Override JPQLStatement build(); }
@Test public void testBuild() throws Exception { setUp(getJoinClauseList()); JPQLJoinStatementBuilder jpqlJoinStatementBuilder = new JPQLJoinStatementBuilder(context); try { JPQLStatement jpqlStatement = jpqlJoinStatementBuilder.build(); assertEquals("SELECT mat FROM SOHeader soh JOIN soh.soItem soi JOIN soi.material mat WHERE soh.buyerId = 2 AND soh.createdBy = 'Peter' AND soi.shId = soh.soId AND mat.id = 'abc' ORDER BY mat.buyerId asc , mat.city desc", jpqlStatement.toString()); } catch (ODataJPARuntimeException e) { fail("Should not have come here"); } } @Test public void testJoinClauseAsNull() throws Exception { setUp(null); JPQLJoinStatementBuilder jpqlJoinStatementBuilder = new JPQLJoinStatementBuilder(context); try { jpqlJoinStatementBuilder.build(); fail("Should not have come here"); } catch (ODataJPARuntimeException e) { assertTrue(true); } } @Test public void testJoinClauseListAsEmpty() throws Exception { setUp(new ArrayList<JPAJoinClause>()); JPQLJoinStatementBuilder jpqlJoinStatementBuilder = new JPQLJoinStatementBuilder(context); try { jpqlJoinStatementBuilder.build(); fail("Should not have come here"); } catch (ODataJPARuntimeException e) { assertTrue(true); } }