org.apache.olingo.commons.api.format.ContentType Java Examples

The following examples show how to use org.apache.olingo.commons.api.format.ContentType. 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: InOperatorITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void querySimple() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$filter=PropertyString%20in%20("
      + "%27Second%20Resource%20-%20negative%20values%27,%27xyz%27)");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"value\":[{\"PropertyInt16\":-32768,"
      + "\"PropertyString\":\"Second Resource - negative values\","
      + "\"PropertyBoolean\":false,\"PropertyByte\":0,\"PropertySByte\":-128,"
      + "\"PropertyInt32\":-2147483648,\"PropertyInt64\":-9223372036854775808,"
      + "\"PropertySingle\":-1.79E8,\"PropertyDouble\":-179000.0,\"PropertyDecimal\":-34,"
      + "\"PropertyBinary\":\"ASNFZ4mrze8=\",\"PropertyDate\":\"2015-11-05\","
      + "\"PropertyDateTimeOffset\":\"2005-12-03T07:17:08Z\",\"PropertyDuration\":\"PT9S\","
      + "\"PropertyGuid\":\"76543201-23ab-cdef-0123-456789dddfff\","
      + "\"PropertyTimeOfDay\":\"23:49:14\"}]"));
}
 
Example #2
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void validFormatWithAcceptCharsetHeader() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf-8;q=0.1");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(3, contentType.getParameters().size());
  assertEquals("0.1", contentType.getParameter("q"));
  assertEquals("minimal", contentType.getParameter("odata.metadata"));
  assertEquals("utf-8", contentType.getParameter("charset"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example #3
Source File: ContentNegotiator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private static List<ContentType> getDefaultSupportedContentTypes(final RepresentationType type) {
  switch (type) {
  case METADATA:
    return Collections.unmodifiableList(Arrays.asList(ContentType.APPLICATION_XML,
        ContentType.APPLICATION_JSON));
  case MEDIA:
  case BINARY:
    return Collections.singletonList(ContentType.APPLICATION_OCTET_STREAM);
  case VALUE:
  case COUNT:
    return Collections.singletonList(ContentType.TEXT_PLAIN);
  case BATCH:
    return Collections.singletonList(ContentType.MULTIPART_MIXED);
  default:
    return DEFAULT_SUPPORTED_CONTENT_TYPES;
  }
}
 
Example #4
Source File: SelectOnComplexPropertiesITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void queryESKeyColPropertyComp1() throws Exception {
  URL url = new URL(SERVICE_URI + "ESKeyNav(1)/CollPropertyComp"
      + "?$select=PropertyComp/PropertyString");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"value\":[{\"PropertyComp\":"
          + "{\"PropertyString\":\"First Resource - positive values\"}},"
          + "{\"PropertyComp\":{\"PropertyString\":\"First Resource - positive values\"}},"
          + "{\"PropertyComp\":{\"PropertyString\":\"First Resource - positive values\"}}]"));
}
 
Example #5
Source File: EntityTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void withInlineEntitySet(final ContentType contentType) throws Exception {
  final InputStream input = getClass().getResourceAsStream(
      "Accounts_101_expand_MyPaymentInstruments." + getSuffix(contentType));
  final ClientEntity entity = client.getBinder().getODataEntity(
      client.getDeserializer(contentType).toEntity(input));
  assertNotNull(entity);

  final ClientLink instruments = entity.getNavigationLink("MyPaymentInstruments");
  assertNotNull(instruments);
  assertEquals(ClientLinkType.ENTITY_SET_NAVIGATION, instruments.getType());

  final ClientInlineEntitySet inline = instruments.asInlineEntitySet();
  assertNotNull(inline);
  assertEquals(3, inline.getEntitySet().getEntities().size());

  // count shouldn't be serialized
  inline.getEntitySet().setCount(3);
  // operations won't get serialized
  entity.getOperations().clear();
  final ClientEntity written = client.getBinder().getODataEntity(
      new ResWrap<Entity>((URI) null, null, client.getBinder().getEntity(entity)));
  assertEquals(entity, written);
  input.close();
}
 
