Category Archives: Grails

How to Configure Amazon Cloud Front with Grails Web Application

 How do you setup Amazon’s CloudFront?

The S3 just provides a way to put content on Amazon’s system, so that it can then be distributed to CloudFront.

Once you’ve signed up with S3, you create a “bucket”, which is a storage vessel: a way of organizing your content. I created a single bucket for my single site, but you may need to create more than one. Into this bucket you’d put any content that needs to be stored. Following are the steps to follow:

  1.  Login in to Amazon Cloud Front

https://console.aws.amazon.com/cloudfront/home

2.  Create a bucket.

Go to Service-> Select S3 , Create Bucket option is there.

3.  Create distribution.

Go to service -> Select Cloud front,  Create Distribution option is there

4.  After click on Create Distribution button. Select Delivery method  Web

5.  After selection of Web

Origin Setting has Origin domain name field.

In that created bucket option will show. Choose it.

6. Distribution Settings area has

Price Class Field (Choose the region)

7.  And Click on Create Distribution button on bottom.

8.  And Cloud Front Distribution Screen will appear , The Distribution is going to deploy it takes at least 15 minutes. Check the Status is in progress and state is enabled. Once the Status is deployed we can use it.

9.  To use this created resources we need to make bucket public just right click on bucket and make it public.

To Configure Amazon Cloud Front with Grails we need to configure some settings in Config.groovy.

Just put the below lines as per requirement either in dev mode or prod mode.

//Amazon Cloud Front Setting

grails.resources.mappers.baseurl.enabled = true

grails.resources.mappers.baseurl.default=

http://aersdeghyi.cloudfront.net // put here domain name.

grails.resources.mappers.bundle.excludes = ['**/*']

grails.resources.uri.prefix = “”

grails.resources.adhoc.patterns =

['/images/*', '/css/*', '/js/*', '/plugins/*']

To test it just hit the image request.

<img class=“imgSize” src=“http://amazoncloudfrontbucket.s3-us-west-2.amazonaws.com/resources/pump.jpg”/>

Reference links:

  • Upload our content to Amazon S3 and grant permission.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/GettingStarted.html

  • To automate upload and download. We need to Install bucket explorer.

http://www.bucketexplorer.com/

  • Serving Compressed or Uncompressed File doc.

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html

 


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

Configuration Of Quartz Scheduler with Database in Grails

 

In my steps below, I’m using Grails 2.2.0 and Quartz 2.1.1. I’m also connecting to a local mysql database.

1. Add the “quartz-all-2.1.1.jar” and “c3p0-0.9.1.1.jar” (in the lib folder of your Quartz download) to your lib directory.

2. Add your Quartz.properties file to your “conf” directory (or somewhere else on your classpath). Here’s the Quartz.properties file I used (you’ll need to change the username and password)

#============================================================================

# Configure Main Scheduler Properties

#============================================================================

quartz.scheduler.instanceName = MyClusteredScheduler

quartz.scheduler.instanceId = AUTO

#============================================================================

# Configure ThreadPool

#============================================================================

quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool

quartz.threadPool.threadCount = 25

quartz.threadPool.threadPriority = 5

#============================================================================

# Configure JobStore

#============================================================================

quartz.jobStore.misfireThreshold = 60000

quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX

quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate

quartz.jobStore.useProperties = false

quartz.jobStore.dataSource = myDS

quartz.jobStore.tablePrefix = QRTZ_

quartz.jobStore.isClustered = true

quartz.jobStore.clusterCheckinInterval = 20000

#============================================================================

# Configure Datasources

#============================================================================

quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver

quartz.dataSource.myDS.URL = jdbc:mysql://localhost/schedulerproject?useUnicode=yes&characterEncoding=UTF-8

quartz.dataSource.myDS.user = root

quartz.dataSource.myDS.password = root

quartz.dataSource.myDS.maxConnections = 5

quartz.dataSource.myDS.validationQuery=select 0 from dual.

