Thursday, 10 December 2015

Consuming REST service through JavaScript Client in JDeveloper

This blog is intended to give you a basic idea on the application and usage of the new JavaScript client feature introduced in JDeveloper
This usecase talks about using the RESTful JavaScript Client feature provided by JDeveloper to invoke a RESTful service. For this, we will be creating a javascript client for a service which gives us basic employee details, ie., id and name. We will also perform search operation on the employees and insert new employee data, using HTML and JavaScript at the front end, while talking to the service behind the scene.

1)      Run the attached service in integrated weblogic server. Copy the WADL URL.
2)      Create a new Custom application. Invoke the new gallery wizard and select RESTful JavaScript Client as shown below. In the resulting dialog, enter the WADL URL of the service. Navigate to the next page of the wizard. Here, you can optionally rename the ‘Class Name’ to a more convenient name. In this sample, I have used the name as ‘EmpClient’. Finish the wizard. A client.js file will get auto generated for you at this stage. As we had renamed the Class name to ‘EmpClient’, the main variable and function in this js file will also be named in a similar fashion. This file contains all the javascript code required to invoke the RESTful service. All we need to do now is design an HTML page and invoke the operations.
3)      To invoke the operations of the service, start off by creating a HTML page. Let’s call the html page as EmployeePage.html.
4)      To use the variables and functions defined in client.js, we need to include it in our HTML page. client.js in turn uses jquery.min.js. Thus, we need to include it as well in our HTML file. Without jquery.min.js, you will end up with the error ‘$ is not defined’ at runtime.
5)      To design the HTML page, add a button with an onClick event attached to it. A snippet of the auto-generated client.js file as well as the initial HTML page is shown below. The page also includes the skeletal structure of a table, which we will use to render the data returned from the service.
Snippet of client.js:
var EmpClientClient = {
rootUri : "http://localhost:7101/REST_Service-Model-context-root/resources/",
EmpClient : function()
var path0 = EmpClientClient.rootUri;
return {
Project1 : function()
var path1 = path0+"project1";
getAsJson : function(){

Initial HTML Structure:
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
        <title>Employee Page</title>
        <script type="text/javascript" src="js/client.js"></script>
        <script src=""></script>
            <button onclick="invokeGETOperation()">Invoke GET Operation</button>
        <table border="1" id="tbl1" hidden="hidden">

6)      We then create the invokeGETOperation() function within the script tags as shown.

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
        <title>Employee Page</title>
        <script type="text/javascript" src="js/client.js"></script>
        <script src=""></script>
          function invokeGETOperation() {
              $("tbody").children().remove();   //clear table body
              var myJsonObj = EmpClientClient.EmpClient().Project1().getAsJson();
              myJsonObj.success(function (data) {

      function populateResultTable(data) {
var dataSize = data.list.length;
                for (i = 0;i < dataSize;i++) {
                   var tbl = document.getElementById("tbl1").innerHTML;
                   var tableData = tbl + '<tr><td>' + data.list[i].id + '<\/td><td>' + data.list[i].name + '<\/td><\/tr>';
                   document.getElementById("tbl1").innerHTML = tableData;
              document.getElementById("tbl1").hidden = false;
            <button onclick="invokeGETOperation()">Invoke GET Operation</button>
        <table border="1" id="tbl1" >

7)      That’s it! Run the page.

NOTE: In the browser, change the URL from to localhost. Otherwise, the request will not go through (you may need to use Access-Control-Allow-Origin header when hostnames of service and client are different).
HTML Output:
For PUT operation:
Code snippet to invoke Put operation:
             //Create new JSON data and populate it with new user data
              var newJsonData = new Object();
     = eId;           // eId is taken from input text box using document.getElementById("empId").value;
     = ename;       
              var myJsonObj = EmpClientClient.EmpClient().Project1().putJson(newJsonData); //passing the employee JSON object to the put operation

For Search (GET) operation:
Code snippet to invoke Search operation (Uses PathParam and QueryParam):
var myJsonObj = EmpClientClient.EmpClient().Project1().SearchEmpId(eId).getAsJson(ename);
Final  Output

A sample JavaScript client app can be found here.

Friday, 6 November 2015

React-Native DrawerLayoutAndroid - How to Open the Menu on Click of an Menu Icon

Recently had a chance to develop an app using the react native. On of my requirement for the app was a hamburgur menu. While the DrawerLayoutAndroid available does the job, to a great extend, had a requirement to open the menu on click of the Home Menu/Hamburgur menu.

This turned out to be quite a challenge. The document did not provide any means to open the drawer. On digging deeper into the code, noticed one method within the called openDrawer. This looked to be promising but the challenge was this was withing the Component, but react provides a nice feature called ref which is a callback function that is executed after render returning an instance of the rendered component. By using this i was able to access the openDrawer method and open the menu as required.

The below code snippet will explain this better:
var MenuDrawerLayout = React.createClass({
    navigationView : function(){
        return (
             <View style={{flex: 1,alignItems: 'center'}}>
                <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>Hello</Text>
                <Text style={{margin: 10, fontSize: 15, textAlign: 'right'}}>World!</Text>
    drawerInstance : {instance : {openDrawer : function(){}}},
    initInstance : function(instance){
        this.drawerInstance.instance = instance;
    onMenuClick : function(event){
        //callback function called when menu is clicked. This
               <View style={styles.container} >
                    <View style={[styles.body]}>
                        <Header onMenuClick={this.onMenuClick}></Header>
                        <Dashboard.DashboardBody />

Thursday, 5 November 2015

Creating ADFBC REST services - A new feature in Oracle JDeveloper 12.2.1

With the release of JDeveloper 12.2.1, a number of new features have come in. One particular feature w.r.t web services that has been introduced in this release is the ability to create RESTful services using ADF business components. In this blog, I will take you through the steps to expose ADFBC components as REST services.

Create a new ADF fusion application.

Call the application ‘EmployeeDescribe’.

On the Model project, invoke the ‘Business Components From Tables’ wizard.

Connect to the DB in which you created the tables. I have used EMPLOYEES table from HR schema in my case. In Step 1 of the wizard, query and toggle the EMPLOYEES table to the RHS as shown.

In step 2, toggle EmployeesView to the RHS as shown. In Step 4, ensure ‘Add to Application Module’ is ticked. Click Finish to close the wizard.

To create the ADFBC REST service, open the AppModule by double clicking on it. Navigate to Web Service -> REST and click the plus icon. In the resulting dialog, click on the link provided.

It will take you to the adf-config.xml page. Navigate to 'Release versions' tab and create a new version.

Come back to the REST tab under App module and click the plus icon. Click Yes in the resulting dialog. Doing so will configure your application for REST services and add a new project to it.

Next, provide a name, say emp for the resource. This will expose the employee object with endpoint as emp.

Next, run the RESTWebService project. A URL gets generated in the console. Copy that to the browser and replace the last part with version/resourcename. So, the final URL may look something as below:

In the browser, a description of the emp resource is shown.
You can get the complete description of the service, by using a URL such as:

In this case, you will be able to see details about what resources the REST service exposes, the attributes that are present, their type, methods exposed etc. This is the basically a description of the REST service.
You have now successfully exposed your ADF business components as a REST service!!!

Wednesday, 16 September 2015

Obtaining the name of the key in fasterxml

In this blog, I have just presented a simple sample of using fasterxml API to parse JSON data. This shows you how you can get the name of the key within a JSON object.

Suppose, you have a JSON sample as below:

"data": {
        "itemId": 1,
        "itemName": "Table",
        "price": 400,
        "dimensions": {
            "length": 5.0,
            "width": 10.0,
            "height": 4.0
        "warehouseLocation": {
            "latitude": -48.45,
            "longitude": 20.5
 "contact": [{
  "name": "Alison",
  "phone": "6454666"
  "name": "Simon",
  "phone": "6433666"

Now, using java, if you are interested in obtaining itemName's contents, you would write code as below using fasterxml:

            ObjectMapper _MAPPER = new ObjectMapper();
            JsonNode node = _MAPPER.readTree(reader);
            JsonNode dataNode = node.get("data");
            Iterator<String> iter = dataNode.fieldNames();
            while (iter.hasNext()) {
                String key =; //get the key of the object node
                if (key == "itemName") {
                    JsonNode dataVal = dataNode.get(key);
                    System.out.println("KEY:"+key+" VALUE:"+dataVal);

This will give output as below:
 KEY:itemName VALUE:"Table"

That's it in this blog. Hope you found it useful.

Wednesday, 12 August 2015

"GraphMethodException - No node specified" Error on accessing Facebook API

Sometimes on hitting the methods provided by Facebook API, you may see an error such as below:

The code 100 with this error indicates that there is an invalid parameter that is being passed in the request (Refer error-reference).This would in turn mean that the URL you are trying to hit is not valid. For example, in my case, the problem was with the query parameters I was passing. The keys of the query parameters were not matching with the ones specified by Facebook API. Hence, I was seeing this error. I fixed it by referring the API docs and supplying the right query parameters.

Hope this helps!

Wednesday, 29 July 2015

Add Web Service Policy Reference for JEE clients - Explored

While working on something, I recently bumped into this cool feature in JDeveloper whereby you can easily consume secure web services through servlets. As usual, Jdevloper takes care of a lot of things for you, and all you really need to do is use the wizards and write some minimalist code.

In this usecase, I will demonstrate how a secure SOAP service can be consumed through a JEE client using the 'Add Policy Reference feature'. I will be consuming the service in JEE through a servlet.


  • For the purpose of this demo, I created a basic Hello service as below and secured it with the policy 'oracle/wss_username_token_service_policy'.
package pack;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import weblogic.wsee.jws.jaxws.owsm.SecurityPolicy;

@SecurityPolicy(uri = "oracle/wss_username_token_service_policy")
public class Hello {
    public String helloWorld(@WebParam(name = "arg0") String s) {
        return "Hello " + s;

  • Create the web service proxy for this service in a new application. Select the corresponding client policy during creation of the proxy. This step is required since this is the proxy reference that we will be referring to in the servlet.

  • Create a servlet in the same project.

  • Right click on the servlet editor and select Insert Proxy Reference -> As shown, @WebServiceRef annotation gets generated with a reference to our proxy. 

  • Since the proxy also has client side security attached, we can now bring in the security aspect to the servlet as well. For this, place the mouse over @WebServiceRef and right click. Select the option to 'Add JEE Client Policy Annotations'. A confirmation dialog will show up. Select Yes in that to bring in the security annotations.

  • Modify the doGet method to add code to invoke the service. This involves  initializing the port, passing security information and calling the service.
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<p>The servlet has received a GET. This is the reply.</p>");
        /*Add these lines to invoke secure service*/
        Hello port = helloService.getHelloPort();
        Map<String, Object> reqContext = ((BindingProvider)port).getRequestContext();
        reqContext.put(BindingProvider.USERNAME_PROPERTY, "weblogic");
        reqContext.put(BindingProvider.PASSWORD_PROPERTY, "weblogic1");
        /* End of add lines*/
  • Thats it. Run the servlet to see the output from the service.

Thursday, 7 May 2015

Google API Getting OAUTH2 Access Token (Part 1 Create Project and Get Access Token)

This post is aimed at exploring the Google API access through an access token. In order to do so one needs to get the access token and the steps to do so is detailed below.

Step 1: Register An App in Google developer Console

Create a Project in the Google developer console:

Click on the API link and Enable the Required API (In this case I have enabled the Drive API)

Step 2: Create the Client Id
Click on the Credentials tab to navigate to the Create Client Id screen

Click on Create New Client ID.

Select the appropriate application type. In my case I chose Web Application I was using it on a browser for accessing the Google Drive.

Select email id, enter the Product Name and save

On the Create Client Id enter the host from where your application would run. In my case i have entered a localhost url as I am testing the same.

There are two things of importance here:
1) The Authorized Javascript Origin: this is your application url from where all the requests would origin. When the application is granted to access the google API, the request should origin from the domain mentioned in this scree.
2) Authorized redirect URI : This is very important for further processing as during the auth process the browser will redirect to the Google pages for consent where the user accepts the permissions sought by the app (scopes will cover in subsequent blogs). 

Submission of the page creates the client id.

This completes the steps to Creating the Client Id and we are ready proceed towards obtaining a access_token.

3) Fetch the Access Code:

The access token can be fetched directly in the first response, but then the token retrieved has a short life. In order to be able to fetch the access token endlessly it is good to store a reference to the refresh token and use it to fetch all subsequent tokens. 

Request Url :
Parametes : 
client_id : The client id of the app project (as per screenshot it is "")
scope : "openid profile email"  
redirect_uri : The uri defined during the client id creation (https://localhost:3002/oauth2callback)
state : A random string that can be used to identify the request on redirect back from google consent screens
access_type : offline (this indicates that the application requires an offline access which will help in getting the refresh token which can be used to get access token for access till permissions are revoked by the user

Request Code:

var CLIENT_ID = ""
var oauthparams = {};
oauthparams.client_id = CLIENT_ID;
oauthparams.response_type = 'code';
oauthparams.scope = "openid profile email";
oauthparams.redirect_uri = "https://localhost:3002/oauth2callback";
oauthparams.state = "usearandomidlater";
oauthparams.access_type = "offline";
var authurl = "";
var queryparams = $.param(oauthparams);

As you can see the page is redirected to the google auth url with request parameters. Accept the authorization in the page.

On Accepting the page will be redirected back to the redirect url : 
https://localhost:3002/oauth2callback?state=usearandomidlater&code=4/Z6U2Rfdw56GRz_y-4IvXEB3MDEGk0VlQCFduu5S3ayA.4ichVUMhZqodcp7tdiljKKapJNNjmgI&authuser=0&prompt=consent&session_state=84c996f4ae4ad226d8edb0b834b113c88 a5393fd..93b2#

The code retrieved at this stage is very important which can be used in further AJAX calls to retrieve the access token and refresh tokens.

4) Redeem the code to fetch the Access Token:

I have made us of the google API scripts to fetch the access token as it takes care of the required request encoding.

var code = "4/Z6U2Rfdw56GRz_y-4IvXEB3MDEGk0VlQCFduu5S3ayA.4ichVUMhZqodcp7tdiljKKapJNNjmgI";
var CLIENT_ID = "";
var CLIENT_SECRET = "li80cFplMMk1HW2PZ7VxgwPJ";
var request = gapi.client.request({
 path : "/oauth2/v3/token",
 method : 'POST',
 headers : {
  'Content-Type': 'application/x-www-form-urlencoded'
 params : {
  'code' : code,
  'client_id' : CLIENT_ID,
  'client_secret' : CLIENT_SECRET,
  'redirect_uri' : "https://localhost:3002/oauth2callback",
  'grant_type' : 'authorization_code'

When code is first redeemed the refresh token and the access_token is returned and all subsequent request would return only the access_token. To get the access token it is good to store the refresh token.

By sending the following request parameters instead of the one mentioned above. The rest of the process remain same.
'refresh_token' : <refresh token from above request>,
'client_id' : CLIENT_ID,
'client_secret' : CLIENT_SECRET,
'grant_type' : 'refresh_token'

The response would contain the access code(default expiry in 3600s) which can be used in all Google API requests (provided the API has access has been granted). In case any new API request add the same to scope and initiate the consent form request.

Tuesday, 21 April 2015

Declarative Hyperlinking using @InjectLink - Part 2

In my previous post, I talked about the set-up required to use declarative hyperlinking feature provided by Jersey 2.x. This post is a continuation to that post. In this post, we will create links to individual accounts based on the balance amount available in the account.
Let us first update the service to include a GET method, which returns information for a particular account. We also need to add a method that performs POST operation to update account information. For this, go to and add the below code:
    public Accounts accountsInfoById(@PathParam("id") int id) {
        for (int i = 0; i < accList.size(); i++) {
            if (accList.get(i).getAccount_number() == id) {
                return accList.get(i);
        return null;

    public AccountWrapper updateAccountById(@PathParam("id") int id, Accounts account) {
        List<Accounts> tempList = new ArrayList<Accounts>();
        Accounts ac = accountsInfoById(id);
        if (ac != null) {
            return new AccountWrapper(tempList);
        } else {
            return null;
Next, go to class and add @InjectLink annotations on the view & update fields.

    @InjectLink(resource = AccountService.class, method="accountsInfoById",  bindings ={@Binding(name = "id", value = "${instance.account_number}")},style =  Style.ABSOLUTE)
    private String view;
    @InjectLink(resource = AccountService.class, method="updateAccountById",  bindings ={@Binding(name = "id", value = "${instance.account_number}")}, condition = "${instance.balance >= 0}", style =  Style.ABSOLUTE)
    private String update;

Here, we have specified the InjectLink annotation with a resource attribute. In the resource attribute, we are providing the name of the class whose @Path annotation needs to be used to create the URI. The method parameter further refines the URI by providing the name of the method to look within the class. The @Path annotation specified on this method will be appended to the previously created URI. Using bindings attribute, the path parameter values are being specified. Since, in our case, the path parameter maps to the account number, we have specified the value to be account_number. At runtime, the current value of account number will be injected into this.

Run the service.

Below is the navigation to the update operation for account 111 by following the update link.

In this post, I have shown field level injection. It is also possible to perform method level injection. I will probably go through that in another post.

Monday, 13 April 2015

Declarative Hyperlinking using @InjectLink - Part 1

Declarative hyperlinking is one of the features introduced in Jersey 2.x. This feature is powerful, in that it enables you to create hyperlinks on the fly, thereby helping you in making your REST services adhere to HATEOS principle.

Declarative hyperlinking can be achieved using Jersey's @InjectLink annotation. For a detailed understanding on declarative linking and this annotation, refer jersey page.
In this post, I will show you how links can be generated using @InjectLink API. 

The final output will be something like:

The main URI will be available at all times and will enable users to come back to the list of all accounts. To get information about a specific account, a user can invoke the 'view' link associated with the account. Similarly, to update an account, a user can invoke the 'update' link corresponding to that account. The update link is available only if the balance is greater than zero in the account.

Getting started:
In Part 1 of this post, I will show you how to set up your IDE and create the main URI link. In Part 2, I will show how the account specific links are created.
For this demo, I am using Eclipse with tomcat server, but it should work on similar lines in other IDEs.

To begin, create a new dynamic web application. Next, create 3 classes in the application:

  •  – Bean class holding account information, mainly account number, currency, balance. It also has two fields for links - view, update; which will provide URIs to view/update account specific information.

package accountInfo;

import javax.xml.bind.annotation.XmlRootElement;

public class Accounts {
    public Accounts() {

    Accounts(int account_number, int balance, String currency) {
        this.account_number = account_number;
        this.currency = currency;
        this.balance = balance;

    private int account_number;
    private String currency;
    private int balance;

    private String view; //will hold the link to view account details
    private String update; //will hold the link to update account details

    public void setAccount_number(int account_number) {
        this.account_number = account_number;

    public int getAccount_number() {
        return account_number;

    public void setCurrency(String currency) {
        this.currency = currency;

    public void setBalance(int balance) {
        this.balance = balance;

    public int getBalance() {
        return balance;

    public String getCurrency() {
        return currency;

    public void setView(String view) {
        this.view = view;

    public String getView() {
        return view;

    public void setUpdate(String update) {
        this.update = update;

    public String getUpdate() {
        return update;

  • –  wrapper class encapsulates the account info into a list. The main thing to observe in this class is the @InjectLink(resource = AccountService.class, style = Style.ABSOLUTE) 
          Don't worry if you get compilation issues at this stage. The set-up step discussed later will take care of it.

package accountInfo;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import org.glassfish.jersey.linking.InjectLink.*;
import org.glassfish.jersey.linking.InjectLink;

public class AccountWrapper {
    public AccountWrapper() {

    public AccountWrapper(List<Accounts> account) {
        this.acccount = account;
    List<Accounts> acccount = new ArrayList<Accounts>();

    @InjectLink(resource = AccountService.class, style = Style.ABSOLUTE)
    URI uri;

    public void setUri(URI uri) {
        this.uri = uri;

    public URI getUri() {
        System.out.println("URI:" + uri);
        return uri;

    public void setAcccount(List<Accounts> acccount) {
        this.acccount = acccount;

    public List<Accounts> getAcccount() {
        return acccount;


  • – the main service class with HTTP verbs and methods.

package accountInfo;

import java.util.ArrayList;
import java.util.List;

public class AccountService {
    private static List<Accounts> accList = null;

    public AccountService() {
        if(accList == null)
     * Get information of all the accounts
    public AccountWrapper allAccountsInfo() {
        return new AccountWrapper(accList);

     * Helper method - to initialize data
    private void populateAccInfo() {
        accList = new ArrayList<Accounts>();
        Accounts acc1 = new Accounts();

        Accounts acc2 = new Accounts();

The presence of @InjectLink annotation on 'uri' field in AccountWrapper will ensure that every time allAccountsInfo() method returns the AccountWrapper instance, the link is injected and sent along in the 'uri' field. The InjectLink annotation 'resource' attribute specifies that the link has to created by using the @Path annotation defined in AccountService class.
At this stage, the code is ready. However, for declarative hyperlinking to work, we need to set up a few things.

To use declarative linking feature (& if you are not using maven), first you need to download the Jersey 2.x bundle from jersey site. Additionally, you need to download the JAR for declarative linking from maven repo. In eclipse, you can place these JARS under the WEB-INF -> lib folder of your application.

Additionally, you need to register the declarative linking feature in the Application class. Without doing this, injection will not work. For this, create a new java class, say 'MyApplication' which extends 'org.glassfish.jersey.server.ResourceConfig'. In the default constructor, add the lines to register the declarative linking package as below:

package accountInfo;

import org.glassfish.jersey.linking.DeclarativeLinkingFeature;
import org.glassfish.jersey.server.ResourceConfig;

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        System.out.println("In here");
Don't forget to include the package which contains your service class (in my case, accountInfo). Also, remember to add the @ApplicationPath annotation on this class.
The app is now ready with the main URI. Run the service class and invoke the allAccountsInfo method to see it in  action.
Look out for Part 2 of this post which talks about individual links.