Example #6
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void updateMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
    ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException {
  
  final UriResource firstResoucePart = uriInfo.getUriResourceParts().get(0);
  if (firstResoucePart instanceof UriResourceEntitySet) {
    final EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
    final UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) firstResoucePart;

    final Entity entity = storage.readEntityData(edmEntitySet, uriResourceEntitySet.getKeyPredicates());
    if (entity == null) {
      throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(),
          Locale.ENGLISH);
    }
    
    final byte[] mediaContent = odata.createFixedFormatDeserializer().binary(request.getBody());
    storage.updateMedia(entity, requestFormat.toContentTypeString(), mediaContent);
    
    response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #7
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleValuesInAcceptHeader1() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json,"
      + "application/json;q=0.1,application/json;q=0.8");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertNotNull(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  ContentType contentType = ContentType.parse(connection.getHeaderField(HttpHeader.CONTENT_TYPE));
  assertEquals("application", contentType.getType());
  assertEquals("json", contentType.getSubtype());
  assertEquals(1, contentType.getParameters().size());
  assertEquals("minimal", contentType.getParameter("odata.metadata"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example #8
Source File: EntityUpdateTestITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void onContained(final ContentType contentType) {
  final String newName = UUID.randomUUID().toString();
  final ClientEntity changes = getClient().getObjectFactory().newEntity(
      new FullQualifiedName("Microsoft.Test.OData.Services.ODataWCFService.PaymentInstrument"));
  changes.getProperties().add(getClient().getObjectFactory().newPrimitiveProperty("FriendlyName",
      getClient().getObjectFactory().newPrimitiveValueBuilder().buildString(newName)));

  final URI uri = getClient().newURIBuilder(testStaticServiceRootURL).
      appendEntitySetSegment("Accounts").appendKeySegment(101).
      appendNavigationSegment("MyPaymentInstruments").appendKeySegment(101901).build();
  final ODataEntityUpdateRequest<ClientEntity> req = getClient().getCUDRequestFactory().
      getEntityUpdateRequest(uri, UpdateType.PATCH, changes);
  req.setFormat(contentType);

  final ODataEntityUpdateResponse<ClientEntity> res = req.execute();
  assertEquals(204, res.getStatusCode());

  final ClientEntity actual = getClient().getRetrieveRequestFactory().getEntityRequest(uri).execute().getBody();
  assertNotNull(actual);
  assertEquals(newName, actual.getProperty("FriendlyName").getPrimitiveValue().toString());
}
 
Example #9
Source File: InOperatorITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void queryInOperatorWithFunction() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$filter=PropertyString%20in%20olingo.odata.test1.UFCRTCollString()");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"value\":[{\"PropertyInt16\":10,"
      + "\"PropertyString\":\"[email protected]\","
      + "\"PropertyBoolean\":false,\"PropertyByte\":0,\"PropertySByte\":0,"
      + "\"PropertyInt32\":0,\"PropertyInt64\":0,\"PropertySingle\":0.0,"
      + "\"PropertyDouble\":0.0,\"PropertyDecimal\":0,\"PropertyBinary\":\"\","
      + "\"PropertyDate\":\"1970-01-01\","
      + "\"PropertyDateTimeOffset\":\"2005-12-03T00:00:00Z\","
      + "\"PropertyDuration\":\"PT0S\","
      + "\"PropertyGuid\":\"76543201-23ab-cdef-0123-456789cccddd\","
      + "\"PropertyTimeOfDay\":\"00:01:01\"}]"));
}
 
Example #10
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
                          ContentType requestFormat, ContentType responseFormat)
						throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity set which belongs to the requested entity 
	List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
	// Note: only in our example we can assume that the first segment is the EntitySet
	UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); 
	EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. update the data in backend
	// 2.1. retrieve the payload from the PUT request for the entity to be updated 
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the modification in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	// Note that this updateEntity()-method is invoked for both PUT or PATCH operations
	HttpMethod httpMethod = request.getMethod();
	storage.updateEntityData(edmEntitySet, keyPredicates, requestEntity, httpMethod);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #11
