org.apache.olingo.odata2.api.edm.EdmEntitySet Java Examples

The following examples show how to use org.apache.olingo.odata2.api.edm.EdmEntitySet. 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: XmlEntityDeserializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test(expected = EntityProviderException.class)
public void readEntryTooManyValues() throws Exception {
  // prepare
  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  String content =
      EMPLOYEE_1_XML.replace("<d:Age>52</d:Age>",
          "<d:Age>52</d:Age><d:SomeUnknownTag>SomeUnknownValue</d:SomeUnknownTag>");
  InputStream contentBody = createContentAsStream(content);

  // execute
  try {
    EntityStream stream = new EntityStream();
    stream.setContent(contentBody);
    stream.setReadProperties(DeserializerProperties.init().build());

    // execute
    XmlEntityDeserializer xec = new XmlEntityDeserializer();
    xec.readEntry(entitySet, stream);
  } catch (EntityProviderException e) {
    assertEquals(EntityProviderException.INVALID_PROPERTY.getKey(), e.getMessageReference().getKey());
    assertEquals("SomeUnknownTag", e.getMessageReference().getContent().get(0));
    throw e;
  }
}
 
Example #2
Source File: AtomEntryProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeepInContentNull() throws Exception {
  AtomEntityProvider ser = createAtomEntityProvider();
  EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos");

  EdmProperty customProperty = (EdmProperty) entitySet.getEntityType().getProperty("CustomProperty");
  when(customProperty.getCustomizableFeedMappings().isFcKeepInContent()).thenReturn(null);

  ODataResponse response = ser.writeEntry(entitySet, photoData, DEFAULT_PROPERTIES);
  String xmlString = verifyResponse(response);

  assertXpathExists("/a:entry", xmlString);
  assertXpathExists("/a:entry/custom:CustomProperty", xmlString);
  assertXpathNotExists("/a:entry/custom:CustomProperty/text()", xmlString);
  assertXpathEvaluatesTo("true", "/a:entry/custom:CustomProperty/@m:null", xmlString);
  assertXpathExists("/a:entry/m:properties/d:CustomProperty", xmlString);
  verifyTagOrdering(xmlString, "category", "Содержание", "CustomProperty", "content", "properties");
}
 
Example #3
Source File: ExpandSelectProducerWithBuilderTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void selectIdAndBuildingLink() throws Exception {
  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> selectedNavigationProperties = new ArrayList<String>();
  selectedNavigationProperties.add("nr_Building");

  List<String> selectedProperties = new ArrayList<String>();
  selectedProperties.add("Id");

  ExpandSelectTreeNode expandSelectTree =
      ExpandSelectTreeNode.entitySet(roomsSet).selectedProperties(selectedProperties).selectedLinks(
          selectedNavigationProperties).build();

  EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.fromProperties(DEFAULT_PROPERTIES).expandSelectTree(expandSelectTree).build();
  ODataResponse entry = EntityProvider.writeEntry("application/xml", roomsSet, roomData, properties);

  String xml = StringHelper.inputStreamToString((InputStream) entry.getEntity());
  assertXpathExists("/a:entry/a:content/m:properties", xml);
  assertXpathExists("/a:entry/a:link[@type]", xml);
}
 
Example #4
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithoutCompositeKeyWithOneKeyNull() throws Exception {
  Edm edm = MockFacade.getMockEdm();
  EdmEntitySet entitySet = edm.getEntityContainer("Container2").getEntitySet("Photos");
  
  Entity photoData = new Entity();
  photoData.addProperty("Name", "Mona Lisa");
  photoData.addProperty("Id", Integer.valueOf(1));
  photoData.setWriteProperties(
      EntitySerializerProperties.serviceRoot(URI.create(BASE_URI)).build());
  
  EdmTyped typeProperty = edm.getEntityContainer("Container2").getEntitySet("Photos").
      getEntityType().getProperty("Type");
  EdmFacets facets = mock(EdmFacets.class);
  when(facets.getConcurrencyMode()).thenReturn(EdmConcurrencyMode.Fixed);
  when(facets.getMaxLength()).thenReturn(3);
  when(((EdmProperty) typeProperty).getFacets()).thenReturn(facets);

  try {
    new JsonSerializerDeserializer().writeEntry(entitySet, photoData);
  } catch (EntityProviderProducerException e) {
    assertTrue(e.getMessage().contains("The metadata do not allow a null value for property 'Type'"));
  }
}
 
