Thursday, June 19, 2014

2-way Data binding


A model is a javascript object (data holder) which holds information for the view to render and controller to process. To define a model, just assign them to $scope scope. 

Example:
$scope.ename="Deiveehan Nallazhagappan";

The values can be single value, any valid javascript object or even an array. 

<body>

A controller is a AngularJS javascript object which is tied to the view. Its main responsibility is to provide default values to the model and supplement them with more UI specific functionalities. 

<div ng-controller="Student">
Enter your name : <input type="text" ng-model="ename">
<br>

Hello {{ ename }}
</div>


<script type="text/javascript" src="../js/lib/angular.min.js"></script>
<script type="text/javascript">
var Student = function($scope) {
       $scope.ename="Deiveehan Nallazhagappan";
}

</script>

Note:
--       ng-controller is an attribute used to map a controller to a view.
-          The controller object is available only to that view.
-          $scope object in the controller is a special object which contains custom models. In this case, the ename attribute is available in the scope object which is available only to that div having the controller.

In the above code, the ename attribute is modified when the page loads. This is done using the sentence

$scope.ename="Deiveehan Nallazhagappan";

And the data is updated both in the label and the text box. And whenever you modify the data in the textbox, the data is updated in the model.
This is called 2-way data binding and is a very important feature of AngularJS. 





Hello AngularJS

This article explains how to get started with AnglularJS and develop a simple application

Step 1: Include angular js file
Step 2: Include ng-app attribute (bootstrap our application.)
Step 3: Include ng-model attribute that need to be mapped to view.

Source:

<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

Enter your name : <input type="text" ng-model="ename">
<br>

Hello {{ ename }}

<script type="text/javascript" src="../js/lib/angular.min.js"></script>
</body>

</html>


Whenever you type anything on the text box, the value gets bound to the model and in the code, we display whatever is present in the mode.

Note:
-          {{ ename }} is angularJS expressions where ename is model attribute. Ename is bound to the text box as well, so whenever the text box is changed, the model attribute value is changed and vice versa.
-          ng-model is an attribute used to bind the model with the view.

-          All the special html tags and attributes are called as “directives” in angularJS.

Monday, May 26, 2014

What is Angular JS

AngularJS is a Javascript framework which makes it incredibly easy to build web applications. AngularJS is a MV* framework where 'M' stands for the model (i.e., data) that the view need to render, 'V' stands for the actual page content (i.e., the DOM). The * here refers to anything (i.e., it can be a controller, viewmodel etc., ). AngularJS is open-source and is maintained by Google. 

One great feature of AngularJS is data-binding, which makes it special, in-fact the data-binding is 2-way, which means, if you change the model, the view gets updated and if you change the view content, the model gets updated. Most of the frameworks currently in the market either does not support data-binding (i.e., the developer has to get and manually set it to the model) or it supports only one way.

AngularJS extends the HTML vocabulary by means of custom tag attributes called directives, thus helping the developers to teach new tricks. AngularJS components are testable using frameworks such as Jasmine, testacular etc.,

For example you can create new tags like

<multitogglebutton id="mButton" /> which can in turn have code to render multiple toggle buttons. This way you can create view components that can be reused in different places.

You can also use jQuery, Zepto and other libraries inside a directive, thus allowing developer to freely chose the libraries he likes.

AngularJS supports lot of features such as dirty checking, For more information go to www.angularjs.org.

The AngularJS source code is made freely available on Github under the MIT license.




Wednesday, April 9, 2014

Shindig communication

 

There are different ways a gadget can interact with the container and vice versa.
  1. RPC
  2. Gadget to server communication
  3. Publish / Subscribe

 RPC

The RPC mechanism is used to perform Gadget to Container communication & Gadget to Gadget communication.

The following needs to be done in order to call an RPC service from a gadget:
Container Page:
§  Create a new javascript Function

§  Register the function as a javascript service using gadgets.rpc.register API.

                Gadget Page:
§  From the gadget, call the RPC service using gadgets.rpc.call API

The first parameter “” indicates that we are going to call arpc service of the parent container.
Define the callback method for processSearchTerm.



1.2.    Gadget to Server communication.


Gadget.io API provides a mechanism by which the gadget will be able to communicate with the server side.

