Saturday, November 7, 2015

Composite Component in JSF

Any component is essentially a piece of reusable code that behaves in a particular way. JSF 2 composite tag library facilitate you to create reusable components Facelets from the existing components. In this tutorial we will learn, how to create a simple composite component (registerComp.xhtml), a user registration form, which comprises name and email fields and a submit to button to process the action.

A composite component is a Facelet that resides in a resource library. So the component you are going to create must reside under the resource folder. Let's say if you are going to put the components under the folder named customcomponent. The Directory structure of your project will look like this below. Here the folder name resource is a must, except the resource folder name, all other folders and file names are user defined.



Now we will see, what are the contents, we need to place in our registerComp.xhtml, which we have created.

1) First we need to define the Composite Namespace in the html header as shown below

 <html xmlns="http://www.w3.org/1999/xhtml"    
    xmlns:h="http://java.sun.com/jsf/html"  
    xmlns:f="http://java.sun.com/jsf/core"  
    xmlns:composite="http://java.sun.com/jsf/composite"  
    >  
 ...  
 </html>  

2) Next Composite Tags. Below are the some of the tags available, but we will be using the composite:interface, composite:attribute and composite:implementation for our simple example.

Tag Description
composite:interface Declares the usage contract for a composite component. The composite component can be used as a single component whose feature set is the union of the features declared in the usage contract. Within the tag ( parent tag ) you can add the children tags to it according to the implementation requirements. In short it is used to declare the configurable values which are exposed to the developer who use it.
composite:implementation Defines the implementation of the composite component. If a composite:interface element appears, there must be a corresponding composite:implementation. It is used for implementing the composite components declared in the composite:interface. To access the component interface attributes an expression #{cc.attrs.attribute_name} is used (cc is a reserved keyword in JSF).
composite:attribute Declares an attribute that may be given to an instance of the composite component in which this tag is declared. This tag can be used inside the tag by a zero or many times according to the requirement. This tag can also be nested inside the other tag
composite:insertChildren Any child components or template text within the composite component tag in the using page will be reparented into the composite component at the point indicated by this tag’s placement within the composite:implementation section.
composite:valueHolder Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of javax.faces.component.ValueHolder suitable for use as the target of attached objects in the using page.
composite:editableValueHolder Declares that the composite component whose contract is declared by the composite:interface in which this element is nested exposes an implementation of javax.faces.component.EditableValueHolder suitable for use as the target of attached objects in the using page.

 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml"    
    xmlns:h="http://java.sun.com/jsf/html"  
    xmlns:f="http://java.sun.com/jsf/core"  
    xmlns:composite="http://java.sun.com/jsf/composite"  
    >  
   <!-- INTERFACE -->       
   <composite:interface>  
        <composite:attribute name="userNameLable" />  
        <composite:attribute name="userNameValue" />  
        <composite:attribute name="emailLable" />  
        <composite:attribute name="emailValue" />  
        <composite:attribute name="registerButtonText" />  
        <composite:attribute name="registerButtonAction"   
             method-signature="java.lang.String action()" />  
   </composite:interface>  
   <!-- IMPLEMENTATION -->  
   <composite:implementation>  
      <h:form>  
           <h:panelGrid columns="2" id="textPanel">  
                #{cc.attrs.userNameLable} :   
                <h:inputText id="userName" value="#{cc.attrs.userNameValue}" />  
                #{cc.attrs.emailLable} :   
                <h:inputText id="email" value="#{cc.attrs.emailValue}" />  
           </h:panelGrid>  
           <h:commandButton action="#{cc.attrs.registerButtonAction}"   
                value="#{cc.attrs.registerButtonText}"  
           />  
      </h:form>  
   </composite:implementation>  
 </html>  

Now we have created the component, make sure that it resides in the resource folder.

3) Now let's see how to define this component for usage. Use the Custom Namespace

 <html xmlns="http://www.w3.org/1999/xhtml"    
   xmlns:h="http://java.sun.com/jsf/html"  
   xmlns:ui="http://java.sun.com/jsf/facelets">  
   xmlns:customcomponent="http://java.sun.com/jsf/composite/customcomponent">  

xmlns:customcomponent="http://java.sun.com/jsf/composite/customcomponent"
The first part defines that the namespace for the composite component is "customcomponent", and the second part declares where in the resources folder to find the definition of this composite component. In this example its in the "customcomponent" subfolder inside resources.



4) Now let's how to use and pass values to the Component

This is how you use the tag: namespace:FileName; in our example customcomponent:registerComp, registerComp is the name of the file, so by default its the tag name;

 <customcomponent:registerComp   
           userNameLable="Name"   
           userNameValue="Ramanujam"   
           emailLable="E-mail"   
           emailValue="reachram_ramesh@hotmail.com"  
           registerButtonText="Register"   
           registerButtonAction="#{register.userAction}"  
       />  

Above, we have passed the hard coded values to the userName and email and binded the submit to userAction in a managed bean named register

That's all we have created a new Composite Component. Now when you call the page, which has the defined composite component, you will see the form, which has username and email value hardcoded, and a submit button.

Happy Programming...!!!

Monday, October 5, 2015

