Thursday, 23 July 2015

Ionic Framework : How to create simple mobile application

Ionic Framework 

Why we need Hybrid Mobile Application

Hi All, today everyone wants to have their business on smartphone  using mobile application.By using mobile application one(company/seller) could be connected to customers 24 X 7 on their smartphones, so this would give their company value,revenue,popularity etc..
So before Hybrid Mobile Application, we were required to learn mobile OS specific language like Android,.Net,J2ME etc.. which would take lots of time in development as well as in testing.

Now using Hybrid Mobile Application we just need to learn

  1. Java Script 
  2. CSS 3
  3. HTML 5
There are many frameworks available in the market for creating hybrid mobile applications like reapp,Ionic,SuperSonic etc.. We can choose any framework and start doing development. 
So I choose Ionic from a long list of frameworks, lets dive into this.

Getting Started With Ionic


Ionic is a powerful HTML5 native app development framework that helps you build native-feeling mobile apps all with web technologies like HTML, CSS, and Javascript.


Ionic is focused mainly on the look and feel, and UI interaction of your app.That means we aren’t a replacement for PhoneGap or your favorite Javascript framework. Instead, Ionic simply fits in well with these projects in order to simplify one big part of your app: the front end. Ionic currently requires AngularJS in order to work at its full potential. While you can still use the CSS portion of the framework, you’ll miss out on powerful UI interactions, gestures, animations, and other things.



Lets start building our first application using Ionic Framework.

Before start development we need to follow some installation steps :-
  1. Install Node.js
  2. Run npm install -g ionic cordova  using command prompt
This command will install Ionic as well as cordova . Now Its time to create mobile application in Ionic using ready-made app templates which are


Open command prompt and Run any as per the template you chose
  • ionic start myApp blank
  • ionic start myApp sideMenu
  • ionic start myApp tabs

Lets Execute It

  1. cd myApp
  2. ionic platform add ios/android
  3. ionic build ios/android
  4. ionic emulate ios

If you are in development phase you can test your application using following command after 1st step without performing 2nd,3rd and 4th step.


ionic serve

above command will run your application on in-built local server and open your browser and run the application.

Friday, 17 April 2015

What is Garbage Collection in Java ?

What is Garbage ?

Java provides the means to create an object, but the language doesn't provide the means to destroy the object explicitly.

As long as the reference to an object is present in the program , JVM ensures that the object exists.

1. If Java provided the means to destroy the object , it would produce unpredictable result if program calls any method on the reference of the object (destroyed already) because reference still existed. In this case these reference are called dangling reference.


Reference ---------------------> Dead or Destroyed Object = Dangling Reference


So Java eliminates dangling reference problem by disallowing the destruction of objects explicitly.

2. If Java provided the means to destroy objects explicitly then program would need to keep track all the objects created and destroyed which are no longer used . In this scenario if program somehow lose the track of object it has created the that object cannot be destroyed. And if the object is never destroyed , the memory used by the object cannot be reused by the program causes memory leak.

A program that loses track of objects before it destroys them suffers from a memory leak . If we run a program that has a memory leak for a very long time, it is quite possible that it will exhaust all the available memory and eventually fail because no new objects can be created.



An unreferenced object is called garbage  and the process of finding all the unreferenced objects and reclaiming the storage is called garbage collection .

Wednesday, 15 April 2015

EJB 3.0 Features in Detail


EJB 3.0 Features


We have already discussed features in EJB 3.0 in the previous post (EJB Features) , so in this post we will discuss features in details so we can understand them easily.

1. ( Deployment descriptor - optional )


Now we can create our EJB application without deployment descriptor XML file by using java metadata annotations for EJB. Annotation were introduced in J2SE 5.0 , are used to simplify the Enterprise Java Beans.


In EJB 3.0 , beans are simple POJO (plain old java object) with annotation, annotation processor creates the deployment descriptor at runtime. The developer doesn't have to maintain multiple files for one bean. For example, the following code shows how to define a simple stateless session bean:

/* Example class for Stateless session */
@Stateless
public class MySessionBean implements MyBean{
    public String getMessage(){
        return "Test Message";
    }
}

/* Example class for Business Interface */
@Remote
public interface MyBean{
    public String getMessage();
}

@Stateless annotation mark the MySessionBean as stateless session bean.

@Remote  annotation mark the MyBean as business interface.

2. Remote Interface are not mandatory to write


Note : Its is not mandatory to write Remote interface in EJB 3.0 we can use @Remote in the bean class itself to let the container generate the business interface,
as in the following example:
@Stateless
@Remote
public class MessageStoreBean{
public String getMessage(){
     return "Test Message";
   }

}

In the above example, the bean class doesn't implement the business interface, and uses @Remote instead. This makes development much easier than in previous versions. EJB 3.0 provides annotations for every type of metadata previously addressed by deployment descriptors, so no XML descriptor is needed and you can deploy your beans simply by deploying a plain old .jar
into your application server.


3. Callback Methods and Listener Classes


In EJB 3.0 , bean developer does not need to implement callback methods which were there in EJB 2.1 like ejbCreate(), ejbPassivate(), ejbActivate(). 
Now we have freedom to make any method as callback using some callback annotations in the bean class itself.
/* Callback method defined inside a bean class */ 
@Stateful 
public class TestBean {
     private int var;
     public int method(){}

     @PreDestroy testMethod(){}
 }

Listener classes: We can create listener classes instead of creating callback methods in the bean, only the difference is in the method signature A callback method defined in a listenerclass must take a Object as a parameter, which is not needed when the callback is in the bean itself.
Here's an example

