private void withActions(final ODataPubFormat format) {
    final InputStream input =
        getClass().getResourceAsStream("ComputerDetail_-10." + getSuffix(format));
    final ODataEntity entity =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getDeserializer()
                    .toEntry(input, getClient().getResourceFactory().entryClassForFormat(format)));
    assertNotNull(entity);

    assertEquals(1, entity.getOperations().size());
    assertEquals("ResetComputerDetailsSpecifications", entity.getOperations().get(0).getTitle());

    final ODataEntity written =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getBinder()
                    .getEntry(
                        entity, getClient().getResourceFactory().entryClassForFormat(format)));
    entity.setOperations(Collections.<ODataOperation>emptyList());
    assertEquals(entity, written);
  }
  private void readGeospatial(final ODataPubFormat format) {
    final InputStream input =
        getClass().getResourceAsStream("AllGeoTypesSet_-8." + getSuffix(format));
    final ODataEntity entity =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getDeserializer()
                    .toEntry(input, getClient().getResourceFactory().entryClassForFormat(format)));
    assertNotNull(entity);

    boolean found = false;
    for (ODataProperty property : entity.getProperties()) {
      if ("GeogMultiLine".equals(property.getName())) {
        found = true;
        assertTrue(property.hasPrimitiveValue());
        assertEquals(
            EdmSimpleType.GeographyMultiLineString.toString(),
            property.getPrimitiveValue().getTypeName());
      }
    }
    assertTrue(found);

    final ODataEntity written =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getBinder()
                    .getEntry(
                        entity, getClient().getResourceFactory().entryClassForFormat(format)));
    assertEquals(entity, written);
  }
  public void getOpenTypeEntityWithString(
      final ODataPubFormat format,
      final String contentType,
      final int id,
      final String prefer,
      String uuid) {
    try {
      ODataEntity entity =
          ODataObjectFactory.newEntity("Microsoft.Test.OData.Services.OpenTypesService.Row");
      entity.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "Id",
              client
                  .getPrimitiveValueBuilder()
                  .setType(EdmSimpleType.Guid)
                  .setValue(uuid)
                  .build()));
      entity.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "LongValue",
              client
                  .getPrimitiveValueBuilder()
                  .setType(EdmSimpleType.Int64)
                  .setValue(44L)
                  .build()));
      entity.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "DoubleValue",
              client
                  .getPrimitiveValueBuilder()
                  .setType(EdmSimpleType.Double)
                  .setValue(4.34567D)
                  .build()));

      final ODataEntityCreateRequest createReq =
          client
              .getCUDRequestFactory()
              .getEntityCreateRequest(
                  client
                      .getURIBuilder(testOpenTypeServiceRootURL)
                      .appendEntityTypeSegment("Row")
                      .build(),
                  entity);
      createReq.setFormat(format);
      createReq.setPrefer(prefer);
      createReq.setContentType(contentType);
      final ODataEntityCreateResponse createRes = createReq.execute();
    } catch (Exception e) {
      if (e.getMessage().equals("Provided value is not compatible with Edm.Guid")) {
        assertTrue(true);
      } else {
        fail(e.getMessage());
      }
    }
  }
示例#4
0
  private void processDelayedUpdates(
      final List<EntityLinkDesc> delayedUpdates,
      int pos,
      final TransactionItems items,
      final ODataChangeset changeset) {

    for (EntityLinkDesc delayedUpdate : delayedUpdates) {
      pos++;
      items.put(delayedUpdate.getSource(), pos);

      final ODataEntity changes =
          ODataFactory.newEntity(delayedUpdate.getSource().getEntity().getName());

      AttachedEntityStatus status =
          EntityContainerFactory.getContext().entityContext().getStatus(delayedUpdate.getSource());

      final URI sourceURI;
      if (status == AttachedEntityStatus.CHANGED) {
        sourceURI =
            URIUtils.getURI(
                factory.getServiceRoot(),
                delayedUpdate.getSource().getEntity().getEditLink().toASCIIString());
      } else {
        int sourcePos = items.get(delayedUpdate.getSource());
        sourceURI = URI.create("$" + sourcePos);
      }

      for (EntityTypeInvocationHandler target : delayedUpdate.getTargets()) {
        status = EntityContainerFactory.getContext().entityContext().getStatus(target);

        final URI targetURI;
        if (status == AttachedEntityStatus.CHANGED) {
          targetURI =
              URIUtils.getURI(
                  factory.getServiceRoot(), target.getEntity().getEditLink().toASCIIString());
        } else {
          int targetPos = items.get(target);
          targetURI = URI.create("$" + targetPos);
        }

        changes.addLink(
            delayedUpdate.getType() == ODataLinkType.ENTITY_NAVIGATION
                ? ODataFactory.newEntityNavigationLink(delayedUpdate.getSourceName(), targetURI)
                : ODataFactory.newFeedNavigationLink(delayedUpdate.getSourceName(), targetURI));

        LOG.debug(
            "'{}' from {} to {}",
            new Object[] {delayedUpdate.getType().name(), sourceURI, targetURI});
      }

      batchUpdate(delayedUpdate.getSource(), sourceURI, changes, changeset);
    }
  }
  public ODataEntity getInfo(final int id, final String info) {
    final ODataEntity entity =
        ODataObjectFactory.newEntity(
            "Microsoft.Test.OData.Services.AstoriaDefaultService.CustomerInfo");
    entity.setMediaEntity(true);

    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "Information",
            client.getPrimitiveValueBuilder().setText(info).setType(EdmSimpleType.String).build()));
    return entity;
  }