Source File: PropertyTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void collection(final ContentType contentType) throws ODataDeserializerException, ODataSerializerException {
  final InputStream input = getClass().getResourceAsStream("Products_5_CoverColors." + getSuffix(contentType));
  final ClientProperty property = client.getReader().readProperty(input, contentType);
  assertNotNull(property);
  assertTrue(property.hasCollectionValue());
  assertEquals(3, property.getCollectionValue().size());

  final ClientProperty written = client.getReader().readProperty(
          client.getWriter().writeProperty(property, contentType), contentType);
  // This is needed because type information gets lost with JSON serialization
  if(contentType.isCompatible(ContentType.APPLICATION_XML)) {
    final ClientCollectionValue<ClientValue> typedValue = client.getObjectFactory().
            newCollectionValue(property.getCollectionValue().getTypeName());
    for (final Iterator<ClientValue> itor = written.getCollectionValue().iterator(); itor.hasNext();) {
      final ClientValue value = itor.next();
      typedValue.add(value);
    }
    final ClientProperty comparable = client.getObjectFactory().
            newCollectionProperty(property.getName(), typedValue);

    assertEquals(property, comparable);
  }
}
 
Example #12
Source File: ConformanceITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * 12. MAY support odata.metadata=minimal in a JSON response (see [OData-JSON]).
 */
@Test
public void supportMetadataMinimal() {
  assumeTrue("format should be json", isJson());
  ODataClient client = getClient();
  final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_URI)
          .appendEntitySetSegment(ES_TWO_PRIM)
          .appendKeySegment(32767)
          .expand("NavPropertyETAllPrimOne");

  final ODataEntityRequest<ClientEntity> req =
      client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
  req.setFormat(ContentType.JSON);

  assertEquals("application/json;odata.metadata=minimal", req.getHeader("Accept"));
  assertEquals("application/json;odata.metadata=minimal", req.getAccept());

  final ODataRetrieveResponse<ClientEntity> res = req.execute();
  assertTrue(res.getContentType().startsWith("application/json; odata.metadata=minimal"));

  assertNotNull(res.getBody());
}
 
Example #13
Source File: KeyAsSegmentTestITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void read(final ContentType contentType) {
  final URIBuilder uriBuilder = client.newURIBuilder(testKeyAsSegmentServiceRootURL).
      appendEntitySetSegment("Accounts").appendKeySegment(101);

  final ODataEntityRequest<ClientEntity> req =
      client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
  req.setFormat(contentType);

  final ODataRetrieveResponse<ClientEntity> res = req.execute();
  final ClientEntity entity = res.getBody();
  assertNotNull(entity);

  // In JSON with minimal metadata, links are not provided
  if (contentType.equals(ContentType.APPLICATION_ATOM_XML) || contentType.equals(ContentType.JSON_FULL_METADATA)) {
    assertFalse(entity.getEditLink().toASCIIString().contains("("));
    assertFalse(entity.getEditLink().toASCIIString().contains(")"));
  }
}
 
Example #14
Source File: ODataWriterImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream writeLink(final ClientLink link, final ContentType contentType) throws ODataSerializerException {
  final ByteArrayOutputStream output = new ByteArrayOutputStream();
  OutputStreamWriter writer;
  try {
    writer = new OutputStreamWriter(output, Constants.UTF8);
  } catch (final UnsupportedEncodingException e) {
    writer = null;
  }
  try {
    client.getSerializer(contentType).write(writer, client.getBinder().getLink(link));

    return new ByteArrayInputStream(output.toByteArray());
  } finally {
    IOUtils.closeQuietly(writer);
  }
}
 
Example #15
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void dispatchPrimitivePropertyValue() throws Exception {
  final String uri = "ESAllPrim(0)/PropertyString/$value";
  final PrimitiveValueProcessor processor = mock(PrimitiveValueProcessor.class);

  dispatch(HttpMethod.GET, uri, processor);
  verify(processor).readPrimitiveValue(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class),
      any(ContentType.class));

  dispatch(HttpMethod.PUT, uri, null, HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString(),
      processor);
  verify(processor).updatePrimitiveValue(
      any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class), any(ContentType.class),
      any(ContentType.class));

  dispatch(HttpMethod.DELETE, uri, processor);
  verify(processor).deletePrimitiveValue(any(ODataRequest.class), any(ODataResponse.class), any(UriInfo.class));

  dispatchMethodNotAllowed(HttpMethod.POST, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.PATCH, uri, processor);
  dispatchMethodNotAllowed(HttpMethod.HEAD, uri, processor);
}
 
