org.apache.olingo.odata2.api.processor.ODataResponse Java Examples

The following examples show how to use org.apache.olingo.odata2.api.processor.ODataResponse. 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: InvalidDataInScenarioTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse readEntity(GetEntityUriInfo uriInfo, String contentType) throws ODataException {
  HashMap<String, Object> data = new HashMap<String, Object>();

  if ("Employees".equals(uriInfo.getTargetEntitySet().getName())) {
    if ("2".equals(uriInfo.getKeyPredicates().get(0).getLiteral())) {
      data.put("EmployeeId", "1");
      data.put("TeamId", "420");
    }

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

    return EntityProvider.writeEntry(contentType, uriInfo.getTargetEntitySet(), data, writeProperties);
  } else {
    throw new ODataApplicationException("Wrong testcall", Locale.getDefault(), HttpStatusCodes.NOT_IMPLEMENTED);
  }
}
 
Example #2
Source File: BatchHandlerImpl.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private ODataResponse setContentIdHeader(ODataRequest request, final ODataResponse response, 
    final String mimeHeaderContentId, final String requestHeaderContentId) {
  ODataResponse modifiedResponse;
  if (requestHeaderContentId != null && mimeHeaderContentId != null) {
    String baseUri = getBaseUri(request);
    fillContentIdMap(response, requestHeaderContentId, baseUri);
    fillContentIdMap(response, mimeHeaderContentId, baseUri);
    modifiedResponse =
        ODataResponse.fromResponse(response).header(BatchHelper.REQUEST_HEADER_CONTENT_ID, requestHeaderContentId)
            .header(BatchHelper.MIME_HEADER_CONTENT_ID, mimeHeaderContentId).build();
  } else if (requestHeaderContentId != null) {
    modifiedResponse =
        ODataResponse.fromResponse(response).header(BatchHelper.REQUEST_HEADER_CONTENT_ID, requestHeaderContentId)
            .build();
  } else if (mimeHeaderContentId != null) {
    modifiedResponse =
        ODataResponse.fromResponse(response).header(BatchHelper.MIME_HEADER_CONTENT_ID, mimeHeaderContentId).build();
  } else {
    return response;
  }
  return modifiedResponse;
}
 
Example #3
Source File: JsonFeedEntityProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void unbalancedPropertyFeedWithSelect() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Companys");
  List<Map<String, Object>> originalData = createData(true);
  List<String> selectedPropertyNames = new ArrayList<String>();
  selectedPropertyNames.add("Id");
  selectedPropertyNames.add("Location");
  ExpandSelectTreeNode select =
      ExpandSelectTreeNode.entitySet(entitySet).selectedProperties(selectedPropertyNames).build();
  
  final ODataResponse response = new JsonEntityProvider().writeFeed(entitySet, originalData,
      EntityProviderWriteProperties.serviceRoot(URI.create(BASE_URI)).expandSelectTree(select).
      isDataBasedPropertySerialization(true).build());

  EntityProviderReadProperties readProperties = EntityProviderReadProperties.init().mergeSemantic(false).build();
  JsonEntityConsumer consumer = new JsonEntityConsumer();
  ODataFeed feed = consumer.readFeed(entitySet, (InputStream) response.getEntity(), readProperties);

  compareList(originalData, feed.getEntries());
}
 