3. In your Config.groovy file, add or modify your “grails.config.locations” property. Here’s what I added

grails.config.locations = [

"classpath:conf/Quartz.properties"

]

4. I added the JobScheduler.java and HelloJob.java classes to my src/java directory. These could be groovy or whatever, but I just stole the example from Quartz to get it working correctly.

JobScheduler.java

package sample.quartz.scheduler;

import static org.quartz.JobBuilder.newJob;

import static org.quartz.TriggerBuilder.newTrigger;

import static org.quartz.CronScheduleBuilder.*;

import org.apache.log4j.Logger;

import org.quartz.JobDetail;

import org.quartz.Scheduler;

import org.quartz.SchedulerException;

import org.quartz.Trigger;

import org.quartz.impl.StdSchedulerFactory;

 

public class JobScheduler {

private static Logger log = Logger.getLogger(JobScheduler.class);

private static JobScheduler JOB_SCHEDULER = new JobScheduler();

private Scheduler scheduler = null;

public JobScheduler() {

}

public static JobScheduler getInstance() {

return JOB_SCHEDULER;

}

public void startup() {

try {

// and start it off

scheduler = StdSchedulerFactory.getDefaultScheduler();

System.out.println(“NAME: ” + cheduler.getSchedulerName());

scheduler.start();

// define the job and tie it to our HelloJob class

JobDetail job = newJob(HelloJob.class)

.withIdentity(“job1″, “group1″)

.build();

// Trigger a job that repeats every 20 seconds

Trigger trigger = newTrigger()

.withIdentity(“trigger1″, “group1″)

.withSchedule(cronSchedule(“0/20 * * * * ?”))

.build();

System.out.println(“Starting Jobs”);

// Tell quartz to schedule the job using our trigger

scheduler.scheduleJob(job, trigger);

scheduler.start();

} catch (SchedulerException se) {

se.printStackTrace();

}

}

public void shutdown() {

try {

scheduler.shutdown();

} catch (SchedulerException se) {

se.printStackTrace();

}

}

}

5. I added the JobScheduler and HelloJob java classes to my src/java directory.

HelloJob.java

package sample.quartz.scheduler;

import java.util.Date;

import org.apache.log4j.Logger;

import org.quartz.Job;

import org.quartz.JobExecutionContext;

import org.quartz.JobExecutionException;

 

public class HelloJob implements Job {

private static Logger log = Logger.getLogger(HelloJob.class);

public HelloJob() {

}

public void execute(JobExecutionContext context)

throws JobExecutionException {

System.out.println(“Hello!  HelloJob is executing. ” + new Date());

}

}

6. In your BootStrap.groovy file, add…

import sample.quartz.scheduler.JobScheduler

class BootStrap {

def init = { servletContext ->

JobScheduler.getInstance().startup()

}

def destroy = {

JobScheduler.getInstance().shutdown()

}

}

7. Create database. Here, my database name is schedulerproject.

and create table like as given below .

DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;

DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;

DROP TABLE IF EXISTS QRTZ_LOCKS;

DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_TRIGGERS;

DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;

DROP TABLE IF EXISTS QRTZ_CALENDARS;

CREATE TABLE QRTZ_JOB_DETAILS

(

SCHED_NAME VARCHAR(120) NOT NULL,

JOB_NAME  VARCHAR(200) NOT NULL,

JOB_GROUP VARCHAR(200) NOT NULL,

DESCRIPTION VARCHAR(250) NULL,

JOB_CLASS_NAME   VARCHAR(250) NOT NULL,

IS_DURABLE VARCHAR(1) NOT NULL,

IS_NONCONCURRENT VARCHAR(1) NOT NULL,

IS_UPDATE_DATA VARCHAR(1) NOT NULL,

REQUESTS_RECOVERY VARCHAR(1) NOT NULL,

JOB_DATA BLOB NULL,

PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)

);

 

CREATE TABLE QRTZ_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

