Wednesday, January 29, 2014

How to list all the table names in the database with sql?

Oracle:


  1. To get all the tables that you own: select * from user_tables;
  2. To get all the tables that you have access: select * from all_tables; 
  3. If you have access to the DBA_TABLES data dictionary view: select * from dba_tables;
  4. From legacy CAT view: select * from CAT where TABLE_TYPE = 'TABLE';
  5. To get all the table columns: select * from all_tab_columns order by owner, table_name, column_id;

DB2:


  1. SELECT * FROM SYSCAT.TABLES
  2. To get all the table columns: SELECT COLNAME FROM SYSCAT.COLUMNS order by TABNAME;



MySQL


  1. SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ;
  2. To list all the table columns: SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS order by TABLE_NAME
-------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Tuesday, January 28, 2014

What does addNotify() do?

Defined by Java, addNotify makes a JFrame displayable by connecting it to a native screen resource. Making a frame displayable will cause any of its children to be made displayable. This method is called internally by the toolkit and should not be called directly by programs. And for a JComponent, addNotify notifies this component that it now has a parent component. When this method is invoked, the chain of parent components is set up with KeyboardAction event listeners. This method is called by the toolkit internally and should not be called directly by programs.

In the following sample code, a JPanel p2 is set as the content pane of the JFrame. Another JPanel p1 is added to p2, and a JTextField tf is added to p1. When you execute the code, the addNotify is called in the sequence of JFrame, p2, p1, and tf. If you comment out the super.addNotify() in the JFrame, the whole gui will not show at all. If you comment out the super.addNotify() in any of the other components, you are not able to type anything in the text field.


import java.awt.BorderLayout;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class AddNotifyTest extends JFrame {

    public AddNotifyTest() {
//        System.out.println("Contructing.....");
        JPanel p1 = new JPanel() {
            @Override
            public void addNotify() {
                System.out.println("p1....");
                super.addNotify();
            }
        };
        
        JPanel p2 = new JPanel() {
            @Override
            public void addNotify() {
                System.out.println("p2....");
                super.addNotify();
            }
        };        
        
        JTextField tf = new JTextField (20) {
            @Override
            public void addNotify() {
                System.out.println("tf....");
                super.addNotify();
            }
        };
        
        p1.setLayout(new BorderLayout());
        p2.setLayout(new BorderLayout());
        p1.add(tf);
        p2.add(p1);
        setContentPane(p2);
        
        tf.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e){
                if (e.getKeyCode() == KeyEvent.VK_F1){
                    System.out.println("F1 pressed....");
                }
            }
        });
        
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setSize(300, 200);
    }
    
    @Override
    public void addNotify() {
        System.out.println("JFrame....");
        super.addNotify();
    }

    public static void main(String[] args){

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                AddNotifyTest at = new AddNotifyTest();
                at.setVisible(true);
            }
        });
    }

}

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

                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, January 27, 2014

How to execute code when JInternalFrame is closing programmatically

To programmatically close a JInternalFrame, the JInternalFrame setClosed is programmactically called to set the IS_CLOSED_PROPERTY to true. It calls the fireInternalFrameEvent, InternalFrameListener.internalFrameClosing, dispose and InternalFrameListener.internalFrameClosed methods in the order listed if there is an InternalFrameListener added to the JInternalFrame, and then set the IS_CLOSED_PROPERTY to trueIf there is no InternalFrameListener added to the JInternalFrame, the InternalFrameListener methods will not be called. The JInternalFrame dispose method is called and the internal frame is closed.  If you would like to let the user to decide if he/she really wants to close the internal frame, the method to override is setClosed. If you just want to do some setting/cleaning , you may override any of these methods.

import javax.swing.JDesktopPane;

