Java Code Examples for org.apache.olingo.commons.api.data.EntityCollection#setCount()

The following examples show how to use org.apache.olingo.commons.api.data.EntityCollection#setCount() . 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: AtomDeserializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void count(final XMLEventReader reader, final StartElement start, final EntityCollection entitySet)
    throws XMLStreamException {

  boolean foundEndElement = false;
  while (reader.hasNext() && !foundEndElement) {
    final XMLEvent event = reader.nextEvent();

    if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
      entitySet.setCount(Integer.valueOf(event.asCharacters().getData()));
    }

    if (event.isEndElement() && start.getName().equals(event.asEndElement().getName())) {
      foundEndElement = true;
    }
  }
}
 
Example 2
Source File: ODataBinderImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public EntityCollection getEntitySet(final ClientEntitySet odataEntitySet) {
  final EntityCollection entitySet = new EntityCollection();

  entitySet.setCount(odataEntitySet.getCount());

  final URI next = odataEntitySet.getNext();
  if (next != null) {
    entitySet.setNext(next);
  }

  for (ClientEntity entity : odataEntitySet.getEntities()) {
    entitySet.getEntities().add(getEntity(entity));
  }

  entitySet.setDeltaLink(odataEntitySet.getDeltaLink());
  annotations(odataEntitySet, entitySet);
  return entitySet;
}
 
Example 3
Source File: DataCreator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void linkPropMixPrimCompInESCompMixPrimCollCompToCollETTwoKeyNav(
    Map<String, EntityCollection> data) {
  EntityCollection collection = data.get("ESCompMixPrimCollComp");
  Entity entity = collection.getEntities().get(0);
  ComplexValue complexValue = entity.getProperties().get(1).asComplex();
  final List<Entity> esTwoKeyNavTargets = data.get("ESTwoKeyNav").getEntities();
  Link link = new Link();
  link.setRel(Constants.NS_NAVIGATION_LINK_REL + "NavPropertyETTwoKeyNavMany");
  link.setType(Constants.ENTITY_SET_NAVIGATION_LINK_TYPE);
  link.setTitle("NavPropertyETTwoKeyNavMany");
  EntityCollection target = new EntityCollection();
  target.setCount(2);
  target.getEntities().addAll(Arrays.asList(esTwoKeyNavTargets.get(0), esTwoKeyNavTargets.get(2)));
  link.setInlineEntitySet(target);
  link.setHref(entity.getId().toASCIIString() + "/" + 
  entity.getProperties().get(1).getName() + "/"
      + "NavPropertyETTwoKeyNavMany");
  complexValue.getNavigationLinks().add(link);
}
 
Example 4
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private EntityCollection getFlights(int tripId, EntityCollection result) {
  Map<String, Object> map = this.tripLinks.get(tripId);
  if (map == null) {
    return null;
  }

  ArrayList<Integer> flights = (ArrayList<Integer>) map.get("Flights");
  EntityCollection set = getEntitySet("Flight");
  int i = result.getEntities().size();
  if (flights != null) {
    for (int flight : flights) {
      for (Entity e : set.getEntities()) {
        if (e.getProperty("PlanItemId").getValue().equals(flight)) {
          result.getEntities().add(e);
          i++;
          break;
        }
      }
    }
  }
  result.setCount(i);
  return result;
}
 
Example 5
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private EntityCollection getEvents(int tripId, EntityCollection result) {
  Map<String, Object> map = this.tripLinks.get(tripId);
  if (map == null) {
    return null;
  }

  ArrayList<Integer> events = (ArrayList<Integer>) map.get("Events");
  EntityCollection set = getEntitySet("Event");
  int i = result.getEntities().size();
  if (events != null) {
    for (int event : events) {
      for (Entity e : set.getEntities()) {
        if (e.getProperty("PlanItemId").getValue().equals(event)) {
          result.getEntities().add(e);
          i++;
          break;
        }
      }
    }
  }
  result.setCount(i);
  return result;
}
 
