Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Sunday, 21 May 2017

How to Setup MAVEN on Windows

You can setup Maven framework on windows, link and Mac OS platforms. Here we will learn how to setup it in windows operating system:

To install Maven, you need to follow below steps:

1. Download Maven and extract it.
2. Setup JAVA_HOME and MAVEN_HOME environment variables.
3. Append Maven's bin path in the 'path' system variable.
4. Verify Maven by running 'mvn' command.

1. Download MAVEN:

Download Apache's maven latest version : apache-maven-3.5.0.
And extract it in your C-drive












2.  Setup new Environment variables and append 'path' variable  :

We will setup below Environment variables :

JAVA_HOME, MAVEN_HOME and MAVEN_OPTS

Please see below screenshots:

























































































3. Verify MAVEN

You can verify Maven configuration by running below command from command prompt.

mvn -version











Read Basics of Maven from the previous tutorial.  Comment below if you find any challenges in configuring maven.


Saturday, 20 May 2017

MAVEN Tool: Introduction

Maven is a framework for project management which manages project's build, reporting, documentation, releases and distributions. It provides developers a complete build life cycle framework.

Advantages of Maven:
1. No need to add jars files in each project.
2. Creates correct directory structure
3. Setup the multiple development team environment in a very short time.
4. Build and deploy the project.
5. Generate source code if auto-deploy mode is enable.
6. Compile Source Code.
7. Packages compiled code into JAR.

What is POM.XML file in Maven:

POM stands for Project Object Model. It is a XML file which contains information about project and configurations details which are used by maven to build the project. Maven reads the pom.xml file and then perform the tasks.

Maven has 3 type of repositories which contains all the JARs and POM.XML file which can help in building the project.

1.  Local Repository: It is located in the local system.By default, it is in %USER_HOME%/.m2 directory.
2. Central Repository: It is created by maven community itself. It contains a lot of common libraries.
3. Remote Repository: There can be possibilities that a libraries can't be available in central repository  so that we can take it from the web.  For those libraries we need to define remote repository in the pom.xml file.


Read: How to setup maven on windows.

Saturday, 9 April 2016

How to set current date and time using Prepared Statement ?

We can do this in following two ways:

1. By using Prepared's method setTimestamp( )

pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis()));

2. Or we can use DB specific calls to set the currect date and time in table.

String ins_into_pub_log="Insert into trx_pub(trx_id,curr_date,pub_code,sub_code)values(?,current_date,?,?);";

-- Here we used postgreSQl in our program thats why we used current_date, if you are using oracle then you can use SYSDATE.

Diamond Syntax in JAVA

"Diamond Syntax" is the project coin improvement in JAVA 7.
For example, Earlier we use to declare collections like this:

ArrayList<String> str=new ArrayList<String>();

       Map<String,File> myfile=new HashMap<String,File>();

Notice that the type parameters are duplicated in these declarations. As of Java 7 these declarations could be simplified to:

ArrayList<String> str=new ArrayList<>();

       Map<String,Filemyfile=new HashMap<>();

This <> is known as Diamond operator.

NOTE: You cannot swap these , the following is NOT legal.

          Map<> myfile=new HashMap<String,File>();  // Not a legal Diamond Syntax



Sunday, 3 April 2016

Read multiple files of same extension at a time by Multi threading in JAVA

In this post we will tell you, how you can read all the files of a particular extension present in a directory simultaneously.
Pseudo Code:
1. Take directory and file extension as input.
2. Scan the input directory and fetch all the file present with input extension in a FILE array.
3. Create a class where we input these file's name. This class should extend THREAD class or implements RUNNABLE interface for providing multi threading features.
4. Override RUN( ) method of Thread/Runnable and read the files using wrapper of FileReader and BufferedReader. Check previous post for better understanding.

In this screenshot, you can see four text files (.txt) are present in our project directory.
Note: You can add as many as text files in this directory for reading.











Source code for this project:

1. SearchFiles.java : We will create SearchFiles's object for passing directory path and extension of file. 

import java.io.File;
public class SearchFiles {

      private   String DIR_PATH;
      private   String FILE_EXT;
     
      public SearchFiles(String dirpath,String file_extn) {
            // TODO Auto-generated constructor stub
            DIR_PATH=dirpath;
            FILE_EXT=file_extn;
      }
     
      public File[] filenames() {
           
            File dir =new File(DIR_PATH);
            if (!dir.exists()) {
                  System.out.println(DIR_PATH+ "  is not exist in your system.");
            }
            else {
                  System.out.println(DIR_PATH+ "  FOUND");
            }
            Filterfiles ff=new Filterfiles(FILE_EXT);
            File[] files=dir.listFiles(ff);

            return files;
      }}

2. Filterfiles.java : This class implements FilenameFilter interface and overrides its method accept( ) , this method is responsible for returning files with inputed extension.

import java.io.File;
import java.io.FilenameFilter;

public class Filterfiles implements FilenameFilter {

      private String fileext;
      public Filterfiles(String ext) {
            this.fileext=ext;
      }
      @Override
      public boolean accept(File dir, String name) {
            // TODO Auto-generated method stub
            return (name.endsWith(fileext));
      }

}

 3. ReadFileByThread.java : This class will call main( ) method and do what we want in this program.

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

