Friday, April 17, 2009

Send mail using javamail and gmail

This is my fully tested code. You need javamail 1.4 api to run this. If u find any kind of exception check ur system firewall that is blocking to send mail.

Add mail.jar and activation.jar in ur buildpath and run the code:


import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleSSLMail {

  private static final String SMTP_HOST_NAME = "smtp.gmail.com";
  private static final int SMTP_HOST_PORT = 465;
  private static final String SMTP_AUTH_USER = "xxxxx@gmail.com";
  private static final String SMTP_AUTH_PWD = "xxxx";

  public static void main(String[] args) throws Exception{
  new SimpleSSLMail().test();
  }

  public void test() throws Exception{
  Properties props = new Properties();

  props.put("mail.transport.protocol", "smtps");
  props.put("mail.smtps.host", SMTP_HOST_NAME);
  props.put("mail.smtps.auth", "true");
  // props.put("mail.smtps.quitwait", "false");

  Session mailSession = Session.getDefaultInstance(props);
   
  mailSession.setDebug(true);
   
  Transport transport = mailSession.getTransport();

  MimeMessage message = new MimeMessage(mailSession);
  message.setSubject("Hello Attatched world");
   
  //message.setContent("This is a test", "text/plain");
   
  // content
  MimeBodyPart mimeBodyPart = new MimeBodyPart();
   
  //mimeBodyPart.setText("Link goes here:");  
  String strLink = " Link goes here : http://www.google.com";
  mimeBodyPart.setText(strLink);
   
  // multipart is the main content holder
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(mimeBodyPart);
   
  // Part two is attachment
  File f = new File("F:\\angel.JPG");
  if(f.exists() && f.isFile())
  {
  System.out.println("attatching file......."+f.getName());
  mimeBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(f);  
  DataHandler handler = new DataHandler(source);
  mimeBodyPart.setDataHandler(handler);
   
  mimeBodyPart.setFileName(f.getName());
   
  multipart.addBodyPart(mimeBodyPart);
   
  }
   
  // add multipart data to message
  message.setContent(multipart);
   
   
  message.addRecipient(Message.RecipientType.TO,
  new InternetAddress("xxxx@yahoo.com"));

  transport.connect
  (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

   
  transport.sendMessage(message,
  message.getRecipients(Message.RecipientType.TO));
  transport.close();
  }
}


Wednesday, March 18, 2009

ORA-1017: invalid username/password; logon denied

This problem occur in oracle 11g. This is because login information case sensitivity. By default in oracle 11g, 10 versions have login case sensitivity value set true - you have to change it to false to resolve it. Just execute the following command in oracle :

ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE

Hope it will help you cause it really helped me a lot!!!

For further information visit following links:

Friday, February 6, 2009

Pagination in Hibernate and EJB3

This class with SQL Server 2000 and jTDS 0.8.1 and it works very well.

Enjoy!


/*
* Created on Oct 27, 2004
*/
package com.ugs.it.salescentre.navigation;

import java.util.List;

import org.apache.log4j.Logger;

import com.ugs.it.salescentre.logger.SalesCentreLogger;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.ScrollableResults;

/**
* This class provides pagination for displaying results from a large result set
* over a number of pages (i.e. with a given number of results per page).
*
* Taken from http://blog.hibernate.org/cgi-bin/blosxom.cgi/2004/08/14#fn.html.
*
* @author Gavin King
* @author Eric Broyles
*/
public class Page
{

private List results;
private int pageSize;
private int page;
private ScrollableResults scrollableResults;
private int totalResults = 0;

/**
* Construct a new Page. Page numbers are zero-based, so the
* first page is page 0.
*
* @param query
* the Hibernate Query
* @param page
* the page number (zero-based)
* @param pageSize
* the number of results to display on the page
*/
public Page(Query query, int page, int pageSize)
{
this.page = page;
this.pageSize = pageSize;
try
{
scrollableResults = query.scroll();
/*
* We set the max results to one more than the specfied pageSize to
* determine if any more results exist (i.e. if there is a next page
* to display). The result set is trimmed down to just the pageSize
* before being displayed later (in getList()).
*/
results = query.setFirstResult(page * pageSize).setMaxResults(
pageSize + 1).list();
}
catch (HibernateException e)
{
getLogger().error(
"Failed to get paginated results: " + e.getMessage());
}

}

public boolean isFirstPage()
{
return page == 0;
}

public boolean isLastPage()
{
return page >= getLastPageNumber();
}

public boolean hasNextPage()
{
return results.size() > pageSize;
}

public boolean hasPreviousPage()
{
return page > 0;
}

public int getLastPageNumber()
{
/*
* We use the Math.floor() method because page numbers are zero-based
* (i.e. the first page is page 0).
*/
double totalResults = new Integer(getTotalResults()).doubleValue();
return new Double(Math.floor(totalResults / pageSize)).intValue();
}

public List getList()
{
/*
* Since we retrieved one more than the specified pageSize when the
* class was constructed, we now trim it down to the pageSize if a next
* page exists.
*/
return hasNextPage() ? results.subList(0, pageSize) : results;
}

public Logger getLogger()
{
return SalesCentreLogger.getStaticLogger(this);
}

public int getTotalResults()
{
try
{
getScrollableResults().last();
totalResults = getScrollableResults().getRowNumber();
}
catch (HibernateException e)
{
getLogger().error(
"Failed to get last row number from scollable results: "
+ e.getMessage());
}
return totalResults;
}

public int getFirstResultNumber()
{
return page * pageSize + 1;
}

public int getLastResultNumber()
{
int fullPage = getFirstResultNumber() + pageSize - 1;
return getTotalResults() < fullPage ? getTotalResults() : fullPage;
}

public int getNextPageNumber()
{
return page + 1;
}

public int getPreviousPageNumber()
{
return page - 1;
}

protected ScrollableResults getScrollableResults()
{
return scrollableResults;
}

}



Reference

Wednesday, January 7, 2009

Java Important Tips

Hibernate Collection Sorting

Java Jobs

Java Papers

Servlet

Servlet Interview Questions


RoseIndia's Java


Sort Java (for sql query generated / except hibernate relational data) Collections


Full Example to sort Collection

Generic Sorts

If you write a sort for a List, e.g. ArrayList, with proper generics, it will work on collections of any type that supports Comparable or Comparator. To see how to pull it off, have a look at the source for any of my sorts, or Sun’s sort.

However, because of Java’s lack of orthogonality, your List sort won’t work for arrays of such Objects. You need to write very similar code to do that. Even that array version won’t sort an array of primitives such as long, int or byte. You have to write yet another slightly different version of the sort to handle each type of primitive.

Complete Example:

package com.mindprod.example;

import com.mindprod.palette.NamedColor.Alphabetically;
import com.mindprod.palette.NamedColor.ByRGB;

import java.awt.Color;
import static java.lang.System.out;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
* Demonstrate how to sort a Collection in Various orders using Sun's Collections.sort
* Created by IntelliJ IDEA.
*
* @author Roedy Green
*/
public class TestSort
{
// --------------------------- main() method ---------------------------

public static void main( String[] args )
{
// build ArrayList of Animals
ArrayList<Animal> animals = new ArrayList<Animal>( 5 );
animals.add( new Animal( "panther", Color.BLACK, 4 ) );
animals.add( new Animal( "frog", Color.GREEN, 4 ) );
animals.add( new Animal( "crab", Color.RED, 10 ) );
animals.add( new Animal( "elephant", Color.GRAY, 2 ) );
animals.add( new Animal( "spider", Color.BLACK, 8 ) );

out.println( "sort in Natural Order (by legs)" );
Collections.sort( animals );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort in Reverse Natural Order (by legs)" );
Collections.sort( animals, Collections.reverseOrder() );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort alphabetically" );
Collections.sort( animals, new Animal.Alphabetically() );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort reverse alphabetically" );
Collections.sort( animals, Collections.reverseOrder( new Animal.Alphabetically() ) );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort by color" );
Collections.sort( animals, new Animal.ByRGB() );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}
// end main
}
}

