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

Sunday, October 30, 2016

How to start using DerbyDB with Netbean?

Why we need to use DerbyDB, fisrt of all , it is shipped a long with Java JDK,

If you first learn Java and want to learn How Java work with Database,

We can use DerbyDB, Because we dont need to install a new DB that reason.

Another reason, I am wonder, how to use all tools shipped by Java JDK,

First Open Netbean,

Check Derby database configuration

Check configuration of JavaDB Choose location of JavaDB installed on your machine, normally the

DerbyDB was shipped along with JDK

 Right click on JavaDB --> Choose create new DB



After create DB success, a new database connection automatically created by Netbean,



Click on connect to



Netbean will automatically startup DerbyDB and Connect to that data.



 Now database is ready for futher more steps.

Saturday, October 22, 2016

Serialization and Deserialization JSON in JAVA with GSON

Hello,

Today I will give an example of using GSON to Serialization and Deserialization JSON in JAVA

When we work with JSON, there are some tasks we usually do,

  1. Parse Object to JSON and vice versa
  2. Parse Collection to JSON and vice versa
  3. And sometime we need to create an JSON object with dynamic field, In my example I used Map to do it.We also need to Deserialization and JSON object with dynamic field to Java Object


Here is some code example:


package com.blogspot.ducnguyen.dev.json.example;

import com.google.gson.Gson;
import java.awt.Point;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author ducnguyen
 */
public class Main {

    private static Gson gson = new Gson();

    public static void main(String[] args) {
        System.out.println("Serialization and Deserialization an OBJECT");
        Point p1 = new Point(2, 1);
        String json1 = gson.toJson(p1);
        System.out.println("p1 -> json1 : " + json1);
        Point p2 = gson.fromJson(json1, Point.class);
        System.out.println("json1 -> p2 : " + p2.toString());

        System.out.println("Serialization and Deserialization a LIST");
        List l1 = Arrays.asList(new Point(2, 1), new Point(3, 4));
        String json2 = gson.toJson(l1);
        System.out.println("l1 -> json2 : " + json1);
        List l2 = gson.fromJson(json2, List.class);
        System.out.println("json2 -> l2 : " + l2.toString());

        System.out.println("Create object fields with MAP");
        Map jsonObject = new HashMap<>();
        jsonObject.put("integer", 100);
        jsonObject.put("string", "hello world");
        jsonObject.put("boolean", Boolean.TRUE);
        String json3 = gson.toJson(jsonObject);
        System.out.println("jsonObject -> json3 : " + json3);
        System.out.println("Deserialization MAP");
        Map jsonObject2 = gson.fromJson(json3, Map.class);
        System.out.println("json3 -> jsonObject2 : "+ jsonObject2.toString());

    }

}




Here is output of the code:

Serialization and Deserialization an OBJECT
p1 -> json1 : {"x":2,"y":1}
json1 -> p2 : java.awt.Point[x=2,y=1]
Serialization and Deserialization a LIST
l1 -> json2 : {"x":2,"y":1}
json2 -> l2 : [{x=2.0, y=1.0}, {x=3.0, y=4.0}]
Create object fields with MAP
jsonObject -> json3 : {"integer":100,"string":"hello world","boolean":true}
Deserialization MAP
json3 -> jsonObject2 : {integer=100.0, string=hello world, boolean=true}


You can download source code here

Wednesday, October 5, 2016

Java8 - Working with Base64

In JDK8, It is supported Base64 decode/encoding,

Here is an example of using Base64



package my.example.java.base64;

import java.util.Base64;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author nvduc
 */
public class Base64Test {

    public Base64Test() {
    }

    @Test
    public void test() {
        String origin = "Hello World";
        String base64 = new String(Base64.getEncoder().encode(origin.getBytes()));
        String fromBase64 = new String(Base64.getDecoder().decode(base64));
        System.out.println("text Encoded : " + base64);
        System.out.println("text Decoded : " + fromBase64);
        Assert.assertEquals(origin, fromBase64);
    }
}

You can find this example code on Github

Wednesday, September 21, 2016

Java - Create image inside a rectangle

Here is an example put image into a rectangle, with calculation to keep full width of image:


package my.example.image;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import javax.imageio.ImageIO;

public class ImageInRectange {

    public static void main(String[] args) throws IOException {
        createImageInRectagle(512, 1024, new File("./src/main/resources/chelsea.png"));
    }

