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

The following examples show how to use org.apache.olingo.server.api.uri.UriResource. 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: 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 #2
Source File: ExpandSelectHelper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * @param selectedPaths
 * @param parts
 * @param path
 */
private static Set<List<String>> extractPathsFromResourceParts(
    Set<List<String>> selectedPaths, final List<UriResource> parts,
    List<String> path) {
  if (parts.size() > 1) {
    for (final UriResource part : parts.subList(1, parts.size())) {
      if (part instanceof UriResourceProperty) {
        path.add(((UriResourceProperty) part).getProperty().getName());
      } else if (part instanceof UriResourceNavigation) {
        path.add(((UriResourceNavigation) part).getProperty().getName());
      }
      if (part instanceof UriResourceComplexProperty &&
          ((UriResourceComplexProperty) part).getComplexTypeFilter() != null) {
        path.add(((UriResourceComplexProperty) part).getComplexTypeFilter().
            getFullQualifiedName().getFullQualifiedNameAsString());
      }
    }
    selectedPaths.add(path);
  } else if (!path.isEmpty()) {
    selectedPaths.add(path);
  } else {
    return null;
  }
  return selectedPaths.isEmpty() ? null : selectedPaths;
}
 
Example #3
Source File: ExpandSelectHelper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static ExpandItem getExpandItem(final List<ExpandItem> expandItems, final String propertyName) {
  for (final ExpandItem item : expandItems) {
    if (item.isStar()) {
        continue;
    }
    final List<UriResource> resourceParts = item.getResourcePath().getUriResourceParts();
    UriResource resource = null;
    if (resourceParts.get(resourceParts.size() - 1) instanceof UriResourceRef ||
        resourceParts.get(resourceParts.size() - 1) instanceof UriResourceCount) {
      resource = resourceParts.get(resourceParts.size() - 2);
    } else {
      resource = resourceParts.get(resourceParts.size() - 1);
    }
    if ((resource instanceof UriResourceNavigation
        && propertyName.equals(((UriResourceNavigation) resource).getProperty().getName())) ||
        resource instanceof UriResourceProperty
        && propertyName.equals(((UriResourceProperty) resource).getProperty().getName())) {
      return item;
    }
  }
  return null;
}
 
Example #4
Source File: UriHelperImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public UriResourceEntitySet parseEntityId(final Edm edm, final String entityId, final String rawServiceRoot)
    throws DeserializerException {

  String oDataPath = entityId;
  if (rawServiceRoot != null && entityId.startsWith(rawServiceRoot)) {
    oDataPath = entityId.substring(rawServiceRoot.length());
  }
  oDataPath = oDataPath.startsWith("/") ? oDataPath : "/" + oDataPath;

  try {
    final List<UriResource> uriResourceParts =
        new Parser(edm, new ODataImpl()).parseUri(oDataPath, null, null, rawServiceRoot).getUriResourceParts();
    if (uriResourceParts.size() == 1 && uriResourceParts.get(0).getKind() == UriResourceKind.entitySet) {
      final UriResourceEntitySet entityUriResource = (UriResourceEntitySet) uriResourceParts.get(0);

      return entityUriResource;
    }

    throw new DeserializerException("Invalid entity binding link", MessageKeys.INVALID_ENTITY_BINDING_LINK,
        entityId);
  } catch (final ODataLibraryException e) {
    throw new DeserializerException("Invalid entity binding link", e, MessageKeys.INVALID_ENTITY_BINDING_LINK,
        entityId);
  }
}
 
Example #5
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 #6
Source File: ApplyParser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private UriResource parsePathSegment(final EdmElement property) throws UriParserException {
  if (property == null
      || !(property.getType().getKind() == EdmTypeKind.COMPLEX
      || property instanceof EdmNavigationProperty)) {
    // Could be a customAggregate or $count.
    return null;
  }
  if (tokenizer.next(TokenKind.SLASH)) {
    final EdmStructuredType typeCast = ParserHelper.parseTypeCast(tokenizer, edm,
        (EdmStructuredType) property.getType());
    if (typeCast != null) {
      ParserHelper.requireNext(tokenizer, TokenKind.SLASH);
    }
    return property.getType().getKind() == EdmTypeKind.COMPLEX ?
        new UriResourceComplexPropertyImpl((EdmProperty) property).setTypeFilter(typeCast) :
        new UriResourceNavigationPropertyImpl((EdmNavigationProperty) property).setCollectionTypeFilter(typeCast);
  } else {
    return null;
  }
}
 
