org.apache.olingo.commons.api.http.HttpStatusCode Java Examples

The following examples show how to use org.apache.olingo.commons.api.http.HttpStatusCode. 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: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo)
         throws ODataApplicationException {
	
	// 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();

	// 2. delete the data in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	storage.deleteEntityData(edmEntitySet, keyPredicates);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #2
Source File: FilterExpressionVisitor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public Object visitUnaryOperator(UnaryOperatorKind operator, Object operand)
    throws ExpressionVisitException, ODataApplicationException {
  // OData allows two different unary operators. We have to take care, that the type of the operand fits to
  // operand
  
  if(operator == UnaryOperatorKind.NOT && operand instanceof Boolean) {
    // 1.) boolean negation 
    return !(Boolean) operand;
  } else if(operator == UnaryOperatorKind.MINUS && operand instanceof Integer){
    // 2.) arithmetic minus
    return -(Integer) operand;
  }
  
  // Operation not processed, throw an exception
  throw new ODataApplicationException("Invalid type for unary operator", 
      HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ENGLISH);
}
 
Example #3
Source File: SelectOnComplexPropertiesITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void queryESCompCollDerivedWithMixedComplexTypes() throws Exception {
  URL url = new URL(SERVICE_URI + "ESCompCollDerived(12345)/"
      + "CollPropertyCompAno?$select=PropertyString");
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full");
  connection.connect();

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

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains("\"@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrimAno)\","
      + "\"value\":[{\"@odata.type\":\"#olingo.odata.test1.CTBaseAno\","
      + "\"PropertyString\":\"TEST12345\"},{\"@odata.type\":"
      + "\"#olingo.odata.test1.CTTwoPrimAno\",\"PropertyString\":\"TESTabcd\"}]"));
}
 
Example #4
Source File: BasicITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void updateEntityWithIEEE754CompatibleParameterWithNullString() {
  assumeTrue("There is no IEEE754Compatible content-type parameter in XML.", isJson());

  final URI uri = getClient().newURIBuilder(SERVICE_URI)
      .appendEntitySetSegment(ES_ALL_PRIM).appendKeySegment(0).build();

  final ClientEntity entity = getFactory().newEntity(ET_ALL_PRIM);
  entity.getProperties().add(getFactory().newPrimitiveProperty(PROPERTY_INT64,
      getFactory().newPrimitiveValueBuilder().buildString("null")));
  entity.getProperties().add(getFactory().newPrimitiveProperty(PROPERTY_DECIMAL,
      getFactory().newPrimitiveValueBuilder().buildString("null")));

  final ODataEntityUpdateRequest<ClientEntity> requestUpdate = getEdmEnabledClient().getCUDRequestFactory()
      .getEntityUpdateRequest(uri, UpdateType.PATCH, entity);
  requestUpdate.setContentType(CONTENT_TYPE_JSON_IEEE754_COMPATIBLE);
  requestUpdate.setAccept(CONTENT_TYPE_JSON_IEEE754_COMPATIBLE);

  try {
    requestUpdate.execute();
    fail();
  } catch (ODataClientErrorException e) {
    assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusLine().getStatusCode());
  }
}
 
Example #5
Source File: ODataHandlerImplTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceDocumentDefault() throws Exception {
  final ODataResponse response = dispatch(HttpMethod.GET, "/", null);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());

  String ct = response.getHeader(HttpHeader.CONTENT_TYPE);
  assertThat(ct, containsString("application/json"));
  assertThat(ct, containsString("odata.metadata=minimal"));

  assertNotNull(response.getContent());
  String doc = IOUtils.toString(response.getContent());

  assertThat(doc, containsString("\"@odata.context\":\"$metadata\""));
  assertThat(doc, containsString("\"value\":"));
  
  final ODataResponse response2 = dispatch(HttpMethod.HEAD, "/", null);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response2.getStatusCode());
  assertNull(response2.getHeader(HttpHeader.CONTENT_TYPE));
  assertNull(response2.getContent());
}
 
Example #6
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private Entity getProduct(EdmEntityType edmEntityType, List<UriParameter> keyParams) throws ODataApplicationException{

		// the list of entities at runtime
		EntityCollection entitySet = getProducts();
		
		/*  generic approach  to find the requested entity */
		Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);
		
		if(requestedEntity == null){
			// this variable is null if our data doesn't contain an entity for the requested key
			// Throw suitable exception
			throw new ODataApplicationException("Entity for requested key doesn't exist",
          HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
		}

		return requestedEntity;
	}
 