public class ReadFileByThread extends Thread {
      File alpha;
     
      public ReadFileByThread(String filename) {
            // TODO Auto-generated constructor stub
             alpha=new File(filename);
           
      }

      public  void run() {
           
            //File alpha=new File("alpha.txt");
            try {
                  FileReader fr=new FileReader(alpha);
                  BufferedReader br=new BufferedReader(fr);
                  String line;
                  try {
                        while ((line=br.readLine())!=null) {
                              System.out.println(Thread.currentThread().getName()+": "+line);
                             
                        }
                  } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
            } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
           
      }
     
      public static void main(String[] args) {
SearchFiles sf=new SearchFiles("C:\\Users\\workspace\\Readfiles", ".txt");
            File[] allfiles=sf.filenames();
            for(File f:allfiles){
                  System.out.println(f.getName());
            }
           
            ReadFileByThread[] readfile=new ReadFileByThread[allfiles.length];
            Thread[] th=new Thread[allfiles.length];
            for (int i = 0; i < readfile.length; i++) {
                  readfile[i]=new ReadFileByThread(allfiles[i].toString());
                   th[i]=new Thread(readfile[i]);
                   th[i].start();
            }
            try {
                  Thread.sleep(5000);
            } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }}}

This code will generate one thread for one file and reads its data. Out of above program is shown below.


Saturday, 2 April 2016

Read two different files using multiple threads simultaneously in Java

In this program, we will use different threads to read two different files simultaneously.
Here we have two files number.txt and alpha.txt.



Here we created a class ReadFileByThread which extends Thread class. So ReadFileByThread  class will override the method Run() of thread class. By using ReadFileByThread (String filename) constructor, we will pass filenames at the time of object creation in main() method.

In run() method, we will read file by using wrapper of FileReader and BufferedReader class and print the data of file line by line onto the screen. We used Thread's static Sleep() method to check the behaviour of threads.

Source code:

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

public class ReadFileByThread extends Thread {
      File alpha;
     
      public ReadFileByThread(String filename) {
             alpha=new File(filename);
           
      }

      public  void run() {
           
            try {
                  FileReader fr=new FileReader(alpha);
                  BufferedReader br=new BufferedReader(fr);
                  String line;
                  try {
                        while ((line=br.readLine())!=null) {
                              System.out.println(Thread.currentThread().getName()+": "+line);
                             
                        }
                  } catch (IOException e) {
                        e.printStackTrace();
                  }
            } catch (FileNotFoundException e) {
                  e.printStackTrace();
            }
           
      }
     
      public static void main(String[] args) {
           
            ReadFileByThread one=new ReadFileByThread("alpha.txt");
            ReadFileByThread two=new ReadFileByThread("number.txt");
            System.out.println(Thread.currentThread().getName()+" is our Thread-1 thread");
            Thread t1=new Thread(one);
            Thread t2=new Thread(two);
            t1.start();
            t2.start();
            try {
                  Thread.sleep(5000);
            } catch (InterruptedException e) {
                  e.printStackTrace();

            }}}

Both the thread t1 and t2 will execute simultaneously. Thread t1 will work on 'one' object where we passed alpha.txt and t2 will work on 'two' object with file number.txt.  Check the below screenshot for output of above program.




Read Data from Database and Store it into file by using JAVA

For this program, you must have basic knowledge of I/O and JDBC. We will use JDBC for reading data from database table. And  I/O,  for writing that data into a file.
Note: Here we used PostgreSQL JDBC (postgresql-9.4.1208.jre6.jar). PostgreSQL is a powerful, open source object-relational database system. Download postgresql-(VERSION).jdbc.jar
Create a table in database which you want to read. Here we created VOUCHER table in database.
Steps:
2. Create Connection with database.
3. Retrieve data into ResultSet. 
4. Create a file using FILE class if file doesn't exists.
5. Use FileOutputStream for opening the file in append mode.
6. Use ResultSet's next() method for reading data from database.
7. By using PrintWriter Class, we copy that data into file.

Complete Java Program:

public class jdbcMain {

          public static void main(String[] args) {
                  
                   try {                     
                            
Connection c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "dbname", "dbpassword");
Statement s=c.createStatement();
ResultSet rs=s.executeQuery("select voucher_no,sys_creation_date,voucher_status from voucher where voucher_no<2000;");
         
File file=new File("FreeVoucher.txt");
PrintWriter pw=new PrintWriter(new FileOutputStream(file, true));
try {
                                     
if (!file.exists()) {
          file.createNewFile();
}
                                     
                                      while (rs.next()) {
                                                pw.print(rs.getInt("voucher_no")+" ");
                                                pw.print(rs.getDate("sys_creation_date")+" ");
                                                pw.println(rs.getString("voucher_status"));
                                               
                                               
                                      }
                                      pw.println();
                                     
                                     
                             } catch (IOException e) {
                                      // TODO Auto-generated catch block
                                      e.printStackTrace();
                             }
                             finally {
                                      pw.flush();
                                      pw.close();
                             }
                   } catch (Exception e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                   }
                   }}
/********************* END of PROGRAM ******************************/

After running this program, file FreeVoucher.txt will have all the voucher's details.