org.apache.olingo.odata2.api.ep.EntityProvider Java Examples

The following examples show how to use org.apache.olingo.odata2.api.ep.EntityProvider. 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: ODataJPADefaultProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse executeBatch(final BatchHandler handler, final String contentType, final InputStream content)
    throws ODataException {
  try {
    oDataJPAContext.setODataContext(getContext());

    ODataResponse batchResponse;
    List<BatchResponsePart> batchResponseParts = new ArrayList<BatchResponsePart>();
    PathInfo pathInfo = getContext().getPathInfo();
    EntityProviderBatchProperties batchProperties = EntityProviderBatchProperties.init().pathInfo(pathInfo).build();
    List<BatchRequestPart> batchParts = EntityProvider.parseBatchRequest(contentType, content, batchProperties);

    for (BatchRequestPart batchPart : batchParts) {
      batchResponseParts.add(handler.handleBatchPart(batchPart));
    }
    batchResponse = EntityProvider.writeBatchResponse(batchResponseParts);
    return batchResponse;
  } finally {
    close(true);
  }
}
 
Example #2
Source File: ServiceTicketODataConsumer.java    From C4CODATAAPIDEVGUIDE with Apache License 2.0 6 votes vote down vote up
public ODataEntry readEntry(String serviceUri, String contentType,
		String entitySetName, String keyValue, SystemQueryOptions options)
		throws IllegalStateException, IOException, EdmException,
		EntityProviderException {
	EdmEntityContainer entityContainer = readEdm()
			.getDefaultEntityContainer();
	logger.info("Entity container is => " + entityContainer.getName());
	String absolutUri = createUri(serviceUri, entitySetName, keyValue,
			options);

	InputStream content = executeGet(absolutUri, contentType);

	return EntityProvider.readEntry(contentType,
			entityContainer.getEntitySet(entitySetName), content,
			EntityProviderReadProperties.init().build());
}
 
Example #3
Source File: BatchHandlerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void contentIdReferencingWithAdditionalSegments() throws Exception {
  SERVICE_ROOT = SERVICE_BASE + "seg1/seg2/";
  PathInfoImpl pathInfo = new PathInfoImpl();
  pathInfo.setPrecedingPathSegment(Arrays.asList(
      (PathSegment) new ODataPathSegmentImpl("seg1", null),
      (PathSegment) new ODataPathSegmentImpl("seg2", null)));
  pathInfo.setServiceRoot(new URI(SERVICE_ROOT));
  pathInfo.setODataPathSegment(Collections.<PathSegment> singletonList(
      new ODataPathSegmentImpl("$batch", null)));
  EntityProviderBatchProperties properties = EntityProviderBatchProperties.init().pathInfo(pathInfo).build();
  InputStream content = readFile("/batchContentIdReferencing.batch");
  List<BatchRequestPart> parsedRequest = EntityProvider.parseBatchRequest(CONTENT_TYPE, content, properties);

  PathInfo firstPathInfo = parsedRequest.get(0).getRequests().get(0).getPathInfo();
  assertFirst(firstPathInfo);

  handler.handleBatchPart(parsedRequest.get(0));
}
 
Example #4
Source File: ServiceTicketODataConsumer.java    From C4CODATAAPIDEVGUIDE with Apache License 2.0 6 votes vote down vote up
private Edm readEdm() throws EntityProviderException,
		IllegalStateException, IOException {

	// This is used for both setting the Edm and CSRF Token :)
	if (m_edm != null) {
		return m_edm;
	}

	String serviceUrl = new StringBuilder(getODataServiceUrl())
			.append(SEPARATOR).append(METADATA).toString();

	logger.info("Metadata url => " + serviceUrl);

	final HttpGet get = new HttpGet(serviceUrl);
	get.setHeader(AUTHORIZATION_HEADER, getAuthorizationHeader());
	get.setHeader(CSRF_TOKEN_HEADER, CSRF_TOKEN_FETCH);

	HttpResponse response = getHttpClient().execute(get);

	m_csrfToken = response.getFirstHeader(CSRF_TOKEN_HEADER).getValue();
	logger.info("CSRF token => " + m_csrfToken);

	m_edm = EntityProvider.readMetadata(response.getEntity().getContent(),
			false);
	return m_edm;
}
 
