[SOLVED] Hangs while Configuring CLASSPATH

Posted by Anantha Narayanan On 11:15 AM

I had created a new app in grails, and my colleague was trying to access this app after copying this folder to his local machine. Our environments were setup as follows:

GRAILS Version - 2.4.0
GROOVY Version - 2.3.3
JAVA Version - 1.8

Both of our environments matched. When he created a fresh application, grails created the application, however he was not able to run the application. The same was case with the copied application.

After 5 odd minutes the error was thrown into the screen:

C:\MyTrainigs\GroovyApp\test123>grails
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=32m; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; sup
| Configuring classpath
| Error Resolve error obtaining dependencies: Failed to read artifact descriptor for xalan erializer:jar:2.7.1 (Use --stacktrace to see the full trace)
| Error Required Grails build dependencies were not found. This is normally due to internet connectivity issues (such as a misconfigured proxy) or missing repositories in grails-app/conf/BuildConfig.groovy. Please verify your configuration to continue.


Only then we realized that this is internet access issue as grails pointed out. We were both accessing the application from corporate network, through internet proxy. The my colleague tried to access internet through data card and it worked. He was able to execute the application.

So if you have tried all other resolutions and if it has not worked, setup your proxy in startGrails.bat and it will work.

The example for setting up this is as below:
set JAVA_OPTS=%JAVA_OPTS% -Dhttps.proxyHost=yourproxyserver -Dhttps.proxyPort=proxyport

Let me know if this works for you.

Rounding off decimal value in Groovy

Posted by Anantha Narayanan On 9:56 PM

I am new to groovy language, so assume its going to be bare basic.

By default you have an object defined in groovy like follows:

groovy> def number=12.11 
groovy> println number.round(2) 

Exception thrown

groovy.lang.MissingMethodException: No signature of method: java.math.BigDecimal.round() is applicable for argument types: (java.lang.Integer) values: [2]
Possible solutions: round(java.math.MathContext), find(), pow(int), and(java.lang.Number), power(java.lang.Integer), mod(java.lang.Number)

I was searching in google for identifying the issue, but could not resolve it. Later only I realized that round() is available in double in groovy. I then explicitly converted the variable to double using toDouble() method and chained the round() method to it. It solved my problem.

groovy> def number=12.11 
groovy> println number.getClass()
groovy> println number.toDoublt().getClass()
groovy> println number.toDouble().round(2) 

class java.lang.Double
class java.math.BigDecimal
12.11

So it is evident that the method round() is not available to BigDecimal whereas it is available to Double.

So how can I round off a BigDecimal? Waiting for the answer.

Playing video files in HTML5

Posted by Anantha Narayanan On 12:53 PM

Section 3: How to play video files in HTML5

The sweetest and simplest way to play video files is HTML5.

<video src="videofile.ogg" autoplay poster="posterimage.jpg">
  Sorry, your browser doesn't support embedded videos, 
  but don't worry, you can <a href="videofile.ogg">download 
  it</a>and watch it with your favorite video player!
</video>

Arriving upon a video format and a codec is the complex part of playing a video file. Refer the browser compatibility in MDN before you use this.

Note: the source you are using in src need not be from same server where html5 is residing. This means that you can embed videos from YouTube inside your webpages using this same tag. The advantage is that you can put more controls on your webpage by using JavaScript.

Playing audio files in HTML5

Posted by Anantha Narayanan On 12:38 PM

Section 3: How to play audio files in HTML5

The sweetest and simplest way to play audio files is HTML5. You will agree with me after seeing the following code:

<audio src="audiotest.ogg" autoplay>
  Your browser does not support the <code>audio</code> element.
</audio>

Was I right in guessing your reaction?

The only point you must know while playing audio files within browsers is that there is no ONE format of audio compatible with all browsers out there. So what is the option? You must encode your audio files to at least two formats, OGG and MP3. For a full list of browser compatible audio file formats refer this link in MDN.

But for now, you will be safe if you had OGG and MP3. The mechanism is called as fallback, where the browser reads the first format, and if it can play it will play. Otherwise it will move on to the next one and play the second one.

<audio controls autobuffer>
  <source src="sample.mp3"/>
  <source src="sample.ogg"/>
</audio>