import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class InternalFrameTest extends JInternalFrame {


    public InternalFrameTest() {

        setClosable(true);
        setSize(250, 150);
        add(new JLabel("Internal Frame Test"));
        setVisible(true);
        try {
            setSelected(true);
        } catch (java.beans.PropertyVetoException e) {
            System.out.println(e.getMessage());
        }
        
        this.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                System.out.println("internalFrameClosing....");
                //do some cleaning here
                super.internalFrameClosing(e);
            }
            
            @Override
            public void internalFrameClosed(InternalFrameEvent e) {
                System.out.println("internalFrameClosed....");
                //do some cleaning here
                super.internalFrameClosed(e);
            }
        });
    }

    @Override

    protected void fireInternalFrameEvent(int id) {
        if (id == InternalFrameEvent.INTERNAL_FRAME_CLOSING) {
            System.out.println("fireInternalFrameEvent....");
            //do some cleaning here
        }
        super.fireInternalFrameEvent(id);
    }
    
    @Override
    public void setClosed (boolean closed) throws java.beans.PropertyVetoException {
        System.out.println("setClosed....");
        int opt = JOptionPane.showConfirmDialog(null,
                "Are you sure to close this window?", "Confirm",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (opt == JOptionPane.NO_OPTION) {
            return;
        }
        //do some cleaning here
        super.setClosed(closed);
    }

    @Override

    public void dispose() {
        System.out.println("dispose...");
        super.dispose();
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                JDesktopPane dtp = new JDesktopPane();
                frame.setContentPane(dtp);
                InternalFrameTest test = new InternalFrameTest();
                dtp.add(test);

                frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

                frame.setSize(300, 200);
                frame.setVisible(true);

                //programmatically close the internal frame

                try {
                    test.setClosed(true);
                } catch (java.beans.PropertyVetoException e) {
                    System.out.println(e.getMessage());
                }
            }
        });
    }
}
        
-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.
--------------------------------------------------------------------------------------------------------------------------

References:

1. How to execute code when JFrame is closing after the [X] button is pressed?

2. How to execute code when a JInternalFrame is closing after the [X] button is pressed

How to execute code when a JInternalFrame is closing after the [X] button is pressed

When the [X] button of JInternalFrame is clicked, it calls the doDefaultClosingAction first, then the fireInternalFrameEvent, InternalFrameListener.internalFrameClosing, dispose and InternalFrameListener.internalFrameClosed methods in the order listed if there is a InternalFrameListener added to the JInternalFrame. If there is no InternalFrameListener added to the JInternalFrame, the InternalFrameListener methods as well as the JInternalFrame dispose method will not be called and the internal frame will not close when the [X] button is clicked. If you would like to let the user to decide if he/she really wants to close the internal frame, the method to override is doDefaultClosingAction. If you just want to do some setting/cleaning , you may override any of these methods.

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class InternalFrameTest extends JInternalFrame {

    public InternalFrameTest() {
        setClosable(true);
        setSize(250, 150);
        add(new JLabel("Internal Frame Test"));
     
        setVisible(true);
        try {
            setSelected(true);
        } catch (java.beans.PropertyVetoException e) {
            System.out.println(e.getMessage());
        }
     
        this.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                System.out.println("internalFrameClosing....");
                //do some cleaning here
                super.internalFrameClosing(e);
            }
         
            @Override
            public void internalFrameClosed(InternalFrameEvent e) {
                System.out.println("internalFrameClosed....");
                //do some cleaning here
                super.internalFrameClosed(e);
            }
        });
    }

    @Override
    protected void fireInternalFrameEvent(int id) {
        if (id == InternalFrameEvent.INTERNAL_FRAME_CLOSING) {
            System.out.println("fireInternalFrameEvent....");
            //do some cleaning here
        }
        super.fireInternalFrameEvent(id);
    }
 
    @Override
    public void doDefaultCloseAction() {
        System.out.println("doDefaultCloseAction....");
        int opt = JOptionPane.showConfirmDialog(null,
                "Are you sure to close this window?", "Confirm",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (opt == JOptionPane.NO_OPTION) {
            return;
        }
        //do some cleaning here
        super.doDefaultCloseAction();
    }

    @Override
    public void dispose() {
        System.out.println("dispose...");
        super.dispose();
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                JDesktopPane dtp = new JDesktopPane();
                frame.setContentPane(dtp);
                InternalFrameTest test = new InternalFrameTest();
                dtp.add(test);

                frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                frame.setSize(300, 200);
                frame.setVisible(true);
            }
        });
    }
}
 
-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.
-----------------------------------------------------------------------------------------------------------------------------

References:
1. How to execute code when JInternalFrame is closing programmatically
2. How to execute code when JFrame is closing after the [X] button is pressed?

How to execute code when JFrame is closing after the [X] button is pressed?

