Sunday, July 13, 2014

loose coupling and tight coupling



loose coupling and tight coupling

Coupling is the degree to which one class knows about another class. If the only knowledge that class A
has about class B, is what class B has exposed through its interface, then class A and
class B are said to be loosely coupled…that's a good thing. If, on the other hand,
class A relies on parts of class B that are not part of class B's interface, then the
coupling between the classes is tighter…not a good thing. In other words, if A knows
more than it should about the way in which B was implemented, then A and B are
tightly coupled.


Tight Coupling


we have two classes first is traveller and the second is a car. Traveller class is calling logic of car class; in this case traveller

class creates an object of car class.

This will mean the car class will depend on the traveller object.


public class Car {
    public void move(){
     
    }
}

public class Plane {
    public void move(){
     
    }
}


public class Traveller {
    Car c = new Car();
    public void startJourney() {
        c.move();
    }
}

Here traveller object is tightly coupled with car object.
If traveler wants to change from car to plane then the whole traveler class has to be changed like the following:

public class Traveller {
    Plane p = new Plane();
    public void startJourney() {
        p.move();
    }
}



Loose Coupling


Our main object, traveler in this case will allow an external entity, a so called container to provide the object. So traveler doesn't have to create an own class from the car or plane object it will get it from the container

When a object allow dependency injection mechanism.

The external entity, the container can inject the car or plane object based on a certain logic, a requirement of the traveler.

public interface Vehicle{
   public abstract void move();
}

public class Car implements Vehicale {
    Public void move(){
     
    }
}

public class Plane implements Vehicale{
    Public void move(){
     
    }
}


public class Traveller {
    Vehicle v;

    public void setV(Vehicle v) {
        this.v = v;
    }
    public void startJourney() {
        v.move();
    }
}


Here traveler class injects either a car or a plane object. No changes required in traveler class if we would like to change the dependency from car to a plane.

Traveler class took a vehicle reference, so an external object (Container) can inject either car object or plane object, depends on requirement of traveler.

Saturday, July 12, 2014

Sending Email Using Java




download Java Mail Download



import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;


public class SendMail {

    private String HOST_NAME = "gmail-smtp.l.google.com";
    String messageBody;

    public void postMail(String recipients, String subject, String message,String yourEmail, String yourEmailPassword) throws MessagingException{

        boolean debug = false;
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST_NAME);
        props.put("mail.smtp.auth", "true");

        Authenticator authenticator = new SMTPAuthenticator(yourEmail, yourEmailPassword);
        Session session = Session.getDefaultInstance(props, authenticator);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(yourEmail);
        msg.setFrom(addressFrom);


        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(message);

        Multipart multipart = new MimeMultipart();

        //add the message body to the mime message
        multipart.addBodyPart(messageBodyPart);

        //Put all message parts in the message
        msg.setContent(multipart);
        Transport.send(msg);
        System.out.println("Sucessfully Sent mail to All Users");
     
    }

   

    class SMTPAuthenticator extends javax.mail.Authenticator {

        String username;
        String password;

        private SMTPAuthenticator(String authenticationUser, String authenticationPassword) {
            username = authenticationUser;
            password = authenticationPassword;
        }

        public PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(username, password);
        }
    }

}




class SendTestEmail{
   