What has been done in the latest example is to move the src of <audio> tag separately as a new tag within <audio> called the <source>. You can define different formats of the same file, and the browser just plays the one format which it can read. Even if the browser can understand multiple formats, it just settles and plays the first one it can understand.

Sweet new tags in HTML5

Posted by Anantha Narayanan On 12:24 PM

Section 2: Sweet, I have new tags

While HTML5 is not always about introducing new tags, its there. Its just not added newly because they had to, but they really help identify the content you are going to put in the webpage.

Before understanding new tags which are introduced, we will understand the meaningless nature of <div> tags. A div tag is used only to stuff contents together, and later style it using stylesheets (CSS). Consider the following example:

<div id="navigation">
  some navigation links
</div>

Well do you consider the following or above to be simple enough to understand?

<nav>
  some navigation links
</nav>

It makes sense to write less code and which is intelligible for humans. After all humans write HTML.

For a full list of tags available in HTML5 check this link in MDN.

Previous Section Next Section

Starting with HTML5

Posted by Anantha Narayanan On 12:22 PM

Section 1: HTML5 basics

What is the point of learning Grails (or any other web framework) if you don't know basic HTML. In this age of HTML5, I am starting to learn HTML5 the old fashioned way, self-learning.

I will be sharing my learning to all those who want it. This is really basic stuff.

The following is the simplest of simple valid HTML5 page you will create yourself.

<!DOCTYPE html>
<title>Hello World</title>
<h1>My first HTML5 Document</h1>

Yes, you heard it right, you don't need a <head> or <body> etc. tags to call your document a valid HTML5 document. The browsers now-a-days (except IE) are smart enough to identify that <title> is the title of the document, and <h1> has to be printed within the body.

If you doubt that the above code is not a valid HTML5, be my guest and copy the code and paste it in the validator. http://validator.w3.org/#validate_by_input

This is the first thing you must know about HTML5.

Next Section

What is CRUD

Posted by Anantha Narayanan On 11:41 AM

A CRUD or short form for Create/Read/Update/Delete is a controller action that is built in grails for supporting basic inserting of data, querying of data, updating of data and deleting of data from table linked to a domain class.

In short, these common actions of users need not be coded for a domain class.

Consider the following example of a controller with just one line of code which enables this feature.


class BookController {
    static scaffold = true
}

The scaffold variable if its true, grails helps to auto-generate user actions for CRUD without a single line of code. The naming convention for controller follows the domain name. For a domain name Book a controller of BookController can be created.

This naming convention helps grails auto-identify your domain class and provide you with code for insert, query, update and delete for the domain class.

When the scaffold is created, grails automatically adds the above four user actions which are common for database access.

For more information on scaffolding refer Grails docs.

What are Transient Properties

Posted by Anantha Narayanan On 3:32 PM


Grails GORM by default creates all the properties on your domain as columns in database tables. We may not require such functionality. For Example in a user creation domain we may require the user to enter the confirm password along with password. We will definitely not require two columns in tables with same password (provided there is validation for that).

In such cases you can map properties in domain as Transient, conveying to Grails GORM not to create a column for the property. For Example:

Class Person {
  static transients = ["confirmPassswd"]

  String firstName
  String lastName
  String emailID
  String loginPasswd
  String confirmPasswd
}

In Grails it is simple enough to define such extensible features.

Login application - Validate from Database

Posted by Anantha Narayanan On 5:17 PM


Click here to see a very basic login application with hard-coded user credentials. In current article I am discussing as on how to validate from a table where login id and password is stored. The article above points to the usage of flash and session's uses. I will not discuss more about flash and session in this article.

My assumption is that a person is assigned for a login with his email id. Based on that I planned for a domain called "Person" as below (I named the application happy):

package happy
class Person {
  String firstName
  String lastName
  String emailID
  String loginPassword
  Boolean superUser

  static constraints = { 
    firstName(size:1..120,nullable:false,blank:false)
    lastName(size:1..120,nullable:false,blank:false)
    emailID(email:true,size:1..120,nullable:false,blank:false)
    loginPassword(password:true,size:6..20,nullable:false,blank:false)
  }
}


In my PersonController.groovy, I added an interceptor which should validate a session. If no session is available it should redirect me to login page.