Example #5
Source File: JPQLBuilderFactoryTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private GetEntityUriInfo getEntityUriInfo() throws EdmException {
  GetEntityUriInfo getEntityView = EasyMock.createMock(GetEntityUriInfo.class);
  EdmEntitySet edmEntitySet = EasyMock.createMock(EdmEntitySet.class);
  EdmEntityType edmEntityType = EasyMock.createMock(EdmEntityType.class);
  EasyMock.expect(edmEntityType.getKeyProperties()).andStubReturn(new ArrayList<EdmProperty>());
  EasyMock.expect(edmEntityType.getMapping()).andStubReturn(null);
  EasyMock.expect(edmEntityType.getName()).andStubReturn("");
  EasyMock.expect(edmEntitySet.getEntityType()).andStubReturn(edmEntityType);
  EasyMock.expect(getEntityView.getSelect()).andStubReturn(null);
  EasyMock.expect(getEntityView.getTargetEntitySet()).andStubReturn(edmEntitySet);
  EdmEntitySet startEdmEntitySet = EasyMock.createMock(EdmEntitySet.class);
  EdmEntityType startEdmEntityType = EasyMock.createMock(EdmEntityType.class);
  EasyMock.expect(startEdmEntityType.getMapping()).andStubReturn(null);
  EasyMock.expect(startEdmEntityType.getName()).andStubReturn("SOHeader");
  EasyMock.expect(startEdmEntitySet.getEntityType()).andStubReturn(startEdmEntityType);
  EasyMock.expect(getEntityView.getStartEntitySet()).andStubReturn(startEdmEntitySet);
  EasyMock.replay(startEdmEntityType, startEdmEntitySet);
  EasyMock.replay(edmEntityType, edmEntitySet);
  EasyMock.expect(getEntityView.getKeyPredicates()).andStubReturn(new ArrayList<KeyPredicate>());
  List<NavigationSegment> navigationSegments = new ArrayList<NavigationSegment>();
  EasyMock.expect(getEntityView.getNavigationSegments()).andStubReturn(navigationSegments);
  EasyMock.replay(getEntityView);
  return getEntityView;
}
 
Example #6
Source File: XmlEntityConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadEntryRequestObjectMapping() throws Exception {
  XmlEntityConsumer xec = new XmlEntityConsumer();

  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  InputStream content = createContentAsStream(EMPLOYEE_1_XML);
  ODataEntry result =
      xec.readEntry(entitySet, content,
          EntityProviderReadProperties.init().mergeSemantic(true).addTypeMappings(
              createTypeMappings("EmployeeName", Object.class)).build());

  // verify
  Map<String, Object> properties = result.getProperties();
  assertEquals(9, properties.size());

  assertEquals("1", properties.get("EmployeeId"));
  Object o = properties.get("EmployeeName");
  assertTrue(o instanceof String);
  assertEquals("Walter Winter", properties.get("EmployeeName"));
  assertEquals("1", properties.get("ManagerId"));
  assertEquals("1", properties.get("RoomId"));
  assertEquals("1", properties.get("TeamId"));
}
 
Example #7
Source File: EdmEntityContainerImplProvTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityContainerInheritance() throws EdmException {
  assertEquals("fooFromParent", edmEntityContainer.getEntitySet("fooFromParent").getName());

  EdmEntitySet sourceEntitySet = mock(EdmEntitySet.class);
  when(sourceEntitySet.getName()).thenReturn("foo");

  EdmAssociation edmAssociation = mock(EdmAssociation.class);
  when(edmAssociation.getNamespace()).thenReturn("AssocNs");
  when(edmAssociation.getName()).thenReturn("AssocName");

  EdmNavigationProperty edmNavigationProperty = mock(EdmNavigationProperty.class);
  when(edmNavigationProperty.getRelationship()).thenReturn(edmAssociation);
  when(edmNavigationProperty.getFromRole()).thenReturn("wrongRole");

  boolean failed = false;
  try {
    edmEntityContainer.getAssociationSet(sourceEntitySet, edmNavigationProperty);
  } catch (EdmException e) {
    failed = true;
  }

  assertTrue(failed);
}
 
