org.apache.olingo.commons.api.edm.EdmEntityType Java Examples

The following examples show how to use org.apache.olingo.commons.api.edm.EdmEntityType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EdmEntityTypeImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void hasStreamInherited() throws Exception {
  CsdlEdmProvider provider = mock(CsdlEdmProvider.class);
  EdmProviderImpl edm = new EdmProviderImpl(provider);

  FullQualifiedName baseName = new FullQualifiedName("namespace", "BaseTypeName");
  CsdlEntityType baseType = new CsdlEntityType();
  baseType.setHasStream(true);
  when(provider.getEntityType(baseName)).thenReturn(baseType);

  FullQualifiedName typeName = new FullQualifiedName("namespace", "typeName");
  CsdlEntityType type = new CsdlEntityType();
  type.setBaseType(baseName);
  EdmEntityType typeWithBaseTypeWithStream = new EdmEntityTypeImpl(edm, typeName, type);
  when(provider.getEntityType(typeName)).thenReturn(type);

  assertTrue(typeWithBaseTypeWithStream.hasStream());
}
 
Example #2
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Consumes all remaining fields of Json ObjectNode and tries to map found values
 * to according Entity fields and omits OData fields to be ignored (e.g., control information).
 *
 * @param edmEntityType edm entity type which for which the json node is consumed
 * @param node json node which is consumed
 * @param entity entity instance which is filled
 * @throws DeserializerException if an exception during consumation occurs
 */
private void consumeRemainingJsonNodeFields(final EdmEntityType edmEntityType, final ObjectNode node,
    final Entity entity) throws DeserializerException {
  final List<String> toRemove = new ArrayList<>();
  Iterator<Entry<String, JsonNode>> fieldsIterator = node.fields();
  while (fieldsIterator.hasNext()) {
    Entry<String, JsonNode> field = fieldsIterator.next();

    if (field.getKey().contains(constants.getBind())) {
      Link bindingLink = consumeBindingLink(field.getKey(), field.getValue(), edmEntityType);
      entity.getNavigationBindings().add(bindingLink);
      toRemove.add(field.getKey());
    }
  }
  // remove here to avoid iterator issues.
  node.remove(toRemove);

  removeAnnotations(node);
}
 
Example #3
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
                          ContentType requestFormat, ContentType responseFormat)
						throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity set which belongs to the requested entity 
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. update the data in backend
	// 2.1. retrieve the payload from the PUT request for the entity to be updated 
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the modification in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	// Note that this updateEntity()-method is invoked for both PUT or PATCH operations
	HttpMethod httpMethod = request.getMethod();
	storage.updateEntityData(edmEntitySet, keyPredicates, requestEntity, httpMethod);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #4
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #5
Source File: ODataJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void geoPoint() throws Exception {
  final EdmEntityType entityType = mockEntityType(EdmPrimitiveTypeKind.GeometryPoint);
  Entity entity = new Entity()
      .addProperty(new Property(null, entityType.getPropertyNames().get(0), ValueType.GEOSPATIAL,
          createPoint(1.5, 4.25)));
  Assert.assertEquals("{\"" + entityType.getPropertyNames().get(0) + "\":{"
      + "\"type\":\"Point\",\"coordinates\":[1.5,4.25]}}",
      IOUtils.toString(serializerNoMetadata.entity(metadata, entityType, entity, null).getContent()));

  Point point = new Point(Dimension.GEOMETRY, null);
  point.setZ(42);
  entity = new Entity().addProperty(new Property(null, entityType.getPropertyNames().get(0), ValueType.GEOSPATIAL,
      point));
  Assert.assertEquals("{\"" + entityType.getPropertyNames().get(0) + "\":{"
      + "\"type\":\"Point\",\"coordinates\":[0.0,0.0,42.0]}}",
      IOUtils.toString(serializerNoMetadata.entity(metadata, entityType, entity, null).getContent()));
}
 