Example #4
Source File: AcceptHeaderTypeTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private HttpResponse testGetRequest(final String uriExtension, final String acceptHeader,
    final HttpStatusCodes expectedStatus, final String expectedContentType)
    throws ClientProtocolException, IOException, ODataException {
  // prepare
  ODataResponse expectedResponse = ODataResponse.contentHeader(expectedContentType).entity("Test passed.").build();
  when(processor.readMetadata(any(GetMetadataUriInfo.class), any(String.class))).thenReturn(expectedResponse);
  when(processor.readEntity(any(GetEntityUriInfo.class), any(String.class))).thenReturn(expectedResponse);
  when(processor.readEntitySet(any(GetEntitySetUriInfo.class), any(String.class))).thenReturn(expectedResponse);

  HttpGet getRequest = new HttpGet(URI.create(getEndpoint().toString() + uriExtension));
  getRequest.setHeader(HttpHeaders.ACCEPT, acceptHeader);

  // execute
  HttpResponse response = getHttpClient().execute(getRequest);

  // validate
  assertEquals(expectedStatus.getStatusCode(), response.getStatusLine().getStatusCode());
  Header[] contentTypeHeaders = response.getHeaders("Content-Type");
  assertEquals("Found more then one content type header in response.", 1, contentTypeHeaders.length);
  assertEquals("Received content type does not match expected.", expectedContentType, contentTypeHeaders[0]
      .getValue());
  assertEquals("Received status code does not match expected.", expectedStatus.getStatusCode(), response
      .getStatusLine().getStatusCode());
  //
  return response;
}
 
Example #5
Source File: ODataServlet.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
protected void handleRedirect(final HttpServletRequest req, final HttpServletResponse resp,
                              ODataServiceFactory serviceFactory) throws IOException {
  String method = req.getMethod();
  if (ODataHttpMethod.GET.name().equals(method) ||
      ODataHttpMethod.POST.name().equals(method) ||
      ODataHttpMethod.PUT.name().equals(method) ||
      ODataHttpMethod.DELETE.name().equals(method) ||
      ODataHttpMethod.PATCH.name().equals(method) ||
      ODataHttpMethod.MERGE.name().equals(method) ||
      HTTP_METHOD_HEAD.equals(method) ||
      HTTP_METHOD_OPTIONS.equals(method)) {
    ODataResponse odataResponse = ODataResponse.status(HttpStatusCodes.TEMPORARY_REDIRECT)
        .header(HttpHeaders.LOCATION, createLocation(req))
        .build();
    createResponse(resp, odataResponse);
  } else {
    createNotImplementedResponse(req, ODataHttpException.COMMON, resp, serviceFactory);
  }

}
 
Example #6
Source File: XmlFunctionImportTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void singleComplexType() throws Exception {
  final EdmFunctionImport functionImport =
      MockFacade.getMockEdm().getDefaultEntityContainer().getFunctionImport("MostCommonLocation");

  final ODataResponse response =
      createAtomEntityProvider()
          .writeFunctionImport(functionImport, employeeData.get("Location"), DEFAULT_PROPERTIES);
  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntitypProvider must not set content header", response.getContentHeader());

  final String xml = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(xml);

  assertXpathExists("/d:MostCommonLocation", xml);
  assertXpathEvaluatesTo("RefScenario.c_Location", "/d:MostCommonLocation/@m:type", xml);
  assertXpathEvaluatesTo("Duckburg", "/d:MostCommonLocation/d:City/d:CityName/text()", xml);
}
 
Example #7
Source File: AtomEntryProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeETagEncoding() throws IOException, XpathException, SAXException, XMLStreamException,
    FactoryConfigurationError, ODataException {
  Edm edm = MockFacade.getMockEdm();
  EdmTyped roomIdProperty = edm.getEntityType("RefScenario", "Room").getProperty("Id");
  EdmFacets facets = mock(EdmFacets.class);
  when(facets.getConcurrencyMode()).thenReturn(EdmConcurrencyMode.Fixed);
  when(facets.getMaxLength()).thenReturn(3);
  when(((EdmProperty) roomIdProperty).getFacets()).thenReturn(facets);

  roomData.put("Id", "<\">");
  AtomEntityProvider ser = createAtomEntityProvider();
  ODataResponse response =
      ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, DEFAULT_PROPERTIES);

  assertNotNull(response);
  assertNotNull(response.getEntity());
  assertNull("EntityProvider should not set content header", response.getContentHeader());
  assertEquals("W/\"<\">.3\"", response.getETag());

  String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());

  assertXpathExists("/a:entry", xmlString);
  assertXpathExists("/a:entry/@m:etag", xmlString);
  assertXpathEvaluatesTo("W/\"<\">.3\"", "/a:entry/@m:etag", xmlString);
}
 