Example 6
Source File: EdmAssistedJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void entityCollectionIEEE754Compatible() throws Exception {
  EntityCollection entityCollection = new EntityCollection();
  entityCollection.getEntities().add(new Entity()
      .addProperty(new Property(null, "Property1", ValueType.PRIMITIVE, Long.MIN_VALUE))
      .addProperty(new Property(null, "Property2", ValueType.PRIMITIVE, BigDecimal.valueOf(Long.MAX_VALUE, 10)))
      .addProperty(new Property("Edm.Byte", "Property3", ValueType.PRIMITIVE, 20)));
  entityCollection.setCount(3);
  Assert.assertEquals(
      "{\"@odata.context\":\"$metadata#EntitySet(Property1,Property2,Property3)\","
          + "\"@odata.count\":\"3\","
          + "\"value\":[{\"@odata.id\":null,"
          + "\"[email protected]\":\"#Int64\",\"Property1\":\"-9223372036854775808\","
          + "\"[email protected]\":\"#Decimal\",\"Property2\":\"922337203.6854775807\","
          + "\"[email protected]\":\"#Byte\",\"Property3\":20}]}",
      serialize(
          oData.createEdmAssistedSerializer(
              ContentType.create(ContentType.JSON_FULL_METADATA, ContentType.PARAMETER_IEEE754_COMPATIBLE, "true")),
          metadata, null, entityCollection, null));
}
 
Example 7
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private EntityCollection getTrips(String userName) {
  Map<String, Object> map = this.peopleLinks.get(userName);
  if (map == null) {
    return null;
  }

  ArrayList<Integer> trips = (ArrayList<Integer>) map.get("Trips");
  EntityCollection set = getEntitySet("Trip");

  EntityCollection result = new EntityCollection();
  int i = 0;
  if (trips != null) {
    for (int trip : trips) {
      for (Entity e : set.getEntities()) {
        if (e.getProperty("TripId").getValue().equals(trip)) {
          result.getEntities().add(e);
          i++;
          break;
        }
      }
    }
  }
  result.setCount(i);
  return result;
}
 
Example 8
Source File: TripPinDataModel.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private EntityCollection getFriends(String userName) {
  Map<String, Object> map = this.peopleLinks.get(userName);
  if (map == null) {
    return null;
  }
  ArrayList<String> friends = (ArrayList<String>) map.get("Friends");
  EntityCollection set = getEntitySet("People");

  EntityCollection result = new EntityCollection();
  int i = 0;
  if (friends != null) {
    for (String friend : friends) {
      for (Entity e : set.getEntities()) {
        if (e.getProperty("UserName").getValue().equals(friend)) {
          result.getEntities().add(e);
          i++;
          break;
        }
      }
    }
  }
  result.setCount(i);
  return result;
}
 
Example 9
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 10
Source File: ODataXmlSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void entitySetCompAllPrim() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESCompAllPrim");
  EntityCollection entitySet = data.readAll(edmEntitySet);
  entitySet.setCount(entitySet.getEntities().size());
  entitySet.setNext(URI.create("/next"));
  CountOption countOption = Mockito.mock(CountOption.class);
  Mockito.when(countOption.getValue()).thenReturn(true);
  InputStream result = serializer.entityCollection(metadata, edmEntitySet.getEntityType(), entitySet,
      EntityCollectionSerializerOptions.with()
          .contextURL(ContextURL.with().serviceRoot(new URI("http://host:port"))
              .entitySet(edmEntitySet).build())
          .id("http://host/svc/ESCompAllPrim")
          .count(countOption)
          .build()).getContent();
  final String resultString = IOUtils.toString(result);
  String prefix = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
      + "<a:feed xmlns:a=\"http://www.w3.org/2005/Atom\" "
      + "xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" "
      + "xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" "
      + "m:context=\"http://host:port$metadata#ESCompAllPrim\" "
      + "m:metadata-etag=\"metadataETag\">"
      + "<a:id>http://host/svc/ESCompAllPrim</a:id>"
      + "<m:count>4</m:count>"
      + "<a:link rel=\"next\" href=\"/next\"></a:link>"
      + "<a:entry m:etag=\"W/&quot;32767&quot;\">"
      + "<a:id>ESCompAllPrim(32767)</a:id><a:title></a:title><a:summary></a:summary>";
  Assert.assertTrue(resultString.startsWith(prefix));
}
 
