Java Code Examples for org.apache.olingo.commons.api.data.Entity#getProperties()

The following examples show how to use org.apache.olingo.commons.api.data.Entity#getProperties() . 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: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void odataControlInformationIsIgnoredForRequests() throws Exception {
  String entityString =
      "{"
          + "\"@odata.context\":\"http://localhost:8080\","
          + "\"@odata.metadataEtag\":\"metadataEtag\","
          + "\"@odata.id\":\"value\","
          + "\"@odata.editLink\":\"value\","
          + "\"@odata.readLink\":\"value\","
          + "\"@odata.etag\":\"value\","
          + "\"@odata.mediaEtag\":\"value\","
          + "\"@odata.mediaReadLink\":\"value\","
          + "\"@odata.mediaEditLink\":\"value\","
          + "\"PropertyInt16\":32767,"
          + "\"PropertyString\":\"First Resource - positive values\""
          + "}";
  final Entity entity = deserialize(entityString, "ETAllPrim");
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(2, properties.size());
}
 
Example 2
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private List<Entity> cloneEntityCollection(final List<Entity> entities) {
  final List<Entity> clonedEntities = new ArrayList<Entity>();
  
  for(final Entity entity : entities) {
    final Entity clonedEntity = new Entity();
    
    clonedEntity.setId(entity.getId());
    for(final Property property : entity.getProperties()) {
      clonedEntity.addProperty(new Property(property.getType(), 
                                            property.getName(), 
                                            property.getValueType(), 
                                            property.getValue()));
    }
     
    clonedEntities.add(clonedEntity);
  }
  
  return clonedEntities;
}
 
Example 3
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 4
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void mappingTest() throws Exception {
  EdmEntityType entityType = mock(EdmEntityType.class);
  when(entityType.getFullQualifiedName()).thenReturn(new FullQualifiedName("namespace", "name"));
  List<String> propertyNames = new ArrayList<String>();
  propertyNames.add("PropertyDate");
  propertyNames.add("PropertyDateTimeOffset");
  when(entityType.getPropertyNames()).thenReturn(propertyNames);
  CsdlMapping mapping = new CsdlMapping().setMappedJavaClass(Date.class);

  EdmProperty propertyDate = mock(EdmProperty.class);
  when(propertyDate.getName()).thenReturn("PropertyDate");
  when(propertyDate.getMapping()).thenReturn(mapping);
  when(propertyDate.getType()).thenReturn(odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.Date));
  when(entityType.getProperty("PropertyDate")).thenReturn(propertyDate);

  EdmProperty propertyDateTimeOffset = mock(EdmProperty.class);
  when(propertyDateTimeOffset.getName()).thenReturn("PropertyDateTimeOffset");
  when(propertyDateTimeOffset.getMapping()).thenReturn(mapping);
  when(propertyDateTimeOffset.getType()).thenReturn(
      odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.DateTimeOffset));
  when(entityType.getProperty("PropertyDateTimeOffset")).thenReturn(propertyDateTimeOffset);

  String entityString =
      "{\"PropertyDate\":\"2012-12-03\","
          + "\"PropertyDateTimeOffset\":\"2012-12-03T07:16:23Z\"}";
  InputStream stream = new ByteArrayInputStream(entityString.getBytes());
  ODataDeserializer deserializer = odata.createDeserializer(ContentType.JSON, metadata);
  Entity entity = deserializer.entity(stream, entityType).getEntity();
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(2, properties.size());

  assertNotNull(entity.getProperty("PropertyDate").getValue());
  assertEquals(java.sql.Date.class, entity.getProperty("PropertyDate").getValue().getClass());
  assertNotNull(entity.getProperty("PropertyDateTimeOffset").getValue());
  assertEquals(java.sql.Timestamp.class, entity.getProperty("PropertyDateTimeOffset").getValue().getClass());
}
 