Example #16
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void readMediaEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
    throws ODataApplicationException, ODataLibraryException {
  
  final UriResource firstResoucePart = uriInfo.getUriResourceParts().get(0);
  if(firstResoucePart instanceof UriResourceEntitySet) {
    final EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
    final UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) firstResoucePart;
    
    final Entity entity = storage.readEntityData(edmEntitySet, uriResourceEntitySet.getKeyPredicates());
    if(entity == null) {
      throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), 
          Locale.ENGLISH);
    }

    final byte[] mediaContent = storage.readMedia(entity);
    final InputStream responseContent = odata.createFixedFormatSerializer().binary(mediaContent);
    
    response.setStatusCode(HttpStatusCode.OK.getStatusCode());
    response.setContent(responseContent);
    response.setHeader(HttpHeader.CONTENT_TYPE, entity.getMediaContentType());
  } else {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.BAD_REQUEST.getStatusCode(), 
        Locale.ENGLISH);
  }
}
 
Example #17
Source File: TechnicalEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public void countEntityCollection(final ODataRequest request, final ODataResponse response,
    final UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException {
  validateOptions(uriInfo.asUriInfoResource());
  getEdmEntitySet(uriInfo); // including checks
  final EntityCollection entitySetInitial = readEntityCollection(uriInfo);
  EntityCollection entitySet = new EntityCollection();
  entitySet.getEntities().addAll(entitySetInitial.getEntities());
  FilterHandler.applyFilterSystemQuery(uriInfo.getFilterOption(), entitySet, uriInfo, serviceMetadata.getEdm());
  SearchHandler.applySearchSystemQueryOption(uriInfo.getSearchOption(), entitySet);
  int count =  entitySet.getEntities().size();
  for (SystemQueryOption systemQueryOption : uriInfo.getSystemQueryOptions()) {
    if (systemQueryOption.getName().contains(DELTATOKEN)) {
      count = count + getDeltaCount(uriInfo);
      break;
    }
  }
  response.setContent(odata.createFixedFormatSerializer().count(count));
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.TEXT_PLAIN.toContentTypeString());
}
 
Example #18
Source File: BasicBoundActionsITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void boundActionReturningComplexDerivedTypeWithComplexTypeSegInAction() throws Exception {
  Map<String, Object> segmentValues = new HashMap<String, Object>();
  segmentValues.put("PropertyInt16", 1);
  segmentValues.put("PropertyString", "1");
  URIBuilder builder = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment("ESTwoKeyNav").
      appendKeySegment(segmentValues).appendPropertySegment("PropertyCompNav").
      appendDerivedEntityTypeSegment("olingo.odata.test1.CTTwoBasePrimCompNav").
      appendActionCallSegment("olingo.odata.test1."
          + "BAETTwoKeyNavCTBasePrimCompNavCTTwoBasePrimCompNavRTCTTwoBasePrimCompNav");
  
  Map<String, ClientValue> parameters = new HashMap<String, ClientValue>();
  
  final ODataInvokeRequest<ClientEntity> req =
      client.getInvokeRequestFactory().getActionInvokeRequest(builder.build(), ClientEntity.class, parameters);
  req.setFormat(ContentType.JSON_FULL_METADATA);
  req.setContentType(ContentType.APPLICATION_JSON.toContentTypeString() + ";odata.metadata=full");
  ClientEntity entity = req.execute().getBody();
  assertNotNull(entity);
  assertEquals(entity.getProperties().size(), 2);
  assertEquals(entity.getTypeName().getFullQualifiedNameAsString(), 
      "olingo.odata.test1.CTTwoBasePrimCompNav");
}
 
Example #19
Source File: ClientEntitySetIteratorTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetEntitySetIteratorWithInnerNav() throws IOException, URISyntaxException {
    String str = "{\"@odata.context\":\"$metadata#Cubes(Name)\","
        + "\"value\":[{\"@odata.etag\":\"W/\\\"c24af675e00a3f95ef63f223fb9c2cc8d6455459\\\"\","
        + "\"Name\":\"}Capabilities\","
        + "\"NavProp\":{\"PropertyInt\":1}}]}";
    
    InputStream stream = new ByteArrayInputStream(str.getBytes());
    ODataClient oDataClient = ODataClientFactory.getClient();
    ClientEntitySetIterator<ClientEntitySet, ClientEntity> entitySetIterator = 
        new ClientEntitySetIterator<ClientEntitySet, ClientEntity>(
        oDataClient, stream, ContentType.parse(ContentType.JSON.toString()));

    ArrayList<ClientEntity> entities = new ArrayList<ClientEntity>();
    while (entitySetIterator.hasNext()) {
        ClientEntity next = entitySetIterator.next();
        entities.add(next);
    }

    Assert.assertEquals(1, entities.size());
    Assert.assertNotNull(entities.get(0).getProperty("NavProp"));
    Assert.assertEquals("}Capabilities", entities.get(0).getProperty("Name").getPrimitiveValue().toString());
}
 
