All posts by admin

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.

How to rerun BootStrap with grails without restarting server?

You can do this with the console plugin. It is useful for running ad-hoc code inside a running server.

To rerun your BootStrap init closure, browse to the web-based console at http://localhost:8080/appname/console. Enter the following in the console:

def servletCtx = org.codehaus.groovy.grails.web.context.ServletContextHolder.servletContext
def myBootstrapArtefact = grailsApplication.getArtefacts(‘Bootstrap’)[-1]
myBootstrapArtefact.referenceInstance.init(servletCtx)


 

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

How to access Grails configuration?

You can access grails configuration in following ways:

1. In Controller :
class DemoController {
def grailsApplication
def demoAction = {
def obj = grailsApplication.config.propertyInConfig
}
}

2. In services :
class DemoService {
def grailsApplication

def demoMethod = {

          def obj = grailsApplication.config.propertyInConfig

}

}
3. In taglib :

class DemoTaglib {
def grailsApplication
static namespace = “cd”
def demoMethod = {
def obj = grailsApplication.config.propertyInConfig
out << obj
}

}

You can call this method of taglib in view as <cd:demoMethod/>
4. In view :
<html>
<head><title>Demo</title></head>
<body>
${grailsApplication.config.propertyInConfig}
</body>
</html>

   


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

Difference between getAll, findAll and list in Grails?

    getAll is an enhanced version of get that takes multiple ids and returns a List of instances. The list size will be the same as the number of provided ids. If some of the provided ids are null or there are no instances with these ids, the resulting List will have null values in those positions.

    findAll lets you use HQL queries and supports pagination.  It finds all of domain class instances matching the specified query.

    list finds all instances and supports pagination.

 


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

How to execute code depending on environment you are in?

You can execute code depending on environment you are in following ways:

In Bootstrap:

import grails.util.Environment
class BootStrap {
        def init = { servletContext ->
         if (Environment.current == Environment.DEVELOPMENT) {
         // insert Development environment specific code here
        } else
        if (Environment.current == Environment.TEST) {
         // insert Test environment specific code here
       } else
      if (Environment.current == Environment.PRODUCTION) {
      // insert Production environment specific code here
       }
    }
}   

In Controller:

import grails.util.Environment
class SomeController {
         def someAction() {
              if (Environment.current == Environment.DEVELOPMENT) {
               // insert Development environment specific code here
              } else
              if (Environment.current == Environment.TEST) {
              // insert Test environment specific code here
              } else
            if (Environment.current == Environment.PRODUCTION) {
           // insert Production environment specific code here
           }
            render “Environment is ${Environment.current}”
         }
}

In Views:

<g:if env=”development”>
We are in Development Mode
</g:if>
<g:if env=”production”>
We are in Production Mode
</g:if>
<g:if env=”test”>
We are in Test Mode
</g:if>


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

How to integrate CKEditor with grails?

For integrating CKEditor with Grails you have to do following :

1. Installation:

grails install-plugin ckeditor

2. Usage in GSP:

add following in head section of your GSP,

    <head>
       …
      <ckeditor:resources/>
      …
      </head>

and in your page add following,

     <ckeditor:editor name=”myeditor” height=”400px”  width=”80%”>
           ${initialValue}
    </ckeditor:editor>

3. Configurations:

You have to do some configuration for file manager in config.groovy file as shown below:

ckeditor {
               config = “/js/myckconfig.js”
               skipAllowedItemsCheck = false
               defaultFileBrowser = “ofm”
upload {
              basedir = “/uploads/”
             overwrite = false
link {
            browser = true
           upload = false
           allowed = []
           denied = ['html', 'htm', 'php', 'php2', 'php3', 'php4', 'php5',
                                 'phtml', 'pwml', 'inc', 'asp', 'aspx', 'ascx', 'jsp',
                                 'cfm', 'cfc', 'pl', 'bat', 'exe', 'com', 'dll', 'vbs', 'js', 'reg',
                                 'cgi', 'htaccess', 'asis', 'sh', 'shtml', 'shtm', 'phtm']
}
image {
           browser = true
           upload = true
          allowed = ['jpg', 'gif', 'jpeg', 'png']
          denied = []
}
flash {
          browser = false
          upload = false
          allowed = ['swf']
          denied = []
        }
   }
}

4. Advanced topics:

  • Internal URI’s customization:

It is possible to customize the URI’s used to invoke the plugin’s connectors,

ckeditor.connectors.prefix = “/my/app/ck/”

  • Custom upload types:

You can customize upload types add following in above code snippet,

 …

upload {
     …
          avatar {
                 browser = true
                 upload = true
                 allowed = ['gif', 'jpg']
                 denied = ['exe', 'sh', 'cgi']
            }

}

 


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

How to override mail address?

Situation may arise where we want to send mails to a different mail id in development and  production mode.For this  Grails provides option of overriding mail so that all mails are send to a common mail id.

In config.groovy do following:

environments {
development {
grails.logging.jul.usebridge = false
grails {
mail {
host = “smtp.gmail.com”
port = 465
username = “sent_from_mail_id”
password = “password”
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
overrideAddress=”sent_to_mail_id”
}
}

}

production {
grails.logging.jul.usebridge = false
grails {
mail {
host = “smtp.gmail.com”
port = 465
username = “sent_from_mail_id”
password = “password”
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
overrideAddress=”sent_to_mail_id”
}
}

}

}


 

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

How to restrict Url access based on roles in Grails?

In Grails, you can restrict url access depending on role of user.

1. In Controller:

In controller, you can you can restrict access to methods (i.e. pages) by using @secured annotation as shown below:

import grails.plugin.springsecurity.annotation.Secured

@Secured(["ROLE_ADMIN"])
def index(Integer max) {
          …
}

In above example, only user having ROLE_ADMIN will be able to access index page.Likewise, you can give multiple roles also as shown below:

@Secured(["ROLE_ADMIN","ROLE_ORG_ADMIN"])

2. In View:

You can restrict access on view using SecurityTagLib as shown below:

<sec:ifAnyGranted roles=”ROLE_ADMIN,ROLE_ORG_ADMIN”>
<a href=”${createLink(controller:’leave’ ,action: ‘teamLeaveCalendar’)}”>Team Leave calender</a>
</sec:ifAnyGranted>

Like <sec:ifAnyGranted></sec:ifAnyGranted>, you can use  <sec:ifAllGranted></sec:ifAllGranted>, <sec:ifNotGranted></sec:ifNotGranted>


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

How to attach multiple attachments with mail in grails?

For sending mail you can use Asynchronous Mail Plugin.

1. Install Asynchronous Mail Plugin :

Dependency:  compile “:asynchronous-mail:1.2″

2. Usage :

Add following:

import grails.plugin.asyncmail.AsynchronousMailService

     AsynchronousMailService asynchronousMailService

3. In your method to add multiple attachment create map as shown below,

Map<String,ByteArrayOutputStream> attachments = new HashMap<String,ByteArrayOutputStream>();

ByteArrayOutputStream bytes0,bytes1,bytes2; // attachments

attachments.put(‘key0′,bytes0);

attachments.put(‘key1′,bytes1);

attachments.put(‘key2′,bytes2);

asynchronousMailService.sendMail {
multipart true
to emailID
subject emailSubject
html emailBodyContent
attachBytes “Approval”, “application/pdf”, attachments

}

attachBytes is used to attach attachments.


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