    public static File createImageInRectagle(int width, int height, File image) throws IOException {
        Image originImage = ImageIO.read(image);
        int oImgWidth = originImage.getWidth(null);
        int oImgHeight = originImage.getHeight(null);
        float imageRatio = (float) oImgHeight / oImgWidth;
        float rectangleRatio = (float) width / height;

        BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        BufferedImage bufferedImage = ImageIO.read(image);
        Graphics g2 = combined.getGraphics();
        Point p = new Point(0, 0);
        if (Math.abs(imageRatio - rectangleRatio) < 0.05) {
            bufferedImage = scale(bufferedImage, width, height);
            p.x = 0;
            p.y = 0;
        } else {
            int minEdge = width < height ? width : height;
            if (oImgHeight > oImgWidth) {
                float diff = (float) oImgHeight / minEdge;
                int newWidth = Math.round(oImgWidth / diff);
                bufferedImage = scale(bufferedImage, newWidth, minEdge);
                if (minEdge == height) {
                    p.x = Math.abs((width - newWidth) / 2);
                    p.y = 0;
                } else {
                    p.x = 0;
                    p.y = Math.abs((height - minEdge) / 2);
                }
            } else {
                float diff = (float) oImgWidth / minEdge;
                int newHeight = Math.round(oImgHeight / diff);
                bufferedImage = scale(bufferedImage, minEdge, newHeight);
                if (minEdge == height) {
                    p.x = Math.abs((width - minEdge) / 2);
                    p.y = 0;
                } else {
                    p.x = 0;
                    p.y = Math.abs((height - newHeight) / 2);
                }
            }
        }
        g2.drawImage(bufferedImage, p.x, p.y, null);
        g2.dispose();
        File tempImage = Paths.get("target", "ok.png").toFile();
        ImageIO.write(combined, "png", tempImage);
        return tempImage;
    }

    public static BufferedImage scale(BufferedImage imgb, int newWidth, int newHeight) {
        Image image;
        image = imgb.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        return toBufferedImage(image);
    }

    public static BufferedImage toBufferedImage(Image img) {
        if (img instanceof BufferedImage) {
            return (BufferedImage) img;
        }
        BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(img, 0, 0, null);
        bGr.dispose();
        return bimage;
    }
}

You can find source code on Github

Wednesday, September 14, 2016

APACHE PDFBOX EXAMPLE WITH MAVEN

Here is an example of create a Maven project using Netbean.

In this example, I used Apache PDFBox as an example of using maven for managing Java library

1. We create a new project using Netbean:



New Maven project with Netbean

Input the artifactId and package name


2. Add code


Declare maven dependenies


    4.0.0
    com.blogspot.ducnguyen.dev
    pdfbox-example
    1.0-SNAPSHOT
    jar
    
        UTF-8
        1.7
        1.7
    
    
        
        
            org.apache.pdfbox
            pdfbox
            2.0.0
        
    



Add Java Code:
package com.blogspot.ducnguyen.dev.pdfbox.example;

import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
 *
 * @author nvduc
 */
public class Main {
    public static void main(String[] args) throws IOException
    {
        long timestamp = System.currentTimeMillis();
        String filename = "test-"+timestamp+".pdf";
        String message = "Hello World at : "+ timestamp;
        
        PDDocument doc = new PDDocument();
        try
        {
            PDPage page = new PDPage();
            doc.addPage(page);
            
            PDFont font = PDType1Font.HELVETICA_BOLD;

            PDPageContentStream contents = new PDPageContentStream(doc, page);
            contents.beginText();
            contents.setFont(font, 12);
            contents.newLineAtOffset(100, 700);
            contents.showText(message);
            contents.endText();
            contents.close();
            
            doc.save(filename);
        }
        finally
        {
            doc.close();
        }
    }
}



3. Running


Before running, we must build project, When we build, maven will get pdfbox library from maven repository

Build project in NetBean



Right click on Main.java file, Choose Run File

We can check the result in Files view

Result after choose Run File

You can check the source code on Github

Tuesday, November 5, 2013

Java Enum Example

Here is an example of Enum in Java
public class EnumExample {
    public static void main(String []args){
        
        System.out.println(SearchCriteriaComparisonExpression.equal);
        System.out.println(SearchCriteriaComparisonExpression.equal.sqlExpression());
        
        for(SearchCriteriaComparisonExpression value: SearchCriteriaComparisonExpression.values()){
            System.out.println(value.name()+" | "+value);
            
        }
        System.out.println();
    }

    
}
enum SearchCriteriaComparisonExpression {

    /**
     *
     */    
    equal("equal") , // equal (=)    
    notequal("notequal"), // Not equal (<>)
    greaterthan("gt"), // Greater Than (>)
    greaterthanorequal("ge"), // Greater Than or equal (>=)
    lessthan("lt"), // // Less Than (<)
    lessthanorequal("le"), // Less Than or equal (<=)       
    isnull("isnull"), // IS NULL
    isnotnull("isnotnull"); // IS NOT NULL
    
    private String expression;
   
    private SearchCriteriaComparisonExpression(String expression) {
        this.expression = expression;       
    }
       
    @Override
    public String toString() {        
        return this.expression.toLowerCase();
    }

