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

The following examples show how to use org.apache.olingo.server.api.uri.UriParameter. 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: 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 #2
Source File: ProductEntityProcessor.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
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();
    for (UriParameter kp : keyPredicates) {
        LOG.info("Deleting entity {} ( {} )", kp.getName(), kp.getText());
    }

    storage.deleteEntityData(edmEntitySet, keyPredicates);

    // 3. configure the response object
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #3
Source File: ParserHelper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private static UriParameter keyValuePair(UriTokenizer tokenizer,
    final String keyPredicateName, final EdmEntityType edmEntityType,
    final Edm edm, final EdmType referringType, final Map<String, AliasQueryOption> aliases)
    throws UriParserException, UriValidationException {
  final EdmKeyPropertyRef keyPropertyRef = edmEntityType.getKeyPropertyRef(keyPredicateName);
  final EdmProperty edmProperty = keyPropertyRef == null ? null : keyPropertyRef.getProperty();
  if (edmProperty == null) {
    throw new UriValidationException(keyPredicateName + " is not a valid key property name.",
        UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, keyPredicateName);
  }
  ParserHelper.requireNext(tokenizer, TokenKind.EQ);
  if (tokenizer.next(TokenKind.COMMA) || tokenizer.next(TokenKind.CLOSE) || tokenizer.next(TokenKind.EOF)) {
    throw new UriParserSyntaxException("Key value expected.", UriParserSyntaxException.MessageKeys.SYNTAX);
  }
  if (nextPrimitiveTypeValue(tokenizer, (EdmPrimitiveType) edmProperty.getType(), edmProperty.isNullable())) {
    return createUriParameter(edmProperty, keyPredicateName, tokenizer.getText(), edm, referringType, aliases);
  } else {
    throw new UriParserSemanticException(keyPredicateName + " has not a valid  key value.",
        UriParserSemanticException.MessageKeys.INVALID_KEY_VALUE, keyPredicateName);
  }
}
 
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: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getProduct(EdmEntityType edmEntityType, List<UriParameter> keyParams) throws ODataApplicationException{

		// the list of entities at runtime
		EntityCollection entitySet = getProducts();
		
		/*  generic approach  to find the requested entity */
		Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);
		
		if(requestedEntity == null){
			// this variable is null if our data doesn't contain an entity for the requested key
			// Throw suitable exception
			throw new ODataApplicationException("Entity for requested key doesn't exist",
          HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
		}

		return requestedEntity;
	}
 
Example #6
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #7
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

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

  EdmProperty property = request.getUriResourceProperty().getProperty();

  if (streamContent == null) {
    boolean deleted = this.dataModel.deleteStream(entity, property);
    if (deleted) {
      response.writeNoContent();
    } else {
      response.writeNotFound();
    }
  } else {
    boolean updated = this.dataModel.updateStream(entity, property, streamContent);
    if (updated) {
      response.writeNoContent();
    } else {
      response.writeServerError(true);
    }
  }
}
 
Example #9
Source File: Util.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet, List<UriParameter> keyParams)
    throws ODataApplicationException {

    List<Entity> entityList = entitySet.getEntities();

    // loop over all entities in order to find that one that matches all keys in request
    // e.g. contacts(ContactID=1, CompanyID=1)
    for (Entity entity : entityList) {
        boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
        if (foundEntity) {
            return entity;
        }
    }

    return null;
}
 
Example #10
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #11
Source File: ODataAdapter.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method return entity by searching from the entity collection according to keys and etag.
 *
 * @param entityType       EdmEntityType
 * @param entityCollection EntityCollection
 * @param keys             keys
 * @return Entity
 * @throws ODataApplicationException
 * @throws ODataServiceFault
 */