示例#6
0
  private void batchDelete(
      final EntityTypeInvocationHandler handler,
      final ODataEntity entity,
      final ODataChangeset changeset) {

    LOG.debug("Delete '{}'", entity.getEditLink());

    final ODataDeleteRequest req =
        ODataCUDRequestFactory.getDeleteRequest(
            URIUtils.getURI(factory.getServiceRoot(), entity.getEditLink().toASCIIString()));

    if (StringUtils.isNotBlank(handler.getETag())) {
      req.setIfMatch(handler.getETag());
    }

    changeset.addRequest(req);
  }
  @Override
  public ODataEntityUpdateRequest getEntityUpdateRequest(
      final UpdateType type, final ODataEntity entity) {
    if (entity.getEditLink() == null) {
      throw new IllegalArgumentException("No edit link found");
    }

    final ODataEntityUpdateRequest req;

    if (client.getConfiguration().isUseXHTTPMethod()) {
      req = new ODataEntityUpdateRequest(client, HttpMethod.POST, entity.getEditLink(), entity);
      req.setXHTTPMethod(type.getMethod().name());
    } else {
      req = new ODataEntityUpdateRequest(client, type.getMethod(), entity.getEditLink(), entity);
    }

    return req;
  }
  // compares links of the newly created entity with the previous
  public void validateLinks(
      final Collection<ODataLink> original, final Collection<ODataLink> actual) {
    assertTrue(original.size() <= actual.size());

    for (ODataLink originalLink : original) {
      ODataLink foundOriginal = null;
      ODataLink foundActual = null;

      for (ODataLink actualLink : actual) {

        if (actualLink.getType() == originalLink.getType()
            && (originalLink.getLink() == null
                || actualLink
                    .getLink()
                    .toASCIIString()
                    .endsWith(originalLink.getLink().toASCIIString()))
            && actualLink.getName().equals(originalLink.getName())) {

          foundOriginal = originalLink;
          foundActual = actualLink;
        }
      }

      assertNotNull(foundOriginal);
      assertNotNull(foundActual);

      if (foundOriginal instanceof ODataInlineEntity && foundActual instanceof ODataInlineEntity) {
        final ODataEntity originalInline = ((ODataInlineEntity) foundOriginal).getEntity();
        assertNotNull(originalInline);

        final ODataEntity actualInline = ((ODataInlineEntity) foundActual).getEntity();
        assertNotNull(actualInline);

        checkProperties(originalInline.getProperties(), actualInline.getProperties());
      }
    }
  }
  private void mediaEntity(final ODataPubFormat format) {
    final InputStream input = getClass().getResourceAsStream("Car_16." + getSuffix(format));
    final ODataEntity entity =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getDeserializer()
                    .toEntry(input, getClient().getResourceFactory().entryClassForFormat(format)));
    assertNotNull(entity);
    assertTrue(entity.isMediaEntity());
    assertNotNull(entity.getMediaContentSource());
    assertNotNull(entity.getMediaContentType());

    final ODataEntity written =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getBinder()
                    .getEntry(
                        entity, getClient().getResourceFactory().entryClassForFormat(format)));
    assertEquals(entity, written);
  }
  private void issue128(final ODataPubFormat format) {
    final InputStream input =
        getClass().getResourceAsStream("AllGeoTypesSet_-5." + getSuffix(format));
    final ODataEntity entity =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getDeserializer()
                    .toEntry(input, getClient().getResourceFactory().entryClassForFormat(format)));
    assertNotNull(entity);

    final ODataProperty geogCollection = entity.getProperty("GeogCollection");
    assertEquals(
        EdmSimpleType.GeographyCollection.toString(),
        geogCollection.getPrimitiveValue().getTypeName());

    int count = 0;
    for (Geospatial g : geogCollection.getPrimitiveValue().<GeospatialCollection>toCastValue()) {
      assertNotNull(g);
      count++;
    }
    assertEquals(2, count);
  }
