Play framework tutorial for Starters

What is play-Play! is very different compared to your average Java web application. Play! doesn’t follow many of the J2EE conventions or standards. Instead the developers of Play! decided to make the most efficient web framework possible. It’s not a full Java Enterprise stack and Play! expressly states that it is built for web developers. This humble developer started out very skeptical that it would be useful and some of the design choices made little sense to my “Java Enterprise” mindset.

So what is Play!? – let’s take a look at what it offers at a glance.

Completely stateless – matching the HTTP standard
Non-blocking IO – reactive, fast
Hot-reload of Java classes – more on this later
Compiled views – which can be tested
Symmetrical simple routes – created with purpose and design
Both Scala and Java – Built with Scala but Java is a first class alternative
Large third-party module repository – growing daily
Commercial Support – by TypeSafe and Zenexity
Download and install the Play binary package from http://www.playframework.com/download .

To check if play is working or not, open the command prompt and type ‘play help’.

C:\>play help

you should get below screen.

Creting a new Application
step 1 : C:\>play new myFirstApp
step 2 : Confirm the application name.Press enter.
Step 3: type 2 for creating a simple java application.

Creating a working eclipse project from a play application
step 1 : cd to the new application directory
C:\>cd myFirstApp
step 2 : play
C:\myFirstApp>play
step 3 : eclipsify
[myFirstApp] $ eclipsify

Import the project in eclipse.

The app/ directory contains executables. Below are 3 packages
app/controllers
app/models
app/views

The public/ directory contains static assets. Has 3 subdirectories
images
css
javascript

The conf/ directory contains applications configuration files.There are 2 configuration files.
application.conf – standard configuration parameters.
routes – routes defination file

The lib/ directory – libraries/jar files

The project/ directory – sbt build definitions
Plugins.sbt
Build.scala – application build script

The target/ directory – contains things generated by build system

Typical .gitignore file – Generated folders should be ignored by your version control system
logs
project/project
project/target
target
tmp

To run the newly created application

[myFirstApp] $ run

On the browser address type
localhost:9000

The below screen gets displayed.

Modify the source code as below.

Application.java

package controllers;

import model.Task;
import play.*;
import play.data.Form;
import play.mvc.*;

import views.html.*;
import views.*;

public class Application extends Controller {
	
  public static Result index() {
	
	  Form<Task> form = form(Task.class);
    return ok(index.render(form));
  }
  
  public static Result sayHello() {
	  Form<Task> taskForm = form(Task.class).bindFromRequest();
	  if(taskForm.hasErrors())
		  return badRequest(index.render(taskForm));
	  else
	  {
	  Task data = taskForm.get();
	  
	  return ok(sayHello.render(data.name, data.age));
	  }
	  
		  
  }

}

Task.java

package model;

import java.util.*;
import play.data.validation.Constraints.*;
public class Task {
  
	@Required
  public String name;
  
	@Required
  public String age;
    
}
Index.scala
@(form1: Form[model.Task])
@import helper._

@main(title = "The 'helloworld' application") {
    
    <h1>Configure your 'Hello world':</h1>
  @form(action = routes.Application.sayHello, args = 'id -> "helloform") {
        
        @inputText(
            field = form1("name"),
            args = '_label -> "What's your name?"
        )
        
        @inputText(
            field = form1("age"),
            args = '_label -> "What's your age?", 'size -> 3
        )
        
         <p class="buttons">
            <input type="submit">
        <p>
       } 
}


[/sourcecode ]

You can write the code for creating form in HTML also if not in Scala.



 <form action= @routes.Application.sayHello method=GET >
  <table>
  <tr>
  <td>Name   :</td>
  <td><input type="text" name="name"   required="required" > </td></tr>
 <tr><td> Age :</td><td><input type="text" name="age" > </td></tr>

  <tr><td><input type="submit" value="Submit" /></td></tr>
      
  </table>
main.scala

@(title: String)(content: Html)
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>@title</title>		
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
     
    </head>
    <body>
        @content 
    </body>
</html>

sayHello.scala

@(name: String, age: String)
@main("Details are : "){
<h1>Hello @name!</h1>
<h1>Your age is @age</h1> 
<a href="@{routes.Application.index()}">Back to form</a>
}
</body>
</html>

routes.conf
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET / controllers.Application.index()

GET /sayHello controllers.Application.sayHello()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path=”/public”, file)

Refresh the browser.
You will see the below screen.

Test your application.