Example #5
Source File: ODataClient.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Reads an entry (an Entity, a property, a complexType, ...).
 * 
 * @param resource_path the resource path to the parent of the requested
 *    EntitySet, as defined in {@link #getResourcePath(URI)}.
 * @param query_parameters Query parameters, as defined in {@link URI}.
 * 
 * @return an ODataEntry for the given {@code resource_path}.
 * 
 * @throws HttpException if the server emits an HTTP error code.
 * @throws IOException if the connection with the remote service fails.
 * @throws EdmException if the EDM does not contain the given entitySetName.
 * @throws EntityProviderException if reading of data (de-serialization)
 *    fails.
 * @throws UriSyntaxException violation of the OData URI construction rules.
 * @throws UriNotMatchingException URI parsing exception.
 * @throws ODataException encapsulate the OData exceptions described above.
 * @throws InterruptedException if running thread has been interrupted.
 */
public ODataEntry readEntry(String resource_path,
   Map<String, String> query_parameters) throws IOException, ODataException, InterruptedException
{
   if (resource_path == null || resource_path.isEmpty ())
      throw new IllegalArgumentException (
         "resource_path must not be null or empty.");
   
   ContentType contentType = ContentType.APPLICATION_ATOM_XML;
   
   String absolutUri = serviceRoot.toString () + '/' + resource_path;
   
   // Builds the query parameters string part of the URL.
   absolutUri = appendQueryParam (absolutUri, query_parameters);
   
   InputStream content = execute (absolutUri, contentType, "GET");
   
   return EntityProvider.readEntry(contentType.type (),
      getEntitySet (resource_path), content,
      EntityProviderReadProperties.init ().build ());
}
 
Example #6
Source File: ODataClient.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Reads a feed (the content of an EntitySet).
 * 
 * @param resource_path the resource path to the parent of the requested
 *    EntitySet, as defined in {@link #getResourcePath(URI)}.
 * @param query_parameters Query parameters, as defined in {@link URI}.
 * 
 * @return an ODataFeed containing the ODataEntries for the given 
 *    {@code resource_path}.
 * 
 * @throws HttpException if the server emits an HTTP error code.
 * @throws IOException if the connection with the remote service fails.
 * @throws EdmException if the EDM does not contain the given entitySetName.
 * @throws EntityProviderException if reading of data (de-serialization)
 *    fails.
 * @throws UriSyntaxException violation of the OData URI construction rules.
 * @throws UriNotMatchingException URI parsing exception.
 * @throws ODataException encapsulate the OData exceptions described above.
 * @throws InterruptedException if running thread has been interrupted.
 */
public ODataFeed readFeed(String resource_path,
   Map<String, String> query_parameters) throws IOException, ODataException, InterruptedException
{
   if (resource_path == null || resource_path.isEmpty ())
      throw new IllegalArgumentException (
         "resource_path must not be null or empty.");
   
   ContentType contentType = ContentType.APPLICATION_ATOM_XML;
   
   String absolutUri = serviceRoot.toString () + '/' + resource_path;
   
   // Builds the query parameters string part of the URL.
   absolutUri = appendQueryParam (absolutUri, query_parameters);
   
   InputStream content = execute (absolutUri, contentType, "GET");
   
   return EntityProvider.readFeed (contentType.type (),
      getEntitySet (resource_path), content,
      EntityProviderReadProperties.init ().build ());
}
 
Example #7
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private ODataEntry parseEntry(final EdmEntitySet entitySet, final InputStream content,
    final String requestContentType, final EntityProviderReadProperties properties) throws ODataBadRequestException {
  ODataContext context = getContext();
  final int timingHandle = context.startRuntimeMeasurement("EntityConsumer", "readEntry");

  ODataEntry entryValues;
  try {
    entryValues = EntityProvider.readEntry(requestContentType, entitySet, content, properties);
  } catch (final EntityProviderException e) {
    throw new ODataBadRequestException(ODataBadRequestException.BODY, e);
  }

  context.stopRuntimeMeasurement(timingHandle);

  return entryValues;
}
 
Example #8
Source File: Processor.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public ODataResponse executeFunctionImport(GetFunctionImportUriInfo uri_info, String content_type)
      throws ODataException
{
   EdmFunctionImport function_import = uri_info.getFunctionImport();
   Map<String, EdmLiteral> params = uri_info.getFunctionImportParameters();
   EntityProviderWriteProperties entry_props =
         EntityProviderWriteProperties.serviceRoot(makeLink()).build();

   AbstractOperation op = Model.getServiceOperation(function_import.getName());

   fr.gael.dhus.database.object.User current_user =
         ApplicationContextProvider.getBean(SecurityService.class).getCurrentUser();
   if (!op.canExecute(current_user))
   {
      throw new NotAllowedException();
   }

   Object res = op.execute(params);

   return EntityProvider.writeFunctionImport(content_type, function_import, res, entry_props);
}
 
Example #9
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 #10
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse readEntitySimplePropertyValue(final GetSimplePropertyUriInfo uriInfo, final String contentType)
    throws ODataException {
  Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

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

  final List<EdmProperty> propertyPath = uriInfo.getPropertyPath();
  final EdmProperty property = propertyPath.get(propertyPath.size() - 1);
  final Object value = property.getMapping() == null || property.getMapping().getMediaResourceMimeTypeKey() == null ?
      getPropertyValue(data, propertyPath) : getSimpleTypeValueMap(data, propertyPath);

  return ODataResponse.fromResponse(EntityProvider.writePropertyValue(property, value)).eTag(
      constructETag(uriInfo.getTargetEntitySet(), data)).build();
}
 
Example #11
Source File: ClientBatchTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleBatchWithAbsoluteUri() throws Exception {
  final String batchRequestBody = StringHelper.inputStreamToStringCRLFLineBreaks(
      EntityProvider.writeBatchRequest(
          Collections.<BatchPart> singletonList(
              BatchQueryPart
                  .method(ODataHttpMethod.GET.name())
                  .uri(getEndpoint().getPath() + "Employees('2')/EmployeeName/$value")
                  .build()),
          BOUNDARY));
  final HttpResponse batchResponse = execute(batchRequestBody);
  final List<BatchSingleResponse> responses = EntityProvider.parseBatchResponse(
      batchResponse.getEntity().getContent(),
      batchResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
  assertEquals(1, responses.size());
  final BatchSingleResponse response = responses.get(0);
  assertEquals(Integer.toString(HttpStatusCodes.OK.getStatusCode()), response.getStatusCode());
  assertEquals(HttpStatusCodes.OK.getInfo(), response.getStatusInfo());
  assertEquals(EMPLOYEE_2_NAME, response.getBody());
  assertEquals(HttpContentType.TEXT_PLAIN_UTF8, response.getHeader(HttpHeaders.CONTENT_TYPE));
  assertNotNull(response.getHeader(HttpHeaders.CONTENT_LENGTH));
}
 
Example #12
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse updateEntityMedia(final PutMergePatchUriInfo uriInfo, final InputStream content,
    final String requestContentType, final String contentType) throws ODataException {
  final Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

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

  ODataContext context = getContext();
  final int timingHandle = context.startRuntimeMeasurement("EntityProvider", "readBinary");

  final byte[] value = EntityProvider.readBinary(content);

  context.stopRuntimeMeasurement(timingHandle);

  final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
  dataSource.writeBinaryData(entitySet, data, new BinaryData(value, requestContentType));

  return ODataResponse.newBuilder().eTag(constructETag(entitySet, data)).build();
}
 
Example #13
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 #14
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
private <T> ODataResponse writeEntry(final EdmEntitySet entitySet, final ExpandSelectTreeNode expandSelectTree,
    final T data, final String contentType) throws ODataException, EntityProviderException {
  final EdmEntityType entityType = entitySet.getEntityType();
  final Map<String, Object> values = getStructuralTypeValueMap(data, entityType);

  ODataContext context = getContext();
  EntityProviderWriteProperties writeProperties = EntityProviderWriteProperties
      .serviceRoot(context.getPathInfo().getServiceRoot())
      .expandSelectTree(expandSelectTree)
      .callbacks(getCallbacks(data, entityType))
      .build();

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

  final ODataResponse response = EntityProvider.writeEntry(contentType, entitySet, values, writeProperties);

  context.stopRuntimeMeasurement(timingHandle);

  return response;
}
 
Example #15
Source File: ClientBatchTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void errorBatch() throws Exception {
  List<BatchPart> batch = new ArrayList<BatchPart>();
  BatchPart request = BatchQueryPart.method(ODataHttpMethod.GET.name())
      .uri("nonsense")
      .build();
  batch.add(request);

  InputStream body = EntityProvider.writeBatchRequest(batch, BOUNDARY);
  String bodyAsString = StringHelper.inputStreamToStringCRLFLineBreaks(body);
  checkMimeHeaders(bodyAsString);
  checkBoundaryDelimiters(bodyAsString);

  assertTrue(bodyAsString.contains("GET nonsense HTTP/1.1"));
  HttpResponse batchResponse = execute(bodyAsString);
  InputStream responseBody = batchResponse.getEntity().getContent();
  String contentType = batchResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
  List<BatchSingleResponse> responses = EntityProvider.parseBatchResponse(responseBody, contentType);
  for (BatchSingleResponse response : responses) {
    assertEquals("404", response.getStatusCode());
    assertEquals("Not Found", response.getStatusInfo());
  }
}
 
Example #16
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 #17
Source File: ExpandSelectProducerWithBuilderTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void selectOnlyProperties() throws Exception {
  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> selectedProperties = new ArrayList<String>(roomData.keySet());

  ExpandSelectTreeNode expandSelectTree =
      ExpandSelectTreeNode.entitySet(roomsSet).selectedProperties(selectedProperties).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);
  assertXpathNotExists("/a:entry/a:link[@type]", xml);
}
 
Example #18
Source File: ExpandSelectProducerWithBuilderTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void selectOnlyLinks() throws Exception {
  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> selectedNavigationProperties = new ArrayList<String>();
  selectedNavigationProperties.add("nr_Building");
  selectedNavigationProperties.add("nr_Employees");

  ExpandSelectTreeNode expandSelectTree =
      ExpandSelectTreeNode.entitySet(roomsSet).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());
  assertXpathNotExists("/a:entry/a:content/m:properties", xml);
  assertXpathExists("/a:entry/a:link[@type]", xml);
}
 
Example #19
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 #20
Source File: ExpandSelectProducerWithBuilderTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void expandBuilding() throws Exception {
  EdmEntitySet roomsSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Rooms");
  List<String> expandedNavigationProperties = new ArrayList<String>();
  expandedNavigationProperties.add("nr_Building");

  ExpandSelectTreeNode expandSelectTree =
      ExpandSelectTreeNode.entitySet(roomsSet).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", xml);
  assertXpathExists("/a:entry/a:link[@type]/m:inline", xml);
}
 
Example #21
Source File: MapProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse readEntity(final GetEntityUriInfo uriInfo, final String contentType) throws ODataException {
  final EntityProviderWriteProperties properties =
      EntityProviderWriteProperties.serviceRoot(getContext().getPathInfo().getServiceRoot()).build();

  // query
  final String mappedKeyName =
      (String) uriInfo.getTargetEntitySet().getEntityType().getKeyProperties().get(0).getMapping().getObject();
  final String keyValue = uriInfo.getKeyPredicates().get(0).getLiteral();
  final int index = indexOf(mappedKeyName, keyValue);
  if ((index < 0) || (index > records.size())) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY.addContent(keyValue));
  }
  final HashMap<String, String> record = records.get(index);

  final HashMap<String, Object> data = new HashMap<String, Object>();
  for (final String pName : uriInfo.getTargetEntitySet().getEntityType().getPropertyNames()) {
    final EdmProperty property = (EdmProperty) uriInfo.getTargetEntitySet().getEntityType().getProperty(pName);
    final String mappedPropertyName = (String) property.getMapping().getObject();
    data.put(pName, record.get(mappedPropertyName));
  }

  final ODataResponse response =
      EntityProvider.writeEntry(contentType, uriInfo.getTargetEntitySet(), data, properties);
  return response;
}
 
