Archive

Archive for April, 2009

Not able to connect to the Jboss server remotely?

April 29th, 2009

Not able to connect to the server remotely? All the services appear to be bound to localhost only. Here is the solution for connecting Jboss remotely.

Before 4.2.0.GA jboss always bound to the any address “0.0.0.0″. Many people would put unprotected instances of JBoss on the internet, or even on their own local LAN. For Security reason Jboss is bound only to localhost, now you have to explicitly choose to bound to any address or specific address, so with the “-b” option of jboss you can bound to any address. e.g.

For UNIX users:

./run.sh -b 0.0.0.0

For Windows users:

run.bat -b 0.0.0.0

Note: Starting the server with -b 0.0.0.0 will get things going for you.

S.Chandru Jboss , , ,

Creating a Flex 3 Web application in Tomcat integrated Server in MyEclipse

April 24th, 2009

This article is continuation of my previous article on Installing Flex Builder Plugin in MyEclipse In this article I’ve focused on how to create and deploy a Flex 3.0 and Java Web application using BlazeDS in Tomcat integrated server in MyEclipse.

Prerequisites:
  • Should have integrated Flex Builder with MyEclipse.
  • Download latest release of binary version of BlazeDS from Adobe Open source site - Point to be noted BINARY DISTRIBUTION TO BE DOWNLOADED NOT ‘TURNKEY’ VERSION - Turnkey version has Tomcat & Samples in built.
  • After download, unzip the zip file & further unzip the “blazeDS.war” file to a temp folder.
  • The temp folder contains two folders “META-INF” & “WEB-INF”. Keep this in one place.