Example #7
Source File: BasicITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("The client does not recognize the IEEE754Compatible content-type parameter.")
public void readEdmDecimalPropertyWithIEEE754CompatibleParameter() {
  assumeTrue("There is no IEEE754Compatible content-type parameter in XML.", isJson());

  final URI uri = getClient().newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV)
      .appendKeySegment(1)
      .appendPropertySegment(PROPERTY_COMP_ALL_PRIM)
      .appendPropertySegment(PROPERTY_DECIMAL)
      .build();
  ODataPropertyRequest<ClientProperty> request = getEdmEnabledClient().getRetrieveRequestFactory()
      .getPropertyRequest(uri);
  request.setAccept(CONTENT_TYPE_JSON_IEEE754_COMPATIBLE);
  setCookieHeader(request);
  final ODataRetrieveResponse<ClientProperty> response = request.execute();
  saveCookieHeader(response);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());

  assertEquals(BigDecimal.valueOf(34), response.getBody().getPrimitiveValue().toValue());
}
 
Example #8
Source File: MediaITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void delete() {
  final URI uri = getClient().newURIBuilder(TecSvcConst.BASE_URI)
      .appendEntitySetSegment("ESMedia").appendKeySegment(4).appendValueSegment().build();
  ODataDeleteRequest request = getClient().getCUDRequestFactory().getDeleteRequest(uri);
  request.setIfMatch("W/\"4\"");
  assertNotNull(request);

  final ODataDeleteResponse response = request.execute();
  assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode());

  // Check that the media stream is really gone.
  // This check has to be in the same session in order to access the same data provider.
  ODataMediaRequest mediaRequest = getClient().getRetrieveRequestFactory().getMediaRequest(uri);
  mediaRequest.addCustomHeader(HttpHeader.COOKIE, response.getHeader(HttpHeader.SET_COOKIE).iterator().next());
  try {
    mediaRequest.execute();
    fail("Expected exception not thrown!");
  } catch (final ODataClientErrorException e) {
    assertEquals(HttpStatusCode.NOT_FOUND.getStatusCode(), e.getStatusLine().getStatusCode());
  }
}
 
Example #9
Source File: BasicITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void test1Olingo1064() throws ODataDeserializerException {
  EdmMetadataRequest request = getClient().getRetrieveRequestFactory().getMetadataRequest(SERVICE_URI);
  assertNotNull(request);
  setCookieHeader(request);    
  
  ODataRetrieveResponse<Edm> response = request.execute();
  saveCookieHeader(response);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());

  Edm edm = response.getBody();
  
  EdmEnabledODataClient odataClient = ODataClientFactory.getEdmEnabledClient(SERVICE_URI, edm, null);
  final InputStream input = Thread.currentThread().getContextClassLoader().
      getResourceAsStream("ESCompAllPrimWithValueForComplexProperty.json");
  ClientEntity entity = odataClient.getReader().readEntity(input, ContentType.JSON);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
  assertNotNull(entity.getProperty(PROPERTY_COMP).getComplexValue());
  assertEquals("olingo.odata.test1.CTAllPrim", entity.getProperty(PROPERTY_COMP).getComplexValue().getTypeName());
  assertEquals(PROPERTY_COMP, entity.getProperty(PROPERTY_COMP).getName());
  assertNull(entity.getProperty(PROPERTY_COMP).getComplexValue().get("PropertyString").
      getPrimitiveValue().toValue());
  assertNull(entity.getProperty(PROPERTY_COMP).getComplexValue().get("PropertyBoolean").
      getPrimitiveValue().toValue());
}
 
Example #10
Source File: BoundOperationITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void invokeFunction(){
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
      .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
          .appendEntitySetSegment("ESAllPrim").build());    
  assertNotNull(request);
  setCookieHeader(request);

  final ODataRetrieveResponse<ClientEntitySet> response = request.execute();
  saveCookieHeader(response);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
  assertEquals("application/json; odata.metadata=full", response.getContentType());

  final ClientEntitySet entitySet = response.getBody();
  assertNotNull(entitySet);

  entitySet.getOperation(SERVICE_URI);
  
  
}
 
