Wednesday, 26 December 2012

Knowledge Simplified (Java)


What is a Class in Java?

What is a Class in Java?

A class is a blueprint for an object. Just as an architect creates a blueprint before the construction of a house, similarly in Java we need a class before we construct an object or before we “instantiate” an object. In software terms we call creation of an object from a class as instantiation.



Again, in the real world we see that before we construct a bridge or a ship we always create a blueprint. Then using that blueprint we can create hundreds of ships or hundreds of bridges.  So this means that once you have the blueprint in place it is easier to construct objects and the same concept is used in Java. You will see that we create a class and then keep instantiating objects from it, as and when we like.



How would you instantiate an object from a class in Java, I mean in programming terms?
Use the “new” keyword and you have your object.
House houseObject = new House()
How about making your own class, a BRIDGE or a FRIDGE?

What is Encapsulation?

What is Inheritance?

What are objects and classes?

http://ksimplified.com/?cat=1





Thanks for visiting................

Tuesday, 4 December 2012

Maven Tutorial

http://www.shankh.com/2009/07/12/maven-commands-reference-mini-guide/

Good Tutorial for learning PureMVC with Sample Code

Good Tutorial for learning PureMVC  with Sample Code:-
(url: http://codeofdoom.com/wordpress/2009/01/25/puremvc-sample/ )


Well it has been awhile since I have written anything, but that doesn’t mean that I haven’t been busy. Lately at work I’ve been working a lot more closely with Flex, writing some pretty creative/new custom components, learning a lot, etc. Lately we discussed the possibilities of switching from the standard use of Cairngorm to the use a PureMVC, so I wanted to go over a brief tutorial of PureMVC to show how its used. Later I will be posting a short article over the differences of cairngorm vs PureMVC.

First, what is PureMVC? It’s an open source MVC (Model, View, Component) framework that has now been ported over to 10 different languages (latest has been to Objective C for iPhone dev) that really forces you follow the rules of MVC. It allows you to separate out all of your logic of retrieving your data, for what to do with that data, what components get what, etc all through one central facade object. Now this tutorial will be focusing on how it works with the singleton core, but they also have the notion of a “multiton”, which is basically a map of singletons.
Quick run down of the 4 parts.
  • Proxies are used to manage your data object. It will be the one that requests your data. Once the data returns, it will then fire off a notification stating that the data has returned.
  • Mediators are used to managed your components. This also picks up notifications of data and that is where you will set the data to your components.
  • Commands are mostly there to interact with the Proxies and Mediators
  • Facade is the single interface (also are a singleton) used to manage the communications of your application
So lets start diving into some code. In this example, I am basically using a HTTPService to load an rss feed into a datagrid.
First things first, we grab an instance of our facade and pass in the components we want to register with it. This is within the PureMvcExample.mxml file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationComplete()">
 <mx:Script>
  <![CDATA[
   import mx.controls.DataGrid;
   import mx.controls.ComboBox;
   import mx.controls.Label;
   import com.codeofdoom.puremvc.facade.MyFacade;
   public function creationComplete():void{
    var facade:MyFacade = MyFacade.getInstance();
    facade.startup(grid);
   }
  ]]>
 </mx:Script>
 <mx:DataGrid id="grid" width="80%">
  <mx:columns>
   <mx:DataGridColumn dataField="title"/>
   <mx:DataGridColumn dataField="link"/>
   <mx:DataGridColumn dataField="description"/>
  </mx:columns>
 </mx:DataGrid>
</mx:Application>
When you first initialize the facade, you will notice there is an initializeController method called whenever you do super() in the constructor. This is where it will register your command to start the application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.codeofdoom.puremvc.facade
{
 import com.PureMvcConstants;
 import com.codeofdoom.puremvc.command.StartUpCommand;
 
 import org.puremvc.as3.interfaces.IModel;
 import org.puremvc.as3.patterns.facade.Facade;
 import org.puremvc.as3.patterns.observer.Notification;
 
 public class MyFacade extends Facade
 {
  public function MyFacade()
  {
   super();
  }
  public static function getInstance():MyFacade {
   if (instance == null) {
    instance = new MyFacade( );
   }
   return instance as MyFacade;
  }
  public function startup(app:Object):void{
   notifyObservers(new Notification(PureMvcConstants.STARTUP,app));
  }
 
  override protected function initializeController():void {
   super.initializeController();
   registerCommand(PureMvcConstants.STARTUP, StartUpCommand);
  }
 
 }
}
As you see, the StartUpCommand just extends Command and is used to registered both the proxies and the mediators with the facade. Nothing too special.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.codeofdoom.puremvc.proxy
{
 import com.PureMvcConstants;
 import com.codeofdoom.puremvc.facade.MyFacade;
 import flash.net.URLRequest;
 import flash.utils.Proxy;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.http.HTTPService;
 import org.puremvc.as3.interfaces.IProxy;
 import org.puremvc.as3.patterns.observer.Notification;
 
 public final class MyProxy extends Proxy implements IProxy
 {
  public static const NAME:String = "com.codeofdoom.puremvc.MyProxy";
  private var _service:HTTPService;
  private var _xml:XML;
 
  public function MyProxy(data:Object = null){
   super();
   setup();
  }
 
  private function setup():void{
   _service = new HTTPService();
   _service.resultFormat="e4x";
   _service.url = "http://feedproxy.google.com/IdeaExcursion";
   _service.addEventListener(ResultEvent.RESULT,onLoad); 
  }
 
  private function onLoad(e:ResultEvent):void{
   var facade:MyFacade = MyFacade.getInstance();
   facade.notifyObservers(new Notification(PureMvcConstants.DATA_LOADED,e.result));
  }
 
  public function getProxyName():String{
   return NAME;
  }
 
  public function loadInfo():void{
   _service.send();
  }
 
 }
}
When we initialize MyProxy, you will notice that it will call setup(). This is what we use to setup the service call. We add an eventlistener to it for when data comes back and thats where some fun stuff goes on. Now that our proxy is initialized, the next line in the StartUpCommand is to initialize the mediator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.codeofdoom.puremvc.mediator
{
 import com.PureMvcConstants;
 import com.codeofdoom.puremvc.proxy.MyProxy;
 import mx.controls.DataGrid;
 import org.puremvc.as3.interfaces.IMediator;
 import org.puremvc.as3.interfaces.INotification;
 import org.puremvc.as3.patterns.mediator.Mediator;
 
 public class MyMediator extends Mediator implements IMediator
 {
  public static const NAME:String = "com.codeofdoom.puremvc.mediator.MyMediator";
 
  public function MyMediator(viewComponent:Object=null)
  {
   super(NAME, viewComponent);
   loading();
  }
 
  override public function getMediatorName():String
  {
   return NAME;
  }
 
  override public function getViewComponent():Object
  {
   return viewComponent;
  }
 
 
  override public function listNotificationInterests():Array
  {
   return [PureMvcConstants.DATA_LOADED];
  }
 
  override public function handleNotification(notification:INotification):void
  {
   switch (notification.getName()){
    case PureMvcConstants.DATA_LOADED:
     var xml:Xml = notification.getBody().channel.item;
     (viewComponent as DataGrid).dataProvider = xml;
     break;
    default: viewComponent.text = "notification name not found";
   }
  }
 
  public function loading():void{
   MyProxy(facade.retrieveProxy(MyProxy.NAME)).loadInfo();
  }
 }
}
Now whenever we register a mediator, within PureMVC, it will call the listNotificationInterests method. This is what tells PureMVC which events that this specific mediator cares about. For our example, we only care about PureMvcConstants.DATA_LOADED. Inside the constructor, we then call loading that calls MyProxy to go retrieve the data. Note that we are receiving the proxy through the facade. Typically you would have an interface that you would cast this to in a real application and not cast MyProxy directly, but this is just an example.
So lets look back at MyProxy.
1
2
3
4
private function onLoad(e:ResultEvent):void{
 var facade:MyFacade = MyFacade.getInstance();
 facade.notifyObservers(new Notification(PureMvcConstants.DATA_LOADED,e.result));
}
The loadInfo() just has a _service.send() call. After that our eventlistener that we setup before picks it up. All that does is just takes the data uses the facade to fire off the notification that “here is some data” (under the fancy name PureMvcConstants.DATA_LOADED) . But who is listening?
Recall earlier that our mediator listed PureMvcConstants.DATA_LOADED as an “interest”.
1
2
3
override public function listNotificationInterests():Array{
 return [PureMvcConstants.DATA_LOADED];
}
So if you go back to MyMediator, there is a handleNotificationMethod that we have overridden.
1
2
3
4
5
6
7
8
override public function handleNotification(notification:INotification):void{
 switch (notification.getName()){
  case PureMvcConstants.DATA_LOADED:
   var xml:Xml = notification.getBody().channel.item;
   (viewComponent as DataGrid).dataProvider = xml;
   break;
 }
}
This is where we take our data back that was sent off with the notification and apply it to our viewComponent.
You might not notice it, but I feel the mediator level is what really makes PureMvc special. We have now separated out application specific code into their own class. With this extra layer, if you wanted to swap out what happens when data comes back in the application, all you have to do is change the mediator. You dont have to worry about writing that code within the viewComponent itself anymore.
Now this is a small example of how the flow of a PureMvc application works, but normally you would pass in a higher level component as your viewComponent into the mediator. Something that will contain 1 or more actual components within it. If you didnt take that route, then you are talking about having proxys and mediators for everything. I suppose that is doable, but it is probably not recommended.
Here is the source

How and when to use Singleton classes


How and when to use Singleton classes

It’s a pretty well known pattern, but I want to discuss what a Singleton class is first. In a nutshell, a Singleton class is a class that will only have one instance of the class. In certain cases, we want to make sure that we cannot instantiate multiple copies of the object, so we limit it to just one copy. Instead of having a public constructor for our class, we use a private constructor. Then we use a public method (usually named getInstance()) to make sure there is only one copy.

Here is how it looks:
1
2
3
4
5
6
7
8
9
10
11
public class Singleton {
   private static final Singleton instance;   
 
   private Singleton(){}
 
   public static Singleton getInstance() {
     if (instance == null)
       instance = new Singleton();
     return instance;
   }
 }
As you can see, the constructor is private, so we are unable instantiate it in the normal fashion. What you have to do is call it like this:
1
public Singleton singleton = Singleton.getInstance();
When you do this, the getInstance() method then checks to see if the parameter ‘instance’ is null. If it is, it will create a new one by calling the private constructor. After that, it just returns it. Of course, if it is not null, it just returns the existing instance of it. This insures that there is only one copy of the object within your program.
Of course, this post wouldn’t have much meat to it if thats what I left it at. So lets talk about some of the uses of a Singleton class. Also you might at some point as ‘why not just make it static?’, which is a common question, so I will go over that about that as well.
First, what are the uses of a Singleton?. Singleton classes are normally used for things such as a Factory classes, Builder classes and things like that. A few real world examples include the the SessionFactory class in Hibernate – it’s actually a singleton. Or with log4j, when you call its logger, it uses a singleton class to return it. If anyone has used Cairngorm within Flex/Actionscript 3, its model locator is a Singleton.
So why do we want to use singleton’s in these instances? Lets look at the ModelLocator example within Cairngorm. The model locator is used within Cairngorm to keep the state of data within our Flex application. But the reason why its kept in this one object is that it is used across multiple components. The data in one component is usually important to another component, so everything is managed in one central object. It’s quick to realize why we only want one of these in our program. If not, it would be pretty tough to maintain state if other components are affecting data providers that others are using.
Another question that usually comes up when it comes to using a Singleton is “Why not just use a static class?”. Static classes still have many uses and lots of times, people get confused and will use a Singleton as much as possible. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.
So here is a quick list of uses for static classes:
Math.pow(double a, double b);
Interger.parseInt(String s);
Interger.toString(int i);
As you can see, the state of these methods don’t matter. You just want to use them to perform a simple task for you. But if you coding your application and you are using a central object where state does matter(such as the ModelLocator example), then its best to use a Singleton.
The next reason you may want to use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, you probably only one of those objects floating around. This is the case for things like a if you have a factory method that is particularly robust, you want to make sure that its not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening.
The Singleton is a simple and powerful design pattern. Newer programmers may not realize what potential it has and will over look it. Others may love it so much and end of overusing it in the wrong way. Hopefully this article was helpful for you.


Thanks for Visiting............

What is the crossdomain.xml file?


What is the crossdomain.xml file?
The crossdomain.xml file is a cross-domain policy file. It grants the Flash Player permission to talk to servers other than the one it's hosted on.
In what circumstances do I need to use one?
You need a crossdomain.xml file when your Speedtest uses external hosts as testing servers.
  • the Speedtest application is hosted on your main webserver (www.mycompany.com for example), but you have a dedicated testing server that the test uses. (speedtest.mycompany.com)
  • You want to use more than 2 threads. You will need a crossdomain file to allow access to speedtest2.mycompany.com
  • You have multiple servers
What should it look like?
If your company's website is hosted at www.mycompany.com and you also wanted to allow speedtest.net to use your server as a host, your crossdomain would look like:
<?xml version="1.0"?>
<cross-domain-policy>
    <allow-access-from domain="*.mycompany.com" />
    <allow-access-from domain="*.speedtest.net" />
</cross-domain-policy>

This file goes in  the root of document folder on the server you want to allow access. Ex: http://speedtest.mycompany.com/crossdomain.xml in this case.


url:(https://support.ookla.com/entries/21097566-what-is-crossdomain-xml-and-why-do-i-need-it)


Thanks for visiting.........

Friday, 30 November 2012

Imp Tutorial for Java Developers


1. Spring Integration with different Technologies
 http://krams915.blogspot.in/p/tutorials.html

2. Hibernate,Springs
 http://javabrains.koushik.org/

3. Servlets,JSP
http://www.sharmanj.com/

Wednesday, 28 November 2012

String Manipulation in Java(Mutable and Immutable)


String Manipulation in Java:
(http://sourcecodemania.com/string-manipulation-in-java/)

A string is a sequence of symbols. Java provides you with String class in java.lang package, which does not require an import statement. That means Strings are available to use anywhere. String class provides many operations for manipulating strings.
·         Constructors
·         Utility
·         Comparisons
·         Conversions
An object of the String class represents a string of characters.
String Basics-Declaration and Creation
There is no single way to create a string in java. Following are some of the different ways to create strings in java:
String str = "niit";
str="seecs";
String name=str;
String stringName= new String ("string value");
String city=  new String ("Islamabad");
In Java, we traditionally declare a String with initial value of null. If we declare a String variable without initialization e.g String myString; what would happen? We have to initialize String variable with special null value, if you really don’t want to initialize it with useful value at the start.
String myString = null;
We can define an empty string as given below:
String str = new String( );

We can define a string with initial value as:
String str = new String("Java Strings");
(Note!  String str = “Java Strings”; produces the same result)
Immutability
Characters in Strings can not be changed after the Strings are created. Once created, a string cannot be changed. None of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely. There is no danger of changing an object through one reference without the others being aware of the change.
Immutable strings are efficient because it uses less memory. Following figure might explain the difference between mutable and immutable strings.
String Objects
String objects are immutable — they cannot be changed once they have been created.  References to string objects may be changed.
String str1 = new String("I like dogs.");
String str2 = new String("I prefer cats.");
str1 = str2; //reassign reference
String Operations in Java
String Classes:
Following are some useful classes that Java provides for String operations.
·         String Class
·         StringBuffer Class
·         StringTokenizer Class
String Operations:
·         int length()
·         char charAt(int index)
·         indexOf( ) & lastIndexOf( )
·         indexOf(char ch)          // first position of ‘ch’
·         indexOf(String str)       // first position of ‘str’
·         lastIndexOf(char ch)    // last position of ‘ch’
·         lastIndexOf(String str) // last position of ‘str’
·         String Substring (int) & String Substring (int startindex, int lastindex)
·         public String toLowerCase() & public String toUpperCase()
·         startsWith(String prefix)   &  endsWith(String suffix )
·         public String trim() – Returns a copy of the string, with leading and trailing whitespace omitted.
·         public String replace(char oldChar, char newChar) – Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
·         Concatenation  (+) returns  a string


Concatenation Example
Declare and construct two strings, then concatenate str2 to the end of str1.
String str1 = new String("This is the winter");
String str2 = new String("of our discontent");
str1 = str1.concat(str2); //concatenate str1 with str2
Note! The same result occurs for str1 = str1 + str2;
toCharArray( )
String string1 = "Hello How are you";
char[] array = string1.toCharArray();
copyValueOf( )
Static method
String string2;
string2 = String.copyValueOf(array); //copyValueOf(array,6,3);
String Comparison
Following are different ways to compare strings in Java.
·         Shallow comparison  = =
·         Deep comparison     equals( );
·         Deep comparison     compareTo( );
Shallow comparison using ==
The == will check whether the two String variables refer to the same string. If strings reference two separate strings, you will get false regardless of whether or not the strings happen to be identical. It does not compare the strings themselves, it compares the references to the strings, hence called shallow comparison.
Deep Comparison using equals()
Equals( ) is used to decide whether the strings referred by two String variables are equal or not. This method does a case sensitive comparison. Two strings are equal if they are the same length and each character in one string is identical to the corresponding character in the other. Use equalsIgnoreCase( ) method to check for equality between two strings ignoring the case of the string characters.
String s1 = new String ("I am a string");
String s2 = " a string";
String s3 = s1.substring(0,4);
String s4 = " a string";
String s5 = s3 + s2;
if (s5 == s1) {  }
if (s1.equals(s5))  {  }
if (s2 == s4)  {  }
if (s5.equals(s3+s4))  {  }
Deep Comparison using compareTo()
compareTo( ) is used to decide whether the string object from which it is called is less than , equal to or greater than the string passed as argument to it. Returns an integer which is negative if the String object is less than the argument String. Returns positive integer if the String object is greater than the argument String. It returns zero if both are equal.
System.out.println("hello".compareTo("hell"));  // returns 1
StringBuffer objects can be altered directly. A String object is always a fixed string. How to create StringBuffer objects?
StringBuffer string1 = "Hello How are you";//not allowed
StringBuffer string1 = new StringBuffer("Hello How are you");
StringBuffer contains a block of memory called buffer which may or may not contain a string and if it does, the string need not occupy all of the buffer.
append( );
string1.append("To");
string1.append(string2,3,3); //appending substrings
string1.append(x);//where x is an int
insert( );
string1.insert(4," how");//4 is the index position
insert also has many versions like append
Other Useful methods of StringBuffer Class
You can produce a String object from a StringBuffer object by using the toString( ) method of the StringBuffer class
String string2 = string1.toString( );
How does the compiler handles the string concatenation of String objects? Append( ) and toString( ) methods are used
String message = "hello" + "How are you";
String message = new StringBuffer( ).append("Hello").append("how are you").toString( );


Thanks for Visiting............