Creating and Deploying Flex web application step by step:

  • Open MyEclipse
  • Create a new Web Project, not Flex Project as shown below.new-web-project
  • New Web Project Window screen appears. Fill in all credentials as shown in below image.webprojdetails
  • [Note: Below are the credentials which are used in this document]
  1. Project Name: “FlexSampleWeb”
  2. Location: “use default location”, or user can have their choice of directory here
  3. Source Folder: “src”
  4. Web root folder: “WebRoot”
  5. Context root url: “/FlexSampleWeb”.
  6. If user has JDK or Java EE 5.0 Version of Java installed, it might alert for the same, click Ok button. It basically means to use JDK 1.4 or whatever default version selected to be used for this project [Make sure it should be JDK 1.4 or higher - as it is required for BlazeDS]
  • Click Finish to See Web Project being created.
  • Now minimize MyEclipse, and go to “FlexSampleWeb” Project root directory which is created just few steps before. In general scenario it would be present in “[WorkSpace Folder] > FlexSampleWeb” directory or path.
  • Also open the blazeDS.war extracted directory
  • Copy both “META-INF” & “WEB-INF” directories from blazeDS extracted directory to “FlexSampleWeb” project’s “WebRoot” directory.
  • Probably it will ask user for existences of few files & and asks for confirming the operation.
  • Click YES button to overwrite the files. (Don’t panic this operation is not harmful)
  • Now open or maximize the MyEclipse Editor
  • Refresh “FlexBlazeDSSample” project
  • The latest files along with “BlazeDS” config files under “WEB-INF > flex” directory are seen
  • And checking the properties of project & moving to java build path > library should also show blazeDS libraries
  • Below snapshots should be the outcomeproperties-for-flexsampleweb
  • Close all properties windows or any windows opened.
  • Go to Windows, Open Server Window View, you would basically see “Tomcat” Server with stopped status
  • Click Start to Start the Server
  • Deploy the web project which is created just now
  • Right Click on Tomcat Server on Server Panel
  • Click Manage Deployments to deploy
  • New Deployment screen appears.
  • Click Finish to deploy the web project.
  • Now, create a Flex Project which will integrate with the web project which was created earlier.
  • Either from File Menu or through right click options being Flex Development Perspective, Create new project.new-flex-project
  • Fill in the credentials as shown in above image
  • Project Name - “FlexSampleUi”
  • Project location - “use default location” - user can choose directory of their choice
  • Application Type - “Web Application”
  • Server Technology
    1. Application Server Type - “J2EE”
    2. Check on “use remote object access service”
    3. “LiveCycle Data Service” Radio button being selected
    4. Uncheck “Create combined Java/Flex project using WTP” option.
  • Click Next to continue and below screen appears.configure-j2ee-server
  • Fill in the form as shown in below picture or snapshotconfigure-j2ee-server-step-2
  • For those who cannot see the above image, follow below steps
  • Server Location - Uncheck “Use default location”
  • Root directory - Browse through folder structure of your system to Web-Project’s “WebRoot” directory [Above created web project]
  • Root Url - type in the full fledge url to access the web project on server for me it was “http://localhost:8080/FlexSampleWeb “
  • Context Root - “/FlexSampleWeb” - if you have different context root, specify that here
  • Leave compilation options as is.
  • Compiled Flex application location - output folder - would have full path of WebRoot followed by “FlexSampleUi-debug”
  • Remove “FlexSampleUi-debug” and live it as shown in next snapshotconfigure-j2ee-server-step-3
  • Click Validate Configuration button to validate the configuration.
  • This operation will result in below snapshotconfigure-j2ee-server-step-4
  • Click Finish to complete Project creation and expand the directory structure in Navigator or File Explorer should look like belowflex-development
  • Click on Run Button selecting Flex Project to see that it opens up url “http://localhost:8080/FlexSampleWeb//FlexSampleUi.html”
  • The Screen should be empty as it has no source at all.
  • Now create a Java class called “HelloWorld” in “com.test” package in “FlexSampleWeb” Web Project
  • Copy the below code into the java file

    package com.test;
    import java.util.Date;

    public class HelloWorld
    {
    private String userSaid;

    public String repeat( String said )
    {
    this.userSaid = “Reply from server: ” + said;
    return this.userSaid;
    }

    public String sayHello()
    {
    Date now = new Date();
    return “Hello World ” + now;
    }
    }

  • Open Flex Mxml file and copy below code.

    <?xml version=”1.0″ encoding=”utf-8″?>

    <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>

    <mx:RemoteObject id=”myservice” fault=”faultHandler(event)” showBusyCursor=”true” destination=”Hello”>

    <mx:method name=”sayHello” result=”resultHandler(event)” />

    <mx:method name=”repeat” result=”resultHandler(event)” />

    </mx:RemoteObject>

    <mx:Script>

    <![CDATA[

    import mx.managers.CursorManager;

    import mx.rpc.events.ResultEvent;

    import mx.rpc.events.FaultEvent;

    private function faultHandler(fault:FaultEvent):void

    {
    CursorManager.removeBusyCursor();
    result_text.text = "code:\n" + fault.fault.faultCode + "\n\nMessage:\n" + fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail;
    }
    private function resultHandler(evt:ResultEvent):void
    {
    result_text.text = evt.message.body.toString(); // same as: evt.result.toString();
    }

    ]]>

    </mx:Script>

    <mx:Button x=”250″ y=”157″ label=”sayHello” width=”79″ click=”myservice.getOperation(’sayHello’).send();”/>

    <mx:Button x=”250″ y=”187″ label=”Repeat” click=”myservice.getOperation(’repeat’).send(myText.text); “/>

    <mx:TextArea x=”10″ y=”36″ width=”319″ height=”113″ id=”result_text”/>

    <mx:Label x=”10″ y=”10″ text=”Result:”/>

    <mx:TextInput x=”82″ y=”187″ id=”myText” text=”Sent to Server”/>

    </mx:Application>

  • BlazeDS server-side configuration:
    On the sever side, need to extend a BlazeDS configuration file to enable the Java service to be accessed later from the Flex client. Open the “remoting-config.xml” file in the project folder “FlexSampleWeb\WebRoot\WEB-INF\flex” and overwrite the content with the following:

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <service id=”remoting-service”
    class=”flex.messaging.services.RemotingService”>

    <adapters>
    <adapter-definition id=”java-object” class=”flex.messaging.services.remoting.adapters.JavaAdapter” default=”true”/>
    </adapters>

    <default-channels>
    <channel ref=”my-amf”/>
    </default-channels>

    <!– Flex Demo application –>

    <destination id=”Hello”>
    <properties>
    <source>com.test.HelloWorld</source>
    </properties>
    </destination>

    </service>

  • Save, Select web project back, refresh once, it should deploy the latest files on web project,
  • And start the tomcat server.
  • Now by selecting Flex Project, click on Run button to see the flex application the screen shown in snapshot below appears.output
  • Click on say hello button to see its functionality
  • Type in some message in text box & click on Repeat button to see the same on text area, which is returned from server