Example #11
Source File: DeepInsertITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void validateSet(final URI uri, final String cookie, final short... keys) throws EdmPrimitiveTypeException {
  final EdmEnabledODataClient client = getEdmEnabledClient();
  final ODataEntitySetRequest<ClientEntitySet> request = client.getRetrieveRequestFactory()
      .getEntitySetRequest(uri);
  request.addCustomHeader(HttpHeader.COOKIE, cookie);
  final ODataRetrieveResponse<ClientEntitySet> response = request.execute();

  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());
  assertEquals(3, response.getBody().getEntities().size());

  for (final ClientEntity responseEntity : response.getBody().getEntities()) {
    short propertyInt16 = responseEntity.getProperty(PROPERTY_INT16)
        .getPrimitiveValue().toCastValue(Short.class);

    boolean found = false;
    for (int i = 0; i < keys.length && !found; i++) {
      if (propertyInt16 == keys[i]) {
        found = true;
      }
    }

    if (!found) {
      fail("Invalid key " + propertyInt16);
    }
  }
}
 
Example #12
Source File: NavigationITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void oneLevelToEntityWithKey() throws Exception {
  final ODataRetrieveResponse<ClientEntity> response =
      getClient().getRetrieveRequestFactory().getEntityRequest(
          getClient().newURIBuilder(TecSvcConst.BASE_URI)
              .appendEntitySetSegment("ESAllPrim").appendKeySegment(32767)
              .appendNavigationSegment("NavPropertyETTwoPrimMany").appendKeySegment(-365).build())
          .execute();
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());

  final ClientEntity entity = response.getBody();
  assertNotNull(entity);
  final ClientProperty property = entity.getProperty("PropertyString");
  assertNotNull(property);
  assertNotNull(property.getPrimitiveValue());
  assertEquals("Test String2", property.getPrimitiveValue().toValue());
}
 
Example #13
Source File: MethodCallOperator.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private List<String> getParametersAsString() throws ODataApplicationException {
  List<String> result = new ArrayList<String>();

  for (VisitorOperand param : parameters) {
    TypedOperand operand = param.asTypedOperand();
    if (operand.isNull()) {
      result.add(null);
    } else if (operand.is(primString)) {
      result.add(operand.getTypedValue(String.class));
    } else {
      throw new ODataApplicationException("Invalid parameter. Expected Edm.String", HttpStatusCode.BAD_REQUEST
          .getStatusCode(), Locale.ROOT);
    }
  }

  return result;
}
 
Example #14
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void unsupportedAcceptHeaderWithSupportedAcceptCharsetHeader() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf8;q=0.1");
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;charset=iso8859-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("utf8", contentType.getParameter("charset"));

  final String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
}
 
Example #15
Source File: ServerSidePagingHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Applies server-side paging to the given entity collection.</p>
 * <p>The next link is constructed and set in the data. It must support client-specified
 * page sizes. Therefore, the format <code>page*pageSize</code> (with a literal asterisk)
 * has been chosen for the skiptoken.</p> 
 * @param skipTokenOption   the current skiptoken option (from a previous response's next link)
 * @param entityCollection  the data
 * @param edmEntitySet      the EDM entity set to decide whether paging must be done
 * @param rawRequestUri     the request URI (used to construct the next link)
 * @param preferredPageSize the client's preference for page size
 * @return the chosen page size (or <code>null</code> if no paging has been done);
 *         could be used in the Preference-Applied HTTP header
 * @throws ODataApplicationException
 */
public static Integer applyServerSidePaging(final SkipTokenOption skipTokenOption, EntityCollection entityCollection,
    final EdmEntitySet edmEntitySet, final String rawRequestUri, final Integer preferredPageSize)
    throws ODataApplicationException {

  if (edmEntitySet != null && shouldApplyServerSidePaging(edmEntitySet)) {
    final int pageSize = getPageSize(getPageSize(skipTokenOption), preferredPageSize);
    final int page = getPage(skipTokenOption);
    final int itemsToSkip = pageSize * page;

    if (itemsToSkip <= entityCollection.getEntities().size()) {
      SkipHandler.popAtMost(entityCollection, itemsToSkip);
      final int remainingItems = entityCollection.getEntities().size();
      TopHandler.reduceToSize(entityCollection, pageSize);

      // Determine if a new next Link has to be provided.
      if (remainingItems > pageSize) {
        entityCollection.setNext(createNextLink(rawRequestUri, page + 1, pageSize));
      }
    } else {
      throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
    }
    return pageSize;
  }
  return null;
}
 
Example #16
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 #17
Source File: BasicITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void readServiceDocument() {
  ODataServiceDocumentRequest request = getClient().getRetrieveRequestFactory()
      .getServiceDocumentRequest(SERVICE_URI);
  assertNotNull(request);
  setCookieHeader(request);

  ODataRetrieveResponse<ClientServiceDocument> response = request.execute();
  saveCookieHeader(response);
  assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode());

  ClientServiceDocument serviceDocument = response.getBody();
  assertNotNull(serviceDocument);
  assertThat(serviceDocument.getEntitySetNames(), hasItem(ES_ALL_PRIM));
  assertThat(serviceDocument.getFunctionImportNames(), hasItem("FICRTCollCTTwoPrim"));
  assertThat(serviceDocument.getSingletonNames(), hasItem("SIMedia"));
}
 