Example #8
Source File: ProducerConsumerIntegrationTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private List<Map<String, Object>> execute1(final EntityCollection localRoomData, final EdmEntitySet roomSet,
    final String contentType)
    throws ODataException {
  List<Map<String, Object>> propertiesList = new ArrayList<Map<String,Object>>();
  localRoomData.setCollectionProperties(EntityCollectionSerializerProperties.serviceRoot(BASE_URI).build());
  ODataResponse response = ODataClient.newInstance().createSerializer(contentType)
      .writeFeed(roomSet, localRoomData);
  InputStream content = response.getEntityAsStream();
  EntityStream entityContent = new EntityStream();
  entityContent.setReadProperties(DEFAULT_READ_PROPERTIES);
  entityContent.setContent(content);
  ODataFeed feed = ODataClient.newInstance()
      .createDeserializer(contentType).readFeed(roomSet, entityContent);
  List<ODataEntry> entries = feed.getEntries();
  for (ODataEntry entry : entries) {
    propertiesList.add(entry.getProperties());
  }
  return propertiesList;
}
 
Example #9
Source File: JsonFeedConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * Rooms navigate to Employees and has inline entry Teams
 * E.g: Rooms('1')/nr_Employees?$expand=ne_Team
 * @throws Exception
 */
@Test
public void roomsFeedWithRoomsToEmployeesInlineTeams() throws Exception {
  InputStream stream = getFileAsStream("JsonRoomsToEmployeesWithInlineTeams.json");
  assertNotNull(stream);
  FeedCallback callback = new FeedCallback();

  EntityProviderReadProperties readProperties = EntityProviderReadProperties.init()
      .mergeSemantic(false).callback(callback).build();

  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  JsonEntityConsumer xec = new JsonEntityConsumer();
  ODataDeltaFeed feed = xec.readDeltaFeed(entitySet, stream, readProperties);
  assertNotNull(feed);
  assertEquals(2, feed.getEntries().size());

  Map<String, Object> inlineEntries = callback.getNavigationProperties();
  getExpandedData(inlineEntries, feed);
  for (ODataEntry entry : feed.getEntries()) {
    assertEquals(10, entry.getProperties().size());
    assertEquals(3, ((ODataEntry)entry.getProperties().get("ne_Team")).getProperties().size());
  }
}
 
Example #10
Source File: JsonEntryDeserializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * Employee with inline entity Room with inline entity Buildings 
 * Scenario of 1:1:1 navigation
 * E.g: Employees('1')?$expand=ne_Room/nr_Building
 * @throws Exception
 */
@Test
public void employeesEntryWithEmployeeToRoomToBuildingWithTypeMappings() throws Exception {
  InputStream stream = getFileAsStream("JsonEmployeeInlineRoomBuilding.json");
  assertNotNull(stream);
  EntityStream entityStream = new EntityStream();
  entityStream.setContent(stream);
  Map<String, Object> typeMappings = new HashMap<String, Object>();
  typeMappings.put("EntryDate", java.sql.Timestamp.class);
  typeMappings.put("Name", String.class);
  entityStream.setReadProperties(DeserializerProperties.init().addTypeMappings(typeMappings)
      .build());
  
  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  JsonEntityDeserializer xec = new JsonEntityDeserializer();
  ODataEntry result =
      xec.readEntry(entitySet, entityStream);
  assertNotNull(result);
  assertEquals(10, result.getProperties().size());
  assertEquals(5, ((ODataEntry)result.getProperties().get("ne_Room")).getProperties().size());
  assertEquals(3, ((ODataEntry)((ODataEntry)result.getProperties().get("ne_Room")).getProperties()
      .get("nr_Building")).getProperties().size());
}
 
Example #11
Source File: XmlEntityConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void roomsFeedWithRoomInlineDifferent() throws Exception {
  InputStream stream = getFileAsStream("employeesWithDifferentInlines.xml");
  assertNotNull(stream);

  EntityProviderReadProperties readProperties = EntityProviderReadProperties.init()
      .mergeSemantic(false).isValidatingFacets(false).build();

  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  XmlEntityConsumer xec = new XmlEntityConsumer();
  ODataEntry entry = xec.readEntry(entitySet, stream, readProperties);
  assertNotNull(entry);
  assertNotNull(entry.getExpandSelectTree().getLinks().get("nr_Employees"));
  assertNotNull(entry.getExpandSelectTree().getExpandedList().get(3)
      .getLinks().get("nr_Employees").getLinks().get("ne_Team"));
  assertNotNull(entry.getExpandSelectTree().getExpandedList().get(1)
      .getLinks().get("nr_Employees").getLinks().get("ne_Room"));
  assertNotNull(entry.getExpandSelectTree().getExpandedList().get(1)
      .getLinks().get("nr_Employees").getLinks().get("ne_Room")
      .getLinks().get("nr_Building"));
  assertNotNull(entry.getExpandSelectTree().getExpandedList().get(2)
      .getLinks().get("nr_Employees").getLinks().get("ne_Room"));
  assertNull(entry.getExpandSelectTree().getExpandedList().get(0)
      .getLinks().get("nr_Employees").getLinks().get("ne_Room"));
}
 
