Java Code Examples for org.apache.olingo.commons.api.data.Property#setValue()

The following examples show how to use org.apache.olingo.commons.api.data.Property#setValue() . 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: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity createProduct(EdmEntityType edmEntityType, Entity entity) {

    // the ID of the newly created product entity is generated automatically
    int newId = 1;
    while (productIdExists(newId)) {
      newId++;
    }

    Property idProperty = entity.getProperty("ID");
    if (idProperty != null) {
      idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));
    } else {
      // as of OData v4 spec, the key property can be omitted from the POST request body
      entity.getProperties().add(new Property(null, "ID", ValueType.PRIMITIVE, newId));
    }
    entity.setId(createId("Products", newId));
    this.productList.add(entity);

    return entity;

  }
 
Example 2
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity createProduct(EdmEntityType edmEntityType, Entity entity) {

    // the ID of the newly created product entity is generated automatically
    int newId = 1;
    while (productIdExists(newId)) {
      newId++;
    }

    Property idProperty = entity.getProperty("ID");
    if (idProperty != null) {
      idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));
    } else {
      // as of OData v4 spec, the key property can be omitted from the POST request body
      entity.getProperties().add(new Property(null, "ID", ValueType.PRIMITIVE, newId));
    }
    entity.setId(createId("Products", newId));
    this.productList.add(entity);

    return entity;

  }
 
Example 3
Source File: ODataXmlSerializerTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testXML10ReplacementChar() throws Exception {
  final EdmEntitySet edmEntitySet = entityContainer.getEntitySet("ESAllPrim");
  final EdmProperty edmProperty = (EdmProperty) edmEntitySet.getEntityType().getProperty("PropertyString");
  final Property property = data.readAll(edmEntitySet).getEntities().get(0).getProperty(edmProperty.getName());
  property.setValue(ValueType.PRIMITIVE, "ab\u0000cd\u0001");
  final String resultString = IOUtils.toString(serializer
      .primitive(metadata, (EdmPrimitiveType) edmProperty.getType(), property,
          PrimitiveSerializerOptions.with()
              .contextURL(ContextURL.with()
                  .entitySet(edmEntitySet).keyPath("32767").navOrPropertyPath(edmProperty.getName())
                  .build())
              .xml10InvalidCharReplacement("XX")
              .unicode(Boolean.TRUE)
              .build()).getContent());

  String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
      + "<m:value xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" "
      + "m:context=\"../$metadata#ESAllPrim(32767)/PropertyString\" "
      + "m:metadata-etag=\"metadataETag\">"
      + "abXXcdXX</m:value>";
  Assert.assertEquals(expected, resultString);
}
 
Example 4
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity createEntity(EdmEntityType edmEntityType, Entity entity, List<Entity> entityList) {
  
  // the ID of the newly created entity is generated automatically
  int newId = 1;
  while (entityIdExists(newId, entityList)) {
    newId++;
  }

  Property idProperty = entity.getProperty("ID");
  if (idProperty != null) {
    idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));
  } else {
    // as of OData v4 spec, the key property can be omitted from the POST request body
    entity.getProperties().add(new Property(null, "ID", ValueType.PRIMITIVE, newId));
  }
  entity.setId(createId(entity, "ID"));
  entityList.add(entity);

  return entity;
}
 
Example 5
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity createEntity(EdmEntityType edmEntityType, Entity entity, List<Entity> entityList) {
  
  // the ID of the newly created entity is generated automatically
  int newId = 1;
  while (entityIdExists(newId, entityList)) {
    newId++;
  }

  Property idProperty = entity.getProperty("ID");
  if (idProperty != null) {
    idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));
  } else {
    // as of OData v4 spec, the key property can be omitted from the POST request body
    entity.getProperties().add(new Property(null, "ID", ValueType.PRIMITIVE, newId));
  }
  entity.setId(createId(entity, "ID"));
  entityList.add(entity);

  return entity;
}
 
Example 6
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity createEntity(EdmEntityType edmEntityType, Entity entity, List<Entity> entityList) {
  
  // the ID of the newly created entity is generated automatically
  int newId = 1;
  while (entityIdExists(newId, entityList)) {
    newId++;
  }

  Property idProperty = entity.getProperty("ID");
  if (idProperty != null) {
    idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));
  } else {
    // as of OData v4 spec, the key property can be omitted from the POST request body
    entity.getProperties().add(new Property(null, "ID", ValueType.PRIMITIVE, newId));
  }
  entity.setId(createId(entity, "ID"));
  entityList.add(entity);

  return entity;
}
 
