Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
rileyrainey
Product and Topic Expert
Product and Topic Expert
2,470

I recently discovered a nifty feature in Olingo V2's JPA APIs. There are cases in web services programming where you'll need to return a custom error message, a specific HTTP error status code, or both. Olingo V2 now provides an easy to use exception class to support this.

Olingo V2 version 2.0.6 introduces a new exception class, ODataRuntimeApplicationException. This exception can be invoked to generate a specific HTTP error on demand.


A common case where you'd want to employ this would be to validate property values of an object before allowing it to be saved in the database. If you are using Olingo's JPA API, you probably want to take care where you'd perform these checks. Since these checks are associated with Olingo/JPA web service calls, we probably want to restrict the check(s) to code that would only be executed in an Olingo context. That's a convoluted way of saying that this sort of integrity check should not be done in the POJO "setter" methods -- those functions will be called in places that will have nothing to do with the Olingo web service.


I'll start by creating a separate method to perform all required validations.



private void validateFieldsBeforeSave() throws ODataRuntimeApplicationException {
// reject null or empty Name field
if (supplierName == null || supplierName.length() == 0) {
throw new ODataRuntimeApplicationException(
               "Invalid value for supplier name field",
               Locale.ROOT,
               HttpStatusCodes.BAD_REQUEST
           );
      }
  }

As you can see, you as the developer have control over the HTTP status code returned and also can supply a custom error status message.


I choose to call this validation code in the JPA object's @PrePersist and @PreUpdate methods. Those methods are associated with object creation and object updates -- what a great place to do such checks.



@PrePersist
@PreUpdate
  private void persist() throws ODataRuntimeApplicationException {
      validateFieldsBeforeSave();
  }

I have added an example putting all of this together in my version of the SAP ESPM example web service. The source code can be found on github: GitHub - SAP/sap_mobile_platform_espm_olingo_services: A version of SAP's ESPM web services ...Take a look at the Supplier.java class definition.


Data validation in your Olingo V2 JPA projects is now easy to control with this new feature. The only requirement is to use version 2.0.6 or later of the Olingo V2 libraries.

10 Comments