Example #8
Source File: BatchResponseTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testissueWithHeaderHavingUmlautChars() throws BatchException, IOException {
  List<BatchResponsePart> parts = new ArrayList<BatchResponsePart>();
  String headerValue = "<notification xmlns:ns=\"http://namespace\">"
      + "<code>TEST_MSG/004</code><message>Team ID 'XXX_E'äöü Ö is not in the defined range."
      + "</message><target>Team_Identifier</target><severity>error</severity><details><detail>"
      + "<code>TEST_MSG/010</code><message>"
      + "This is a message text of a business exception raised by the provider.</message><target>"
      + "</target><severity>warning</severity></detail></details></notification>";
  ODataResponse response = ODataResponse.entity("Walter Winter")
      .status(HttpStatusCodes.OK)
      .header("message", headerValue)
      .contentHeader("application/xml")
      .build();
  List<ODataResponse> responses = new ArrayList<ODataResponse>(1);
  responses.add(response);
  parts.add(BatchResponsePart.responses(responses).changeSet(false).build());

  BatchResponseWriter writer = new BatchResponseWriter();
  ODataResponse batchResponse = writer.writeResponse(parts);

  assertNotNull(batchResponse.getEntity());
  assertTrue(batchResponse.getEntity().toString().
      contains("Team ID 'XXX_E'äöü Ö is not in the defined range."));
}
 
Example #9
Source File: JsonEntryEntitySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void addEmptyEntityToNavigation() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  Entity employeeData = new Entity();
  employeeData.addProperty("EmployeeId", "1");
  Entity managerLink = new Entity();
  employeeData.addNavigation("ne_Manager", managerLink); 

  EntitySerializerProperties properties =
      EntitySerializerProperties.fromProperties(DEFAULT_PROPERTIES).build();
  employeeData.setWriteProperties(properties);
  final ODataResponse response = new JsonSerializerDeserializer().writeEntry(entitySet, employeeData);
  @SuppressWarnings("unchecked")
  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"));
  assertNull(employee.get("ne_Room"));

  assertEquals("1", employee.get("EmployeeId"));
  assertNotNull(employee.get("ne_Manager"));
}
 
Example #10
Source File: AtomEntrySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void entityWithEmptyInlineEntry() throws Exception {

  Entity roomData = new Entity();
  roomData.addProperty("Id", "1");
  roomData.addProperty("Name", "Neu Schwanstein");
  roomData.addProperty("Seats", new Integer(20));
  Entity buildingData = new Entity();
  roomData.addNavigation("nr_Building", buildingData);
  EntitySerializerProperties properties =
      EntitySerializerProperties.serviceRoot(BASE_URI)
          .includeMetadata(true).build();
  roomData.setWriteProperties(properties);
  buildingData.setWriteProperties(properties);
  AtomSerializerDeserializer provider = createAtomEntityProvider();
  ODataResponse response =
      provider.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms"), roomData);

  String xmlString = verifyResponse(response);
  assertXpathNotExists("/a:entry/m:properties", xmlString);
  assertXpathExists("/a:entry/a:link", xmlString);
  assertXpathExists("/a:entry/a:content/m:properties/d:Id", xmlString);
  assertXpathExists("/a:entry/a:content/m:properties/d:Name", xmlString);
  assertXpathExists("/a:entry/a:content/m:properties/d:Seats", xmlString);
}
 
