Wednesday, September 5, 2012

Design patterns usage in Java SE and Java EE



Creational patterns

Abstract factory (recognizeable by creational methods returning an abstract/interface type)

java.util.Calendar#getInstance()
java.util.Arrays#asList()
java.util.ResourceBundle#getBundle()
java.net.URL#openConnection()
java.sql.DriverManager#getConnection()
java.sql.Connection#createStatement()
java.sql.Statement#executeQuery()
java.text.NumberFormat#getInstance()
java.lang.management.ManagementFactory (all getXXX() methods)
java.nio.charset.Charset#forName()
javax.xml.parsers.DocumentBuilderFactory#newInstance()
javax.xml.transform.TransformerFactory#newInstance()
javax.xml.xpath.XPathFactory#newInstance()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String) (Returns singleton object per protocol)
______________________________________________________

Builder (recognizeable by creational methods returning the instance itself)

java.lang.StringBuilder#append() (unsynchronized)
java.lang.StringBuffer#append() (synchronized)
java.nio.ByteBuffer#put() (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer and DoubleBuffer)
javax.swing.GroupLayout.Group#addComponent()
All implementations of java.lang.Appendable 
______________________________________________________

Factory method (recognizeable by creational methods returning a concrete type)

java.lang.Object#toString() (overrideable in all subclasses)
java.lang.Class#newInstance()
java.lang.Integer#valueOf(String) (also on Boolean, Byte, Character, Short, Long, Float and Double) 
java.lang.Class#forName()
java.lang.reflect.Array#newInstance()
java.lang.reflect.Constructor#newInstance() 
______________________________________________________

Prototype (recognizeable by creational methods returning a different instance of itself with the same properties)

java.lang.Object#clone() (the class has to implement java.lang.Cloneable) 
______________________________________________________

Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)

java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop() 
______________________________________________________

Structural patterns

Adapter (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own/another abstract/interface type which decorates/overrides the given instance)

java.io.InputStreamReader(InputStream) (returns a Reader)
java.io.OutputStreamWriter(OutputStream) (returns a Writer)
javax.xml.bind.annotation.adapters.XmlAdapter#marshal() and #unmarshal() 
______________________________________________________

Bridge (recognizeable by creational methods taking an instance of different abstract/interface type and returning an implementation of own abstract/interface type which delegates/uses the given instance)
None comes to mind yet. A fictive example would be new LinkedHashMap(LinkedHashSet<K>, List<V>) which returns an unmodifiable linked map which doesn't clone the items, but uses them.

The java.util.Collections#newSetFromMap() and singletonXXX() methods however comes close. 
______________________________________________________

Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)

java.awt.Container#add(Component) (practically all over Swing thus)
javax.faces.component.UIComponent#getChildren() (practically all over JSF UI thus) 
______________________________________________________

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)

All subclasses of java.io.InputStream, OutputStream, Reader and Writer have a constructor taking an instance of same type.
java.util.Collections, the checkedXXX(), synchronizedXXX() and unmodifiableXXX() methods.
javax.servlet.http.HttpServletRequestWrapper and HttpServletResponseWrapper 
______________________________________________________

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

javax.faces.context.FacesContext, it internally uses among others the abstract/interface types LifeCycle, ViewHandler, NavigationHandler and many more without that the enduser has to worry about it (which are however overrideable by injection).
javax.faces.context.ExternalContext, which internally uses ServletContext, HttpSession, HttpServletRequest, HttpServletResponse, etc. 
______________________________________________________

Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)

java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short, Long, Float and Double) 
______________________________________________________

Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)

java.lang.reflect.Proxy
java.rmi.*, the whole API actually. 
The Wikipedia example is IMHO a bit poor, lazy loading has actually completely nothing to do with the proxy pattern at all.
______________________________________________________

Behavioral patterns

Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in another implementation of same abstract/interface type in a queue)

java.util.logging.Logger#log()
javax.servlet.Filter#doFilter() 
______________________________________________________

Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)

All implementations of java.lang.Runnable
All implementations of javax.swing.Action
______________________________________________________

Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

java.util.Pattern
java.text.Normalizer
All subclasses of java.text.Format
All subclasses of javax.el.ELResolver 
______________________________________________________

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

All implementations of java.util.Iterator (thus among others also java.util.Scanner!).
All implementations of java.util.Enumeration 
______________________________________________________

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