Example #12
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse updateEntity(final PutMergePatchUriInfo uriInfo, final InputStream content,
    final String requestContentType, final boolean merge, final String contentType) throws ODataException {
  Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

  if (!appliesFilter(data, uriInfo.getFilter())) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
  }

  final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
  final EdmEntityType entityType = entitySet.getEntityType();
  final EntityProviderReadProperties properties = EntityProviderReadProperties.init()
      .mergeSemantic(merge)
      .addTypeMappings(getStructuralTypeTypeMap(data, entityType))
      .build();
  final ODataEntry entryValues = parseEntry(entitySet, content, requestContentType, properties);

  setStructuralTypeValuesFromMap(data, entityType, entryValues.getProperties(), merge);

  return ODataResponse.newBuilder().eTag(constructETag(entitySet, data)).build();
}
 
Example #13
Source File: JsonEntryConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void readEntryWithNullProperty() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  final String content = "{\"Id\":\"99\",\"Seats\":null}";

  for (final boolean merge : new boolean[] { false, true }) {
    final ODataEntry result = new JsonEntityConsumer().readEntry(entitySet, createContentAsStream(content),
        EntityProviderReadProperties.init().mergeSemantic(merge).build());

    final Map<String, Object> properties = result.getProperties();
    assertNotNull(properties);
    assertEquals(2, properties.size());
    assertEquals("99", properties.get("Id"));
    assertTrue(properties.containsKey("Seats"));
    assertNull(properties.get("Seats"));

    assertTrue(result.getMetadata().getAssociationUris("nr_Employees").isEmpty());
    checkMediaDataInitial(result.getMediaMetadata());
  }
}
 
Example #14
Source File: AtomEntryProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeWithCustomSrcAndTypeAttributeOnEmployee() throws Exception {
  AtomEntityProvider ser = createAtomEntityProvider();
  Map<String, Object> localEmployeeData = new HashMap<String, Object>(employeeData);
  String mediaResourceSourceKey = "~src";
  localEmployeeData.put(mediaResourceSourceKey, "http://localhost:8080/images/image1");
  String mediaResourceMimeTypeKey = "~type";
  localEmployeeData.put(mediaResourceMimeTypeKey, "image/jpeg");
  EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EdmMapping mapping = employeesSet.getEntityType().getMapping();
  when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey);
  when(mapping.getMediaResourceMimeTypeKey()).thenReturn(mediaResourceMimeTypeKey);
  ODataResponse response = ser.writeEntry(employeesSet, localEmployeeData, DEFAULT_PROPERTIES);
  String xmlString = verifyResponse(response);

  assertXpathExists(
      "/a:entry/a:link[@href=\"Employees('1')/$value\" and" +
          " @rel=\"edit-media\" and @type=\"image/jpeg\"]", xmlString);
  assertXpathExists("/a:entry/a:content[@type=\"image/jpeg\"]", xmlString);
  assertXpathExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString);
}
 
Example #15
Source File: XmlEntityConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * We only support <code>UTF-8</code> as character encoding.
 * 
 * @throws Exception
 */
@Test(expected = EntityProviderException.class)
public void validationOfWrongXmlEncodingUtf32() throws Exception {
  String roomWithValidNamespaces =
      "<?xml version='1.0' encoding='UTF-32'?>"
          +
          "<entry xmlns=\"http://www.w3.org/2005/Atom\" " +
          "xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" " +
          "xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" " +
          "xml:base=\"http://localhost:19000/test/\" m:etag=\"W/&quot;1&quot;\">"
          +
          "</entry>";

  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  InputStream reqContent = createContentAsStream(roomWithValidNamespaces);
  readAndExpectException(entitySet, reqContent, EntityProviderException.UNSUPPORTED_CHARACTER_ENCODING
      .addContent("UTF-32"));
}
 
Example #16
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void unbalancedPropertyEntryWithInlineEntry() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  Entity roomData = new Entity();
  roomData.addProperty("Id", "1");
  roomData.addProperty("Version", 1);
  roomData.setWriteProperties(DEFAULT_PROPERTIES);
  
  Entity buildingData = new Entity();
  buildingData.addProperty("Id", "1");
  buildingData.addProperty("Name", "Building1");
  roomData.addNavigation("nr_Building", buildingData);
  
  final ODataResponse response =
      new JsonSerializerDeserializer().writeEntry(entitySet, roomData);
  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntitypProvider must not set content header", response.getContentHeader());

  final String json = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(json);
  assertEquals("{\"Id\":\"1\",\"Version\":1,\"nr_Building\":{\"Id\":\"1\",\"Name\":\"Building1\"}}", json);
}
 
Example #17
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void entryWithExpandedEntry() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  Entity roomData = new Entity();
  roomData.addProperty("Id", "1");
  roomData.addProperty("Version", 1);
  roomData.setWriteProperties(EntitySerializerProperties.serviceRoot(URI.create(BASE_URI))
              .build());
  
  Entity buildingData = new Entity();
  buildingData.addProperty("Id", "1");
  buildingData.setWriteProperties(EntitySerializerProperties.serviceRoot(URI.create(BASE_URI)).build());
  roomData.addNavigation("nr_Building", buildingData);

  final ODataResponse response =
      new JsonSerializerDeserializer().writeEntry(entitySet, roomData);
  final String json = verifyResponse(response);
  assertEquals("{\"Id\":\"1\",\"Version\":1,"
      + "\"nr_Building\":{\"Id\":\"1\"}}",
      json);
}
 
Example #18
Source File: XmlEntityDeserializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
/**
 * For media resource if <code>properties</code> tag is within <code>content</code> tag it results in an exception.
 * 
 * OData specification v2: 2.2.6.2.2 Entity Type (as an Atom Entry Element)
 * And RFC5023 [section 4.2]
 * 
 * @throws Exception
 */
@Test(expected = EntityProviderException.class)
public void validationOfWrongPropertiesTagPositionForMediaLinkEntry() throws Exception {
  String roomWithValidNamespaces =
      "<?xml version='1.0' encoding='UTF-8'?>"
          +
          "<entry xmlns=\"http://www.w3.org/2005/Atom\" " +
          "xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" " +
          "xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" " +
          "xml:base=\"http://localhost:19000/test/\" m:etag=\"W/&quot;1&quot;\">"
          +
          "  <id>http://localhost:19000/test/Employees('1')</id>" +
          "  <title type=\"text\">Walter Winter</title>" +
          "  <updated>2013-01-11T13:50:50.541+01:00</updated>" +
          "  <content type=\"application/xml\">" +
          "    <m:properties>" +
          "      <d:EmployeeId>1</d:EmployeeId>" +
          "    </m:properties>" +
          "  </content>" +
          "</entry>";

  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  InputStream reqContent = createContentAsStream(roomWithValidNamespaces);
  readAndExpectException(entitySet, reqContent, EntityProviderException.INVALID_PARENT_TAG.addContent("properties")
      .addContent("content"));
}
 
Example #19
Source File: XmlEntityDeserializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void readCustomizableFeedMappingsWithMergeSemantic() throws Exception {
  XmlEntityDeserializer xec = new XmlEntityDeserializer();

  EdmEntitySet entitySet = MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos");
  InputStream reqContent = createContentAsStream(PHOTO_XML);
  EntityStream stream = new EntityStream();
  stream.setContent(reqContent);
  stream.setReadProperties(DeserializerProperties.init().build());

  // execute
  ODataEntry result = xec.readEntry(entitySet, stream);
  // verify
  EntryMetadata entryMetadata = result.getMetadata();
  assertEquals("http://localhost:19000/test/Container2.Photos(Id=1,Type='image%2Fpng')", entryMetadata.getId());

  Map<String, Object> data = result.getProperties();
  assertEquals("Photo1", data.get("Name"));
  assertEquals("image/png", data.get("Type"));
  // ignored customizable feed mapping
  assertNotNull(data.get("Содержание"));
  assertNull(data.get("ignore"));
}
 