Example #11
Source File: AtomFeedSerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void feedWithGlobalEntityProperties() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Teams");
  EntityCollection teamsData = new EntityCollection();
  Entity team1Data = new Entity();
  team1Data.addProperty("Id", "1");
  team1Data.addProperty("isScrumTeam", true);
  Entity team2Data = new Entity();
  team2Data.addProperty("Id", "2");
  team2Data.addProperty("isScrumTeam", false);
  teamsData.addEntity(team1Data);
  teamsData.addEntity(team2Data);
  teamsData.setCollectionProperties(EntityCollectionSerializerProperties.serviceRoot(BASE_URI).build());
  teamsData.setGlobalEntityProperties(EntitySerializerProperties.serviceRoot(BASE_URI).
      includeMetadata(true).build());
  
  final ODataResponse response = new AtomSerializerDeserializer().writeFeed(entitySet, teamsData);
  final String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertNotNull(xmlString);
  assertXpathExists("/a:feed", xmlString);
  assertXpathExists("/a:feed/a:entry/a:id", xmlString);
  assertXpathExists("/a:feed/a:entry/a:content/m:properties", xmlString);
  assertXpathExists("/a:feed/a:entry/a:content/m:properties/d:Id", xmlString);
  assertXpathExists("/a:feed/a:entry/a:content/m:properties/d:isScrumTeam", xmlString);
}
 
Example #12
Source File: AtomEntryProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeWithoutFacetsValidation() throws Exception {
  Edm edm = MockFacade.getMockEdm();
  EdmTyped roomNameProperty = edm.getEntityType("RefScenario", "Room").getProperty("Name");
  EdmFacets facets = mock(EdmFacets.class);
  when(facets.getMaxLength()).thenReturn(3);
  when(((EdmProperty) roomNameProperty).getFacets()).thenReturn(facets);

  String name = "1234567";
  roomData.put("Name", name);
  AtomEntityProvider ser = createAtomEntityProvider();
  EntityProviderWriteProperties properties = EntityProviderWriteProperties
      .fromProperties(DEFAULT_PROPERTIES).validatingFacets(false).build();
  ODataResponse response =
      ser.writeEntry(edm.getDefaultEntityContainer().getEntitySet("Rooms"), roomData, properties);
  assertNotNull(response);


  assertNotNull(response.getEntity());
  String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity());

  assertXpathEvaluatesTo(name, "/a:entry/a:content/m:properties/d:Name/text()", xmlString);
}
 
Example #13
Source File: ExpandSelectProducerWithBuilderTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void expandBuildingAndSelectIdFromRoom() throws Exception {
  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> expandedNavigationProperties = new ArrayList<String>();
  expandedNavigationProperties.add("nr_Building");

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

  ExpandSelectTreeNode expandSelectTree =
      ExpandSelectTreeNode.entitySet(roomsSet).selectedProperties(selectedProperties).expandedLinks(
          expandedNavigationProperties).build();

  Map<String, ODataCallback> callbacks = new HashMap<String, ODataCallback>();
  callbacks.put("nr_Building", new LocalCallback());
  EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.fromProperties(DEFAULT_PROPERTIES).callbacks(callbacks).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/d:Id", xml);
  assertXpathNotExists("/a:entry/a:content/m:properties/d:Name", xml);
  assertXpathExists("/a:entry/a:link[@type]/m:inline", xml);
}
 
Example #14
Source File: AtomEntrySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeWithCustomSrcAttributeOnEmployee() throws Exception {
  AtomSerializerDeserializer ser = createAtomEntityProvider();
  Entity localEmployeeData = new Entity();
  for (Entry<String, Object> data : employeeData.getProperties().entrySet()) {
    localEmployeeData.addProperty(data.getKey(), data.getValue());
  }
  String mediaResourceSourceKey = "~src";
  localEmployeeData.addProperty(mediaResourceSourceKey, "http://localhost:8080/images/image1");
  EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EdmMapping mapping = employeesSet.getEntityType().getMapping();
  when(mapping.getMediaResourceSourceKey()).thenReturn(mediaResourceSourceKey);
  localEmployeeData.setWriteProperties(DEFAULT_PROPERTIES);
  ODataResponse response = ser.writeEntry(employeesSet, localEmployeeData);
  String xmlString = verifyResponse(response);

  assertXpathExists(
      "/a:entry/a:link[@href=\"Employees('1')/$value\" and" +
          " @rel=\"edit-media\" and @type=\"application/octet-stream\"]", xmlString);
  assertXpathExists("/a:entry/a:content[@type=\"application/octet-stream\"]", xmlString);
  assertXpathExists("/a:entry/a:content[@src=\"http://localhost:8080/images/image1\"]", xmlString);
}
 