/**
* objects we will sort, represent animals, not nested
*/
class Animal implements Comparable<Animal>
{

/**
* what color this animal is.
*/
final Color color;

/**
* name of the animal
*/
final String name;

/**
* how many legs this animal has
*/
final int legs;
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
/**
* compare by legs then by colour (numerically).
*
* @param o other animal to compare with
* @return +ve if this animal is bigger, -ve if smaller, 0 if equal
*/
public int compareTo( Animal o )
{
int diff = legs - o.legs;
if ( diff != 0 )
{
return diff;
}
return ( color.getRGB() & 0xffffff ) - ( o.color.getRGB() & 0xffffff );
}

/**
* what colour is the animal
*
* @return colour
*/
public Color getColor()
{
return color;
}

/**
* how many legs has this animal?
*
* @return number of legs
*/
public int getLegs()
{
return legs;
}

/**
* override usual ToString to give a debugging represenation.
*
* @return name, color, legs as a string.
*/
public String toString()
{
return name + " " + color + " " + legs;
}

// --------------------------- CONSTRUCTORS ---------------------------

/**
* constructor
*
* @param name name of the animal.
* @param color what colonr the animal is
* @param legs howw many legs the animal has
*/
Animal( String name, Color color, int legs )
{
this.name = name;
this.color = color;
this.legs = legs;
}


/**
* Comparator for sorting Animals by alphabetically, case insensitive
*/
static class Alphabetically implements Comparator<Animal>
{
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
/**
* compare two animal objects
*
* @param o1 first object
* @param o2 second object
* @return +ve if o1 is biggern, -ve if smaller, 0 if equal
*/
public int compare( Animal o1, Animal o2 )
{
return o1.name.compareToIgnoreCase( o2.name );
}
}

/**
* Comparator for sorting Animals by Color then legs
*/
static class ByRGB implements Comparator<Animal>
{
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
/**
* compare two animal objects
*
* @param o1 first object
* @param o2 second object
* @return +ve if o1 is biggern, -ve if smaller, 0 if equal
*/
public int compare( Animal o1, Animal o2 )
{
int diff = ( o1.color.getRGB() & 0xffffff ) - ( o2.color.getRGB() & 0xffffff );
if ( diff != 0 )
{
return diff;
}
return o1.legs - o2.legs;
}
}
}

