Monday, July 18, 2011

How to add label icon in to our Swing List box

How to add label icon in to our Swing Jlist box
----------------------------------------------------
Steps.
-----
1.create a class(here OnlineUserCellRenderer) and implement ListCellRenderer.

  class OnlineUserCellRenderer extends JLabel implements 
  ListCellRenderer {

        private final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);

        public OnlineUserCellRenderer() {
            setOpaque(true);
            setIconTextGap(12);
        }

        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {
            TestImageList entry = (TestImageList) value;
            setText(entry.getUser());
            if (entry.getImage() != null) {
                setIcon(entry.getImage());
            }
            setIconTextGap(12);
            if (isSelected) {
                setBackground(HIGHLIGHT_COLOR);
                setForeground(Color.white);
            } else {
                setBackground(Color.white);
                setForeground(Color.black);
            }
            return this;
        }
    }

2. Then create a TestImageList class.This class is used to set
   properties for label.
    class TestImageList {

        private final String Name;
        private ImageIcon image;

        public TestImageList(String Name, ImageIcon image) {
            this.Name = Name;
            this.image = image;
        }

        public String getName() {
            return Name;
        }

        public ImageIcon getImage() {
            return image;
        }

        // Override standard toString method to give a useful result
        public String toString() {
            return Name;
        }
    }

3.  Declare DefaultListModel object for inserting data in to jlist
    box in our class import javax.swing.DefaultListModel.and 
    declare a object for DefaultListModel.
   
    public DefaultListModel model = new DefaultListModel();
   
4.  Then add elements in to our DefaultListModel for insert it in
    to swing jList box.
   
    model.add(comboCount, new OnlineUserListEntry(Name, newIcon));
    lstChatlist.setModel(model);
    OnlineUserCellRenderer labelUser = new OnlineUserCellRenderer();
    lstChatlist.setCellRenderer(labelName);
      

How to resize image using java.

How to resize image using java.


Steps

1. Import useful libraries in to our class.
    here we need

    import java.awt.image.BufferedImage;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;


2. Then we need to create a function ie 'imageIconResize'
   for resizing the image.and we need to pass some parameters in to
   that function
   
   here is the function.


  public BufferedImage imageIconResize(Image img,int postionX,int 
  postionY, int width, int hight)

  {

  BufferedImage bi = new BufferedImage(img.getWidth(null),
  img.getHeight(null),  BufferedImage.SCALE_FAST);
  Graphics g = bi.createGraphics();
  g.drawImage(img, postionX, postionY, width, hight, null, null);
  return bi;


  }
3. Then pass the parameters in to our function. for that we must
   have a image.
   In my example i have byte array of image.then convert it to
   ImageIcon.

   ie

  iconImage = new ImageIcon(bytes);
   
   I use getImage() function for get image from icon object.
   
  iconImage = new ImageIcon(bytes);
  Image img = iconImage.getImage();


4. So we have a image then we call the function it return a
   BufferedImage object.
   we need to convert it to ImageIcon.
   
 BufferedImage imageIconResize = imageIconResize(img,10,15, 50, 50);
 ImageIcon newIcon = new ImageIcon(imageIconResize);

   
5. Changing the value of parameters will change the size of the
   image.

Thursday, May 26, 2011

File upload using spring framework

Upload file using spring framework


how to upload file using spring.

Upload a file using spring framework is easy.

first of all we must import the required spring classes(that are given below).

To upload file using spring framework we must import 'MultipartHttpServletRequest' and

'MultipartFile' in to our project.to deal with multi part content in a servelet request we must include

MultipartHttpServletRequest interface. MultipartFile interface is used to store file that are comming with

Multipart HttpServlet Request. Here when the user click the 'Upload Doc' button the corresponding handler function

works in this case 'upLoadHandler()' and the function mapp the request(@RequestMapping(value = "/fileupload.do", method =

RequestMethod.POST)).Then corresponding code executed.after uploading the file server redirect the request to upload page

again.