Happy coding with Techartifact

Learn Hibernate core implementation.- How hibernate works

Lessons to learn from the Hibernate Core implementation

Hibernate is an open source Java persistence framework project. Perform powerful object relational mapping and query databases using HQL and SQL.
In general the widely used libraries are well designed and implemented, and it’s very interesting to learn from them some coding best practices. Let’s take a look inside the hibernate core library and discover some of its design keys.
In this post Hibernate Core is analyzed by JArchitect to go deep inside its design and implementation.

Package by Feature
Package-by-feature uses packages to reflect the feature set. It places all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other.
Here’s a good article talking about packaging by feature.
Hibernate core contains many packages, each one is related to a specific feature hql, sql, and others.

Coupling
Low coupling is desirable because a change in one area of an application will require fewer changes throughout the entire application. In the long run, this could alleviate a lot of time, effort, and cost associated with modifying and adding new features to an application.
Here are three key benefits derived from using interfaces:
• An interface provides a way to define a contract that promotes reuse. If an object implements an interface then that object is to conform to a standard. An object that uses another object is called a consumer. An interface is a contract between an object and its consumer.
• An interface also provides a level of abstraction that makes programs easier to understand. Interfaces allow developers to start talking about the general way that code behaves without having to get in to a lot of detailed specifics.
• An interface enforce low coupling between components, what’s make easy to protect the interface consumer from any implementation changes in the classes implementing the interfaces.
Let’s search for all interfaces defined by Hibernate Core, for that we use CQLinq to query the code base.

from  t in Types where t.IsInterface select t

If our primary goal is to enforce low coupling, there’s a common mistake when using interfaces that could kill the utility of using them. It’s the using of the concrete classes instead of interfaces, and to explain better this problem let’s take the following example:
The class A implements the Interface IA who contains the calculate() method, the consumer class C is implemented like that

public class C

{

   ….

   public void calculate()

   {

     …..

     m_a.calculate();

     ….

    }

    A m_a;

}

The Class C instead of referencing the interface IA, it references the class A, in this case we lose the low coupling benefit, and this implementation has two major drawbacks:
• If we decide to use another implementation of IA, we must change the code of C class.
• If some methods are added to A not existing in IA, and C use them, we also lose the contract benefit of using interfaces.
C# introduced the explicit interface implementation capability to the language to ensure that a method from the IA will be never called from a reference to concrete classes, but only from a reference to the interface. This technique is very useful to protect developers from losing the benefit of using interfaces.
With JArchitect we can check this kind of mistakes using CQLinq, the idea is to search for all methods from concrete classes used directly by other methods.

from m in Methods  where m.NbMethodsCallingMe>0 && m.ParentType.IsClass

 && !m.ParentType.IsThirdParty && !m.ParentType.IsAbstract

let interfaces= m.ParentType.InterfacesImplemented

from i in interfaces where i.Methods.Where(a=>a.Name==m.Name &&

a.ParentType!=m.ParentType).Count()>0 

select new { m,m.ParentType,i }

For example the method getEntityPersister from SessionFactoryImpl which implements SessionFactoryImplementor interface is concerned by this problem.
Let’s search for methods invoking directly SessionFactoryImpl.getEntityPersister.
from m in Methods where m.IsUsing (“org.hibernate.internal.SessionFactoryImpl.getEntityPersister(String)”)
select new { m, m.NbBCInstructions }

Methods like SessionImpl.instantiate invoke directly getEntityPersister, instead of passing by interface, what break the benefit of using interfaces. Fortunately hibernate core doesn’t contains many methods having this problem.
Coupling with external jars
When external libs are used, it’s better to check if we can easily change a third party lib by another one without impacting the whole application, there are many reasons that can encourage us to change a third party lib. The other lib could:
– Have more features.
– More powerful.
– More secure.
Let’s take the example of antlr lib which used to parse the hql queries, and imagine that another parser more powerful than antlr was created, could we change the antlr by the new parser easily?
To answer this question let’s search which methods from hibernate use it directly:

from m in Methods where m.IsUsing ("antlr-2.7.7")
select new { m, m.NbBCInstructions }
 

And which ones used it indirectly:

from m in Projects.WithNameNotIn( "antlr-2.7.7").ChildMethods()
let depth0 = m.DepthOfIsUsing("antlr-2.7.7")
where depth0 > 1 orderby depth0
select new { m, depth0 }

