Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Monday, January 1, 2018

few defensive coding techniques

Here is a guide to a few guarded (defensive) coding techniques:

(1) Guarding against string nulls

if (StringUtils.isNotBlank(inputString)) {
    // Process
}

Will return false if inputString is blank, spaces or null

(2) Guarding against empty List

A list may be not null, yet it can be empty – to check if the list does contain any elements

If (list != null && !list.isEmpty) {
        // Processing
}
Note: If an instanceof check is present, an extra null check is not required

(3) Boolean  can have 3 values (not 2) – true, false and null.

So, Boolean isVerified = getVerified(…)

Assume isVerified is null, in that case below would fail.

if (isVerified)  {
         // process
}


Instead:

BooleanUtils.isTrue(Boolean.TRUE)  = true
BooleanUtils.isTrue(Boolean.FALSE) = false
BooleanUtils.isTrue(null)          = false


if (BooleanUtils.isTrue(isVerified)) {
      // process
}

(4) A list contains different objects 

Say, List fruits = new ArrayList();
fruits.add(new Apple())
fruits.add(new Orange())

while (iterator.hasNext()) {
    Apple apple = (Apple) iterator.next() ; This code will fail with a classcast
}

Adding instanceof check:

while (iterator.hasNext()) {
            Object o = iterator.next() ;
            if (o instanceof Apple) {
                        Apple apple = (Apple) o;
            }
}


(5) Ensuring numeric checks are present

Backdrop: Say the following code can fail with a NumberFormat if the ageofdriver is not numeric

int driverAge = Integer.parseInt(ageOfDriver);

One of the defensive way of writing that would be as follows:

if (StringUtils.isNotBlank(ageOfDriver) && StringUtils.isNumeric(ageOfDriver)) {
      int driverAge = Integer.parseInt(ageOfDriver);

}

Thursday, May 15, 2014

Java Mail API example

package com.org.sbollam;



import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;

public class SendMailExample {
    public static void main(String[] args) {
        String msg = " Mail sent successfully (java mail service application)";
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        //props.put("mail.smtp.socketFactory.port", "465");
       // props.put("mail.smtp.socketFactory.class",
        //        "javax.net.ssl.SSLSocketFactory");
      //  props.put("mail.debug", "true");  // Debug the program
        props.put("mail.smtp.auth", "true");
        //props.put("mail.smtp.port", "465");
        props.put("mail.transport.protocol", "smtp");

        Session session = Session.getDefaultInstance(props,
          new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("*****@gmail.com","*****@***");
                }
            });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("*****@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("****@gmail.com"));
            message.setSubject(" **SAI HAI- ** ");
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //message body
            messageBodyPart.setText("**************** SAY Hi TO,  How R U *************** ");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            //attachment
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource("C:\\Users\\demo\\Desktop\\hai.txt");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName("hai.txt");
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
       
            Transport.send(message);

            //System.out.println("Email sent successfully using this java application");
        } catch (MessagingException e) {
            msg = "Error while sending";
            throw new RuntimeException(e);
        }
        JOptionPane.showMessageDialog(null, msg);
    }
}

Thursday, December 5, 2013

JDBC vs Hibernate

JDBC 
Hibernate 
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. 
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  
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.  
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.  
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.  
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.  
With JDBC, caching is maintained by hand-coding.  
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.  
In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  
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 saving it because this user does not have updated data.  

Thursday, May 23, 2013

How to print GC details into a file for your program?

 For your local program (for example - say you have written a standalone DOM xml parser or any memory intensive program on which you want to check GC*  usage).

In RAD (for IBM JVM) --> right click on the java class --> goto "Run As" --> goto "Run configurations" --> goto "Arguments" tab in the pop-up --> set the below under VM arguments

-Xverbosegclog:D:\Your_Path\Your_Sub_Path\jvm.log

On a Sun JVM:
  -Xloggc:C:\Your_Path\jvm.log -verbose:gc -XX:+PrintGCDateStamps
(if there are spaces in folder or file names, it will be interpreted as another VM argument)
Then Run your program. GC details will be logged in that file (jvm.log in this case)

* GC- Garbage Collector
Referene:

http://stackoverflow.com/questions/1161647/how-to-redirect-verbose-garbage-collection-output-to-a-file

JVM Architecture

The Java Virtual Machine (JVM) is an abstract computing machine. The JVM is a program that looks like a machine to the programs written to execute in it. This way, Java programs are written to the same set of interfaces and libraries. Each JVM implementation for a specific operating system, translates the Java programming instructions into instructions and commands that run on the local operating system. This way, Java programs achieve platform independence.
        The Java virtual machine knows nothing of the Java programming language, only of a particular binary format, the class file format. A class file contains Java virtual machine instructions (or bytecodes) and a symbol table, as well as other ancillary information.
