Pages

Thursday, 10 December 2015

Consuming REST service through JavaScript Client in JDeveloper

Purpose:
This blog is intended to give you a basic idea on the application and usage of the new JavaScript client feature introduced in JDeveloper 12.2.1.0.0.
Usecase:
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.
Pre-requisites:
JDeveloper 12.2.1.0.0

Steps:
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>
<html>
    <head>
        <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="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
        <div>
            <button onclick="invokeGETOperation()">Invoke GET Operation</button>
        </div>
        <table border="1" id="tbl1" hidden="hidden">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>NAME</th>
                </tr>
            </thead><tbody></tbody>
        </table>
    </body>
</html>

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

<!DOCTYPE html>
<html>
    <head>
        <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="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
          function invokeGETOperation() {
              $("tbody").children().remove();   //clear table body
              var myJsonObj = EmpClientClient.EmpClient().Project1().getAsJson();
              myJsonObj.success(function (data) {
                  populateResultTable(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;
          }
     </script>
    </head>
    <body>
        <div>
            <button onclick="invokeGETOperation()">Invoke GET Operation</button>
        </div>
        <table border="1" id="tbl1" >
            <thead>
                <tr>
                    <th>ID</th>
                    <th>NAME</th>
                </tr>
            </thead><tbody></tbody>
        </table>
    </body>
</html>

 
7)      That’s it! Run the page.

NOTE: In the browser, change the URL from 127.0.0.1 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:
Similarly,
For PUT operation:
Code snippet to invoke Put operation:
             //Create new JSON data and populate it with new user data
              var newJsonData = new Object();
              newJsonData.id = eId;           // eId is taken from input text box using document.getElementById("empId").value;
              newJsonData.name = 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 DrawerLayoutAndroid.android.js 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>
              </View>
               );
    },
    drawerInstance : {instance : {openDrawer : function(){}}},
    initInstance : function(instance){
        console.log(instance);
        this.drawerInstance.instance = instance;
    },
    onMenuClick : function(event){
        //callback function called when menu is clicked. This
       console.log(this.drawerInstance.instance);
    this.drawerInstance.instance.openDrawer();
    },
    render:function(){
        return(<DrawerLayoutAndroid
            drawerWidth={dimension.width-56}
            drawerPosition={DrawerLayoutAndroid.positions.Left}
            ref={this.initInstance}
            renderNavigationView={this.navigationView}>
               <View style={styles.container} >
                    <View style={[styles.body]}>
                        <Header onMenuClick={this.onMenuClick}></Header>
                        <Dashboard.DashboardBody />
                    </View>
               </View>
        </DrawerLayoutAndroid>);
    }
})



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.

Steps:
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:
http://127.0.0.1:7101/EmployeeDescribe-RESTWebService-context-root/rest/rel1/emp

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:

http://127.0.0.1:7101/EmployeeDescribe-RESTWebService-context-root/rest/rel1/describe


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 = iter.next(); //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:


Cause:
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.

Usecase:
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.

Pre-requisities:
JDevloper 12.1.3.0.0

Steps:
  • 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;

@WebService
@SecurityPolicy(uri = "oracle/wss_username_token_service_policy")
public class Hello {
    @WebMethod
    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 -> HelloService.java. 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 {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Servlet1</title></head>");
        out.println("<body>");
        out.println("<p>The servlet has received a GET. This is the reply.</p>");
        out.println("</body></html>");
        
        /*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");
        out.println(port.helloWorld("Sansa"));
        /* End of add lines*/
        out.close();
    }
  • 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 : https://accounts.google.com/o/oauth2/auth
Parametes : 
client_id : The client id of the app project (as per screenshot it is "661108709854-s9m8cso3fqsne680d90tumdrrk5ver0u.apps.googleusercontent.com")
scope : "openid profile email https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds"  
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 = "661108709854-s9m8cso3fqsne680d90tumdrrk5ver0u.apps.googleusercontent.com"
var oauthparams = {};
oauthparams.client_id = CLIENT_ID;
oauthparams.response_type = 'code';
oauthparams.scope = "openid profile email https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds";
oauthparams.redirect_uri = "https://localhost:3002/oauth2callback";
oauthparams.state = "usearandomidlater";
oauthparams.access_type = "offline";
var authurl = "https://accounts.google.com/o/oauth2/auth";
var queryparams = $.param(oauthparams);
window.location.replace(authurl+"?"+queryparams)


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 = "661108709854-s9m8cso3fqsne680d90tumdrrk5ver0u.apps.googleusercontent.com";
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'
 }
});
request.execute(function(resp){
 console.log(resp);
})


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 AccountService.java and add the below code:
    @GET
    @Path("view/{id}")
    @Produces("application/xml")
    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;
    }


    @POST
    @Path("update/{id}")
    @Consumes("application/xml")
    @Produces("application/xml")
    public AccountWrapper updateAccountById(@PathParam("id") int id, Accounts account) {
        List<Accounts> tempList = new ArrayList<Accounts>();
        Accounts ac = accountsInfoById(id);
        if (ac != null) {
            ac.setBalance(account.getBalance());
            ac.setCurrency(account.getCurrency());
            tempList.add(ac);
            return new AccountWrapper(tempList);
        } else {
            return null;
        }
    }
Next, go to Accounts.java 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:

  • Accounts.java  – 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;

@XmlRootElement
public class Accounts {
    public Accounts() {
        super();
    }

    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;
    }
}

  • AccountsWrapper.java –  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.net.URI;
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;

@XmlRootElement
public class AccountWrapper {
    public AccountWrapper() {
        super();
    }

    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) {
        System.out.println(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;
    }

}

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


package accountInfo;

import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("account_info")
public class AccountService {
    private static List<Accounts> accList = null;

    public AccountService() {
        super();
        if(accList == null)
            populateAccInfo();
    }
    /**
     * Get information of all the accounts
     */
    @GET
    @Produces("application/xml")
    public AccountWrapper allAccountsInfo() {
        return new AccountWrapper(accList);
    }

    /**
     * Helper method - to initialize data
     */
    private void populateAccInfo() {
        accList = new ArrayList<Accounts>();
        System.out.println("populate");
        Accounts acc1 = new Accounts();
        acc1.setAccount_number(111);
        acc1.setBalance(20000);
        acc1.setCurrency("$");
        accList.add(acc1);

        Accounts acc2 = new Accounts();
        acc2.setAccount_number(222);
        acc2.setBalance(-400);
        acc2.setCurrency("$");
        accList.add(acc2);
    }
}

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.

Set-up:
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 javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.linking.DeclarativeLinkingFeature;
import org.glassfish.jersey.server.ResourceConfig;
@ApplicationPath("resources")

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("accountInfo;org.glassfish.jersey.examples.linking").register(DeclarativeLinkingFeature.class);
        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.