Tuesday 22 December 2015

Java - Comparing two BigDecimal numbers

Comparing two BigDecimal Numbers :
java.math.BigDecimal.compareTo(BigDecimal val) compares the BigDecimal Object with the specified BigDecimal value.
JAVA PROGRAM :
import java.math.BigInteger;
public class BigIntegerTest {
public static void main(String[] args) {
// create 2 BigInteger objects
        BigInteger big1, big2;
        big1 = new BigInteger("6"); //first number
        big2 = new BigInteger("3"); // second number
        // create int object
        int res;
        // compare bi1 with bi2
res = big1.compareTo(big2);  
if( res == 0 )
System.out.println( "Both values are equal " );
else if( res == 1 )
System.out.println( "First Value is greater " );
else if( res == -1 )
System.out.println( "Second value is greater" );
System.out.println("comparing with zero");
if(big1.compareTo(BigInteger.ZERO)> 0)
{
System.out.println("bi1 is greater ");
}
       }
}


Friday 18 December 2015

JAVA - Generating Barcode and adding to a pdf

Generating Barcode and adding to a pdf :
Barcode can be easily generated through barcode4j.jar, which can be downloaded from many sites. Moreover, its integration with the PDF file can done through itextpdf jar.

Here is a complete program to generate bar code and integrate with pdf file. You need to download these two jars and add in libraries.

import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
public class barcodeGeneration {

public static void main(String[] args) {
Code128Bean obj = new Code128Bean();
obj.setHeight(15f);
obj.setModuleWidth(0.3);
obj.setQuietZone(10);
obj.doQuietZone(true);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
obj.generateBarcode(canvas, "1234567890");

try {
canvas.finish();
//writing bar to png file
FileOutputStream fos = new FileOutputStream("barcode.png");
fos.write(baos.toByteArray());
fos.flush();
fos.close();
//writing  to pdf
Image png = Image.getInstance(baos.toByteArray());
png.setAbsolutePosition(400, 685);
png.scalePercent(25);
Rectangle rec = new Rectangle(595,595,842,842);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("barcodeFile.pdf"));
document.open();
document.add(png);
document.close();
writer.close();
} catch (FileNotFoundException e) {
System.out.println("file not foundException");
e.printStackTrace();
} catch (BadElementException e) {
System.out.println("BadExcption");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} catch (DocumentException e) {
System.out.println("DocumentException");
e.printStackTrace();
}
}

}

Wednesday 16 December 2015

Java - Left padding a Number with Zeros

Left padding a Number with Zeros :
If  you have a number e.g num=1234 then you can directly use them in String.format() function, else if you have a String that contains only numeric value then convert them to integer and then use the String.format() function to do left padding.

Examples:
int yournumber = 67;
String.format("%05d", yournumber);
for zero-padding with length=5.

String mystring = "12";
String.format("%010d", Integer.parseInt(mystring));
for zero-padding with length=10.


Jboss EAP 6.1 Configuration for Auto Reconnecting to DataBase

Jboss EAP 6.1 Configuration for Auto Reconnecting to DataBase 
This is the configuration that we need to include in datasource configuration in JBoss EAP 6.1 if we want the Jboss EAP 6.1 to automatically re-connect to the database in case DB is crased and is restarted.
Otherwise, we will have to restart the jboss application to again reconnect with the DB.

<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker"/>
<stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLStaleConnectionChecker"/>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter"/>
<check-valid-connection-sql>select 1</check-valid-connection-sql>
<validate-on-match>true</validate-on-match>                      
<use-fast-fail>true</use-fast-fail>                      
</validation>

The following is the live example for Postgres DB:
<datasource jndi-name="java:jboss/datasources/ExampleDB" pool-name="ExampleDB" enabled="true" use-java-context="true">
<connection-url>jdbc:postgresql://localhost:5432/EXAMPLE_DB</connection-url>
                    <driver>postgres</driver>
                    <security>
                        <user-name>postgres</user-name>
                        <password>postgres</password>
                    </security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker"/>
<stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLStaleConnectionChecker"/>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter"/>
<check-valid-connection-sql>select 1</check-valid-connection-sql>
<validate-on-match>true</validate-on-match>                        
<use-fast-fail>true</use-fast-fail>                        
</validation>
</datasource>

