Wednesday 13 January 2016

Dynamic Star Rating Generation using Java Script and CSS

Here i am sending GET request to REST service for fetching result. Extracting 'image' and 'rating' keys from result.

  • Rating is string value  for example in output it's like: "rating":"3.2"
  • To display this value as a star, using width variable
                    var width = ((actual rating/5)*100)
        
         setting width in style attribute through DOM.


Html :


 <div id="main">  
 </div>  

Java Script :

 var theUrl = "https://hackerearth.0x10.info/api/problems?type=json&query=list_problems";  
 var xmlHttp = new XMLHttpRequest();  
 xmlHttp.open("GET", theUrl, false);  
 xmlHttp.send("NULL");  
 var result = JSON.parse(xmlHttp.response);  
 for (var i = 0;i < result.problems.length;i++) {  
   var container = document.createElement("div");  
   container.className = "container";  
   var obj = result.problems[i];  
   var right = document.createElement("div");  
   right.className = "right";  
   var empty = 0;  
   for (var key in obj) {  
     if (key == "image") {  
       var x = document.createElement("IMG");  
       x.className = "image";  
       x.setAttribute("src", obj[key]);  
       x.setAttribute("width", "130");  
       x.setAttribute("height", "130");  
       var left = document.createElement('div');  
       left.className = "left";  
       left.appendChild(x);  
       container.appendChild(left);  
     }  
     else if (key == "rating") {  
       var starRatingsCss = document.createElement('div');  
       starRatingsCss.className = "star-ratings-css";  
       var width = (obj[key] / 5) * 100;  
       var starRatingsCssTop = document.createElement('div');  
       starRatingsCssTop.className = "star-ratings-css-top";  
       starRatingsCssTop.setAttribute("style", "width:" + width + "%");  
       starRatingsCssTop.innerHTML = "<span>★</span><span>★</span><span>★</span><span>★</span><span>★</span>";  
       starRatingsCss.appendChild(starRatingsCssTop);  
       var starRatingsCssBottom = document.createElement('div');  
       starRatingsCssBottom.className = "star-ratings-css-bottom";  
       starRatingsCssBottom.innerHTML = "<span>★</span><span>★</span><span>★</span><span>★</span><span>★</span>";  
       starRatingsCss.appendChild(starRatingsCssBottom);  
       var content = document.createElement('div');  
       content.className = "content";  
       content.innerHTML = "<span><b>" + key.toUpperCase() + "</b></span>";  
       content.appendChild(starRatingsCss);  
       right.appendChild(content);  
     }  
     if (obj[key] === null) {  
       empty = 1;  
       break;  
     }  
   }  
   if (empty == 0) {  
     container.appendChild(right);  
     document.getElementById('main').appendChild(container);  
   }  
 }  

CSS:


 .container {  
  width: 40%;  
  float: left;  
  border-radius: 25px;  
  border: 2px solid #73AD21;  
  margin: 10px 10px 10px 10px;  
  background: #d9f2d9;  
  overflow:hidden;  
 }  
 .left {  
  width: 150px;  
  height: 150px;  
  padding: 10px 10px 10px 10px;  
  float: left;  
 }  
 .right {  
  margin-left: 150px;  
   height: 160px;  
  padding: 10px 5px 2px 11px;  
  overflow: hidden;  
 }  
 #main {  
  border: 1px solid yellow;  
  width: 100%;  
 }  
 .star-ratings-css {  
  unicode-bidi: bidi-override;  
  color: #c5c5c5;  
  font-size: 25px;  
  height: 25px;  
  width: 100px;  
  position: relative;  
  margin-bottom: 5px;  
  margin-top: -5px;  
 }  
 .star-ratings-css-top {  
  color: #e7711b;  
  padding: 0;  
  text-shadow: 0px 1px 0 #ab5414;  
  position: absolute;  
  z-index: 1;  
  overflow: hidden;  
 }  
 .star-ratings-css-bottom {  
  z-index: 0;  
 }  

