Thursday, 24 May 2018

Handaling XLS File In Java

This code will help you to handle xls file in java using apache poi.

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class test {
public static void main(String[] args) {
String file="C:\\Users\\Documents\\file.xls";
File excelfile=new File(file);
FileInputStream excleFileInputStream;
try {
excleFileInputStream = new FileInputStream(excelfile);
HSSFWorkbook wb = new HSSFWorkbook(excleFileInputStream);
int noOfsheet =wb.getNumberOfSheets();
for(int i=0;i<noOfsheet;i++){
HSSFSheet sheet = wb.getSheetAt(i);
String wbName =sheet.getSheetName();
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()){
    Row row = rowIterator.next();
    Iterator<Cell> cellIterator = row.iterator();
    String rowString="";
    while(cellIterator.hasNext()){
    Cell cell = cellIterator.next();
    rowString=rowString+cell.toString()+" ; ";
    System.out.println(rowString);
    }
   
   
    }
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Thursday, 15 March 2018

Understanding MVC - Model–View–Controller

MVC stands for Model–View–Controller



What is MVC ?

MVC is a code organization architecture style to organize your code-logic in a meaningful way.

  • It is an architectural pattern OR
  • It is the name of a methodology or design pattern.
Why it is the use of MVC  or why to use MVC  or What is the goal of MVC ?

well why should I use a filing cabinet or folders to organize my plethora of paper and not just have my papers stashed in a large pile and have others figure how they connect to each other.
  • To separate business logic, data base access and presentation.
  • So that developers can work in parallel on different components without impacting or blocking one another.            
 For example:  Team might divide their developers between the front-end and the back-end
  • To create scalable and extensible projects.
Where MVC is used ?

Traditionally used for desktop graphical user interfaces (GUIs).

  • But the architecture has become popular for designing web applications,mobile, desktop and other clients.
  • Programming languages like Java, C#, Ruby, PHP and others have popular MVC frameworks that are currently being used in web application development.

How it do so?

It divides a given software application into three interconnected parts.
Each of these components are built to handle specific development aspects of an application.

Below are the Three components :

        1. Model                   2. View                     3. Controller

  1. Model  

  • It directly manages the data, logic and rules of the application.
  • The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself.
             For example: A Student object will retrieve the Student information from the                                 database, manipulate it and update it data back to the database or use it to render data.

2. View 


  • The view means presentation of data in a particular format, triggered by a controller's decision to present the data.
  • Can be any output representation of information.

3. Controller

  • Act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output. 
  • The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model.

For example: The Student controller will handle all the interactions and inputs from the Student View and update the database using the Student Model. The same controller will be used to view the Student data.

Monday, 26 February 2018

Difference between JDK, JRE and JVM.


Let’s understand all the three elements with some diagram first.


JDK = JRE + JVM

JDK - Java Development Kit

As name depicts it’s a tool for development, but for development of what?
It is a software development kit to develop applications in Java.
So it’s a kind of complete package, if you have this you can develop your own java application           nothing else is required.
Now as it is a complete tool it must be consist of several elements or we can say sub tools.
Now JDK composed of several sub tool namely:

JRE + Compiler + Debuggers + JavaDocs

So when you will download JDK you will be provided with all those sub tools.


JRE - Java Run time Environment

Now as you see JRE is a sub tool of JDK
As name depicts it provides run time environment for your java application to run
As you have JDK you will start developing your java application i.e.
You will write your java program i.e. .java file right?
As soon as you are done with writing your .java file i.e. Java Source Code
Next you will compile that code i.e. will convert it to .class file
.class file is also called as your Byte Code
Now as you are done with your compilation process you need to run your application
Here comes the role of JRE.
JRE will provide you a run time environment to run your application.
In order to provide this environment JRE make use of its sub tool
And JVM is a sub tool of JRE.
JRE is responsible for running an application, so it can be downloaded separately
In case you do not need to develop any application, rather you are interested in just running the         application yo do not need to download whole JDK, JRE will be enough in this case.


JVM - Java Virtual Machine

The purpose of JVM is to translate byte code into native machine code.

That’s why JVM is Machine Specific, let’s understand how?

We all know that Java is a platform-independent language.
It's because when you write Java code, it's ultimately written for JVM but not your physical
        machine.      
JVM translates byte code into native machine code, In order to generate machine specific code
        JVM needs to be machine specific.
That’s why you have different JVM for Windows, Linux or Solaris but one JAR can run on all
         this operating system.
So in order to make java a platform independent our JVM is a platform dependent.
Every type of Machine (Windows / Linux / Mac) has a specific JVM.
In this way the coder doesn't need to bother with generating byte code. JVM takes care of
        portability
We can say Java is Portable but JVM is Machine Specific.

Next we can ask what are machine codes?

Machine code  are set of instructions that a computer's CPU executes directly)
After JVM converts byte code to machine code CPU executes those instructions and gives the
        output.





Thursday, 22 February 2018

Greedy and Non-Greedy match - Regex to compute first n digits in a string

This Post will clear all your doubts about what greedy and non-greedy means in the context of Regex.


Input String: AV assd 201708 DC18 ROUTE PO205960-205961-206200-    
                       206129ASSS 90a852585 108524724A

Req Output: 201708 i.e. first six digits in the input string.

I am not going to write the answer at once, rather we will go step by step from here.

Try to have some online tool ready where you can test while going through the below steps.
You may use the below available tools or any other as of your choice:



Step 1: What if we want to match to each digit i.e. every single digit in the given
             String.

Possible Sol: (\d) or ^.*(\d) looks good, will match to each and every occurrence of
                      digit in the string.

(\d):
  • Will make as many full match as single digit in the string(i.e.2,0,2,7....4)
  • Will make as many groups as single digit in the string(i.e.2,0,2,7....4)

^.*(\d):
  • This will also do the same thing, only difference will be:
  • Will make as one full match that will start from the beginning of the string and will last up to the last single digit in the string.
(i.e. AV assd 201708 DC18 ROUTE PO205960-205961-206200-206129ASSS 90a852585 108524724)
  • Will make as many groups as single digit in the string. (i.e.2,0,2,7....4)
And this difference is because of “^.*”  let’s see how it is effecting.

  • ^ matches to the start of the line i.e. in our case it will point before first char "A"
  • .* matches to anything.

In general if we write *txt this means everything that ends with txt.
Similarly, we are writing ^.*(\d), here anything can be present before(\d) but should last with digit(\d.

So you can ask it should end on this first digit i.e 2 in our case AV assd 2.

But no it will go up to the last digit in the string i.e. 4(see screen shot below).

This is because .* is greedy after finding the first match it is not going to stop, rather it will keep on traversing and will find all the possible match

And when you will use it in your code it will give the last matched group as the result i.e. 4 in our case


Step 2: Similarly, what if we want to match to 6 consecutive digits.

(\d{6}) or ^.*(\d{6}) looks possible solutions.

(\d{6})
  • Will make as many full match as six consecutive digits occur in the string(i.e. 201708,205960.......108524)
  • Will make as many groups as six consecutive digits occurs in the string(i.e. 201708,205960.......108524)

^.*(\d{6})

Again we can write it as ^.*(\d{6}) i.e. go to the start of line, and match as many possible 6 consecutive no’s.

It will start from "A" will find first 6 consecutive nos i.e. "201708" but will not stop and keep on finding till it find last 6 consecutive digits i.e. "524724" and will give the last group as result i.e. "524724"

  • This will also do the same thing, only difference will be:
  • Will make as one full match that will start from the beginning of the string and will last up to  the last six consecutive digits occurs in the string.
(i.e. AV assd 201708 DC18 ROUTE PO205960-205961-206200-206129ASSS 90a852585 108524724)
  • Will make as many groups as six consecutive digits occurs in the string.
(i.e. 201708,205960.......108524)



Step 4: Here comes our requirement i.e. match only the first six digits

As I already mentioned .* is greedy, so how to stop its greediness and make it lazy.

We saw in previous steps that how our expression is not stopping after the first match occurred rather it finds all the possible match and the last match is the output.

This is the meaning of greedy in regex

To make it lazy or say non greedy ? comes into play


? Will restrict the search up to the first match only, even if matches are available after the first match, it will make your regex lazy to avoid all other matches.

^.*?(\d{6})
  • Will make as one full match that will start from the beginning of the string and will last up to  the first six consecutive digits occurs in the string(i.e. AV assd 201708)
  • Will make as one groups as six consecutive digits occurs in the string.(i.e.201708)

Fell free to mention doubts in comment section.
Hope this post will help you.

Wednesday, 7 February 2018

Quick Guide to SVN

Know SVN

Apache subversion is commonly known as SVN.
Created by collabNet Inc. in 2000.
Software versioning and revision control system.
Distributed under open source license ,free over internet.
Comes by default with most of GNU/Linux distributions.
To check availability use the command : svn --version.
Now developed as a product of apache software foundation.
Version control system i.e. VCS  is a software.
It helps software developers to work together and maintain a complete history of their work.

Goals of VCS:
             Allow developers to work simultaneously
             Do not over write each other’s change
             Maintain history of each version
Categories of VCS:
             Centralized VCS – CVCS
             Decentralized/Distributed VCS – DVCS
Repository:
             Heart of VCS
             Stores files as well as history
             Repository is accessed over a network – acting as server
             Version control tool – acting as client
             Client i.e. VC tool can connect to the repository and can store or retrieve changes
Trunk:
             Directory where main development works are stored
             Developers can check out the project to work on and can check-in back the project
Tags:
             Stores named snapshot of the project
             It allows to give descriptive and memorable names to a specific version in the repository
             Ex: repository ID : abcg9de-4116-54ab-ss11-wi81n5hl39s  and version no 2
                     :Tags:LATEST-CODE_FOR_XYZ_PROJECT
Branch:
             Used to create another line of deployment
             Useful when you want your development process to fork off in two different direction
             Ex:After release of version 1.0,you can create a branch for developing version 2.0,to keep it                 separate from version 1.0 bug fixes
Working copy:
             Snapshot of the repository
             Checked in by the developers in local work space
             Isolated from the rest of the team
Commit Changes:
             Process of storing changes from workplace to the central server
             It is an atomic operation
             Either the whole commit succeed or the roll back

Monday, 5 February 2018

Install Mongodb in 5 simple steps

Step 1 : Know your computer architecture
open command prompt and type the below command:
 C:\>wmic os get osarchitecture
This will give architecture of your PC.


Step 2 : Download mongo db
Download as per your PC architecture from below link:
https://www.mongodb.org/downloads - Zip file

Step 3 : Extract to c:\ drive Or unzip and save in c drive
Name of the extracted folder will be mongodb-win32-i386-[version]
Or you may choose your own folder name.

Step 4 : Create mongodb data folder.
MongoDB requires a data folder to store its files.
The default location for the MongoDB data directory is c:\data\db.
So you need to create this folder using the Command Prompt.
Execute the following command sequence.
This is the path where all your mongo data will be saved.
C:\>\md data\db or Create manually.

Step 5: Final Step - Run your mongodb
Then issue the below command to set the data path.

C:\mongodb-win32-x86_64-enterprise-windows-64-3.6.2\bin>mongod.exe --dbpath "c:\data\db"

Now to run the MongoDB, you need to open another command prompt and issue the below command to set the data path
C:\mongodb-win32-x86_64-enterprise-windows-64-3.6.2\bin>mongo.exe


Next time when you run MongoDB, you need to issue only commands.

C:\mongodb-win32-x86_64-enterprise-windows-64-3.6.2\bin>mongod.exe --dbpath "c:\data\db" 
C:\mongodb-win32-x86_64-enterprise-windows-64-3.6.2\bin>mongo.exe -->Run this in new cmd

Note:You can place your mongo db in any of the drive not necessarily in c drive.
Also you can make your data folder any where as well
But c drive is recommended to avoid any confusion.



Difference between URI,URN and URL



  • URI can be either URL or URN or both.
  • All URLs are URIs,but not nececarily all all URIs are URLs,it can be either URL or URN or both

  • Example:
    •  Name: Swati----URN.
    •  Location/Address: street no -44,flat no-26,xyz colony,new city,old state,bigcountry-URL.

    Sunday, 4 February 2018

    Java program to generate a random 10 digit number

    Hi all ,my friend asked me this program today,so i thought of sharing it with you all.

    This program will generate a random 10 digit no every time you will run

    here base is taken as 1000000000

    and max limit as 9999999999

    Math.abs() is used to insure it give positive number

    if Math.abs() is removed you can get negative number as well

    In order to generate more than one number remove for loop in program

    and assign desired value to the x present in for loop

    long variable(start and end) both are initialized in different manner ,both style can be used to initialize a long variable in java

    Hope you like this post!!!

    Ask questions if any,Thanks a lot

    package random;

    import java.util.Random;

    public class random {

    public static void main(String[] args) {

    long start= Integer.parseInt("1000000000");

    //LONG can initializes as start(long start) as well as the next line end(long end)

    long end=9999999999L;

    Random random =new Random();

    //for(int x=1;x<=10;x++){

    //you can remove comment from for loop in order to generate multiple times

    //jut assign the value to x,whatever tome you want to generate

    long range =(long)end-(long)start+1;

    long fraction =(long)(range*random.nextDouble());

    int randomNumber=(int)(fraction+start);

    System.out.println(Math.abs(randomNumber));

    //Math.abs() is used in order to give positive numer

    //if you will remove Math.abs() it will give positive as well as negative number

    //}

    }

    }

    Java program to get Root xml from a file,convert file to xml document and get the root element

    import java.io.*;
    import javax.xml.parsers.*;
    import java.io.File;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import java.io.File;

    public class Util {

    public static void main(String[] args) {

    File inputFile = new File("input.txt");

    System.out.println("get root element of xml");
    root(xml) ;

    }

    public static void root(File inputFile)
    throws SAXException, ParserConfigurationException, IOException {
    // Parse the given input

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputFile);

    System.out.println("Root element in xml is:"+doc.getDocumentElement());

    }
    }

    If you have filr instead of xml string,

    make your xml structure

    save it to

    Get root element of a xml/document.getDocumentElement() function in xml

    your xml:

    <employee>
    <name>swati</name>
    <id>1209202</id>
    <department>audit</department>
    </employee>

    program:

    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;

    public class Util {

    public static void main(String[] args) {

    String xml="<employee><name>swati</name><id>1209202</id><department>audit</department></employee>"

    System.out.println("get root element of xml");
    root(xml) ;

    }

    public static void root(String xmlSource)
    throws SAXException, ParserConfigurationException, IOException {
    // Parse the given input
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));

    System.out.println("Root element in xml is:"+doc.getDocumentElement());

    }
    }

    doc.getDocumentElement() will give the root element of your xml document.

    working with xml,convert a xml string to xml document

    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;

    public class Util {

    public static void main(String[] args) {

    String xml="<employee><name>swati</name><id>1209202</id><department>audit</department></employee>";

    System.out.println("get xml document from string xml);
    stringToDom(xml) ;
    System.out.println("document is ready for use");

    }

    public static void stringToDom(String xmlSource)
    throws SAXException, ParserConfigurationException, IOException {
    // Parse the given input
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlSource)));
    }

    After document(doc) is created one can work on nodes,elements etc.

    can save xml to files or can convert back to string and enjoy results.

    I will post for more operations on xml documents.

    Handaling XLS File In Java

    This code will help you to handle xls file in java using apache poi. package test; import java.io.File; import java.io.FileInputStream...