package fileUpload.document;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UploadController {


    ModelAndView mav;


//location where to upload file
    private static final String destinationDir = "/mnt/disk1/uploads/";


    @RequestMapping(value = "/upload.do", method = RequestMethod.GET)
    public String uploadPage()
    {
        return "document/upPage";
    }


    @RequestMapping(value = "/fileupload.do", method = RequestMethod.POST)
    public String upLoadHandler(HttpServletRequest req,
            HttpServletResponse res) throws Exception {


        res.setContentType("text/plain");
        if (!(req instanceof MultipartHttpServletRequest)) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expected multipart request");
            return null;
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //here "fileUploaded" is the name of the html file upload tag in the web page
    MultipartFile file = multipartRequest.getFile("fileUploaded");
        File destination = new File(destinationDir + file.getOriginalFilename());
        file.transferTo(destination);       
        return "redirect:upload.do";
    }
}


file uploading html


this is the html page for uploading file in to server.only required part of the html

is given.

here we can see that the method is POST and encryption type is

multipart/form-data'

    <form method="post" action="/fileupload.do" enctype="multipart/form-data">
     <input type="file" name="fileUploaded" />
    <input type="submit" value="Upload Doc"/>
    </form>

before writing the code we must include multi part resolver bean in our application-context.xml file

<!-- Configure the multipart resolver -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!-- one of the properties available; the maximum file size in bytes -->
 <property name="maxUploadSize" value="100000"/>
 </bean>


Thursday, May 19, 2011

how to make Entity classes using Hibernate mapping file and POJO from Database?

How to make entity classes using hibernate mapping file and POJO from Database.

Step by step way is given below.
using net beans you can done it easily

With NetBeans.

assuming that we created a new project named 'HBN_Test'.

then add hibernate and spring framework file to our project.


Making hibernate configuration wizard file

then we need to configure hibernate configuration file in to our program


1.Right click the project then in the 'new' option select
hibernate configuration wizard option.it will open a new window.
2.Then click next and select appropriate database connection and
and we can see that database dialect is
'org.hibernate.dialect.MySQLDialect'
3.click finish button
this fill connect hibernate with our database
then


Making hibernate reverse engineering wizard file


1.Right click the project then in the 'new' option select
hibernate reverse engineering wizard option.it will open a new window
2.click next then we can see the tables in our data base select wanted tables check if we want to include related tables(forigen key referance tables)
3.click finish button.

this fill connect hibernate with our selected tables
then


Making hibernate mapping file and pojo from database



1.Right click the project then in the 'new' option select
hibernate mapping file and pojo from database option.it will open a new window
2.select our hibernate configuration file(hibernate.cfg.xml) and also hibernate reverse engineering wizard(hibernate.reveng.xml)
3.In general setting section select jdk 5 language features and EJB 3
annotation if we want.
4.then select appropriate package to import our entity classes.
5.then click finish button.
6.this will makes entity classes for our tables in the database.

Thursday, March 3, 2011

chat program using java

Chatting program using Google account


Before using this program you need to download the following jar

files and include this jar files in to your application libraries.

here we are making a sample chat program for Google.
with this exmaple you can chat with the person who is online.

1.smack.jar
2.smackx-debug.jar
3.smackx-jingle.jar
4.smackx.jar

 
package ChatTest;

import java.util.*;
import java.io.*;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class ChatTest implements MessageListener {

XMPPConnection connection;
public String[] ids;

public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
config.setSASLAuthenticationEnabled(false);
connection = new XMPPConnection(config);
try {
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(userName, password);
System.out.println(connection.isAuthenticated());
} catch (Exception e) {
System.out.println(e);
System.exit(0);

}
}

public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}

public void displayBuddyList() {
Roster roster = connection.getRoster();
Collection entries = roster.getEntries();
System.out.println("\n\n" + entries.size() + " buddy(ies):");
for (RosterEntry r : entries) {

System.out.println(r.getUser());
}
}

public void disconnect() {
connection.disconnect();
}

public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat) {
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
}