Example #20
Source File: JsonEntryEntityProducerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void serializeWithCustomSrcAttributeOnRoom() throws Exception {
  Map<String, Object> roomData = new HashMap<String, Object>();
  roomData.put("Id", "1");
  roomData.put("Name", "Neu Schwanstein");
  roomData.put("Seats", new Integer(20));
  roomData.put("Version", new Integer(3));

  String mediaResourceSourceKey = "~src";
  roomData.put(mediaResourceSourceKey, "http://localhost:8080/images/image1");

  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  EdmEntityType roomType = roomsSet.getEntityType();
  EdmMapping mapping = mock(EdmMapping.class);
  when(roomType.getMapping()).thenReturn(mapping);
  when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey);

  ODataResponse response = new JsonEntityProvider().writeEntry(roomsSet, roomData, DEFAULT_PROPERTIES);
  String jsonString = verifyResponse(response);
  Gson gson = new Gson();
  LinkedTreeMap<String, Object> jsonMap = gson.fromJson(jsonString, LinkedTreeMap.class);
  jsonMap = (LinkedTreeMap<String, Object>) jsonMap.get("d");
  jsonMap = (LinkedTreeMap<String, Object>) jsonMap.get("__metadata");

  assertNull(jsonMap.get("media_src"));
  assertNull(jsonMap.get("content_type"));
  assertNull(jsonMap.get("edit_media"));
}
 
Example #21
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse readEntityLink(final GetEntityLinkUriInfo uriInfo, final String contentType)
    throws ODataException {
  final Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

  if (data == null) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
  }

  final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();

  Map<String, Object> values = new HashMap<String, Object>();
  for (final EdmProperty property : entitySet.getEntityType().getKeyProperties()) {
    values.put(property.getName(), valueAccess.getPropertyValue(data, property));
  }

  ODataContext context = getContext();
  final EntityProviderWriteProperties entryProperties = EntityProviderWriteProperties
      .serviceRoot(context.getPathInfo().getServiceRoot())
      .build();

  final int timingHandle = context.startRuntimeMeasurement("EntityProvider", "writeLink");

  final ODataResponse response = EntityProvider.writeLink(contentType, entitySet, values, entryProperties);

  context.stopRuntimeMeasurement(timingHandle);

  return ODataResponse.fromResponse(response).build();
}
 
Example #22
Source File: JsonFeedDeserializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void feedWithTeamAndDeltaAndDeletedEntriesWithoutWhen() throws Exception {
  EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams");
  String content =
      "{\"d\":{\"results\":[{" +
          "\"__metadata\":{\"id\":\"http://localhost:8080/ReferenceScenario.svc/Teams('1')\"," +
          "\"uri\":\"http://localhost:8080/ReferenceScenario.svc/Teams('1')\",\"type\":\"RefScenario.Team\"}," +
          "\"Id\":\"1\",\"Name\":\"Team 1\",\"isScrumTeam\":false,\"nt_Employees\":{\"__deferred\":{" +
          "\"uri\":\"http://localhost:8080/ReferenceScenario.svc/Teams('1')/nt_Employees\"}}}" +
          ",{ \"@odata.context\":\"$metadata#Teams/$deletedEntity\",\"id\":\"/Teams('2')\"}" +
          "]," +
          "\"__delta\":\"http://localhost:8080/ReferenceScenario.svc/Teams?!deltatoken=4711\"}}";
  assertNotNull(content);
  InputStream contentBody = createContentAsStream(content);
  EntityStream entityStream = new EntityStream();
  entityStream.setContent(contentBody);
  entityStream.setReadProperties(DEFAULT_PROPERTIES);

  // execute
  JsonEntityDeserializer xec = new JsonEntityDeserializer();
  ODataDeltaFeed feed = xec.readDeltaFeed(entitySet, entityStream);
  assertNotNull(feed);

  List<ODataEntry> entries = feed.getEntries();
  assertNotNull(entries);
  assertEquals(1, entries.size());

  FeedMetadata feedMetadata = feed.getFeedMetadata();
  assertNotNull(feedMetadata);
  assertEquals("http://localhost:8080/ReferenceScenario.svc/Teams?!deltatoken=4711", feedMetadata.getDeltaLink());

  List<DeletedEntryMetadata> deletedEntries = feed.getDeletedEntries();
  assertEquals(1, deletedEntries.size());
  assertEquals("/Teams('2')", deletedEntries.get(0).getUri());
  assertNull(deletedEntries.get(0).getWhen());
}
 
Example #23
Source File: JsonEntryEntityProducerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void contentOnlyWithMetadata() throws Exception {
  HashMap<String, Object> employeeData = new HashMap<String, Object>();
  Calendar date = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  date.clear();
  date.set(1999, 0, 1);
  employeeData.put("EmployeeId", "1");
  employeeData.put("ImmageUrl", null);
  employeeData.put("ManagerId", "1");
  employeeData.put("Age", new Integer(52));
  employeeData.put("RoomId", "1");
  employeeData.put("EntryDate", date);
  employeeData.put("TeamId", "42");
  employeeData.put("EmployeeName", "Walter Winter");
  Map<String, Object> locationData = new HashMap<String, Object>();
  Map<String, Object> cityData = new HashMap<String, Object>();
  cityData.put("PostalCode", "33470");
  cityData.put("CityName", "Duckburg");
  locationData.put("City", cityData);
  locationData.put("Country", "Calisota");
  employeeData.put("Location", locationData);

  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.fromProperties(DEFAULT_PROPERTIES).omitJsonWrapper(true).contentOnly(true)
          .includeMetadataInContentOnly(true).build();
  final ODataResponse response = new JsonEntityProvider().writeEntry(entitySet, employeeData, properties);
  Map<String, Object> employee =
      (Map<String, Object>) new Gson().fromJson(new InputStreamReader((InputStream) response.getEntity()), Map.class);
  assertNotNull(employee.get("__metadata"));
  assertNull(employee.get("ne_Manager"));
  assertNull(employee.get("ne_Team"));
  assertNull(employee.get("ne_Room"));
}
 
Example #24
Source File: JsonFeedWithDeltaLinkProducerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void deletedEntries() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");

  TombstoneCallback tombstoneCallback =
      new TombstoneCallbackImpl(deletedRoomData, null);

  final String json = writeRoomData(entitySet, tombstoneCallback);

  assertDeletedEntries(json);
  assertTrue("Somthing wrong with closing brakets after deleted entries!", json.endsWith("}]}}"));
}
 
Example #25
Source File: EdmUriBuilderTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUriWithExpand() throws EdmException {
  EdmEntitySet entitySet = edm.getDefaultEntityContainer().getEntitySet("Managers");
  URI uri = new EdmURIBuilderImpl(SERVICE_ROOT_URI).
  appendEntitySetSegment(entitySet).
  appendKeySegment((EdmProperty)entitySet.getEntityType().getProperty("EmployeeId"), "1").
  expand("nm_Employees").
  build();
  assertNotNull(uri);
  assertEquals("http://host:80/service/Managers('1')?$expand=nm_Employees", uri.toASCIIString());
}
 
Example #26
Source File: UriParserImpl.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private void handleNormalInitialSegment() throws UriSyntaxException, UriNotMatchingException, EdmException {
  final Matcher matcher = INITIAL_SEGMENT_PATTERN.matcher(currentPathSegment);
  if (!matcher.matches()) {
    throw new UriNotMatchingException(UriNotMatchingException.MATCHPROBLEM.addContent(currentPathSegment));
  }

  final String entityContainerName = percentDecode(matcher.group(1));
  final String segmentName = percentDecode(matcher.group(2));
  final String keyPredicate = matcher.group(3);
  final String emptyParentheses = matcher.group(4);

  final EdmEntityContainer entityContainer =
      entityContainerName == null ? edm.getDefaultEntityContainer() : edm.getEntityContainer(entityContainerName);
  if (entityContainer == null) {
    throw new UriNotMatchingException(UriNotMatchingException.CONTAINERNOTFOUND.addContent(entityContainerName));
  }
  uriResult.setEntityContainer(entityContainer);

  final EdmEntitySet entitySet = entityContainer.getEntitySet(segmentName);
  if (entitySet != null) {
    uriResult.setStartEntitySet(entitySet);
    handleEntitySet(entitySet, keyPredicate);
  } else {
    final EdmFunctionImport functionImport = entityContainer.getFunctionImport(segmentName);
    if (functionImport == null) {
      throw new UriNotMatchingException(UriNotMatchingException.NOTFOUND.addContent(segmentName));
    }
    uriResult.setFunctionImport(functionImport);
    handleFunctionImport(functionImport, emptyParentheses, keyPredicate);
  }
}
 
