Saturday, June 30, 2012

resize image to required height and width

 How to resize image to required height and width. 


To resize the image firstly need to create a method  'resizeImage()' and pass the required parameters .

Here the 'resizeImage()' method accept 3 parameters (input Stream, required Width , required height )
the code is given below.

public static BufferedImage resizeImage(InputStream in, int requiredWidth, int requiredHeight) throws IOException {
        BufferedImage bfrImage = ImageIO.read(in);


        int imageWidth = bfrImage.getWidth();
        int imageheight = bfrImage.getHeight();
        double scalex = (double) requiredWidth / imageWidth;
        double scaley = (double) requiredHeight / imageheight;
        Image scaledImage = null;

 scaledImage = bfrImage.getScaledInstance(imageWidth, imageheight, Image.SCALE_SMOOTH);

BufferedImage destination = new BufferedImage(requiredWidth, requiredHeight, BufferedImage.SCALE_SMOOTH);
        Graphics2D g2d = destination.createGraphics();
        g2d.scale(scalex, scaley);
        g2d.drawImage(scaledImage, 0, 0, null);
        g2d.dispose();


        return destination;
    }


Thursday, June 28, 2012

access files inside web inf folder



  how to access files inside web inf folder



Direct accessing to web-inf is not possible by client. And its
restricted. Files inside the WEB-INF is only accessible by the
server.To access files inside web-inf we need to create a
java servlet.

using that servlet we can redirect the request to specified file
inside the web-inf folder. Here we are using a sample pure jsp
project that uses a login page 'login.jsp'. And its inside the
WEB-INF folder. Inside WEB-INF/jsp/login.jsp.

This example code will show how toredirect the request to 
login.jsp inside the web-inf folder.To do this firstly we need 
to modify the web.xml.


After modifying the web.xml create a class names
LoginController.java'and place the class inside'servletmapping'
package. Code is given below


pckage servletmapping;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginController extends HttpServlet {


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
String location = "/WEB-INF/jsp/login.jsp";
// location of jsp file inside the web inf


RequestDispatcher rd = getServletContext().getRequestDispatcher(location);
rd.forward(req, resp);
}
}


This is how we redirect the request inside the WEB-INF folder.
when we request '/app/login.jsp' then the corresponding
servlet handle the request(that we are defined inside the
web.xml) and serve the file inside the web inf.And it is not
possible to access the file by typing the exact
location inside the server that is 'WEB-INF/jsp/login.jsp'


Tuesday, May 1, 2012

Custom Entity Creation in Hibernate



CUSTOM ENTITY CREATION

We can create entity class of a table using hibernate and pojo. And it can be used with hibernate query and hibernate native sql queries.`@Entity` annotation is used to identify the entity class.
Assume that we use hibernate query to return particular result from table and map the result to entity.
Example :-
we have 2 table named `shop_type` and `shop`
And we set `shop_type_id` as foreign key for `shop ` table

table `shop_type`
shop_type_id
name
1
Hotel
2
M.Market
3
Textile

table `shop`
shop_id
shop_type_Id
name
entry_date
1
1
AVN
03/16/12 12:05 AM
2
1
AKN
03/16/12 12:10 AM
3
2
Reliance m
03/16/12 12:15 AM
4
3
AnimalTXT
03/16/12 12:20 AM


Assume that we have 2 entity classes named `Shop` and `ShopType`
and so we have two entity classes.  if we want to select a particular details from 'shop' table we can simply use our hibernate query
         eg:- hql  = "from Shop s where s.shopId = ?";
                     Query query = session.createQuery(hql);
                     query.setInteger(0, shopId);
                     (Shop)(query.uniqueResult());


and when we execute this statement . Hibernate will include all column of `shop` table in select statement by default and its a background process doing by hibernate. The reason for this behavior is only then  hibernate can map this result to corresponding entity class here it is `Shop.class`.

Example for background process is something like this
  select s.shop_id,s.shop_type_id,s.name,s.phone_number from shop s whee
  s.shop_id = 1;

 we can also use our native sql query also for select the result.

 Eg :- sql = "select {s.*} from shop s where s.shop_id = ?";
         SQLQuery query = session.createSQLQuery(sql);
         query.addEntity("s", Shop.class);
         query.setInteger(0, shopId);
        (Shop)(query.uniqueResult());