Example #20
Source File: SelectOnComplexPropertiesITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void queryESKeyPropertyCompCompNav() throws Exception {
  URL url = new URL(SERVICE_URI + "ESKeyNav(1)/PropertyCompCompNav"
      + "?$select=PropertyCompNav/PropertyInt16");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"PropertyCompNav\":{\"PropertyInt16\":1}"));
  connection.disconnect();
}
 
Example #21
Source File: MetadataValidationTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void checkInValidV4XMLMetadataWithTwoSchemas() {
  
  boolean checkException = false;
  try {
      InputStream stream = new ByteArrayInputStream(invalidV4MetadataWithV2AndV4Schemas.getBytes("UTF-8"));
      final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML).
          toMetadata(stream);
      assertNotNull(metadata);
      ODataMetadataValidation metadataValidator = client.metadataValidation();
      assertEquals(false,metadataValidator.isV4Metadata(metadata));
      
    } catch (Exception e) {
    	checkException = true;
    	 
    } 
    assertEquals(false,checkException);
}
 
Example #22
Source File: SingletonTestITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void readWithAnnotations(final ODataClient client, final ContentType contentType)
    throws EdmPrimitiveTypeException {

  final URIBuilder builder = client.newURIBuilder(testStaticServiceRootURL).appendSingletonSegment("Boss");
  final ODataEntityRequest<ClientSingleton> singleton =
      client.getRetrieveRequestFactory().getSingletonRequest(builder.build());
  singleton.setFormat(contentType);
  singleton.setPrefer(client.newPreferences().includeAnnotations("*"));
  final ClientSingleton boss = singleton.execute().getBody();
  assertNotNull(boss);

  assertFalse(boss.getAnnotations().isEmpty());
  final ClientAnnotation isBoss = boss.getAnnotations().get(0);
  assertTrue(isBoss.getPrimitiveValue().toCastValue(Boolean.class));
}
 
Example #23
Source File: AtomTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void issue3OLINGO1073_WithAnnotations() throws Exception {
  InputStream inputStream = getClass().getResourceAsStream(
      "olingo1073_2" + "." + getSuffix(ContentType.APPLICATION_ATOM_XML));
  ClientEntity entity = client.getReader().readEntity(inputStream, ContentType.APPLICATION_ATOM_XML);
  assertNotNull(entity);
  assertEquals(7, entity.getProperties().size());
  assertEquals(1, entity.getAnnotations().size());
  assertEquals("com.contoso.PersonalInfo.PhoneNumbers", entity.getAnnotations().get(0).getTerm());
  assertEquals(2, entity.getAnnotations().get(0).getCollectionValue().size());
  
  assertEquals("com.contoso.display.style", entity.getProperty("LastName").
      getAnnotations().get(0).getTerm());
  assertEquals(2, entity.getProperty("LastName").
      getAnnotations().get(0).getComplexValue().asComplex().asJavaMap().size());
  
  assertEquals(3, entity.getProperty("AddressInfo").getCollectionValue().asCollection().size());
  assertEquals("Collection(Microsoft.OData.SampleService.Models.TripPin.Location)", 
      entity.getProperty("AddressInfo").getCollectionValue().asCollection().getTypeName());
  assertEquals(true, entity.getProperty("AddressInfo").getCollectionValue().isCollection());
  ClientCollectionValue<ClientValue> collectionValue = entity.getProperty("AddressInfo").
      getCollectionValue().asCollection();
  int i = 0;
  for (ClientValue _value : collectionValue) {
    if (i == 0) {
      assertEquals("#Microsoft.OData.SampleService.Models.TripPin.Location", _value.getTypeName());
      assertEquals(2, _value.asComplex().asJavaMap().size());
      assertEquals("Microsoft.OData.SampleService.Models.TripPin.City", 
          _value.asComplex().get("City").getComplexValue().getTypeName());
    } else if (i == 1) {
      assertEquals("#Microsoft.OData.SampleService.Models.TripPin.EventLocation", _value.getTypeName());
      assertEquals(3, _value.asComplex().asJavaMap().size());
    } else if (i == 2) {
      assertEquals("#Microsoft.OData.SampleService.Models.TripPin.AirportLocation", _value.getTypeName());
      assertEquals(3, _value.asComplex().asJavaMap().size());
    }
    i++;
  }
}
 