private Entity getEntity(EdmEntityType entityType, EntityCollection entityCollection, List<UriParameter> keys)
        throws ODataApplicationException, ODataServiceFault {
    List<Entity> search = null;
    if (entityCollection.getEntities().isEmpty()) {
        if (log.isDebugEnabled()) {
            StringBuilder message = new StringBuilder();
            message.append("Entity collection was null , For ");
            for (UriParameter parameter : keys) {
                message.append(parameter.getName()).append(" = ").append(parameter.getText()).append(" ,");
            }
            message.append(".");
            log.debug(message);
        }
        return null;
    }
    for (UriParameter param : keys) {
        search = getMatch(entityType, param, entityCollection.getEntities());
    }
    if (search == null) {
        return null;
    } else {
        return search.get(0);
    }
}
 
Example #12
Source File: ODataAdapter.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns matched entity list, where it uses in getEntity method to get the matched entity.
 *
 * @param entityType EdmEntityType
 * @param param      UriParameter
 * @param entityList List of entities
 * @return list of entities
 * @throws ODataApplicationException
 * @throws ODataServiceFault
 */
private List<Entity> getMatch(EdmEntityType entityType, UriParameter param, List<Entity> entityList)
        throws ODataApplicationException, ODataServiceFault {
    ArrayList<Entity> list = new ArrayList<>();
    for (Entity entity : entityList) {
        EdmProperty property = (EdmProperty) entityType.getProperty(param.getName());
        EdmType type = property.getType();
        if (type.getKind() == EdmTypeKind.PRIMITIVE) {
            Object match = readPrimitiveValue(property, param.getText());
            Property entityValue = entity.getProperty(param.getName());
            if (match != null) {
                if (match.equals(entityValue.asPrimitive())) {
                    list.add(entity);
                }
            } else {
                if (null == entityValue.asPrimitive()) {
                    list.add(entity);
                }
            }
        } else {
            throw new ODataServiceFault("Complex elements are not supported, couldn't compare complex objects.");
        }
    }
    return list;
}
 
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 = 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: ParserHelper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private static UriParameter createUriParameter(final EdmProperty edmProperty, final String parameterName,
    final String literalValue, final Edm edm, final EdmType referringType,
    final Map<String, AliasQueryOption> aliases) throws UriParserException, UriValidationException {
  final AliasQueryOption alias = literalValue.startsWith("@") ?
      getKeyAlias(literalValue, edmProperty, edm, referringType, aliases) :
      null;
  final String value = alias == null ? literalValue : alias.getText();
  final EdmPrimitiveType primitiveType = (EdmPrimitiveType) edmProperty.getType();
  try {
    if (!(primitiveType.validate(primitiveType.fromUriLiteral(value), edmProperty.isNullable(),
        edmProperty.getMaxLength(), edmProperty.getPrecision(), edmProperty.getScale(), edmProperty.isUnicode()))) {
      throw new UriValidationException("Invalid key property",
          UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, parameterName);
    }
  } catch (final EdmPrimitiveTypeException e) {
    throw new UriValidationException("Invalid key property", e,
        UriValidationException.MessageKeys.INVALID_KEY_PROPERTY, parameterName);
  }

  return new UriParameterImpl()
      .setName(parameterName)
      .setText("null".equals(literalValue) ? null : literalValue)
      .setAlias(alias == null ? null : literalValue)
      .setExpression(alias == null ? null :
          alias.getValue() == null ? new LiteralImpl(value, primitiveType) : alias.getValue());
}
 
Example #15
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getProduct(EdmEntityType edmEntityType, List<UriParameter> keyParams) throws ODataApplicationException{

		// the list of entities at runtime
		EntityCollection entitySet = getProducts();
		
		/*  generic approach  to find the requested entity */
		Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);
		
		if(requestedEntity == null){
			// this variable is null if our data doesn't contain an entity for the requested key
			// Throw suitable exception
			throw new ODataApplicationException("Entity for requested key doesn't exist",
          HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
		}

		return requestedEntity;
	}
 