Output:


Note: 

Fiddle Link:
https://jsfiddle.net/rashmi9425/579z9p48/


Wednesday 16 September 2015

Dynamic table generation for JSON schema using Angular JS


1. Here is sample schema, which will be used to generate table header.
 {
    "$schema" : "http://json-schema.org/draft-04/schema#",
    "type" : "array",
    "items" : {
        "type" : "object",
        "properties" : {
            "id" : {
                "type" : "integer",
                "title" : "Record ID"
            },
            "rowType" : {
                "type" : "string"
            },
            "recordName" : {
                "type" : "string",
                "title" : "Record Name"
            },
            "createdBy" : {
                "type" : "string",
                "title" : "Created By"
            },
            "creationDate" : {
                "type" : "string",
                "title" : "Creation Date"
            },
            "lastUpdatedBy" : {
                "type" : "string",
                "title" : "Last Updated By"
            }
        }
    }
}

2. Create a REST service to populate data into table. This is sample for GET method response.
 {  
   "list" : [  
     {  
       "createdBy" : "rash",  
       "creationDate" : "2015-09-15",  
       "id" : 1000010412,  
       "lastUpdatedBy" : "rash",  
       "recordName" : "Adithya",  
       "rowType" : "rashmi's object"  
     },  
     {  
       "createdBy" : "rash",  
       "creationDate" : "2015-09-15",  
       "id" : 1000010413,  
       "lastUpdatedBy" : "rash",  
       "recordName" : "Padmaja",  
       "rowType" : "rashmi's object"  
     },  
     {  
       "createdBy" : "rash",  
       "creationDate" : "2015-09-15",  
       "id" : 1000010414,  
       "lastUpdatedBy" : "rash",  
       "recordName" : "ashwani",  
       "rowType" : "rashmi's object"  
     }  
   ]  
 }  

3. Create a html page with text boxes, buttons and table. Page will look like this:



4. Table generation code (Inside html file):
1:  <table style="border: 1px solid black; margin: 0px auto;">  
2:            <thead>  
3:              <tr>  
4:                <th style="border: 1px solid black; width: 100%; height: 100%"  
5:                  data-ng-repeat="v1 in tableColumns">  
6:                  <span data-ng-if="response[v1].title!=null">{{ response[v1].title}}</span>  
7:                  <span data-ng-if="response[v1].title==null">{{ v1}}</span>  
8:                </th>  
9:              </tr>  
10:            </thead>  
11:            <tbody>  
12:              <tr data-ng-repeat="dataVal in data">  
13:                <td style=" border: 1px solid black;" data-ng-repeat="v2 in tableColumns">  
14:                  <span>{{dataVal[v2]}}</span>  
15:                </td>  
16:              </tr>  
17:            </tbody>  
18:          </table>  

  • Line 5: Repeating on table columns.
  • Line 6: If title is present in schema then display title otherwise display key value.
  • Line 12 to 14: Populating table data based on service output.

5. Table generation code  (Inside controller file):
1:  app.controller("schemaParseController", function ($scope, $http) {  
2:    $scope.schemaUrl = "http://sttool32.idc.oracle.com/WebServices/MCS/MCS%20usecase%203/recordSchema.json";  
3:    $scope.serviceUrl = "http://127.0.0.1:7101/REST_AllOperations-Project1-context-root/resources/project1";  
4:    $scope.invokeSchema = function () {  
5:      $http.get($scope.schemaUrl).success(function (output) {  
6:        $scope.response = output.properties;  
7:        if ($scope.response == null) {  
8:          $scope.response = output.items.properties;  
9:        }  
10:        $scope.fillTableColumns();  
11:      });  
12:    }  
13:    $scope.invokeService = function () {  
14:      $http.get($scope.serviceUrl).success(function (service) {  
15:        $scope.data = service.list;  
16:      });  
17:    }  
18:    $scope.fillTableColumns = function () {  
19:      $scope.tableColumns = [];  
20:      for (var i in $scope.response) {  
21:        $scope.tableColumns.push(i);  
22:      }  
23:    }  
24:  });  