Example #6
Source File: JsonDeltaSerializerWithNavigations.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected void writeEntitySet(final ServiceMetadata metadata, final EdmEntityType entityType,
    final Delta entitySet, final EntityCollectionSerializerOptions options,
    final JsonGenerator json) throws IOException,
    SerializerException {
  json.writeStartArray();
  for (final Entity entity : entitySet.getEntities()) {
    writeAddedUpdatedEntity(metadata, entityType, entity, options.getExpand(), options.getSelect(),
        options.getContextURL(), false, options.getContextURL().getEntitySetOrSingletonOrType(), json,
        options.isFullRepresentation());
  }
  for (final DeletedEntity deletedEntity : entitySet.getDeletedEntities()) {
    writeDeletedEntity(deletedEntity, json);
  }
  for (final DeltaLink addedLink : entitySet.getAddedLinks()) {
    writeLink(addedLink, options, json, true);
  }
  for (final DeltaLink deletedLink : entitySet.getDeletedLinks()) {
    writeLink(deletedLink, options, json, false);
  }
  json.writeEndArray();
}
 
Example #7
Source File: JsonDeltaSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void writeAddedUpdatedEntity(final ServiceMetadata metadata, final EdmEntityType entityType,
    final Entity entity, final ExpandOption expand, final SelectOption select, final ContextURL url,
    final boolean onlyReference, String name, final JsonGenerator json)
    throws IOException, SerializerException {
  json.writeStartObject();
  if (entity.getId() != null && url != null) {
    String entityId = entity.getId().toString();
    name = url.getEntitySetOrSingletonOrType();
    if (!entityId.contains(name)) {
      String entityName = entityId.substring(0, entityId.indexOf("("));
      if (!entityName.equals(name)) {
        json.writeStringField(Constants.JSON_CONTEXT, HASH + entityName + ENTITY);
      }
    }
  }
  json.writeStringField(Constants.JSON_ID, getEntityId(entity, entityType, name));
  writeProperties(metadata, entityType, entity.getProperties(), select, json);
  json.writeEndObject();

}
 
Example #8
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example #9
Source File: Util.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet, List<UriParameter> keyParams)
    throws ODataApplicationException {

    List<Entity> entityList = entitySet.getEntities();

    // loop over all entities in order to find that one that matches all keys in request
    // e.g. contacts(ContactID=1, CompanyID=1)
    for (Entity entity : entityList) {
        boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
        if (foundEntity) {
            return entity;
        }
    }

    return null;
}
 
Example #10
Source File: ODataJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void selectMissingId() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESAllPrim");
  final EdmEntityType entityType = edmEntitySet.getEntityType();
  final Entity entity = data.readAll(edmEntitySet).getEntities().get(0);
  entity.setId(null);
  final SelectItem selectItem1 = ExpandSelectMock.mockSelectItem(edmEntitySet, "PropertyDate");
  final SelectItem selectItem2 = ExpandSelectMock.mockSelectItem(edmEntitySet, "PropertyBoolean");
  final SelectOption select = ExpandSelectMock.mockSelectOption(Arrays.asList(
      selectItem1, selectItem2, selectItem2));
    InputStream result = serializer.entity(metadata, entityType, entity,
          EntitySerializerOptions.with()
              .contextURL(ContextURL.with().entitySet(edmEntitySet)
                  .selectList(helper.buildContextURLSelectList(entityType, null, select))
                  .suffix(Suffix.ENTITY).build())
              .select(select)
              .build()).getContent();
        Assert.assertNotNull(result);   
        final String resultString = IOUtils.toString(result);
         Assert.assertEquals(  "{\"@odata.context\":\"$metadata#ESAllPrim(PropertyInt16,"
   + "PropertyBoolean,PropertyDate)/$entity\","+
         "\"@odata.metadataEtag\":\"W/\\\"metadataETag\\\"\",\"@odata.id\":\"ESAllPrim(32767)\","+
          "\"PropertyInt16\":32767,\"PropertyBoolean\":true,\"PropertyDate\":\"2012-12-03\"}",
        resultString);   
}
 
