Class BaseResource

java.lang.Object
com.onenetwork.platform.integ.rest.BaseResource

public abstract class BaseResource
extends java.lang.Object
Base class for a JAX-RS based RESTful web services. The BaseResource class contains many methods which are useful in building web services including access to the PlatformUserContext.

The JAX-RS standard defines a mechanism called a Provider which maps an http request parameter to a method parameter and a method return value to a http response message body. Platform contains providers for a few common types including:
  • JSONObject and JSONArray
  • Table
  • SqlResult
This means that resource methods like the one below are possible without any direct mapping yourself (annotations have been excluded):
public Table getResults(JSONObject params){ ... }

By default, all REST resources are authenticated. Authentication can happen in one of two ways:

  • Session Cookie - any REST request coming from the browser (through the Command Center User Interface, for example) will typically work in this fashion. The same session cookie which is given to the client on login is used to identify the incoming request and execute the given Resource with a proper PlatformUserContext.
  • Basic Authentication - one can also authenticate using HTTP headers (this is typically how command-line and other clients call REST resources). To authenticate this way, you should Base64-encode the string "user=username:password" (replacing username with your username, password with your password), then supply this as the "Authorization" header with a prefix of "Basic". For example: "Authorization: Basic ZW50PSx1c2VyPUluc3RhbmNlQWRtaW5Vc2VyOnBhc3N3b3Jk"

By default, these REST resources' methods not transactionally scoped. Thus if you make multiple database writes, these will occur in separate transactions. To make your REST resource transactional, you can apply Spring-based annotations. Annotate your resource as with Component and Scope("request"), and mark any methods which you want to be transactional with @Transactional. For example:

@Component
@Scope("request")
@Path("/txnsample")
public class TransactionalResource extends BaseResource {

  @POST
  @Produces({ "application/json" })
  @Transactional
  public JSONObject txnsample() {
    // all logic within this method will occur in a single database transaction;
    // if any RuntimeExceptions are thrown, the transaction will be rolled back.
    // if you want to rollback on checked exceptions, you must add rollbackFor attributes, for example:
    // @Transactional(rollbackFor = {MyException1.class, MyException2.class})
  }

}
 
Please note that if you want to rollback the transaction while still returning a 200 with an explicit error message, you can throw ResourceException.

In some cases, you may want to have an "anonymously" accessible REST resource, i.e. one which the user need not be authenticated to access. To achieve this, you should put "/anon" somewhere in your REST resource's path. For example:

@Path("/anon/test")
public class AnonResource extends BaseResource {

  @POST
  @Path("/example")
  @Produces({ "application/json" })
  public JSONObject anonTestPost() {
    return new JSONObject("{key:'successful anonymous access'}");
  }

}
 
This can be accessed with an HTTP client, for example the linux "curl" utility:
 curl -X POST http://localhost/oms/rest/ZBKS/anon/test/example?VcId=9123
 
Please note that you must provide the value chain id as a request parameter "VcId". This is used to lookup the Anonymous user in the database to be used when authenticating. Anonymous access can be enabled/disabled by a value chain admin by activating/deactivating this user.
  • Field Summary

    Fields 
    Modifier and Type Field Description
    static java.lang.String JSON_SUCCESS_MSG  
    protected javax.servlet.http.HttpServletRequest request  
    protected javax.servlet.http.HttpServletResponse response  
    protected static java.util.regex.Pattern SAFE_CALLBACK_PATTERN  
  • Constructor Summary

    Constructors 
    Constructor Description
    BaseResource()  
  • Method Summary

    Modifier and Type Method Description
    PlatformUserContext getPlatformUserContext()
    Returns a PlatformUserContext for the user which initiated the request.
    PlatformUserProfile getPlatformUserProfile()
    Returns a PlatformUserProfile for the user which initiated the request.
    javax.servlet.http.HttpServletRequest getRequest()
    Returns the request which called this REST resource
    javax.servlet.http.HttpServletResponse getResponse()
    Returns the response which will be produced by this REST resource
    java.lang.String getSanitizedPathInfo()  
    protected java.lang.String jsonp​(org.json.JSONObject json, java.lang.String callback)
    JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server.
    org.json.JSONObject successJson()
    Returns a new JSONObject with one property {success: true}.
    static void validateWebSafeJsonp​(java.lang.String str)
    This method is used to validate strings which will may be emitted into a web page as a jsonp (callback) parameter It allows a very restrictive set of characters, including alphanumeric, whitespace, and a few others which are not interpreted by HTML, such as _ and .

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

  • Constructor Details

  • Method Details

    • successJson

      public org.json.JSONObject successJson()
      Returns a new JSONObject with one property {success: true}. Useful when returning success results to extjs-based user interface.
    • getRequest

      public javax.servlet.http.HttpServletRequest getRequest()
      Returns the request which called this REST resource
    • getResponse

      public javax.servlet.http.HttpServletResponse getResponse()
      Returns the response which will be produced by this REST resource
    • getPlatformUserContext

      public PlatformUserContext getPlatformUserContext()
      Returns a PlatformUserContext for the user which initiated the request. Available from both browser & non-browser clients.
    • getPlatformUserProfile

      public PlatformUserProfile getPlatformUserProfile()
      Returns a PlatformUserProfile for the user which initiated the request. Available from both browser & non-browser clients.
    • jsonp

      protected java.lang.String jsonp​(org.json.JSONObject json, java.lang.String callback)
      JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. http://en.wikipedia.org/wiki/JSON#JSONP

      Given a JSON object which is to be returned to a client, this method will wrap the JSON with a callback function iff the request parameter "jsonp" is present. Thus given a JSON { key: "val" } it will return ...

      • { key: "val" } (if no jsonp param is present)
      • myFunction('{ key: "val" }') (if jsonp=myFunction is present in the request)
      Presumably myFunction would be something like:
       function myFunction(val) {
         var json = eval(val);
       }
       
      Parameters:
      json - JSON Object which is to be wrapped with a callback function and returned
      Returns:
      JSON wrapped with jsonp callback
    • validateWebSafeJsonp

      public static void validateWebSafeJsonp​(java.lang.String str)
      This method is used to validate strings which will may be emitted into a web page as a jsonp (callback) parameter It allows a very restrictive set of characters, including alphanumeric, whitespace, and a few others which are not interpreted by HTML, such as _ and . This helps ensure the string has not html elements like < or > which could allow a user to inject scripts/etc into a page if their input is reflected back as markup in the response.
    • getSanitizedPathInfo

      public java.lang.String getSanitizedPathInfo()