Tuesday, January 27, 2009

How do I convert String to Date object?

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

try
{
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}

How do I get MAC address of a host?

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {

public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();

/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();

/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i <>

How do I do a date add or substract?

public class CalendarAddExample
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();

System.out.println("Today : " + cal.getTime());

// Substract 30 days from the calendar
cal.add(Calendar.DATE, -30);
System.out.println("30 days ago: " + cal.getTime());

// Add 10 months to the calendar
cal.add(Calendar.MONTH, 10);
System.out.println("10 months later: " + cal.getTime());

// Substract 1 year from the calendar
cal.add(Calendar.YEAR, -1)
System.out.println("1 year ago: " + cal.getTime());
}
}

Calculate days difference between two dates?

import java.util.Calendar;

public class DateDifferentExample
{
public static void main(String[] args)
{
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

// Set the date for both of the calendar instance
cal1.set(2006, 12, 30);
cal2.set(2007, 05, 03);

// Get the represented date in milliseconds
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();

// Calculate difference in milliseconds
long diff = milis2 - milis1;

// Calculate difference in seconds
long diffSeconds = diff / 1000;

// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);

// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);

// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}
}

Monday, January 26, 2009

Reading and Writing a Properties File.

// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}

// Write properties file.
try {
properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}

Here is an example of the contents of a properties file:

# a comment
! a comment

a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e.f = another string

How to manage session in an application

1) Cookie
- they store user information on local machine.
- this cookie is passed to browser for checking user authentication.
- some of the browsers does not provide support for cookies.

2) URL rewriting
- additional user information will be appended to the URL to pass information to the destination
- Cons - limitation is 256 chars of URL
- Cons - user data is exposed to the world

3) Hidden Variables in HTML/JSP
- user data is maintained across the HTML/JSPs using hidden fields
- and in servlets by using request.getParameter("") - by passing parameter names.

3) HttpSession class
- maintaining a session object across an active session.
- we can store diff. user objects, need to be maintained across the session.
- its a hashmap
- request.getSession(true), to get a new session if does not exist.
- overcomes limitations of cookie and URL rewriting for storing sessionID.
- set maximum lifetime of the session.

Copy file from one location to another location

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}

Creating a temporary file.

try {
// Create temp file.
File temp = File.createTempFile("pattern", ".suffix");

// Delete temp file when program exits.
temp.deleteOnExit();

// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
out.close();
} catch (IOException e) {
}

Renaming a file or directory.

// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}

Forcing updates to a file to a disk.

try {
// Open or create the output file
FileOutputStream os = new FileOutputStream("outfilename");
FileDescriptor fd = os.getFD();

// Write some data to the stream
byte[] data = new byte[]{(byte)0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE};
os.write(data);

// Flush the data from the streams and writers into system buffers.
// The data may or may not be written to disk.
os.flush();

// Block until the system buffers have been written to disk.
// After this method returns, the data is guaranteed to have
// been written to disk.
fd.sync();
} catch (IOException e) {
}

Copy file from one location to another location

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}

Sunday, January 25, 2009

Download Collage's Subjects Books (All)



DOWNLOAD BOOKS

Use Gmail to convert .pdf, .doc, .xls, .ppt, .rtf, etc to HTML



Gmail is a nifty little application that handles email in a very efficient manner. It can, however, also be used for converting the following types of files to HTML -

.pdf, .doc, .xls, .ppt, .rtf, .sxw, .sxc, .sxi, .sdw, .sdc, .sdd, and .wml.

This is a great way to view of a particular type of file in case you are missing the application that opens that file. Here are the steps -

1. Compose a new message in GMail. (Sign up at http://mail.google.com in case you don’t have an account)

2. Attach any PDF or Word document that you want to convert to HTML You can attach multiple files in this step by clicking Attach another File.

3. Enter your own email address in the To: box and click send.

4. You instantly receive a message in your GMail Inbox folder. Open the message and click the “View as HTML” link next to your attachment.

5. The contents of your attachment appear as HTML in a new browser window without having to download the file. When you’re finished reading the attached file, close the new browser window to return to Gmail or you can even save the file to your harddrive.

Enjoy your new found multi format viewer

Free Download E-books



1. Hiberbate

1.1 Hibernate Criteria Query

Open Multiple Gmail A/c in Google Talk





Step-1 create short cut on desktop
Step-2 Right click on GTalk shot cut.
Step-3 Paste ""C:\Program Files\Google\Google Talk\googletalk.exe" /nomutex" in Target






Step-4 Now Press "OK"
Step-5 Now You can open multiple Gmail A/c in Google Talk. Each time you click on GTalk icon you can start new Conversions

Hibernate Criteria API



Download PDF: http://www.javapassion.com/j2ee/hibernatecriteria.pdf



Hibernate Criteria API


Three ways of retrieving data in

Hibernate

● Criteria query API

The easiest way to retrieve data Pure Java language based

● Hibernate Query Language (HQL)

● Native SQL query


How to use Criteria Query API

● Create org.hibernate.Criteria object via

createCriteria() factory method of the Session

– Pass persistent object's class or its entity name to

the createCriteria() method

● Call list() method of the Criteria object

// Get all instances of Person class and its subclasses

Criteria crit = sess.createCriteria(Person.class);

List results = crit.list();


Criteria Query API Feature

● Uses a set of Java objects for constructing queries

– Instead of query language

● Lets you build nested, structured query expressions

in Java programming language

– Compile time syntax checking possible

– Polymorphic behavior – get instances of X & subclass(X)

● Supports Query By Example (QBE)

– Performing a query by providing an example object that

contain properties that need to be retrieved

● Supports aggregation methods (from Hibernate 3)

– Count