示例#11
0
  private void batchUpdate(
      final EntityTypeInvocationHandler handler,
      final ODataEntity changes,
      final ODataChangeset changeset) {

    LOG.debug("Update '{}'", changes.getEditLink());

    final ODataEntityUpdateRequest req =
        ODataCUDRequestFactory.getEntityUpdateRequest(UpdateType.PATCH, changes);
    req.setPrefer(ODataHeaderValues.preferReturnContent);

    if (StringUtils.isNotBlank(handler.getETag())) {
      req.setIfMatch(handler.getETag());
    }

    changeset.addRequest(req);
  }
  public ODataEntity validateEntities(
      final String serviceRootURL,
      final ODataPubFormat format,
      final ODataEntity original,
      final int actualObjectId,
      final Collection<String> expands,
      final String entitySetName) {

    final URIBuilder uriBuilder =
        client
            .getURIBuilder(serviceRootURL)
            .appendEntityTypeSegment(entitySetName)
            .appendKeySegment(actualObjectId);

    // search expanded
    if (expands != null) {
      for (String expand : expands) {
        uriBuilder.expand(expand);
      }
    }
    final ODataEntityRequest req =
        client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
    req.setFormat(format);

    final ODataRetrieveResponse<ODataEntity> res = req.execute();
    assertEquals(200, res.getStatusCode());

    final ODataEntity actual = res.getBody();
    assertNotNull(actual);

    validateLinks(original.getAssociationLinks(), actual.getAssociationLinks());
    validateLinks(original.getEditMediaLinks(), actual.getEditMediaLinks());
    validateLinks(original.getNavigationLinks(), actual.getNavigationLinks());

    // validate equalities of properties
    checkProperties(original.getProperties(), actual.getProperties());
    return actual;
  }
  public void delete(
      final ODataPubFormat format,
      final ODataEntity created,
      final boolean includeInline,
      final String baseUri) {

    final Set<URI> toBeDeleted = new HashSet<URI>();
    toBeDeleted.add(created.getEditLink());

    if (includeInline) {
      for (ODataLink link : created.getNavigationLinks()) {
        if (link instanceof ODataInlineEntity) {
          final ODataEntity inline = ((ODataInlineEntity) link).getEntity();
          if (inline.getEditLink() != null) {
            toBeDeleted.add(URIUtils.getURI(baseUri, inline.getEditLink().toASCIIString()));
          }
        }
        if (link instanceof ODataInlineEntitySet) {
          final ODataEntitySet inline = ((ODataInlineEntitySet) link).getEntitySet();
          for (ODataEntity entity : inline.getEntities()) {
            if (entity.getEditLink() != null) {
              toBeDeleted.add(URIUtils.getURI(baseUri, entity.getEditLink().toASCIIString()));
            }
          }
        }
      }
    }
    assertFalse(toBeDeleted.isEmpty());

    for (URI link : toBeDeleted) {
      final ODataDeleteRequest deleteReq = client.getCUDRequestFactory().getDeleteRequest(link);
      deleteReq.setFormat(format);
      final ODataDeleteResponse deleteRes = deleteReq.execute();
      assertEquals(204, deleteRes.getStatusCode());
      assertEquals("No Content", deleteRes.getStatusMessage());

      deleteRes.close();
    }
  }
  private void readAndWrite(final ODataPubFormat format) {
    final InputStream input = getClass().getResourceAsStream("Customer_-10." + getSuffix(format));
    final ODataEntity entity =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getDeserializer()
                    .toEntry(input, getClient().getResourceFactory().entryClassForFormat(format)));
    assertNotNull(entity);

    assertEquals("Microsoft.Test.OData.Services.AstoriaDefaultService.Customer", entity.getName());
    assertTrue(entity.getEditLink().toASCIIString().endsWith("/Customer(-10)"));
    assertEquals(5, entity.getNavigationLinks().size());
    assertEquals(2, entity.getEditMediaLinks().size());

    boolean check = false;

    for (ODataLink link : entity.getNavigationLinks()) {
      if ("Wife".equals(link.getName())
          && (link.getLink().toASCIIString().endsWith("/Customer(-10)/Wife"))) {
        check = true;
      }
    }

    assertTrue(check);

    final ODataEntity written =
        getClient()
            .getBinder()
            .getODataEntity(
                getClient()
                    .getBinder()
                    .getEntry(
                        entity, getClient().getResourceFactory().entryClassForFormat(format)));
    assertEquals(entity, written);
  }
