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

The following examples show how to use org.apache.olingo.commons.api.data.EntityCollection#setNext() . 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: QueryHandler.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method applies server-side paging to the given entity collection.
 *
 * @param skipTokenOption   Current skip token option (from a previous response's next link)
 * @param entityCollection  Entity collection
 * @param edmEntitySet      EDM entity set to decide whether paging must be done
 * @param rawRequestUri     Request URI (used to construct the next link)
 * @param preferredPageSize Preference for page size
 * @return Chosen page size
 * @throws ODataApplicationException
 */
public static Integer applyServerSidePaging(final SkipTokenOption skipTokenOption,
                                            EntityCollection entityCollection, final EdmEntitySet edmEntitySet,
                                            final String rawRequestUri, final Integer preferredPageSize)
        throws ODataApplicationException {
    if (edmEntitySet != null) {
        final int pageSize = getPageSize(preferredPageSize);
        final int page = getPage(skipTokenOption);
        final int itemsToSkip = pageSize * page;
        if (itemsToSkip <= entityCollection.getEntities().size()) {
            popAtMost(entityCollection, itemsToSkip);
            final int remainingItems = entityCollection.getEntities().size();
            reduceToSize(entityCollection, pageSize);
            // Determine if a new next Link has to be provided.
            if (remainingItems > pageSize) {
                entityCollection.setNext(createNextLink(rawRequestUri, edmEntitySet, page + 1));
            }
        } else {
            throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(),
                                                Locale.ROOT);
        }
        return pageSize;
    }
    return null;
}
 
Example 2
Source File: ServerSidePagingHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Applies server-side paging to the given entity collection.</p>
 * <p>The next link is constructed and set in the data. It must support client-specified
 * page sizes. Therefore, the format <code>page*pageSize</code> (with a literal asterisk)
 * has been chosen for the skiptoken.</p> 
 * @param skipTokenOption   the current skiptoken option (from a previous response's next link)
 * @param entityCollection  the data
 * @param edmEntitySet      the EDM entity set to decide whether paging must be done
 * @param rawRequestUri     the request URI (used to construct the next link)
 * @param preferredPageSize the client's preference for page size
 * @return the chosen page size (or <code>null</code> if no paging has been done);
 *         could be used in the Preference-Applied HTTP header
 * @throws ODataApplicationException
 */
public static Integer applyServerSidePaging(final SkipTokenOption skipTokenOption, EntityCollection entityCollection,
    final EdmEntitySet edmEntitySet, final String rawRequestUri, final Integer preferredPageSize)
    throws ODataApplicationException {

  if (edmEntitySet != null && shouldApplyServerSidePaging(edmEntitySet)) {
    final int pageSize = getPageSize(getPageSize(skipTokenOption), preferredPageSize);
    final int page = getPage(skipTokenOption);
    final int itemsToSkip = pageSize * page;

    if (itemsToSkip <= entityCollection.getEntities().size()) {
      SkipHandler.popAtMost(entityCollection, itemsToSkip);
      final int remainingItems = entityCollection.getEntities().size();
      TopHandler.reduceToSize(entityCollection, pageSize);

      // Determine if a new next Link has to be provided.
      if (remainingItems > pageSize) {
        entityCollection.setNext(createNextLink(rawRequestUri, page + 1, pageSize));
      }
    } else {
      throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
    }
    return pageSize;
  }
  return null;
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: TripPinHandler.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private EntityDetails process(final DataRequest request) throws ODataApplicationException {
  EntityCollection entitySet = null;
  Entity entity = null;
  EdmEntityType entityType;
  Entity parentEntity = null;

  if (request.isSingleton()) {
    EdmSingleton singleton = request.getUriResourceSingleton().getSingleton();
    entityType = singleton.getEntityType();
    if (singleton.getName().equals("Me")) {
      entitySet = this.dataModel.getEntitySet("People");
      entity = entitySet.getEntities().get(0);
    }
  } else {
    final EdmEntitySet edmEntitySet = request.getEntitySet();
    entityType = edmEntitySet.getEntityType();
    List<UriParameter> keys = request.getKeyPredicates();

    // TODO: This example so far ignores all system options; but a real
    // service should not
    if (keys != null && !keys.isEmpty()) {
      entity = this.dataModel.getEntity(edmEntitySet.getName(), keys);
    } else {
      int skip = 0;
      if (request.getUriInfo().getSkipTokenOption() != null) {
        skip = Integer.parseInt(request.getUriInfo().getSkipTokenOption().getValue());
      }
      int pageSize = getPageSize(request);
      entitySet = this.dataModel.getEntitySet(edmEntitySet.getName(), skip, pageSize);
      if (entitySet.getEntities().size() == pageSize) {
        try {
          entitySet.setNext(new URI(request.getODataRequest().getRawRequestUri() + "?$skiptoken="
              + (skip + pageSize)));
        } catch (URISyntaxException e) {
          throw new ODataApplicationException(e.getMessage(), 500, Locale.getDefault());
        }
      }
    }
  }
  EntityDetails details = new EntityDetails();

  if (!request.getNavigations().isEmpty() && entity != null) {
    UriResourceNavigation lastNavigation = request.getNavigations().getLast();
    for (UriResourceNavigation nav : request.getNavigations()) {
      entityType = nav.getProperty().getType();
      if (nav.isCollection()) {
        entitySet = this.dataModel.getNavigableEntitySet(entity, nav);
      } else {
        parentEntity = entity;
        entity = this.dataModel.getNavigableEntity(parentEntity, nav);
      }
    }
    details.navigationProperty = lastNavigation.getProperty().getName();
  }

  details.entity = entity;
  details.entitySet = entitySet;
  details.entityType = entityType;
  details.parentEntity = parentEntity;
  return details;
}
 
Example 8
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);
  }