Example #15
Source File: JsonLinksEntityProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeLinksAndInlineCount() throws Exception {
  final EdmEntitySet entitySet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  Map<String, Object> employee1 = new HashMap<String, Object>();
  employee1.put("EmployeeId", "1");
  Map<String, Object> employee2 = new HashMap<String, Object>();
  employee2.put("EmployeeId", "2");
  ArrayList<Map<String, Object>> employeesData = new ArrayList<Map<String, Object>>();
  employeesData.add(employee1);
  employeesData.add(employee2);

  final ODataResponse response = new JsonEntityProvider().writeLinks(entitySet, employeesData,
      EntityProviderWriteProperties.serviceRoot(URI.create(BASE_URI))
          .inlineCountType(InlineCount.ALLPAGES).inlineCount(42).build());
  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("{\"d\":{\"__count\":\"42\",\"results\":["
      + "{\"uri\":\"" + BASE_URI + "Employees('1')\"},"
      + "{\"uri\":\"" + BASE_URI + "Employees('2')\"}]}}",
      json);
}
 
Example #16
Source File: JsonFunctionImportTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void noReturnTypeAction() throws Exception {
  final EdmFunctionImport functionImport =
      MockFacade.getMockEdm().getDefaultEntityContainer().getFunctionImport("AddEmployee");
  final String uri = "http://host:80/service/";
  final EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.serviceRoot(URI.create(uri)).build();
  Map<String, Object> employeeData = new HashMap<String, Object>();
  employeeData.put("EmployeeId", "1");
  employeeData.put("getImageType", "image/jpeg");
  final ODataResponse response =
      new JsonEntityProvider().writeFunctionImport(functionImport, employeeData, properties);
  assertNotNull(response);
  assertNull(response.getEntity());
  assertNull(response.getContentHeader());
  assertEquals(HttpStatusCodes.ACCEPTED, response.getStatus());
 
}
 
Example #17
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse executeFunctionImportValue(final GetFunctionImportUriInfo uriInfo, final String contentType)
    throws ODataException {
  final EdmFunctionImport functionImport = uriInfo.getFunctionImport();
  final EdmSimpleType type = (EdmSimpleType) functionImport.getReturnType().getType();

  final Object data = dataSource.readData(
      functionImport,
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      null);

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

  ODataResponse response;
  if (type == EdmSimpleTypeKind.Binary.getEdmSimpleTypeInstance()) {
    response = EntityProvider.writeBinary(((BinaryData) data).getMimeType(), ((BinaryData) data).getData());
  } else {
    final String value = type.valueToString(data, EdmLiteralKind.DEFAULT, null);
    response = EntityProvider.writeText(value == null ? "" : value);
  }
  return ODataResponse.fromResponse(response).build();
}
 
Example #18
Source File: SimpleODataErrorCallback.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
	Throwable rootCause = context.getException();
	LOGGER.error("Error in the OData. Reason: " + rootCause.getMessage(), rootCause); //$NON-NLS-1$

	Throwable innerCause = rootCause.getCause();
	if (rootCause instanceof ODataJPAException && innerCause != null && innerCause instanceof AppODataException) {
		context.setMessage(innerCause.getMessage());
		Throwable childInnerCause = innerCause.getCause();
		context.setInnerError(childInnerCause != null ? childInnerCause.getMessage() : ""); //$NON-NLS-1$
	} else {
		context.setMessage(HttpStatusCodes.INTERNAL_SERVER_ERROR.getInfo());
		context.setInnerError(rootCause.getMessage());
	}

	context.setHttpStatus(HttpStatusCodes.INTERNAL_SERVER_ERROR);
	return EntityProvider.writeErrorDocument(context);
}
 