    public String sqlExpression() {
        String value = "";
        if (this.compareTo(equal) == 0) {
            value = "=";
        } else if (this.compareTo(notequal) == 0) {
            value = "<>";
        } else if (this.compareTo(greaterthan) == 0) {
            value = ">";
        } else if (this.compareTo(greaterthanorequal) == 0) {
            value = ">=";
        } else if (this.compareTo(lessthan) == 0) {
            value = "<";
        } else if (this.compareTo(lessthanorequal) == 0) {
            value = "<=";
        } else if (this.compareTo(isnull) == 0) {
            value = "IS NULL";
        } else if (this.compareTo(isnotnull) == 0) {
            value = "IS NOT NULL";
        } 
        return value;
    }
}

Thursday, May 23, 2013

JasperReport example using eclipse


This is link of original post : LINK

1) Structure of Employee Report example

 

   

2) Add below list of jar files in EmployeeReport example

commons-beanutils-1.7.jar
commons-collections-3.1.jar
commons-digester-1.8.jar
commons-lang-2.1.jar
commons-logging-1.1.jar
iText-1.3.jar
jasperreports-1.0.3.jar
ojdbc14.jar

3)  create table like this below
create table Employee(
First_Name  VARCHAR2(10),
Last_Name VARCHAR2(10)
);
insert into Employee values('satyam','reddy');
insert into Employee values('pallavi','reddy');



4) create a jrxml folder in your EmployeeReport Project 
     In side jrxml folder create EmployeeReport.jrxml file and paste below code in inside that file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="EmployeeReport_Satyamsoft">
<queryString>
<![CDATA[select First_Name, Last_Name from employee e]]>
</queryString>
<field name="First_Name" />
<field name="Last_Name" />
<title>
<band height="50">
<staticText>
<reportElement x="0" y="0" width="180" height="15"/>
<textElement/>
<text><![CDATA[Jasper Report - satyamsoft]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height="30">
<staticText>
<reportElement x="0" y="0" width="69" height="24" />
<textElement verticalAlignment="Bottom" />
<text>
<![CDATA[First Name: ]]>
</text>
</staticText>
<staticText>
<reportElement x="140" y="0" width="79" height="24" />
<text>
<![CDATA[Last Name: ]]>
</text>
</staticText>
</band>
</pageHeader>
<detail>
<band height="30">
<textField>
<reportElement x="0" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{First_Name}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="140" y="0" width="69" height="24" />
<textFieldExpression>
<![CDATA[$F{Last_Name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>


5) create ReportGenerator class and paste inside this class

package com.satyamsoft;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ReportGenerator {

Connection conn;

public void generateReport() {

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","123456");
System.out.println("Loading Report Designs");
InputStream input = new FileInputStream(new File("jrxml/EmployeeReport.jrxml"));
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println("Compiling Report Designs");
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

System.out.println("Creating JasperPrint Object");
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("ReportTitle", "PDF JasperReport");

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null,conn);

//Exporting the report
OutputStream output = new FileOutputStream(new File("report/EmployeeReport.pdf"));

JasperExportManager.exportReportToPdfStream(jasperPrint, output);

System.out.println("Report Generation Complete");
conn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new ReportGenerator().generateReport();}
}
 

6) After executing the class we will get EmployeeReport.pdf file in our report folder then the pdf file looks like below

Friday, October 5, 2012

All about “static” Keyword


1. Static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables
  • single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<variable-name>


2. Static method

  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method can be accessed directly by the class name and doesn’t need any object
  • Syntax : <class-name>.<method-name>
  • A static method cannot refer to “this” or “super” keywords in anyway
Side Note:
  • main method is static , since it must be be accessible for an application to run , before any instantiation takes place.
Lets learn the nuances of the static keywords by doing some excercises!
Assignment: To Learn working of static variables & methods
Step 1) Copy the following code into a editor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
  Student(){
   //Constructor incrementing static variable b
   b++;
  }
   public void showData(){
      System.out.println("Value of a = "+a);
      System.out.println("Value of b = "+b);
   }
//public static void increment(){
//a++;
//}
}
class Demo{
   public static void main(String args[]){
     Student s1 = new Student();
     s1.showData();
     Student s2 = new Student();
     s2.showData();
     //Student.b++;
     //s1.showData();
  }
}
Step 2) Save & Compile the code. Run the code as, java Demo.
Step 3) Check output.
Step 4) It is possible to access a static variable from outside the class using the syntaxClassName.Variable_Name. Uncomment line # 27 & 28 . Save , Compile & Run . Observe the output.
Step 5) Uncomment line 15,16 & 17 . Save , Compile & Run.
Step 5) Error = ? This is because it is not possible to access instance variable “a” from static method “increment“.

3. static block

The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM
1
2
3
4
5
class Test{
 static {
 //Code goes here
 }
}
static block helps to initialize the static data members, just like constructors help to initialize instance members.

References