Tuesday 15 December 2015

Program to find the Next Palindrome Number

JAVA Program to find Next PALINDROME NUMBER

import java.*;
public class NextPalindromNumber {
public static void main(String[] args) {
//String  num = "123450";
String num=args[0];
int len=num.length();
if(len%2 == 1)
{       int m=len/2;
String substr1 =num.substring(0, m);
//System.out.println("substring1 : " + substr1);
String substr2 = num.substring(m+1);
//System.out.println("substring2 : "+ substr2);
String revsubstr1 = new StringBuilder(substr1).reverse().toString();
if(revsubstr1.equals(substr2))
{
                           System.out.println("Number is already a palindrome");
}
else
{      int num1=Integer.parseInt(revsubstr1);
int num2=Integer.parseInt(substr2);
if(num2 > num1)
{
char c = num.charAt(m);
//System.out.println("char at middle :" + c);
if(Character.getNumericValue(c)==9)
{
String res0=num.substring(0,m);
int value = Integer.parseInt(res0);
value++;
res0=value+"";
String res2=new StringBuilder(res0).reverse().toString();

String res1=res0 +"0" + res2;
System.out.println(res1);
}
else
{
int x = Character.getNumericValue(c)+1;
//System.out.println(x);
String res0=num.substring(0,m) ;
String res2=new StringBuilder(res0).reverse().toString();
String res1=res0 + x+ res2;
System.out.println(res1);
}
}
else
{
String res0=num.substring(0,m);
String res2=new StringBuilder(res0).reverse().toString();
String res1=num.substring(0, m+1)+res2;
System.out.println(res1);
}
}
}
else
{ int m=len/2;
String substr1 =num.substring(0, m);
String substr2 = num.substring(m);
String revsubstr1 = new StringBuilder(substr1).reverse().toString();
int num1=Integer.parseInt(revsubstr1);
int num2=Integer.parseInt(substr2);
if(num2>num1)
{
int value=Integer.parseInt(substr1);
value++;
String res0=value+"";
String res2=new StringBuilder(res0).reverse().toString();
String res1=res0+res2;
System.out.println(res1);
}
else
{
String res2=new StringBuilder(substr1).reverse().toString();
String res1=substr1+res2;
System.out.println(res1);
}
}
}

}

Sunday 13 December 2015

Normalization of Database

While designing a database out of an entity–relationship model, the main problem existing in that “raw” data is redundancy. Redundancy is storing the same data item in more one place. A redundancy creates several problems like the following:
  1. Extra storage space: storing the same data in many places takes large amount of disk space.
  2. Entering same data more than once during data insertion.
  3. Deleting data from more than one place during deletion.
  4. Modifying data in more than one place.
  5. Anomalies may occur in the database if insertion, deletion, modification etc are not done properly. It creates inconsistency and unreliability in the database.
To solve this problem, the “raw” database needs to be normalized. This is a step by step process of removing different kinds of redundancy and anomaly at each step. At each step a specific rule is followed to remove specific kind of impurity in order to give the database a slim and clean look.
Normalization is a systematic approach of dividing a table into different small tables to eliminate data redundancy and undesirable characteristics like Insertion, Update and Deletion Anomalies. It is a multi-step process that puts data into small tabular form by removing duplicated data from the a large relation table.

Normalization is used for mainly two purpose:
1. Eliminating redundant (useless) data.
2. Ensuring data dependencies make sense i.e data is logically stored.

Problem Without Normalization

Without Normalization, it becomes difficult to handle and update the database, without facing data loss. Insertion, Updation and Deletion Anamolies are very frequent if Database is not Normalized. To understand these anomalies let us take an example of Student table.
S_idS_NameS_AddressSubject_opted
401AdamNoidaBio
402AlexPanipatMaths
403StuartJammuMaths
404AdamNoidaPhysics

  • Updation Anamoly : To update address of a student who occurs twice or more than twice in a table, we will have to update S_Address column in all the rows, else data will become inconsistent.
  • Insertion Anamoly : Suppose for a new admission, we have a Student id(S_id), name and address of a student but if student has not opted for any subjects yet then we have to insert NULL there, leading to Insertion Anamoly.
  • Deletion Anamoly : If (S_id) 401 has only one subject and temporarily he drops it, when we delete that row, entire student record will be deleted along with it.