Example #19
Source File: XmlSelectProducerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void selectAge() throws Exception {
  ExpandSelectTreeNode selectTree = getSelectExpandTree("Age", null);

  EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.serviceRoot(BASE_URI).expandSelectTree(selectTree).build();
  AtomEntityProvider provider = createAtomEntityProvider();
  ODataResponse response =
      provider.writeEntry(MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees"),
          employeeData, properties);

  String xmlString = verifyResponse(response);

  verifyNavigationProperties(xmlString, F, F, F);
  assertXpathExists("/a:entry/m:properties", xmlString);
  verifyKeyProperties(xmlString, F, F, F, F);
  verifySingleProperties(xmlString, F, T, F, F);
  verifyComplexProperties(xmlString, F);
}
 
Example #20
Source File: JsonEntityProvider.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse writeFunctionImport(final EdmFunctionImport functionImport, final Object data,
    final EntityProviderWriteProperties properties) throws EntityProviderException {
  try {
    if(functionImport.getReturnType() !=null){
      if (functionImport.getReturnType().getType().getKind() == EdmTypeKind.ENTITY) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>) data;
        return writeEntry(functionImport.getEntitySet(), map, properties);
      }

      final EntityPropertyInfo info = EntityInfoAggregator.create(functionImport);
      if (functionImport.getReturnType().getMultiplicity() == EdmMultiplicity.MANY) {
        return writeCollection(info, (List<?>) data);
      } else {
        return writeSingleTypedElement(info, data);
      }
    }else{
      return ODataResponse.newBuilder().status(HttpStatusCodes.ACCEPTED).build();
    }
  } catch (final EdmException e) {
    throw new EntityProviderProducerException(e.getMessageReference(), e);
  }
}
 
Example #21
Source File: AtomEntrySerializerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void serializeWithValueEncoding() throws IOException, XpathException, SAXException, XMLStreamException,
 FactoryConfigurationError, ODataException {
 photoData.addProperty("Type", "< Ö >");
 photoData.setWriteProperties(DEFAULT_PROPERTIES);
 
 AtomSerializerDeserializer ser = createAtomEntityProvider();
 ODataResponse response =
 ser.writeEntry(MockFacade.getMockEdm().getEntityContainer("Container2").getEntitySet("Photos"), photoData);
 String xmlString = verifyResponse(response);
 
 assertXpathExists("/a:entry", xmlString);
 assertXpathEvaluatesTo(BASE_URI.toASCIIString(), "/a:entry/@xml:base", xmlString);
 assertXpathExists("/a:entry/a:id", xmlString);
 assertXpathEvaluatesTo(BASE_URI.toASCIIString() + "Container2.Photos(Id=1,Type='%3C%20%C3%96%20%3E')",
 "/a:entry/a:id/text()", xmlString);
 assertXpathEvaluatesTo("Container2.Photos(Id=1,Type='%3C%20%C3%96%20%3E')", "/a:entry/a:link/@href", xmlString);
 }
 
Example #22
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse deleteEntityLink(final DeleteUriInfo uriInfo, final String contentType) throws ODataException {
  final List<NavigationSegment> navigationSegments = uriInfo.getNavigationSegments();
  final List<NavigationSegment> previousSegments = navigationSegments.subList(0, navigationSegments.size() - 1);

  final Object sourceData = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      previousSegments);

  final EdmEntitySet entitySet = previousSegments.isEmpty() ?
      uriInfo.getStartEntitySet() : previousSegments.get(previousSegments.size() - 1).getEntitySet();
  final EdmEntitySet targetEntitySet = uriInfo.getTargetEntitySet();
  final Map<String, Object> keys = mapKey(uriInfo.getTargetKeyPredicates());

  final Object targetData = dataSource.readRelatedData(entitySet, sourceData, targetEntitySet, keys);

  // if (!appliesFilter(targetData, uriInfo.getFilter()))
  if (targetData == null) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
  }

  dataSource.deleteRelation(entitySet, sourceData, targetEntitySet, keys);

  return ODataResponse.newBuilder().build();
}
 