Example 11
Source File: JsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected String setInline(final String name, final String suffix, final JsonNode tree,
    final ObjectCodec codec, final Link link) throws IOException {

  final String entityNamePrefix = name.substring(0, name.indexOf(suffix));

  Integer count = null;
  if (tree.hasNonNull(entityNamePrefix+Constants.JSON_COUNT)) {
    count = tree.get(entityNamePrefix+Constants.JSON_COUNT).asInt();
  }        
  
  if (tree.has(entityNamePrefix)) {
    final JsonNode inline = tree.path(entityNamePrefix);
    JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(serverMode);

    if (inline instanceof ObjectNode) {
      link.setType(Constants.ENTITY_NAVIGATION_LINK_TYPE);
      link.setInlineEntity(entityDeserializer.doDeserialize(inline.traverse(codec)).getPayload());

    } else if (inline instanceof ArrayNode) {
      link.setType(Constants.ENTITY_SET_NAVIGATION_LINK_TYPE);

      final EntityCollection entitySet = new EntityCollection();
      if (count != null) {
        entitySet.setCount(count);
      }
      for (final Iterator<JsonNode> entries = inline.elements(); entries.hasNext();) {
        entitySet.getEntities().add(entityDeserializer.doDeserialize(entries.next().traverse(codec)).getPayload());
      }

      link.setInlineEntitySet(entitySet);
    }
  }
  return entityNamePrefix;
}
 
Example 12
Source File: ODataBinderImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private ClientLink createLinkFromEmptyNavigationProperty(final String propertyName, 
    final Integer count) {
    EntityCollection inlineEntitySet = new EntityCollection();
    if (count != null) {
      inlineEntitySet.setCount(count);
    }
    return createODataInlineEntitySet(inlineEntitySet, null, propertyName, null);
}
 
Example 13
Source File: EdmAssistedJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void entityCollectionMetadataNone() throws Exception {
  Entity entity = new Entity();
  entity.setId(null);
  entity.addProperty(new Property(null, "Property0", ValueType.PRIMITIVE, null))
      .addProperty(new Property(null, "Property1", ValueType.PRIMITIVE, 1));
  Calendar date = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  date.clear();
  date.set(2000, 1, 29);
  entity.addProperty(new Property("Edm.Date", "Property2", ValueType.PRIMITIVE, date))
      .addProperty(new Property("Edm.DateTimeOffset", "Property3", ValueType.PRIMITIVE, date))
      .addProperty(new Property(null, "Property4", ValueType.COLLECTION_PRIMITIVE,
          Arrays.asList(true, false, null)));
  EntityCollection entityCollection = new EntityCollection();
  entityCollection.getEntities().add(entity);
  entityCollection.setCount(2);
  entityCollection.setNext(URI.create("nextLink"));
  Assert.assertEquals(
      "{"
          + "\"@odata.count\":2,"
          + "\"value\":[{"
          + "\"Property0\":null,"
          + "\"Property1\":1,"
          + "\"Property2\":\"2000-02-29\","
          + "\"Property3\":\"2000-02-29T00:00:00Z\","
          + "\"Property4\":[true,false,null]}],"
          + "\"@odata.nextLink\":\"nextLink\"}",
      serialize(serializerNone, metadata, null, entityCollection, null));
}
 
Example 14
Source File: EdmAssistedJsonSerializerTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void entityCollectionMetadataMin() throws Exception {
  Entity entity = new Entity();
  entity.setId(null);
  entity.addProperty(new Property(null, "Property0", ValueType.PRIMITIVE, null))
      .addProperty(new Property(null, "Property1", ValueType.PRIMITIVE, 1));
  Calendar date = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  date.clear();
  date.set(2000, 1, 29);
  entity.addProperty(new Property("Edm.Date", "Property2", ValueType.PRIMITIVE, date))
      .addProperty(new Property("Edm.DateTimeOffset", "Property3", ValueType.PRIMITIVE, date))
      .addProperty(new Property(null, "Property4", ValueType.COLLECTION_PRIMITIVE,
          Arrays.asList(true, false, null)));
  EntityCollection entityCollection = new EntityCollection();
  entityCollection.getEntities().add(entity);
  entityCollection.setCount(2);
  entityCollection.setNext(URI.create("nextLink"));
  Assert.assertEquals(
      "{\"@odata.context\":\"$metadata#EntitySet(Property0,Property1,Property2,Property3,Property4)\","
          + "\"@odata.count\":2,"
          + "\"value\":[{"
          + "\"Property0\":null,"
          + "\"Property1\":1,"
          + "\"Property2\":\"2000-02-29\","
          + "\"Property3\":\"2000-02-29T00:00:00Z\","
          + "\"Property4\":[true,false,null]}],"
          + "\"@odata.nextLink\":\"nextLink\"}",
      serialize(serializerMin, metadata, null, entityCollection, null));
}
 