Many methods use antlr directly what makes hibernate core highly coupled with it, and changing antlr with another one is not an easy task. this fact not means that we have a problem in hibernate design, but we have to be careful when using a third party lib and well check if a third party lib must be low coupled or not with the application.
Cohesion
The single responsibility principle states that a class should have one, and only one, reason to change. Such a class is said to be cohesive. A high LCOM value generally pinpoints a poorly cohesive class. There are several LCOM metrics. The LCOM takes its values in the range [0-1]. The LCOMHS (HS stands for Henderson-Sellers) takes its values in the range [0-2]. Note that the LCOMHS metric is often considered as more efficient to detect non-cohesive types.
LCOMHS value higher than 1 should be considered alarming.
In general classes more concerned by the cohesion are the classes having many methods and fields.
Let’s search for types having many methods and fields.

from t in Types where
(t.Methods.Count() > 40 || t.Fields.Count()>40) && t.IsClass
orderby t.Methods.Count() descending
select new { t, t.InstanceMethods, t.Fields,t.LCOMHS }

Only few types are concerned by this query, and for all them the LCOMHS is less than 1.
Using Annotations
Annotation-based development relieves Java developers from the pain of cumbersome configuration. And give us a powerful feature to free the source code from the boilerplate code. The resulting code is also less likely to contain bugs.
Let’s search for all annotations defined by hibernate core.
from t in Types where t.IsAnnotationClass && !t.IsThirdParty select t

Many annotations are defined, what make hibernate easy to use by developers, and the headache of configuration files is avoided.
Conclusion
Hibernate Core is a good example of open source projects to learn from, don’t hesitate to take a look inside it.

JSF UTIL class in Oracle ADF

Well i am refering here the jsfutil class for my reference.this code doesn’t written by me.But it is very helpful for ADF developer.

 import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import oracle.adf.model.binding.DCBindingContainer;
