Service (JCS) provides a platform to
develop and deploy business applications in the cloud. In Fusion Applications
Cloud deployments customers do not have the
option to deploy custom applications developed with JDeveloper to ensure the
integrity and supportability of the hosted application service. Instead the custom applications can be deployed
to the JCS and integrated to the Fusion Application Cloud instance.
This series of articles will go through the
features of JCS, provide end-to-end examples on how to develop and deploy
applications on JCS and how to integrate them with the Fusion Applications
instance.
In this article a
custom application integrating with REST service will be implemented. We will
use REST services provided by Taleo as an example; however the same approach
will work with any REST service. In this example the data from the REST service
is used to populate a dynamic table.
Pre-requisites
Access to Cloud instance
In order to deploy the application access to a JCS instance is needed, a free trial JCS instance can be obtained from Oracle Cloud site. To register you will need a credit card even if the credit card will not be charged. To register simply click "Try it" and choose the "Java" option. The confirmation email will contain the connection details. See this video for example of the registration.Once the request is processed you will be assigned 2 service instances; Java and Database. Applications deployed to the JCS must use Oracle Database Cloud Service as their underlying database. So when JCS instance is created a database instance is associated with it using a JDBC data source.The cloud services can be monitored and managed through the web UI. For details refer to Getting Started with Oracle Cloud.
JDeveloper
JDeveloper contains Cloud specific features related to e.g. connection and deployment. To use these features download the JDeveloper from JDeveloper download site by clicking the "Download JDeveloper 11.1.1.7.1 for ADF deployment on Oracle Cloud" link, this version of JDeveloper will have the JCS integration features that will be used in this article. For versions that do not include the Cloud integration features the Oracle Java Cloud Service SDK or the JCS Java Console can be used for deployment. For details on installing and configuring the JDeveloper refer to the installation guideFor details on SDK refer to Using the Command-Line Interface to Monitor Oracle Java Cloud Service and Using the Command-Line Interface to Manage Oracle Java Cloud Service.
Access to a local database
The database associated with the JCS instance cannot be connected to with JDBC. Since creating ADFbc business component requires a JDBC connection we will need access to a local database.
3rd party libraries
This example will use some 3rd party libraries for implementing the REST service call and processing the input / output content. Other libraries may also be used, however these are tested to work.
Jersey 1.x
Jersey library will be used as a client to make the call to the REST service. JCS documentation for supported specifications states:
Java API for RESTful Web Services (JAX-RS) 1.1
So Jersey 1.x will be used. Download the single-JAR Jersey bundle; in this example Jersey 1.18 JAR bundle is used.
Json-simple
Jjson-simple library will be used to process the json objects. Download the JAR file; in this example json-simple-1.1.1.jar is used.
Accessing data in Taleo
Before implementing the application it is beneficial to familiarize oneself with the data in Taleo. Easiest way to do this is by using a RESTClient on your browser. Once added to the browser you can access the UI:
The client can be used to call the REST services to test the URLs and data before adding them into the application. First derive the base URL for the service this can be done with:
Method: GET
URL: https://tbe.taleo.net/MANAGER/dispatcher/api/v1/serviceUrl/<company name>
The response will contain the base URL to be used for the service calls for the company. Next obtain authentication token with:
Method: POST
URL: https://ch.tbe.taleo.net/CH07/ats/api/v1/login?orgCode=<company>&userName=<user name>&password=<password>
The response includes an authentication token that can be used for few hours to authenticate with the service:
{
"response": {
"authToken": "webapi26419680747505890557"
},
"status": {
"detail": {},
"success": true
}
}
To authenticate the service calls navigate to "Headers -> Custom Header":
And add a new request header with:
Name: Cookie
Value: authToken=webapi26419680747505890557
Once authentication token is defined the tool can be used to invoke REST services; for example:
Method: GET
URL: https://ch.tbe.taleo.net/CH07/ats/api/v1/object/candidate/search.xml?status=16
This data will be used on the application to be created. For details on the Taleo REST services refer to the Taleo Business Edition REST API Guide.
Create Application
First Fusion Web Application is created and configured. Start JDeveloper and click "New Application":
Application Name: JcsRestDemo
Application Package Prefix: oracle.apps.jcs.test
Application Template: Fusion Web Application (ADF)
Configure Local Cloud Connection
Follow the steps documented in the "Java Cloud Service ADF Web Application" article to configure a local database connection needed to create the ADFbc objects.
Configure Libraries
Add the 3rd party libraries into the class path. Create the following directory and copy the jar files into it:
<JDEV_USER_HOME>/JcsRestDemo/lib
Select the "Model" project, navigate "Application -> Project Properties -> Libraries and Classpath -> Add JAR / Directory" and add the 2 3rd party libraries:
Accessing Data from Taleo
To access data from Taleo using the REST service the 3rd party libraries will be used. 2 Java classes are implemented, one representing the Candidate object and another for accessing the Taleo repository
Candidate
Candidate object is a POJO object used to represent the candidate data obtained from the Taleo repository. The data obtained will be used to populate the ADFbc object used to display the data on the UI. The candidate object contains simply the variables we obtain using the REST services and the getters / setters for them: Navigate "New -> General -> Java -> Java Class", enter "Candidate" as the name and create it in the package "oracle.apps.jcs.test.model". Copy / paste the following as the content:
import oracle.jbo.domain.Number;
public class Candidate {
private Number candId;
private String firstName;
private String lastName;
public Candidate() {
super();
}
public Candidate(Number candId, String firstName, String lastName) {
super();
this.candId = candId;
this.firstName = firstName;
this.lastName = lastName;
}
public void setCandId(Number candId) {
this.candId = candId;
}
public Number getCandId() {
return candId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
Taleo Repository
Taleo repository class will interact with the Taleo REST services. The logic will query data from Taleo and populate Candidate objects with the data. The Candidate object will then be used to populate the ADFbc object used to display data on the UI. Navigate "New -> General -> Java -> Java Class", enter "TaleoRepository" as the name and create it in the package "oracle.apps.jcs.test.model". Copy / paste the following as the content (for details of the implementation refer to the documentation in the code):
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import oracle.jbo.domain.Number;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* This class interacts with the Taleo REST services
*/
public class TaleoRepository {
/**
* Connection information needed to access the Taleo services
*/
String _company = null;
String _userName = null;
String _password = null;
/**
* Jersey client used to access the REST services
*/
Client _client = null;
/**
* Parser for processing the JSON objects used as
* input / output for the services
*/
JSONParser _parser = null;
/**
* The base url for constructing the REST URLs. This is obtained
* from Taleo with a service call
*/
String _baseUrl = null;
/**
* Authentication token obtained from Taleo using a service call.
* The token can be used to authenticate on subsequent
* service calls. The token will expire in 4 hours
*/
String _authToken = null;
/**
* Static url that can be used to obtain the url used to construct
* service calls for a given company
*/
private static String _taleoUrl =
"https://tbe.taleo.net/MANAGER/dispatcher/api/v1/serviceUrl/";
/**
* Default constructor for the repository
* Authentication details are passed as parameters and used to generate
* authentication token. Note that each service call will
* generate its own token. This is done to avoid dealing with the expiry
* of the token. Also only 20 tokens are allowed per user simultaneously.
* So instead for each call there is login / logout.
*
* @param company the company for which the service calls are made
* @param userName the user name to authenticate with
* @param password the password to authenticate with.
*/
public TaleoRepository(String company, String userName, String password) {
super();
_company = company;
_userName = userName;
_password = password;
_client = Client.create();
_parser = new JSONParser();
_baseUrl = getBaseUrl();
}
/**
* This obtains the base url for a company to be used
* to construct the urls for service calls
* @return base url for the service calls
*/
private String getBaseUrl() {
String result = null;
if (null != _baseUrl) {
result = _baseUrl;
} else {
try {
String company = _company;
WebResource resource = _client.resource(_taleoUrl + company);
ClientResponse response =
resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).get(ClientResponse.class);
String entity = response.getEntity(String.class);
JSONObject jsonObject =
(JSONObject)_parser.parse(new StringReader(entity));
JSONObject jsonResponse =
(JSONObject)jsonObject.get("response");
result = (String)jsonResponse.get("URL");
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* Generates authentication token, that can be used to authenticate on
* subsequent service calls. Note that each service call will
* generate its own token. This is done to avoid dealing with the expiry
* of the token. Also only 20 tokens are allowed per user simultaneously.
* So instead for each call there is login / logout.
* @return authentication token that can be used to authenticate on
* subsequent service calls
*/
private String login() {
String result = null;
try {
MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
formData.add("orgCode", _company);
formData.add("userName", _userName);
formData.add("password", _password);
WebResource resource = _client.resource(_baseUrl + "login");
ClientResponse response =
resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class,
formData);
String entity = response.getEntity(String.class);
JSONObject jsonObject =
(JSONObject)_parser.parse(new StringReader(entity));
JSONObject jsonResponse = (JSONObject)jsonObject.get("response");
result = (String)jsonResponse.get("authToken");
} catch (Exception ex) {
throw new RuntimeException("Unable to login ", ex);
}
if (null == result)
throw new RuntimeException("Unable to login ");
return result;
}
/**
* Releases a authentication token. Each call to login must be followed
* by call to logout after the processing is done. This is required as
* the tokens are limited to 20 per user and if not released the tokens
* will only expire after 4 hours.
* @param authToken
*/
private void logout(String authToken) {
WebResource resource = _client.resource(_baseUrl + "logout");
resource.header("cookie", "authToken=" + authToken).post(ClientResponse.class);
}
/**
* This method is used to obtain a list of candidates using a REST
* service call. At this example the query is hard coded to query
* based on status. The url constructed to access the service is:
* <_baseUrl>/object/candidate/search.xml?status=16
* @return List of candidates obtained with the service call
*/
public List<Candidate> getCandidates() {
List<Candidate> result = new ArrayList<Candidate>();
try {
// First login, note that in finally block we must have logout
_authToken = "authToken=" + login();
/**
* Construct the URL, the resulting url will be:
* <_baseUrl>/object/candidate/search.xml?status=16
*/
MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
formData.add("status", "16");
JSONArray searchResults =
(JSONArray)getTaleoResource("object/candidate/search",
"searchResults", formData);
/**
* Process the results, the resulting JSON object is something like
* this (simplified for readability):
*
* {
* "response":
* {
* "searchResults":
* [
* {
* "candidate":
* {
* "candId": 211,
* "firstName": "Mary",
* "lastName": "Stochi",
* logic here will find the candidate object(s), obtain the desired
* data from them, construct a Candidate object based on the data
* and add it to the results.
*/
for (Object object : searchResults) {
JSONObject temp = (JSONObject)object;
JSONObject candidate =
(JSONObject)findObject(temp, "candidate");
Long candIdTemp = (Long)candidate.get("candId");
Number candId =
(null == candIdTemp ? null : new Number(candIdTemp));
String firstName = (String)candidate.get("firstName");
String lastName = (String)candidate.get("lastName");
result.add(new Candidate(candId, firstName, lastName));
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (null != _authToken)
logout(_authToken);
}
return result;
}
/**
* Convenience method to construct url for the service call, invoke the
* service and obtain a resource from the response
* @param path the path for the service to be invoked. This is combined
* with the base url to construct a url for the service
* @param resource the key for the object in the response that will be
* obtained
* @param parameters any parameters used for the service call. The call
* is slightly different depending whether parameters exist or not.
* @return the resource from the response for the service call
*/
private Object getTaleoResource(String path, String resource,
MultivaluedMap<String, String> parameters) {
Object result = null;
try {
WebResource webResource = _client.resource(_baseUrl + path);
ClientResponse response = null;
if (null == parameters)
response =
webResource.header("cookie", _authToken).get(ClientResponse.class);
else
response =
webResource.queryParams(parameters).header("cookie", _authToken).get(ClientResponse.class);
String entity = response.getEntity(String.class);
JSONObject jsonObject =
(JSONObject)_parser.parse(new StringReader(entity));
result = findObject(jsonObject, resource);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* Convenience method to recursively find a object with an key
* traversing down from a given root object. This will traverse a
* JSONObject / JSONArray recursively to find a matching key, if found
* the object with the key is returned.
* @param root root object which contains the key searched for
* @param key the key for the object to search for
* @return the object matching the key
*/
private Object findObject(Object root, String key) {
Object result = null;
if (root instanceof JSONObject) {
JSONObject rootJSON = (JSONObject)root;
if (rootJSON.containsKey(key)) {
result = rootJSON.get(key);
} else {
Iterator children = rootJSON.entrySet().iterator();
while (children.hasNext()) {
Map.Entry entry = (Map.Entry)children.next();
Object child = entry.getValue();
if (child instanceof JSONObject ||
child instanceof JSONArray) {
result = findObject(child, key);
if (null != result)
break;
}
}
}
} else if (root instanceof JSONArray) {
JSONArray rootJSON = (JSONArray)root;
for (Object child : rootJSON) {
if (child instanceof JSONObject ||
child instanceof JSONArray) {
result = findObject(child, key);
if (null != result)
break;
}
}
}
return result;
}
}
Creating Business Objects
While JCS application can be created without a local database, the local database is required when using ADFbc objects even if database objects are not referred. For this example we will create a "Transient" view object that will be programmatically populated based the data obtained from Taleo REST services.
Creating ADFbc objects
Choose the "Model" project and navigate "New -> Business Tier : ADF Business Components : View Object". On the "Initialize Business Components Project" choose the local database connection created in previous step. On Step 1 enter "JcsRestDemoVO" on the "Name" and choose "Rows populated programmatically, not based on query":
On step 2 create the following attributes:
CandId
Type: Number
Updatable: Always
Key Attribute: checked
Name
Type: String
Updatable: Always
On steps 3 and 4 accept defaults and click "Next". On step 5 check the "Application Module" checkbox and enter "JcsRestDemoAM" as the name:
Click "Finish" to generate the objects.
Populating the VO
To display the data on the UI the "transient VO" is populated programmatically based on the data obtained from the Taleo REST services. Open the "JcsRestDemoVOImpl.java". Copy / paste the following as the content (for details of the implementation refer to the documentation in the code):
import java.sql.ResultSet;
import java.util.List;
import java.util.ListIterator;
import oracle.jbo.server.ViewObjectImpl;
import oracle.jbo.server.ViewRowImpl;
import oracle.jbo.server.ViewRowSetImpl;
// ---------------------------------------------------------------------
// --- File generated by Oracle ADF Business Components Design Time.
// --- Tue Feb 18 09:40:25 PST 2014
// --- Custom code may be added to this class.
// --- Warning: Do not modify method signatures of generated methods.
// ---------------------------------------------------------------------
public class JcsRestDemoVOImpl extends ViewObjectImpl {
/**
* This is the default constructor (do not remove).
*/
public JcsRestDemoVOImpl() {
}
@Override
public void executeQuery() {
/**
* For some reason we need to reset everything, otherwise
* 2nd entry to the UI screen may fail with
* "java.util.NoSuchElementException" in createRowFromResultSet
* call to "candidates.next()". I am not sure why this is happening
* as the Iterator is new and "hasNext" is true at the point
* of the execution. My theory is that since the iterator object is
* exactly the same the VO cache somehow reuses the iterator including
* the pointer that has already exhausted the iterable elements on the
* previous run. Working around the issue
* here by cleaning out everything on the VO every time before query
* is executed on the VO.
*/
getViewDef().setQuery(null);
getViewDef().setSelectClause(null);
setQuery(null);
this.reset();
this.clearCache();
super.executeQuery();
}
/**
* executeQueryForCollection - overridden for custom java data source support.
*/
protected void executeQueryForCollection(Object qc, Object[] params,
int noUserParams) {
/**
* Integrate with the Taleo REST services using TaleoRepository class.
* A list of candidates matching a hard coded query is obtained.
*/
TaleoRepository repository = new TaleoRepository(<company>, <username>, <password>);
List<Candidate> candidates = repository.getCandidates();
/**
* Store iterator for the candidates as user data on the collection.
* This will be used in createRowFromResultSet to create rows based on
* the custom iterator.
*/
ListIterator<Candidate> candidatescIterator =
candidates.listIterator();
setUserDataForCollection(qc, candidatescIterator);
super.executeQueryForCollection(qc, params, noUserParams);
}
/**
* hasNextForCollection - overridden for custom java data source support.
*/
protected boolean hasNextForCollection(Object qc) {
boolean result = false;
/**
* Determines whether there are candidates for which to create a row
*/
ListIterator<Candidate> candidates =
(ListIterator<Candidate>)getUserDataForCollection(qc);
result = candidates.hasNext();
/**
* If all candidates to be created indicate that processing is done
*/
if (!result) {
setFetchCompleteForCollection(qc, true);
}
return result;
}
/**
* createRowFromResultSet - overridden for custom java data source support.
*/
protected ViewRowImpl createRowFromResultSet(Object qc,
ResultSet resultSet) {
/**
* Obtain the next candidate from the collection and create a row
* for it.
*/
ListIterator<Candidate> candidates =
(ListIterator<Candidate>)getUserDataForCollection(qc);
ViewRowImpl row = createNewRowForCollection(qc);
try {
Candidate candidate = candidates.next();
row.setAttribute("CandId", candidate.getCandId());
row.setAttribute("Name", candidate.getFirstName() + " " + candidate.getLastName());
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
/**
* getQueryHitCount - overridden for custom java data source support.
*/
public long getQueryHitCount(ViewRowSetImpl viewRowSet) {
/**
* For this example this is not implemented rather we always return 0.
*/
return 0;
}
}
Creating UI
Choose the "ViewController" project and navigate "New -> Web Tier : JSF : JSF Page". On the "Create JSF Page" enter "JcsRestDemo" as name and ensure that the "Create as XML document (*.jspx)" is checked. Open "JcsRestDemo.jspx" and navigate to "Data Controls -> JcsRestDemoAMDataControl -> JcsRestDemoVO1" and drag & drop the VO to the "<af:form> " as a "ADF Read-only Table":
Accept the defaults in "Edit Table Columns". To execute the query navigate to to "Data Controls -> JcsRestDemoAMDataControl -> JcsRestDemoVO1 -> Operations -> Execute" and drag & drop the operation to the "<af:form> " as a "Button":
Deploying to JCS
Follow the same steps as documented in previous article"Java Cloud Service ADF Web Application". Once deployed the application can be accessed with URL:
https://java-[identity domain].java.[data center].oraclecloudapps.com/JcsRestDemo-ViewController-context-root/faces/JcsRestDemo.jspx
The UI displays a list of candidates obtained from the Taleo REST Services:
Summary
In this article we learned how to integrate with REST services using Jersey library in JCS. In future articles various other integration techniques will be covered.