The dispose() method is only called when the default close operation is set to JFrame.DISPOSE_ON_CLOSE (setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE)). When the default close operation is set to JFrame.EXIT_ON_CLOSE, the JVM and everything else is shutdown and there is no need to dispose. When it is set to DO_NOTHING_ON_CLOSE or HIDE_ON_CLOSE, it means that you do not want the dispose() to be called and indeed it is not called. If you do not specifically set the default close operation value, by default it is HIDE_ON_CLOSE.

Therefore, overriding the dispose() method does not guarantee that your code is executed. The correct way to do this is either to add a WindowListener to the JFrame or override the processWindowEvent method. If you would like the user to decide if he/she truly wants to close the frame, the method to override is processWindowEvent. If you just want to do some setting/cleaning, you may override either of these methods.

1. Add a WindowListener to the JFrame


import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class WindowCloseTest extends JFrame {
    public WindowCloseTest() {
        this.add(new JLabel("WindowCloseTest"));
        setSize(300, 200);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e){
                //your code to be executed before window is closed.
                //not the place to opt out closing window
                System.out.println("exiting1...");
                super.windowClosing(e);
                System.out.println("exiting1.1...");
            }
        });
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                WindowCloseTest test = new WindowCloseTest();
                test.setVisible(true);
            }
        });
    }
}

2. Override the processWindowEvent method


import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class WindowCloseTest extends JFrame {
    public WindowCloseTest() {
        this.add(new JLabel("WindowCloseTest"));
        setSize(300, 200);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    @Override
    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            int opt = JOptionPane.showConfirmDialog(null,
                    "Are you sure to close this window?", "Confirm",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (opt == JOptionPane.NO_OPTION) {
                return;
            }
            System.out.println("exiting2.2...");
            //your code to be executed before window is closed.
        }
       
        super.processWindowEvent(e);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                WindowCloseTest test = new WindowCloseTest();
                test.setVisible(true);
            }
        });
    }
}

References:
1. How to execute code when JInternalFrame is closing programmatically
2. How to execute code when a JInternalFrame is closing after the [X] button is pressed

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Friday, January 24, 2014

Interpreter Design Pattern

The interpreter pattern is used to interpret a passed-in object using a set of definitions.

//The interpreter interface
public interface StringInterpreter {
      public void interpret(String input);
}

//The interpreter class
public class CharToNumber implements Interpreter {
 
      public void interpret(String input) {
            String result = "";
            for (int i=0; i < input.length(); i++) {
                  char c = input.charAt(i);
                  if (c == 'A') {
                        result += "1";
                  } else if (c=='B') {
                        result += "2"
                  } else {
                         result += "9";
                  }
            }
      }    
}