示例#15
0
  private int processEntityContext(
      final EntityTypeInvocationHandler handler,
      int pos,
      final TransactionItems items,
      final List<EntityLinkDesc> delayedUpdates,
      final ODataChangeset changeset) {

    LOG.debug("Process '{}'", handler);

    items.put(handler, null);

    final ODataEntity entity = SerializationUtils.clone(handler.getEntity());
    entity.getNavigationLinks().clear();

    final AttachedEntityStatus currentStatus =
        EntityContainerFactory.getContext().entityContext().getStatus(handler);

    if (AttachedEntityStatus.DELETED != currentStatus) {
      entity.getProperties().clear();
      EngineUtils.addProperties(factory.getMetadata(), handler.getPropertyChanges(), entity);
    }

    for (Map.Entry<NavigationProperty, Object> property : handler.getLinkChanges().entrySet()) {
      final ODataLinkType type =
          Collection.class.isAssignableFrom(property.getValue().getClass())
              ? ODataLinkType.ENTITY_SET_NAVIGATION
              : ODataLinkType.ENTITY_NAVIGATION;

      final Set<EntityTypeInvocationHandler> toBeLinked =
          new HashSet<EntityTypeInvocationHandler>();
      final String serviceRoot = factory.getServiceRoot();

      for (Object proxy :
          type == ODataLinkType.ENTITY_SET_NAVIGATION
              ? (Collection) property.getValue()
              : Collections.singleton(property.getValue())) {

        final EntityTypeInvocationHandler target =
            (EntityTypeInvocationHandler) Proxy.getInvocationHandler(proxy);

        final AttachedEntityStatus status =
            EntityContainerFactory.getContext().entityContext().getStatus(target);

        final URI editLink = target.getEntity().getEditLink();

        if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
            && !target.isChanged()) {
          entity.addLink(
              buildNavigationLink(
                  property.getKey().name(),
                  URIUtils.getURI(serviceRoot, editLink.toASCIIString()),
                  type));
        } else {
          if (!items.contains(target)) {
            pos = processEntityContext(target, pos, items, delayedUpdates, changeset);
            pos++;
          }

          final Integer targetPos = items.get(target);
          if (targetPos == null) {
            // schedule update for the current object
            LOG.debug("Schedule '{}' from '{}' to '{}'", type.name(), handler, target);
            toBeLinked.add(target);
          } else if (status == AttachedEntityStatus.CHANGED) {
            entity.addLink(
                buildNavigationLink(
                    property.getKey().name(),
                    URIUtils.getURI(serviceRoot, editLink.toASCIIString()),
                    type));
          } else {
            // create the link for the current object
            LOG.debug("'{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);

            entity.addLink(
                buildNavigationLink(property.getKey().name(), URI.create("$" + targetPos), type));
          }
        }
      }

      if (!toBeLinked.isEmpty()) {
        delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, toBeLinked, type));
      }
    }

    // insert into the batch
    LOG.debug("{}: Insert '{}' into the batch", pos, handler);
    batch(handler, entity, changeset);

    items.put(handler, pos);

    int startingPos = pos;

    if (handler.getEntity().isMediaEntity()) {

      // update media properties
      if (!handler.getPropertyChanges().isEmpty()) {
        final URI targetURI =
            currentStatus == AttachedEntityStatus.NEW
                ? URI.create("$" + startingPos)
                : URIUtils.getURI(
                    factory.getServiceRoot(), handler.getEntity().getEditLink().toASCIIString());
        batchUpdate(handler, targetURI, entity, changeset);
        pos++;
        items.put(handler, pos);
      }

      // update media content
      if (handler.getStreamChanges() != null) {
        final URI targetURI =
            currentStatus == AttachedEntityStatus.NEW
                ? URI.create("$" + startingPos + "/$value")
                : URIUtils.getURI(
                    factory.getServiceRoot(),
                    handler.getEntity().getEditLink().toASCIIString() + "/$value");

        batchUpdateMediaEntity(handler, targetURI, handler.getStreamChanges(), changeset);

        // update media info (use null key)
        pos++;
        items.put(null, pos);
      }
    }

    for (Map.Entry<String, InputStream> streamedChanges :
        handler.getStreamedPropertyChanges().entrySet()) {
      final URI targetURI =
          currentStatus == AttachedEntityStatus.NEW
              ? URI.create("$" + startingPos)
              : URIUtils.getURI(
                  factory.getServiceRoot(),
                  EngineUtils.getEditMediaLink(streamedChanges.getKey(), entity).toASCIIString());

      batchUpdateMediaResource(handler, targetURI, streamedChanges.getValue(), changeset);

      // update media info (use null key)
      pos++;
      items.put(handler, pos);
    }

    return pos;
  }
  public ODataEntity getNewCustomer(final int id, final String name, final boolean withInlineInfo) {

    final ODataEntity entity =
        ODataObjectFactory.newEntity(
            "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");

    // add name attribute
    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "Name",
            client.getPrimitiveValueBuilder().setText(name).setType(EdmSimpleType.String).build()));

    // add key attribute
    if (id != 0) {
      entity.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "CustomerId",
              client
                  .getPrimitiveValueBuilder()
                  .setText(String.valueOf(id))
                  .setType(EdmSimpleType.Int32)
                  .build()));
    } else {
      entity.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "CustomerId",
              client
                  .getPrimitiveValueBuilder()
                  .setText(String.valueOf(0))
                  .setType(EdmSimpleType.Int32)
                  .build()));
    }
    final ODataCollectionValue backupContactInfoValue =
        new ODataCollectionValue(
            "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");

    final ODataComplexValue contactDetails =
        new ODataComplexValue("Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");

    final ODataCollectionValue altNamesValue = new ODataCollectionValue("Collection(Edm.String)");
    altNamesValue.add(
        client
            .getPrimitiveValueBuilder()
            .setText("My Alternative name")
            .setType(EdmSimpleType.String)
            .build());
    contactDetails.add(ODataObjectFactory.newCollectionProperty("AlternativeNames", altNamesValue));

    final ODataCollectionValue emailBagValue = new ODataCollectionValue("Collection(Edm.String)");
    emailBagValue.add(
        client
            .getPrimitiveValueBuilder()
            .setText("*****@*****.**")
            .setType(EdmSimpleType.String)
            .build());
    contactDetails.add(ODataObjectFactory.newCollectionProperty("EmailBag", emailBagValue));

    final ODataComplexValue contactAliasValue =
        new ODataComplexValue("Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    contactDetails.add(ODataObjectFactory.newComplexProperty("ContactAlias", contactAliasValue));

    final ODataCollectionValue aliasAltNamesValue =
        new ODataCollectionValue("Collection(Edm.String)");
    aliasAltNamesValue.add(
        client
            .getPrimitiveValueBuilder()
            .setText("myAlternativeName")
            .setType(EdmSimpleType.String)
            .build());
    contactAliasValue.add(
        ODataObjectFactory.newCollectionProperty("AlternativeNames", aliasAltNamesValue));

    final ODataComplexValue homePhone =
        new ODataComplexValue("Microsoft.Test.OData.Services.AstoriaDefaultService.Phone");
    homePhone.add(
        ODataObjectFactory.newPrimitiveProperty(
            "PhoneNumber",
            client
                .getPrimitiveValueBuilder()
                .setText("8437568356834568")
                .setType(EdmSimpleType.String)
                .build()));
    homePhone.add(
        ODataObjectFactory.newPrimitiveProperty(
            "Extension",
            client
                .getPrimitiveValueBuilder()
                .setText("124365426534621534423ttrf")
                .setType(EdmSimpleType.String)
                .build()));
    contactDetails.add(ODataObjectFactory.newComplexProperty("HomePhone", homePhone));

    backupContactInfoValue.add(contactDetails);
    entity.addProperty(
        ODataObjectFactory.newCollectionProperty("BackupContactInfo", backupContactInfoValue));
    if (withInlineInfo) {
      final ODataInlineEntity inlineInfo =
          ODataObjectFactory.newInlineEntity(
              "Info", URI.create("Customer(" + id + ")/Info"), getInfo(id, name + "_Info"));
      inlineInfo.getEntity().setMediaEntity(true);
      entity.addLink(inlineInfo);
    }

    return entity;
  }
  public ODataEntity getComputerDetailsEntity(
      final int id,
      final String sampleName,
      final boolean withInlineInfo,
      final String purchaseDate,
      String dimensionValue) {

    final ODataEntity entity =
        ODataObjectFactory.newEntity(
            "Microsoft.Test.OData.Services.AstoriaDefaultService.ComputerDetail");

    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "Manufacturer",
            client
                .getPrimitiveValueBuilder()
                .setText("manufacturer name")
                .setType(EdmSimpleType.String)
                .build()));

    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "ComputerDetailId",
            client
                .getPrimitiveValueBuilder()
                .setText(String.valueOf(id))
                .setType(EdmSimpleType.Int32)
                .build()));

    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "Model",
            client
                .getPrimitiveValueBuilder()
                .setText("Model Name")
                .setType(EdmSimpleType.String)
                .build()));

    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "PurchaseDate",
            client
                .getPrimitiveValueBuilder()
                .setText(purchaseDate)
                .setType(EdmSimpleType.DateTime)
                .build()));

    // add Dimensions attribute (collection)
    final ODataComplexValue dimensions =
        new ODataComplexValue("Microsoft.Test.OData.Services.AstoriaDefaultService.Dimensions");
    dimensions.add(
        ODataObjectFactory.newPrimitiveProperty(
            "Width",
            client
                .getPrimitiveValueBuilder()
                .setText(dimensionValue)
                .setType(EdmSimpleType.Decimal)
                .build()));
    dimensions.add(
        ODataObjectFactory.newPrimitiveProperty(
            "Height",
            client
                .getPrimitiveValueBuilder()
                .setText(dimensionValue)
                .setType(EdmSimpleType.Decimal)
                .build()));
    dimensions.add(
        ODataObjectFactory.newPrimitiveProperty(
            "Depth",
            client
                .getPrimitiveValueBuilder()
                .setText(dimensionValue)
                .setType(EdmSimpleType.Decimal)
                .build()));

    entity.addProperty(ODataObjectFactory.newComplexProperty("Dimensions", dimensions));
    return entity;
  }
  @Test
  public void createNoMultipleKey() {
    final ODataPubFormat format = ODataPubFormat.JSON_FULL_METADATA;
    final String contentType = "application/json;odata=fullmetadata";
    final String prefer = "return-content";
    try {
      final ODataEntity message =
          ODataObjectFactory.newEntity(
              "Microsoft.Test.OData.Services.AstoriaDefaultService.Message");

      message.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "MessageId",
              client
                  .getPrimitiveValueBuilder()
                  .setText(String.valueOf(25))
                  .setType(EdmSimpleType.Int32)
                  .build()));
      message.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "FromUsername",
              client
                  .getPrimitiveValueBuilder()
                  .setText("user")
                  .setType(EdmSimpleType.String)
                  .build()));
      message.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "ToUsername",
              client
                  .getPrimitiveValueBuilder()
                  .setValue("usernameabc")
                  .setType(EdmSimpleType.String)
                  .build()));
      message.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "Subject",
              client
                  .getPrimitiveValueBuilder()
                  .setValue("Subject of message")
                  .setType(EdmSimpleType.String)
                  .build()));
      message.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "Body",
              client
                  .getPrimitiveValueBuilder()
                  .setValue("Body Content")
                  .setType(EdmSimpleType.String)
                  .build()));
      message.addProperty(
          ODataObjectFactory.newPrimitiveProperty(
              "IsRead",
              client
                  .getPrimitiveValueBuilder()
                  .setValue(false)
                  .setType(EdmSimpleType.Boolean)
                  .build()));

      final URIBuilder builder =
          client.getURIBuilder(testDefaultServiceRootURL).appendEntitySetSegment("Message");
      final ODataEntityCreateRequest req =
          client.getCUDRequestFactory().getEntityCreateRequest(builder.build(), message);
      req.setFormat(format);
      req.setContentType(contentType);
      req.setPrefer(prefer);
      final ODataEntityCreateResponse res = req.execute();
      assertNotNull(res);
      assertEquals(201, res.getStatusCode());
    } catch (Exception e) {
      fail(e.getMessage());
    }
  }
  private ODataEntity sampleODataEntity() throws IOException {
    final ODataEntity entity =
        getClient()
            .getObjectFactory()
            .newEntity("Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");

    // add name attribute
    entity.addProperty(
        getClient()
            .getObjectFactory()
            .newPrimitiveProperty(
                "Name",
                getClient()
                    .getPrimitiveValueBuilder()
                    .setText("A name")
                    .setType(EdmSimpleType.String)
                    .build()));

    // add key attribute
    entity.addProperty(
        getClient()
            .getObjectFactory()
            .newPrimitiveProperty(
                "CustomerId",
                getClient()
                    .getPrimitiveValueBuilder()
                    .setText("0")
                    .setType(EdmSimpleType.Int32)
                    .build()));

    // add BackupContactInfo attribute (collection)
    final ODataCollectionValue bciv =
        new ODataCollectionValue(
            "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
    entity.addProperty(
        getClient().getObjectFactory().newCollectionProperty("BackupContactInfo", bciv));

    // add BackupContactInfo.ContactDetails attribute (complex)
    final ODataComplexValue contactDetails =
        new ODataComplexValue("Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
    bciv.add(contactDetails);

    // add BackupContactInfo.ContactDetails.AlternativeNames attribute (collection)
    final ODataCollectionValue altNamesValue = new ODataCollectionValue("Collection(Edm.String)");
    altNamesValue.add(
        getClient()
            .getPrimitiveValueBuilder()
            .setText("myname")
            .setType(EdmSimpleType.String)
            .build());
    contactDetails.add(
        getClient().getObjectFactory().newCollectionProperty("AlternativeNames", altNamesValue));

    // add BackupContactInfo.ContactDetails.EmailBag attribute (collection)
    final ODataCollectionValue emailBagValue = new ODataCollectionValue("Collection(Edm.String)");
    emailBagValue.add(
        getClient()
            .getPrimitiveValueBuilder()
            .setText("*****@*****.**")
            .setType(EdmSimpleType.String)
            .build());
    contactDetails.add(
        getClient().getObjectFactory().newCollectionProperty("EmailBag", emailBagValue));

    // add BackupContactInfo.ContactDetails.ContactAlias attribute (complex)
    final ODataComplexValue contactAliasValue =
        new ODataComplexValue("Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    contactDetails.add(
        getClient().getObjectFactory().newComplexProperty("ContactAlias", contactAliasValue));

    // add BackupContactInfo.ContactDetails.ContactAlias.AlternativeNames attribute (collection)
    final ODataCollectionValue aanv = new ODataCollectionValue("Collection(Edm.String)");
    aanv.add(
        getClient()
            .getPrimitiveValueBuilder()
            .setText("myAlternativeName")
            .setType(EdmSimpleType.String)
            .build());
    contactAliasValue.add(
        getClient().getObjectFactory().newCollectionProperty("AlternativeNames", aanv));

    return entity;
  }
  public void getOpenTypeEntity(
      final ODataPubFormat format,
      final String contentType,
      final int id,
      final String prefer,
      String uuid) {
    final UUID guid;
    if (uuid.equals("random")) {
      guid = UUID.randomUUID();
    } else {
      guid = UUID.fromString(uuid);
    }
    ODataEntity entity =
        ODataObjectFactory.newEntity("Microsoft.Test.OData.Services.OpenTypesService.Row");
    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "Id",
            client.getPrimitiveValueBuilder().setType(EdmSimpleType.Guid).setValue(guid).build()));
    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "LongValue",
            client.getPrimitiveValueBuilder().setType(EdmSimpleType.Int64).setValue(44L).build()));
    entity.addProperty(
        ODataObjectFactory.newPrimitiveProperty(
            "DoubleValue",
            client
                .getPrimitiveValueBuilder()
                .setType(EdmSimpleType.Double)
                .setValue(4.34567D)
                .build()));

    final ODataEntityCreateRequest createReq =
        client
            .getCUDRequestFactory()
            .getEntityCreateRequest(
                client
                    .getURIBuilder(testOpenTypeServiceRootURL)
                    .appendEntityTypeSegment("Row")
                    .build(),
                entity);
    createReq.setFormat(format);
    createReq.setPrefer(prefer);
    createReq.setContentType(contentType);
    final ODataEntityCreateResponse createRes = createReq.execute();
    assertEquals(201, createRes.getStatusCode());
    entity = createRes.getBody();
    assertNotNull(entity);
    if (format.equals(ODataPubFormat.JSON_NO_METADATA)) {
      assertEquals(
          EdmSimpleType.String.toString(),
          entity.getProperty("Id").getPrimitiveValue().getTypeName());
      assertEquals(
          EdmSimpleType.String.toString(),
          entity.getProperty("LongValue").getPrimitiveValue().getTypeName());
      assertEquals(
          EdmSimpleType.Double.toString(),
          entity.getProperty("DoubleValue").getPrimitiveValue().getTypeName());
    } else if (format.equals(ODataPubFormat.JSON)) {
      assertEquals(
          EdmSimpleType.String.toString(),
          entity.getProperty("Id").getPrimitiveValue().getTypeName());
      assertEquals(
          EdmSimpleType.Int64.toString(),
          entity.getProperty("LongValue").getPrimitiveValue().getTypeName());
      assertEquals(
          EdmSimpleType.Double.toString(),
          entity.getProperty("DoubleValue").getPrimitiveValue().getTypeName());
    } else {
      assertEquals(
          EdmSimpleType.Guid.toString(),
          entity.getProperty("Id").getPrimitiveValue().getTypeName());
      assertEquals(
          EdmSimpleType.Int64.toString(),
          entity.getProperty("LongValue").getPrimitiveValue().getTypeName());
      assertEquals(
          EdmSimpleType.Double.toString(),
          entity.getProperty("DoubleValue").getPrimitiveValue().getTypeName());
    }
    ODataDeleteResponse deleteRes;
    try {
      deleteRes =
          client
              .getCUDRequestFactory()
              .getDeleteRequest(new URI(testOpenTypeServiceRootURL + "/Row(guid'" + guid + "')"))
              .execute();
      assertEquals(204, deleteRes.getStatusCode());
    } catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      LOG.error("", e);
    }
  }
    public void geoSpacialTest(final ODataPubFormat format, final String contentType, final String prefer, final int id) {
        try {
            final ODataEntity entity =
                    ODataFactory.newEntity("Microsoft.Test.OData.Services.AstoriaDefaultService.AllSpatialTypes");
            entity.addProperty(ODataFactory.newPrimitiveProperty("Id",
                    new ODataPrimitiveValue.Builder().setText(String.valueOf(id)).setType(EdmSimpleType.Int32).build()));

            final Point point1 = new Point(Geospatial.Dimension.GEOGRAPHY);
            point1.setX(6.2);
            point1.setY(1.1);
            final Point point2 = new Point(Geospatial.Dimension.GEOGRAPHY);
            point2.setX(33.33);
            point2.setY(-2.5);

            // create a point
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogPoint",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyPoint).
                    setValue(point1).build()));

            // create  multiple point
            final List<Point> points = new ArrayList<Point>();
            points.add(point1);
            points.add(point2);
            final MultiPoint multipoint = new MultiPoint(Geospatial.Dimension.GEOGRAPHY, points);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogMultiPoint",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyMultiPoint).
                    setValue(multipoint).build()));

            // create a line
            final List<Point> linePoints = new ArrayList<Point>();
            linePoints.add(point1);
            linePoints.add(point2);
            final LineString lineString = new LineString(Geospatial.Dimension.GEOGRAPHY, linePoints);

            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogLine",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyLineString).
                    setValue(lineString).build()));

            // create a polygon
            linePoints.set(1, point2);
            linePoints.add(point2);
            linePoints.add(point1);
            final Polygon polygon = new Polygon(Geospatial.Dimension.GEOGRAPHY, linePoints, linePoints);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogPolygon",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyPolygon).
                    setValue(polygon).build()));

            // create a multi line string
            final List<LineString> multipleLines = new ArrayList<LineString>();
            multipleLines.add(lineString);
            multipleLines.add(lineString);
            final MultiLineString multiLine = new MultiLineString(Geospatial.Dimension.GEOGRAPHY, multipleLines);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogMultiLine",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyMultiLineString).
                    setValue(multiLine).build()));

            // create a multi polygon        
            final List<Polygon> polygons = new ArrayList<Polygon>();
            polygons.add(polygon);
            polygons.add(polygon);
            final MultiPolygon multiPolygon = new MultiPolygon(Geospatial.Dimension.GEOGRAPHY, polygons);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogMultiPolygon",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyMultiPolygon).
                    setValue(multiPolygon).build()));

            // create  acolletion of various shapes
            final List<Geospatial> geospatialCollection = new ArrayList<Geospatial>();
            geospatialCollection.add(point1);
            geospatialCollection.add(lineString);
            geospatialCollection.add(polygon);
            final GeospatialCollection collection = new GeospatialCollection(Geospatial.Dimension.GEOGRAPHY,
                    geospatialCollection);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeogCollection",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyCollection).
                    setValue(collection).build()));

            // with geometry test

            final Point goemPoint1 = new Point(Geospatial.Dimension.GEOMETRY);
            goemPoint1.setX(6.2);
            goemPoint1.setY(1.1);
            final Point goemPoint2 = new Point(Geospatial.Dimension.GEOMETRY);
            goemPoint2.setX(33.33);
            goemPoint2.setY(-2.5);

            // create a point
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomPoint",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeometryPoint).
                    setValue(goemPoint2).build()));

            // create  multiple point
            final List<Point> geomPoints = new ArrayList<Point>();
            geomPoints.add(point1);
            geomPoints.add(point2);
            final MultiPoint geomMultipoint = new MultiPoint(Geospatial.Dimension.GEOMETRY, geomPoints);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomMultiPoint",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeometryMultiPoint).
                    setValue(geomMultipoint).build()));

            // create a line
            final List<Point> geomLinePoints = new ArrayList<Point>();
            geomLinePoints.add(goemPoint1);
            geomLinePoints.add(goemPoint2);
            final LineString geomLineString = new LineString(Geospatial.Dimension.GEOMETRY, geomLinePoints);

            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomLine",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeometryLineString).
                    setValue(geomLineString).build()));

            // create a polygon
            geomLinePoints.set(1, goemPoint2);
            geomLinePoints.add(goemPoint2);
            geomLinePoints.add(goemPoint1);
            final Polygon geomPolygon = new Polygon(Geospatial.Dimension.GEOMETRY, geomLinePoints, geomLinePoints);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomPolygon",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeometryPolygon).
                    setValue(geomPolygon).build()));

            // create a multi line string
            final List<LineString> geomMultipleLines = new ArrayList<LineString>();
            geomMultipleLines.add(geomLineString);
            geomMultipleLines.add(geomLineString);
            final MultiLineString geomMultiLine = new MultiLineString(Geospatial.Dimension.GEOMETRY, geomMultipleLines);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomMultiLine",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeometryMultiLineString).
                    setValue(geomMultiLine).build()));

            // create a multi polygon        
            final List<Polygon> geomPolygons = new ArrayList<Polygon>();
            geomPolygons.add(geomPolygon);
            geomPolygons.add(geomPolygon);
            final MultiPolygon geomMultiPolygon = new MultiPolygon(Geospatial.Dimension.GEOMETRY, geomPolygons);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomMultiPolygon",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyMultiPolygon).
                    setValue(geomMultiPolygon).build()));

            // create  a collection of various shapes
            final List<Geospatial> geomspatialCollection = new ArrayList<Geospatial>();
            geomspatialCollection.add(goemPoint1);
            geomspatialCollection.add(geomLineString);
            final GeospatialCollection geomCollection = new GeospatialCollection(Geospatial.Dimension.GEOMETRY,
                    geomspatialCollection);
            entity.addProperty(ODataFactory.newPrimitiveProperty("GeomCollection",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeometryCollection).
                    setValue(geomCollection).build()));

            // create request
            final ODataEntityCreateRequest createReq = ODataCUDRequestFactory.
                    getEntityCreateRequest(new ODataURIBuilder(testDefaultServiceRootURL).
                    appendEntityTypeSegment("AllGeoTypesSet").build(), entity);
            createReq.setFormat(format);
            createReq.setContentType(contentType);
            createReq.setPrefer(prefer);
            final ODataEntityCreateResponse createRes = createReq.execute();
            final ODataEntity entityAfterCreate = createRes.getBody();
            final ODataProperty geogCollection = entityAfterCreate.getProperty("GeogCollection");
            if (format.equals(ODataPubFormat.JSON) || format.equals(ODataPubFormat.JSON_NO_METADATA)) {
                assertTrue(geogCollection.hasComplexValue());
            } else {
                assertEquals(EdmSimpleType.GeographyCollection.toString(), geogCollection.getPrimitiveValue().
                        getTypeName());

                final ODataProperty geometryCollection = entityAfterCreate.getProperty("GeomCollection");
                assertEquals(EdmSimpleType.GeographyCollection.toString(),
                        geogCollection.getPrimitiveValue().getTypeName());

                int count = 0;
                for (Geospatial g : geogCollection.getPrimitiveValue().<GeospatialCollection>toCastValue()) {
                    assertNotNull(g);
                    count++;
                }
                assertEquals(3, count);
                count = 0;
                for (Geospatial g : geometryCollection.getPrimitiveValue().<GeospatialCollection>toCastValue()) {
                    assertNotNull(g);
                    count++;
                }
                assertEquals(2, count);
            }
            // update geog points 
            final Point updatePoint1 = new Point(Geospatial.Dimension.GEOGRAPHY);
            updatePoint1.setX(21.2);
            updatePoint1.setY(31.1);
            final Point updatePoint2 = new Point(Geospatial.Dimension.GEOGRAPHY);
            updatePoint2.setX(99.99);
            updatePoint2.setY(-3.24);
            ODataProperty property = entityAfterCreate.getProperty("GeogPoint");
            entityAfterCreate.removeProperty(property);
            entityAfterCreate.addProperty(ODataFactory.newPrimitiveProperty("GeogPoint",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyPoint).
                    setValue(updatePoint1).build()));
            updateGeog(format, contentType, prefer, entityAfterCreate, UpdateType.REPLACE, entityAfterCreate.getETag());

            // update geography line  
            final List<Point> updateLinePoints = new ArrayList<Point>();
            updateLinePoints.add(updatePoint1);
            updateLinePoints.add(updatePoint2);
            final LineString updateLineString = new LineString(Geospatial.Dimension.GEOGRAPHY, updateLinePoints);
            ODataProperty lineProperty = entityAfterCreate.getProperty("GeogLine");
            entityAfterCreate.removeProperty(lineProperty);
            entityAfterCreate.addProperty(ODataFactory.newPrimitiveProperty("GeogLine",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyLineString).
                    setValue(updateLineString).build()));
            //updateGeog(format,contentType, prefer, entityAfterCreate, UpdateType.REPLACE,entityAfterCreate.getETag());

            // update a geography polygon
            updateLinePoints.set(1, updatePoint2);
            updateLinePoints.add(updatePoint2);
            updateLinePoints.add(updatePoint1);
            final Polygon updatePolygon =
                    new Polygon(Geospatial.Dimension.GEOGRAPHY, updateLinePoints, updateLinePoints);
            ODataProperty polygonProperty = entityAfterCreate.getProperty("GeogPolygon");
            entityAfterCreate.removeProperty(polygonProperty);
            entityAfterCreate.addProperty(ODataFactory.newPrimitiveProperty("GeogPolygon",
                    new ODataGeospatialValue.Builder().setType(EdmSimpleType.GeographyPolygon).
                    setValue(updatePolygon).build()));
            //updateGeog(format,contentType, prefer, entityAfterCreate, UpdateType.REPLACE,entityAfterCreate.getETag());

            // delete the entity
            ODataURIBuilder deleteUriBuilder = new ODataURIBuilder(testDefaultServiceRootURL).
                    appendEntityTypeSegment("AllGeoTypesSet(" + id + ")");
            ODataDeleteRequest deleteReq = ODataCUDRequestFactory.getDeleteRequest(deleteUriBuilder.build());
            deleteReq.setFormat(format);
            deleteReq.setContentType(contentType);
            assertEquals(204, deleteReq.execute().getStatusCode());
        } catch (Exception e) {
            LOG.error("", e);
            if (format.equals(ODataPubFormat.JSON) || format.equals(ODataPubFormat.JSON_NO_METADATA)) {
                assertTrue(true);
            } else {
                fail(e.getMessage());
            }
        } catch (AssertionError e) {
            LOG.error("", e);
            fail(e.getMessage());
        }
    }