Gadgets.io.makeRequest accepts 3 parameters.
The first param is the URI that defines a service, second one defines the callback method, and the third one is the input parameters to the service.  The content type mentioned in the parameter is given as “TEXT”, which means the service will return a TEXT. The other content types supported are DOM, FEED & JSON. This has been explained in detail here: http://code.google.com/apis/gadgets/docs/remote-content.html#Content_Types
In the above example, the uri - rest/searchResults is nothing but a REST based service defined in Wink.

The code is given below:
           



1.3.    Publish/Subscribe.

This works on the basic bulletin board concept. A gadget can publish a message and the other gadgets which has subscribed for it can obtain the information and perform some business logic.
The example given below is taken from Shindig and is part of the distribution:
Subscriber:


The gadget can subscribe to master gadget using the subscribe API. The first parameter “random-number” defines a channel which it listens to.
The master gadget publishes a message using the following API:

Once this is called, the message is published to the channel, and the callback method is called on the subscriber.


Apache Shindig - Getting started

Shindig Environment Setup (Running the example)

Software installation

There are 2 ways of setting up the Shindig environment:
1.       Directly downloading the shindig war file
§  Download Shindig war from the url: http://shindig.apache.org/download/index.html (shindig-server-1.1-BETA5-incubating.war). Download the latest war.
§  Deploy it in the App Server.

(OR) 

if you want to build from source

2.     From source.
§  Download Apache Maven
§  Ensure JDK 6 is installed in the machine.
§  Set the path to JDK and Maven.
§  Build the war file out of the source using the following command.
mvn install -Dmaven.test.skip=true
Note: We were getting some compilation errors on the test classes hence ensure that we build using the above command.
§  The WAR file would be generated – place where it is built will be mentioned at the end of running the build.
§  Deploy the WAR in the App server.

Note: Deploying the war file:
Tomcat: deploy the war in the webapps directory, rename the war to ROOT.war and restart the server.

JBoss: deploy the war in the server/default/deploy directory, rename the war to ROOT.war and restart the server.

Invoke the following url to ensure that the application is properly installed.



Developing Gadgets

Steps:
§  Choose the gadget type – HTML or URL
§  Develop the gadget as defined in this section.
§  Place it in a location where it can be identified by an URI.
§  Develop the container code (which displays these gadgets)
§  Develop miscellaneous services like communication between container, gadget and server depending on your requirement.

Writing a simple Gadget (HTML): 




Code to display the gadget: 


The following were done in the above code:
§  Get the location of the gadget xml
§  Set the layout for the gadget container.
§  Create and add the gadget.
§  Render the gadget using the renderGadgets() API.

Writing a simple Gadget (URL): 

Just mention the url name in the attribute “href” instead of the html content.
There is no change in the way we display the URL type gadget. It follows the same step as we followed in the previous section. 

Apache shindig - Overview

Shindig is an open source framework from Apache that acts as a container for gadgets. iGoogle is built using this framework.

So what is a gadget:

Gadgets are mini applications (similar to portlet) that are written in HTML, Javascript& XML. Gadgets are iframes that are rendered into your web page. 


Date and time gadget, weather gadget, are all shindig gadgets.
These gadgets can interact with the page, communicate between gadgets.

The developer normally writes the gadget as HTML written within the gadget XML. Gadget server processes these XML and converts them into html snippets and displays them as iframe in the web page.

Types of Gadgets:
§  HTML gadgets
This is a type of gadget where the content of the gadget (html) resides within the gadget XML.

§  URL type gadgets
This is a type of gadget where the content of the gadget resides in a third party server. The URI is given as an attribute in the xml.

What is a gadget Container

It is the context where the gadget is embedded. In developer terms it is the page where the gadget resides. The page has some javascript APIs which inturn interacts with the Gadget server for rendering, communicating etc.,

What you can do using Shindig.

Shindig acts as a container for the gadgets. The gadget can perform the following using Shindig
-          Communicate with other gadgets using pub/sub feature.
-          Communicate with the container using RPC.
-          Communicate with server using gadget.io
-          Obtain open social information using the Open social API. 

How can i develop my own gadgets.

Click here to find out how to create your own gadgets.

Some reference links:

Monday, March 17, 2014

Word / Sentence detector using opennlp

OpenNLP is a machine learning toolkit used for processing NLP. This article focuses on setting up a simple maven project and runs a simple program using OpenNLP:

