Sunday, August 8, 2010

finding Fibonacci series in Java

import java.util.*;
/**
 *
 * @author Akhter Wahab
 */

public class Main {

    /**
     * @param args the command line arguments
     */
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        int N = Integer.parseInt(scan.nextLine());//taking input from the user the limit of the Fibonacci series
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }

}

Saturday, August 7, 2010

finding Prime Number in java

class Prime {
  public static void main(String[] args) {
    int number = 11;
    int i;
    for (i=2; i < num ;i++ ){
      int n = number%i;
      if (n==0){
        System.out.println("number is not Prime!");
        break;
      }
    }
    if(i == num){
      System.out.println("number is Prime !");
    }
  }
}

difference between abstraction and encapsulation

 The difference between both are ,Abstraction and encapsulation are two  separate concepts in Java. Abstraction is a technique that is used to represent common functionality amongst a set of classes. An analogy is to look at a set of vehicles: Car, Truck and Bus have some common features that all road vehicles share. From a Java perspective, the mechanics of turning four wheels, an engine, could be handled in abstract form through a common superclass. Abstraction allows subclasses to share common code without duplication.

Friday, August 6, 2010

Java Mail as text


public class MakeSend {
 
 String userName;
 String passWord;
 Logger logger = Logger.getLogger(MakeSend.class);
 
 public MakeSend(String userName,String passWord){
  
  this.userName = userName;
  this.passWord = passWord;
 }
  
 public String doSend(String smtp, StringBuffer msgBody,
String toEmail, String subject, String mimetype){
  
  Session mailSession;
  
  try{
   Properties mailProps = new Properties();
   mailProps.setProperty("mail.transport.protocol", "smtp");
   mailProps.setProperty("mail.smtp.host", smtp);
   mailProps.setProperty("mail.smtp.auth", "true");
   
   Authenticator mailAuth = new SMTPAuthenticator();
   mailSession = Session.getInstance(mailProps,mailAuth);
   Transport transport = mailSession.getTransport();
   
   MimeMessage msg = new MimeMessage(mailSession);
   
   msg.setFrom(new InternetAddress(userName));
   msg.setSubject(subject,"UTF-8");
   msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
   msg.setDataHandler(new DataHandler(
     new javax.mail.util.ByteArrayDataSource(msgBody.
toString(), mimetype)));
   
   transport.connect();
   transport.sendMessage(msg, msg.getRecipients(Message.
RecipientType.TO));
   transport.close();
   
  } catch (MessagingException mex) {   
   logger.error("Email send failed, exception on:
[" + toEmail + "] -" + mex);
          return "ERROR";
  }catch (IOException ioex){
   logger.error("Email send failed, exception on:
[" + toEmail + "] -" + ioex);
   return "ERROR";
  }
  finally {
   mailSession = null;
  }
  
  return "OK";
 }
 
 private class SMTPAuthenticator extends Authenticator {
  
  public PasswordAuthentication getPasswordAuthentication(){
     
   return new PasswordAuthentication(userName,passWord);
  }  
 }

}

java Mail

you can send mail by using transport service here is the cod for example

public void sendEmail(String emailBody, String emailRecipients, String subject){
        try {
            String[] toAddress = parseArray(emailRecipients);
            String from = (FROM_ADDRESS);
            if (toAddress != null) {
                for (int i = 0; i < toAddress.length; i++) {
                    String address = (String) toAddress[i];
                    m_transportService.sendText(emailBody, subject, address, from);
                }
            }
        } catch (Exception e) {
            getLogger().log(LogLevel.WARN, e.getMessage());
        }
    }

my First Program in JAVA

public class MyFirstProgram{
    public MyFirstProgram(){
    }
public static void main (String args[]){
      System.out.println("This is my First Program ");
}

the out put is "This is my first program " pm the console

primitive data types in JAVA

There is Eight primitive data types in the JAVA
boolean
one-bit. can take one value true and false only.

true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean.

byte
one byte .values from -128 to 127.

short
two bytes, -32,768 to 32,767

int
four bytes -2,147,483,648 to 2,147,483,647.

long
eight bytes Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float
four bytes range from 1.40129846432481707e-45 to 3.40282346638528860e+38

double
eight bytes IEEE 754. range from 4.94065645841246544e-324d to 1.79769313486231570e+308d .
char
two bytes, 0 to 65,535 unicode

JAVA Magic

this program will not compiled

 public class Magic {
 public void test() {
while(true) {
 System.out.println(“I am here”);
 }
 System.out.println(“Bye”);
 }
public static void main(String[] aergs){
Magic c=new Magic();
c.test();
 }
 }

but this will be compiled guess what is the reasion for this ???

 public class Magic {
 public void test() {
boolean b = true; // Now, it should work!
while(b) {
 System.out.println(“i am here”);
 }
 System.out.println(“bye”);
 }
public static void main(String[] aergs){
Magic c=new Magic();
c.test();
 }
 }

Thread in JAVA

you can create a Thread in java with two different ways

1)by extending from Thread class

public class MyThread extends Thread {
  
    public void run() {
        System.out.println("This is Thread");
    }
  
    public static void main(String[] args) {
        Thread thread = new MyThread();
        thread.start();
    }
}

2) by implementing runnable

public class MyRunnable implements Runnable {
  