Example #24
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void unsupportedRequestContentType() throws Exception {
  EntityProcessor processor = mock(EntityProcessor.class);
  ErrorProcessor errorProcessor = mock(ErrorProcessor.class);
  dispatch(HttpMethod.POST, "ESAllPrim", null, HttpHeader.CONTENT_TYPE, "some/unsupported", errorProcessor);
  verifyZeroInteractions(processor);
  verify(errorProcessor).processError(any(ODataRequest.class), any(ODataResponse.class),
      any(ODataServerError.class),
      any(ContentType.class));
}
 
Example #25
Source File: PropertyTestITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void geospatial(final ODataClient client, final ContentType contentType) {
  final URIBuilder uriBuilder = client.newURIBuilder(testStaticServiceRootURL).
      appendEntitySetSegment("People").appendKeySegment(5).appendPropertySegment("Home");
  final ODataPropertyRequest<ClientProperty> req = client.getRetrieveRequestFactory().
      getPropertyRequest(uriBuilder.build());
  req.setFormat(contentType);

  final ClientProperty prop = req.execute().getBody();
  assertNotNull(prop);
  // cast to workaround JDK 6 bug, fixed in JDK 7
  assertEquals("Edm.GeographyPoint", ((ClientValuable) prop).getValue().getTypeName());
}
 
Example #26
Source File: ODataJsonDeserializerEntityTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void mappingTest() throws Exception {
  EdmEntityType entityType = mock(EdmEntityType.class);
  when(entityType.getFullQualifiedName()).thenReturn(new FullQualifiedName("namespace", "name"));
  List<String> propertyNames = new ArrayList<String>();
  propertyNames.add("PropertyDate");
  propertyNames.add("PropertyDateTimeOffset");
  when(entityType.getPropertyNames()).thenReturn(propertyNames);
  CsdlMapping mapping = new CsdlMapping().setMappedJavaClass(Date.class);

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

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

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

  assertNotNull(entity.getProperty("PropertyDate").getValue());
  assertEquals(java.sql.Date.class, entity.getProperty("PropertyDate").getValue().getClass());
  assertNotNull(entity.getProperty("PropertyDateTimeOffset").getValue());
  assertEquals(java.sql.Timestamp.class, entity.getProperty("PropertyDateTimeOffset").getValue().getClass());
}
 
Example #27
Source File: ODataReferenceAddingRequestImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * No payload: null will be returned.
 */
@Override
public InputStream getPayload() {
  if (reference == null) {
    return null;
  } else {
    ODataWriter writer = odataClient.getWriter();
    try {
      return writer.writeReference(reference, ContentType.parse(getContentType()));
    } catch (ODataSerializerException e) {
      LOG.warn("Error serializing reference {}", reference);
      throw new IllegalArgumentException(e);
    }
  }
}
 
Example #28
Source File: ErrorHandler.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public ErrorHandler(OData odata, ServiceMetadata metadata,
    ServiceHandler handler, ContentType contentType) {
  this.odata = odata;
  this.handler = handler;
  this.contentType = contentType;
  this.metadata = metadata;
}
 
Example #29
Source File: AuthEntityRetrieveTestITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
protected InMemoryEntities getContainer() {
  final Service<EdmEnabledODataClient> ecf = Service.getV4(testAuthServiceRootURL);
  ecf.getClient().getConfiguration().setDefaultBatchAcceptFormat(ContentType.APPLICATION_OCTET_STREAM);
  ecf.getClient().getConfiguration().
  setHttpClientFactory(new BasicAuthHttpClientFactory("odatajclient", "odatajclient"));
  return ecf.getEntityContainer(InMemoryEntities.class);
}
 
Example #30
Source File: TechnicalActionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public void processActionVoid(final ODataRequest request, final ODataResponse response, final UriInfo uriInfo,
    final ContentType requestFormat) throws ODataApplicationException, ODataLibraryException {
  final UriResourceAction resource =
      ((UriResourceAction) uriInfo.getUriResourceParts().get(uriInfo.getUriResourceParts().size() - 1));
  final EdmAction action = resource.getAction();
  readParameters(action, request.getBody(), requestFormat);
  response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}