java.util.Timer (all scheduleXXX() methods)
java.util.concurrent.Executor#execute()
java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods)
java.lang.reflect.Method#invoke() 
______________________________________________________

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)

java.util.Date (the setter methods do that, Date is internally represented by a long value) 
All implementations of java.io.Serializable
All implementations of javax.faces.component.StateHolder 
______________________________________________________

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

java.util.Observer/java.util.Observable (rarely used in real world though)
All implementations of java.util.EventListener (practically all over Swing thus)
javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener 
______________________________________________________

State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle) 
______________________________________________________

Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)

java.util.Comparator#compare(), executed by among others Collections#sort().
javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
javax.servlet.Filter#doFilter() 
______________________________________________________

Template method (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)

All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. You're free to implement none or any of them. 
______________________________________________________

Visitor (recognizeable by two different abstract/interface types which has methods definied which takes each the other abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)

javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
javax.lang.model.element.Element and ElementVisitor
javax.lang.model.type.TypeMirror and TypeVisitor 

_________________________________________________________________
Source copied from: StackOverflow





Wednesday, August 22, 2012

Android App Development

Error when starting to run your first Android App

"debug certificate expired android packaging problem"

Solution:
1) Simply delete the debug.keystore file located under
C:\Documents and Settings\.android\ on Windows XP, 
or in C:\Users\.android\ on Windows Vista and Windows 7.

Friday, March 2, 2012

WHY VISIT TEMPLES ? (Scientific Reason)

WHY VISIT TEMPLES ? (Scientific Reason)
There are thousands of temples all over India in different size, shape and locations but not all of them are considered to be built the Vedic way. Generally, a temple should be located at a place where earth's magnetic wave path passes through densely. It can be in the outskirts of a town/village or city, or in middle of the dwelling place, or on a hilltop. The essence of visiting a temple is discussed here.

Now, these temples are located strategically at a place where the positive energy is abundantly available from the magnetic and electric wave distributions of north/south pole thrust. The main idol is placed in the core center of the temple, known as "*Garbhagriha*" or *Moolasthanam*. In fact, the temple structure is built after the idol has been placed. This *Moolasthanam* is where earth’s magnetic waves are found to be maximum. We know that there are some copper plates, inscribed with Vedic scripts, buried beneath the Main Idol. What are they really? No, they are not God’s / priests’ flash cards when they forget the *shlokas*. The copper plate absorbs earth’s magnetic waves and radiates it to the surroundings. Thus a person regularly visiting a temple and walking clockwise around the Main Idol receives the beamed magnetic waves and his body absorbs it. This is a very slow process and a regular visit will let him absorb more of this positive energy. Scientifically, it is the positive energy that we all require to have a healthy life.

Further, the Sanctum is closed on three sides. This increases the effect of all energies. The lamp that is lit radiates heat energy and also provides light inside the sanctum to the priests or *poojaris* performing the pooja. The ringing of the bells and the chanting of prayers takes a worshipper into trance, thus not letting his mind waver. When done in groups, this helps people forget personal problems for a while and relieve their stress. The fragrance from the flowers, the burning of camphor give out the chemical energy further aiding in a different good aura. The effect of all these energies is supplemented by the positive energy from the idol, the copper plates and utensils in the *Moolasthan*am / *Garbagraham*. *Theertham*, the “holy” water used during the pooja to wash the idol is not
plain water cleaning the dust off an idol. It is a concoction of Cardamom,*Karpura* (Benzoin), zaffron / saffron, *Tulsi* (Holy Basil), Clove, etc...Washing the idol is to charge the water with the magnetic radiations thus increasing its medicinal values. Three spoons of this holy water is distributed to devotees. Again, this water is mainly a source of magneto-therapy. Besides, the clove essence protects one from tooth decay, the saffron & *Tulsi* leafs protects one from common cold and cough, cardamom and *Pachha Karpuram* (benzoin), act as mouth fresheners. It is proved that *Theertham* is a very good blood purifier, as it is highly energized. Hence it is given as *prasadam* to the devotees. This way, one can claim to remain healthy by regularly visiting the Temples. This is why our elders used to suggest us to offer prayers at the temple so that you will be cured of many ailments. They were not always superstitious. Yes, in a few cases they did go overboard when due to ignorance they hoped many serious diseases could be cured at temples by deities. When people go to a temple for the *Deepaaraadhana*, and when the doors open up, the positive energy gushes out onto the persons who are there. The water that is sprinkled onto the assemblages passes on the energy to all. This also explains why men are not allowed to wear shirts at a few temples and women are requested to wear more ornaments during temple visits. It is through these jewels (metal) that positive energy is absorbed by the women. Also, it is a practice to leave newly purchased jewels at an idol’s feet and then wear them with the idol’s blessings. This act is now justified after reading this article. This act of “seeking divine blessings” before using any new article, like books or pens or automobiles may have stemmed from this through mere observation.

