org.apache.olingo.commons.api.data.Entity Java Examples

The following examples show how to use org.apache.olingo.commons.api.data.Entity. 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: 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 #2
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 #3
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private SerializerResult serializeEntity(final ODataRequest request, final Entity entity,
    final EdmEntitySet edmEntitySet, final EdmEntityType edmEntityType,
    final ContentType requestedFormat,
    final ExpandOption expand, final SelectOption select, final boolean isContNav)
    throws ODataLibraryException {

  ContextURL contextUrl = isODataMetadataNone(requestedFormat) ? null :
      getContextUrl(request.getRawODataPath(), edmEntitySet, edmEntityType, true, expand, select,isContNav);
  return odata.createSerializer(requestedFormat, request.getHeaders(HttpHeader.ODATA_VERSION)).entity(
      serviceMetadata,
      edmEntityType,
      entity,
      EntitySerializerOptions.with()
          .contextURL(contextUrl)
          .expand(expand).select(select)
          .build());
}
 
Example #4
Source File: JSONTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * @return
 */
private Entity createEntity() {
  Entity en = new Entity();
  Property p1 = new Property();
  p1.setName("Id");
  p1.setType("Int64");
  p1.setValue(ValueType.PRIMITIVE, Long.valueOf(123));
  en.addProperty(p1);
  
  Property p2 = new Property();
  p2.setName("Name");
  p2.setType("String");
  p2.setValue(ValueType.PRIMITIVE, "ABC");
  en.addProperty(p2);
  return en;
}
 
Example #5
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 #6
Source File: JSONTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * @param entity
 */
private void setNavigationBindingLinkOnEntity(ResWrap<Entity> entity) {
  Link entityLink = new Link();
  Entity en = createEntity();
  
  entityLink.setBindingLink("Photos");
  entityLink.setInlineEntity(en);
  entityLink.setType("Microsoft.OData.SampleService.Models.TripPin.Photos");
  
  Link entityColLink = new Link();
  EntityCollection enCol = new EntityCollection();
  enCol.getEntities().add(en);
  
  entityColLink.setBindingLink("Friends");
  entityColLink.setInlineEntitySet(enCol);
  entityColLink.setType("Microsoft.OData.SampleService.Models.TripPin.Friends");
  
  Link link = new Link();
  link.setBindingLink("Trips");
  link.setType("Microsoft.OData.SampleService.Models.TripPin.Trips");
  
  entity.getPayload().getNavigationBindings().add(entityLink);
  entity.getPayload().getNavigationBindings().add(entityColLink);
  entity.getPayload().getNavigationBindings().add(link);
}
 