Source, Reference and Credit : Srinivas’s Blog

S.Chandru Adobe Flex, Java

Installing Flex Builder Plugin in MyEclipse

April 20th, 2009

This article puts emphasis on step by step installation of flex builder plugin in MyEclipse. These installation steps are carried out within Windows platform, but no need to worry you can follow these steps in any platform, only one thing to keep in mind is, to download the platform specific flex builder from the Adobe Site.

Follow the below given steps:
  • Download the Flex builder Plugin version from Adobe Site
  • Launch the installer. Installer starts up with the language selection screen.
  • Choose language of wish (Default is English) and click Ok, Introduction screen appears, and click next.
  • Next Screen is License Agreement. Read the License Agreement and click Yes to accept and continue.
  • Next Comes Choosing program and data location.
  • For Windows default path would be “C:\Program Files\Adobe\Flex Builder 3 Plug-in“; Select the desired path and click Next to proceed.
  • Choosing Eclipse directory location screen appears to Extend Form. Create a temporary folder “Eclipse” in “C:” or “D:” drive itself. This temporary Eclipse folder acts as a container for “links” folder which Flex Builder Installer places it. It does lot more than that, but as there is no configuration folder. choosefolder
  • Click Next, a window pops up notifying that the folder does not have any eclipse version in it. Click “Proceed with Caution” to proceed.supportedversion
  • Next would be selecting Additional Installations, select whatever needed and click Next.
  • The installer takes you to Installation Summary Section, showing all the details. Please make sure you have the things you had chosen before.reviewconfig
  • Click Install to begin the Installation process and ends up with installation Wizard Complete screen as below.installationcomplete
  • Upon completion, the installation Wizard Complete screen appears, Click Done to complete the installation process.
  • Now, open MyEclipse and in Menu navigate to Help > Software Updates > Find and Install
  • Feature Updates” Screen appearsfeatureupdates1
  • Check “Search for new features to install” radio button and click Next to continue.  “Update sites to visit” page will be appeared on screen.updatesitetovisit
  • Click “New Local Site” to browse the path the Flex Builder Plugin is installed. Under this installation, there would be a directory “com.adobe.flexbuilder.update.site“, select it, click Ok.
  • Upon selection of Flex Builder Plugin path. “Edit Local Site” Window appeared again, with url field being filled in, Fill in “Name” field with “Flex Builder” and click Ok.editlocalsite
  • “Update Site to visit” screen appears, with a list of plugins. i.e., Flex 3 Builder: [with path information], and list of features available. Select only Flex Builder 3 and click Next.finishinstall
  • Click Next to see “License agreement” window. Read the License Agreement and click Yes to accept and continue.featurelicense
  • Click Finish to complete the plugin installation.clickfinish
  • Upon completion of plugin installation to MyEclipse, the popup appears, prompting the user to restart MyEclipse. Click Yes to restart.
  • To create a small Test Flex project and to check plugin installation is proper switch to “Flex Development Perspective“.
  • Create a new project “Test”, Click Finish
  • Once done, user would see that in Problems window “Error” message popups.
  • Move to “design mode“, you would see error there too
  • Fix these errors before moving on, for that delete the project.flexdevelopment
  • This error or problem occurs because MyEclipse or the builder is unable to locate the SDK’s folder. To fix this, go to “Preferences” of “myEclipse.
  • Click “Flex > Installed Flex SDKs“. Errors are appearing in the window and show the reason too.
  • Select First one of the list, click “Edit“, would end up in “Edit Flex SDK” window. And then browse through and point it to “[Flex Builder Plugin Installation]\sdks\[Version First.. it's 2.0.1], click OK.
  • Update Flex SDK Name field with “Flex 2.0.1″ & click Ok to fix the error.installflexsdkinstallflexsdk2
  • Repeat for next one in the list, this time select “3.x.x” version under “sdks” folder & name it properly according to version & click Ok. And click Apply & then Ok to accept the changes. And Click on Install All button of the next screen.installall
  • User can download as many SDKs version as he/she wish, install it under “SDKS” version of Flex Builder plugin or which ever location user want, and then just point the SDK by adding new version as mentioned in the previous steps.
  • Create new Flex project and test the functionality of builder.

Note: Users switching to new workspaces are required to set the preferences again as mentioned in the above steps.

I hope this article will be useful for the beginers to install the Adobe Flex Builder 3 plugin in MyEclipse, and soon i will be writing article on Creating and deploying Adobe Flex 3 Web application using BlazeDS, Java and Tomcat integrated Server in MyEclipse. You can read my previous Adobe Flex 3 article Data Access with Flex 3

Source, Reference and Credit : Srinivas’s Blog

S.Chandru Adobe Flex , , , , ,

How Java Annotations Works

April 20th, 2009

java_annotationsThis article explains what are Java Annotations, How to define and use Java Annotation and how Java Annotations works. Java annotations are meta data provides data about a program that is not part of the program itself. They have no direct impact on the operations of the code they annotate. An annotation indicates that the declared element( can be field, class, method, package etc..,) should be processed in some special way by a compiler, development tool, deployment tool, or during runtime. To develop APIs require a fair amount of coding. For example, in order to write a JAX-RPC web service, we must provide a paired interface and implementation. This code could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible.

We can make our APIs less error-prone using annotations. Many APIs require additional files to be maintained in parallel with programs. For example, “JavaBean” requires a “AdditionalInfo” class to be maintained in parallel with it and Enterprise Java Bean (EJB) requires deployment descriptor.

The Java platform has always had various ad hoc annotation mechanisms. For example, the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used, and the transient modifier is an ad hoc annotation indicating that the field should be ignored during serialization. Java 5.0 has general purpose annotatons (aka metadata) allows you to define and use your own annotation type. The facility consists of a syntax for declaring annotation types, a syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations, and an annotation processing tool.

Annotation do not have direct impact on program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time. Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Annotation type declaration:

Annotation type declarations are similar to interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines the element of the annotation type, and method must not have any parameters or any throw clause. Return types are restricted to primitives, String, enum, annotations and array of the mentioned types. Method can also have default values.

Here is an illustration to declare annotation type.

package com.thetechhournals.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangeRequest
{
int    id();
String title();
String designer() default “[unassigned]“;
String status();    default “[unassigned]“;
}

The @interface in the code indicates that the interface itself is an annotation, It is required to be import java.lang.annotation package.

The next thing to be noted about the ChangeRequest annotation is @Retention(RetentionPolicy.RUNTIME) indicates that the @ChangeRequest is compiled into class file and made available to Java Virtual Machine at run time. This makes it possible for development tool to look for @ChangeRequest annotation through reflection at run time and to perform a specific task because the annotation was present in the code.

The other possible values for the @Retention annotation are:
  • The RetentionPolicy.SOURCE constant indicates that the annotation should be discarded by the compiler, and is usable by any development tools at coding time only.
  • The RetentionPolicy.CLASS constant indicates that the annotation is useful to the compiler, and should be retained in the .class file for use by the compiler at compile time.
Note: nless you are writing your own Java compiler, it is not possible to create your own useful compile-time annotations.

One more interesting part of the ChangeRequest annotation is @Target(ElementType.METHOD) indicates that the annotation should appear only on a method declaration but not on a class, a constructor, would generate a compiler error. It is possible to specify that an annotation appear on one or more elements within Java program, including on constructors, fields, local variables, method declarations, package declarations, parameter declarations; and class, interface, or enumeration declarations. Have look at below given example:

@Target({ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.TYPE})

How to use Java Annotation:

Once the annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:

@ChangeRequest(
id    = 226724,
title = “Enable - Express shipping”,
designer = “S. Chandru”,
status = “Work in progress”
)
public boolean expressShipping(){…}

An annotation type with no elements is termed a marker annotation type, for example:

public @interface Basic{ }

It is permissible to omit the parentheses in marker annotations, as shown below:

@Basic
public class Shipping{ ... }

In annotations with a single element, the element should be named value, as shown below:

public @interface Copyright
{
    String value();
}

It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, as shown below:

@Copyright("2009 The Tech Journals")
public class ShippingService{ ... }

How annotations works:

We will build small annotation-based MyAnnotation framework explain how annotation works. First let’s create a marker annotation type and should be run by the testing tool.

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation{ }

Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. @Target(ElementType.METHOD) indicate that MyAnnotation should appear on methods and @Retention(RetentionPolicy.RUNTIME) make MyAnnotation available to JVM at run-time.

Here is sample program that uses the above defined annotation type.

package com.thetechjournals.annotation;

public class UsingAnnotation
{
@MyAnnotation
public static void use()
{
System.out.println(”I’m using annotations”);
}
public static void dontUse()
{
System.out.println(”I’m using annotations”);
}
}

and the testing tool:

import java.lang.reflect.*;

public class RunAnnotation
{
public static void main(String[] args) throws Exception
{
for (Method m : Class.forName(”com.thetechjournals.annotation.UsingAnnotation”).getMethods())
{
if (m.isAnnotationPresent(MyAnnotation.class))
{
System.out.println(”Annotated elements process in special way”);
m.invoke(null);
}
}
}
}

Using reflection we are dynamically loading UsingAnnotation class and iterates over all the methods of the class. Invoking each method that is annotated with the MyAnnotation annotation type. isAnnotationPresent( annotationType ) returns true if an annotation for the specified type is present on this element, else false. We can now process all the annotated elements in special way e.g., we can perform some operation before and after executing only annotated element.

Source and reference : Sun Official Site

S.Chandru Java , , ,

Interview Questions : OOPs and Core Java

April 16th, 2009

OOPS and CORE JAVA

1. What is JVM (Java Virtual Machine)?

a. JVM is software implementation which stands on top of the hardware platform and OS.  It provides abstraction compiled java program and the hardware and OS. The Java virtual machine executes instructions that a Java compiler generates. All the Java programs are compiled into bytecodes(.class files). JVM  interpret Java bytecodes into instructions understandable by the particular processor.

2. What is OOPs?

a. Object-Oriented Programming (OOP) is a programming language model orgnized around the “Objects” rather than the “actions” and data rather than the logic. Programming techniques may include data abstraction, encapsulation, inheritance, information hiding, modularity and polymorphism.

3. What is Class?

a. Class is a template that describes the kinds of state and behavior that object of its type supports.

4. What is Object?

a. Object is run time entity and will have its own state and access to all of its behaviors defined by its class. At run time when JVM encounters the “new” keyword , it will use appropriate class create a object which is instance its class.

5. What is Interface?

a. Interface is 100% abstract super class that defines the methods a subclass must support, but not how they supported. A powerful companion to inheritance is the use of Interfaces.

6. What is abstract class?

a. Abstract class can never be instantiated, its sole purpose is to be extended(to subclassed). It is incomplete class.

7. What is the purpose of abstract class?

a. Consider a abstract class represent Person, it has three methods “numOfEyes”, “numOfLegs” and “sex”. Now conceptually all humans have to two legs and two eyes, but sex is something which can vary from person to person. So write implementaton for methods “numOfEyes” and “numOfLegs” and leave the method “sex” implemetation to subclass. Now class Male and class Female extends Person, implementation for method “sex” of Female is implemented in class Female and of Male is implemented in class Male.

8. What are the abstract methods?

a. Abstract methods do not have implementation. Abstrct methods should be implemeted in the subclass which inherits them. The class inherits abstract class should implement all the abstract methods or else java compiler will throw an error. Abstract class can have abstract methods. Abstract methods defined using “abstract” keyword.

9. What is state (instance variables) in Java?

a. State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object’s instance variables make up the object’s state.

10. What is Behavior (methods) in Java?

a. Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class’ logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.

11. What is relation between Classes and Objects?

a. They look very much same but are not same. Class is a definition, while object is instance of the class created. Class is blue print or prototype while objects are actual existing in real world. For example  CAR is class and Mustang is object of the class.

12. What is the difference between “Abstract” classes and “Interfaces”?

a. Abstract classes can only be extended by any class while Interface can not be, it has to be, implemented. Interfaces can not implement methods, whereas an abstract class can have implementation. Class can implement any number of interfaces but only one super class.

13. What is difference between Static and Non-Static fields of class?

a. Static fields are fields per class whereas Non-Static fields are fields per object of the class. Non-Static values are called as instance variables. Each object of the class has its own copy of Non-Static instance variables. So when a new object is created of the same class it will have completely its own copy of instance variable. Where in Static values have only one copy of instance variables and will be shared among all the objects of the class.

14. What is use of “instanceof”  keyword?

a. “instanceof” keyword is used to check what is the type of the object.

15. How do refer to a current instance of object?

a. You can refer the current instance of object using this” keyword.

S.Chandru Java ,