Normalization Rule

Normalization rule are divided into following normal form.
  1. First Normal Form
  2. Second Normal Form
  3. Third Normal Form
  4. BCNF

First Normal Form (1NF)

As per First Normal Form, no two Rows of data must contain repeating group of information i.e each set of column must have a unique value, such that multiple columns cannot be used to fetch the same row. Each table should be organized into rows, and each row should have a primary key that distinguishes it as unique.
The Primary key is usually a single column, but sometimes more than one column can be combined to create a single primary key. For example consider a table which is not in First normal form
Student Table :
StudentAgeSubject
Adam15Biology, Maths
Alex14Maths
Stuart17Maths
In First Normal Form, any row must not have a column in which more than one value is saved, like separated with commas. Rather than that, we must separate such data into multiple rows.
Student Table following 1NF will be :
StudentAgeSubject
Adam15Biology
Adam15Maths
Alex14Maths
Stuart17Maths
Using the First Normal Form, data redundancy increases, as there will be many columns with same data in multiple rows but each row as a whole will be unique.

Second Normal Form (2NF)

As per the Second Normal Form there must not be any partial dependency of any column on primary key. It means that for a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence. If any column depends only on one part of the concatenated key, then the table fails Second normal form.
In example of First Normal Form there are two rows for Adam, to include multiple subjects that he has opted for. While this is searchable, and follows First normal form, it is an inefficient use of space. Also in the above Table in First Normal Form, while the candidate key is {StudentSubject}, Age of Student only depends on Student column, which is incorrect as per Second Normal Form. To achieve second normal form, it would be helpful to split out the subjects into an independent table, and match them up using the student names as foreign keys.
New Student Table following 2NF will be :
StudentAge
Adam15
Alex14
Stuart17
In Student Table the candidate key will be Student column, because all other column i.e Age is dependent on it.
New Subject Table introduced for 2NF will be :
StudentSubject
AdamBiology
AdamMaths
AlexMaths
StuartMaths
In Subject Table the candidate key will be {StudentSubject} column. Now, both the above tables qualifies for Second Normal Form and will never suffer from Update Anomalies. Although there are a few complex cases in which table in Second Normal Form suffers Update Anomalies, and to handle those scenarios Third Normal Form is there.

Third Normal Form (3NF)

Third Normal form applies that every non-prime attribute of table must be dependent on primary key, or we can say that, there should not be the case that a non-prime attribute is determined by another non-prime attribute. So this transitive functional dependency should be removed from the table and also the table must be in Second Normal form. For example, consider a table with following fields.
Student_Detail Table :
Student_idStudent_nameDOBStreetcityStateZip
In this table Student_id is Primary key, but street, city and state depends upon Zip. The dependency between zip and other fields is called transitive dependency. Hence to apply 3NF, we need to move the street, city and state to new table, with Zip as primary key.
New Student_Detail Table :
Student_idStudent_nameDOBZip
Address Table :
ZipStreetcitystate

The advantage of removing transtive dependency is,
  • Amount of data duplication is reduced.
  • Data integrity achieved.

Boyce and Codd Normal Form (BCNF)

Boyce and Codd Normal Form is a higher version of the Third Normal form. This form deals with certain type of anamoly that is not handled by 3NF. A 3NF table which does not have multiple overlapping candidate keys is said to be in BCNF. For a table to be in BCNF, following conditions must be satisfied:
  • R must be in 3rd Normal Form
  • and, for each functional dependency ( X -> Y ), X should be a super Key.
BCNF Normal Form

How to connect to My SQL and Postgres through Java Programs

My SQL Connection String in JAVA :

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driver = "com.mysql.jdbc.Driver";
    String connection = "jdbc:mysql://localhost:3306/YourDBName";
    String user = "root";
    String password = "root";
    Class.forName(driver);
    Connection con = DriverManager.getConnection(connection, user, password);
    if (!con.isClosed()) {
      con.close();
    }
  }
}

Postgres Connection String in JAVA :

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);

OR-
String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);
user = String
The database user on whose behalf the connection is being made.

password = String
The database user's password.