Example #7
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void createReference(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat) throws ODataApplicationException, ODataLibraryException {

  final ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
  final DeserializerResult references = deserializer.entityReferences(request.getBody());

  if (references.getEntityReferences().size() != 1) {
    throw new ODataApplicationException("A post request to a collection navigation property must "
        + "contain a single entity reference", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
  }

  final Entity entity = readEntity(uriInfo, true);
  final UriResourceNavigation navigationProperty = getLastNavigation(uriInfo);
  ensureNavigationPropertyNotNull(navigationProperty);
  dataProvider.createReference(entity, navigationProperty.getProperty(), references.getEntityReferences().get(0),
      request.getRawBaseUri());

  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #8
Source File: TripPinHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void upsertMediaStream(MediaRequest request, String entityETag, InputStream mediaContent,
    NoContentResponse response) throws ODataLibraryException, ODataApplicationException {
  final EdmEntitySet edmEntitySet = request.getEntitySet();
  List<UriParameter> keys = request.getKeyPredicates();
  Entity entity = this.dataModel.getEntity(edmEntitySet.getName(), keys);

  if (mediaContent == null) {
    boolean deleted = this.dataModel.deleteMedia(entity);
    if (deleted) {
      response.writeNoContent();
    } else {
      response.writeNotFound();
    }
  } else {
    boolean updated = this.dataModel.updateMedia(entity, mediaContent);
    if (updated) {
      response.writeNoContent();
    } else {
      response.writeServerError(true);
    }
  }
}
 
Example #9
Source File: AtomSerializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void write(final Writer writer, final T obj) throws ODataSerializerException {
  try {
    if (obj instanceof EntityCollection) {
      entitySet(writer, (EntityCollection) obj);
    } else if (obj instanceof Entity) {
      entity(writer, (Entity) obj);
    } else if (obj instanceof Property) {
      property(writer, (Property) obj);
    } else if (obj instanceof Link) {
      link(writer, (Link) obj);
    }
  } catch (final XMLStreamException | EdmPrimitiveTypeException e) {
    throw new ODataSerializerException(e);
  }
}
 
Example #10
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity readEntityByBindingLink(final String entityId, final EdmEntitySet edmEntitySet, 
    final String rawServiceUri) throws ODataApplicationException {
  
  UriResourceEntitySet entitySetResource = null;
  try {
    entitySetResource = odata.createUriHelper().parseEntityId(edm, entityId, rawServiceUri);
    
    if(!entitySetResource.getEntitySet().getName().equals(edmEntitySet.getName())) {
      throw new ODataApplicationException("Execpted an entity-id for entity set " + edmEntitySet.getName() 
        + " but found id for entity set " + entitySetResource.getEntitySet().getName(), 
        HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ENGLISH);
    }
  } catch (DeserializerException e) {
    throw new ODataApplicationException(entityId + " is not a valid entity-Id", 
        HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ENGLISH);
  }

  return readEntityData(entitySetResource.getEntitySet(), entitySetResource.getKeyPredicates());
}
 
Example #11
Source File: QueryHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method applies filter query option to the given entity collection.
 *
 * @param filterOption Filter option
 * @param entitySet    Entity collection
 * @param edmEntitySet Entity set
 * @throws ODataApplicationException
 */
public static void applyFilterSystemQuery(final FilterOption filterOption, final EntityCollection entitySet,
                                          final EdmBindingTarget edmEntitySet) throws ODataApplicationException {
    try {
        final Iterator<Entity> iter = entitySet.getEntities().iterator();
        while (iter.hasNext()) {
            final VisitorOperand operand =
                    filterOption.getExpression().accept(new ExpressionVisitorImpl(iter.next(), edmEntitySet));
            final TypedOperand typedOperand = operand.asTypedOperand();

            if (typedOperand.is(ODataConstants.primitiveBoolean)) {
                if (Boolean.FALSE.equals(typedOperand.getTypedValue(Boolean.class))) {
                    iter.remove();
                }
            } else {
                throw new ODataApplicationException(
                        "Invalid filter expression. Filter expressions must return a value of " +
                        "type Edm.Boolean", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
            }
        }

    } catch (ExpressionVisitException e) {
        throw new ODataApplicationException("Exception in filter evaluation",
                                            HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT);
    }
}
 
Example #12
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getFlightTo(int flighID) {
  Map<String, Object> map = this.flightLinks.get(flighID);
  if (map == null) {
    return null;
  }

  String to = (String) map.get("To");
  EntityCollection set = getEntitySet("Airports");

  if (to != null) {
    for (Entity e : set.getEntities()) {
      if (e.getProperty("IataCode").getValue().equals(to)) {
        return e;
      }
    }
  }
  return null;
}
 
Example #13
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public EntityCollection getEntitySet(String name, int skip, int pageSize) {
  EntityCollection set = this.entitySetMap.get(name);
  if (set == null) {
    return null;
  }

  EntityCollection modifiedES = new EntityCollection();
  int i = 0;
  for (Entity e : set.getEntities()) {
    if (skip >= 0 && i >= skip && modifiedES.getEntities().size() < pageSize) {
      modifiedES.getEntities().add(e);
    }
    i++;
  }
  modifiedES.setCount(i);
  set.setCount(i);

  if (skip == -1 && pageSize == -1) {
    return set;
  }
  return modifiedES;
}
 
Example #14
Source File: DataCreator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected static void setLinks(final Entity entity, final String navigationPropertyName, final Entity... targets) {
  Link link = entity.getNavigationLink(navigationPropertyName);
  if (link == null) {
    link = new Link();
    link.setRel(Constants.NS_NAVIGATION_LINK_REL + navigationPropertyName);
    link.setType(Constants.ENTITY_SET_NAVIGATION_LINK_TYPE);
    link.setTitle(navigationPropertyName);
    EntityCollection target = new EntityCollection();
    target.getEntities().addAll(Arrays.asList(targets));
    link.setInlineEntitySet(target);
    link.setHref(entity.getId().toASCIIString() + "/" + navigationPropertyName);
    entity.getNavigationLinks().add(link);
  } else {
    link.getInlineEntitySet().getEntities().addAll(Arrays.asList(targets));
  }
}
 
Example #15
Source File: EdmAssistedJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void entityCollectionWithComplexCollection() throws Exception {
  final EdmEntitySet entitySet = entityContainer.getEntitySet("ESMixPrimCollComp");
  ComplexValue complexValue1 = new ComplexValue();
  complexValue1.getValue().add(new Property(null, "PropertyInt16", ValueType.PRIMITIVE, 1));
  complexValue1.getValue().add(new Property(null, "PropertyString", ValueType.PRIMITIVE, "one"));
  ComplexValue complexValue2 = new ComplexValue();
  complexValue2.getValue().add(new Property(null, "PropertyInt16", ValueType.PRIMITIVE, 2));
  complexValue2.getValue().add(new Property(null, "PropertyString", ValueType.PRIMITIVE, "two"));
  ComplexValue complexValue3 = new ComplexValue();
  complexValue3.getValue().add(new Property(null, "PropertyInt16", ValueType.PRIMITIVE, 3));
  complexValue3.getValue().add(new Property(null, "PropertyString", ValueType.PRIMITIVE, "three"));
  EntityCollection entityCollection = new EntityCollection();
  entityCollection.getEntities().add(new Entity()
      .addProperty(new Property(null, "CollPropertyComp", ValueType.COLLECTION_COMPLEX,
          Arrays.asList(complexValue1, complexValue2, complexValue3))));
  Assert.assertEquals("{\"@odata.context\":\"$metadata#ESMixPrimCollComp(CollPropertyComp)\","
      + "\"value\":[{\"@odata.id\":null,"
      + "\"CollPropertyComp\":["
      + "{\"PropertyInt16\":1,\"PropertyString\":\"one\"},"
      + "{\"PropertyInt16\":2,\"PropertyString\":\"two\"},"
      + "{\"PropertyInt16\":3,\"PropertyString\":\"three\"}]}]}",
      serialize(serializer, metadata, entitySet, entityCollection, "CollPropertyComp"));
}
 
Example #16
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getProduct(EdmEntityType edmEntityType, List<UriParameter> keyParams) throws ODataApplicationException{

		// the list of entities at runtime
		EntityCollection entitySet = getProducts();
		
		/*  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 #17
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void readMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  
  final UriResource firstResoucePart = uriInfo.getUriResourceParts().get(0);
  if(firstResoucePart instanceof UriResourceEntitySet) {
    final EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
    final UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) firstResoucePart;
    
    final Entity entity = storage.readEntityData(edmEntitySet, uriResourceEntitySet.getKeyPredicates());
    if(entity == null) {
      throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), 
          Locale.ENGLISH);
    }

    final byte[] mediaContent = storage.readMedia(entity);
    final InputStream responseContent = odata.createFixedFormatSerializer().binary(mediaContent);
    
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setContent(responseContent);
    response.setHeader(HttpHeader.CONTENT_TYPE, entity.getMediaContentType());
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.BAD_REQUEST.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #18
Source File: DataCreator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void linkCollPropCompInESCompMixPrimCollCompToETTwoKeyNav(Map<String, EntityCollection> data2) {
  EntityCollection collection = data.get("ESCompMixPrimCollComp");
  Entity entity = collection.getEntities().get(0);
  ComplexValue complexValue = entity.getProperties().get(1).asComplex();
  List<ComplexValue> innerComplexValue = (List<ComplexValue>) complexValue.getValue().get(3).asCollection();
  final List<Entity> esTwoKeyNavTargets = data.get("ESTwoKeyNav").getEntities();
  for (ComplexValue innerValue : innerComplexValue) {
    Link link = new Link();
    link.setRel(Constants.NS_NAVIGATION_LINK_REL + "NavPropertyETTwoKeyNavOne");
    link.setType(Constants.ENTITY_NAVIGATION_LINK_TYPE);
    link.setTitle("NavPropertyETTwoKeyNavOne");
    link.setHref(esTwoKeyNavTargets.get(1).getId().toASCIIString());
    innerValue.getNavigationLinks().add(link);
    link.setInlineEntity(esTwoKeyNavTargets.get(1));
  }
}
 
Example #19
Source File: DataCreator.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private EntityCollection createESAllKey(final Edm edm, final OData odata) {
  EntityCollection entityCollection = new EntityCollection();

  entityCollection.getEntities().add(new Entity()
      .addProperty(createPrimitive("PropertyString", "First"))
      .addProperty(createPrimitive("PropertyBoolean", true))
      .addProperty(createPrimitive("PropertyByte", (short) 255))
      .addProperty(createPrimitive("PropertySByte", Byte.MAX_VALUE))
      .addProperty(createPrimitive("PropertyInt16", Short.MAX_VALUE))
      .addProperty(createPrimitive("PropertyInt32", Integer.MAX_VALUE))
      .addProperty(createPrimitive("PropertyInt64", Long.MAX_VALUE))
      .addProperty(createPrimitive("PropertyDecimal", BigDecimal.valueOf(34)))
      .addProperty(createPrimitive("PropertyDate", getDate(2012, 12, 3)))
      .addProperty(createPrimitive("PropertyDateTimeOffset", getDateTime(2012, 12, 3, 7, 16, 23)))
      .addProperty(createPrimitive("PropertyDuration", BigDecimal.valueOf(6)))
      .addProperty(createPrimitive("PropertyGuid", GUID))
      .addProperty(createPrimitive("PropertyTimeOfDay", getTime(2, 48, 21))));

  entityCollection.getEntities().add(new Entity()
      .addProperty(createPrimitive("PropertyString", "Second"))
      .addProperty(createPrimitive("PropertyBoolean", true))
      .addProperty(createPrimitive("PropertyByte", (short) 254))
      .addProperty(createPrimitive("PropertySByte", (byte) 124))
      .addProperty(createPrimitive("PropertyInt16", (short) 32764))
      .addProperty(createPrimitive("PropertyInt32", 2147483644))
      .addProperty(createPrimitive("PropertyInt64", 9223372036854775804L))
      .addProperty(createPrimitive("PropertyDecimal", BigDecimal.valueOf(34)))
      .addProperty(createPrimitive("PropertyDate", getDate(2012, 12, 3)))
      .addProperty(createPrimitive("PropertyDateTimeOffset", getDateTime(2012, 12, 3, 7, 16, 23)))
      .addProperty(createPrimitive("PropertyDuration", BigDecimal.valueOf(6)))
      .addProperty(createPrimitive("PropertyGuid", GUID))
      .addProperty(createPrimitive("PropertyTimeOfDay", getTime(2, 48, 21))));

  setEntityType(entityCollection, edm.getEntityType(EntityTypeProvider.nameETAllKey));
  createEntityId(edm, odata, "ESAllKey", entityCollection);
  createOperations( "ESAllKey", entityCollection, EntityTypeProvider.nameETAllKey);
  return entityCollection;
}
 
Example #20
Source File: EdmAssistedJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected void doSerialize(final EdmEntityType entityType, final AbstractEntityCollection entityCollection,
    final String contextURLString, final String metadataETag, JsonGenerator json)
    throws IOException, SerializerException {

  json.writeStartObject();

  metadata(contextURLString, metadataETag, null, null, entityCollection.getId(), false, json);

  if (entityCollection.getCount() != null) {
    if (isIEEE754Compatible) {
      json.writeStringField(Constants.JSON_COUNT, Integer.toString(entityCollection.getCount()));
    } else {
      json.writeNumberField(Constants.JSON_COUNT, entityCollection.getCount());
    }
  }
  if (entityCollection.getDeltaLink() != null) {
    json.writeStringField(Constants.JSON_DELTA_LINK, entityCollection.getDeltaLink().toASCIIString());
  }

  for (final Annotation annotation : entityCollection.getAnnotations()) {
    valuable(json, annotation, '@' + annotation.getTerm(), null, null);
  }

  json.writeArrayFieldStart(Constants.VALUE);
  for (final Entity entity : entityCollection) {
    doSerialize(entityType, entity, null, null, json);
  }
  json.writeEndArray();

  if (entityCollection.getNext() != null) {
    json.writeStringField(Constants.JSON_NEXT_LINK, entityCollection.getNext().toASCIIString());
  }

  json.writeEndObject();
}
 
Example #21
Source File: ODataJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test(expected = SerializerException.class)
public void entityAllPrimKeyNull() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESAllPrim");
  Entity entity = data.readAll(edmEntitySet).getEntities().get(0);
  entity.getProperties().clear();
  serializer.entity(metadata, edmEntitySet.getEntityType(), entity,
      EntitySerializerOptions.with()
          .contextURL(ContextURL.with().entitySet(edmEntitySet).suffix(Suffix.ENTITY).build())
          .build());
}
 
Example #22
Source File: ODataXmlSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void writeReference(final Entity entity, final ContextURL contextURL, final XMLStreamWriter writer,
    final boolean top)
    throws XMLStreamException {
  writer.writeStartElement(METADATA, "ref", NS_METADATA);
  if (top) {
    writer.writeNamespace(METADATA, NS_METADATA);
    if (contextURL != null) { // top-level entity
      writer.writeAttribute(METADATA, NS_METADATA, Constants.CONTEXT,
          ContextURLBuilder.create(contextURL).toASCIIString());
    }
  }
  writer.writeAttribute(Constants.ATOM_ATTR_ID, entity.getId().toASCIIString());
  writer.writeEndElement();
}
 
Example #23
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void bindingOperationNullOnToOneNull() throws Exception {
  String entityString =
      "{\"PropertyInt16\":32767,"
          + "\"PropertyString\":\"First Resource - positive values\","
          + "\"[email protected]\":null"
          + "}";
  
  final Entity entity = deserialize(entityString, "ETTwoPrim");
  assertEquals("First Resource - positive values", entity.getProperty("PropertyString").asPrimitive());
  assertNull(entity.getNavigationBinding("NavPropertyETAllPrimOne").getBindingLink());
}
 
Example #24
Source File: JsonDeltaSerializerWithNavigationsTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIdAnnotationWithNavigationManyInDelta() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESDelta");
  Delta delta = new Delta();
  final Entity entity = data.readAll(edmEntitySet).getEntities().get(1);
  final Entity entity2 = data.readAll(edmEntitySet).getEntities().get(2);
  final ExpandOption expand = ExpandSelectMock.mockExpandOption(Collections.singletonList(
      ExpandSelectMock.mockExpandItem(edmEntitySet, "NavPropertyETBaseContTwoContMany")));
  List<Entity> addedEntity = new ArrayList<Entity>();
  Entity changedEntity = new Entity();
  changedEntity.setId(entity2.getId());
  changedEntity.addProperty(entity2.getProperty("PropertyString"));
  addedEntity.add(entity);
  addedEntity.add(changedEntity);
  delta.getEntities().addAll(addedEntity);
   InputStream stream = ser.entityCollection(metadata, edmEntitySet.getEntityType(), delta ,
      EntityCollectionSerializerOptions.with()
      .contextURL(ContextURL.with().entitySet(edmEntitySet).build()).expand(expand)
      .build()).getContent();
     String jsonString = IOUtils.toString(stream);
     final String expectedResult = "{\"@context\":\"$metadata#ESDelta/$delta\","
         + "\"value\":[{\"@id\":\"ESDelta(-32768)\",\"PropertyInt16\":-32768,"
         + "\"PropertyString\":\"Number:-32768\","
         + "\"NavPropertyETBaseContTwoContMany@delta\":"
         + "[{\"@id\":\"ESDelta(-32768)/NavPropertyETBaseContTwoContMany"
         + "(PropertyInt16=222,PropertyString='TEST%20B')\","
         + "\"PropertyInt16\":222,\"PropertyString\":\"TEST B\"},"
         + "{\"@id\":\"ESDelta(-32768)/NavPropertyETBaseContTwoContMany"
         + "(PropertyInt16=333,PropertyString='TEST%20C')\",\"PropertyInt16\":333,"
         + "\"PropertyString\":\"TEST C\"}]},{\"@id\":\"ESDelta(0)\","
         + "\"PropertyString\":\"Number:0\",\"NavPropertyETBaseContTwoContMany\":[]}]}";
     Assert.assertNotNull(jsonString);
     Assert.assertEquals(expectedResult, jsonString);
   }
 
Example #25
Source File: ODataJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void expandSelect() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESTwoPrim");
  final EdmEntityType entityType = edmEntitySet.getEntityType();
  final Entity entity = data.readAll(edmEntitySet).getEntities().get(3);
  final SelectOption select = ExpandSelectMock.mockSelectOption(Collections.singletonList(
      ExpandSelectMock.mockSelectItem(entityContainer.getEntitySet("ESAllPrim"), "PropertyDate")));
  ExpandItem expandItem = ExpandSelectMock.mockExpandItem(edmEntitySet, "NavPropertyETAllPrimOne");
  Mockito.when(expandItem.getSelectOption()).thenReturn(select);
  final ExpandOption expand = ExpandSelectMock.mockExpandOption(Collections.singletonList(expandItem));
  final String resultString = IOUtils.toString(serializer
      .entity(metadata, entityType, entity,
          EntitySerializerOptions.with()
              .contextURL(ContextURL.with().entitySet(edmEntitySet)
                  .selectList(helper.buildContextURLSelectList(entityType, expand, select))
                  .suffix(Suffix.ENTITY).build())
              .expand(expand)
              .build()).getContent());
  Assert.assertEquals("{"
      + "\"@odata.context\":\"$metadata#ESTwoPrim(PropertyInt16,"
+ "NavPropertyETAllPrimOne(PropertyInt16,PropertyDate))/$entity\","
      + "\"@odata.metadataEtag\":\"W/\\\"metadataETag\\\"\","
      + "\"PropertyInt16\":32767,\"PropertyString\":\"Test String4\","
      + "\"NavPropertyETAllPrimOne\":{\"@odata.id\":\"ESAllPrim(32767)\","
+ "\"PropertyInt16\":32767,\"PropertyDate\":\"2012-12-03\"}}",
      resultString);
}
 
Example #26
Source File: ActionData.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Entity createETKeyNavEntity(final Short number, final OData oData, final Edm edm)
    throws DataProviderException {
  Entity entity = new Entity()
      .addProperty(DataCreator.createPrimitive("PropertyInt16", number))
      .addProperty(DataCreator.createPrimitive("PropertyString", "UARTCollETKeyNavParam int16 value: " + number))
      .addProperty(DataCreator.createComplex("PropertyCompNav",
          ComplexTypeProvider.nameCTNavFiveProp.getFullQualifiedNameAsString(),
          DataCreator.createPrimitive("PropertyInt16", (short) 0)))
      .addProperty(createKeyNavAllPrimComplexValue("PropertyCompAllPrim"))
      .addProperty(DataCreator.createComplex("PropertyCompTwoPrim", 
            ComplexTypeProvider.nameCTTwoPrim.getFullQualifiedNameAsString(),
            DataCreator.createPrimitive("PropertyInt16", (short) 0),
            DataCreator.createPrimitive("PropertyString", ""))).addProperty(
            DataCreator.createPrimitiveCollection("CollPropertyString"))
      .addProperty(DataCreator.createPrimitiveCollection("CollPropertyInt16"))
      .addProperty(DataCreator.createComplexCollection("CollPropertyComp",
          ComplexTypeProvider.nameCTPrimComp.getFullQualifiedNameAsString()))
      .addProperty(DataCreator.createComplex("PropertyCompCompNav",
          ComplexTypeProvider.nameCTCompNav.getFullQualifiedNameAsString(),
          DataCreator.createPrimitive("PropertyString", ""),
          DataCreator.createComplex("PropertyCompNav", 
              ComplexTypeProvider.nameCTNavFiveProp.getFullQualifiedNameAsString(),
              DataCreator.createPrimitive("PropertyInt16", (short) 0))));
  setEntityId(entity, "ESKeyNav", oData, edm);
  return entity;
}
 
Example #27
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private URI createId(Entity entity, String idPropertyName, String navigationName) {
  try {
    StringBuilder sb = new StringBuilder(getEntitySetName(entity)).append("(");
    final Property property = entity.getProperty(idPropertyName);
    sb.append(property.asPrimitive()).append(")");
    if(navigationName != null) {
      sb.append("/").append(navigationName);
    }
    return new URI(sb.toString());
  } catch (URISyntaxException e) {
    throw new ODataRuntimeException("Unable to create (Atom) id for entity: " + entity, e);
  }
}
 
Example #28
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
						throws ODataApplicationException, SerializerException {

	// 1. retrieve the Entity Type
	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();

	// 2. retrieve the data from backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);

	// 3. serialize
	EdmEntityType entityType = edmEntitySet.getEntityType();

	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).suffix(ContextURL.Suffix.ENTITY).build();
 	// expand and select currently not supported
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build();

	ODataSerializer serializer = this.odata.createSerializer(responseFormat);
	SerializerResult serializerResult = serializer.entity(serviceMetadata, entityType, entity, options);
	InputStream entityStream = serializerResult.getContent();

	//4. configure the response object
	response.setContent(entityStream);
	response.setStatusCode(HttpStatusCode.OK.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #29
Source File: ODataJsonSerializerv01Test.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void geoCollection() throws Exception {
  final EdmEntityType entityType = mockEntityType(EdmPrimitiveTypeKind.GeometryCollection);
  final Entity entity = new Entity()
      .addProperty(new Property(null, entityType.getPropertyNames().get(0), ValueType.GEOSPATIAL,
          new GeospatialCollection(Dimension.GEOMETRY, null, Arrays.asList(
              createPoint(100, 0),
              new LineString(Dimension.GEOMETRY, null, Arrays.asList(createPoint(101, 0), createPoint(102, 1)))))));
  Assert.assertEquals("{\"" + entityType.getPropertyNames().get(0) + "\":{"
      + "\"type\":\"GeometryCollection\",\"geometries\":["
      + "{\"type\":\"Point\",\"coordinates\":[100.0,0.0]},"
      + "{\"type\":\"LineString\",\"coordinates\":[[101.0,0.0],[102.0,1.0]]}]}}",
      IOUtils.toString(serializerNoMetadata.entity(metadata, entityType, entity, null).getContent()));
}
 
Example #30
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private List<Entity> applyCountQueryOption(EntityCollection entityCollection, List<Entity> modifiedEntityList, 
    CountOption countOption) {

  // handle $count: always return the original number of entities, without considering $top and $skip
  if (countOption != null) {
    boolean isCount = countOption.getValue();
    if (isCount) {
      entityCollection.setCount(modifiedEntityList.size());
    }
  }
  
  return modifiedEntityList;
}