Thursday 13 March 2014

How to Serializated multple Object in Java


Few days before as per requirement, need to build a class that serialized an object and store in a file and later should be retrieved through de-serialized process.

As per requirement, every Save Button clicked bean object should be serialized in a file and on Load Button click all persisted object could be back to JListBox.When i started this stuff then serialization are working file and store on the files But when Click on a Load Button then throws an exception.
then i did google on web after spending some time,i screw it in some other ways myself which is given below,this is fit for our requirement and working  good.

java.io.StreamCorruptedException: invalid type code: AC


HostPersistor.Java class is responsible to take a HostInfo bean and serialized and de-serialized.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.bean.HostInfo;

public class HostPersistor {

    static Map<String,HostInfo> HostInfoMap = new Hashtable<String,HostInfo>();
    public static void write(HostInfo obj) {

        FileOutputStream fout = null;
        ObjectOutputStream objout = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            if (!file.exists()) {
                file.createNewFile();
            }
            fout = new FileOutputStream(file);

            if (!HostInfoMap.containsKey(obj)) {
                HostInfoMap.put(obj.getIpaddress(),obj);
                objout = new ObjectOutputStream(fout);
                for (Map.Entry<String,HostInfo> info : HostInfoMap.entrySet()) {
                    objout.writeObject(info.getValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (objout != null)
                    objout.close();
                if (fout != null)
                    fout.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

   
    private static Set<String> readObject() {

        FileInputStream fin = null;
        ObjectInputStream objin = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            objin = new ObjectInputStream(new FileInputStream(file));
            while (true) {
                try {
                    HostInfo info = (HostInfo) objin.readObject();
                    HostInfoMap.put(info.getIpaddress(),info);
                } catch (Exception e) {
                    break;
                }

            }
        } catch (IOException e) {

        } finally {
            try {
                if (objin != null)
                    objin.close();
                if (fin != null)
                    fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       
        return HostInfoMap.keySet();
    }

    public static Set<String> getHostInfos() {
        return readObject();
    }

    public static List<String> getHosts(){
       
        List<String> list = new ArrayList<String>();
        list.addAll(getHostInfos());
        Collections.sort(list);
        return list;
       
    }
   

    public static void main(String args[]) throws IOException {

       
        HostInfo info1 = new HostInfo("xxxx", "xx", "xxx", 22);
        HostInfo info2 = new HostInfo("aaaa", "aaaa", "aaa", 22);
        HostInfo info3 = new HostInfo("yyyyy", "yyy", "yyyy", 22);
       
        write(info1);
        write(info2);
        write(info3);
       
        for(String info : getHostInfos()){
           
            System.out.println(info);
           
        }
       
       
        //System.out.println(getHosts());
    }


    public static Map<String, HostInfo> getHostInfoMap() {
        return HostInfoMap;
    }


    public static void setHostInfoMap(Map<String, HostInfo> hostInfoMap) {
        HostInfoMap = hostInfoMap;
    }

}

HostInfo.Java bean which describe host information.

import java.io.Serializable;
import java.util.Stack;

/**
 * @author ajaykumar.gupta
 *
 */

public final class HostInfo implements Serializable,Comparable<HostInfo> {

    private static final long serialVersionUID = 6243919138889562890L;

    private String ipaddress;
    private String username;
    private String password;
    private String pwd;
    private Stack<String> cmdList = new Stack<String>();

    private int port;
   

    public HostInfo(String ipaddress, String username, String password, int port) {

        this.ipaddress = ipaddress;
        this.username = username;
        this.password = password;
        this.port = port;
       
        cmdList.add(this.username+"@"+this.ipaddress);

    }

    public String getIpaddress() {
        return ipaddress;
    }

    public void setIpaddress(String ipaddress) {
        this.ipaddress = ipaddress;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Stack<String> getCmdList() {
        return cmdList;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("HostInfo [ipaddress=");
        builder.append(ipaddress);
        builder.append(", username=");
        builder.append(username);
        builder.append(", password=");
        builder.append(password);
        builder.append(", port=");
        builder.append(port);
        builder.append(", pwd=");
        builder.append(pwd);
        builder.append(", cmdList=");
        builder.append(cmdList);
        builder.append("]");
        return builder.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((ipaddress == null) ? 0 : ipaddress.hashCode());
        result = prime * result + port;
        result = prime * result
                + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        HostInfo other = (HostInfo) obj;
        if (ipaddress == null) {
            if (other.ipaddress != null)
                return false;
        } else if (!ipaddress.equals(other.ipaddress))
            return false;
        if (port != other.port)
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public int compareTo(HostInfo o) {
        return this.ipaddress.compareTo(o.ipaddress);
    }
   
   
   

}


Friday 21 February 2014

PostgresSQL Commands

PostgreSQL

About
Icon
PostgreSQL is a powerful, open source object-relational database system.It runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It is fully ACID compliant, has full support for foreign keys, joins, views, triggers, and stored procedures (in multiple languages). It includes most SQL:2008 data types, including INTEGER, NUMERIC, BOOLEAN, CHAR, VARCHAR, DATE, INTERVAL, and TIMESTAMP. It also supports storage of binary large objects, including pictures, sounds, or video. It has native programming interfaces for C/C++, Java, .Net, Perl, Python, Ruby, Tcl, ODBC.



@Commands :
#Login to postgresql:
psql -d mydb -U myuser -W
psql -h myhost -d mydb -U myuser -W
#Default Admin Login:
sudo -u postgres psql -U postgres
#List databases on postgresql server:
psql -l [-U myuser] [-W]
#Turn off line pager pagination in psql:
\pset pager
#Determine system tables:
select * from pg_tables where tableowner = 'postgres';
#List databases from within a pg shell:
\l;
#List databases from UNIX command prompt:
psql -U postgres -l;
#Describe a table:
\d tablename
#Quit psql:
\q;
#Switch postgres database within admin login shell:
\connect databasename;
#Reset a user password as admin: 
alter user usertochange with password 'new_passwd';
#Show all tables:
\dt;
#List all Schemas: 
\dn;
#List all users:
\du;
#Load data into posgresql:
psql -W -U username -H hostname < file.sql
#Dump (Backup) Data into file:
pg_dump -W -U username -h hostname database_name > file.sql
#Increment a sequence:
SELECT nextval('my_id_seq');
#Create new user:
CREATE USER tom WITH PASSWORD 'myPassword';
#Change user password: 
ALTER USER Postgres WITH PASSWORD 'mypass';
#Grant user createdb privilege: 
ALTER USER myuser WITH createdb;
#Create a superuser user:
create user mysuper with password '1234' SUPERUSER
# or even better
create user mysuper with password '1234' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN REPLICATION;
#Upgrade an existing user to superuser: 
alter user mysuper with superuser;
# or even better
alter user mysuper with SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN REPLICATION
#Show Database Version:
SELECT version();
#Change Database Owner:
alter database database_name owner to new_owner;
#Copy a database: 
CREATE DATABASE newdb WITH TEMPLATE originaldb;
#View Database Connections:
SELECT * FROM pg_stat_activity;
#View show data directory (works on 9.1+; not on 7.x):
show data_directory;
#Show run-time parameters:
show all;
select * from pg_settings;
#If you wish to list all tables, you must use:
\dt *.*;
#connect to the database, then list the tables:
\c liferay;
\dt;
#You can combine those two commands onto a single line, if you prefer:
\c liferay \dt;

Thursday 13 February 2014

Differences between Ant and Maven



 

The differences between Ant and Maven in this example? 


Ant doesn't have formal conventions like a common project directory structure, you have to tell Ant exactly where to find the source and where to put the output. Informal conventions have emerged over time, but they haven't been codified into the product.

  • Ant is procedural, you have to tell Ant exactly what to do and when to do it. You had to tell it to compile, then copy, then compress.
  • Ant doesn't have a lifecycle, you had to define goals and goal dependencies. You had to attach a sequence of tasks to each goal manually.
  • Ant is mainly a build tool.

Where Maven...

  • Maven has conventions, it already knew where your source code was because you followed the convention. It put the bytecode in target/classes, and it produced a JAR file in target.
  • Maven is declarative. All you had to do was create a pom.xml file and put your source in the default directory. Maven took care of the rest.
  • Maven has a lifecycle, which you invoked when you executed mvn install. This command told Maven to execute a series of sequence steps until it reached the lifecycle. As a side-effect of this journey through the lifecycle, Maven executed a number of default plugin goals which did things like compile and create a JAR. 
  • Maven is a project and dependencies management tool which build project as well.
  • Maven support modules base project integratio.

Default life cycle of Maven : 


  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test - process and deploy the package if necessary into an environment where integration tests can be run
  • verify - run any checks to verify the package is valid and meets quality criteria
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Wednesday 12 February 2014

How to mount Windows 7 folder into guest Ubuntu 12.04 directory




Well,Hope you doing well.

When you are working on VM Box and Window machine simultaneously then usually you do share some stuff between Window and Virtual Box like some project file or other files/directroy which are reside in your Window machine .
Sometime you upload files intoVMBox using some external software which is tedious task.

Here, do some easy step's that make your easier to switch/mount window file into VMBox or vice-verse.


Step 1.

Open VM Virtualbox and Click on setting, select "Shared Folder" from left panel and add share folder to which you want to share into VM Box.At last ok with done.

Here Share folder name is D:\Shared



Steps-2: (VM Box Ubuntu Side )


Open a terminal and run following command one by one

$ sudo apt-get install dkms

Need to reboot your VM Virtaul Box then
$ sudo /sbin/reboot   

$sudo apt-get install virtualbox-ose-guest-x11

 Create a shared folder under /usr/work/ directory.


$mkdir shared_work

$sudo mount -t vboxsf Shared ./shared_work



I hope this stuff will help you.
Thanks
--------