    public static void main(String[] args) {
        try {
            String recipients = "resiver@gmail.com";
            String yourEmail = "myEmail@gmail.com";
            String yourPassword = "myPassword";
            String subject = "Test";
            String message = "Hi, this is my mail";
           
           
            SendMail sendMail = new SendMail();
            sendMail.postMail(recipients, subject, message, yourEmail, yourPassword);
        } catch (MessagingException ex) {
            Logger.getLogger(SendTestEmail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
















java - Polymorphism



The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.


class Shape {

    public void area() {
        System.out.println("Shape area");
    }
}

class Circle extends Shape {

    public void area() {
        System.out.println("Circle area");
    }
}

class Square extends Shape {

    public void area() {
        System.out.println("Square area");
    }
}





class RunPol {

    public static void main(String[] args) {
        Shape[] shape = new Shape[2];
        shape[0] = new Circle();
        shape[1] = new Square();

        for (int i = 0; i < shape.length; i++) {
            Shape sh = shape[i];
            sh.area();
        }

    }
}

Note that the area() method is overridden.


output:
Circle area
Square area

The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.





Tuesday, July 8, 2014

Trai Icon





import Home.LoginUI;
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;


public class TryIcon {

    private static JFrame jfame;
    private static TrayIcon trayicon;

    public static JFrame getJfame() {
        return jfame;
    }

    public static TrayIcon getTrayicon() {
        return trayicon;
    }

    public static void setJfame(final JFrame aJfame) throws AWTException {
        jfame = aJfame;

        if (trayicon == null) {
            setTrayObject();
            SystemTray.getSystemTray().add(trayicon);
        }

        trayicon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (aJfame.isVisible()) {
                    jfame.setState(JFrame.MAXIMIZED_BOTH);
                    jfame.setVisible(true);
                    jfame.setAlwaysOnTop(true);
                } else if (jfame.isVisible()) {
                    jfame.setState(0);
                    jfame.setVisible(false);
                }
            }
        });





    }

    public static void setTrayicon(TrayIcon aTrayicon) {
        trayicon = aTrayicon;
    }

    public static void setTrayObject() {
        trayicon = new TrayIcon(new ImageIcon(jfame.getClass().getResource("/Title/star.png")).getImage(), "Create And Develop By", getPopupMenu());
    }

    private static PopupMenu getPopupMenu() {
        PopupMenu menu = new PopupMenu();
        MenuItem item = new MenuItem("Logout");
        menu.add(item);
        item.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(1);

                new LoginUI().setVisible(true);
            }
        });

        return menu;
    }

    public static void main(String[] args) {
        try {
            TryIcon.setJfame(new JFrame());
            TryIcon.getTrayicon().displayMessage("Backup", "your database create backup", MessageType.INFO);
        } catch (AWTException ex) {
            Logger.getLogger(TryIcon.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Auto Suggesions





import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;


public class ShowSuggesions {

    private ArrayList<String> suggeshions;
    private JTextField field;
    private JTextField nextToFocus;
    private int width;
    private int height = 100;
    private Point point;
    private JFrame jWindow = new JFrame();
    private JScrollPane jScrollPane = new JScrollPane();
    private JList<String> jList = new JList<String>();
    private int size;

    public ShowSuggesions() {
    }

    private void addKeyEvents() {

       
       
        jList.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                if(e.getKeyChar() ==10){
                    setSelectedValue();
                }
               
            }
           
        });
       
       
       
        jList.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                setSelectedValue();
            }
           
        });

    }

    private void setSelectedValue() {
        field.setText(jList.getSelectedValue());
        jWindow.dispose();
        if(nextToFocus!=null){
            nextToFocus.requestFocus();
        }
       

    }

    private void init() {


        height = field.getWidth();
        width = (int) field.getPreferredSize().getHeight();
        Point locationOnScreen = field.getLocationOnScreen();
        point = new Point((int) locationOnScreen.getX(), (int) locationOnScreen.getY() + field.getHeight());
        jWindow.setAlwaysOnTop(true);
        jWindow.setUndecorated(true);
        jScrollPane.setVisible(true);
        jScrollPane.setAutoscrolls(true);
        jList.setVisible(true);
        jWindow.setVisible(true);
       
       

    }
   
   
   
    public void hideFrame(){
        jWindow.dispose();
    }

    public void show(Vector<String> suggeshions, JTextField field, KeyEvent event,JTextField nexToFocues) {

        if (suggeshions != null && suggeshions.size() > 0) {

            if (!jWindow.isVisible()) {
                this.field = field;
                init();
            }
           
            size = suggeshions.size();
            jList.setListData(suggeshions);
            jScrollPane.setViewportView(jList);
            jWindow.getContentPane().add(jScrollPane);
            this.nextToFocus = nexToFocues;
           
            jWindow.setSize(field.getWidth(), 100);
            jWindow.setLocation(point);
          
            addKeyEvents();


        }
    }
}