Example 5
Source File: EdmAssistedJsonSerializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
protected void doSerialize(final EdmEntityType entityType, final Entity entity,
    final String contextURLString, final String metadataETag, JsonGenerator json)
    throws IOException, SerializerException {

  json.writeStartObject();

  final String typeName = entity.getType() == null ? null : new EdmTypeInfo.Builder().setTypeExpression(entity
      .getType()).build().external();
  metadata(contextURLString, metadataETag, entity.getETag(), typeName, entity.getId(), true, json);

  for (final Annotation annotation : entity.getAnnotations()) {
    valuable(json, annotation, '@' + annotation.getTerm(), null, null);
  }

  for (final Property property : entity.getProperties()) {
    final String name = property.getName();
    final EdmProperty edmProperty = entityType == null || entityType.getStructuralProperty(name) == null ? null
        : entityType.getStructuralProperty(name);
    valuable(json, property, name, edmProperty == null ? null : edmProperty.getType(), edmProperty);
  }

  if (!isODataMetadataNone &&
      entity.getEditLink() != null && entity.getEditLink().getHref() != null) {
    json.writeStringField(Constants.JSON_EDIT_LINK, entity.getEditLink().getHref());

    if (entity.isMediaEntity()) {
      json.writeStringField(Constants.JSON_MEDIA_READ_LINK, entity.getEditLink().getHref() + "/$value");
    }
  }

  links(entity, entityType, json);

  json.writeEndObject();
}
 
Example 6
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void deriveEntityETMixPrimCollComp() throws Exception {
  final String entityString = "{"
      + "\"PropertyInt16\":32767,"
      + "\"CollPropertyString\":"
      + "[\"[email protected]\",\"[email protected]\",\"[email protected]\"],"
      + "\"PropertyComp\":{\"@odata.type\": \"#olingo.odata.test1.CTBase\","
      + "\"PropertyInt16\":111,\"PropertyString\":\"TEST A\",\"AdditionalPropString\":\"Additional\"},"
      + "\"CollPropertyComp\":["
      + "{\"@odata.type\": \"#olingo.odata.test1.CTBase\",\n"
      + "\"PropertyInt16\":123,\"PropertyString\":\"TEST 1\",\"AdditionalPropString\":\"Additional\"},"
      + "{\"PropertyInt16\":456,\"PropertyString\":\"TEST 2\"},"
      + "{\"PropertyInt16\":789,\"PropertyString\":\"TEST 3\"}]}";
  final Entity entity = deserialize(entityString, "ETMixPrimCollComp");
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(4, properties.size());
  Property prop = entity.getProperty("PropertyComp");
  ComplexValue asComp = prop.asComplex();
  assertEquals(3,asComp.getValue().size());
  assertEquals("olingo.odata.test1.CTBase",prop.getType());
  Property property = entity.getProperty("CollPropertyComp");
  assertEquals(ValueType.COLLECTION_COMPLEX, property.getValueType());

  assertTrue(property.getValue() instanceof List);
  List<? extends Object> asCollection = property.asCollection();
  assertEquals(3, asCollection.size());
  assertEquals(3,((ComplexValue)asCollection.get(0)).getValue().size());
  assertEquals(2,((ComplexValue)asCollection.get(1)).getValue().size());
  assertEquals(2,((ComplexValue)asCollection.get(2)).getValue().size());
}
 
Example 7
Source File: ODataDeserializerEntityCollectionTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void esAllPrim() throws Exception {
  final EntityCollection entitySet = deserialize(getFileAsStream("ESAllPrim.json"), "ETAllPrim");
  assertNotNull(entitySet);
  assertEquals(3, entitySet.getEntities().size());

  // Check first entity
  Entity entity = entitySet.getEntities().get(0);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(16, properties.size());

  assertEquals(new Short((short) 32767), entity.getProperty("PropertyInt16").getValue());
  assertEquals("First Resource - positive values", entity.getProperty("PropertyString").getValue());
  assertEquals(new Boolean(true), entity.getProperty("PropertyBoolean").getValue());
  assertEquals(new Short((short) 255), entity.getProperty("PropertyByte").getValue());
  assertEquals(new Byte((byte) 127), entity.getProperty("PropertySByte").getValue());
  assertEquals(new Integer(2147483647), entity.getProperty("PropertyInt32").getValue());
  assertEquals(new Long(9223372036854775807l), entity.getProperty("PropertyInt64").getValue());
  assertEquals(new Float(1.79E20), entity.getProperty("PropertySingle").getValue());
  assertEquals(new Double(-1.79E19), entity.getProperty("PropertyDouble").getValue());
  assertEquals(new BigDecimal(34), entity.getProperty("PropertyDecimal").getValue());
  assertNotNull(entity.getProperty("PropertyBinary").getValue());
  assertNotNull(entity.getProperty("PropertyDate").getValue());
  assertNotNull(entity.getProperty("PropertyDateTimeOffset").getValue());
  assertNotNull(entity.getProperty("PropertyDuration").getValue());
  assertNotNull(entity.getProperty("PropertyGuid").getValue());
  assertNotNull(entity.getProperty("PropertyTimeOfDay").getValue());
}
 