package happy
class PersonController {
  def beforeInterceptor = [action.this.&checkUser]
  static scaffold = true
  def checkUser() {
    if(!session.user) {
      redirect(controller:'person',action:'login')
      flash.message = "Invalid Username/Password, please try again."
    }
  }
}


I have successfully added a validation for all controllers in Person. If there is no login detected the user should be redirected to a login page. Next part is to design that page.


  def login = {
  }
 
   

I have put a blank controller inside the Person controller for login. Now I have to create a gsp file for this controller to successfully work. For this, I copied the index.gsp from views folder and copied it as login.gsp inside person foler within views. I deleted the entire contents within body tag and replaced with the following code:


<body>
  <a href="#page-body" class="skip">
  <g:message code="default.link.skip.label" default="Skip to content&hellip;"/></a>
  <g:render template="loginHeader"/>
  <div class="bodyContent" id="bodyContent">
    <g:if test="${flash.message}">
      <div class="message">${flash.message}
</div>
    </g:if>
  </div>
</body>


It is a simple code, please read through all lines. From <g:render> tag, I will explain. It is looking for a _loginHeader.gsp as its a template. It then displays the body content and if any messages.

The following are the contents of _loginHeader.gsp located in views/person folder.


<g:if test="${session.user}">
<div class="login">
<g:remoteLink controller="person" action="list" update="bodyContent">${session.user.emailID}</g:remoteLink> | <g:link action="logout">Logout</g:link>
</div>
</g:if>
<g:else>
<g:form action="doLogin" method="post">
<div class="login">
 <label for='emailID'>Email ID</label>
 <input id="emailID" required type='text' name='emailID' value='${person?.emailID}' />
 <label for='loginPassword'>Password</label>
 <input id="loginPassword" required type='password' name='loginPassword' value='${person?.loginPassword}' />
 <input type="submit" value="Login"></input>
 </div>
</g:form>
</g:else>


This page will be used across all pages, that is why I decided to create it as a template. It checks for a session, and if found it displays the person logged in or else displays the login input boxes.

The form which has the input boxes for email ID and password are submitting to a doLogin. This method must be defined within the PersonController.groovy as well.

def doLogin = {
  def user = Person.findWhere(emailID:params['emailID'],loginPassword:params['loginPassword'])
  session.user = user
  if (user){
    redirect(controller:'person',action:'list')
    flash.message = "Logged in as <b>$user.firstName $user.lastName ($user.emailID)</b>"
  }else{
    redirect(controller:'person',action:'login')
    flash.message = "Invalid Username/Password, please try again."
  }
}

This method extracts values from params variable which will have all input boxes value. By checking using Person.findWhere by passing these parameters (Email ID &amp; Login Password) we will get some value to user object. If user variable was null then we assume that it is an invalid login and once more redirect to login page. If the validation was successfull, this will redirect to Person/List page.

Download Application Note: The application uses Grails 2

Bug Tracker Application - biTracker

Posted by Anantha Narayanan On 3:52 PM

This application can be used to track issues/bugs which might be arising in development.

The features include:
  • User defined resource names 
  • User defined browser names (in case of browser based application for checking compatibility) 
  • User defined pages/program units 
  • User defined environments (like uat/development etc) 
  • User defined severity status 
  • Issues/bugs are searchable using searchable plugin 

This application is intented to be a starting place wherein MS-Excel sheets can be replaced and the bugs/issues could be saved to Oracle database.

The configuration for connecting to oracle can be done by modifying the file DataSource.groovy inside grails-app/conf folder. 

Download the source and execute this application and serve your clients much better.

Request your help in improving this and making it a full-fledged application. Please share your valuable comments below.

What is SCAFFOLD?

Posted by Anantha Narayanan On 10:48 PM

Scaffold in normal English means

"scaf·fold·ing/ˈskafəldiNG/Noun:
  1. A temporary structure on the outside of a building, made of wooden planks and metal poles, used by workers while building, repairing, or...
  2. The materials used in such a structure."

In Grails and some more "Model-View-Controller (MVC for short)" frameworks this term is used to describe the automatic "Create-Read-Update-Delete" database functions that are constructed and executed at run time.