6. At run time:
  • Specify schema url and click on Generate table button.
  • Inside controller Line 5 (invoke schema()) is getting called, It requests for schema file over HTTP. Line 10 fillTableColumns function is executed to store key value of schema inside table columns array.

Generate Table Header
  • Specify service url and click on invoke service button.
  • Inside controller Line 13 is executed, It sends GET request to service. 

Populated Table


Monday 14 September 2015

Display TOOLTIP in angular js on mouseover


Define module and controller for Angular JS application. Controller class contains business logic behind the application. Create a html page and bind it  to controller using data-ng-controller directive.

1. Inside html file create a <div> where you want to display output on mouseover. output is getting displayed based on 'temp' variable value.

 <div data-ng-show="temp">{{TOOLTIP}}</div>  

2. Create two functions inside controller.
  • hoverIn function takes a input and set the value of 'temp' to true.
  • hoverOut function  set temp variable to false. 

  $scope.hoverIn = function (value) {  
       $scope.temp = true;  
       $scope.TOOLTIP= value;  
      }  
  $scope.hoverOut = function () {  
       $scope.temp = false;  
      }  

3. Populating table header with data-ng-repeat.

  • When you hover on particular table header, hoverIn function is getting called with tooltip value.
  • When mouse leaves column, hoverOut function is getting executed and it sets temp value to false. so previously displayed tooltip will disappear. 

 
       <table style="border: 1px solid black; margin: 0px auto;">  
           <thead>  
             <tr>  
               <th style="border: 1px solid black" data-ng-repeat="v1 in tableColumns"  
                 ng-mouseover="hoverIn(v1.TOOLTIP)" ng-mouseleave="hoverOut()">  
                 <span>{{v1.title}}</span>
               </th>  
             </tr>  
           </thead>  
         </table>  

Friday 1 May 2015

Extract latest posts of a Blog (Blogger) using JSOUP API


JSoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods Refer. Using JSoup DOM traversal you can extract data. Manipulation of HTML attributes and elements is very easy through JSoup  library.