public static void main(String args[]) throws XMPPException, IOException {
// declare variables
ChatTest c = new ChatTest();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg;
DataInputStream input = new DataInputStream(System.in);
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
try {
// Enter your login information here
System.out.println("Enter Your gmail id");
String userId = input.readLine();
System.out.println("Password :");
String password = input.readLine();
userId = userId.replaceAll("@gmail.com", "");
c.login(userId, password);
System.out.println("-----");
c.displayBuddyList();

System.out.println("-----");

System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();

System.out.println("-----");

System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");

while (!(msg = br.readLine()).equals("bye")) {
c.sendMessage(msg, talkTo);
}

c.disconnect();
System.exit(0);
} catch (Exception e) {
System.out.println("Sorry Failed");
System.exit(0);
}
}
}

using this chat program.you can chat with one person at a time.

Sending mail using java program

Chatting program using Google talk account



Before using this program you need to download the following jar files

and include this jar files in to your application libraries.

here we are making a sample chat program for Google.

with this exmaple you can chat with the person who is online.


1.smack.jar
2.smackx-debug.jar
3.smackx-jingle.jar
4.smackx.jar



package ChatTest;

import java.util.*;

import java.io.*;


import org.jivesoftware.smack.Chat;

import org.jivesoftware.smack.ConnectionConfiguration;

import org.jivesoftware.smack.MessageListener;

import org.jivesoftware.smack.Roster;

import org.jivesoftware.smack.RosterEntry;

import org.jivesoftware.smack.SASLAuthentication;

import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.XMPPException;

import org.jivesoftware.smack.packet.Message;


public class ChatTest implements MessageListener {


XMPPConnection connection;

public String[] ids;


public void login(String userName, String password) throws XMPPException {

ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");

config.setSASLAuthenticationEnabled(false);

connection = new XMPPConnection(config);

try {

connection.connect();

SASLAuthentication.supportSASLMechanism("PLAIN", 0);

connection.login(userName, password);

System.out.println(connection.isAuthenticated());

} catch (Exception e) {

System.out.println(e);

System.exit(0);


}

}


public void sendMessage(String message, String to) throws XMPPException {

Chat chat = connection.getChatManager().createChat(to, this);

chat.sendMessage(message);

}


public void displayBuddyList() {

Roster roster = connection.getRoster();

Collection entries = roster.getEntries();
System.out.println("\n\n" + entries.size() + " buddy(ies):");
for (RosterEntry r : entries) {

System.out.println(r.getUser());
}
}

public void disconnect() {
connection.disconnect();
}

public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat) {
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
}

public static void main(String args[]) throws XMPPException, IOException {
// declare variables
ChatTest c = new ChatTest();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg;
DataInputStream input = new DataInputStream(System.in);
// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;
try {
// Enter your login information here
System.out.println("Enter Your gmail id");
String userId = input.readLine();
System.out.println("Password :");
String password = input.readLine();
userId = userId.replaceAll("@gmail.com", "");
c.login(userId, password);
System.out.println("-----");
c.displayBuddyList();

System.out.println("-----");

System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();

System.out.println("-----");

System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");

while (!(msg = br.readLine()).equals("bye")) {
c.sendMessage(msg, talkTo);
}

c.disconnect();
System.exit(0);
} catch (Exception e) {
System.out.println("Sorry Failed");
System.exit(0);
}
}
}

using this chat program.you can chat with one person at a time.

Friday, February 18, 2011

Generate mySql Script


I am using Linux Ubuntu 10.x Os


1.Open 'MySql Workbench 5.2.31'

2.Select your Default Database

3.Select 'Database' option In menu bar

4.Then Select 'Reverse Engineer' or press 'ctrl+R'

5.It Will Open A 'model' Window Dont Close it

6.Then select 'File' option in menu bar

7.Select 'Export' then Select 'Forward Engineer Sql Create Script ' option
   /Ctrl+Shift+G it Will open a new Window

8.Click 'Browse' Window Save Your File As '.sql' Extension

9.Then Tick Wanted Options In that Window then Click 'Next' button

10.Then Tick wanted Options.This will import wanted tables into sql Script
     You can Select Views as well as Triggers

11.Then Click 'Next' Button(you Can see Generated Sql Script)

12.Click 'Finish'...Its Done!!!