Example #11
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList)
    throws ODataApplicationException {

  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #12
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected EdmEntityType resolveEntityType(final ServiceMetadata metadata, final EdmEntityType baseType,
    final String derivedTypeName) throws SerializerException {
  if (derivedTypeName == null ||
      baseType.getFullQualifiedName().getFullQualifiedNameAsString().equals(derivedTypeName)) {
    return baseType;
  }
  EdmEntityType derivedType = metadata.getEdm().getEntityType(new FullQualifiedName(derivedTypeName));
  if (derivedType == null) {
    throw new SerializerException("EntityType not found",
        SerializerException.MessageKeys.UNKNOWN_TYPE, derivedTypeName);
  }
  EdmEntityType type = derivedType.getBaseType();
  while (type != null) {
    if (type.getFullQualifiedName().equals(baseType.getFullQualifiedName())) {
      return derivedType;
    }
    type = type.getBaseType();
  }
  throw new SerializerException("Wrong base type",
      SerializerException.MessageKeys.WRONG_BASE_TYPE, derivedTypeName,
          baseType.getFullQualifiedName().getFullQualifiedNameAsString());
}
 
Example #13
Source File: EdmTypeValidator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * This method validates Edm Entity types.
 * Looks for correct namespace aliases and correct base types
 */
private void validateEdmEntityTypes() {
  for (Map.Entry<FullQualifiedName, EdmEntityType> entityTypes : edmEntityTypesMap.entrySet()) {
    if (entityTypes.getValue() != null && entityTypes.getKey() != null) {
      EdmEntityType entityType = entityTypes.getValue();
      if (entityType.getBaseType() != null) {
        FullQualifiedName baseTypeFQName = entityType.getBaseType().getFullQualifiedName();
        EdmEntityType baseEntityType = edmEntityTypesMap.get(baseTypeFQName);
        
        if (baseEntityType != null && baseEntityType.getKeyPredicateNames().isEmpty()) {
          throw new RuntimeException("Missing key for EntityType " + baseEntityType.getName());
        }
      } else if (entityType.getKeyPredicateNames().isEmpty()) {
        throw new RuntimeException("Missing key for EntityType " + entityType.getName());
      }
    }
  }

}
 
Example #14
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example #15
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #16
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private List<Entity> getMatch(UriParameter param, List<Entity> es)
    throws ODataApplicationException {
  ArrayList<Entity> list = new ArrayList<Entity>();
  for (Entity entity : es) {

    EdmEntityType entityType = this.metadata.getEdm().getEntityType(
        new FullQualifiedName(entity.getType()));

    EdmProperty property = (EdmProperty) entityType.getProperty(param.getName());
    EdmType type = property.getType();
    if (type.getKind() == EdmTypeKind.PRIMITIVE) {
      Object match = readPrimitiveValue(property, param.getText());
      Property entityValue = entity.getProperty(param.getName());
      if (match.equals(entityValue.asPrimitive())) {
        list.add(entity);
      }
    } else {
      throw new RuntimeException("Can not compare complex objects");
    }
  }
  return list;
}
 
Example #17
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example #18
Source File: ExpressionParserTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test(expected = UriParserSemanticException.class)
public void testPropertyPathExpWithoutProperty() throws Exception {
  final String entitySetName = "ESName";
  final String keyPropertyName = "a";
  EdmProperty keyProperty = mockProperty(keyPropertyName, 
      OData.newInstance().createPrimitiveTypeInstance(EdmPrimitiveTypeKind.String));
  EdmKeyPropertyRef keyPropertyRef = mockKeyPropertyRef(keyPropertyName, keyProperty);
  EdmEntityType entityType = mockEntityType(keyPropertyName, keyPropertyRef);
  Mockito.when(entityType.getFullQualifiedName()).thenReturn(new FullQualifiedName("test.ETName"));
  EdmEntitySet entitySet = mockEntitySet(entitySetName, entityType);
  EdmEntityContainer container = mockContainer(entitySetName, entitySet);
  Edm mockedEdm = Mockito.mock(Edm.class);
  Mockito.when(mockedEdm.getEntityContainer()).thenReturn(container);
  
  UriTokenizer tokenizer = new UriTokenizer("a eq \'abc\'");
  new ExpressionParser(mockedEdm, odata).parse(tokenizer, entityType, null, null);
}
 
Example #19
Source File: ODataJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void selectComplex() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESFourKeyAlias");
  final EdmEntityType entityType = edmEntitySet.getEntityType();
  final EntityCollection entitySet = data.readAll(edmEntitySet);
 final SelectOption select = ExpandSelectMock.mockSelectOption(Arrays.asList(
      ExpandSelectMock.mockSelectItem(edmEntitySet, "PropertyInt16"),
      ExpandSelectMock.mockSelectItem(edmEntitySet,"PropertyCompComp", "PropertyComp", "PropertyString")));
  InputStream result = serializer
      .entityCollection(metadata, entityType, entitySet,
          EntityCollectionSerializerOptions.with()
              .contextURL(ContextURL.with().entitySet(edmEntitySet)
                  .selectList(helper.buildContextURLSelectList(entityType, null, select))
                  .build())
              .select(select)
              .build()).getContent();
  final String resultString = IOUtils.toString(result);
  final String expected = "{"
      +     "\"@odata.context\":\"$metadata#ESFourKeyAlias"
      +        "(PropertyInt16,PropertyCompComp/PropertyComp/PropertyString)\"," 
      +     "\"@odata.metadataEtag\":\"W/\\\"metadataETag\\\"\","
      +     "\"value\":[" 
      +     "{" 
      +         "\"@odata.id\":\""
      +         "ESFourKeyAlias(PropertyInt16=1,KeyAlias1=11,KeyAlias2='Num11',KeyAlias3='Num111')\"," 
      +         "\"PropertyInt16\":1," 
      +         "\"PropertyCompComp\":{" 
      +             "\"PropertyComp\":{" 
      +             "\"@odata.type\":\"#olingo.odata.test1.CTBase\"," 
      +             "\"PropertyString\":\"Num111\"" 
      +     "}}}]}";

 Assert.assertEquals(expected, resultString);
}
 
Example #20
Source File: ODataWritableContent.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public StreamContent(EntityIterator iterator, EdmEntityType entityType, ServiceMetadata metadata,
    EntityCollectionSerializerOptions options) {
  this.iterator = iterator;
  this.entityType = entityType;
  this.metadata = metadata;
  this.options = options;
}
 
Example #21
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void deleteEntityData(EdmEntitySet edmEntitySet, List<UriParameter> keyParams)
    throws ODataApplicationException {

  EdmEntityType edmEntityType = edmEntitySet.getEntityType();

  if (edmEntitySet.getName().equals(DemoEdmProvider.ES_PRODUCTS_NAME)) {
    deleteEntity(edmEntityType, keyParams, productList);
  } else if(edmEntitySet.getName().equals(DemoEdmProvider.ES_CATEGORIES_NAME)) {
    deleteEntity(edmEntityType, keyParams, categoryList);
  }
}
 
Example #22
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public Entity readEntityData(EdmEntitySet edmEntitySet, List<UriParameter> keyParams) throws ODataApplicationException{

		EdmEntityType edmEntityType = edmEntitySet.getEntityType();

		// actually, this is only required if we have more than one Entity Type
		if(edmEntityType.getName().equals(DemoEdmProvider.ET_PRODUCT_NAME)){
			return getProduct(edmEntityType, keyParams);
		}

		return null;
	}
 
Example #23
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void deleteEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  Entity entity = getEntity(edmEntityType, keyParams, entityList);
  if (entity == null) {
    throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  entityList.remove(entity);
}
 
Example #24
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public Entity createEntityData(EdmEntitySet edmEntitySet, Entity entityToCreate, String rawServiceUri) 
    throws ODataApplicationException {

  EdmEntityType edmEntityType = edmEntitySet.getEntityType();

  if (edmEntitySet.getName().equals(DemoEdmProvider.ES_PRODUCTS_NAME)) {
    return createEntity(edmEntitySet, edmEntityType, entityToCreate, 
        manager.getEntityCollection(DemoEdmProvider.ES_PRODUCTS_NAME), rawServiceUri);
  } else if(edmEntitySet.getName().equals(DemoEdmProvider.ES_CATEGORIES_NAME)) {
    return createEntity(edmEntitySet, edmEntityType, entityToCreate, 
        manager.getEntityCollection(DemoEdmProvider.ES_CATEGORIES_NAME), rawServiceUri);
  }

  return null;
}
 
Example #25
Source File: UriResourceImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void uriResourceStartingTypeFilterImpl() {
  EdmEntityType entityType = edm.getEntityType(EntityTypeProvider.nameETTwoKeyNav);

  UriResourceStartingTypeFilterImpl impl = new UriResourceStartingTypeFilterImpl(entityType, false);
  assertEquals("olingo.odata.test1.ETTwoKeyNav", impl.toString());
  assertEquals(entityType, impl.getType());
  assertFalse(impl.isCollection());

  impl = new UriResourceStartingTypeFilterImpl(entityType, true);
  assertTrue(impl.isCollection());
  impl.setKeyPredicates(Collections.singletonList(
      (UriParameter) new UriParameterImpl().setName("ParameterInt16")));
  assertFalse(impl.isCollection());
}
 
Example #26
Source File: EdmKeyPropertyRefImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test(expected = EdmException.class)
public void aliasForPropertyInComplexPropertyButWrongPath2() {
  CsdlPropertyRef providerRef = new CsdlPropertyRef().setName("wrong/Id").setAlias("alias");
  EdmEntityType etMock = mock(EdmEntityType.class);
  EdmProperty keyPropertyMock = mock(EdmProperty.class);
  EdmElement compMock = mock(EdmProperty.class);
  EdmComplexType compTypeMock = mock(EdmComplexType.class);
  when(compTypeMock.getProperty("Id")).thenReturn(keyPropertyMock);
  when(compMock.getType()).thenReturn(compTypeMock);
  when(etMock.getProperty("comp")).thenReturn(compMock);
  new EdmKeyPropertyRefImpl(etMock, providerRef).getProperty();
}
 
Example #27
Source File: TechnicalActionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * @param entitySet
 * @param edmType
 * @param edmEntityType
 * @return
 */
private EdmEntitySet getTypeCastedEntitySet(EdmEntitySet entitySet, EdmEntityType edmEntityType) {
  EdmEntityContainer container = serviceMetadata.getEdm().getEntityContainer();
  List<EdmEntitySet> entitySets = container.getEntitySets();
  for (EdmEntitySet enSet : entitySets) {
    if (enSet.getEntityType().getFullQualifiedName().getFullQualifiedNameAsString().equals
        (edmEntityType.getFullQualifiedName().getFullQualifiedNameAsString())) {
      entitySet = enSet;
      break;
    }
  }
  return entitySet;
}
 
