org.apache.olingo.server.api.uri.UriInfo Java Examples

The following examples show how to use org.apache.olingo.server.api.uri.UriInfo. 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: ExpandParserTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void expandNavigationApplyOption() throws Exception {
  UriInfo uriInfo = new Parser(edm, oData).parseUri("ESTwoKeyNav",
      "$expand=NavPropertyETKeyNavMany($apply=identity),NavPropertyETKeyNavOne", null, null);
  Assert.assertEquals(ApplyItem.Kind.IDENTITY,
      uriInfo.getExpandOption().getExpandItems().get(0).getApplyOption().getApplyItems().get(0).getKind());
  Assert.assertEquals("NavPropertyETKeyNavOne",
      uriInfo.getExpandOption().getExpandItems().get(1)
          .getResourcePath().getUriResourceParts().get(0).getSegmentValue());

  uriInfo = new Parser(edm, oData).parseUri("ESTwoKeyNav",
      "$expand=NavPropertyETKeyNavMany($apply=aggregate(PropertyInt16 with sum as s))", null, null);
  final ApplyItem applyItem =
      uriInfo.getExpandOption().getExpandItems().get(0).getApplyOption().getApplyItems().get(0);
  Assert.assertEquals(ApplyItem.Kind.AGGREGATE, applyItem.getKind());
  Assert.assertEquals(AggregateExpression.StandardMethod.SUM,
      ((Aggregate) applyItem).getExpressions().get(0).getStandardMethod());
}
 