    public void run() {
        System.out.println("this is Thread");
    }
  
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

List /ArrayList itration

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class ArrayToList {
  public static void main(String[] argv) {

 String myArray[] = new String []{"Arr1", "Arr2", "Arr 3"};

 //conversion of array to list
 List list = Arrays.asList(myArray);

          // loop itration
 Iterator iterator = list.iterator();
 while ( iterator.hasNext() ){
     System.out.println( iterator.next().toString() );
 }

          // 2nd way throgh for loop
 for (int i=0; i< list.size(); i++)
 {
 System.out.println( list.get(i) );
 }

          //3rd way through while loop
 int j=0;
 while (j< list.size())
 {
 System.out.println( list.get(j) );
 j++;
 }

  }
}

Servlet Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SomeServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    // Use "out" to send content to browser
    out.println("Hello i m first servlet");
  }
}

when this servlet invoke the output will be "Hello i m first servlet"

JSF Login Logout Example

Let's illustrate these ideas with a full example. We're going to implement user login/logout for an application that uses JSF. First, we'll define a Web Bean to hold the username and password entered during login:
@Named @RequestScoped
public class Credentials {
    private String username;
    private String password; 
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }   
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }   
}
This Web Bean is bound to the login prompt in the following JSF form:

    
        Username:
        
        Password:
        
    
    
    

The actual work is done by a session scoped Web Bean that maintains information about the urrently logged-in user and exposes the User entity to other Web Beans:
@SessionScoped @Named
public class Login {
    @Current Credentials credentials;
    @PersistenceContext EntityManager userDatabase;
    private User user;
        public void login() {
        List results = userDatabase.createQuery(
           "select u from User u where u.username=:username and u.password=:password")
           .setParameter("username", credentials.getUsername())
           .setParameter("password", credentials.getPassword())
           .getResultList();
                if ( !results.isEmpty() ) {
          user = results.get(0);
         }
          }   
    public void logout() {
        user = null;
    }
     public boolean isLoggedIn() {
       return user!=null;
    }
        @Produces @LoggedIn User getCurrentUser() {
        return user;
    }
}
Of course, @LoggedIn is a binding annotation:
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD})
@BindingType
public @interface LoggedIn {}
Now, any other Web Bean can easily inject the current user:
public class DocumentEditor {
    @Current Document document;
    @LoggedIn User currentUser;
    @PersistenceContext EntityManager docDatabase;
      public void save() {
        document.setCreatedBy(currentUser);
        docDatabase.persist(document);
    }
   }
Hopefully, this example gives a flavor of the Web Bean programming model. In the next chapter, we'll explore Web Beans dependency injection in greater depth.

Eclipse ShortKeys

1. Ctrl+Shift+F: Shortcut used for formatting the code. The formatting rules provided by default can be changed by navigating to the location Windows Preferences Java Code Style Formatter
2. Ctrl+Shift+O: Organizes the imports, removes the unwanted imports. When you first try to include any class and your editor shows an error in red, just use this key combination to get rid of it. If the Class is available in more than one package all the occurrences re listed
3. Ctrl +O: Lists all the variables and methods available in a particular class.
4. Ctrl+T: Lists all the implementation classes of a particular interface. Example if you open the class List and use this key combination, lists all possible implementations available in the class path
5. Ctrl+Shift+T: Open Type? What is this, don’t be bothered, it just lists all the classes available in its class path, it works as a pattern based search.
6. Ctrl+Shift+G: Key combination is very useful as it lists down the hierarch from where this method is called; this key combination has to be used when the name of the method is selected. If you use this combination selecting the name of the class; lists all the classes where the reference of this class is used.
7. Ctrl+N: Opens a New Wizard, suppose if you want to create a new class, instead of navigating to New Others, use this combination.
9. Ctrl+F8: Moving across the perspectives, say if you are in java perspective and would want to navigate to Debug environment, press and hold the key combination , can be navigated up and down to switch between the perspectives.
10. Ctrl+L: Go to the specified line number in a class.
11. Ctrl+F: Find and replace a word,
12. Ctrl+E: Lists all the classes than are opened and not displayed in the perspective, can say as explorer shows all the folders, this combination lists all the classes available in the hierarchy.
13. Ctrl+M: Maxmizes or Minimizes the current window
14. Ctrl+I: Corrects the inundation, but don’t forget to select the entire code usingCtr l+A before using this key combination
 15. Ctrl+Shift+B: This key combination will be useful for either inserting/removing of a breakpoint, in short toggle breakpoint.
 16. Ctrl+F11: Run your code, using this combination
 17. Alt+Shift+J: Adds the java documentation to a variable, method and Class
18. Ctrl + B: Builds the selected java project
19. Alt+Shift+R: Refractor rename, renames all the occurrences in the project.

Wednesday, August 4, 2010

Pattern.compile

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainClass {
  public static void main(String args[]) {
    Pattern p = Pattern.compile("\\d");
    Matcher matcher = p.matcher("5");
    boolean isOk = matcher.matches();
    System.out.println("original pattern matches " + isOk);

    // recycle the pattern
    String tmp = p.pattern();
    Pattern p2 = Pattern.compile(tmp);
    matcher = p.matcher("5");
    isOk = matcher.matches();
    System.out.println("second pattern matches " + isOk);
  }
}