//The Runner
public class interpterDemo {
      public static void main (String[] args) {
            Interpreter inter = new CharToNumber();
            inter.interpret("ABABAABBCCCC");
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Command Design Pattern

In the command pattern, all requests for an object are passed to a common command interface. Each implementing  class of the command interface executes a particular method of the passed-in object when called.

//The command interface (interface or abstract class)
public interface Command {
      public void execute();
}

//The object to be requested for
public BookProcessor {
      String name;

      public BookProcessor(String n) {
            name = n;
      }

      public void borrowBook() {
            System.out.println("Borrowing book: " + name);
      }

      public void returnBook() {
            System.out.println("Returning book: " + name);
     }
}

//The concrete command classes
public class BorrowBook implements Command {
      private BookProcessor bp;

      public BorrowBook(String name) {
            bp = new BookProcessor(name)
      }

      //the command method
      public void execute() {
            bp.borrowBook();
      }
}

public class ReturnBook implements Command {
      private BookProcessor bp;

      public ReturnBook(String name) {
            bp = new BookProcessor(name)
      }

      //the command method
      public void execute() {
            bp.returnBook();
      }
}

//The Runner
public class CommandDemo {
      public static void main(String[] args) {
            Command borrow = new BorrowBook("Readers are Lucky");
            borrow.execute();

            Command return = new ReturnBook("Happy to finish");
            return.execute();
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, January 22, 2014

Chain of Responsibility Design Pattern

The chain of responsibility pattern is used to pass a request through a chain of processors until it is resolved. It usually has a interface or abstract class that defines the common fields, request levels,  and methods used by all the processors. Each implementing processor is specialized to process only requests below a certain level.

For example, a company is hiring new employees. The policy is that if the position is entry level, the team leader interviews the person and makes the decision; if it is middle level, the project leader does the interview and makes the decision; else if the position is senior level, the department chair does the interview and makes the decision.

//Create the HireProcessor common interface
public abstract class HireProcessor {
      public static final int ENTRY = 1;
      public static final int MIDDLE = 2;
      public static final int SENIOR = 3;

      protected int level;

      protected HireProcessor nextProcessor

      public void setNextProcessor(HireProcessor np) {
            nextProcessor = np;
      }

      public void process(int lev) {
            if (lev <= level) {
                  printDecision();
            } else {
                  nextProcessor.process(lev);
            }
      }

      protected abstract void printDecision();
}

//Create each processor
//Entry level processor
public class EntryHireProcessor extends HireProcessor {
      public EntryHireProcessor(int level) {
            this.level = level;
      }

      protected void printDecision() {
            System.out.println("Hire as an entry level employee.");
      }
}

//Middle level processor
public class MiddleHireProcessor extends HireProcessor {
      public MiddleHireProcessor(int level) {
            this.level = level;
      }

      protected void printDecision() {
            System.out.println("Hire as a middle level employee.");
      }
}

//Senior level processor
public class SeniorHireProcessor extends HireProcessor {
      public SeniorHireProcessor(int level) {
            this.level = level;
      }

      protected void printDecision() {
            System.out.println("Hire as a senior level employee.");
      }
}

//The Runner
public class ChainDemo {
      public static void main(String[] args) {
            //create the chain
            HireProcessor ep = new EntryHireProcessor(HireProcessor.ENTRY);
            HireProcessor mp = new MiddleHireProcessor(HireProcessor.MIDDLE);
            HireProcessor sp = new SeniorHireProcessor(HireProcessor.SENIOR);

            ep.setNextProcessor(mp);
            mp.setNextProcessor(sp);

            //call the first element in the chain to process a request
            ep.process(HireProcessor.SENIOR);
            ep.process(HireProcessor.MIDDLE);
            ep.process(HireProcessor.ENTRY);
            ep.process(HireProcessor.SENIOR);
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, January 21, 2014

Observer Design Pattern

The observer pattern is used in situation when one object is updated, a series of objects need to be notified. For example, a teacher uses a homework assigner to assign homework to students. whenever the homework assigner is updated, the registered student accounts will be notified.

Java has made this more convenient for it has already created an Observer interface and an Observable class.

//Create the HomeworkAssigner
public class HomeworkAssigner extends Observable {
    private JTextArea textArea;
    private String text;

    public HomeworkAssigner() {
        textArea = new JTextArea(5, 50);
        textArea.setEditable(true);
        text = "";

        textArea.addKeyListener(new HomeworkListener());
    }

    private class HomeworkListener extends KeyAdapter {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                System.out.println("listener fired");
                String newText = textArea.getText();
                if (!newText.equals(text)) {
                    text = newText;
                    //Observable methods to notify Observers
                    setChanged();
                    notifyObservers();
                }
            }
        }
    }

    public String getText() {
        return text;
    }

    public JTextArea getTextArea() {
        return textArea;
    }
}

//Create StudentAccount
public class StudentAccount implements Observer {
      private String name;
      private String emailAddress;

      public StudentAccount(String n, String e) {
            name = n;
            emailAddress = e;
      }
   
    @Override
      public void update (Observable nwa, Object arg) {
            String text = ((HomeworkAssigner)nwa).getText();
            //send email to student
            System.out.println("email sent to "+name+": "+text);
      }
}

//The runner
public class TestDemo {
     public static void main(String[] args) {
            HomeworkAssigner nwa = new HomeworkAssigner();
            Observer ob1 = new StudentAccount("Maria", "maria@gmail.com");
            Observer ob2 = new StudentAccount("John", "john@yahoo.com");
            nwa.addObserver(ob1);
            nwa.addObserver(ob2);

            JFrame frame = new JFrame();
            frame.getContentPane().add(nwa.getTextArea());

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Proxy Design Pattern

The proxy pattern is used to cash an object that is expensive to create (e.g. loading large media file) or retrieve from remote site through network. It acts as the interface for accessing the object. One of its major characters is to create/retrieve the object on the fly.

For example, a company has an office and need to access it to get information frequently.

//The interface
public interface Office {
      public Integer getDailySale();
      public void setDailyGoal();
      public boolean isOverSea();
}

//The concrete class
public class OverSeaOffice implements Office {
      private String manager;
      private boolean overSea;

      public OverSeaOffice(String m) {
            manager = m;
            overSea = true;
      }

      public Integer getDailySale() {
            return new Integer(500);
      }

      public void setDailyGoal() {
            System.out.println("Today is to make 200 contracts");
      }

      public boolean isOverSea() {
            return overSea;
      }
}

//The proxy. Only need to create the OverSeaOffice once
public class OfficeProxy implements Office {
      private String manager;
      private Office theOffice;

      public OfficeProxy(String m) {
            manager = m;
      }
   
       public Integer getDailySale() {
             if (theOffice == null) {
                  theOffice = new OverSeaOffice(manager);
            }
             return theOffice.getDailySale();
      }

      public void setDailyGoal() {
             if (theOffice == null) {
                  theOffice = new OverSeaOffice(manager);
            }
            theOffice.setDailyGoal();
      }

      public boolean isOverSea() {
            if (theOffice == null) {
                  theOffice = new OverSeaOffice(manager);
            }
            return theOffice.isOverSea();
      }
}

//The runner
public class OfficeRunner {
      public static void main(String[] args) {
            OfficeProxy op = new OfficeProxy("Smith");
            System.out.println(op.getDailySale());
            op.setDailyGoal();
            System.out.println("Is the office oversea? " + op.isOverSea());
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, January 20, 2014

Flyweight Design Pattern

The flyweight pattern is used to decrease the number of objects created, therefore reducing memory usage and increasing performance. For example, we have a BuildingMaker that is able to build with four types of materials: brick, stone, wood, and concrete. If we want to build 500 buildings, without using the flyweight pattern, 500 BuildingMaker objects are going to be created, however only four BuildingMaker objects are needed when the flyweight pattern is used.

public class BuildingMaker {
      private String material;

      public BuildingMaker(String m) {
            material = m;
      }

      public void build(int length, int width, int height) {
            System.out.println("Building house with " + material);
            System.out.println("The size of the house is: " + length + "x" + width + "x" + height);
      }
}

1. Without using the flyweight pattern


public class Builder {
      private numberOfBuidings = 500;
      private String[] materials = {"brick", "stone", "wood", "concrete"};
      private int minLength = 100;
      private int minWidth = 50;
      private int minHeight = 25;
   
      public void construct() {
            int len, wid, hei;
            String material;
            for (int i=0; i<numberOfBuidings; i++) {
                  len = minLength + Math.random()*20;
                  wid = minWidth + Math.random()*15;
                  hei = minHeight +  Math.random()*10;
             
                  material = Math.random()*materials.length;
                  BuildingMaker bm = new BuildingMaker(material);//500 BuildingMakers created
                  bm.build(len, wid, hei);
            }
      }
}

2. Using the flyweight pattern


//Create a BuildingMakerFactory to reuse the BuildingMaker set for a material type
public class BuildingMakerFactory {
       //maps material to BuildingMaker
       private HashMap<String, BuildingMaker> buildingMakerMap = new HashMap<String, BuildingMaker>();

      public BuildingMaker getBuildingMaker(String material) {
           BuildingMaker bm = buildingMakerMap.get(material);

            if (bm == null) {
                  bm = new BuildingMaker(material);
                  buildingMakerMap.put(material, bm);
            }

            return bm;
      }
}

public class Builder {
      private numberOfBuidings = 500;
      private String[] materials = {"brick", "stone", "wood", "concrete"};
      private int minLength = 100;
      private int minWidth = 50;
      private int minHeight = 25;

      private BuildingMakerFactory bmf = new BuildingMakerFactory();
   
      public void construct() {
            int len, wid, hei;
            String material;
            for (int i=0; i<numberOfBuidings; i++) {
                  len = minLength + Math.random()*20;
                  wid = minWidth + Math.random()*15;
                  hei = minHeight +  Math.random()*10;
             
                  material = Math.random()*materials.length;
                  BuildingMaker bm = bmf.getBuildingMaker( material);//maximum 4 BuildingMakers created
                  bm.build(len, wid, hei);
            }
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.



java.sql.SQLException: Io exception: The Network Adapter could not establish the connection

This exception can be caused by many problems such as wrong URL, wrong username/password, or the database server is not reachable from your computer. However, if you can access the database with sqlplus or other tools and checked the username/password carefully, it is most likely caused by using a wrong URL.

The basic structure of database URL is like this.

      jdbc:<vendor>:<driver type>@<database host ip address>:<port>:<database SID>

For example, an Oracle database URL could look like this: jdbc:oracle:thin:@11.08.0.123:1521:orcl

The database SID can be retrieved with the following query.

      select sys_context('userenv','instance_name') from dual;

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, January 17, 2014

Facade Design Pattern

The facade pattern collects a group of related objects and provides a single user interface to access these objects.

public abstract class Event {
      protected Calendar date;
      protected String place;
      protected String topic;

      public Event (Calendar date, String place, String topic) {
            this.date = date;
            this.place = place;
            this.topic = topic;
      }

      public abstract void addToSchedule();
}


public class Meeting extends Event {
   
      public void addToSchedule() {
            //add meeting to schedule
      }
}


public class Interview extends Event {
      public void addToSchedule() {
            //add interview to schedule
      }
}


//The single user interface
public class EventScheduler {
      private Event event;

      public void scheduleMeeting(Calendar d, String p, String t) {
            event = new Meeting(d, p, t);
            event.addToScehdule();
      }

      public void scheduleInterview(Calendar d, String p, String t) {
            event = new Interview (d, p, t);
            event.addToScehdule();
      }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Decorator/Wrapper Design Pattern

The Decorator/Wrapper pattern is used to add more functions to an existing class or interface. For example, you need to sort an array of Vectors, you have to make the vectors comparable. This can be done in two ways, one is using a subclass of Vector, the other is using the Decorator pattern.

1. Using a subclass


//Can access Vector method
public class ComparableVector extends Vector implements Comparable {
      public int compareTo (Object obj) {
            ComparableVector toBeCompared = (ComparableVector) obj;

            if (this.get(0) > toBeCompared.get(0)) {
                  return 1;
            } else if (this.get(0) < toBeCompared.get(0)) {
                  return -1;
            } else {
                  return 0;
            }
      }
}

public class VectorSorter1 {
      public static void main (String[] args) {
            ComparableVector cv1 = new ComparableVector(Arrays.asList(new Integer(100), newInteger(80), new Integer(101));

            ComparableVector cv2 =  new ComparableVector(Arrays.asList(new Integer(10), newInteger(88));

            ComparableVector cv3 = new ComparableVector(Arrays.asList(new Integer(130), newInteger(400), new Integer(10), new Integer(10));

            ComparableVector[] array = {cv1 ,cv2, cv3);

            Arrays.sort(array);
      }
}

2. Using the Decorator/Wrapper pattern


//Cannot directly access Vector methods.
public class ComparableVector implements Comparable {
     private Vector vector;

      public ComparableVector(Vector v) {
            vector = v;
      }

      public Vector getVector() {
            return vector;
      }

     //Need to write a method to access the corresponding Vector method
      public int size() {
            return vector.size();
      }

      public int compareTo (Object obj) {
            ComparableVector cv = (ComparableVector) obj;
            Vector toBeCompared = cv.getVector();

            Integer v1 = this.getVector().get(0);
            Integer v2 = toBeCompared.get(0);

            if (v1 > v2) {
                  return 1;
            } else if (v1 < v2) {
                  return -1;
            } else {
                  return 0;
            }
      }
}

public class VectorSorter2 {
      public static void main (String[] args) {
            Vector v1 = new Vector(Arrays.asList(new Integer(100), newInteger(80), new Integer(101));
             ComparableVector cv1 = new ComparableVector(v1);

            Vector v2 =  new Vector(Arrays.asList(new Integer(10), newInteger(88));
            ComparableVector cv2 = new ComparableVector(v2);

            Vector v3 = new Vector(Arrays.asList(new Integer(130), newInteger(400), new Integer(10), new Integer(10));
            ComparableVector cv3 = new ComparableVector(v3);

            ComparableVector[] array = {cv1 ,cv2, cv3);

            Arrays.sort(array);
      }
}

----------------------------------------------------------------------------------------------------------------
      
              
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.