Monday, September 10, 2012

Story Reader Android Application

As you all know that I have deployed a Story Reader Android Application on Android play market. I am requesting all parents to share stories which they like most. I have decided to share those stories on my story reader android app. Please mention the following details while sharing your stories.



  1. Title of the story
  2. Story contents
  3. Moral of the story
  4. Name of your kid
  5. Standard in which s/he studies
Please share stories on usharadjadhav@gmail.com




Saturday, September 8, 2012

Story Reader Android Application



Story Reader is simple and good application to learn English stories using this application. This application is useful and helpful to parents too. Parents can tell story to their children using this application. Story Reader application is our first try digitize primary and medium education. Parents are welcome to share their ideas to improve this application. Anyone can share stories with us which can be added in this application. 







Essay Reader Android Application


Essay Reader is simple and good application to learn English essay using this application. This application is useful and helpful to parents to teach essay to their children. Essay Reader application is our first try digitize primary and medium education. Parents are welcome to share their ideas to improve this application.

Download Available

Saturday, August 11, 2012

Wednesday, August 8, 2012

Pune Auto Rickshaw Fare Calculator


Pune Auto Rickshaw Fare Calculator is android application works on android 2.1 and above. Its very easy application to calculate the auto fare in single step.
  1. Please enter meter reading which is displayed in auto rickshaw meter like 1.2, 3.7, 4.0 etc.
  2. Output will be displayed to user as Day time auto fare and Night time auto fare.
Pune Auto Rickshaw Fare Calculator




This application valid for Pune, Solapur, Pimpri-Chinchwad, Baramati, Akluj area only.
Download

Sunday, October 2, 2011

Free SMS India - Android and J2ME Apps - For Way2SMS

Want to send free sms in india using way2sms now do not need to use your desktop or laptop. You can download the mobile applications to send the sms free in india naywhere. If you have android operating system mobile or java enabled mobile.

Android OS mobile
You need to download the .apk file from http://way2smsapps.codeplex.com/releases/62599/download/217544
and install it on your mobile. Create account with way2sms and use those credentials for sending free sms anywhere in india.

Java Enabled mobile
You need to download the .jar file from http://way2smsapps.codeplex.com/releases/62563/download/217412
and install it on your mobile. Create account with way2sms and use those credentials for sending free sms anywhere in india.

Monday, September 12, 2011

Java for Mobile - Android

What is Android?

Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The
Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language. 

Features
  • Application framework enabling reuse and replacement of components 
  • Dalvik virtual machine optimized for mobile devices 
  • Integrated browser based on the open source WebKit engine
  • Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
  • SQLite for structured data storage
  • Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
  • GSM Telephony (hardware dependent)
  • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)Camera, GPS, compass, and accelerometer (hardware dependent) 
  • Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

Monday, June 20, 2011

How to Increase Java Heap Memory for Maven 2

The heap size of the JVM used by Maven can be changed using the environment variable MAVEN_OPTS. 


On Windows : 

Update build.bat with following command
set MAVEN_OPTS=-Xmx512m


On Linux (bash shell) :

Update build.sh with following command
export MAVEN_OPTS=-Xmx512m

Thursday, May 12, 2011

Constructor Chaining

We know that constructors are invoked at runtime when you say new on some class type as follows:
Sparrow sparrow = new Sparrow();

Now we will see what really happens when we say new Sparrow()?
(Assume Sparrow extends Bird and Bird extends Object.)
  1. Sparrow constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(), unless the constructor invokes an overloaded constructor of the same class (more on that in a minute). 
  2. Bird constructor is invoked (Bird is the superclass of Sparrow).
  3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Bird extends Object even though you don't actually type "extends Object" into the Bird class declaration. It's implicit.) At this point we're on the top of the stack.
  4. Object instance variables are given their explicit values. By explicit values,we mean values that are assigned at the time the variables are declared,like "int x = 27", where "27" is the explicit value (as opposed to the default value) of the instance variable.
  5. Object constructor completes.
  6. Bird instance variables are given their explicit values (if any).
  7. Bird constructor completes
  8. Sparrow instance variables are given their explicit values (if any). 
  9. Sparrow constructor completes.
You can find below,  how constructors are working in call stack

  1. Object()
  2.  Bird() calls super()
  3.  Sparrow() calls super()
  4. main() calls  new Sparrow()


Tuesday, May 3, 2011

SAR (Service Archive)

