Friday, August 6, 2010

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);
  }
}