Example #2
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, SerializerException {

  // The sample service supports only functions imports and entity sets.
  // We do not care about bound functions and composable functions.

  UriResource uriResource = uriInfo.getUriResourceParts().get(0);

  if (uriResource instanceof UriResourceEntitySet) {
    readEntityInternal(request, response, uriInfo, responseFormat);
  } else if (uriResource instanceof UriResourceFunction) {
    readFunctionImportInternal(request, response, uriInfo, responseFormat);
  } else {
    throw new ODataApplicationException("Only EntitySet is supported",
        HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
  }
}
 
Example #3
Source File: UriValidator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void validatePropertyOperations(final UriInfo uriInfo, final HttpMethod method)
    throws UriValidationException {
  final List<UriResource> parts = uriInfo.getUriResourceParts();
  final UriResource last = !parts.isEmpty() ? parts.get(parts.size() - 1) : null;
  final UriResource previous = parts.size() > 1 ? parts.get(parts.size() - 2) : null;
  if (last != null
      && (last.getKind() == UriResourceKind.primitiveProperty
      || last.getKind() == UriResourceKind.complexProperty
      || (last.getKind() == UriResourceKind.value
          && previous != null && previous.getKind() == UriResourceKind.primitiveProperty))) {
    final EdmProperty property = ((UriResourceProperty)
        (last.getKind() == UriResourceKind.value ? previous : last)).getProperty();
    if (method == HttpMethod.PATCH && property.isCollection()) {
      throw new UriValidationException("Attempt to patch collection property.",
          UriValidationException.MessageKeys.UNSUPPORTED_HTTP_METHOD, method.toString());
    }
    if (method == HttpMethod.DELETE && !property.isNullable()) {
      throw new UriValidationException("Attempt to delete non-nullable property.",
          UriValidationException.MessageKeys.UNSUPPORTED_HTTP_METHOD, method.toString());
    }
  }
}
 
Example #4
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo)
    throws ODataApplicationException {

  // 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();

  // 2. delete the data in backend
  List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
  storage.deleteEntityData(edmEntitySet, keyPredicates);

  // 3. configure the response object
  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
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: ServerCoreDebugger.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public ODataResponse createDebugResponse(final ODataRequest request, final ODataResponse response,
    final Exception exception, final UriInfo uriInfo, final Map<String, String> serverEnvironmentVariables) {
  // Failsafe so we do not generate unauthorized debug messages
  if (!isDebugMode) {
    return response;
  }

  try {
    DebugInformation debugInfo =
        createDebugInformation(request, response, exception, uriInfo, serverEnvironmentVariables);

    return debugSupport.createDebugResponse(debugFormat, debugInfo);
  } catch (Exception e) {
    return createFailResponse();
  }
}
 
Example #7
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchMedia() throws Exception {
  final String uri = "ESMedia(1)/$value";
  final MediaEntityProcessor processor = mock(MediaEntityProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readMediaEntity(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class));

  dispatch(HttpMethod.POST, "ESMedia", processor);
  verify(processor).createMediaEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class), any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, processor);
  verify(processor).updateMediaEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class), any(ContentType.class));

  dispatch(HttpMethod.DELETE, uri, processor);
  verify(processor).deleteMediaEntity(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.PATCH, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #8
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchComplexCollectionProperty() throws Exception {
  final String uri = "ESMixPrimCollComp(7)/CollPropertyComp";
  final ComplexCollectionProcessor processor = mock(ComplexCollectionProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readComplexCollection(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, processor);
  verify(processor).updateComplexCollection(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class),
      any(ContentType.class));

  dispatch(HttpMethod.DELETE, uri, processor);
  verify(processor).deleteComplexCollection(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #9
Source File: ServiceRequest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public DataRequest parseLink(URI uri) throws UriParserException, UriValidationException  {
  String path = "/";
  URI servicePath = URI.create(getODataRequest().getRawBaseUri());
  path = servicePath.getPath();
  
  String rawPath = uri.getPath();
  int e = rawPath.indexOf(path);
  if (-1 == e) {
    rawPath = uri.getPath();
  } else {
    rawPath = rawPath.substring(e+path.length());
  }

  UriInfo reqUriInfo = new Parser(serviceMetadata.getEdm(), odata).parseUri(rawPath, uri.getQuery(), null, 
      getODataRequest().getRawBaseUri());
  ServiceDispatcher dispatcher = new ServiceDispatcher(odata, serviceMetadata, null, customContentType);
  dispatcher.visit(reqUriInfo);
  dispatcher.request.setUriInfo(reqUriInfo);
  return (DataRequest)dispatcher.request;
}
 
Example #10
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void readMediaEntity(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
  getEdmEntitySet(uriInfo); // including checks
  final Entity entity = readEntity(uriInfo);
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo.asUriInfoResource());
  if (isMediaStreaming(edmEntitySet)) {
EntityMediaObject mediaEntity = new EntityMediaObject();
mediaEntity.setBytes(dataProvider.readMedia(entity));
   response.setODataContent(odata.createFixedFormatSerializer()
   		.mediaEntityStreamed(mediaEntity).getODataContent());
  } else {
  	response.setContent(odata.createFixedFormatSerializer().binary(dataProvider.readMedia(entity)));
  }
  response.setContent(odata.createFixedFormatSerializer().binary(dataProvider.readMedia(entity)));
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, entity.getMediaContentType());
  if (entity.getMediaETag() != null) {
    response.setHeader(HttpHeader.ETAG, entity.getMediaETag());
  }
}
 
Example #11
Source File: GenericEntityCollectionProcessor.java    From spring-boot-Olingo-oData with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method for providing some sample data.
 *
 * @param edmEntitySet
 *            for which the data is requested
 * @return data of requested entity set
 */
private EntitySet getData(UriInfo uriInfo) {
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths
			.get(0); // in our example, the first segment is the EntitySet
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();

	EntitySet entitySet = null;

	Map<String, EntityProvider> entityProviders = ctx
			.getBeansOfType(EntityProvider.class);

	for (String entity : entityProviders.keySet()) {
		EntityProvider entityProvider = entityProviders.get(entity);
		if (entityProvider
				.getEntityType().getName()
				
				.equals(edmEntitySet.getEntityType().getName())) {
			entitySet = entityProvider.getEntitySet(uriInfo);
			break;
		}
	}
	return entitySet;
}
 
Example #12
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void countEntityCollection(final ODataRequest request, final ODataResponse response,
    final UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException {
  validateOptions(uriInfo.asUriInfoResource());
  getEdmEntitySet(uriInfo); // including checks
  final EntityCollection entitySetInitial = readEntityCollection(uriInfo);
  EntityCollection entitySet = new EntityCollection();
  entitySet.getEntities().addAll(entitySetInitial.getEntities());
  FilterHandler.applyFilterSystemQuery(uriInfo.getFilterOption(), entitySet, uriInfo, serviceMetadata.getEdm());
  SearchHandler.applySearchSystemQueryOption(uriInfo.getSearchOption(), entitySet);
  int count =  entitySet.getEntities().size();
  for (SystemQueryOption systemQueryOption : uriInfo.getSystemQueryOptions()) {
    if (systemQueryOption.getName().contains(DELTATOKEN)) {
      count = count + getDeltaCount(uriInfo);
      break;
    }
  }
  response.setContent(odata.createFixedFormatSerializer().count(count));
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
}
 
Example #13
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void updateMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType requestFormat, 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 = odata.createFixedFormatDeserializer().binary(request.getBody());
    storage.updateMedia(entity, requestFormat.toContentTypeString(), mediaContent);
    
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #14
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private boolean isContNav(UriInfo uriInfo) {
  List<UriResource> resourceParts = uriInfo.getUriResourceParts();
  for (UriResource resourcePart : resourceParts) {
    if (resourcePart instanceof UriResourceNavigation) {
      UriResourceNavigation navResource = (UriResourceNavigation) resourcePart;
      if (navResource.getProperty().containsTarget()) {
        return true;
      }
    }
  }
  return false;
}
 
Example #15
Source File: ApplyParser.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private UriInfo parseGroupingProperty(final EdmStructuredType referencedType) throws UriParserException {
  UriInfoImpl uriInfo = new UriInfoImpl();
  final String identifierLeft = parsePathPrefix(uriInfo, referencedType);
  if (identifierLeft != null) {
    throw new UriParserSemanticException("Unknown identifier in grouping property path.",
        UriParserSemanticException.MessageKeys.EXPRESSION_PROPERTY_NOT_IN_TYPE,
        identifierLeft,
        uriInfo.getLastResourcePart() != null && uriInfo.getLastResourcePart() instanceof UriResourcePartTyped ?
            ((UriResourcePartTyped) uriInfo.getLastResourcePart())
                .getType().getFullQualifiedName().getFullQualifiedNameAsString() :
            "");
  }
  return uriInfo;
}
 
Example #16
Source File: ProductEntityProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
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 = this.odata.createDeserializer(requestFormat);
    DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
    Entity requestEntity = result.getEntity();
    LOG.info("Updating entity {}", requestEntity.getSelfLink());

    // 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 #17
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 {
  
  final UriResource firstResourceSegment = uriInfo.getUriResourceParts().get(0);
  
  if(firstResourceSegment instanceof UriResourceEntitySet) {
    readEntityCollectionInternal(request, response, uriInfo, responseFormat);
  } else if(firstResourceSegment instanceof UriResourceFunction) {
    readFunctionImportCollection(request, response, uriInfo, responseFormat);
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #18
Source File: GenericEntityCollectionProcessor.java    From spring-boot-Olingo-oData 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 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
	EntitySet entitySet = getData(uriInfo);

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

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

	EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions
			.with().contextURL(contextUrl).build();
	InputStream serializedContent = serializer.entityCollection(
			edmEntityType, entitySet, opts);

	// 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 #19
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = storage.createEntityData(edmEntitySet, requestEntity);
	
	// 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #20
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();
		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 and deliver as EntitySet
		EntityCollection entityCollection = 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 serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entityCollection, opts);
		InputStream serializedContent = serializerResult.getContent();

		// 4th: 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 #21
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 #22
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 #23
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void readFunctionImportCollection(final ODataRequest request, final ODataResponse response, 
    final UriInfo uriInfo, final ContentType responseFormat) throws ODataApplicationException, SerializerException {
  
  // 1st step: Analyze the URI and fetch the entity collection returned by the function import
  // Function Imports are always the first segment of the resource path
  final UriResource firstSegment = uriInfo.getUriResourceParts().get(0);
  
  if(!(firstSegment instanceof UriResourceFunction)) {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
  
  final UriResourceFunction uriResourceFunction = (UriResourceFunction) firstSegment;
  final EntityCollection entityCol = storage.readFunctionImportCollection(uriResourceFunction, serviceMetadata);
  
  // 2nd step: Serialize the response entity
  final EdmEntityType edmEntityType = (EdmEntityType) uriResourceFunction.getFunction().getReturnType().getType();
  final ContextURL contextURL = ContextURL.with().asCollection().type(edmEntityType).build();
  EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with().contextURL(contextURL).build();
  final ODataSerializer serializer = odata.createSerializer(responseFormat);
  final SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entityCol, 
      opts); 

  // 3rd configure the response object
  response.setContent(serializerResult.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #24
Source File: UriInfoImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void entityNames() {
  final UriInfo uriInfo = new UriInfoImpl()
      .addEntitySetName("A")
      .addEntitySetName("B");
  assertArrayEquals(new String[] { "A", "B" }, uriInfo.getEntitySetNames().toArray());
}
 
Example #25
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 #26
Source File: CarsProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void readEntity(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final ContentType requestedContentType) throws ODataApplicationException, SerializerException {
  // First we have to figure out which entity set the requested entity is in
  final EdmEntitySet edmEntitySet = getEdmEntitySet(uriInfo.asUriInfoResource());

  // Next we fetch the requested entity from the database
  Entity entity;
  try {
    entity = readEntityInternal(uriInfo.asUriInfoResource(), edmEntitySet);
  } catch (DataProviderException e) {
    throw new ODataApplicationException(e.getMessage(), 500, Locale.ENGLISH);
  }

  if (entity == null) {
    // If no entity was found for the given key we throw an exception.
    throw new ODataApplicationException("No entity found for this key", HttpStatusCode.NOT_FOUND
        .getStatusCode(), Locale.ENGLISH);
  } else {
    // If an entity was found we proceed by serializing it and sending it to the client.
    ODataSerializer serializer = odata.createSerializer(requestedContentType);
    final ExpandOption expand = uriInfo.getExpandOption();
    final SelectOption select = uriInfo.getSelectOption();
    InputStream serializedContent = serializer.entity(edm, edmEntitySet.getEntityType(), entity,
        EntitySerializerOptions.with()
            .contextURL(isODataMetadataNone(requestedContentType) ? null :
                getContextUrl(edmEntitySet, true, expand, select, null))
            .expand(expand).select(select)
            .build()).getContent();
    response.setContent(serializedContent);
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setHeader(HttpHeader.CONTENT_TYPE, requestedContentType.toContentTypeString());
  }
}
 
Example #27
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 {
  
  final UriResource firstResourceSegment = uriInfo.getUriResourceParts().get(0);
  
  if(firstResourceSegment instanceof UriResourceEntitySet) {
    readEntityCollectionInternal(request, response, uriInfo, responseFormat);
  } else if(firstResourceSegment instanceof UriResourceFunction) {
    readFunctionImportCollection(request, response, uriInfo, responseFormat);
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #28
Source File: DataRequest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
static ContextURL.Builder buildEntitySetContextURL(UriHelper helper,
    EdmBindingTarget edmEntitySet, List<UriParameter> keyPredicates, UriInfo uriInfo,
    LinkedList<UriResourceNavigation> navigations, boolean collectionReturn, boolean singleton, ODataRequest request)
    throws SerializerException {

  ContextURL.Builder builder =
      ContextURL.with().entitySetOrSingletonOrType(getTargetEntitySet(edmEntitySet, navigations));
  String select = helper.buildContextURLSelectList(edmEntitySet.getEntityType(),
      uriInfo.getExpandOption(), uriInfo.getSelectOption());
  if (!singleton) {
    builder.suffix(collectionReturn ? null : Suffix.ENTITY);
  }

  setServiceRoot(builder, request);    
  builder.selectList(select);

  final UriInfoResource resource = uriInfo.asUriInfoResource();
  final List<UriResource> resourceParts = resource.getUriResourceParts();
  final List<String> path = getPropertyPath(resourceParts);
  String propertyPath = buildPropertyPath(path);
  final String navPath = buildNavPath(helper, edmEntitySet.getEntityType(), navigations, collectionReturn);
  if (navPath != null && !navPath.isEmpty()) {
    if (keyPredicates != null) {
      builder.keyPath(helper.buildContextURLKeyPredicate(keyPredicates));
    }
    if (propertyPath != null) {
      propertyPath = navPath+"/"+propertyPath;
    } else {
      propertyPath = navPath;
    }
  }
  builder.navOrPropertyPath(propertyPath);
  return builder;
}
 
Example #29
Source File: DemoEntityCollectionProcessor.java    From cxf 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 we have retrieve the requested EntitySet from the uriInfo object 
    // (representation of the parsed service 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 = getData(edmEntitySet);

    // 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).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 #30
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = storage.createEntityData(edmEntitySet, requestEntity);
	
	// 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}