Add the following in the maven configuration:
              <!-- Open NLP -->
              <dependency>
                  <groupId>org.apache.opennlp</groupId>
                  <artifactId>opennlp-tools</artifactId>
                  <version>1.5.3</version>
              </dependency>
             
              <dependency>
                  <groupId>commons-io</groupId>
                  <artifactId>commons-io</artifactId>
                  <version>2.4</version>
              </dependency>

Write a java program for getting sentences:

Following are the high level steps:
  • Get a reference of the model en-sent.bin using the InputStream
  • Create Sentence model and SentenceDetector for the input model stream.
  • Get the sentence array using open nlp api


public class SentenceDetectorClient {

       public static void main(String[] args) {
              new SentenceDetectorClient().go();

       }

       private void go() {
              try {

                     InputStream modelIn = new FileInputStream("src/main/resources/models/en-sent.bin");  // --- Import en-sent.bin feil for sentence mich
                     SentenceModel sModel = new SentenceModel(modelIn);
                    
                     SentenceDetectorME sentenceDetector = new SentenceDetectorME(sModel); // ------ Creating a Sentence detector based on the input stream
                    
                     String articleText = "Chris Gayle on Monday sounded out a warning to the rival teams ahead of the World Twenty20 by declaring that he can score a hundred irrespective of the conditions. “I am capable of scoring a century in any condition and on any wicket in the world. I just want to give the team that kind of a start. It will be nice to get another hundred,” Gayle said. “However it also depends on the conditions as well and how the wicket is playing,” he said. Asked about the tremendous pressure on him to perform every time, when he goes out to bat, the Jamaican dasher said it indeed was a challenge to live up to the expectations. “It creates a lot of pressure as expectations are rising. When you actually set a trend, then people expect you to come good at all times. You have fans worldwide who want me to do well. That’s what they pay for and want to see. But it’s not going to happen all the time but when I do get a chance I try to entertain people as much as possible,” he said. “We are here to retain the title and that’s not going to be easy but we are ready for it and we are ready for the challenges. Our first priority is to make it to the last four, it’s a tough group. Everybody is looking to win the tournament.”";            
              String[] sentences = sentenceDetector.sentDetect(articleText); // -----D
                    
                     int index = 0;
                     for (int i = 0; i < sentences.length; i++) {
                           index++;
                           String sentence = sentences[i];
                           System.out.println("Sentence : " + index  + " " + sentence); // --- printing seach sentence.
                          
                     }
                    
              } catch (Exception e) {
                     System.out.println("Exception : " + e);
                    
              }

       }

}

Output:
Sentence : 1 Chris Gayle on Monday sounded out a warning to the rival teams ahead of the World Twenty20 by declaring that he can score a hundred irrespective of the conditions.
Sentence : 2 “I am capable of scoring a century in any condition and on any wicket in the world.
Sentence : 3 I just want to give the team that kind of a start.
Sentence : 4 It will be nice to get another hundred,” Gayle said.
Sentence : 5 “However it also depends on the conditions as well and how the wicket is playing,” he said.
Sentence : 6 Asked about the tremendous pressure on him to perform every time, when he goes out to bat, the Jamaican dasher said it indeed was a challenge to live up to the expectations.
Sentence : 7 “It creates a lot of pressure as expectations are rising.
Sentence : 8 When you actually set a trend, then people expect you to come good at all times.
Sentence : 9 You have fans worldwide who want me to do well.
Sentence : 10 That’s what they pay for and want to see.
Sentence : 11 But it’s not going to happen all the time but when I do get a chance I try to entertain people as much as possible,” he said.
Sentence : 12 “We are here to retain the title and that’s not going to be easy but we are ready for it and we are ready for the challenges.
Sentence : 13 Our first priority is to make it to the last four, it’s a tough group.
Sentence : 14 Everybody is looking to win the tournament.”

-----------------------------------------------------------------------------

Similarly the following code, tokenizes the words from the same article:

InputStream modelIn = new FileInputStream(
"src/main/resources/models/en-token.bin");
TokenizerModel tModel = new TokenizerModel(modelIn);

TokenizerME tokenizer = new TokenizerME(tModel);