Modules in Angular JS


Modules
Modules in angular can be thought of as a container where all the other parts of our application like controllers, services etc will be contained in and which specify how an application should be bootstrapped. You can think of a module much like a namespace in C# or Java, except that they are a little more than that.The difference between a module in Angular and a typical namespace is that modules also have methods on them for initialization of the module and for creation of controllers, services, etc. The best part about module is that a module can easily be passed to another module and its functionality can easily be used by other modules. Following are the benefits of using Modules

  • Helps package our code into reusable modules.
  • The declarative process is easier to understand
  • Modules can be loaded in any order.
  • Easily testable and maintainable components.
  • Helps organize your application.

Application Modules - used to initialize an application with controller(s).
Controller Modules - used to define the controller.


To create a module, we need to use the angular.module function. Lets create a simple module named "myApplication".

So to create our module, add the following to the JavaScript:

var myModule = angular.module('myApplication', []);

Notice that there are two parameters passed into the module method: The name of your module and an array. In this example we’re not passing anything into the array, but we could pass in a list of strings that refer to other module names (this is why you need a name for your module in the first place). Passing in other module names in that array allows your new module to inherit the controllers, services, etc. from those modules.So lets say we have another module called "myAnotherApplication" which would want to use the above defined module. We will have to pass the myApplication in the array argument as shown in the following code


var myAnotherModule = angular.module('myAnotherApplication', ["myApplication"]);

We can pass any number of modules in the array, and the created module will have access to all services, controllers available in the injected modules. Once we defined the module, we get handle of the module as below

var myModule = angular.module('myApplication');

Observe that there is no second argument here which means we are getting the reference of a predefined angular module. If you include the second argument, which is an array, then it means you are defining the new module.

Now you have defined the module, you are all set to create all the components inside of this module. After you have done everything, how we are going to use this in our pages. If you want any of your page to use the angular module, we need to put the ng-app="myApplication" in that view. Let's see how we can achieve this.

To reference our module, change that ng-app attribute on the body to look like this:

 <body ng-app="myApplication"> ... </body>  

It's not necessary that the attribute need to be defined in the body tag, you can define in the html tag also as below

 <html ng-app="myApplication">....</html>  

Happy Programming.

Sunday, August 2, 2015

Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource


Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]

I encountered this error when, i was doing a sample web application, using Annotations fully. Below is the sample snippet, which triggered the above issue. Once i registered the AppConfig to the AnnotationConfigWebApplicationContext, i added context.refresh, to fully process the class, which results in the above exception, when i removed the context.refresh, everything seems to be fine, but when i add it back, i am getting the same exception, so what triggers the issue?

public class AppInitializer implements WebApplicationInitializer{
 
 private static final String MAPPING_URL = "/";

 public void onStartup(ServletContext servletContext) throws ServletException {
  AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
  context.register(AppConfig.class); 
  servletContext.addListener(new ContextLoaderListener(context));
  context.refresh();
  ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new CustomDispatcherServlet(context));
  dispatcher.setLoadOnStartup(1);
  dispatcher.addMapping(MAPPING_URL);  
 } 
 
}

As per DispatcherServlet Constructor as specified here

  • If the given context does not already have a parent, the root application context will be set as the parent.
  • If the given context has not already been assigned an id, one will be assigned to it
  • ServletContext and ServletConfig objects will be delegated to the application context
  • FrameworkServlet.postProcessWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext) will be called
  • Any ApplicationContextInitializers specified through the "contextInitializerClasses" init-param or through the
  • FrameworkServlet.setContextInitializers(org.springframework.context.ApplicationContextInitializer...) property will be applied.
  • refresh() will be called if the context implements ConfigurableApplicationContext

If the context has already been refreshed, none of the above will occur, under the assumption that the user has performed these actions (or not) per their specific needs.

So for the DispatcherServlet, you modify the code as below

AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
context.register(WebConfig .class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new CustomDispatcherServlet(webContext));

Sample Code of the WebConfig class as shown below.

@Configuration
@Configuration
@EnableWebMvc
@ComponentScan("com.practice")
public class WebConfig extends WebMvcConfigurerAdapter{

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);

}

Happy Programming...!!!

Tuesday, July 7, 2015

Websphere application start error - A composition unit name already exists.

When you try to deploy an application or perform any administrative actions in Websphere, the following will be thrown:

A composition unit with name already exists. Select a different application name.

Cause
The issue is most frequently observed during the installation or removal of application, Say when you are doing a deployment, and there is an error in your deployment, then this bad deployment is saved in the server, this makes the Websphere go out of sync, since the previous deployment was already saved, when you are trying to do a fresh deployment, you will get above error saying that there is a unit already exist with your application name.
Even after you remove the application, you might not be able to do any further or new deployment.

Solution
The manual workaround is to delete the respective bad application folders from /blas and /cus directories.
The resource are located in the following config directory of the profile

/config/cells/cell/blas
/config/cells/cell/cus

For example if you see the error while installing MySampleApp.ear
Delete the following directory

/config/cells/cell/blas/MySampleApp
/config/cells/cell/cus/MySampleApp.

Once deleted, re-deploy your application.


Happy Programming...!!