JOB_NAME  VARCHAR(200) NOT NULL,

JOB_GROUP VARCHAR(200) NOT NULL,

DESCRIPTION VARCHAR(250) NULL,

NEXT_FIRE_TIME BIGINT(13) NULL,

PREV_FIRE_TIME BIGINT(13) NULL,

PRIORITY INTEGER NULL,

TRIGGER_STATE VARCHAR(16) NOT NULL,

TRIGGER_TYPE VARCHAR(8) NOT NULL,

START_TIME BIGINT(13) NOT NULL,

END_TIME BIGINT(13) NULL,

CALENDAR_NAME VARCHAR(200) NULL,

MISFIRE_INSTR SMALLINT(2) NULL,

JOB_DATA BLOB NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)

REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)

);

 

CREATE TABLE QRTZ_SIMPLE_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

REPEAT_COUNT BIGINT(7) NOT NULL,

REPEAT_INTERVAL BIGINT(12) NOT NULL,

TIMES_TRIGGERED BIGINT(10) NOT NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_CRON_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

CRON_EXPRESSION VARCHAR(200) NOT NULL,

TIME_ZONE_ID VARCHAR(80),

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_SIMPROP_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

STR_PROP_1 VARCHAR(512) NULL,

STR_PROP_2 VARCHAR(512) NULL,

STR_PROP_3 VARCHAR(512) NULL,

INT_PROP_1 INT NULL,

INT_PROP_2 INT NULL,

LONG_PROP_1 BIGINT NULL,

LONG_PROP_2 BIGINT NULL,

DEC_PROP_1 NUMERIC(13,4) NULL,

DEC_PROP_2 NUMERIC(13,4) NULL,

BOOL_PROP_1 VARCHAR(1) NULL,

BOOL_PROP_2 VARCHAR(1) NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_BLOB_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

BLOB_DATA BLOB NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP),

FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_CALENDARS

(

SCHED_NAME VARCHAR(120) NOT NULL,

CALENDAR_NAME  VARCHAR(200) NOT NULL,

CALENDAR BLOB NOT NULL,

PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)

);

CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS

(

SCHED_NAME VARCHAR(120) NOT NULL,

TRIGGER_GROUP  VARCHAR(200) NOT NULL,

PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)

);

CREATE TABLE QRTZ_FIRED_TRIGGERS

(

SCHED_NAME VARCHAR(120) NOT NULL,

ENTRY_ID VARCHAR(95) NOT NULL,

TRIGGER_NAME VARCHAR(200) NOT NULL,

TRIGGER_GROUP VARCHAR(200) NOT NULL,

INSTANCE_NAME VARCHAR(200) NOT NULL,

FIRED_TIME BIGINT(13) NOT NULL,

PRIORITY INTEGER NOT NULL,

STATE VARCHAR(16) NOT NULL,

JOB_NAME VARCHAR(200) NULL,

JOB_GROUP VARCHAR(200) NULL,

IS_NONCONCURRENT VARCHAR(1) NULL,

REQUESTS_RECOVERY VARCHAR(1) NULL,

PRIMARY KEY (SCHED_NAME,ENTRY_ID)

);

CREATE TABLE QRTZ_SCHEDULER_STATE

(

SCHED_NAME VARCHAR(120) NOT NULL,

INSTANCE_NAME VARCHAR(200) NOT NULL,

LAST_CHECKIN_TIME BIGINT(13) NOT NULL,

CHECKIN_INTERVAL BIGINT(13) NOT NULL,

PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)

);

CREATE TABLE QRTZ_LOCKS

(

SCHED_NAME VARCHAR(120) NOT NULL,

LOCK_NAME  VARCHAR(40) NOT NULL,

PRIMARY KEY (SCHED_NAME,LOCK_NAME)

);

commit;

8. Finally  run on different port or server.

grails –Dserver.port=8080 run-app

and

grails –Dserver.port=8090 run-app

clean when we get proxy related classCastException.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to get Connected With LinkedIn in Grails ??