For example if you have defined a domain class in Grails, the table can be created by the framework. More, Grails also allows you to have web interface for the domain automatically for the said operations on your table:
  • CREATE (INSERT)
  • READ (QUERY)
  • UPDATE
  • DELETE
These above operations are termed as scaffolding or CRUD in Grails.

A real use of a SCAFFOLD is in prototyping your design, wherein most of these code does not make much importance to you. Once the design is frozen you may move to more secure and customized way of CRUD operations.

Automatic Scaffold Controller

Posted by Anantha Narayanan On 10:39 PM

By default if you are creating a controller using the following command:

grails create-controller org.example.DomainClass

Suppose your controller is based on an existing DomainClass, you might want to jump start using scaffolding.

You might be opening the controller file and commenting the code which Grails has created for you.

class DomainClassController {

  def index = { }

}
You might be adding the magic keyword that allows scaffolding later.

class DomainClassController {

  //def index = { }

  def scaffold = true

}
If you have many number of controllers to be created for prototyping and want to avoid this commenting and copy/paste activities use the following command:

grails create-scaffold-controller org.example.DomainClass

Grails will generate the controller with scaffold magic keyword by default.

Hope you like this tip (if you are a beginner of Grails and if you are cursing with prototyping for numerous controllers).

Welcome Grails 2

Posted by Anantha Narayanan On 1:01 AM

It was only recently that Grails 2 was released. Being using an ubuntu Linux distro, it is very easy to upgrade Grails and I did.

The first thing I tried was to execute an already existing application (using Grails 1.3.7) and it gave me an error:

| NOTE: Your application currently expects grails version [1.3.7], this target will upgrade it to Grails 2.0.0

I issued the command grails upgrade

WARNING: This target will upgrade an older Grails application to 2.0.0.
  Are you sure you want to continue? [y,n]

I gave a proceed signal and Grails upgraded my application after downloading necessary files. Pretty impressive.
When I executed the application using run-app I got the following error:
| Error 2011-12-20 00:35:57,627 [Thread-7] ERROR context.GrailsContextLoader - Error executing bootstraps: Database driver [org.hsqldb.jdbcDriver] for HSQLDB not found. Since Grails 2.0 H2 is now the default database. You need to either add the 'org.h2.Driver' class as your database driver and change the connect URL format (for example 'jdbc:h2:mem:devDb') in DataSource.groovy or add HSQLDB as a dependency of your application.

He he, looking complex. Do not worry. There is one change that Grails 2 is shipped with. Grails 1.3.7 was using HSQLDB and Grails 2 uses H2 database. The reference to HSQLDB made Grails to spit this error message.

But Grails also has pointed out as to how to solve it.
  1. Modify the org.hsqldb.jdbcDriver with org.h2.Driver in driverClassName.
  2. Modify url = "jdbc:hsqldb:mem:devDB" with url = "jdbc:h2:mem:devDb"
That's it. I was able to execute the application, though I did not appreciate any interface facelift with my old application. Now I created a new application and created a domain class and a controller for it.

When executed the HTML5 styling was what I was expecting. Yes and I got it. So this is another change in Grails 2.

For more about Grails 2, check here.

If you like my blog, please leave your valuable suggestions below.

Difference between nullable and blank

Posted by Anantha Narayanan On 12:10 AM

What is the difference between nullable and blank constraints in Grails domain class? 

Consider the following constraint defined within a domain class:
Package nulltest

Class Test1{
 String someValue
 static constraints = {
   someValue blank:true
 }
}
Grails while compling and running the application creates the fiels someValue to allow blank value.

You will get the following error if you have a controller action for this domain:
Property [someValue] of class [class nulltest.Test1] cannot be null

This property blank is only applicable for a String field. The reason, the term blank does not sound good for non-string fields. To achieve the same for a non-string field, use nullable constraint here.

Package nulltest

Class Test1{
 BigDecimal someValue
 static constraints = {
   someValue nullable:true
 }
}
Note: By default, all domain class properties have an implicit nullable:false constraint.

How to switch off Version

Posted by Anantha Narayanan On 8:57 PM

If you have ever created domain classes and let Grails create the tables, you must have noted that by default there are two columns created. ID and Version.

Why do I have ID and VERSION? 
ID Column is used for creating primary key for the table. VERSION column is used for identifying the version of the record whenever an update is happening to the table.