Example #7
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 #8
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 #9
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 #10
Source File: FilterValidator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public FilterValidator isParameterText(final int parameterIndex, final String parameterText)
    throws ExpressionVisitException, ODataApplicationException {

  if (curExpression instanceof MethodImpl) {
    MethodImpl methodCall = (MethodImpl) curExpression;

    Expression parameter = methodCall.getParameters().get(parameterIndex);
    String actualParameterText = FilterTreeToText.Serialize(parameter);
    assertEquals(parameterText, actualParameterText);
  } else if (curExpression instanceof MemberImpl) {
    final MemberImpl member = (MemberImpl) curExpression;
    final List<UriResource> uriResourceParts = member.getResourcePath().getUriResourceParts();

    if (!uriResourceParts.isEmpty() && uriResourceParts.get(0) instanceof UriResourceFunctionImpl) {
      assertEquals(parameterText, ((UriResourceFunctionImpl) uriResourceParts.get(0)).getParameters()
          .get(parameterIndex).getText());
    } else {
      fail("Current expression is not a method or function");
    }
  } else {
    fail("Current expression is not a method or function");
  }

  return this;
}
 
Example #11
Source File: ExpandSelectMock.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private static UriInfoResource mockResourceOnComplexTypesWithNav(final EdmEntitySet edmEntitySet,
    final String name, final String navProperty) {
  EdmStructuredType type = edmEntitySet.getEntityType();
  List<UriResource> elements = new ArrayList<UriResource>();
  final EdmElement edmElement = type.getProperty(name);
  final EdmProperty property = (EdmProperty) edmElement;
  UriResourceComplexProperty element = Mockito.mock(UriResourceComplexProperty.class);
  Mockito.when(element.getProperty()).thenReturn(property);
  elements.add(element);
  
  mockNavPropertyOnEdmType(navProperty, elements, property);
  
  UriInfoResource resource = Mockito.mock(UriInfoResource.class);
  Mockito.when(resource.getUriResourceParts()).thenReturn(elements);
  return resource;
}
 
Example #12
Source File: ExpandSelectMock.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private static UriInfoResource mockResourceOnDerivedEntityAndComplexTypes(
    final String name, final EdmType derivedEntityType, final EdmType derivedComplexType, 
    final String pathSegment) {
  EdmStructuredType type = (EdmStructuredType) derivedEntityType;
  List<UriResource> elements = new ArrayList<UriResource>();
  mockComplexPropertyWithTypeFilter(name, derivedComplexType, type, elements);
  
  final EdmElement edmElement1 = ((EdmStructuredType) derivedComplexType).getProperty(pathSegment);
  UriResourceNavigation element1 = Mockito.mock(UriResourceNavigation.class);
  Mockito.when(element1.getProperty()).thenReturn((EdmNavigationProperty) edmElement1);
  elements.add(element1);
  
  UriInfoResource resource = Mockito.mock(UriInfoResource.class);
  Mockito.when(resource.getUriResourceParts()).thenReturn(elements);
  return resource;
}
 
Example #13
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 = this.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 #14
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 = this.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 #15
Source File: ResourcePathParser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void requireMediaResourceInCaseOfEntity(UriResource resource) throws UriParserSemanticException {
  // If the resource is an entity or navigatio
  if (resource instanceof UriResourceEntitySet && !((UriResourceEntitySet) resource).getEntityType().hasStream()
      || resource instanceof UriResourceNavigation
      && !((EdmEntityType) ((UriResourceNavigation) resource).getType()).hasStream()) {
    throw new UriParserSemanticException("$value on entity is only allowed on media resources.",
        UriParserSemanticException.MessageKeys.NOT_A_MEDIA_RESOURCE, resource.getSegmentValue());
  }

  // Functions can also deliver an entity. In this case we have to check if the returned entity is a media resource
  if (resource instanceof UriResourceFunction) {
    EdmType returnType = ((UriResourceFunction) resource).getFunction().getReturnType().getType();
    //Collection check is above so not needed here
    if (returnType instanceof EdmEntityType && !((EdmEntityType) returnType).hasStream()) {
      throw new UriParserSemanticException("$value on returned entity is only allowed on media resources.",
          UriParserSemanticException.MessageKeys.NOT_A_MEDIA_RESOURCE, resource.getSegmentValue());
    }
  }
}
 
Example #16
Source File: ODataDispatcher.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void handleCountDispatching(final ODataRequest request, final ODataResponse response,
    final int lastPathSegmentIndex) throws ODataApplicationException, ODataLibraryException {
  validatePreferHeader(request);
  final UriResource resource = uriInfo.getUriResourceParts().get(lastPathSegmentIndex - 1);
  if (resource instanceof UriResourceEntitySet
      || resource instanceof UriResourceNavigation
      || resource instanceof UriResourceFunction
          && ((UriResourceFunction) resource).getType().getKind() == EdmTypeKind.ENTITY) {
    handler.selectProcessor(CountEntityCollectionProcessor.class)
        .countEntityCollection(request, response, uriInfo);
  } else if (resource instanceof UriResourcePrimitiveProperty
      || resource instanceof UriResourceFunction
          && ((UriResourceFunction) resource).getType().getKind() == EdmTypeKind.PRIMITIVE) {
    handler.selectProcessor(CountPrimitiveCollectionProcessor.class)
        .countPrimitiveCollection(request, response, uriInfo);
  } else {
    handler.selectProcessor(CountComplexCollectionProcessor.class)
        .countComplexCollection(request, response, uriInfo);
  }
}
 