Example 7
Source File: Services.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/StoredPIs(1000)")
public Response getStoredPI(@Context final UriInfo uriInfo) {
  final Entity entity = new Entity();
  entity.setType("Microsoft.Test.OData.Services.ODataWCFService.StoredPI");
  final Property id = new Property();
  id.setType("Edm.Int32");
  id.setName("StoredPIID");
  id.setValue(ValueType.PRIMITIVE, 1000);
  entity.getProperties().add(id);
  final Link edit = new Link();
  edit.setHref(uriInfo.getRequestUri().toASCIIString());
  edit.setRel("edit");
  edit.setTitle("StoredPI");
  entity.setEditLink(edit);

  final ByteArrayOutputStream content = new ByteArrayOutputStream();
  final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
  try {
    jsonSerializer.write(writer, new ResWrap<Entity>((URI) null, null, entity));
    return xml.createResponse(new ByteArrayInputStream(content.toByteArray()), null, Accept.JSON_FULLMETA);
  } catch (Exception e) {
    LOG.error("While creating StoredPI", e);
    return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), e);
  }
}
 
Example 8
Source File: Storage.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private Entity createProduct(Entity entity) {
    // the ID of the newly created product entity is generated automatically
    int newId = 1;
    while (productIdExists(newId)) {
        newId++;
    }

    Property idProperty = entity.getProperty(PRODUCT_ID);
    if (idProperty != null) {
        idProperty.setValue(ValueType.PRIMITIVE, Integer.valueOf(newId));
    } else {
        // as of OData v4 spec, the key property can be omitted from the POST request body
        entity.getProperties().add(new Property(null, PRODUCT_ID, ValueType.PRIMITIVE, newId));
    }
    entity.setId(createId(ES_PRODUCTS_NAME, newId));
    this.productList.add(entity);

    return entity;

}
 
Example 9
Source File: Services.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/Company/Microsoft.Test.OData.Services.ODataWCFService.GetEmployeesCount{paren:[\\(\\)]*}")
public Response functionGetEmployeesCount(
    @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
    @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

  try {
    final Accept acceptType;
    if (StringUtils.isNotBlank(format)) {
      acceptType = Accept.valueOf(format.toUpperCase());
    } else {
      acceptType = Accept.parse(accept);
    }

    final Property property = new Property();
    property.setType("Edm.Int32");
    property.setValue(ValueType.PRIMITIVE, 2);
    final ResWrap<Property> container = new ResWrap<Property>(
        URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + property.getType()), null,
        property);

    return xml.createResponse(
        null,
        xml.writeProperty(acceptType, container),
        null,
        acceptType);
  } catch (Exception e) {
    return xml.createFaultResponse(accept, e);
  }
}
 
Example 10
Source File: Services.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/GetDefaultColor()")
public Response functionGetDefaultColor(
    @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
    @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

  try {
    final Accept acceptType;
    if (StringUtils.isNotBlank(format)) {
      acceptType = Accept.valueOf(format.toUpperCase());
    } else {
      acceptType = Accept.parse(accept);
    }

    final Property property = new Property();
    property.setType("Microsoft.Test.OData.Services.ODataWCFService.Color");
    property.setValue(ValueType.ENUM, "Red");
    final ResWrap<Property> container = new ResWrap<Property>(
        URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + property.getType()), null,
        property);

    return xml.createResponse(
        null,
        xml.writeProperty(acceptType, container),
        null,
        acceptType);
  } catch (Exception e) {
    return xml.createFaultResponse(accept, e);
  }
}
 
Example 11
Source File: Services.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/GetProductsByAccessLevel({param:.*})")
public Response functionGetProductsByAccessLevel(
    @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
    @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

  try {
    final Accept acceptType;
    if (StringUtils.isNotBlank(format)) {
      acceptType = Accept.valueOf(format.toUpperCase());
    } else {
      acceptType = Accept.parse(accept);
    }

    final Property property = new Property();
    property.setType("Collection(String)");
    final List<String> value = Arrays.asList("Cheetos", "Mushrooms", "Apple", "Car", "Computer");
    property.setValue(ValueType.COLLECTION_PRIMITIVE, value);
    final ResWrap<Property> container = new ResWrap<Property>(
        URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + property.getType()), null,
        property);

    return xml.createResponse(
        null,
        xml.writeProperty(acceptType, container),
        null,
        acceptType);
  } catch (Exception e) {
    return xml.createFaultResponse(accept, e);
  }
}
 
Example 12
Source File: Services.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/GetBossEmails({param:.*})")
public Response functionGetBossEmails(
    @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
    @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

  try {
    final Accept acceptType;
    if (StringUtils.isNotBlank(format)) {
      acceptType = Accept.valueOf(format.toUpperCase());
    } else {
      acceptType = Accept.parse(accept);
    }

    final Property property = new Property();
    property.setType("Collection(Edm.String)");
    property.setValue(ValueType.COLLECTION_PRIMITIVE,
        Arrays.asList("[email protected]", "[email protected]"));
    final ResWrap<Property> container = new ResWrap<Property>(
        URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + property.getType()), null,
        property);

    return xml.createResponse(null, xml.writeProperty(acceptType, container), null, acceptType);
  } catch (Exception e) {
    return xml.createFaultResponse(accept, e);
  }
}
 
Example 13
Source File: ActionData.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected static EntityActionResult entityBoundActionWithNavigation(final String name, 
    final Map<String, Parameter> parameters,
    final Map<String, EntityCollection> data, List<UriParameter> keyList, 
    EdmEntitySet edmEntitySet, EdmNavigationProperty navProperty) 
        throws DataProviderException {
  List<Object> keyPropertyValues = new ArrayList<Object>();
  List<String> keyPropertyNames = new ArrayList<String>();
  if ("BAETTwoKeyNavRTETTwoKeyNavParam".equals(name)) {
    if (!keyList.isEmpty()) {
      setBindingPropertyKeyNameAndValue(keyList, edmEntitySet, keyPropertyValues, keyPropertyNames);
      EntityCollection entityCollection = data.get(edmEntitySet.getName());
      Entity entity = getSpecificEntity(entityCollection, keyPropertyValues, keyPropertyNames);
      
      Link link = entity.getNavigationLink(navProperty.getName());
      Entity inlineEntity = link.getInlineEntity();
      ComplexValue complexValue = inlineEntity.getProperty("PropertyComp").asComplex();
      List<Property> complexProperties = complexValue.getValue();
      Iterator<Property> itr = complexProperties.iterator();
      Parameter actionParam = parameters.get("PropertyComp");
      Property actionProp = actionParam.asComplex().getValue().get(0);
      while (itr.hasNext()) {
        Property property = itr.next();
        if (property.getName().equals(actionProp.getName())) {
          property.setValue(actionProp.getValueType(), actionProp.getValue());
          break;
        }
      }
      return new EntityActionResult().setEntity(inlineEntity);
      }
  }
  throw new DataProviderException("Action " + name + " is not yet implemented.",
      HttpStatusCode.NOT_IMPLEMENTED);
}
 
Example 14
Source File: TechnicalPrimitiveComplexProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void deleteProperty(final ODataRequest request, ODataResponse response, final UriInfo uriInfo,
    final boolean isValue) throws ODataLibraryException, ODataApplicationException {
  final UriInfoResource resource = uriInfo.asUriInfoResource();
  validatePath(resource);
  getEdmEntitySet(uriInfo); // including checks

  Entity entity = readEntity(uriInfo);
  odata.createETagHelper().checkChangePreconditions(entity.getETag(),
      request.getHeaders(HttpHeader.IF_MATCH),
      request.getHeaders(HttpHeader.IF_NONE_MATCH));

  final List<UriResource> resourceParts = resource.getUriResourceParts();
  final int trailing = isValue ? 1 : 0;
  final List<String> path = getPropertyPath(resourceParts, trailing);

  Property property = getPropertyData(entity, path);

  final EdmProperty edmProperty = ((UriResourceProperty) resourceParts.get(resourceParts.size() - trailing - 1))
      .getProperty();

  if (edmProperty.isNullable()) {
    property.setValue(property.getValueType(), edmProperty.isCollection() ? Collections.emptyList() : null);
    dataProvider.updateETag(entity);
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
    if (entity.getETag() != null) {
      response.setHeader(HttpHeader.ETAG, entity.getETag());
    }
  } else {
    throw new ODataApplicationException("Not nullable.", HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
  }
}
 
Example 15
Source File: UriHelperTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test(expected = SerializerException.class)
public void canonicalURLWithKeyHavingNullValue() throws Exception {
  final EdmEntitySet entitySet = container.getEntitySet("ESAllPrim");
  Entity entity = data.readAll(entitySet).getEntities().get(0);
  Property property = entity.getProperties().get(0);
  property.setValue(property.getValueType(), null);
  helper.buildCanonicalURL(entitySet, entity);
  expectedEx.expect(SerializerException.class);
  expectedEx.expectMessage("Wrong key value!");
}
 
Example 16
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());
  }
}
 
Example 17
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void consumePropertySingleNode(final String name, final EdmType type,
    final boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale,
    final boolean isUnicode, final EdmMapping mapping, final JsonNode jsonNode, final Property property)
    throws DeserializerException {
  switch (type.getKind()) {
  case PRIMITIVE:
  case DEFINITION:
  case ENUM:
    Object value = readPrimitiveValue(name, (EdmPrimitiveType) type,
        isNullable, maxLength, precision, scale, isUnicode, mapping, jsonNode);
    property.setValue(type.getKind() == EdmTypeKind.ENUM ? ValueType.ENUM : ValueType.PRIMITIVE,
        value);
    break;
  case COMPLEX:
    EdmType derivedType = getDerivedType((EdmComplexType) type,
        jsonNode);
    property.setType(derivedType.getFullQualifiedName()
        .getFullQualifiedNameAsString());

    value = readComplexNode(name, derivedType, isNullable, jsonNode);
    property.setValue(ValueType.COMPLEX, value);
    break;
  default:
    throw new DeserializerException("Invalid Type Kind for a property found: " + type.getKind(),
        DeserializerException.MessageKeys.INVALID_JSON_TYPE_FOR_PROPERTY, name);
  }
}
 
Example 18
Source File: TripPinHandler.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void updateProperty(DataRequest request, final Property property, boolean rawValue, boolean merge,
    String entityETag, PropertyResponse response) throws ODataLibraryException,
    ODataApplicationException {

  if (rawValue && property.getValue() != null) {
    // this is more generic, stricter conversion rules must taken in a real service
    byte[] value = (byte[])property.getValue();
    property.setValue(ValueType.PRIMITIVE, new String(value));
  }
  
  EdmEntitySet edmEntitySet = request.getEntitySet();
  Entity entity = this.dataModel.getEntity(edmEntitySet.getName(), request.getKeyPredicates());
  if (entity == null) {
    response.writeNotFound(true);
    return;
  }

  String key = edmEntitySet.getEntityType().getKeyPredicateNames().get(0);
  boolean replaced = this.dataModel.updateProperty(edmEntitySet.getName(), entityETag, key,
      entity.getProperty(key).getValue(), property);

  if (replaced) {
    if (property.getValue() == null) {
      response.writePropertyDeleted();
    } else {
      response.writePropertyUpdated();
    }
  } else {
    response.writeServerError(true);
  }
}
 
Example 19
Source File: Services.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private Response patchEntityInternal(final UriInfo uriInfo,
    final String accept, final String contentType, final String prefer, final String ifMatch,
    final String entitySetName, final String entityId, final String changes) {

  try {
    final Accept acceptType = Accept.parse(accept);

    if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
      throw new UnsupportedMediaTypeException("Unsupported media type");
    }

    final Map.Entry<String, InputStream> entityInfo = xml.readEntity(entitySetName, entityId, Accept.ATOM);

    final String etag = Commons.getETag(entityInfo.getKey());
    if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) {
      throw new ConcurrentModificationException("Concurrent modification");
    }

    final Accept contentTypeValue = Accept.parse(contentType);

    final Entity entryChanges;

    if (contentTypeValue == Accept.XML || contentTypeValue == Accept.TEXT) {
      throw new UnsupportedMediaTypeException("Unsupported media type");
    } else if (contentTypeValue == Accept.ATOM) {
      entryChanges = atomDeserializer.toEntity(
          IOUtils.toInputStream(changes, Constants.ENCODING)).getPayload();
    } else {
      final ResWrap<Entity> jcont = jsonDeserializer.toEntity(IOUtils.toInputStream(changes, Constants.ENCODING));
      entryChanges = jcont.getPayload();
    }

    final ResWrap<Entity> container = atomDeserializer.toEntity(entityInfo.getValue());

    for (Property property : entryChanges.getProperties()) {
      final Property _property = container.getPayload().getProperty(property.getName());
      if (_property == null) {
        container.getPayload().getProperties().add(property);
      } else {
        _property.setValue(property.getValueType(), property.getValue());
      }
    }

    for (Link link : entryChanges.getNavigationLinks()) {
      container.getPayload().getNavigationLinks().add(link);
    }

    final ByteArrayOutputStream content = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
    atomSerializer.write(writer, container);
    writer.flush();
    writer.close();

    final InputStream res = xml.addOrReplaceEntity(
        entityId, entitySetName, new ByteArrayInputStream(content.toByteArray()), container.getPayload());

    final ResWrap<Entity> cres = atomDeserializer.toEntity(res);

    normalizeAtomEntry(cres.getPayload(), entitySetName, entityId);

    final String path = Commons.getEntityBasePath(entitySetName, entityId);
    FSManager.instance().putInMemory(
        cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY));

    final Response response;
    if ("return-content".equalsIgnoreCase(prefer)) {
      response = xml.createResponse(
          uriInfo.getRequestUri().toASCIIString(),
          xml.readEntity(entitySetName, entityId, acceptType).getValue(),
          null, acceptType, Response.Status.OK);
    } else {
      res.close();
      response = xml.createResponse(
          uriInfo.getRequestUri().toASCIIString(),
          null,
          null,
          acceptType, Response.Status.NO_CONTENT);
    }

    if (StringUtils.isNotBlank(prefer)) {
      response.getHeaders().put("Preference-Applied", Collections.<Object> singletonList(prefer));
    }

    return response;
  } catch (Exception e) {
    return xml.createFaultResponse(accept, e);
  }
}
 
Example 20
Source File: DataProvider.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
public void updatePropertyValue(Property property, final Object value) {
  property.setValue(property.getValueType(), value);
}