Search This Blog

Email code in java

We can email anyone on any domain from our local PC with help of smtp server e.g. QK smtp server which is available free. You can find it here.


Now lets digg into java code, but before that you will need some jar files activation.jar and mail.jar from getjar.com


class Main{

public static void main(String args[]){
 try{
           String toemailId="touserId@domain.com";
           String fromemailId="fromuserId@domain.com";
           String subject="Test email";
           String body="This is a test email"; 
          
           //Get system properties
           Properties props = System.getProperties();

           //Specify the desired SMTP server
           props.put("mail.smtp.host", "localhost");

           // create a new Session object
           Session session = Session.getInstance(props,null);

           // create a new MimeMessage object (using the Session created above)
           Message message = new MimeMessage(session);
           message.setFrom(new InternetAddress(fromemailId);
           message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(fromemailId });
           message.setSubject(subject);
           message.setContent(body, "text/plain");
           Transport.send(message);

           }catch(Exception e){
            System.out.println(e); 
           }
}

Spring MVC


Spring MVC helps in building flexible and loosely coupled web applications. The Model-view-controller design pattern helps in seperating the business logic, presentation logic and navigation logic. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object . Controllers are responsible for receiving the request from the user and calling the back-end services.
The figure below shows the flow of request in the Spring MVC Framework.
When a request is sent to the Spring MVC Framework the following sequence of events happen.
  • The DispatcherServlet first receives the request.
  • The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
  • The Controller process the request by calling the appropriate service methods and returns aModeAndView object to the DispatcherServlet. The ModeAndView object contains the model data and the view name.
  • The DispatcherServlet sends the view name to a ViewResolver to find the actual View to invoke.
  • Now the DispatcherServlet will pass the model object to the View to render the result.
  • The View with the help of the model data will render the result back to the user.

Struts MVC Architecture





The model contains the business logic and interact with the persistance storage to store, retrive and manipulate data.
The view is responsible for dispalying the results back to the user. In Struts the view layer is implemented using JSP.
The controller handles all the request from the user and selects the appropriate view to return. In Sruts the controller's job is done by the ActionServlet.


The following events happen when the Client browser issues an HTTP request.
  • The ActionServlet receives the request. 
  • The struts-config.xml file contains the details regarding the Actions, ActionForms,ActionMappings and ActionForwards
  • During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServletmakes decision by refering to this object.
When the ActionServlet receives the request it does the following tasks.
  • Bundles all the request values into a JavaBean class which extends Struts ActionForm class. 
  • Decides which action class to invoke to process the request. 
  • Validate the data entered by the user. 
  • The action class process the request with the help of the model component. The model interacts with the database and process the request. 
  • After completing the request processing the Action class returns an ActionForward to the controller. 
  • Based on the ActionForward the controller will invoke the appropriate view. 
  • The HTTP response is rendered back to the user by the view component.

      Tips before development

      Using javac and java
      ❑ Use -d to change the destination of a class file when it's first generated by the javac command.
      ❑ The -d option can build package-dependent destination classes on-the-fly if the root package directory already exists.
      ❑ Use the -D option in conjunction with the java command when you want to set a system property.
      ❑ System properties consist of name=value pairs that must be appended directly behind the -D, for example, java -Dmyproperty=myvalue.
      ❑ Command-line arguments are always treated as Strings.
      ❑ The java command-line argument 1 is put into array element 0, argument 2 is put into element 1, and so on.

      Searching with java and javac
      ❑ Both java and javac use the same algorithms to search for classes.
      ❑ Searching begins in the locations that contain the classes that come standard with J2SE.
      ❑ Users can define secondary search locations using classpaths.
      ❑ Default classpaths can be defined by using OS environment variables.
      ❑ A classpath can be declared at the command line, and it overrides the default classpath.
      ❑ A single classpath can define many different search locations.
      ❑ In Unix classpaths, forward slashes (/) are used to separate the directories that make up a path. In Windows, backslashes (\) are used.
      ❑ In Unix, colons (:) are used to separate the paths within a classpath. In Windows, semicolons (;) are used.
      ❑ In a classpath, to specify the current directory as a search location, use a dot (.)
      ❑ In a classpath, once a class is found, searching stops, so the order of locations to search is important.

      Packages and Searching
      ❑ When a class is put into a package, its fully qualified name must be used.
      ❑ An import statement provides an alias to a class's fully qualified name.
      ❑ In order for a class to be located, its fully qualified name must have a tight relationship with the directory structure in which it resides.
      ❑ A classpath can contain both relative and absolute paths.
      ❑ An absolute path starts with a / or a \.
      ❑ Only the final directory in a given path will be searched.