Example 15
Source File: ExpandSystemQueryOptionHandler.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public EntityCollection transformEntitySetGraphToTree(final EntityCollection entitySet,
    final EdmBindingTarget edmBindingTarget, final ExpandOption expand, 
    final ExpandItem expandItem) throws ODataApplicationException {

  final EntityCollection newEntitySet = newEntitySet(entitySet);

  for (final Entity entity : entitySet.getEntities()) {
    newEntitySet.getEntities().add(transformEntityGraphToTree(entity, edmBindingTarget, expand, expandItem));
  }
  if (expandItem != null && expandItem.hasCountPath()) {
    newEntitySet.setCount(entitySet.getEntities().size());
  }
  return newEntitySet;
}
 
Example 16
Source File: JsonEntitySetDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected ResWrap<EntityCollection> doDeserialize(final JsonParser parser) throws IOException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    if (!tree.has(Constants.VALUE)) {
      return null;
    }

    final EntityCollection entitySet = new EntityCollection();

    URI contextURL;
    if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
      contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
      tree.remove(Constants.JSON_CONTEXT);
    } else if (tree.hasNonNull(Constants.JSON_METADATA)) {
      contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
      tree.remove(Constants.JSON_METADATA);
    } else {
      contextURL = null;
    }
    if (contextURL != null) {
      entitySet.setBaseURI(URI.create(StringUtils.substringBefore(contextURL.toASCIIString(), Constants.METADATA)));
    }

    final String metadataETag;
    if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
      metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
      tree.remove(Constants.JSON_METADATA_ETAG);
    } else {
      metadataETag = null;
    }

    if (tree.hasNonNull(Constants.JSON_COUNT)) {
      entitySet.setCount(tree.get(Constants.JSON_COUNT).asInt());
      tree.remove(Constants.JSON_COUNT);
    }
    if (tree.hasNonNull(Constants.JSON_NEXT_LINK)) {
      entitySet.setNext(URI.create(tree.get(Constants.JSON_NEXT_LINK).textValue()));
      tree.remove(Constants.JSON_NEXT_LINK);
    }
    if (tree.hasNonNull(Constants.JSON_DELTA_LINK)) {
      entitySet.setDeltaLink(URI.create(tree.get(Constants.JSON_DELTA_LINK).textValue()));
      tree.remove(Constants.JSON_DELTA_LINK);
    }

    if (tree.hasNonNull(Constants.VALUE)) {
      final JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(serverMode);
      for (JsonNode jsonNode : tree.get(Constants.VALUE)) {
        entitySet.getEntities().add(
            entityDeserializer.doDeserialize(jsonNode.traverse(parser.getCodec())).getPayload());
      }
      tree.remove(Constants.VALUE);
    }
    final Set<String> toRemove = new HashSet<>();
    // any remaining entry is supposed to be an annotation or is ignored
    for (final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields(); itor.hasNext();) {
      final Map.Entry<String, JsonNode> field = itor.next();
      if (field.getKey().charAt(0) == '@') {
        final Annotation annotation = new Annotation();
        annotation.setTerm(field.getKey().substring(1));

        try {
          value(annotation, field.getValue(), parser.getCodec());
        } catch (final EdmPrimitiveTypeException e) {
          throw new IOException(e);
        }
        entitySet.getAnnotations().add(annotation);
      } else if (field.getKey().charAt(0) == '#') {
        final Operation operation = new Operation();
        operation.setMetadataAnchor(field.getKey());

        final ObjectNode opNode = (ObjectNode) tree.get(field.getKey());
        operation.setTitle(opNode.get(Constants.ATTR_TITLE).asText());
        operation.setTarget(URI.create(opNode.get(Constants.ATTR_TARGET).asText()));
        entitySet.getOperations().add(operation);
        toRemove.add(field.getKey());
      }
    }
    tree.remove(toRemove);
    return new ResWrap<>(contextURL, metadataETag, entitySet);
  }
 
