Friday, 30 November 2012

Imp Tutorial for Java Developers


1. Spring Integration with different Technologies
 http://krams915.blogspot.in/p/tutorials.html

2. Hibernate,Springs
 http://javabrains.koushik.org/

3. Servlets,JSP
http://www.sharmanj.com/

Wednesday, 28 November 2012

String Manipulation in Java(Mutable and Immutable)


String Manipulation in Java:
(http://sourcecodemania.com/string-manipulation-in-java/)

A string is a sequence of symbols. Java provides you with String class in java.lang package, which does not require an import statement. That means Strings are available to use anywhere. String class provides many operations for manipulating strings.
·         Constructors
·         Utility
·         Comparisons
·         Conversions
An object of the String class represents a string of characters.
String Basics-Declaration and Creation
There is no single way to create a string in java. Following are some of the different ways to create strings in java:
String str = "niit";
str="seecs";
String name=str;
String stringName= new String ("string value");
String city=  new String ("Islamabad");
In Java, we traditionally declare a String with initial value of null. If we declare a String variable without initialization e.g String myString; what would happen? We have to initialize String variable with special null value, if you really don’t want to initialize it with useful value at the start.
String myString = null;
We can define an empty string as given below:
String str = new String( );

We can define a string with initial value as:
String str = new String("Java Strings");
(Note!  String str = “Java Strings”; produces the same result)
Immutability
Characters in Strings can not be changed after the Strings are created. Once created, a string cannot be changed. None of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely. There is no danger of changing an object through one reference without the others being aware of the change.
Immutable strings are efficient because it uses less memory. Following figure might explain the difference between mutable and immutable strings.
String Objects
String objects are immutable — they cannot be changed once they have been created.  References to string objects may be changed.
String str1 = new String("I like dogs.");
String str2 = new String("I prefer cats.");
str1 = str2; //reassign reference
String Operations in Java
String Classes:
Following are some useful classes that Java provides for String operations.
·         String Class
·         StringBuffer Class
·         StringTokenizer Class
String Operations:
·         int length()
·         char charAt(int index)
·         indexOf( ) & lastIndexOf( )
·         indexOf(char ch)          // first position of ‘ch’
·         indexOf(String str)       // first position of ‘str’
·         lastIndexOf(char ch)    // last position of ‘ch’
·         lastIndexOf(String str) // last position of ‘str’
·         String Substring (int) & String Substring (int startindex, int lastindex)
·         public String toLowerCase() & public String toUpperCase()
·         startsWith(String prefix)   &  endsWith(String suffix )
·         public String trim() – Returns a copy of the string, with leading and trailing whitespace omitted.
·         public String replace(char oldChar, char newChar) – Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
·         Concatenation  (+) returns  a string


Concatenation Example
Declare and construct two strings, then concatenate str2 to the end of str1.
String str1 = new String("This is the winter");
String str2 = new String("of our discontent");
str1 = str1.concat(str2); //concatenate str1 with str2
Note! The same result occurs for str1 = str1 + str2;
toCharArray( )
String string1 = "Hello How are you";
char[] array = string1.toCharArray();
copyValueOf( )
Static method
String string2;
string2 = String.copyValueOf(array); //copyValueOf(array,6,3);
String Comparison
Following are different ways to compare strings in Java.
·         Shallow comparison  = =
·         Deep comparison     equals( );
·         Deep comparison     compareTo( );
Shallow comparison using ==
The == will check whether the two String variables refer to the same string. If strings reference two separate strings, you will get false regardless of whether or not the strings happen to be identical. It does not compare the strings themselves, it compares the references to the strings, hence called shallow comparison.
Deep Comparison using equals()
Equals( ) is used to decide whether the strings referred by two String variables are equal or not. This method does a case sensitive comparison. Two strings are equal if they are the same length and each character in one string is identical to the corresponding character in the other. Use equalsIgnoreCase( ) method to check for equality between two strings ignoring the case of the string characters.
String s1 = new String ("I am a string");
String s2 = " a string";
String s3 = s1.substring(0,4);
String s4 = " a string";
String s5 = s3 + s2;
if (s5 == s1) {  }
if (s1.equals(s5))  {  }
if (s2 == s4)  {  }
if (s5.equals(s3+s4))  {  }
Deep Comparison using compareTo()
compareTo( ) is used to decide whether the string object from which it is called is less than , equal to or greater than the string passed as argument to it. Returns an integer which is negative if the String object is less than the argument String. Returns positive integer if the String object is greater than the argument String. It returns zero if both are equal.
System.out.println("hello".compareTo("hell"));  // returns 1
StringBuffer objects can be altered directly. A String object is always a fixed string. How to create StringBuffer objects?
StringBuffer string1 = "Hello How are you";//not allowed
StringBuffer string1 = new StringBuffer("Hello How are you");
StringBuffer contains a block of memory called buffer which may or may not contain a string and if it does, the string need not occupy all of the buffer.
append( );
string1.append("To");
string1.append(string2,3,3); //appending substrings
string1.append(x);//where x is an int
insert( );
string1.insert(4," how");//4 is the index position
insert also has many versions like append
Other Useful methods of StringBuffer Class
You can produce a String object from a StringBuffer object by using the toString( ) method of the StringBuffer class
String string2 = string1.toString( );
How does the compiler handles the string concatenation of String objects? Append( ) and toString( ) methods are used
String message = "hello" + "How are you";
String message = new StringBuffer( ).append("Hello").append("how are you").toString( );


Thanks for Visiting............

Monday, 26 November 2012

Simple code for Sending emails using Java


package project;

import javax.mail.Message.RecipientType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codemonkey.simplejavamail.Email;
import org.codemonkey.simplejavamail.Mailer;
import org.codemonkey.simplejavamail.TransportStrategy;
import org.springframework.stereotype.Service;

import java.util.*l;


@Service
public class MailsService {

protected final Log log = LogFactory.getLog(getClass());

public String sendEmail(String fromAddress, String fromName,
String toAddress,   String toName,
String subject,     String body) {
String status = "";
try {
Email email = new Email();
String emailHost = AppUtil.getProperty("EMAIL_HOST");
String emailPort = AppUtil.getProperty("EMAIL_PORT");
email.setFromAddress(fromName, fromAddress);
email.setReplyToAddress(toName, toAddress);
email.addRecipient(toName, toAddress, RecipientType.TO);
email.setSubject(subject);

// email.setTextHTML(body);
email.setTextHTML("<html> <body>" + body + "</body> </html>");

String mailboxUserName = AppUtil.getProperty("EMAIL_MAILBOX_LOGIN");
String mailboxPassword = AppUtil.getProperty("EMAIL_MAILBOX_PASSWORD");
//String transportStrategy =  AppUtil.getProperty("TRANSPORT_STRATEGY");

Mailer mailer = new Mailer(emailHost, Integer.parseInt(emailPort),
mailboxUserName, mailboxPassword,TransportStrategy.SMTP_SSL);
log.info("Email sent Successfully");

mailer.setDebug(true);
boolean isValid = mailer.validate(email);
mailer.sendMail(email);
status = "SENT";
} catch (Exception ex) {
ex.printStackTrace();
}
return status;
}

}

-------------------------------------------
Sending multiple mails :- 


public String sendEmail(String fromAddress, String fromName,
String toAddress,   String toName,
String subject,     String body) {
String status = "";
try {
Email email = new Email();
String emailHost = AppUtil.getProperty("EMAIL_HOST");
String emailPort = AppUtil.getProperty("EMAIL_PORT");
email.setFromAddress(fromName, fromAddress);
//email.setReplyToAddress(toName, toAddress);
//email.addRecipient(toName, toAddress, RecipientType.TO);
email.setSubject(subject);

String[] toAdd = toAddress.split(",");

// Add To address
for (int i = 0; i < toAdd.length; i++) {
email.addRecipient(toAdd[i].toString(),
toAdd[i].toString(), RecipientType.TO);

// email.setTextHTML(body);
email.setTextHTML("<html> <body>" + body + "</body> </html>");

String mailboxUserName = AppUtil.getProperty("EMAIL_MAILBOX_LOGIN");
String mailboxPassword = AppUtil.getProperty("EMAIL_MAILBOX_PASSWORD");

Mailer mailer = new Mailer(emailHost, Integer.parseInt(emailPort),
mailboxUserName, mailboxPassword,TransportStrategy.SMTP_SSL);

mailer.setDebug(true);
boolean isValid = mailer.validate(email);
mailer.sendMail(email);

}
status = "SENT";
log.info("Email sent Successfully");
} catch (Exception ex) {
ex.printStackTrace();
}
return status;
}

-----------------------------------------

In properties file:


#Email Propertices
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=465             //(ssl)
#TRANSPORT_STRATEGY=TransportStrategy.SMTP_SSL

EMAIL_MAILBOX_LOGIN=phanikumar.r@gmail.com
EMAIL_MAILBOX_PASSWORD=xxxxxxxx


We have to add two jar files for running this program:

<!-- Mail dependencies -->
<dependency>
<groupId>org.codemonkey</groupId>
<artifactId>simple-java-mail</artifactId>
<version>2.1</version>
</dependency>

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.4.4</version>
</dependency>



Thanks for visiting...........

Tuesday, 20 November 2012

Importance of toString() in java


Object class of Java is having predefined toString() method. This method by default Object class calls implicitly when an object created. Overriding toString manually is nothing but implementing this method in our class.The java toString() method is used when we need a string representation of an object. It is defined in Object class. 

The toString() method is useful for debugging. By default, when an object is printed out in a print stream like System.out, the toString() method of the object is automatically called.
While develping the code the developers used to check the object properties are getting through the object or not. For this print statement will be useful to quick test in the console.
public String toString()
Returns: a string representation of the object.

Let us take a Person class and try to print the person object using the System.out.println() statement. 

package blog.javabynataraj;
//@author Muralidhar N
class Person{
 public String fname;
 public String lname;
  
 Person(String fn,String ln){
  this.fname=fn;
  this.lname=ln;
 }
 public String getFname() {
  return fname;
 }
 public void setFname(String fname) {
  this.fname = fname;
 }
 public String getLname() {
  return lname;
 }
 public void setLname(String lname) {
  this.lname = lname;
 }
}
public class ToStringTest {
 public static void main(String[] args) {
  Person p = new Person("murali","dhar");
  System.out.println(p);
 }
}


The output will be the class name@hexadecimal



here the Object class's method toString returning
getClass().getName()+'@'+Integer.toHexString(hashCode())
But here we assumed that the firstname and the lastname will be print. But it is not done. This is the magic toStirng method.

But in the below program we can print the firstname and lastname of person Object. What we are going to do here is just overriding the toString method in Person Class.


package blog.javabynataraj;
//@author Muralidhar N
class Person{
 public String fname;
 public String lname;
  
 Person(String fn,String ln){
  this.fname=fn;
  this.lname=ln;
 }
 public String getFname() {
  return fname;
 }
 public void setFname(String fname) {
  this.fname = fname;
 }
 public String getLname() {
  return lname;
 }
 public void setLname(String lname) {
  this.lname = lname;
 }
 public String toString(){
  return (getClass()+"  FirstName: "+fname+"  LastName: "+lname);
 }
}
public class ToStringTest {
 public static void main(String[] args) {
  Person p = new Person("murali","dhar");
  System.out.println(p);
 }
}

See the output of this: 
Now you can achieve this by overriding the default toString() method inside Person class to return the contents of the instance of Person.

http://javabynataraj.blogspot.in/2012/10/importance-of-tostring-in-java.html


Thanks for visiting.........