Example 8
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleEntityETCompAllPrim() throws Exception {
  String entityString = "{\"PropertyInt16\":32767," +
      "\"PropertyComp\":{" +
      "\"PropertyString\":\"First Resource - first\"," +
      "\"PropertyBinary\":\"ASNFZ4mrze8=\"," +
      "\"PropertyBoolean\":true," +
      "\"PropertyByte\":255," +
      "\"PropertyDate\":\"2012-10-03\"," +
      "\"PropertyDateTimeOffset\":\"2012-10-03T07:16:23.1234567Z\"," +
      "\"PropertyDecimal\":34.27," +
      "\"PropertySingle\":1.79E20," +
      "\"PropertyDouble\":-1.79E19," +
      "\"PropertyDuration\":\"PT6S\"," +
      "\"PropertyGuid\":\"01234567-89ab-cdef-0123-456789abcdef\"," +
      "\"PropertyInt16\":32767," +
      "\"PropertyInt32\":2147483647," +
      "\"PropertyInt64\":9223372036854775807," +
      "\"PropertySByte\":127," +
      "\"PropertyTimeOfDay\":\"01:00:01\"}}";
  final Entity entity = deserialize(entityString, "ETCompAllPrim");
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(2, properties.size());

  assertEquals(new Short((short) 32767), entity.getProperty("PropertyInt16").getValue());

  assertNotNull(entity.getProperty("PropertyComp"));
  assertNotNull(entity.getProperty("PropertyComp") instanceof List);
  List<Property> complexProperties = entity.getProperty("PropertyComp").asComplex().getValue();
  assertEquals(16, complexProperties.size());
}
 
Example 9
Source File: ODataAdapter.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * This method wraps Entity object into DataEntry object.
 *
 * @param entity Entity
 * @return DataEntry
 * @see DataEntry
 */
private ODataEntry wrapEntityToDataEntry(EdmEntityType entityType, Entity entity) throws ODataApplicationException {
    ODataEntry entry = new ODataEntry();
    for (Property property : entity.getProperties()) {
        EdmProperty propertyType = (EdmProperty) entityType.getProperty(property.getName());
        entry.addValue(property.getName(), readPrimitiveValueInString(propertyType, property.getValue()));
    }
    return entry;
}
 
Example 10
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleEntityETAllPrimNoTAllPropertiesPresent() throws Exception {
  String entityString =
      "{\"PropertyInt16\":32767," +
          "\"PropertyString\":\"First Resource - positive values\"" +
          "}";
  final Entity entity = deserialize(entityString, "ETAllPrim");
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(2, properties.size());
}
 
Example 11
Source File: UriHelperTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test(expected = SerializerException.class)
public void canonicalURLWithoutKeys() throws Exception {
  final EdmEntitySet entitySet = container.getEntitySet("ESAllPrim");
  Entity entity = data.readAll(entitySet).getEntities().get(0);
  List<Property> properties = entity.getProperties();
  properties.remove(0);
  helper.buildCanonicalURL(entitySet, entity);
  expectedEx.expect(SerializerException.class);
  expectedEx.expectMessage("Key Value Cannot be null for property: PropertyInt16");
}
 
Example 12
Source File: JsonDeltaSerializerWithNavigations.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void writeDeletedEntity(Entity deletedEntity,
    JsonGenerator json) throws IOException, SerializerException {
  if (deletedEntity.getId() == null) {
    throw new SerializerException("Entity id is null.", SerializerException.MessageKeys.MISSING_ID);
  }
  json.writeStartObject();
  if (isODataMetadataFull) {

    json.writeStringField(Constants.AT + Constants.CONTEXT, Constants.HASH + deletedEntity.getId().toASCIIString()
        + Constants.DELETEDENTITY);
  }
  if (((DeletedEntity) deletedEntity).getReason() == null) {
    throw new SerializerException("DeletedEntity reason is null.",
        SerializerException.MessageKeys.MISSING_DELTA_PROPERTY, Constants.REASON);
  }
  json.writeFieldName(Constants.AT + Constants.REMOVED);
  json.writeStartObject();
  json.writeStringField(Constants.ELEM_REASON,
      ((DeletedEntity) deletedEntity).getReason().name());
  List<Annotation> annotations = deletedEntity.getAnnotations();
  if (annotations != null && !annotations.isEmpty()) {
    for (Annotation annotation : annotations) {
      json.writeStringField(Constants.AT + annotation.getTerm(), annotation.getValue().toString());
    }
  }
  json.writeEndObject();
  List<Property> properties = deletedEntity.getProperties();
  if (properties != null && !properties.isEmpty()) {
    for (Property property : properties) {
      json.writeStringField(property.getName(), property.getValue().toString());
    }
  }
  json.writeStringField(Constants.ID,  deletedEntity.getId().toASCIIString());
  json.writeEndObject();

}
 
Example 13
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyEntity() throws Exception {
  final String entityString = "{}";
  final Entity entity = deserialize(entityString, "ETAllPrim");
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(0, properties.size());
}
 
Example 14
Source File: Storage.java    From syndesis 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 15
Source File: ODataAdapter.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
   * This method updates the entity to the table by invoking ODataDataHandler updateEntityInTable method.
   *
   * @param edmEntityType  EdmEntityType
   * @param entity         entity with changes
   * @param existingEntity existing entity
   * @param merge          PUT/PATCH
   * @throws ODataApplicationException
   * @throws DataServiceFault
   * @see ODataDataHandler#updateEntityInTableTransactional(String, ODataEntry, ODataEntry)
   */
  private boolean updateEntityWithETagMatched(EdmEntityType edmEntityType, Entity entity, Entity existingEntity,
                                              boolean merge) throws ODataApplicationException, DataServiceFault {
/* 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 wso2dss oData model */
      List<Property> oldProperties = existingEntity.getProperties();
      ODataEntry newProperties = new ODataEntry();
      Map<String, EdmProperty> propertyMap = new HashMap<>();
      for (String property : edmEntityType.getPropertyNames()) {
          Property updateProperty = entity.getProperty(property);
          EdmProperty propertyType = (EdmProperty) edmEntityType.getProperty(property);
          if (isKey(edmEntityType, property)) {
              propertyMap.put(property, (EdmProperty) edmEntityType.getProperty(property));
              continue;
          }
          // 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 (merge) {
                  // as of the OData spec, in case of PATCH, the existing property is not touched
                  propertyMap.put(property, (EdmProperty) edmEntityType.getProperty(property));
                  continue;
              } else {
                  // as of the OData spec, in case of PUT, the existing property is set to null (or to default value)
                  propertyMap.put(property, (EdmProperty) edmEntityType.getProperty(property));
                  newProperties.addValue(property, null);
                  continue;
              }
          }
          propertyMap.put(property, (EdmProperty) edmEntityType.getProperty(property));
          newProperties.addValue(property, readPrimitiveValueInString(propertyType, updateProperty.getValue()));
      }
      return this.dataHandler.updateEntityInTableTransactional(edmEntityType.getName(),
                                                               wrapPropertiesToDataEntry(edmEntityType, oldProperties,
                                                                                         propertyMap), newProperties);
  }
 
Example 16
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void derivedEntityESCompCollDerived() throws Exception {
  final String payload = "{\n" +
      "   \"@odata.context\": \"$metadata#ESCompCollDerived/$entity\",\n" +
      "   \"@odata.metadataEtag\":\"W/metadataETag\",\n" +
      "   \"@odata.etag\":\"W/32767\",\n" +
      "   \"PropertyInt16\":32767,\n" +
      "   \"[email protected]\": \"#Collection(olingo.odata.test1.CTTwoPrimAno)\",\n" +
      "   \"CollPropertyCompAno\": [\n" +
      "      {\n" +
      "     \"@odata.type\": \"#olingo.odata.test1.CTBaseAno\",\n" +
      "            \"PropertyString\": \"TEST9876\",\n" +
      "            \"AdditionalPropString\": \"Additional9876\"\n" +
      "        },\n" +
      "        {\n" +
      "            \"@odata.type\": \"#olingo.odata.test1.CTTwoPrimAno\",\n" +
      "            \"PropertyString\": \"TEST1234\"\n" +
      "        }\n" +
      "    ]\n" +
      "   \n" +
      "}";
  final Entity entity = deserialize(payload, "ETDeriveCollComp");
  Assert.assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(2, properties.size());
  assertEquals("PropertyInt16=32767", properties.get(0).toString());
  for (Property prop : properties) {
    assertNotNull(prop);
    if (prop.isCollection()) {
      Property property = entity.getProperty("CollPropertyCompAno");
      assertEquals(ValueType.COLLECTION_COMPLEX, property.getValueType());

      assertTrue(property.getValue() instanceof List);
      List<? extends Object> asCollection = property.asCollection();
      assertEquals(2, asCollection.size());

      for (Object arrayElement : asCollection) {
        assertTrue(arrayElement instanceof ComplexValue);
        List<Property> castedArrayElement = ((ComplexValue) arrayElement).getValue();
        if(castedArrayElement.size() == 1){
          assertEquals("PropertyString=TEST1234", castedArrayElement.get(0).toString());
          assertEquals("olingo.odata.test1.CTTwoPrimAno", ((ComplexValue) arrayElement).getTypeName());
        }else{
          assertEquals(2, castedArrayElement.size());
          assertEquals("AdditionalPropString=Additional9876", castedArrayElement.get(1).toString());
          assertEquals("olingo.odata.test1.CTBaseAno", ((ComplexValue) arrayElement).getTypeName());
        }
      }
    }
  }
}
 