Following are the steps to get connected to linkedIn in grails:

1. First of all install oauth plugin ,

Plugins{

 runtime “:oauth:2.1.0″

}

alternatively install it by grails install-plugin oauth

2. In Config.groovy file, add following

oauth {
providers {
linkedin {
api = org.scribe.builder.api.LinkedInApi
key = ‘xxx’
secret = ‘yyy’

callback = “http://localhost:8080/test2/oauth/linkedin/callback”
successUri = “http://localhost:8080/test2/oauthCallBack/linkedin”

failureUri = “http://localhost:8080/test2/oauthCallBack/linkedinFailure”

requestTokenUrl = “https://api.linkedin.com/uas/oauth/requestToken”
accessTokenUrl = “https://api.linkedin.com/uas/oauth/accessToken”
authUrl = “https://api.linkedin.com/uas/oauth/authorize”
}
}
}

grails.linkedin.api.url = “http://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,date-of-birth)?format=json”

3. In your GSP file add this ,

 

<oauth:connect provider=”linkedin”>Connect</oauth:connect>

4. Add handler for response, i.e. edit  OauthCallBackController  as following:

def linkedin() {
Token linkedinAccessToken = (Token)          session[oauthService.findSessionKeyForAccessToken('linkedin')]
def linkedInResponse = oauthService.getLinkedInResource(linkedinAccessToken, grailsApplication.config.grails.linkedin.api.url)
def linkedinParsedResponse = JSON.parse(linkedInResponse?.getBody())

User user = User.findByLinkedInId(linkedinParsedResponse['id'])
if (user) {
springSecurityService.reauthenticate(user.username)
} else {

}
}

def linkedinFailure() {
render “I am back..,.”
}


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to always set “www” in grailsUrl?

 

To always set “www” in grailsUrl, we have to create filter. Following is the example :