For the sake of security, the Java virtual machine imposes strong syntactic and structural constraints on the code in a class file. However, any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java virtual machine. Attracted by a generally available, machine-independent platform, implementors of other languages can turn to the Java virtual machine as a delivery vehicle for their languages.

 

Exploring the JVM Architecture

Hotspot Architecture

The HotSpot JVM possesses an architecture that supports a strong foundation of features and capabilities and supports the ability to realize high performance and massive scalability. For example, the HotSpot JVM JIT compilers generate dynamic optimizations. In other words, they make optimization decisions while the Java application is running and generate high-performing native machine instructions targeted for the underlying system architecture. In addition, through the maturing evolution and continuous engineering of its runtime environment and multithreaded garbage collector, the HotSpot JVM yields high scalability on even the largest available computer systems.

The main components of the JVM include the classloader, the runtime data areas, and the execution engine.

Key Hotspot Components

The key components of the JVM that relate to performance are highlighted in the following image.




There are three components of the JVM that are focused on when tuning performance. The heap is where your object data is stored. This area is then managed by the garbage collector selected at startup. Most tuning options relate to sizing the heap and choosing the most appropriate garbage collector for your situation. The JIT compiler also has a big impact on performance but rarely requires tuning with the newer versions of the JVM.

Tuesday, May 21, 2013

JVM Memory