Example 17
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void derivedEntityESCompCollDerivedEmptyNull() throws Exception {
  final String payload = "{\n" +
      "   \"@odata.context\": \"$metadata#ESCompCollDerived/$entity\",\n" +
      "   \"@odata.metadataEtag\":\"W/metadataETag\",\n" +
      "   \"@odata.etag\":\"W/32767\",\n" +
      "   \"PropertyInt16\":32767,\n" +
      "   \"PropertyCompAno\":null,\n"+
      "   \"[email protected]\": \"#Collection(olingo.odata.test1.CTTwoPrimAno)\",\n" +
      "   \"CollPropertyCompAno\": [\n" +
      "      {\n" +
      "     \"@odata.type\": \"#olingo.odata.test1.CTBaseAno\",\n" +
      "            \"PropertyString\": null,\n" +
      "            \"AdditionalPropString\": null\n" +
      "        },\n" +
      "        {\n" +
      "        }\n" +
      "    ]\n" +
      "   \n" +
      "}";
  final Entity entity = deserialize(payload, "ETDeriveCollComp");
  Assert.assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(3, properties.size());
  assertEquals("PropertyInt16=32767", properties.get(0).toString());
  assertEquals("PropertyCompAno=null", properties.get(1).toString());
  for (Property prop : properties) {
    assertNotNull(prop);
    if (prop.isCollection()) {
      Property property = entity.getProperty("CollPropertyCompAno");
      assertEquals(ValueType.COLLECTION_COMPLEX, property.getValueType());

      assertTrue(property.getValue() instanceof List);
      List<? extends Object> asCollection = property.asCollection();
      assertEquals(2, asCollection.size());

      for (Object arrayElement : asCollection) {
        assertTrue(arrayElement instanceof ComplexValue);
        List<Property> castedArrayElement = ((ComplexValue) arrayElement).getValue();
       if(castedArrayElement.size() == 2){
          assertEquals(2, castedArrayElement.size());
          assertEquals("AdditionalPropString=null", castedArrayElement.get(1).toString());
        }else{
          assertEquals(0, castedArrayElement.size());
        }
      }
    }
  }
}
 