/**
* General useful static utilies for working with JSF.
* NOTE: Updated to use JSF 1.2 ExpressionFactory.
*
*/
public class JSFUtils {
private static final String NO_RESOURCE_FOUND = "Missing resource: ";
/**
* Method for taking a reference to a JSF binding expression and returning
* the matching object (or creating it).
* @param expression EL expression
* @return Managed object
*/
public static Object resolveExpression(String expression) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);
return valueExp.getValue(elContext);
}
public static String resolveRemoteUser() {
FacesContext facesContext = getFacesContext();
ExternalContext ectx = facesContext.getExternalContext();
return ectx.getRemoteUser();
}
public static String resolveUserPrincipal() {
FacesContext facesContext = getFacesContext();
ExternalContext ectx = facesContext.getExternalContext();
HttpServletRequest request = (HttpServletRequest)ectx.getRequest();
return request.getUserPrincipal().getName();
}
public static Object resloveMethodExpression(String expression,
Class returnType,
Class[] argTypes,
Object[] argValues) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
MethodExpression methodExpression =
elFactory.createMethodExpression(elContext, expression, returnType,
argTypes);
return methodExpression.invoke(elContext, argValues);
}
/**
* Method for taking a reference to a JSF binding expression and returning
* the matching Boolean.
* @param expression EL expression
* @return Managed object
*/
public static Boolean resolveExpressionAsBoolean(String expression) {
return (Boolean)resolveExpression(expression);
}
/**
* Method for taking a reference to a JSF binding expression and returning
* the matching String (or creating it).
* @param expression EL expression
* @return Managed object
*/
public static String resolveExpressionAsString(String expression) {
return (String)resolveExpression(expression);
}
/**
* Convenience method for resolving a reference to a managed bean by name
* rather than by expression.
* @param beanName name of managed bean
* @return Managed object
*/
public static Object getManagedBeanValue(String beanName) {
StringBuffer buff = new StringBuffer("#{");
buff.append(beanName);
buff.append("}");
return resolveExpression(buff.toString());
}
/**
* Method for setting a new object into a JSF managed bean
* Note: will fail silently if the supplied object does
* not match the type of the managed bean.
* @param expression EL expression
* @param newValue new value to set
*/
public static void setExpressionValue(String expression, Object newValue) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);
//Check that the input newValue can be cast to the property type
//expected by the managed bean.
//If the managed Bean expects a primitive we rely on Auto-Unboxing
Class bindClass = valueExp.getType(elContext);
if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
valueExp.setValue(elContext, newValue);
}
}
/**
* Convenience method for setting the value of a managed bean by name
* rather than by expression.
* @param beanName name of managed bean
* @param newValue new value to set
*/
public static void setManagedBeanValue(String beanName, Object newValue) {
StringBuffer buff = new StringBuffer("#{");
buff.append(beanName);
buff.append("}");
setExpressionValue(buff.toString(), newValue);
}
/**
* Convenience method for setting Session variables.
* @param key object key
* @param object value to store
*/
public static void storeOnSession(String key, Object object) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getSessionMap();
sessionState.put(key, object);
}
/**
* Convenience method for getting Session variables.
* @param key object key
* @return session object for key
*/
public static Object getFromSession(String key) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getSessionMap();
return sessionState.get(key);
}
public static String getFromHeader(String key) {
FacesContext ctx = getFacesContext();
ExternalContext ectx = ctx.getExternalContext();
return ectx.getRequestHeaderMap().get(key);
}
/**
* Convenience method for getting Request variables.
* @param key object key
* @return session object for key
*/
public static Object getFromRequest(String key) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getRequestMap();
return sessionState.get(key);
}
/**
* Pulls a String resource from the property bundle that
* is defined under the application <message-bundle> element in
* the faces config. Respects Locale
* @param key string message key
* @return Resource value or placeholder error String
*/
public static String getStringFromBundle(String key) {
ResourceBundle bundle = getBundle();
return getStringSafely(bundle, key, null);
}
/**
* Convenience method to construct a FacesMesssage
* from a defined error key and severity
* This assumes that the error keys follow the convention of
* using _detail for the detailed part of the
* message, otherwise the main message is returned for the
* detail as well.
* @param key for the error message in the resource bundle
* @param severity severity of message
* @return Faces Message object
*/
public static FacesMessage getMessageFromBundle(String key,
FacesMessage.Severity severity) {
ResourceBundle bundle = getBundle();
String summary = getStringSafely(bundle, key, null);
String detail = getStringSafely(bundle, key + "_detail", summary);
FacesMessage message = new FacesMessage(summary, detail);
message.setSeverity(severity);
return message;
}
/**
* Add JSF info message.
* @param msg info message string
*/
public static void addFacesInformationMessage(String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_INFO, msg, "");
ctx.addMessage(getRootViewComponentId(), fm);
}
/**
* Add JSF error message.
* @param msg error message string
*/
public static void addFacesErrorMessage(String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, "");
ctx.addMessage(getRootViewComponentId(), fm);
}
/**
* Add JSF error message for a specific attribute.
* @param attrName name of attribute
* @param msg error message string
*/
public static void addFacesErrorMessage(String attrName, String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_ERROR, attrName, msg);
ctx.addMessage(getRootViewComponentId(), fm);
}
// Informational getters
/**
* Get view id of the view root.
* @return view id of the view root
*/
public static String getRootViewId() {
return getFacesContext().getViewRoot().getViewId();
}
/**
* Get component id of the view root.
* @return component id of the view root
*/
public static String getRootViewComponentId() {
return getFacesContext().getViewRoot().getId();
}
/**
* Get FacesContext.
* @return FacesContext
*/
public static FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
/*
* Internal method to pull out the correct local
* message bundle
*/
private static ResourceBundle getBundle() {
FacesContext ctx = getFacesContext();
UIViewRoot uiRoot = ctx.getViewRoot();
Locale locale = uiRoot.getLocale();
ClassLoader ldr = Thread.currentThread().getContextClassLoader();
return ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(),
locale, ldr);
}
/**
* Get an HTTP Request attribute.
* @param name attribute name
* @return attribute value
*/
public static Object getRequestAttribute(String name) {
return getFacesContext().getExternalContext().getRequestMap().get(name);
}
/**
* Set an HTTP Request attribute.
* @param name attribute name
* @param value attribute value
*/
public static void setRequestAttribute(String name, Object value) {
getFacesContext().getExternalContext().getRequestMap().put(name,
value);
}
/*
* Internal method to proxy for resource keys that don't exist
*/
private static String getStringSafely(ResourceBundle bundle, String key,
String defaultValue) {
String resource = null;
try {
resource = bundle.getString(key);
} catch (MissingResourceException mrex) {
if (defaultValue != null) {
resource = defaultValue;
} else {
resource = NO_RESOURCE_FOUND + key;
}
}
return resource;
}
/**
* Locate an UIComponent in view root with its component id. Use a recursive way to achieve this.
* @param id UIComponent id
* @return UIComponent object
*/
public static UIComponent findComponentInRoot(String id) {
UIComponent component = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
UIComponent root = facesContext.getViewRoot();
component = findComponent(root, id);
}
return component;
}
/**
* Locate an UIComponent from its root component.
* Taken from http://www.jroller.com/page/mert?entry=how_to_find_a_uicomponent
* @param base root Component (parent)
* @param id UIComponent id
* @return UIComponent object
*/
public static UIComponent findComponent(UIComponent base, String id) {
if (id.equals(base.getId()))
return base;
UIComponent children = null;
UIComponent result = null;
Iterator childrens = base.getFacetsAndChildren();
while (childrens.hasNext() && (result == null)) {
children = (UIComponent)childrens.next();
if (id.equals(children.getId())) {
result = children;
break;
}
result = findComponent(children, id);
if (result != null) {
break;
}
}
return result;
}
/**
* Method to create a redirect URL. The assumption is that the JSF servlet mapping is
* "faces", which is the default
*
* @param view the JSP or JSPX page to redirect to
* @return a URL to redirect to
*/
public static String getPageURL(String view) {
FacesContext facesContext = getFacesContext();
ExternalContext externalContext = facesContext.getExternalContext();
String url =
((HttpServletRequest)externalContext.getRequest()).getRequestURL().toString();
StringBuffer newUrlBuffer = new StringBuffer();
newUrlBuffer.append(url.substring(0, url.lastIndexOf("faces/")));
newUrlBuffer.append("faces");
String targetPageUrl = view.startsWith("/") ? view : "/" + view;
newUrlBuffer.append(targetPageUrl);
return newUrlBuffer.toString();
}