In this post, extraction of latest posts through JSoup API will be discussed. 
  • Select a blog URL. Here i have selected my own blog url to get my latest posts.
  •  String rashmiBlog="http://rashmi9425.blogspot.in/";  
  • JdoupGet method has been written to extract posts, where i am passing value which is defined for "rashmiBlog". This method is returning a list of posts.
  • 1:    public static List<String> JsoupGet(String rashmiBlog) {  
    2:        Document doc = null;            
    3:        List<String> list = new ArrayList();  
    
    4:         try {  
    5:           doc = Jsoup.connect(rashmiBlog).get();  
    6:         } catch (IOException e) {  
    7:             e.printStackTrace();  
    8:             System.out.println("not able to connect");  
    9:             return null;  
    10:           }  
    
    11:        //Extract useName  
    12:        String userName =doc.getElementsByClass("post-footer").select ("span[itemprop]").first().text();  
    13:        list.add(userName);  
    
    14:        //select  "posts" class  
    15:        Element posts = doc.getElementsByClass("posts").first();  
    16:        ListIterator<Element> link = posts.getElementsByTag("a").listIterator(); 
     
    17:        while (link.hasNext()) {  
    18:            String href = link.next().getElementsByTag("a").first().attr("href");  
    19:            list.add(href);  
    20:        }  
    21:       
             return list;  
    22:   }  
    
    1. In line 5, connecting to blog url and parse it to a DOM. 

    2. In line 11, Extracting Username or author of blog.
    3.  <div class="post-footer">   
             <div class="post-footer-line post-footer-line-1">  
                  <span class="post-author vcard"> Posted by <span class="fn" itemprop="author" itemscope itemtype="http://schema.org/Person">   
                    <meta content="https://plus.google.com/113911429732794531347" itemprop="url"> 
                      <a class="g-profile" href="https://plus.google.com/113911429732794531347" rel="author" title="author profile"> 
                        <span itemprop="name">Rashmi Verma</span> </a> </span> </span>   
             </div>   
       </div>  
      (1)
      This is code snippet of generated document. To get author select class "post-footer" then select tag span which has a attribute 'itemprop'. There are other span tag with itemprop attribute also present so we are selecting first span tag and extracting "text" from it.

    4. In line 14, 
       <ul class="posts">   
          <li><a href="http://rashmi9425.blogspot.in/2015/04/programmatically-execution-of-create.html">Programmatically execution of CREATE operation in ...</a>  
          </li>   
          <li>  
            .   
            .  
          </li>  
            .  
            .  
        </ul>  
      
      (2)
      Select element from class 'posts', create a list iterator of latest posts. as you can see in code (2) document snippet, post url is present inside tag '<a>' . In Jsoup its very easy to get a element  using "getElementbyTag"

    5. In line 18, Extract the value of  'href' attribute, in code (2) value of attribute is 'http://rashmi9425.blogspot.in/2015/04/programmatically-execution-of-create.html'
      In this scenario only one latest post available.

  • Here is the code to print list, first value inside list is author name and after that all latest posts.
         List<String> url = JsoupGet(rashmiBlog);  
         int i = 0;  
         System.out.println("Author:::" + url.get(i)+"\n");  
         i++;  
         System.out.println("Latest Posts");  
         while (url.size() != i) {  
           System.out.println(url.get(i)+"\n");  
           i++;  
         }  
    
  • Output on console.
     Author:::Rashmi Verma  
    
     Latest Posts  
     http://rashmi9425.blogspot.in/2015/04/programmatically-execution-of-create.html  
    

Limitation: This code is only specific to Blogger URL. other blogs may have different code line. 

Saturday 18 April 2015

Programmatically execution of CREATE operation in ADF


Think of this scenario,  while executing create opetation through web page, you have to D&D Create, commit operation and attributes as a form. when you click on create button and enter values. after that click on Commit operation. Same thing we have to replicate through programmatically.

Before writting code for executing operation some points keep in mind::
1. Attribute Binding should be present onto page.
2. If binding is not present then add attributes onto page.
3. D&D Create and Commit operation onto page or add through bindings.

  • Get current binding entry and extract operational binding for CREATE operation.
  BindingContainer DcCon = BindingContext.getCurrent().getCurrentBindingsEntry();  
      OperationBinding oper = DcCon.getOperationBinding("Create");  
              Object p1 = oper.execute();  

  • Get attribute bindings for 'Usrname', 'Asin', 'Shelf' and 'Comments' attributes.
 AttributeBinding userName = (AttributeBinding) DcCon.getControlBinding("Usrname");  
       userName.setInputValue("rashmi");  
 AttributeBinding asinVal = (AttributeBinding) DcCon.getControlBinding("Asin");  
       asinVal.setInputValue("112456");  
 AttributeBinding shelfVal = (AttributeBinding) DcCon.getControlBinding("Shelf");  
       shelfVal.setInputValue("To Be Read");  
 AttributeBinding comments = (AttributeBinding) DcCon.getControlBinding("Comments");  
       comments.setInputValue("I am newly inserted");  

  • Get operation binding for Commit operation and execute it.
  OperationBinding oper1 = DcCon.getOperationBinding("Commit");  
                oper1.execute();  

        

Friday 27 March 2015

Native Inner Query join in EJB