Example #28
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType responseFormat) throws ODataApplicationException, SerializerException {

  // 1st retrieve the requested EntitySet from the uriInfo (representation of the parsed URI)
  List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
  // in our example, the first segment is the EntitySet
  UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
  EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

  // 2nd: fetch the data from backend for this requested EntitySetName
  // it has to be delivered as EntitySet object
  EntityCollection entitySet = storage.readEntitySetData(edmEntitySet);

  // 3rd: create a serializer based on the requested format (json)
  ODataSerializer serializer = odata.createSerializer(responseFormat);

  // and serialize the content: transform from the EntitySet object to InputStream
  EdmEntityType edmEntityType = edmEntitySet.getEntityType();
  ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build();

  final String id = request.getRawBaseUri() + "/" + edmEntitySet.getName();
  EntityCollectionSerializerOptions opts =
      EntityCollectionSerializerOptions.with().id(id).contextURL(contextUrl).build();
  SerializerResult serializedContent = serializer.entityCollection(serviceMetadata, edmEntityType, entitySet, opts);

  // Finally: configure the response object: set the body, headers and status code
  response.setContent(serializedContent.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #29
Source File: ExpressionParserTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLambdaPropertyPathExp() throws Exception {
  final String entitySetName = "ESName";
  final String keyPropertyName = "a";
  final String complexPropertyName = "comp";
  final String propertyName = "prop";
  EdmProperty keyProperty = mockProperty(keyPropertyName, 
      OData.newInstance().createPrimitiveTypeInstance(EdmPrimitiveTypeKind.String));
  EdmKeyPropertyRef keyPropertyRef = mockKeyPropertyRef(keyPropertyName, keyProperty);
  EdmProperty property = mockProperty(propertyName, 
      OData.newInstance().createPrimitiveTypeInstance(EdmPrimitiveTypeKind.String));
  
  EdmComplexType complexType = mockComplexType(propertyName, property);
  EdmProperty complexProperty = mockProperty(complexPropertyName, complexType);
  Mockito.when(complexProperty.isCollection()).thenReturn(true);
  
  EdmEntityType entityType = mockEntityType(keyPropertyName, keyPropertyRef);
  Mockito.when(entityType.getPropertyNames()).thenReturn(Arrays.asList(keyPropertyName, complexPropertyName));
  Mockito.when(entityType.getProperty(keyPropertyName)).thenReturn(keyProperty);
  Mockito.when(entityType.getProperty(complexPropertyName)).thenReturn(complexProperty);
  Mockito.when(entityType.getFullQualifiedName()).thenReturn(new FullQualifiedName("test.ET"));
  EdmEntitySet entitySet = mockEntitySet(entitySetName, entityType);
  EdmEntityContainer container = mockContainer(entitySetName, entitySet);
  Edm mockedEdm = Mockito.mock(Edm.class);
  Mockito.when(mockedEdm.getEntityContainer()).thenReturn(container);
  
  UriTokenizer tokenizer = new UriTokenizer("comp/any(d:d/prop eq \'abc\')");
  Expression expression = new ExpressionParser(mockedEdm, odata).parse(tokenizer, 
      entityType, null, null);
  assertNotNull(expression);
  assertEquals("[comp, any]", expression.toString());
  
  tokenizer = new UriTokenizer("comp/all(d:d/prop eq \'abc\')");
  expression = new ExpressionParser(mockedEdm, odata).parse(tokenizer, 
      entityType, null, null);
  assertNotNull(expression);
  assertEquals("[comp, all]", expression.toString());
}
 
Example #30
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public Entity read(final EdmEntitySet edmEntitySet, final List<UriParameter> keys) throws DataProviderException {
  final EdmEntityType entityType = edmEntitySet.getEntityType();
  final EntityCollection entitySet = data.get(edmEntitySet.getName());
  if (entitySet == null) {
    return null;
  } else {
    try {
      for (final Entity entity : entitySet.getEntities()) {
        boolean found = true;
        for (final UriParameter key : keys) {
          final EdmProperty property = (EdmProperty) entityType.getProperty(key.getName());
          final EdmPrimitiveType type = (EdmPrimitiveType) property.getType();
          if (!type.valueToString(entity.getProperty(key.getName()).getValue(),
              property.isNullable(), property.getMaxLength(), property.getPrecision(), property.getScale(),
              property.isUnicode())
              .equals(key.getText())) {
            found = false;
            break;
          }
        }
        if (found) {
          return entity;
        }
      }
      return null;
    } catch (final EdmPrimitiveTypeException e) {
      throw new DataProviderException("Wrong key!", e);
    }
  }
}