Friday, 16 November 2018

Rest Web Service Call in Oracle Forms

Getting  Locations from Google using Rest Web Service Call in Oracle Forms

Steps to call Web Service in Oracle Forms

1. Open SoapUI tool and create new REST project.
2. Now add the web service url in the url path and click on import WADL.

3. Generated file is placed in the folder and the path is mentioned in the main java source code as below.

    @Generated(value = { "wadl|file:///C:/2.wadl", "run|21a8cd13-a951-4a69-921a-51a6e3f9f412" }

4. Open jdeveloper and build the following java source as new project.
Google maps API is used in this code,to add other web service url modify the url in the _uriBuilder and finally archive the project.

package rest_test;

import com.sun.jersey.api.client.Client;
import javax.annotation.Generated;
@Generated({ "Oracle JDeveloper", "run|21a8cd13-a951-4a69-921a-51a6e3f9f412" })
public class MapsGoogleapisComClient {
public static void main(String[] args) {
Client client = MapsGoogleapisCom.createClient();

MapsGoogleapisCom.MapsApiPlaceAutocompleteJson mapsgoogleapiscommapsApiPlaceAutocompleteJson =
MapsGoogleapisCom.mapsApiPlaceAutocompleteJson(client,"123");

// add your code here
String str;
str = mapsgoogleapiscommapsApiPlaceAutocompleteJson.get();
}
    
public static String function_call(String input) {
Client client = MapsGoogleapisCom.createClient();
MapsGoogleapisCom.MapsApiPlaceAutocompleteJson mapsgoogleapiscommapsApiPlaceAutocompleteJson =
MapsGoogleapisCom.mapsApiPlaceAutocompleteJson(client,input);
String str;
str = mapsgoogleapiscommapsApiPlaceAutocompleteJson.get();  
return str;
}  
}

package rest_test;

import java.net.URI; 
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder; 
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

@Generated(value = { "wadl|file:///C:/2.wadl", "run|21a8cd13-a951-4a69-921a-51a6e3f9f412" },
comments = "wadl2java, http://wadl.java.net", date = "2018-08-03T08:24:33.033+05:30")
public class MapsGoogleapisCom {
/**
* The base URI for the resource represented by this proxy
*
*/
public final static URI BASE_URI;
static {
URI originalURI = URI.create("https://maps.googleapis.com");
// Look up to see if we have any indirection in the local copy
// of META-INF/java-rs-catalog.xml file, assuming it will be in the
// oasis:name:tc:entity:xmlns:xml:catalog namespace or similar duck type
java.io.InputStream is = MapsGoogleapisCom.class.getResourceAsStream("/META-INF/jax-rs-catalog.xml");
if (is != null) {
try {
// Ignore the namespace in the catalog, can't use wildcard until
// we are sure we have XPath 2.0
String found =javax.xml.xpath.XPathFactory.newInstance().newXPath().evaluate("/*[name(.) = 'catalog']/*[name(.) = 'uri' and @name ='" +
originalURI + "']/@uri",
new org.xml.sax.InputSource(is));

if (found != null && found.length() > 0) {
originalURI = java.net.URI.create(found);
}

} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (java.io.IOException e) {
}
}
}
BASE_URI = originalURI;
}
    /**
     * Json.
     *
     */
public static MapsGoogleapisCom.MapsApiPlaceAutocompleteJson mapsApiPlaceAutocompleteJson(Client client,
URI baseURI,String input) {
        return new MapsGoogleapisCom.MapsApiPlaceAutocompleteJson(client, baseURI, input);
    }

    /**
     * Template method to allow tooling to customize the new Client
     *
     */
    private static void customizeClientConfiguration(ClientConfig cc) {
    }

    /**
     * Template method to allow tooling to override Client factory
     *
     */
    private static Client createClientInstance(ClientConfig cc) {
        return Client.create(cc);
    }

    /**
     * Create a new Client instance
     *
     */
    public static Client createClient() {
        ClientConfig cc = new DefaultClientConfig();
        customizeClientConfiguration(cc);
        return createClientInstance(cc);
    }

    /**
     * Json.
     *
     */
    public static MapsGoogleapisCom.MapsApiPlaceAutocompleteJson mapsApiPlaceAutocompleteJson(String input) {
        return mapsApiPlaceAutocompleteJson(createClient(), BASE_URI,input);
    }

    /**
     * Json.
     *
     */
public static MapsGoogleapisCom.MapsApiPlaceAutocompleteJson mapsApiPlaceAutocompleteJson(Client client,String input) {
return mapsApiPlaceAutocompleteJson(client, BASE_URI,input);
}
 /**
 * Json.
     *
     */
public static class MapsApiPlaceAutocompleteJson {
private Client _client;
private UriBuilder _uriBuilder;
private Map<String, Object> _templateAndMatrixParameterValues;

private MapsApiPlaceAutocompleteJson(Client client, UriBuilder uriBuilder, Map<String, Object> map) {
_client = client;
_uriBuilder = uriBuilder.clone();
_templateAndMatrixParameterValues = map;
}
/**
* Create new instance using existing Client instance, and a base URI and any parameters
         *
         */
public MapsApiPlaceAutocompleteJson(Client client, URI baseUri,String input) {
_client = client;
_uriBuilder = UriBuilder.fromUri(baseUri);
_uriBuilder = _uriBuilder.path("/maps/api/place/autocomplete/json");
_uriBuilder =
_uriBuilder.queryParam("input", input);
_uriBuilder =
_uriBuilder.queryParam("key", "AIzaSyApl0Qp1v94eBH0qqDGFhdUbz4Zr5gX7hs");
_uriBuilder =
_uriBuilder.queryParam("sensor", "false");
_templateAndMatrixParameterValues = new HashMap<String, Object>();
}
//        /**
//         * Json.
//         *
//         */
//        public ClientResponse get() {
//            UriBuilder localUriBuilder = _uriBuilder.clone();
//            WebResource resource = _client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
//            com.sun.jersey.api.client.WebResource.Builder resourceBuilder = resource.getRequestBuilder();
//            ClientResponse response;
//            response = resourceBuilder.method("GET", ClientResponse.class);
//           
//            return response;
//        }
 /**
* Json new trial.
*
*/
public String get() {
String Concatenated_desc = new String();
UriBuilder localUriBuilder = _uriBuilder.clone();
WebResource resource = _client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
com.sun.jersey.api.client.WebResource.Builder resourceBuilder = resource.getRequestBuilder();
ClientResponse response;
response = resourceBuilder.method("GET", ClientResponse.class);
String output;
output = response.getEntity(String.class);
try {
for (int i=0; i<5; i++) {
JSONObject json = new JSONObject(output);
JSONArray pred_array = (JSONArray) json.get("predictions");
JSONObject pred_desc= (JSONObject) pred_array.get(i);
//   System.out.println("The First Description is : "+ pred_desc.get("description"));
if (i >0) { Concatenated_desc = Concatenated_desc + "||"+pred_desc.get("description");}
else
{ Concatenated_desc = Concatenated_desc +pred_desc.get("description");}
if (i == 4){
System.out.println(Concatenated_desc );
}
}
} catch (JSONException e) {
e.printStackTrace();
//  System.out.println(e);
}
return Concatenated_desc;
}
/**
* Json.
*
*/
public <T> T get(GenericType<T> returnType) {
UriBuilder localUriBuilder = _uriBuilder.clone();
WebResource resource = _client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
com.sun.jersey.api.client.WebResource.Builder resourceBuilder = resource.getRequestBuilder();
ClientResponse response;
response = resourceBuilder.method("GET", ClientResponse.class);
if (response.getStatus() >= 400) {
throw new MapsGoogleapisCom.WebApplicationExceptionMessage(Response.status(response.getClientResponseStatus()).build());
}
return response.getEntity(returnType);
}
/**
* Json.
*
 */
 public <T> T get(Class<T> returnType) {
 UriBuilder localUriBuilder = _uriBuilder.clone();
 WebResource resource = _client.resource(localUriBuilder.buildFromMap(_templateAndMatrixParameterValues));
com.sun.jersey.api.client.WebResource.Builder resourceBuilder = resource.getRequestBuilder();
ClientResponse response;
response = resourceBuilder.method("GET", ClientResponse.class);
if (!ClientResponse.class.isAssignableFrom(returnType)) {
if (response.getStatus() >= 400) {
throw new MapsGoogleapisCom.WebApplicationExceptionMessage(Response.status(response.getClientResponseStatus()).build());
}
}
if (!ClientResponse.class.isAssignableFrom(returnType)) {
return response.getEntity(returnType);
} else {
return returnType.cast(response);
}
}
}
    /**
     * Workaround for JAX_RS_SPEC-312
     *
     */
 private static class WebApplicationExceptionMessage extends WebApplicationException {
private WebApplicationExceptionMessage(Response response) {
super(response);
}
/**
* Workaround for JAX_RS_SPEC-312
*
*/
public String getMessage() {
Response response = getResponse();
Response.Status status = Response.Status.fromStatusCode(response.getStatus());
if (status != null) {
return (response.getStatus() + (" " + status.getReasonPhrase()));
} else {
return Integer.toString(response.getStatus());
}
}
public String toString() {
String s = "javax.ws.rs.WebApplicationException";
String message = getLocalizedMessage();
return (s + (": " + message));
}
}
}