Example #17
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 #18
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 #19
Source File: DebugTabUri.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private String getSelectString(final SelectItem selectItem) {
  if (selectItem.isStar()) {
    if (selectItem.getAllOperationsInSchemaNameSpace() == null) {
      return "*";
    } else {
      return selectItem.getAllOperationsInSchemaNameSpace().getFullQualifiedNameAsString() + ".*";
    }
  } else {
    final StringBuilder tmp = new StringBuilder();
    for (UriResource resourcePart : selectItem.getResourcePath().getUriResourceParts()) {
      if (tmp.length() > 0) {
        tmp.append('/');
      }
      tmp.append(resourcePart.toString());
    }
    return tmp.toString();
  }
}
 
Example #20
Source File: PreconditionsValidatorTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private boolean mustValidate(final String uri, final String entitySetName)
    throws UriParserException, UriValidationException, PreconditionException {
  final UriInfo uriInfo = new Parser(edm, odata).parseUri(uri, null, null, null);
  final List<UriResource> parts = uriInfo.getUriResourceParts();
  final boolean isMedia = parts.size() >= 2
      && parts.get(parts.size() - 1) instanceof UriResourceValue
      && parts.get(parts.size() - 2) instanceof UriResourceEntitySet;

  CustomETagSupport support = mock(CustomETagSupport.class);
  final Answer<Boolean> answer = new Answer<Boolean>() {
    public Boolean answer(final InvocationOnMock invocation) throws Throwable {
      if (entitySetName != null) {
        assertEquals(entitySetName, ((EdmBindingTarget) invocation.getArguments()[0]).getName());
      }
      return true;
    }};
  when(support.hasETag(any(EdmBindingTarget.class))).thenAnswer(answer);
  when(support.hasMediaETag(any(EdmBindingTarget.class))).thenAnswer(answer);

  return new PreconditionsValidator(uriInfo).mustValidatePreconditions(support, isMedia);
}
 
Example #21
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 #22
Source File: ApplyParserTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public ResourceValidator goPath() {
  assertNotNull(aggregateExpression);
  assertFalse(aggregateExpression.getPath().isEmpty());
  UriInfoImpl resource = new UriInfoImpl().setKind(UriInfoKind.resource);
  for (final UriResource segment : aggregateExpression.getPath()) {
    resource.addResourcePart(segment);
  }
  return new ResourceValidator().setUpValidator(this).setEdm(edm).setUriInfoPath(resource);
}
 
Example #23
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 #24
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 #25
Source File: ExpandSelectMock.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static UriInfoResource mockResourceOnDerivedComplexTypes(final EdmEntitySet edmEntitySet,
    final String name, final EdmType derivedType, final String pathSegmentAfterCast) {
  EdmStructuredType type = edmEntitySet.getEntityType();
  List<UriResource> elements = new ArrayList<UriResource>();
  mockComplexPropertyWithTypeFilter(name, derivedType, type, elements);
  
  mockPropertyOnDerivedType(derivedType, pathSegmentAfterCast, elements);
  
  UriInfoResource resource = Mockito.mock(UriInfoResource.class);
  Mockito.when(resource.getUriResourceParts()).thenReturn(elements);
  return resource;
}
 
Example #26
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 #27
Source File: ExpandSelectMock.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static UriInfoResource mockResourceOnFunction(EdmEntitySet edmEntitySet, EdmFunction function) {
  UriResourceFunction element = Mockito.mock(UriResourceFunction.class);
  Mockito.when(element.getFunction()).thenReturn(function);
  List<UriResource> elements = new ArrayList<UriResource>();
  elements.add(element);
  
  UriInfoResource resource = Mockito.mock(UriInfoResource.class);
  Mockito.when(resource.getUriResourceParts()).thenReturn(elements);
  return resource;
}
 
Example #28
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 #29
Source File: ExpandSelectMock.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * @param name
 * @param derivedComplexType
 * @param type
 * @param elements
 */
private static void mockComplexPropertyWithTypeFilter(final String name, final EdmType derivedComplexType,
    EdmStructuredType type, List<UriResource> elements) {
  final EdmElement edmElement = type.getProperty(name);
  final EdmProperty property = (EdmProperty) edmElement;
  UriResourceComplexProperty element = Mockito.mock(UriResourceComplexProperty.class);
  Mockito.when(element.getProperty()).thenReturn(property);
  Mockito.when(element.getComplexTypeFilter()).thenReturn((EdmComplexType) derivedComplexType);
  elements.add(element);
}
 
Example #30
Source File: ExpandSelectHelper.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * @param type
 * @param matched
 * @param resource
 * @return
 */
private static boolean isFoundExpandItem(final EdmStructuredType type, 
    boolean matched, UriResource resource) {
  if (!matched) {
    if ((resource instanceof UriResourceProperty && 
            type.compatibleTo(((UriResourceProperty) resource).getType())) ||
        (resource instanceof UriResourceNavigation && 
            type.compatibleTo(((UriResourceNavigation) resource).getType()))) {
      matched = true;
    }
  }
  return matched;
}