Example 18
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
@Test
public void simpleEntityETAllPrim() throws Exception {
  String entityString =
      "{\"PropertyInt16\":32767," +
          "\"PropertyString\":\"First Resource - positive values\"," +
          "\"PropertyBoolean\":true," +
          "\"PropertyByte\":255," +
          "\"PropertySByte\":127," +
          "\"PropertyInt32\":2147483647," +
          "\"PropertyInt64\":9223372036854775807," +
          "\"PropertySingle\":1.79E20," +
          "\"PropertyDouble\":-1.79E19," +
          "\"PropertyDecimal\":34," +
          "\"PropertyBinary\":\"ASNFZ4mrze8=\"," +
          "\"PropertyDate\":\"2012-12-03\"," +
          "\"PropertyDateTimeOffset\":\"2012-12-03T07:16:23Z\"," +
          "\"PropertyDuration\":\"PT6S\"," +
          "\"PropertyGuid\":\"01234567-89ab-cdef-0123-456789abcdef\"," +
          "\"PropertyTimeOfDay\":\"03:26:05\"}";
  final Entity entity = deserialize(entityString, "ETAllPrim");
  assertNotNull(entity);
  List<Property> properties = entity.getProperties();
  assertNotNull(properties);
  assertEquals(16, properties.size());

  assertEquals(new Short((short) 32767), entity.getProperty("PropertyInt16").getValue());
  assertEquals("First Resource - positive values", entity.getProperty("PropertyString").getValue());
  assertEquals(new Boolean(true), entity.getProperty("PropertyBoolean").getValue());
  assertEquals(new Short((short) 255), entity.getProperty("PropertyByte").getValue());
  assertEquals(new Byte((byte) 127), entity.getProperty("PropertySByte").getValue());
  assertEquals(new Integer(2147483647), entity.getProperty("PropertyInt32").getValue());
  assertEquals(new Long(9223372036854775807l), entity.getProperty("PropertyInt64").getValue());
  assertEquals(new Float(1.79E20), entity.getProperty("PropertySingle").getValue());
  assertEquals(new Double(-1.79E19), entity.getProperty("PropertyDouble").getValue());
  assertEquals(new BigDecimal(34), entity.getProperty("PropertyDecimal").getValue());
  assertNotNull(entity.getProperty("PropertyBinary").getValue());
  assertNotNull(entity.getProperty("PropertyDate").getValue());
  assertNotNull(entity.getProperty("PropertyDateTimeOffset").getValue());
  assertNotNull(entity.getProperty("PropertyDuration").getValue());
  assertNotNull(entity.getProperty("PropertyGuid").getValue());
  assertNotNull(entity.getProperty("PropertyTimeOfDay").getValue());
}
 
Example 19
Source File: JsonEntitySerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected void doContainerSerialize(final ResWrap<Entity> container, final JsonGenerator jgen)
    throws IOException, EdmPrimitiveTypeException {

  final Entity entity = container.getPayload();

  jgen.writeStartObject();

  if (serverMode && !isODataMetadataNone) {
    if (container.getContextURL() != null) {
      jgen.writeStringField(Constants.JSON_CONTEXT, container.getContextURL().toASCIIString());
    }
    if (container.getMetadataETag() != null) {
      jgen.writeStringField(Constants.JSON_METADATA_ETAG, container.getMetadataETag());
    }

    if (entity.getETag() != null) {
      jgen.writeStringField(Constants.JSON_ETAG, entity.getETag());
    }
  }

  if (entity.getType() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_TYPE,
        new EdmTypeInfo.Builder().setTypeExpression(entity.getType()).build().external());
  }

  if (entity.getId() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_ID, entity.getId().toASCIIString());
  }

  for (Annotation annotation : entity.getAnnotations()) {
    valuable(jgen, annotation, "@" + annotation.getTerm());
  }

  for (Property property : entity.getProperties()) {
    valuable(jgen, property, property.getName());
  }

  if (serverMode && entity.getEditLink() != null && 
      entity.getEditLink().getHref() != null && isODataMetadataFull) {
    jgen.writeStringField(Constants.JSON_EDIT_LINK, entity.getEditLink().getHref());

    if (entity.isMediaEntity() && isODataMetadataFull) {
      jgen.writeStringField(Constants.JSON_MEDIA_READ_LINK,
          entity.getEditLink().getHref() + "/$value");
    }
  }

  if (!isODataMetadataNone) {
    links(entity, jgen);
  }

  if (isODataMetadataFull) {
    for (Link link : entity.getMediaEditLinks()) {
      if (link.getTitle() == null) {
        jgen.writeStringField(Constants.JSON_MEDIA_EDIT_LINK, link.getHref());
      }

      if (link.getInlineEntity() != null) {
        jgen.writeObjectField(link.getTitle(), link.getInlineEntity());
      }
      if (link.getInlineEntitySet() != null) {
        jgen.writeArrayFieldStart(link.getTitle());
        for (Entity subEntry : link.getInlineEntitySet().getEntities()) {
          jgen.writeObject(subEntry);
        }
        jgen.writeEndArray();
      }
    }
  }

  if (serverMode && isODataMetadataFull) {
    for (Operation operation : entity.getOperations()) {
      final String anchor = operation.getMetadataAnchor();
      final int index = anchor.lastIndexOf('#');
      jgen.writeObjectFieldStart('#' + anchor.substring(index < 0 ? 0 : (index + 1)));
      jgen.writeStringField(Constants.ATTR_TITLE, operation.getTitle());
      jgen.writeStringField(Constants.ATTR_TARGET, operation.getTarget().toASCIIString());
      jgen.writeEndObject();
    }
  }

  jgen.writeEndObject();
}
 
Example 20
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);
  }
}