      JAR Files
      ❑ An entire directory tree structure can be archived in a single JAR file.
      ❑ JAR files can be searched by java and javac.
      ❑ When you include a JAR file in a classpath, you must include not only the directory in which the JAR file is located, but the name of the JAR file too.
      ❑ For testing purposes, you can put JAR files into .../jre/lib/ext, which is somewhere inside the Java directory tree on your machine.

      Static Imports
      ❑ You must start a static import statement like this: import static
      ❑ You can use static imports to create shortcuts for static members (static variables, constants, and methods) of any class.

      Multi- threading in a nutshell

      Defining, Instantiating, and Starting Threads
      ❑ Threads can be created by extending Thread and overriding the public void run() method.
      ❑ Thread objects can also be created by calling the Thread constructor that takes a Runnable argument. The Runnable object is said to be the target of the thread.
      ❑ You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException.
      ❑ It is legal to create many Thread objects using the same Runnable object as the target.
      ❑ When a Thread object is created, it does not become a thread of execution until its start() method is invoked. When a Thread object exists but hasn't been started, it is in the new state and is not considered alive.

      Transitioning Between Thread States
      ❑ Once a new thread is started, it will always enter the runnable state.
      ❑ The thread scheduler can move a thread back and forth between the runnable state and the running state.
      ❑ For a typical single-processor machine, only one thread can be running at a time, although many threads may be in the runnable state.
      ❑ There is no guarantee that the order in which threads were started determines the order in which they'll run.
      ❑ There's no guarantee that threads will take turns in any fair way. It's up to the thread scheduler, as determined by the particular virtual machine implementation. If you want a guarantee that your threads will take turns regardless of the underlying JVM, you can use the sleep() method. This prevents one thread from hogging the running process while another thread starves. (In most cases, though, yield() works well enough to encourage your threads to play together nicely.)
      ❑ A running thread may enter a blocked/waiting state by a wait(), sleep(), or join() call.
      ❑ A running thread may enter a blocked/waiting state because it can't acquire the lock for a synchronized block of code.
      ❑ When the sleep or wait is over, or an object's lock becomes available, the thread can only reenter the runnable state. It will go directly from waiting to running (well, for all practical purposes anyway).
      ❑ A dead thread cannot be started again.

      Sleep, Yield, and Join
      ❑ Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.
      ❑ A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep() method (unless it's interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.
      ❑ The sleep() method is a static method that sleeps the currently executing thread's state. One thread cannot tell another thread to sleep.
      ❑ The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels—some levels may be treated as effectively equal.
      ❑ If not explicitly set, a thread's priority will have the same priority as the priority of the thread that created it.
      ❑ The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out there will be a different thread selected to run. A thread might yield and then immediately reenter the running state.
      ❑ The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in the runnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will usually preempt the running low-priority
      thread and put the high-priority thread in.
      ❑ When one thread calls the join() method of another thread, the currently running thread will wait until the thread it joins with has completed. Think of the join() method as saying, "Hey thread, I want to join on to the end of you. Let me know when you're done, so I can enter the runnable state."

      Concurrent Access Problems and Synchronized Threads
      ❑ synchronized methods prevent more than one thread from accessing an object's critical method code simultaneously.
      ❑ You can use the synchronized keyword as a method modifier, or to start a synchronized block of code.
      ❑ To synchronize a block of code (in other words, a scope smaller than the whole method), you must specify an argument that is the object whose lock you want to synchronize on.
      ❑ While only one thread can be accessing synchronized code of a particular instance, multiple threads can still access the same object's unsynchronized code.
      ❑ When a thread goes to sleep, its locks will be unavailable to other threads.
      ❑ static methods can be synchronized, using the lock from the java.lang.Class instance representing that class.

      Communicating with Objects by Waiting and Notifying
      ❑ The wait() method lets a thread say, "there's nothing for me to do now, so put me in your waiting pool and notify me when something happens that I care about." Basically, a wait() call means "wait me in your pool," or "add me to your waiting list."
      ❑ The notify() method is used to send a signal to one and only one of the threads that are waiting in that same object's waiting pool.
      ❑ The notify() method can NOT specify which waiting thread to notify.
      ❑ The method notifyAll() works in the same way as notify(), only it sends the signal to all of the threads waiting on the object.
      ❑ All three methods—wait(), notify(), and notifyAll()—must be called from within a synchronized context! A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lock on that object.

      Deadlocked Threads
      ❑ Deadlocking is when thread execution grinds to a halt because the code is waiting for locks to be removed from objects.
      ❑ Deadlocking can occur when a locked object attempts to access another locked object that is trying to access the first locked object. In other words, both threads are waiting for each other's locks to be released; therefore, the locks will never be released!
      ❑ Deadlocking is bad. Don't do it.