•Eden Space (heap): The pool from which memory is initially allocated for most objects.
•Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
•Tenured Space (heap): The pool containing objects that have existed for some time in the survivor space.
•Perm Space (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
•Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Sunday, April 21, 2013

Access Specifiers and Access Modifiers

All the four access specifiers, Java supports, can be applied to variables – public,protecteddefault and private. If the specifier is not mentioned, it takes default access. A local variable must be default only.The two access specifiers a class can accept are public or defaultDefault means the specifier is not mentioned at all.

The list of modifiers are : public, protected,default,private,abstract,final, static.


Type Conversions in Java

This summary is not available. Please click here to view the post.

Thursday, March 14, 2013

Shallow Cloning and Deep Cloning in Java

Cloning is of 2 Types:

1. Shallow Cloning  2. Deep Cloning

Whenever clone() method is used 2 different objects are created in 2 different memory locations. So
separate memory is occupied.

If a class contains  X, Y variable and clone is applied two different objects are created in two different situations.

In Shallow Cloning  main problem is instance variables are common for both objects , so if one object is modifed then automatically second object is also modified.

In deep cloning 2 different objects are created in 2 different memory locations , if in case original object is modified then also its duplicate object won't effect , why because there is  no relation between original and duplicate object.



Wednesday, March 13, 2013

different ways to create an object in Java

There are 4 ways of creating objects in Java.

1. Using new operator

Employee emp = new Employee();

Here , we are creating Employee class object  'emp' using new operator.

2. Using factrory methods:

NumberFormat nf  = NumberFormat.getNumberInstace();

Here, we are creatig NumberFormat object using the factory method getNumberInstacne().

3. Using newInstance() method .

(a) First,store the class name  'Employee' as string into an  object. For this purpose , factory method
forName() of the class 'Class' will be useful.

Class c = Class.forName("Employee");

Note: class with the name 'Class' in java.lang package.
(b) create another object to the class whose name is in the object c . For this purpose , we need
newInstance()  method of the class 'Class' . as:

Employee obj = (Employee)c.newInstance();

4. By cloning an already available object, we can create another object . Creating exact copy of an
existing object is called 'cloning':

Employee obj1 = new Employee();
Employee obj2 = (Employee)obj1.clone();

Constructor VS Method in Java

Constructor
 Method
A constructor is used to initialize the instance variables of a class.
A Method is used for any general purpose processing or calculations.
A constructors name and class name should be same.
A method’s name and class name can be same or different.
A constructor is called at the time of creating the object.
A method can be called after creating the object.
A Constructor  is called only once per object.
A method can be called several times on the object.
A constructor is called and executed automatically.
A method is executed only when we call it.


Tuesday, March 12, 2013

Difference between Set and List in Java

Set:

1. A set represents a collection of elements . Order of the elements may change in the set.
2. Set will not allow duplicate values to be stored.
3. Accessing elements by their index(position number) is not possible in case of sets.
4.Sets will not allow null elements.

List:

1. A List represents ordered collection of elements . List preserves the order of elements in
which they are entered.
2. List will allow duplicate value.
3.Accessing elements by index is possible in lists.
4. Lists allow null elements to be stored.

Sunday, March 10, 2013

Difference between HashMap and Hashtable in Java

HashMap:

1. HashMap object is not synchronized by default.
2. In case of a single thread , using HashMap is faster than the Hashtable.
3. HashMap allows null keys and null values to be stored.
4. Iterator in the HashMap is fail-fast . This means iterator will produce exception if concurrent
updates are made to the HashMap.
5. We can make HashMap object synchronied using synchronizedMap() method as:

Collections.synchronizedMap(new HashMap())

Hashtable:

1. Hashtable object is synchronized by default.
2.In case fo multiple threads , using Hashtable is advisable. With a single thread, Hashtable
becomes slow.
3.Hashtable does not allow null keys or values.
4.Enumeration for the Hashtable is not fail-fast. This means even if concurrent updations
are done to to Hashtable, there will not be any incorrect results produced by the Enumeration.


Saturday, March 9, 2013

Difference between ArrayList and Vector in Java

ArrayList:
---------------
1.Array List object is not synchronized by default.
2.In case of a single thread ,using ArrayList is faster than the vector.
3.ArrayList increases its size every time by 50 percent(half).

4. We can synchronize Arraylist using synchronizedList() mehtod as:

List  l = Collections.SynchronizedList(new ArrayList());

Vector:
--------
1.Vector object is synchronized by default.
2. In case of multiple threads, using Vector is advisable. With a single  thread,
   Vector becomes slow.
3. Vector increases its size every time by doubling it.

Friday, March 8, 2013

difference between sleep() and wait() in Java

Both the sleep() and wait() methods are used to suspend a thread execution for a specified time.
When sleep() is executed inside a synchronized block, the object is still under lock .

When wait() method is executed,it breaks the synchronized block , so that the object lock is removed
and it is available.

Generally , sleep() is used for making a thread to wait for some time.But wait() is used in connection
with notify()  or notifyAll() methods in thread communication.

sleep method present in Thread class, wait method present in Object class.
sleep method is static , wait is non static method

Wednesday, February 27, 2013

Difference between Abstract class and Interface

Abstract Class
==========
1.An abstract class can have method body (non-abstract methods).
2.An abstract class can have instance variables.
3.An abstract class can have constructor.
4.An abstract class can have static methods.
5.You can extends one abstract class.

ex:
publlic abstract class TxnCommand
{

public abstract void  show();

public void calculate()
{
//Method Implimentatiion;
}

}

Interface
=======
1.Interface have only abstract methods.
2.An interface cannot have instance variables.
3.Interface cannot have constructor.
4.Interface cannot have static methods.
5.You can implement multiple interfaces.

ex:


public
interface CommonCommand
{

public static final int i = 10;
public abstract void  show();

}

difference between static method and instance method in Java

Static Method:
===========
1.A method i.e. declared as static is known as static method.
2.Object is not required to call static method.
3.Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly.
4.For example: public static void show(){..... }.


Instance Method:
============
1.A method i.e. not declared as static is known as instance method.
2.Object is required to call instance methods.
3.static and non-static variables both can be accessed in instance methods.
4.For example: public void show(){...}.


 

Tuesday, February 19, 2013

System.out.println() In Java?

 In Java, the dot operator can only be used to call methods and variables so we know that ‘out’ must be either a method or a variable. Now, how do we categorize ‘out’? Well, ‘out’ could not possibly be a method because of the fact that there are no parentheses – the ‘( )’ – after ‘out’, which means that out is clearly not a method that is being invoked. And, ‘out’ does not accept any arguments because only methods accept arguments – you will never see something like “System.out(5,6).println”. This means ‘out’ must be a variable.

We now know that ‘out’ is a variable, so we must now ask ourselves what kind of variable is it? There are two possibilities – it could be a static or an instance variable. Because ‘out’ is being called with the ‘System’ class name itself, and not an instance of a class (an object), then we know that ‘out’ must be a static variable, since only static variables can be called with just the class name itself. So now we know that ‘out’ is a static member variable belonging to the System class.

The fact that ‘println()’ is clearly a method, we can further classify ‘out’. We have already reasoned that ‘out’ is a static variable belonging to the class System. But now we can see that ‘out’ must be an instance of a class, because it is invoking the method ‘println()’.

When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().

The more exact answer to the original question is this: inside the System class is the declaration of ‘out’ that looks like: ‘public static final PrintStream out’, and inside the Prinstream class is a declaration of ‘println()’ that has a method signature that looks like: ‘public void println()’.

Here is what the different pieces of System.out.println() actually look like:
//the System class belongs to java.lang package
class System {
  public static final PrintStream out;
  //...
}

//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}

Tuesday, February 12, 2013

Scope of Static variables


Static variables cannot be elected for garbage collection while the class is loaded. They can be collected when the respective class loader (that was responsible for loading this class) is itself collected for garbage.


Monday, February 11, 2013

A JiBXException occurred while Unmarshal of request string

This is generally related to :

1. Might may be because of Jars mismatch i.e. There is a mismatch in the jar compilation versions

2. Jars are not builde properly i.e. some classes are missing while builidin Jars.