Example #22
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse updateEntityMedia(final PutMergePatchUriInfo uriInfo, final InputStream content,
    final String requestContentType, final String contentType) throws ODataException {
  final Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

  final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
  if (!appliesFilter(entitySet, data, uriInfo.getFilter())) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
  }

  ODataContext context = getContext();
  final int timingHandle = context.startRuntimeMeasurement("EntityProvider", "readBinary");

  final byte[] value = EntityProvider.readBinary(content);

  context.stopRuntimeMeasurement(timingHandle);

  dataSource.writeBinaryData(entitySet, data, new BinaryData(value, requestContentType));

  return ODataResponse.newBuilder().eTag(constructETag(entitySet, data)).build();
}
 
Example #23
Source File: XmlFeedConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void roomsFeedWithEtagEntries() throws Exception {
  InputStream stream = getFileAsStream("feed_rooms_small.xml");
  assertNotNull(stream);

  ODataFeed feed =
      EntityProvider.readFeed("application/atom+xml", MockFacade.getMockEdm().getDefaultEntityContainer()
          .getEntitySet(
              "Rooms"), stream, DEFAULT_PROPERTIES);
  assertNotNull(feed);

  FeedMetadata feedMetadata = feed.getFeedMetadata();
  assertNotNull(feedMetadata);
  assertNotNull(feedMetadata.getNextLink());

  List<ODataEntry> entries = feed.getEntries();
  assertEquals(3, entries.size());
  ODataEntry singleRoom = entries.get(0);
  EntryMetadata roomMetadata = singleRoom.getMetadata();
  assertNotNull(roomMetadata);

  assertEquals("W/\"1\"", roomMetadata.getEtag());
}
 