5. Create new system variable in system properties,the variable name as CLASSPATH and mention all the dependency jar files and archive file path in variable value.Dependent jar files are attached in the below Link

https://drive.google.com/open?id=1JKo_fDoSHH5oYJF0cEv3JdPTT-LCC67K

6. Open the Forms builder and goto Program -> Import java classes.Import the java class used in the java project.Find the imported java class in the program units.Now we can call the java class from forms builder.
For example here function_call method is used to invoke the webservice and return the response back,the value from combo box is passed to java and return the response to forms.
DECLARE
   jo   ora_java.jobject;
   rv   VARCHAR2 (32000);
BEGIN
   jo := mapsgoogleapiscomclient.NEW;
   rv := mapsgoogleapiscomclient.function_call (:cbox);
END;


AWS Lambda

Getting Started

  • It is a Compute Service
  • Run your code with out Managing servers
  • Server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging will be handled by AWS Lambda on behalf of yourself.
  • Scales automatically, from a few requests per day to thousands per second
  • You pay only for the compute time you consume
  • You are responsible only for your code
  • All you need to do is supply your code in one of the languages that AWS Lambda supports (currently Node.js, Java, C#, Go and Python)
  •  Your code will be executed in response to the events such as
    • Changes to data in an Amazon S3 bucket or an Amazon DynamoDB table.
    • HTTP requests using Amazon API Gateway;
    • Invoke your code using API calls made using AWS SDKs
  • Your code will be available in Lambda Functions
  • You can use the AWS Lambda console, AWS CLI, and AWS SDKs to create a Lambda function.
  •  Following steps make you to understand the Lambda function which generates a Random 
number between two given numbers using the Nodes.js

Steps

          Step 1 : Log In with AWS Console

          Step 2 : Go to Compute section and click on Lambda(Run Code in Response to           
                      Events)

          Step 3 : New Web page will be opened and click on Get Started Now to create
           New Function

            Step 4 : New Web page will be opened which has Number of Blue         
                         Prints(Sample Codes) such as

    • https-request,
    • hello-world,  
    • Cloudwatch-logs-process-data etc


             Step 5 : Select a run time as Node.js 4.3

           Step 6 : Select hello-world(A Starter AWS Lambda function)

          Step 7 : New Web page will be opened, which has Configure trigger details but 
                       we are not going to do anything will Trigger for this blog so we will skip this 
                       step, Click on Next.

           Step 8 : New web page will be opened which has Configure Function details


          Step 9 : Input the Function Name as ‘random-number-generator’ and leave  the                                 Description as it is.

           Step 10 : Select Runtime as Node.js 4.3


           Step 11 : Select Code entry type as one of following option ‘Edit code 
                          inline’,‘Upload  a .zip file’ and ‘Upload a file from Amazon S3’. I am
                          selecting ‘Edit code inline’ for this Blog


Function using Node.js 4.3

          ‘use strict’
          Console.log(‘Loading function’);

          Export.handler = (event, context, callback) => {
    Let min = 0;
    Let max = 10;
    Let generatedNumber =  Math.floor(Math.random()*max) + min;

   Call back(null, generatedNumber);
          };

          Step 12 : Need to set the lambda function handler and role, we have to do   the    
          below things,


    • There will be handler text field which has value index.handler  it populates     automatically 
    • select a role from the following roles Choose an existing role, creating new role            from templates and Create a custom role. In this blog I am selecting creating new      role from templates
    • Enter Role Name as ‘basic-lambda-execute-role’
    • Enter Policy templates as ‘Simple Microservice permission’


           Step 13 : We have to do the below Advanced Settings



    • Set Memory as 128 MB which is default value but this is a very basic function so 128 MB is more than enough
    • Set time out as 3 Seconds which is also default one, if your function hasn’t finish within the time out period then Amazon kills it and shows an error message
    • By default VPC as ‘No VPC’


             Step 14 : Click on Next which goes to the New Page which has the following     
                            Review details.


    • Name of the Function
    • Description
    • Runtime
    • Handler
    • Role Name
    • Policy Templates
    • Memory
    • Timeout
    • VPC


           Step 15 : Click on Create function once review is completed.



           Step 16 : New Web page will be available with following details




       Code               : You can see your code

Configuration  :  You can see the ‘lambda function handler and role’ and 
                              Advanced Setting details

Triggers          :  You can see the Trigger details but no Trigger available                             for this Blog.

Monitoring      : Here you can see Invocations, Duration,
                            events and Throttles

          Step 17 : Click on Test button in the same page, you can see the Execution
                         result, Summary(which has Request id, Duration, Billed Duration,
                         Resource configured, Max memory used etc) and Log output  down the 
                         screen










`