Energy lost in a day’s work is regained through a temple visit and one is refreshed slightly. The positive energy that is spread out in the entire temple and especially around where the main idol is placed, are simply absorbed by one's body and mind. Did you know, every Vaishnava(Vishnu devotees), “must” visit a Vishnu temple twice every day in their location. Our practices are NOT some hard and fast rules framed by 1 man and his followers or God’s words in somebody’s dreams. All the rituals, all the practices are, in reality, well researched, studied and scientifically backed thesis which form the ways of nature to lead a good healthy life.

The scientific and research part of the practices are well camouflaged as “elder’s instructions” or “granny’s teaching’s” which should be obeyed as a mark of respect so as to once again, avoid stress to the mediocre brains.

Thursday, January 19, 2012

Creating Flex/Java project with Eclipse Helios & Flash Builder 4 plugin

Not able to create a flex/java project with Flash builder 4 plug-in in Eclipse Helios version,
the work around is to use Eclipse Galileo and then open the project in Helios.

Eclipse Galileo/Helios Jboss6 setup

Eclipse Galileo/Helios does not have the JBoss 6 server adapter, so to make JBoss work from eclipse Galileo we need to download a plugin from http://www.cs.hs-rm.de/~knauf/public/index.html and copy it to the eclipse plugins folder.

MSDE Backup and Restore to SQLExpress 2005/2008


MSDE database backup and restore to MSQLExpress 2005/2008
  • To find out the databases in the MSDE run this command
    • OSQL -E –S SQLServerInstanceName –Q "SELECT name FROM sysdatabases"
  • To backup a specific database run this command
    • OSQL -U sa -P admin -S
                              
      Or
    • OSQL -E-S
    • BACKUP DATABASE dbname TO DISK = 'c:\path\to\backupfile.dat'
      Go
  • To restore a specific database run this command
    • RESTORE DATABASE newdb FROM DISK = 'c:\path\to\backupfile.dat' WITH REPLACE
      go

    • If that does not work, then you can enter the following statement as one continuous string, but follow the capitalizations and the spacing in the example.

      RESTORE DATABASE newdb FROM DISK = 'c:\path\to\backupfile.dat' WITH MOVE ' to 'c:\Program Files\Microsoft SQL
      Server\MSSQL$METRIX\Data\METRIXV120copy.mdf', MOVE 'to 'c:\Program Files\Microsoft SQL Server\MSSQL$METRIX\Data\METRIXV120copy.ldf'

       
    • To get the logical names run this command RESTORE FILELISTONLY FROM DISK = 'c:\path\to\backup.dat'

Quick Setup Instructions for MediaWiki


MediaWiki Setup Instructions.

  • Install Apache 2.2 or later 
  • Install Mysql 5 or later 
  • Install PHP from the zip version, just extract the files to a directory. The main directory should contain php5apache2.dll  and similar dll files. 
  • Setup PHP to work with MySqL by uncommenting the lines in php.ini file
    1. extension_dir="c:\php5.3.5\ext" 
    2. extension=php_mysql.dll

  • Setup PHP and Apache by adding these lines into httpd.conf
    1. LoadModule php5_module "c:/php5.3.5/php5apache2_2.dll"
    2. AddType application/x-httpd-php.php 
    3. PHPIniDir "C:/php5.3.5/"
    ** Note to change the Php installation directory to yours.

  • Create a database for the Wiki(dc_wiki_db), create a user/pwd and assign privileges for the user to this db. 
  • Download mediawiki latest version. 
  • Unzip the mediawiki zip file into the root directory of Apache, usually htdocs unless you have changed it. 
  • Navigate to the index.php file under the extracted mediawiki folder from the browser and follow the setup instructions. 
  • The installation will create a LocalSettings.php file under the root directory of mediawiki, this is the main configuration file for the mediawiki.