Example #27
Source File: ExpandSelectTreeNodeBuilderTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test(expected = EdmException.class)
public void buildWithWrongSelectedNavigationPropertiesOnly() throws Exception {
  EdmEntitySet roomsSet = edm.getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> selectedNavigationPropertyNames = new ArrayList<String>();
  selectedNavigationPropertyNames.add("WrongProperty");
  ExpandSelectTreeNode.entitySet(roomsSet).selectedLinks(selectedNavigationPropertyNames).build();
}
 
Example #28
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void addEntityAndMapToNavigation() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  Entity employeeData = new Entity();
  employeeData.addProperty("EmployeeId", "1");

  Entity managerLink = new Entity();
  managerLink.addProperty("EmployeeId", "1");
  employeeData.addNavigation("ne_Manager", managerLink);
  
  Map<String, Object> navigationLink = new HashMap<String, Object>();
  navigationLink.put("Id", "1");
  employeeData.addNavigation("ne_Room", navigationLink);

  EntitySerializerProperties properties =
      EntitySerializerProperties.fromProperties(DEFAULT_PROPERTIES).build();
  employeeData.setWriteProperties(properties);
  final ODataResponse response = new JsonSerializerDeserializer().writeEntry(entitySet, employeeData);
  Map<String, Object> employee =
      (Map<String, Object>) new Gson().fromJson(new InputStreamReader((InputStream) response.getEntity()), Map.class);
  assertNull(employee.get("__metadata"));
  assertNull(employee.get("ne_Team"));
  assertNotNull(employee.get("ne_Room"));

  assertEquals("1", employee.get("EmployeeId"));
  Map<String, Object> map = (Map<String, Object>) employee.get("ne_Manager");
  assertEquals(map.get("EmployeeId"), "1");
  
  Map<String, Object> roomMap = (Map<String, Object>) employee.get("ne_Room");
  assertEquals(((Map<String, Object>)roomMap.get("__deferred")).get("uri"), 
      "http://host:80/service/Rooms('1')");
}
 
Example #29
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void serializeWithCustomSrcAttributeOnRoom() throws Exception {
  Entity roomData = new Entity();
  roomData.addProperty("Id", "1");
  roomData.addProperty("Name", "Neu Schwanstein");
  roomData.addProperty("Seats", new Integer(20));
  roomData.addProperty("Version", new Integer(3));

  String mediaResourceSourceKey = "~src";
  roomData.addProperty(mediaResourceSourceKey, "http://localhost:8080/images/image1");
  roomData.setWriteProperties(EntitySerializerProperties.serviceRoot(URI.create(BASE_URI)).
      includeMetadata(true).build());

  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  EdmEntityType roomType = roomsSet.getEntityType();
  EdmMapping mapping = mock(EdmMapping.class);
  when(roomType.getMapping()).thenReturn(mapping);
  when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey);

  ODataResponse response = new JsonSerializerDeserializer().writeEntry(roomsSet, roomData);
  String jsonString = verifyResponse(response);
  Gson gson = new Gson();
  LinkedTreeMap<String, Object> jsonMap = gson.fromJson(jsonString, LinkedTreeMap.class);
  jsonMap = (LinkedTreeMap<String, Object>) jsonMap.get("__metadata");

  assertNull(jsonMap.get("media_src"));
  assertNull(jsonMap.get("content_type"));
  assertNull(jsonMap.get("edit_media"));
}
 
Example #30
Source File: EdmUriBuilderTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testUriWithSelect() throws EdmException {
  EdmEntitySet entitySet = edm.getDefaultEntityContainer().getEntitySet("Managers");
  URI uri = new EdmURIBuilderImpl(SERVICE_ROOT_URI).
  appendEntitySetSegment(entitySet).
  appendKeySegment((EdmProperty)entitySet.getEntityType().getProperty("EmployeeId"), "1").
  appendNavigationSegment((EdmNavigationProperty)entitySet.getEntityType().getProperty("nm_Employees")).
  select("EmployeeId", "EmployeeName", "RoomId", "TeamId").
  build();
  assertNotNull(uri);
  assertEquals("http://host:80/service/Managers('1')/nm_Employees"
      + "?$select=EmployeeId%2CEmployeeName%2CRoomId%2CTeamId", uri.toASCIIString());
}