Example #24
Source File: XmlFeedConsumerTest.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("RoomsToEmployeesWithInlineTeams.xml");
  assertNotNull(stream);
  FeedCallback callback = new FeedCallback();

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

  ODataFeed feed =
      EntityProvider.readFeed("application/atom+xml", MockFacade.getMockEdm().getDefaultEntityContainer()
          .getEntitySet(
              "Employees"), 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 #25
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse readEntitySimplePropertyValue(final GetSimplePropertyUriInfo uriInfo, final String contentType)
    throws ODataException {
  Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

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

  final List<EdmProperty> propertyPath = uriInfo.getPropertyPath();
  final EdmProperty property = propertyPath.get(propertyPath.size() - 1);
  final Object value = property.getMapping() == null || property.getMapping().getMediaResourceMimeTypeKey() == null ?
      getPropertyValue(data, propertyPath) : getSimpleTypeValueMap(data, propertyPath);

  return ODataResponse.fromResponse(EntityProvider.writePropertyValue(property, value)).eTag(
      constructETag(uriInfo.getTargetEntitySet(), data)).build();
}
 
Example #26
Source File: ServiceDocumentConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAtomServiceDocument() throws EntityProviderException {
  InputStream in = ClassLoader.class.getResourceAsStream("/svcExample.xml");
  ServiceDocument serviceDocument = EntityProvider.readServiceDocument(in, "application/atom+xml");
  assertNotNull(serviceDocument);
  AtomInfo atomInfo = serviceDocument.getAtomInfo();
  assertNotNull(atomInfo);
  for (Workspace workspace : atomInfo.getWorkspaces()) {
    assertEquals(10, workspace.getCollections().size());
    for (Collection collection : workspace.getCollections()) {
      assertNotNull(collection.getExtesionElements().get(0));
      assertEquals("member-title", collection.getExtesionElements().get(0).getName());
      assertEquals("foo", collection.getExtesionElements().get(0).getPrefix());
    }
  }
  for (ExtensionElement extElement : atomInfo.getExtesionElements()) {
    assertEquals(2, extElement.getAttributes().size());
  }
}
 
Example #27
Source File: ServiceDocumentConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonServiceDocument() throws EntityProviderException {
  InputStream in = ClassLoader.class.getResourceAsStream("/svcDocJson.json");
  ServiceDocument serviceDoc = EntityProvider.readServiceDocument(in, "application/json");
  assertNotNull(serviceDoc);
  assertNull(serviceDoc.getAtomInfo());
  List<EdmEntitySetInfo> entitySetsInfo = serviceDoc.getEntitySetsInfo();
  assertEquals(7, entitySetsInfo.size());
  for (EdmEntitySetInfo entitySetInfo : entitySetsInfo) {
    if (!entitySetInfo.isDefaultEntityContainer()) {
      if ("Container2".equals(entitySetInfo.getEntityContainerName())) {
        assertEquals("Photos", entitySetInfo.getEntitySetName());
      } else if ("Container.Nr1".equals(entitySetInfo.getEntityContainerName())) {
        assertEquals("Employees", entitySetInfo.getEntitySetName());
      }
    }
  }
}
 
Example #28
Source File: ServiceDocumentConsumerTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompareJsonWithAtom() throws EntityProviderException {
  InputStream inputJson = ClassLoader.class.getResourceAsStream("/svcDocJson.json");
  ServiceDocument serviceDocJson = EntityProvider.readServiceDocument(inputJson, "application/json");
  assertNotNull(serviceDocJson);
  List<EdmEntitySetInfo> entitySetsInfoJson = serviceDocJson.getEntitySetsInfo();

  InputStream inputAtom = ClassLoader.class.getResourceAsStream("/serviceDocument.xml");
  ServiceDocument serviceDocAtom = EntityProvider.readServiceDocument(inputAtom, "application/atom+xml");
  assertNotNull(serviceDocAtom);
  List<EdmEntitySetInfo> entitySetsInfoAtom = serviceDocAtom.getEntitySetsInfo();

  assertEquals(entitySetsInfoJson.size(), entitySetsInfoAtom.size());
  for (int i = 0; i < entitySetsInfoJson.size(); i++) {
    assertEquals(entitySetsInfoJson.get(i).getEntitySetName(), entitySetsInfoAtom.get(i).getEntitySetName());
    assertEquals(entitySetsInfoJson.get(i).getEntitySetUri(), entitySetsInfoAtom.get(i).getEntitySetUri());
  }
}
 
Example #29
Source File: BatchResponseParserTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void parseWithUnixLineEndingsInBody() throws Exception {
  String body =
      "This is the body we need to parse. The line spaces in the body " + LF + LF + LF + "are " + LF + LF
          + "part of the body and must not be ignored or filtered.";
  String responseString = "--batch_123" + CRLF
      + "Content-Type: application/http" + CRLF
      + "Content-Length: 234" + CRLF
      + "content-transfer-encoding: binary" + CRLF
      + CRLF
      + "HTTP/1.1 500 Internal Server Error" + CRLF
      + "Content-Type: application/xml;charset=utf-8" + CRLF
      + "Content-Length: 125" + CRLF
      + CRLF
      + body
      + CRLF
      + "--batch_123--";
  InputStream stream = new ByteArrayInputStream(responseString.getBytes());
  BatchSingleResponse response =
      EntityProvider.parseBatchResponse(stream, "multipart/mixed;boundary=batch_123").get(0);

  assertEquals(body, response.getBody());
}
 
Example #30
Source File: ListsProcessor.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Override
public ODataResponse readEntityMedia(final GetMediaResourceUriInfo uriInfo, final String contentType)
    throws ODataException {
  final Object data = retrieveData(
      uriInfo.getStartEntitySet(),
      uriInfo.getKeyPredicates(),
      uriInfo.getFunctionImport(),
      mapFunctionParameters(uriInfo.getFunctionImportParameters()),
      uriInfo.getNavigationSegments());

  final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
  if (!appliesFilter(entitySet, data, uriInfo.getFilter())) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
  }

  final BinaryData binaryData = dataSource.readBinaryData(entitySet, data);
  if (binaryData == null) {
    throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
  }

  final String mimeType = binaryData.getMimeType() == null ?
      HttpContentType.APPLICATION_OCTET_STREAM : binaryData.getMimeType();

  return ODataResponse.fromResponse(EntityProvider.writeBinary(mimeType, binaryData.getData())).eTag(
      constructETag(entitySet, data)).build();
}