SAR file is created with the .sar extenstion same like how other archive files (JAR, WAR, EAR) created. But the purpose of the SAR file is differenet from the other archive files. It is used for deploying a service component in the application server without dependent on other componenets. You can create a seperate componenet as a SAR file and deploy it in the server. When application server starts, the component will be deployed and started running independently. Most of the times these SAR files are used for writing thread related components which has to be running independently.

JBoss's service archive architecture is based on the Java Extension Management (JMX). During the server bootup process, the service archive deployer (SARDeployer) instantiates the JBoss service classes and exposes them as manageable beans through JMX. You can view all of registered JBoss service components in the JBoss JMX Console web application.

Cohesion and Coupling

Cohesion and Coupling deal with the quality of an OO design. Generally, good OO design calls for loose coupling and high cohesion. The goals of OO designs are to make the application

* Easy to Create
* Easy to Maintain
* Easy to Enhance

Coupling:

Coupling is the degree to which one class knows about another class. Let us consider two classes class X and class Y. If class X knows class Y through its interface only i.e. it interacts with class Y through its API then class X and class Y are said to be loosely coupled.

If on the other hand class X apart from interacting class Y by means of its interface also interacts through the non-interface stuff of class Y then they are said to be tightly coupled. Suppose the developer changes the class Y‘s non-interface part i.e non API stuff then in case of loose coupling class X does not breakdown but tight coupling causes the class X to break.

So its always a good OO design principle to use loose coupling between the classes i.e all interactions between the objects in OO system should use the APIs. An aspect of good class Xnd API design is that classes should be well encapsulated.
 
Cohesion:

Cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class, better is the OO design.

Benefits of Higher Cohesion:


* Highly cohesive classes are much easier to maintain and less frequently changed.
* Such classes are more usable than others as they are designed with a well-focused purpose.

Friday, April 29, 2011

HTTP methods and the corresponding servlet methods

HTTP method       HttpServlet method

GET                        doGet()
HEAD                    doHead()
POST                     doPost()
PUT                       doPut()
DELETE                doDelete()
OPTIONS             doOptions()
TRACE                  doTrace()

Monday, April 18, 2011

Nested Classes

A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private.
The following table shows the types of nested classes: 

Types of Nested Classes
Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes

Spring batch the batch processing tool

Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems. Spring Batch builds upon the productivity, POJO-based development approach, and general ease of use capabilities people have come to know from the Spring Framework, while making it easy for developers to access and leverage more advanced enterprise services when necessary.
Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.
Spring Batch is part of Spring framework.

For more information visit http://static.springsource.org/spring-batch/index.html

Sunday, April 17, 2011

What is Hibernate Session?

The main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion of a persistence service.

The lifecycle of a Session is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions.)

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session

Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a get() or load() method is persistent. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and update() or merge() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE. saveOrUpdate() and replicate() result in either an INSERT or an UPDATE.

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

A Session instance is serializable if its persistent classes are serializable.

A typical transaction should use the following idiom:

 Session session = factory.openSession();
 Transaction transaction;
 try {
     transaction = session .beginTransaction();
     //do some work
     ...
     transaction.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     session .close();
 }



If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.

Courtesy: http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/Session.html

Saturday, April 16, 2011

Hibernate : Core Interfaces

Following are Core interfaces provided by Hibernate API
org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query
  1. The Session is main runtime interface between a Java application and Hibernate. This is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not thread safe.
  2. The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. SessionFactory instances are not lightweight and typically only one instance is created for the whole application. If the application accesses multiple databases, then it needs to be one per database.
  3. Criteria is a simplified API for retrieving entities by composing Criterion objects. The Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on Restrictions. This provides a provision for conditional search over the resultset. 
  4. Query represents object oriented representation of a Hibernate query. A Query instance is obtained by calling Session.createQuery().

Wednesday, April 6, 2011

Use of persistence.xml file

The EntityManager API is great, but how does the server/ application know which database it is supposed to save / update / query the entity objects?
How do we configure the underlying object-relational-mapping engine and cache for better performance and trouble shooting? The persistence.xml file gives you complete flexibility to configure the EntityManager.
  • The persistence.xml file is a standard configuration file in JPA.
  • It has to be included in the META-INF directory inside the JAR file that contains the entity beans.
  • The persistence.xml file must define a persistence-unit with a unique name in the current scoped classloader.
  • The provider attribute specifies the underlying implementation of the JPA EntityManager. 
  • In JBoss AS, the default and only supported / recommended JPA provider is Hibernate.
  • The jta-data-source points to the JNDI name of the database this persistence unit maps to e.g. java:/DefaultDS.