/* Callback method defined inside a Listener class*/
 public class CustomListener{
     @PrePassivate public testMethod(Object obj){
         // Statements
     } }
 /* Adds callback listener to bean class */
 @CallbackListener
 CustomListener
 @stateful
 public class TestBean{
     private int var;
     public void getPrice(){}
 }

Enterprise Java Beans Features

Enterprise Java Beans

                                                             The Enterprise Java Beans architecture is an architecture for the development and deployment of component-based business applications. 

What is component based business applications ? 

                            Application which emphasizes the "Separation of Concerns" in respect to other wide range functionality.Its a reuse based approach to defining, implementing and composing loosely coupled independent component into systems. With regard to system-wide co-ordination, components communicate with each other via interfaces. When a component offers services to the rest of the system, it adopts a provided interface that specifies the services that other components can utilize, and how they can do so.

EJB applications are:


  • Scalable
  • Transactional
  • Multi user secure
  • Can be deployed on any application server as a distributed application
  • provides various system level service like security,transaction etc.

Various features are introduced in new versions of EJB , some brief points are given as:

Features in EJB 3.0 :


  • Annotation used to annotate EJB application, for simplifying developer's task
  • Eliminating the need for developer to provide an EJB deployment descriptor.
  • JNDI access through the use of annotation,lookup and DI mechanism
  • The required business interface for a session bean can be a plain Java interface rather than an EJBObject, EJBLocalObject, or java.rmi.Remote interface
  • Elimination of the requirement for home interfaces for session beans.
  • An interceptor facility for session beans and message-driven beans.
  • Reduction of the requirements for usage of checked exceptions.
  • Elimination of the requirement for the implementation of callback interfaces.

Features in EJB 3.1 :

                                   EJB 3.1 has many more features and is even easier to use,lets look into these.

  • Optional Session Bean Business Interfaces
  • Global JNDI Names
  • Singleton Session Beans
  • Asynchronous Session beans
  • Easy packaging
  • EJB 3.1 Embeddable Container

Tuesday, 25 February 2014

Calling Javascript method from Java class

We can also call javascript method from Java file .

1. First create a JS file
    Now lets create a js file myJS.js and put below line in the file

var functionDemo = function() { return "hello user"; };

and save this file in C drive (You can save it in any directory but you have to mention it in the java file)

2. Create a java class which will call this method

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavascriptFunctionCallingFromJava {    

    public static void main(String[] args)
            throws ScriptException, NoSuchMethodException {
    String jsString=null;
    try {
InputStreamReader fd=new FileReader("C:\\myJS.js");
BufferedReader br=new BufferedReader(fd);
try {
jsString=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
}
        ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");        // Retrieving the Javascript engine
        if ( Compilable.class.isAssignableFrom(se.getClass()) ) {
            Compilable c = (Compilable) se;
            CompiledScript cs = c.compile(jsString);//We can compile javascript
            cs.eval();
        } else {
            se.eval(jsString);
        }
        if ( Invocable.class.isAssignableFrom(se.getClass()) ) {
            Invocable i = (Invocable) se;
            System.out.println("What our functionDemo in myJS.js returns is:"
                + i.invokeFunction("functionDemo"));
        } else {
            System.out.println( "calling method not supported");
        }
    }
}

Output :
What our functionDemo in myJS.js returns is:hello


Monday, 24 February 2014

First web application in Struts 2

Hi all, as we all know that usually first application is HelloWorld. So lets make our first web  application in Struts 2 .

So the requirements before creating the web application are given below

1. Eclipse
2. Tomcat
3. Struts library files.

Steps for creating web application in struts 2 using Eclipse is given below:

1. Create dynamic web project :-
                                                       Launch Eclipse, and select menu item  File-> New-> Dynamic Web Project.

1.a. Enter Project Name MyFirstStrutsApp


                                                      
and click Finish button.

2. Add Struts jar files in WEB-INF/lib folder.
                                                                          we need some jar files for making the application which are given below:

commons-fileupload-2.x.x.jar
commons-io-2.x.x.jar
commons-lang-2.x.x.jar
freemarker-2.x.x.jar
ognl-2.x.x
struts2-core-2.x.x.jar
xwork-core-2.x.x.jar

3.Change web.xml 
                               Add controller filter in web.xml file so it can handle all the request .

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>MyFirstStrutsApp</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

4. Create index.jsp file under WEB-INF folder

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<s:set name="theme" value="'simple'" scope="page" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <s:form action="HelloWorld" >
            <s:submit/>            
        </s:form>
    </body>
</html>

5. Create success.jsp 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <h1><s:property value="message" /></h1>
    </body>
</html>

6.Create struts.xml in src folder

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
    <action name="HelloWorld" class="com.techArcher.HelloWorld" >
<result>JSP/success.jsp</result>
        </action>
    </package>
</struts>


7. Now create HelloWorld Action class in com.techArcher package







HelloWorld.java

package com.techArcher;

public class HelloWorld {
private String message;
public String execute()
{
message="Hello User";
return "success";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

8.Now start the server

and enter 
http://localhost:8080/MyFirstStrutsApp/HelloWorld.action






Friday, 21 February 2014

Struts include element

So here in struts configuration file we have a <include> element which is used to make this file easier to maintain for large applications.
It is advisable to divide in smaller files and use <include> element .
We use this element to reference the file and these each file will ideally include
1.doctype
2.Package and struts root element.

<struts>     
<include file="struts1.xml" />
<include file="struts2.xml" />
<include file="struts3.xml" />
</struts>

So each included file should include a package ,
valid doctype.