Example #18
Source File: BasicITCase.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Test
public void readHeaderInfoFromClientException1() throws Exception {
  ODataEntityRequest<ClientEntity> request = getClient().getRetrieveRequestFactory()
      .getEntityRequest(getClient().newURIBuilder(SERVICE_URI)
          .appendEntitySetSegment(ES_MIX_PRIM_COLL_COMP).appendKeySegment("42").build());
  assertNotNull(request);
  setCookieHeader(request);
  request.setAccept("text/plain");
  try {
    request.execute();
    fail("Expected Exception not thrown!");
  } catch (final ODataClientErrorException e) {
    assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusLine().getStatusCode());
    final ODataError error = e.getODataError();
    assertThat(error.getMessage(), containsString("key"));
  }    
}
 
Example #19
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo)
         throws ODataApplicationException {
	
	// 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();

	// 2. delete the data in backend
	List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
	storage.deleteEntityData(edmEntitySet, keyPredicates);
	
	//3. configure the response object
	response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
 
Example #20
Source File: ActionData.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static void setEntityId(Entity entity, final String entitySetName, final OData oData, final Edm edm)
    throws DataProviderException {
  try {
    entity.setId(URI.create(oData.createUriHelper().buildCanonicalURL(
        edm.getEntityContainer().getEntitySet(entitySetName), entity)));
  } catch (final SerializerException e) {
    throw new DataProviderException("Unable to set entity ID!", HttpStatusCode.INTERNAL_SERVER_ERROR, e);
  }
}
 
Example #21
Source File: EntityReferenceITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void testContextURLEntityCollection() throws Exception {
  URL url = new URL(SERVICE_URI + "/ESAllPrim/$ref");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty(HttpHeader.ACCEPT, ContentType.APPLICATION_JSON.toContentTypeString());
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.connect();

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());

  final String content = IOUtils.toString(connection.getInputStream());
  assertTrue(content.contains(CONTEXT_COLLECTION_REFERENCE));
}
 
Example #22
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void formatWithWrongParams() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim?$format=application/json;abc=xyz");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.connect();

  assertEquals(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode(), connection.getResponseCode());

  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The $format option 'application/json;abc=xyz' is not supported."));
}
 
Example #23
Source File: QueryHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * This method creates next url link.
 *
 * @param rawRequestUri Request uri
 * @param entitySet     EntitySet
 * @param page          Page num
 * @return uri
 * @throws ODataApplicationException
 */
private static URI createNextLink(final String rawRequestUri, final EdmEntitySet entitySet, final int page)
        throws ODataApplicationException {
    String nextLink = rawRequestUri + "/" + entitySet.getName() + "?$skiptoken=" + page;
    try {
        return new URI(nextLink);
    } catch (final URISyntaxException e) {
        throw new ODataApplicationException("Exception while constructing next link",
                                            HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ROOT, e);
    }
}
 
Example #24
Source File: Storage.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void deleteEntity(EdmEntityType edmEntityType, List<UriParameter> keyParams, List<Entity> entityList) 
    throws ODataApplicationException {
  
  Entity entity = getEntity(edmEntityType, keyParams, entityList);
  if (entity == null) {
    throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), 
        Locale.ENGLISH);
  }

  entityList.remove(entity);
}
 
Example #25
Source File: BasicBoundFunctionITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void boundFunctionETIsComposibleFilter() throws Exception {
  URL url = new URL(SERVICE_URI + "ESTwoKeyNav/olingo.odata.test1.BFESTwoKeyNavRTESTwoKeyNav()?"
      + "$filter=PropertyString%20eq%20%272%27");

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

  assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
  String content = IOUtils.toString(connection.getInputStream());
  assertNotNull(content);
  connection.disconnect();
}
 