// Get the error


String error = iterBind.getError().getMessage();













// Get a session bean

FacesContext ctx = FacesContext.getCurrentInstance();

ExpressionFactory ef = ctx.getApplication().getExpressionFactory();

ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{testSessionBean}", TestSession.class);

TestSession test = (TestSession)ve.getValue(ctx.getELContext());



// main jsf page

DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();

// taskflow binding

DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding("dynamicRegion1");

// pagedef of a page fragment

JUFormBinding form = (JUFormBinding) tf.findExecutableBinding("regions_employee_regionPageDef");

// handle to binding container of the region.

DCBindingContainer dcRegion = form;







// return a methodexpression like a control flow case action or ADF pagedef action

private MethodExpression getMethodExpression(String name) {

Class [] argtypes = new Class[1];

argtypes[0] = ActionEvent.class;

FacesContext facesCtx = FacesContext.getCurrentInstance();

Application app = facesCtx.getApplication();

ExpressionFactory elFactory = app.getExpressionFactory();

ELContext elContext = facesCtx.getELContext();

return elFactory.createMethodExpression(elContext,name,null,argtypes);

}



//

RichCommandMenuItem menuPage1 = new RichCommandMenuItem();

menuPage1.setId("page1");

menuPage1.setText("Page 1");

menuPage1.setActionExpression(getMethodExpression("page1"));



RichCommandButton button = new RichCommandButton();

button.setValueExpression("disabled",getValueExpression("#{!bindings."+item+".enabled}"));

button.setId(item);

button.setText(item);

MethodExpression me = getMethodExpression("#{bindings."+item+".execute}");

button.addActionListener(new MethodExpressionActionListener(me));

footer.getChildren().add(button);





// get a value

private ValueExpression getValueExpression(String name) {

FacesContext facesCtx = FacesContext.getCurrentInstance();

Application app = facesCtx.getApplication();

ExpressionFactory elFactory = app.getExpressionFactory();

ELContext elContext = facesCtx.getELContext();

return elFactory.createValueExpression(elContext, name, Object.class);

}

// an example how to use this

RichInputText input = new RichInputText();

input.setValueExpression("value",getValueExpression("#{bindings."+item+".inputValue}"));

input.setValueExpression("label",getValueExpression("#{bindings."+item+".hints.label}"));

input.setId(item);

panelForm.getChildren().add(input);

// find a jsf component

private UIComponent getUIComponent(String name) {

FacesContext facesCtx = FacesContext.getCurrentInstance();

return facesCtx.getViewRoot().findComponent(name) ;

}

// change the locale

Locale newLocale = new Locale(this.language);

FacesContext context = FacesContext.getCurrentInstance();

context.getViewRoot().setLocale(newLocale);
} 


Happy coding with Vinay in Techartifact.