class HostFilters {

def filters = {
all(controller:’*’, action:’*’) {
before = {
if(request.getHeader(“host”) ==”changeme.com” ){

redirect(url: “http://www.changeme.com”)

}
}

}
}


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to transform Grails Java/Groovy objects to JSON/XML?

There are 4 classes that can be used as Converters:

  • for JSON Conversion
    • grails.converters.JSON
    • grails.converters.deep.JSON
  • for XML Conversion
    • grails.converters.XML
    • grails.converters.deep.XML

1. Initializing Converter

To create a converter instance you can choose any one from  the following notations:

default initialization

def converter = new JSON(target: Book.list());

the “as” operator

def converter = Book.list() as JSON

2. Using Converter  instance

  •      In order to get String representation of JSON/XML result , you can use toString()  on converter’s instance as shown below:

def converter = User.get(1) as JSON;
println converter.toString();

  •   In order to render result to a java.io.Writer, you can use render() as shown below:

def converter = User.list() as XML

converter.render(new java.io.FileWriter(“/path/to/my/file.xml”));

  • In order to render result to a HttpServletResponse, you can use render() as shown below:

import grails.converters.*;
class AjaxController {

def list1 = {
def converter = User.list() as JSON
        converter.render(response)

       return false

}

def list2 = {
render User.list() as JSON
}

  def xmllist = {
         render User.list as XML
   }

}

3. Codecs

The Converters plugin also provides codecsto quickly convert arbitary objects to JSON/XML without the need to import a Converter class.

  • encodeAsJSON

String result = someObject.encodeAsJSON();

  • encodeAsXML

String result = someObject.encodeAsXML();

4. Reverse Conversion

Both Converters have 3 different static parse methods.

  •      parse(String)

     import grails.converters.*
     import org.codehaus.groovy.grails.web.json.*;

// package containing JSONObject, JSONArray,…

    def o = JSON.parse(“{ foo: ‘bar’ }”); // Parse a JSON String
    assert o instanceof JSONObject

// In this case, JSON.parse returns a JSONObject instance
    assert o instanceof Map // which implements the Map interface
assert o.foo == ‘bar’ // access a property

// Parse another JSON String containing a Javascript Array
def a = JSON.parse(“[ 1, 2, 3]“)
assert a instanceof JSONArray
assert a instanceof List
assert a[0] == 1

// The following works in Grails >= 1.0.5
def rootNode = XML.parse “””<foo><bar ding=”dong”></foo>”””

// Same as Groovy’s XmlSlurper.parseText(String)
assert rootNode instanceof groovy.util.slurpersupport.GPathResult
assert rootNode.bar.@ding == ‘dong’

  • parse(InputStream, String)

Both Converters feature a static method for parsing the content from an java.io.InputStream. The second parameter of this method is the character encoding to use.
import grails.converters.*
def json = JSON.parse(new FileInputStream(“/path/to/file.json”), “UTF-8″)
def xml = XML.parse(new FileInputStream(“/path/to/file.xml”), “UTF-8″)

  • parse(HttpServletRequest)

A convenience method which checks the Request Content-Type, tries to detect the character encoding of the request and then parses the Request Body using the request’s inputStream.

request.XML and request.JSON

When you access request.XML or request.JSON the appropriate Converters’ parse method is automatically invoked which then checks the Content-Type header of the Request and in the case of a match parses the Request Body
import grails.converters.*
class SomeController {
// We assume the client requests this action using the request Content-Type
// “application/json” and { foo: ‘bar’ } as Request Body
def postJson = {
def json = request.JSON
assert json.foo == ‘bar’
}
// We assume the client requests this action using the request Content-Type
// “text/xml” and <foo><bar ding=”dong”></foo> as Request Body
def postXml = {
def xml = request.XML
assert xml.bar.@ding == ‘dong’
}
}

5. Configuration:

Example of Configuration in Config.groovy file:

grails.converters {
encoding = “ISO-8859-1″
json.date = “javascript”
default.pretty.print = true
}

6. Customizing Converters Results

You can customize which properties of class should be included in JSON representation by registering a specific Object Marshaller(grails.converters.JSON.registerObjectMarshaller) :

// a class to output in JSON
class User {
      String login
      String passwd

// JSON definition of the User object

static {
      grails.converters.JSON.registerObjectMarshaller(User) {
// you can filter here the key-value pairs to output:
          return it.properties.findAll {k,v -> k != ‘passwd’}
      }

   }

// a controller action

def myAction() {
         def a = new User(login:’bob’, passwd:’1234′)
        def list = [a, a]
        render list as JSON
    }


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

How to generate customize auto generated ids in grails?

You can customize random ids generated by GORM.

For this Hibernate has provided id-generator. You can customize the id generator and the column it maps to as follows:

class Person {

static mapping = {
table ‘people’
version false
id generator: ‘hilo’,
params: [table: 'hi_value',
column: 'next_value',
max_lo: 100]
}
}

Here , ‘hilo’ is  Hibernate’s built in generator that uses a separate table to generate ids.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

 

 

 

 

What is “Groovy” and “Grails” ?

Groovy…

  • is an agile and dynamic language for the Java Virtual Machine
  • builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • makes modern programming features available to Java developers with almost-zero learning curve
  • supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
  • increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
  • simplifies testing by supporting unit testing and mocking out-of-the-box
  • seamlessly integrates with all existing Java objects and libraries
  • compiles straight to Java bytecode so you can use it anywhere you can use Java

Grails…

Grails (previously known as “Groovy on Grails”) is a programming framework based on Groovy and inspired by Ruby on Rails (there are differences, but there are lots of similarities too). Like RoR, Grails promotes “coding by convention”, development best practices, and is meant to be highly productive.

Grails is used to build web applications that run on the JVM.

Advantages:

High productivity, focusing on business instead of plumbing.

 

 


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

 

Grails Environments

Grails supports the concept of environments. You can specify the environment to use before any command:

grails run-app // runs with the default “development” data source
grails dev run-app // runs with the “development” data source
grails prod run-app // runs with the production data source
grails -Dgrails.env=mycustomenv run-app// specific a custom environment

grails test run-app // runs with the test data source

These options are also available when packaging the application as a WAR file, although in this case the default data source used is _production_:

grails war// Packages the application with the “production” data source

grails dev war // Packages the application with the “development” data source
grails prod war // Packages the application with the “production” data source

You can use word ‘production‘ instead of ‘prod‘ and use ‘development‘ instead of ‘dev‘.

The short and full names of the environments defined by Grails are shown below:

 

You can take advantage of these environments you can have different DataSource settings per environment or different Config settings.

Datasource settings:

// environment specific settings
environments {
       development {
              dataSource {
                       dbCreate = “update” // one of ‘create’, ‘create-drop’,            ‘update’, ‘validate’, ”
                       url = “jdbc:mysql://localhost/database_name?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                       username = “XXX”
                       password = “XXX”
         }
}
test {
         dataSource {
                     dbCreate = “update”
                     url = “jdbc:mysql://localhost/database_name?                  useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                      username = “XXX”
                       password = “XXX”
           }
}
production {
               dataSource {
                           dbCreate = “update”
                           url = “jdbc:mysql://localhost/database_name? useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true”
                          username = “XXX”
                          password = “XXX” 
                          pooled = true
                          properties {
                                  maxActive = -1
                                  minEvictableIdleTimeMillis=1800000
                                  timeBetweenEvictionRunsMillis=1800000
                                  numTestsPerEvictionRun=3
                                  testOnBorrow=true
                                  testWhileIdle=true
                                  testOnReturn=true
                                  validationQuery=”SELECT 1″
            }
     }
    }
}

Config.groovy settings:

environments {
          production {
                 grails.serverURL = “http://www.changeme.com”
                 grails.dbconsole.enabled = true
                 grails.dbconsole.urlRoot = ‘/admin/dbconsole’
 }
development {
                 grails.serverURL = “http://localhost:8080/${appName}”
}
test {
          grails.serverURL = “http://localhost:8080/${appName}”
}
}


 

ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

Creating a Multi-Tenant Web App with Grails

The grails multi-tenant plugin allows you to run multiple “customers” (or tenants) from one installation of a grails application with minimum configuration. Application developers who would normally have to install multiple instance of their grails app (one-per-customer) and maintain multiple databases (one-per-customer) can use this plugin to run multiple customers from the same application AND database. The plugin also supports a single-tenant database configuration (one webapp for all tenants, but a datasource for each tenant).

Installation :

For installing run command,

 

 grails install-plugin multi-tenant

Webapp always runs in multi-tenant mode. But you can configure singleTenant  also. In your config.groovy add following,

tenant {
         mode = “singleTenant” // OR “multiTenant”
}

By default its multiTenant.

MultiTenant database set-up:

The ‘multiTenant’ mode relies your application to use just one database for all tenants running. For this firstly, you will need to specify which classes you want to make multitenant.  You can do this by annotating your class with @MultiTenant annotation. As shown below:

import grails.plugin.multitenant.core.groovy.compiler.MultiTenant
@MultiTenant
class MyClass {

}

Integer tenantId() {   //Defining indexes inside Grails domain classes
              id
}

This way, each instance of MyClass will belong to some tenant and all hibernate events that query your database, will add another condition in your queries that will filter just instances of the current tenant.

 


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.

What do “grails clean” or “grails clean-all” actually do?

grails clean command:

When we use the compile or war command Grails will create files and stores them by default in the project’s working directory. The location of the project working directory can be customized in our grails-app/conf/BuildConfig.groovy configuration file. We remove the generated files with the grails clean command. This command will remove all compiled class files, the WAR file, cached scripts and test reports.

grails clean-all command:

The grails clean command, doesn’t remove all files in the project working directory. Like plugins or web.xml file. So, use the         clean-all command to remove those files from the project working directory completely.


ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.