Java Display Image Gray

JButton  photoBtn = new JButton();
File file = new File("C:/photos/myImage.jpg");
BufferedImage myImage = ImageIO.read(file);
BufferedImage imageGray = new BufferedImage(myImage.getWidth(), myImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = imageGray.getGraphics();
g.drawImage(myImage, 0, 0, 200, 200, null);
g.dispose();
photoBtn.setIcon(new ImageIcon(imageGray));
photoBtn.revalidate();

The above code display colored image as gray in button as icon.

Tuesday, April 5, 2011

Java 5 Feature : Simple Example: printf vs. println

• General idea
– Each %s entry in formatting string is replaced by next argument in argument list. %n means newline.
• Example
public static void printSomeStrings() {
        String firstName = "Rohit";
        String lastName = "Sharma";
        int numPets = 7;
        String petType = "dogs";
        System.out.printf("%s %s has %s %s.%n", firstName, lastName, numPets, petType);
        //here in above printf statement first '%s' replaced by firstName, second '%s' by lastName likewise '%s' replaced by other variables.
        System.out.println(firstName + " " + lastName +" has " + numPets + " " +petType + ".");
}
• Result:
Rohit Sharma has 7 dogs.
Rohit Sharma has 7 dogs.

Java 5 Feature : Formatted Output: printf

Takes a variable number of arguments
– System.out.printf("Formatting String", arg1, arg2, …);
• Advantages
– Lets you insert values into output without much clumsier String concatenation.
– Lets you control the width of results so things line up
– Lets you control the number of digits after the decimal point in numbers, for consistent-looking output
• Very similar to C/C++ printf function
– If you know printf in C/C++, you can probably use Java's printf immediately without reading any documentation
        • Although some additions in time formatting and locales
– Use String.format to get the equivalent of C's sprintf

Monday, April 4, 2011

Reading Simple Input: the Scanner Class


Basic Syntax
– Attach a Scanner to System.in
– Call nextLine, nextInt, nextDouble, etc

Examples
                  Scanner inputScanner = new Scanner(System.in);
                  String s = inputScanner.nextLine();
                  int i = inputScanner.nextInt();
                 double d = inputScanner.nextDouble();

• Notes
– Scanner for System.in is useful only for simple testing
       • Use a GUI in a real application
– But you can also attach a Scanner to a File, a Socket, a Process,  and more

Java modifiers list with usage and meaning



Modifier Used on Meaning
abstract class

interface

method
Contains unimplemented methods and cannot be instantiated.
All interfaces are abstract. Optional in declarations

No body, only signature. The enclosing class is abstract
final class

method

field

variable
Cannot be subclassed

Cannot be overridden and dynamically looked up

Cannot change its value. static final fields are compile-time constants.

Cannot change its value.
native method Platform-dependent. No body, only signature
none(package) class

interface

member
Accessible only in its package

Accessible only in its package

Accessible only in its package
private member Accessible only in its class(which defines it).
protected member Accessible only within its package and its subclasses
public class

interface

member
Accessible anywhere

Accessible anywhere

Accessible anywhere its class is.
strictfp class

method
All methods in the class are implicitly strictfp.

All floating-point computation done is strictly conforms to the IEEE 754 standard. All values including intermediate results must be expressed as IEEE float or double values.
It is rarely used.
static class

method

field


initializer
Make an inner class top-level class

A class method, invoked through the class name.

A class field, invoked through the class name
one instance, regardless of class instances created.

Run when the class is loaded, rather than when an instance is created.
synchronized method For a static method, a lock for the class is acquired before executing the method. For a non-static method, a lock for the specific object instance is acquired.

transient field Not be serialized with the object, used with object serializations.
volatile field Accessible by unsynchronized threads, very rarely used.

Java reserved words for literal values


false
A boolean literal value.
null
A reference literal value.
true
A boolean literal value.

Sunday, April 3, 2011

Difference IS-A and HAS-A Relationships

 IS-A
 
In OO, the concept of IS-A is based on class inheritance or interface implementation. IS-A is a way of saying; "this thing is a type of that thing."
For example, a Lion is a type of Wild, so in OO terms we can say, "Lion IS-A Wild."  
You express the IS-A relationship in Java through the keywords extends
(for class inheritance) and implements (for interface implementation).

public class Wild{
// Wild Animal code goes here
}
public class Lion extends Wild {
// Important Lion-specific stuff goes here
// Don't forget Lion inherits accessible Wild members which
// can include both methods and variables.
}

HAS-A

HAS-A relationships are based on usage, rather than inheritance HAS-A is a way of saying; "this thing is a part of that thing."
For example, you can say the following, A Company HAS-A Department.
The code might look like this:

public class Company{
private Department department; // department is part of Company
}

Saturday, April 2, 2011

Java Basics


A Java program is mostly a collection of objects talking to other objects by invoking each other's methods. Every object is of a certain type, and that type is defined by a class or an interface. Most Java programs use a collection of objects of many different types.


  • Class A template that describes the kinds of state and behavior that objects of its type support. 

  • Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class.

  • State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state.



  • Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class' logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.

The main() Method in Java

Signature of main() Method

The controlling class of every Java application must contain a main() method having one of the following signatures (the first signature as being the most descriptive of an array of String references which is what is passed in as an argument).

public static void main(String[] args)
public static void main(String args[])



public

The keyword public indicates that the method can be called by any object. 

static

The keyword static indicates that the method is a class method, which can be called without the requirement to instantiate an object of the class. This is used by the Java interpreter to launch the program by invoking the main method of the class identified in the command to start the program.

void

The keyword void indicates that the method doesn't return any value.

args

The formal parameter args is an array of type String, which contains arguments entered at the command line. Note that the args parameter must be specified whether or not the user is required to enter a command-line argument and whether or not the code in the program actually makes use of the argument.

What is Method Signature?

A method signature is a collection of information about the method, as in a C prototype or a forward function declaration in other languages. It includes the method's name, type, and visibility, as well as its arguments and return type.

                                                                             By Patrick Niemeyer & Joshua Peck (O'Reilly)

Architectural benefits of Spring

Before we get down to specifics, let's look at some of the benefits Spring can bring to a project:
  1. Spring can effectively organize your middle tier objects, whether or not you choose to use EJB. Spring takes care of plumbing that would be left up to you if you use only Struts or other frameworks geared to particular J2EE APIs. And while it is perhaps most valuable in the middle tier, Spring's configuration management services can be used in any architectural layer, in whatever runtime environment. 
  2. Spring can eliminate the proliferation of Singletons seen on many projects. In my experience, this is a major problem, reducing testability and object orientation. 
  3. Spring can eliminate the need to use a variety of custom properties file formats, by handling configuration in a consistent way throughout applications and projects. Ever wondered what magic property keys or system properties a particular class looks for, and had to read the Javadoc or even source code? With Spring you simply look at the class's JavaBean properties or constructor arguments. The use of Inversion of Control and Dependency Injection helps achieve this simplification. 
  4. Spring can facilitate good programming practice by reducing the cost of programming to interfaces, rather than classes, almost to zero. 
  5. Spring is designed so that applications built with it depend on as few of its APIs as possible. Most business objects in Spring applications have no dependency on Spring. 
  6. Applications built using Spring are very easy to unit test. 
  7. Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture. You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code. 
  8. Spring helps you solve many problems without using EJB. Spring can provide an alternative to EJB that's appropriate for many applications. For example, Spring can use AOP to deliver declarative transaction management without using an EJB container; even without a JTA implementation, if you only need to work with a single database. 
  9. Spring provides a consistent framework for data access, whether using JDBC or an O/R mapping product such as TopLink, Hibernate or a JDO implementation. 
  10. Spring provides a consistent, simple programming model in many areas, making it an ideal architectural "glue." You can see this consistency in the Spring approach to JDBC, JMS, JavaMail, JNDI and many other important APIs.

Friday, April 1, 2011

Disadvantages of Hibernate

  1. Steep learning curve.
  2. Use of Hibernate is an overhead for the applications which are :(1)simple and use one database that never change. (2)need to put data to database tables, no further SQL queries(3)there are no objects which are mapped to two different tables. Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice
  3. Support for Hibernate on Internet is not sufficient.
  4. Anybody wanting to maintain application using Hibernate will need to know Hibernate
  5. For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.
  6. Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.

Difference JDBC and Hibernate

Open-Source, Zero-Cost Product License
Hibernate is an open source and free to use for both development and production deployments

Enterprise-Class Reliability and Scalability
Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. JDBC can not be scaled easily.

Automatic Versioning and Time Stamping
By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow to save it because this user does not has updated data. In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

Optimize Performance
Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand-coding.

Database Dependent Code
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

Maintenance Cost
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

Support for Query Language
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

Transparent Persistence
The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

Relational Persistence for JAVA
Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.