Example 17
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 4 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 and deliver as EntitySet
  EntityCollection entityCollection = storage.readEntitySetData(edmEntitySet);

  // 3rd: apply System Query Options
  // modify the result set according to the query options, specified by the end user
  List<Entity> entityList = entityCollection.getEntities();
  EntityCollection returnEntityCollection = new EntityCollection();

  // handle $count: always return the original number of entities, without considering $top and $skip
  CountOption countOption = uriInfo.getCountOption();
  if (countOption != null) {
    boolean isCount = countOption.getValue();
    if (isCount) {
      returnEntityCollection.setCount(entityList.size());
    }
  }
  
  // handle $skip
  SkipOption skipOption = uriInfo.getSkipOption();
  if (skipOption != null) {
    int skipNumber = skipOption.getValue();
    if (skipNumber >= 0) {
      if(skipNumber <= entityList.size()) {
        entityList = entityList.subList(skipNumber, entityList.size());
      } else {
        // The client skipped all entities
        entityList.clear();
      }
    } else {
      throw new ODataApplicationException("Invalid value for $skip", HttpStatusCode.BAD_REQUEST.getStatusCode(),
          Locale.ROOT);
    }
  }
  
  // handle $top
  TopOption topOption = uriInfo.getTopOption();
  if (topOption != null) {
    int topNumber = topOption.getValue();
    if (topNumber >= 0) {
      if(topNumber <= entityList.size()) {
        entityList = entityList.subList(0, topNumber);
      }  // else the client has requested more entities than available => return what we have
    } else {
      throw new ODataApplicationException("Invalid value for $top", HttpStatusCode.BAD_REQUEST.getStatusCode(),
          Locale.ROOT);
    }
  }

  // after applying the system query options, create the EntityCollection based on the reduced list
  for (Entity entity : entityList) {
    returnEntityCollection.getEntities().add(entity);
  }

  // 4th: 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().contextURL(contextUrl).id(id).count(countOption).build();
  SerializerResult serializerResult =
      serializer.entityCollection(serviceMetadata, edmEntityType, returnEntityCollection, opts);
  InputStream serializedContent = serializerResult.getContent();

  // 5th: configure the response object: set the body, headers and status code
  response.setContent(serializedContent);
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 18
Source File: Services.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void setInlineCount(final EntityCollection entitySet, final String count) {
  if ("true".equals(count)) {
    entitySet.setCount(entitySet.getEntities().size());
  }
}
 
Example 19
Source File: ProductsEntityCollectionProcessor.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
    // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI)
    List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
    UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet)resourcePaths.get(0); // in our example, the first segment is the EntitySet
    EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

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

    // 3rd: apply System Query Options
    // modify the result set according to the query options, specified by the end user
    List<Entity> entityList = entityCollection.getEntities();
    EntityCollection returnEntityCollection = new EntityCollection();

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

    applyQueryOptions(uriInfo, entityList, returnEntityCollection);

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

    // 4th: Now 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)
            .count(countOption)
            .contextURL(contextUrl)
            .build();

    SerializerResult serializerResult = serializer.entityCollection(serviceMetadata,
                                                                    edmEntityType,
                                                                    returnEntityCollection,
                                                                    opts);
    InputStream serializedContent = serializerResult.getContent();

    // Finally: configure the response object: set the body, headers and status code
    response.setContent(serializedContent);
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example 20
Source File: QueryHandler.java    From micro-integrator with Apache License 2.0 2 votes vote down vote up
/**
 * This method applies count query option to the given entity collection.
 *
 * @param countOption Count option
 * @param entitySet   Entity collection
 */
public static void applyCountSystemQueryOption(final CountOption countOption, final EntityCollection entitySet) {
    if (countOption.getValue()) {
        entitySet.setCount(entitySet.getEntities().size());
    }
}