Example #26
Source File: ExceptionHelperTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void serializerExceptionMustLeadToBadRequest() {
  for (MessageKey key : SerializerException.MessageKeys.values()) {
    final SerializerException e = new SerializerException(DEV_MSG, key);
    ODataServerError serverError = ODataExceptionHelper.createServerErrorObject(e, null);
    checkStatusCode(serverError, HttpStatusCode.BAD_REQUEST, e);
  }
}
 
Example #27
Source File: TransactionalEntityManager.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void rollbackTransaction() throws ODataApplicationException {
  if(isInTransaction) {
    entities = backupEntities;
    backupEntities = new HashMap<String, List<Entity>>();
    isInTransaction = false;
  } else {
    throw new ODataApplicationException("No transaction in progress", 
        HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), Locale.ENGLISH);
  }
}
 
Example #28
Source File: DemoEntityProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo,
												 ContentType requestFormat, ContentType responseFormat)
			throws ODataApplicationException, DeserializerException, SerializerException {
	
	// 1. Retrieve the entity type from the URI 
	EdmEntitySet edmEntitySet = Util.getEdmEntitySet(uriInfo);
	EdmEntityType edmEntityType = edmEntitySet.getEntityType();

	// 2. create the data in backend 
	// 2.1. retrieve the payload from the POST request for the entity to create and deserialize it
	InputStream requestInputStream = request.getBody();
	ODataDeserializer deserializer = odata.createDeserializer(requestFormat);
	DeserializerResult result = deserializer.entity(requestInputStream, edmEntityType);
	Entity requestEntity = result.getEntity();
	// 2.2 do the creation in backend, which returns the newly created entity
	Entity createdEntity = null;
	
	try {
	  storage.beginTransaction();
	  createdEntity = storage.createEntityData(edmEntitySet, requestEntity, request.getRawBaseUri());
	  storage.commitTransaction();
	} catch( ODataApplicationException e ) {
	  storage.rollbackTransaction();
	  throw e;
	}
	  
	  // 3. serialize the response (we have to return the created entity)
	ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build(); 
	EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build(); // expand and select currently not supported 
	
	ODataSerializer serializer = odata.createSerializer(responseFormat);
	SerializerResult serializedResponse = serializer.entity(serviceMetadata, edmEntityType, createdEntity, options);
	
	//4. configure the response object
	response.setContent(serializedResponse.getContent());
	response.setStatusCode(HttpStatusCode.CREATED.getStatusCode());
	response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
 
Example #29
Source File: PreferHeaderForGetAndDeleteITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void preferHeaderRepresentation_GetComplexProperty() throws Exception {
  URL url = new URL(SERVICE_URI + "ESCompCollDerived(12345)/PropertyCompAno");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.PREFER, "return=representation");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The Prefer header 'return=representation' is not supported for this HTTP Method."));
  
}
 
Example #30
Source File: DemoEntityCollectionProcessor.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private void readFunctionImportCollection(final ODataRequest request, final ODataResponse response, 
    final UriInfo uriInfo, final ContentType responseFormat) throws ODataApplicationException, SerializerException {
  
  // 1st step: Analyze the URI and fetch the entity collection returned by the function import
  // Function Imports are always the first segment of the resource path
  final UriResource firstSegment = uriInfo.getUriResourceParts().get(0);
  
  if(!(firstSegment instanceof UriResourceFunction)) {
    throw new ODataApplicationException("Not implemented", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), 
        Locale.ENGLISH);
  }
  
  final UriResourceFunction uriResourceFunction = (UriResourceFunction) firstSegment;
  final EntityCollection entityCol = storage.readFunctionImportCollection(uriResourceFunction, serviceMetadata);
  
  // 2nd step: Serialize the response entity
  final EdmEntityType edmEntityType = (EdmEntityType) uriResourceFunction.getFunction().getReturnType().getType();
  final ContextURL contextURL = ContextURL.with().asCollection().type(edmEntityType).build();
  EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with().contextURL(contextURL).build();
  final ODataSerializer serializer = odata.createSerializer(responseFormat);
  final SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entityCol, 
      opts); 

  // 3rd configure the response object
  response.setContent(serializerResult.getContent());
  response.setStatusCode(HttpStatusCode.OK.getStatusCode());
  response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}