In this case also we need to select full column in our select statement.'{}'  symbol
is used when selecting all columns  and this tells the hibernate that all fields are selected.

Until now we select all column from table using select statements and mapped it to corresponding entity. And we find that without this way we can't map the result to entity.
Good news is that there is a way to select specified columns from a table using hibernate native sql quires.
using .addScalar property we can achieve this.

Eg:-
 sql = "select s.name as sname from shop s where s.shop_id = ?";


SQLQuery countQuery = session.createSQLQuery(hql).addScalar("sname",Hibernate.STRING)
return ((Object[]) countQuery.uniqueResult());
But using this properties we can't map the result in to entity class and it only return  objects .

Until now the result set column names are assumed to be the same as the column names specified in the mapping document. This can be problematic for SQL queries which join multiple tables, since the same column names may appear in more than one table. Assume that if we have a situation and we want to join two table and select only 3 columns . So we can use  addScalar property but if we need to select 10 columns then  addScalar will not be a proper way to accomplish this task. Because using lots of addScalar properties will  complicate our task and traveling of data will be more difficult. Also if we pass this result to velocity there will be difficulties.

So in this case we can use  custom entity like classes for mapping our join query result. Using this way we can reduce complexity and it behave like an entity class object. We can use it anywhere we like. To doing this we need to create a java class.
This example will give you an clear idea.

We have a sql query
 sql = SELECT s.`name`,st.name,,s.entry_date  FROM shop s JOIN shop_type st ON(s.type_id = st.shop_type_id);

This will return
name
name
entry_date
AVN
Hotel
03/16/12 12:05 AM
AKN
Hotel
03/16/12 12:10 AM
Reliance m
M.Market
03/16/12 12:15 AM
Animal TXT
Textile
03/16/12 12:20 AM

 And i am trying to map the result in to an custom entity to doing this we need  to create a class just like entity class . And this class must have variables. And

1.Variable name must be same as column names in our select statement
2.must include getter and setter methods for that variables .
3.Data type of variable also same as in table .

Here data type of column entry_date is Date in database and so variable `entryDate`.We can see that here some column have same  names.[1st and 2nd column have same name]and this will make some problems in our entity because there is an ambiguity. To solve this we can use alias in our query and so the column name will change

eg :- SELECT s.`name` as shopName,st.name as typeName,s.entry_date as entryDate  FROM shop s JOIN shop_type st ON(s.type_id = st.shop_type_id);

This will return
shopName
typeName
entryDate
AVN
hotel
03/16/12 12:05 AM
AKN
hotel
03/16/12 12:10 AM
Reliance m
M.market
03/16/12 12:15 AM
Animal TXT
textile
03/16/12 12:20 AM

So we can see that now 3 column have different names 'shopName' and 'typeName',entryDate respectively. Use this names for creating variable for class `ShopView` .Now we can create our custom entity class .

Created Class
public class ShopView {
   
    private String shopName;
    private String typeName;
    private Date  entryDate

    public String getShopName () {
        return shopName;
    }

    public void setShopName(String shopName) {
        this. shopName = shopName;
    }

    public String get TypeName () {
        return typeName;
    }

    public void setTypeName (String typeName) {
        this. typeName = typeName;
    }
    public Date getEntryDate() {
        return entryDate;
    }

    public void setEntryDate(Date entryDate) {
        this.entryDate = entryDate;
    }
}

ShopView is our new custom entity class for mapping our result.
For mapping our result to our newly created class we need to  use              query.setResultTransformer(Transformers.aliasToBean(ClassName.class)); method

For our Example we can use like this.

Sql ="SELECT s.`name` as shopName,st.name as typeName,s.entry_date as entryDate  FROM shop s JOIN shop_type st ON(s.type_id = st.shop_type_id)";
SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Transformers.aliasToBean(ShopView .class));
pager.setResult(query.list());

A ResultTransformer is a nice and simple interface that allows you to transform any Criteria result element.
  The above query will return a list which has been instantiated and injected
  into its corresponding properties or fields in ShopView class.   Using this way we can
  map our result into any class. This way is  suitable in   case of sql views. Means we
  can create custom view entities for our needs.

  Use this object in velocity page example.
   Assume that  we passed  the result  to velocity and we set the name as `shopDetailsList`
  then  we can use the list  in velocity as
   #foreach($shopObj in $shopDetailsList)
      $ shopObj .shopName
      $ shopObj .typeName
   #end



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.