I will not discuss about the ID column here, but VERSION column requires more elaboration. Grails uses Optimistic locking technique, wherein a row is only locked in the database when the user saves the data after modification.

In a using default scaffolding view, when a user clicks on Edit for a row; Grails will just get a read-only copy of the row (which includes the VERSION column also). If the user does not modify the data, there is no need to release a lock on the record as Grails has not locked the record.

But if the user modifies and clicks on Save; Grails checks the VERSION of record on which the user has modified with the VERSION for that particular row in the database. If both match, Grails updates the modified data to the database. If both VERSION are not the same, Grails knows that some other user (or the same user in a different browser) has modified the record. That could be the only cause for the VERSION being different from the database. Grails simply throws an error message in this case and stops processing.

How can I tell Grails not to create VERSION column?
Now that we have understood why Grails is creating a VERSION column, we will see how to disable this feature. It is in fact very easy to do so.

Consider the domain class below:
 
Package noversion

Class Vehicle {
  String name
  String registrationNo

  static mapping = {
    version false
  }
}

By mentioning "version false" in the mapping closure of the domain class you are telling Grails not to create VERSION column while creating the table.

How Grails updates to table if there is no VERSION column
In the absence of VERSION column, Grails updates the row based only on ID column. The outcome is the table will have values updated by user who has saved last. All other users values gets lost.

The point to note here is that Grails continue to lock using Optimistic locking only.


Related topics:
Coming Soon How to make Grails, use Pessimistic locking instead of Optimistic locking.

Login Application

Posted by Anantha Narayanan On 7:40 PM

Create an application

C:\GRAILS_APPLICATONS>grails create-app login-test

Now create a controller for the user to show login buttons, or once logged in we need to show some message.

C:\GRAILS_APPLICATONS\LOGIN-TEST>grails create-controller useraccount

Once the controller is created, create a gsp file index.gsp within C:GRAILS_APPLICATION\login-test\grails-app\views\useraccount. Call it index.gsp. We want this controller because by default the controller will have a def index = { } in its body. To use this we are creating the gsp with same name. You are always free to modify the def index to some name you choose for your login, say home. Below is the content of the gsp file

<html>
<head>
<title>Welcome to Grails</title>
<meta name="layout" content="main" />
<style type="text/css" media="screen">
#login{
background-color:darkred;
color:white;
text-align:right;
padding:5px 15px;
height:25px;
}
#login a{
color:white;
}
</style>
</head>
<body>
<div id="login">
<g:if test="${session.user}">
<g:if test="${flash.message}">Welcome back ${flash.message}</g:if>
<g:else>Logged in as <B>${session.user}</B></g:else>
 | <g:link action="logout">Logout</g:link>
</g:if>
<g:else>
<g:form controller="useraccount" action="login">
<label for="name">Username</label>
<input type="text" name="username"/>
<label for="password">Password</label>
<input type="password" name="password"/>
<input type="submit" value="Login"/>
</g:form>
</g:else>
</div>
</body>
</html>

Now modify your controller file (UseraccountController.groovy) as below:

package login.test
class UseraccountController {
def index = { }
def login ={
if (params.username == "grailslover" && params.password == "hi"){
flash.message = "Welcome back, <B>${params.username}</B>."
session.user = "grailslover"
}else{
flash.message = "Login failed"
}
redirect(action: 'index')
}
def logout ={
session.user = null
redirect(action: 'index')
}
}

Now run your application using grails run-app and point your browser to this URL:
http://localhost:8080/login-test/useraccount/index

Login with username grailslover and password as hi. Initially when you login you will see a message Welcome back grailslover along with a link for Logout. Refresh the page and the message changes to Logged in as grailslover.

Now click on Logout the Login page with placeholders for Username and password appears.

To Download the application, click here. If you like the tutorial, please leave your valuable comments below.

Groovy and Grails Tutorial

Posted by Anantha Narayanan On 6:35 PM

A simple tutorial by Harshad Oak.

Groovy Basics
Scripting / Agile / Dynamic ...Language
• Syntax very close to Java
• Meant for Java developers.
• A powerful high level language for the Java "platform"
• Groovy code Compiles to Java bytecode.
• You can get productive quickly

Why Grails