Example #16
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 #17
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
                                List<UriParameter> keyParams) throws ODataApplicationException {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches all keys in request
  // e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity: entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example #18
Source File: ContextURLHelperTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void buildKeyAlias() throws Exception {
  final EdmEntitySet entitySet = entityContainer.getEntitySet("ESFourKeyAlias");
  final EdmProperty edmProperty = entitySet.getEntityType().getStructuralProperty("PropertyComp");
  UriParameter key1 = Mockito.mock(UriParameter.class);
  Mockito.when(key1.getName()).thenReturn("PropertyInt16");
  Mockito.when(key1.getText()).thenReturn("1");
  UriParameter key2 = Mockito.mock(UriParameter.class);
  Mockito.when(key2.getName()).thenReturn("KeyAlias1");
  Mockito.when(key2.getText()).thenReturn("11");
  UriParameter key3 = Mockito.mock(UriParameter.class);
  Mockito.when(key3.getName()).thenReturn("KeyAlias2");
  Mockito.when(key3.getText()).thenReturn("'Num11'");
  UriParameter key4 = Mockito.mock(UriParameter.class);
  Mockito.when(key4.getName()).thenReturn("KeyAlias3");
  Mockito.when(key4.getText()).thenReturn("'Num111'");
  final ContextURL contextURL = ContextURL.with().entitySet(entitySet)
      .keyPath(ContextURLHelper.buildKeyPredicate(Arrays.asList(key1, key2, key3, key4)))
      .navOrPropertyPath(edmProperty.getName()).build();
  assertEquals("../$metadata#ESFourKeyAlias"
          + "(PropertyInt16=1,KeyAlias1=11,KeyAlias2='Num11',KeyAlias3='Num111')/PropertyComp",
      ContextURLBuilder.create(contextURL).toASCIIString());
}
 
Example #19
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 #20
Source File: ExpressionParser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void parseFunction(final FullQualifiedName fullQualifiedName, UriInfoImpl uriInfo,
    final EdmType lastType, final boolean lastIsCollection) throws UriParserException, UriValidationException {

  final List<UriParameter> parameters =
      ParserHelper.parseFunctionParameters(tokenizer, edm, referringType, true, aliases);
  final List<String> parameterNames = ParserHelper.getParameterNames(parameters);
  final EdmFunction boundFunction = edm.getBoundFunction(fullQualifiedName,
      lastType.getFullQualifiedName(), lastIsCollection, parameterNames);

  if (boundFunction != null) {
    ParserHelper.validateFunctionParameters(boundFunction, parameters, edm, referringType, aliases);
    parseFunctionRest(uriInfo, boundFunction, parameters);
    return;
  }

  final EdmFunction unboundFunction = edm.getUnboundFunction(fullQualifiedName, parameterNames);
  if (unboundFunction != null) {
    ParserHelper.validateFunctionParameters(unboundFunction, parameters, edm, referringType, aliases);
    parseFunctionRest(uriInfo, unboundFunction, parameters);
    return;
  }

  throw new UriParserSemanticException("No function '" + fullQualifiedName + "' found.",
      UriParserSemanticException.MessageKeys.FUNCTION_NOT_FOUND, fullQualifiedName.getFullQualifiedNameAsString());
}
 
Example #21
Source File: Util.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public static Entity findEntity(EdmEntityType edmEntityType, EntityCollection entitySet,
    List<UriParameter> keyParams) {

  List<Entity> entityList = entitySet.getEntities();

  // loop over all entities in order to find that one that matches
  // all keys in request e.g. contacts(ContactID=1, CompanyID=1)
  for (Entity entity : entityList) {
    boolean foundEntity = entityMatchesAllKeys(edmEntityType, entity, keyParams);
    if (foundEntity) {
      return entity;
    }
  }

  return null;
}
 
Example #22
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #23
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getProduct(EdmEntityType edmEntityType, List<UriParameter> keyParams)
			throws ODataApplicationException {

  // the list of entities at runtime
  EntityCollection entitySet = getProducts();

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #24
Source File: ExpressionParser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void parseDollarRoot(UriInfoImpl uriInfo) throws UriParserException, UriValidationException {
  UriResourceRootImpl rootResource = new UriResourceRootImpl(referringType, true);
  uriInfo.addResourcePart(rootResource);
  ParserHelper.requireNext(tokenizer, TokenKind.SLASH);
  ParserHelper.requireNext(tokenizer, TokenKind.ODataIdentifier);
  final String name = tokenizer.getText();
  UriResourcePartTyped resource = null;
  final EdmEntitySet entitySet = edm.getEntityContainer().getEntitySet(name);
  if (entitySet == null) {
    final EdmSingleton singleton = edm.getEntityContainer().getSingleton(name);
    if (singleton == null) {
      throw new UriParserSemanticException("EntitySet or singleton expected.",
          UriParserSemanticException.MessageKeys.UNKNOWN_PART, name);
    } else {
      resource = new UriResourceSingletonImpl(singleton);
    }
  } else {
    ParserHelper.requireNext(tokenizer, TokenKind.OPEN);
    final List<UriParameter> keyPredicates =
        ParserHelper.parseKeyPredicate(tokenizer, entitySet.getEntityType(), null, edm, referringType, aliases);
    resource = new UriResourceEntitySetImpl(entitySet).setKeyPredicates(keyPredicates);
  }
  uriInfo.addResourcePart(resource);
  parseSingleNavigationExpr(uriInfo, resource);
}
 
Example #25
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList)
    throws ODataApplicationException {

  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #26
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 #27
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  // the list of entities at runtime
  EntityCollection entitySet = getEntityCollection(entityList);

  /* generic approach to find the requested entity */
  Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);

  if (requestedEntity == null) {
    // this variable is null if our data doesn't contain an entity for the requested key
    // Throw suitable exception
    throw new ODataApplicationException("Entity for requested key doesn't exist",
        HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  return requestedEntity;
}
 
Example #28
Source File: ContextURLHelper.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a key predicate for the ContextURL.
 * @param keys the keys as a list of {@link UriParameter} instances
 * @return a String with the key predicate
 */
public static String buildKeyPredicate(final List<UriParameter> keys) throws SerializerException {
  if (keys == null || keys.isEmpty()) {
    return null;
  } else if (keys.size() == 1) {
    return Encoder.encode(keys.get(0).getText());
  } else {
    StringBuilder result = new StringBuilder();
    for (final UriParameter key : keys) {
      if (result.length() > 0) {
        result.append(',');
      }
      result.append(Encoder.encode(key.getName())).append('=').append(Encoder.encode(key.getText()));
    }
    return result.toString();
  }
}
 
Example #29
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void deleteEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  Entity entity = getEntity(edmEntityType, keyParams, entityList);
  if (entity == null) {
    throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  entityList.remove(entity);
}
 
Example #30
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void updateProduct(EdmEntityType edmEntityType, List<UriParameter> keyParams, Entity entity,
    HttpMethod httpMethod) throws ODataApplicationException {

  Entity productEntity = getProduct(edmEntityType, keyParams);
  if (productEntity == null) {
    throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
  }

  // loop over all properties and replace the values with the values of the given payload
  // Note: ignoring ComplexType, as we don't have it in our odata model
  List<Property> existingProperties = productEntity.getProperties();
  for (Property existingProp : existingProperties) {
    String propName = existingProp.getName();

    // ignore the key properties, they aren't updateable
    if (isKey(edmEntityType, propName)) {
      continue;
    }

    Property updateProperty = entity.getProperty(propName);
    // the request payload might not consider ALL properties, so it can be null
    if (updateProperty == null) {
      // if a property has NOT been added to the request payload
      // depending on the HttpMethod, our behavior is different
      if (httpMethod.equals(HttpMethod.PATCH)) {
        // as of the OData spec, in case of PATCH, the existing property is not touched
        continue; // do nothing
      } else if (httpMethod.equals(HttpMethod.PUT)) {
        // as of the OData spec, in case of PUT, the existing property is set to null (or to default value)
        existingProp.setValue(existingProp.getValueType(), null);
        continue;
      }
    }

    // change the value of the properties
    existingProp.setValue(existingProp.getValueType(), updateProperty.getValue());
  }
}