EJB stands for Enterprise JavaBeans. There are two types of query one is Native Query and other is Named Query.
Named query means Java Persistence query language(JPQA). In Native query SQL is used to express database queries. An SQL INNER JOIN return all rows from multiple tables based on a common field between them. As a IDE Jdeveloper has been used for creating this application.(Download Application)

Steps::
  1. Create a Custom Application and Generate Entities from tables for Person, Country, State and City tables (From HR schema)

  2. Generate a new Session Bean with default options.

  3. Create a java class which will be used for mapping native query result. Generate accessors for it (such as i have created PersonDetail class). This class should implements Serializable interface.

  4. Create a method inside session bean.

  5.    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)  
       public List<PersonDetail> getInnerJoin() {  
            Query query = em.createNativeQuery("SELECT Person.id,Person.name,Country.name,State.name,City.name from Person INNER JOIN Country ON Person.COUNTRY_ID = Country.ID INNER JOIN State ON Person.STATE_ID = State.ID INNER JOIN City ON Person.CITY_ID = City.ID order by Person.id");  
            List<Person> list = query.getResultList();  
            Iterator person = list.iterator();  
            List<PersonDetail> personIterator = new ArrayList();  
            while (person.hasNext()) {  
                  Object col[] = (Object[]) person.next();  
                  PersonDetail test1 = new PersonDetail();  
                   test1.setPersonId(new Integer(col[0].toString()));  
                   test1.setPersonName(col[1].toString());  
                   test1.setCountryName(col[2].toString());  
                   test1.setStateName(col[3].toString());  
                   test1.setCityName(col[4].toString());  
                personIterator.add(test1);  
              }  
         return (personIterator);  
       }  
    

  6. Add this method into Session EJB, Local and Remote java file.
    List<PersonDetail> getInnerJoin();

  7. Right click on SessionEJBBean, 

    •  Select "Session Bean Client.."
    •  Choose client type as "Java Client", finish it.

  8. Add this code inside Session EJB Client

  9.   for (PersonDetail person : (List<PersonDetail>) sessionEJB.getInnerJoin())  
                {  
                    System.out.println(".................................................");  
                    System.out.println("Person Id = "+person.getPersonId());  
                    System.out.println("Person Name = "+person.getPersonName());  
                    System.out.println("Country Name = "+person.getCountryName());  
                    System.out.println("State Name = "+person.getStateName());  
                    System.out.println("City Name = "+person.getCityName());  
                    System.out.println(".................................................");  
                }  
    

  10. First run session EJB bean and after that run Session EJB client.

  11. Screen shot of output console


Tuesday 3 March 2015

Automatic button click in ADF using Java Script

Some time we want to perform a click operation automatically on page load. Consider a scenario where we want to call managed bean on page load event.
To achieve this::


  • Create a jsp or jspx page.
  • Drag & Drop button component inside form.
 <af:button text="click" id="b3" binding="#{backingBeanScope.backing_Shelf.b3}"  
          visible="false"  
          actionListener="#{backingBeanScope.backing_Shelf.callRowFinder}"  
      clientComponent="true"/>   
  •  On page inside <document > tag you can search for <resource> tag. 
  •  First create resource tag, select type="javascript". ( Type defines which type of function you will be keeping inside resource tag, it can be either javascript or css)
  • Create a function such as "invokeOnLoad" inside resource tag. To locate button component onto page pass button id inside method (which button you want to click). In my case button id is "b3". 

Method


  <af:resource type="javascript">  
         function invokeOnLoad() {  
             var button = AdfPage.PAGE.findComponentByAbsoluteId('b3');  
             AdfActionEvent.queue(button, true);  
             event.cancel();  
         }  
     </af:resource>  
  • Now its time to call  method. To achieve this inside <Document> tag,  client listener tag is present, this tag has load property. It invokes method during document load.
                 <af:clientListener method="invokeOnLoad" type="load"/>


Note::
If you use "AdfActionEvent.queue(button)" instead of "AdfActionEvent.queue(button,true) then   button click will occur infinity times.