Example #23
Source File: BatchHandlerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse createEntity(PostUriInfo uriInfo, InputStream content, String requestContentType,
    String contentType) throws ODataException {
  PathInfo pathInfo = getContext().getPathInfo();
  assertFirst(pathInfo);
  assertEquals("Employees", uriInfo.getTargetEntitySet().getName());
  return ODataResponse.newBuilder().status(HttpStatusCodes.OK).idLiteral(SERVICE_ROOT + "Employees('1')").build();
}
 
Example #24
Source File: EntityTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void readTeams() throws Exception {
  final UriInfo uriResult = mockUriResult("Teams", "Id", "1");

  ODataResponse response =
      processor.readEntity(uriResult, ContentType.APPLICATION_ATOM_XML_ENTRY.toContentTypeString());
  assertNotNull(response);
  assertTrue(readContent(response).contains("Team"));
}
 
Example #25
Source File: JsonPropertyProducerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void serializeComplexPropertyNull() throws Exception {
  final EdmProperty property =
      (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Location");
  final ODataResponse response = new JsonEntityProvider().writeProperty(property, null);
  assertEquals("{\"d\":{\"Location\":{\"__metadata\":{\"type\":\"RefScenario.c_Location\"},"
      + "\"City\":{\"__metadata\":{\"type\":\"RefScenario.c_City\"},"
      + "\"PostalCode\":null,\"CityName\":null},\"Country\":null}}}",
      StringHelper.inputStreamToString((InputStream) response.getEntity()));
}
 
Example #26
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 #27
Source File: DebugInfoBodyTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void jsonStringContent() throws Exception {
  ODataResponse response = mock(ODataResponse.class);
  when(response.getEntity()).thenReturn(STRING_CONTENT);
  when(response.getContentHeader()).thenReturn(HttpContentType.APPLICATION_OCTET_STREAM);
  assertEquals(STRING_CONTENT_JSON, appendJson(response));

  when(response.getContentHeader()).thenReturn("image/png");
  assertEquals(STRING_CONTENT_JSON, appendJson(response));
}
 
Example #28
Source File: AnnotationSampleServiceFactory.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse handleError(final ODataErrorContext context) throws ODataApplicationException {
  if (context.getHttpStatus() == HttpStatusCodes.INTERNAL_SERVER_ERROR) {
    LOG.error("Internal Server Error", context.getException());
  }

  return EntityProvider.writeErrorDocument(context);
}
 
Example #29
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public ODataResponse deleteEntityLink(final DeleteUriInfo uriInfo, final String contentType) throws ODataException {
  final List<NavigationSegment> navigationSegments = uriInfo.getNavigationSegments();
  final List<NavigationSegment> previousSegments = navigationSegments.subList(0, navigationSegments.size() - 1);

  final Object sourceData = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      previousSegments);

  final EdmEntitySet entitySet = previousSegments.isEmpty() ?
      uriInfo.getStartEntitySet() : previousSegments.get(previousSegments.size() - 1).getEntitySet();
  final EdmEntitySet targetEntitySet = uriInfo.getTargetEntitySet();
  final Map<String, Object> keys = mapKey(uriInfo.getTargetKeyPredicates());

  final Object targetData = dataSource.readRelatedData(entitySet, sourceData, targetEntitySet, keys);

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

  dataSource.deleteRelation(entitySet, sourceData, targetEntitySet, keys);

  return ODataResponse.newBuilder().build();
}
 
Example #30
Source File: EntityTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void readRooms() throws Exception {
  final UriInfo uriResult = mockUriResult("Rooms", "Id", "1");

  ODataResponse response =
      processor.readEntity(uriResult, ContentType.APPLICATION_ATOM_XML_FEED.toContentTypeString());
  assertNotNull(response);
  assertTrue(readContent(response).contains("Room"));
}