Posted by Anantha Narayanan On 8:08 PM


Grails is an open source framework for web development that runs on the J2EE platform. It is mainly built on Groovy, a language which can be thought of as an extension to Java.

Combines principles such as "convention over configuration" (Convention Over Configuration) and "Do not repeat yourself" (Do not Repeat Yourself) together with a series of open source frameworks like Hibernate, Spring and SiteMesh.

Grails aims to be a highly productive framework, providing a standardized development environment and hiding much of the configuration details to the programmer.

Grails uses two testing frameworks: JUnit and Cano  to implement unit tests, integration and functional. As is known, the goal of software testing is that it behaves as expected and that when you modify the code, the evidence that had happened in the past still worked.

For More information about Grails read here. For information on Installing Grails click here.

Hello World Application

Posted by Anantha Narayanan On 10:03 PM

Now heading straight to create a fresh application we will create a “Hello World” printing application. Grails creates a main folder and numerous sub-folders for each application. It is easy to create a parent folder which holds all my applications (we will be creating more than one applications in our tutorials). Create a folder c:\grails_applications and use command prompt from now on. Navigate to c:\grails_applications folder in command prompt.

Now we are ready to create our first application. Type grails create-app helloworld in command prompt.

C:\GRAILS_APPLICATONS>grails create-app helloworld

You will get a whole lot of lines of messages about creation of folders. Just ignore them for the time-being. You must have got the final line of message as follows:

Created Grails Application at C:\grails_applications\helloworld

That’s all we want now. Navigate inside helloworld folder. Now execute the following command:

C:\GRAILS_APPLICATONS\HELLOWORLD>grails create-controller hello

Once the controller is created, we are ready to modify the class to display the Hello World text. Use a text-editor and edit the following file:

C:\grails_applications\helloworld\grails-app\controllers\helloworld\HelloController.groovy

The default contents of the file will be like this:

package helloworld

class HelloController {
def index = { }
}

Modify it to look like this:

package helloworld

class HelloController {
def world = {
render "Hello World!"
}
}

Thats all required. Before we can view the results in a browser, we have to start the application. Execute the following command for this:

C:\GRAILS_APPLICATIONS\HELLOWORLD>grails run-app

Once you get the following message, its time to open the web browser.

Server running. Browse to http://localhost:8080/helloworld

Copy/Paste the URL into web browser and you will now be able to access your application. Now click on the link below Available Controllers and you will be able to see the Hello World Message.

Note: In case you are getting error saying that port 8080 is already in use, try the following command and use a different port which is not in use.

C:\GRAILS_APPLICATIONS\HELLOWORLD>grails -Dserver.port=8090 run-app
If you like the tutorial, please leave your valuable comments below.

Installing Grails

Posted by Anantha Narayanan On 10:01 PM

Grails is an open source web application framework. It is based on Java and Groovy. (Groovy is a language for Java platform.) To learn more about Groovy click here.

Before downloading Grails, you will need Java 5.0 or greater. Download and install Java before installing Grails. Once java is installed set environment variable JAVA_HOME to the path where java is installed.
Now it is time to download Grails, do it from here. http://www.grails.org/Download.

As of this writing the latest stable release is 1.3 (release: 1.3.7). We will use this version in our examples. We will download any database as and when we hit the topic.
Extract the archive downloaded from Grails website to c:\grails (Unix users are smart and do not need this step-by-step guide of installation).

Set a new environment variable GRAILS_HOME to c:\grails

Modify the PATH environment variable and append %GRAILS_HOME%\bin. Note that, for Windows, both PATH and GRAILS_HOME must be defined at the same environment variable level (eg. 'System variables') rather than across environment variable levels (eg. PATH under 'System variables' and GRAILS_HOME under 'User variables')

You are ready with Grails. Type grails in command prompt and you will get a welcome message. If you are not getting it most probably the error must be with JAVA_HOME or GRAILS_HOME or PATH environment variables. I am using ubuntu linux for executing and I got the following message:

Using Java at: /usr/lib/jvm/java-6-openjdk
Welcome to Grails 1.3.7 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: /usr/share/grails/1.3.7
No script name specified. Use 'grails help' for more info or 'grails interactive' to enter interactive mode

Recommended Post Slide Out For Blogger