String articleText = "Chris Gayle on Monday sounded out a warning to the rival teams ahead of the World Twenty20 by declaring that he can score a hundred irrespective of the conditions. “I am capable of scoring a century in any condition and on any wicket in the world. I just want to give the team that kind of a start. It will be nice to get another hundred,” Gayle said. “However it also depends on the conditions as well and how the wicket is playing,” he said. Asked about the tremendous pressure on him to perform every time, when he goes out to bat, the Jamaican dasher said it indeed was a challenge to live up to the expectations. “It creates a lot of pressure as expectations are rising. When you actually set a trend, then people expect you to come good at all times. You have fans worldwide who want me to do well. That’s what they pay for and want to see. But it’s not going to happen all the time but when I do get a chance I try to entertain people as much as possible,” he said. “We are here to retain the title and that’s not going to be easy but we are ready for it and we are ready for the challenges. Our first priority is to make it to the last four, it’s a tough group. Everybody is looking to win the tournament.”";
String[] tokens = tokenizer.tokenize(articleText);

int index = 0;
String tokenString = "";
for (int i = 0; i < tokens.length; i++) {
index++;
tokenString = tokenString + tokens[i] + "|";
}
System.out.println("No. of tokens : " + tokenString.length());
System.out.println(tokenString);

Output:
No. of tokens : 1244
Chris|Gayle|on|Monday|sounded|out|a|warning|to|the|rival|teams|ahead|of|the|World|Twenty20|by|declaring|that|he|can|score|a|hundred|irrespective|of|the|conditions|.|“|I|am|capable|of|scoring|a|century|in|any|condition|and|on|any|wicket|in|the|world|.|I|just|want|to|give|the|team|that|kind|of|a|start|.|It|will|be|nice|to|get|another|hundred|,|”|Gayle|said|.|“However|it|also|depends|on|the|conditions|as|well|and|how|the|wicket|is|playing|,|”|he|said|.|Asked|about|the|tremendous|pressure|on|him|to|perform|every|time|,|when|he|goes|out|to|bat|,|the|Jamaican|dasher|said|it|indeed|was|a|challenge|to|live|up|to|the|expectations|.|“It|creates|a|lot|of|pressure|as|expectations|are|rising|.|When|you|actually|set|a|trend|,|then|people|expect|you|to|come|good|at|all|times|.|You|have|fans|worldwide|who|want|me|to|do|well|.|That’s|what|they|pay|for|and|want|to|see|.|But|it|’s|not|going|to|happen|all|the|time|but|when|I|do|get|a|chance|I|try|to|entertain|people|as|much|as|possible|,|”|he|said|.|“We|are|here|to|retain|the|title|and|that|’s|not|going|to|be|easy|but|we|are|ready|for|it|and|we|are|ready|for|the|challenges|.|Our|first|priority|is|to|make|it|to|the|last|four|,|it|’s|a|tough|group|.|Everybody|is|looking|to|win|the|tournament|.|”|


Wednesday, March 5, 2014

Spring Annotation based configuration - reading from property file

Spring can be configured using context xml files or using java annotations.

@Configuration can be used if you want to configure using java.

Full configuration code:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.cv")
@EnableMongoRepositories(basePackages = { "com.cv.framework.mongorepositories",
              "com.cv.app.repository" })
@PropertySource(value = "classpath:app.properties")
public class AppConfig extends WebMvcConfigurerAdapter
       @Inject
       Environment environment;
       @Bean
       public InternalResourceViewResolver configureInternalResourceViewResolver() {
              InternalResourceViewResolver resolver = new InternalResourceViewResolver();
              resolver.setPrefix("/WEB-INF/views/");
              resolver.setSuffix(".jsp");
              return resolver;
       }
       @SuppressWarnings("deprecation")
       @Bean
       public Mongo mongo() throws Exception {
              return new Mongo(environment.getProperty("ip"));
       }

       @Bean
       public MongoTemplate mongoTemplate() throws Exception {
              return new MongoTemplate(mongo(),
                           environment.getProperty("mdbname"));
       }

}

@Configuration tells that the current java file is a spring configuration file. 
@ComponentScan tells the container to scan all the java files that starts with the package com.cv

@EnableMongoRepository informs the container where to search for mongo Repositories. 

@PropertySource annotation defines the property file this annotation java file uses to pull configurable values for the application. 

Environment is a spring api class which is used to read from the properties file. 
environment.getProperty("mdbname") tries to read the property mdbname from the app.properties file. 

Java based spring configuration is easier than the xml configuration since it throws all the errors at compile time and the context sensitive help comes very handy. 

Some developers prefer to keep some configuration in the xml to locate easily.