Tuesday, January 6, 2009

Software Site Links

Dreamweaver Extensions

Css Validator

Cross Browser Compatible Useful Article

Make your site cross browser compatible in 5 steps

Make your site cross browser compatible in 5 steps

Make your site cross browser compatible in 5 steps

Making your site cross browser compatible is not easy, but with this tutorial you can make your site cross browser compatible in 5 simple steps.

Step 1: Validate

Lots of bugs are caused by invalid (X)HTML or CSS. If you have your site validated, it will be a lot easier to make it cross browser compatible. Validate your (X)HTML code with the W3C validator and your CSS file with the W3C CSS validator.

validhtml

Step 2: Check your Website

Now you have to check your website in all browsers. I always check my site in the browsers, I’ve installed on my computer (Opera, Safari, Internet Explorer and Firefox). Do it and make a note of the bugs.

Of course, checking your website in the browsers installed on your computer is not enough. You have to check the website in different browser versions on different operating systems. The solution is Browsershots.org. With this website you can take full-length screen shots of your website in a lot of browsers. Just type in your url, bookmark the page and come back 20 minutes later to view the screen shots.

browsers

Analyse the screen shots and look for bugs. Be sure to write them down.

Step 3: Is it worth my time?

If you notice bugs in very old or uncommon used browsers, ask yourself if it’s worth your time to fix the problems. Look at the browser statistics of w3schools.com, but don’t forget to look to your own stats (I recommend AWstats). If you have one or two visitors every month still browsing with IE5.5, you should really ask yourself if it’s necessary to make the changes.

browserstats

Step 4: Search the cause

Now you know about the bugs, you’ll have to look for the CSS attribute or HTML code that is causing this problem. This is often obvious. A good reference can be found on westciv.com. There is a complete list of css attributes with their support in different browsers. Too bad Firefox isn’t in the tables.

If you still cannot find the cause of the issue, search for topics on webmaster forums or post a topic yourself, with a screen shot and (a part of) your CSS and HTML code. A forum I visit often is Ozzu.

ozzu

Step 5: Fix the issues

Now we’re at the essential part of making your website cross browser compatible: fixing the issues. If you know the code that is causing the trouble, find a way to rewrite the code for the specific browser. There are loads of CSS hacks to do that, but I recommend the use of conditional comments. There is an article on 456 Berea St. explaining why you should use conditional comments instead of CSS hacks.

Conditional Comments.
With conditional comments you can link to separate style sheets for all versions of Internet Explorer. A complete reference can be found on quirksmode. For example: