Skip to main content

Posts

Showing posts with the label Grails

Get Current Environment in Grails

How to create custom Environments in GRAILS. This is how you can specify the environments in your grails application. Below we have made five environments. production uat (custom) qa (custom) development test environments { production { grails.serverURL = "http://www.ekiras.com/" } uat { grails.serverURL = "http://uat.ekiras.com:8080/" } qa { grails.serverURL = "http://qa.ekiras.com:8080/" } development { grails.serverURL = "http://localhost:8080/${appName}" } test { grails.serverURL = "http://localhost:8080/${appName}" } } There are Five predefined environments in grails. APPLICATION CUSTOM DEVELOPMENT PRODUCTION TEST How to get Execute a particular Environment in GRAILS To run a particular environment in grails you can do the following grails -Denv=qa -Dserver.port=8080 run-app How to get Current Environment in Grails Controller You can get current environ...

How to execute a SQL query in grails

Points To Remember You need to inject the  SessionFactory  object in the service or the controller, where you want to use it. Get the current session from the session factory and execute the query in this session using  sessionFactory.getCurrentSession(). You can also execute the query in a new session by using  sessionFactory.openSession(). Executing SQL query in grails Person.groovy package com.ekiras.grails; class Person{ String username String email String password static mapping = { } static constraints = { username nullable: true password nullable: false, blank: false email nullable: false, blank: false } } PersonService.groovy package com.ekiras.grails; import org.hibernate.SessionFactory; import grails.transaction.Transactional import com.ekiras.grails.Person; @Transactional class PersonService{ SessionFactory sessionFactory; def listPersons(){ String query = "select distinct username from person"; def person...

How to Upload and Read a Csv in Grails

Points To Remember Add the plugin Csv Grails plugin . You can do it manually without the plugin if the you have a uniform structure of the csv file. Upload a Csv  You need to add the dependency for the csv file reader in BUildConfig.groovy as shown below BuildConfig.groovy compile ":csv:0.3.1" And you have a csv file like the following. upload.jsp <g:uploadForm action="upload"> <input type="file" name="file"> <g:submitButton name="file" value="Upload"/> </g:uploadForm> When the above form is submitted then the request will be handled by the controller action as shown below UploadController.groovy def upload() { MultipartFile file = request.getFile( 'file' ) file.inputStream.eachCsvLine { row -> String name = row[1] ?: "NA"; String email = row[2] ?: "NA"; // Business Logic here } } Now you can do your bus...

How to do Versioning Controllers in Grails Example

Points To Remember Versioning  of Controllers can be done in grails with the help of UrlMappings and Namespaces. We can have two or more controllers with the same name as long as they are in different packages and different namespaces . You can map these controllers in UrlMappings  like  /$namespace/$controller/$action Versioning of Grails Controllers  The easiest way of versioning the grails controllers is to do it with the help of namespaces. So in this example we will try to do versioning of the controllers on the basis of namespaces. Test.groovy package com.ekiras.versioning.v1 class TestController { static namespace = "v1" def index() { render "Hi, This is version 1" } } Test.groovy package com.ekiras.versioning.v2 class TestController { static namespace = "v2" def index() { render "Hi, This is version 2" } } UrlMappings class UrlMappings { static mappings = { "/$namespace/$controller/$a...

Youtube Data Api v3 : Authenticate User

Points To Remember You must have a project created in Developers console to use Youtube data api and other api's. You should save the youtube refresh token in a database or file where you can save it for a long time and use it. Youtube refresh token is generated only once , so if you want to regenerate it go to google accounts page  and revoke access to your project and then re authenticate. To revoke access, go to Connected Apps and Sites  in the above mentioned url and click on your project and then click revoke access to revoke access to the app. Steps to Use Youtube Data Api v3 You need to create a new Project in your at  Developers Console . After creating a project you need to go to  Project -> Api & auth -> Credentials  , and then create a new  Client ID . Go to  Project -> Api & auth ->APIs  and enable  Youtube Analytics API  and  YouTube Data API v3 . This will enable your project to use consume these a...

Spring Security : Custom UserDetailsService and Custom UserDetails

Points To Remember You need to change the UserDetailsService, User Object of the spring security to achieve this. Add Custom User Details to Spring Security Authentication Object First of all we nee to create a new User Object that will override the User class of the spring security in package  org.springframework.security.core.userdetails.User  After this, you need to tell  UserDetailsService to use this object as the principal for the authentication token. For this you will have to override the UserDetailsService of the spring security. You can have the custom User object like. Custom User Class -> MyUser.groovy package com.ekiras import org.springframework.security.core.GrantedAuthority /** * Created by ekansh on 24/1/15. */ class MyUser extends org.springframework.security.core.userdetails.User { // Declare all custom attributes here private final Object id; private String name; public MyUser(String username, String password, boolean enabled, bool...

Spring Security : Create a Custom Authentication Filter

Points To Remember You may need to create an AuthenticatioFilter when you want to create a custom logic for handling the authentication filter. You may also want to create your own Authentication Provider, Entry Point, Authentication Token etc to customize the authentication process to a new level. Step 1 : Create a Filter Let us first create a class named MyAuthenticationFilter and then register it as a bean in resources.groovy . After we have created the class and registered the it as a bean, we can use this class as a filter for our custom spring security authentication. Class : MyAuthenticationFilter.groovy package com.ekiras import org.springframework.context.ApplicationEventPublisher import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent import org.springframework.security.core.Authentication import org.springframework.security.core.AuthenticationExce...

How to integrate Spring Security in Grails

Points To Remember Go to the Grails Spring Security Plugin  and add the dependency in the BuildConfig . Integrate Spring Security in Grails Add the latest grails spring security plugin in the build config of the project. This will add spring security jars and classes that will be used to configure spring security in the project. http://grails.org/plugin/spring-security-core Now run the following command from the terminal. grails s2-quickstart com.ekiras User Role Here the syntax of the above command is grails s2-quickstart {package} {user domain} {authority domain} The above command will create three Domains in the project User, Role and UserRole. user domain will contain the user info, role domain will contain Authorities and UserRole will contain the user authority mappings. It will also add the following settings to the Config.groovy // Added by the Spring Security Core plugin: grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.ekiras.User' grails.plugin.spri...

How to apply Constraints in Command Objects

Points To Remember You need to add the  @Validateable  annotation to the command class. Use  importFrom  in the constraints block with the domain name to import the constraints from domain. How to add Constraints to the Command Object. Lets us look at the example below. We have created a Domain by name User and a Command object by name UserCommand. We have created the constraints for email, password, first name and last name in User domain. We will import these constraints from domain to the command object and add some more constraints like verify password( if password and confirm password match). User.groovy package com.ekiras.domain class User { String email String password String firstName String lastName static constraints = { email(nullable: false, blank: false, unique: true, email:true) password(nullable: false, blank: false) firstName(nullable: false, blank: false) lastName(nullable: false, blank: false) ...

Render HTML String in a GSP in Grails

Points To Remember By default, in grails all the html code and script code is escaped. You can render your html string as html in three ways, change in config, change at page level and change at field level.  Rendering HTML String in a GSP in Grails. Suppose we have a String like the following and we want it to get rendered as HTML in our gsp. By default out code will get rendered like this. Hi < br />My name is Ekansh Rastogi < br />I want this in three lines. But we wanted out output as Hi My name is Ekansh Rastogi I want this in three lines. So, following are the ways in which you can render your HTML String as HTML . Render the Html String you want to encode as HTML. ${raw(htmlString)} This will encode the string and make it render like html. This will encode only the string on which it is called upon. Render the all HTML Strings in a page to encode as HTML. <%@page expressionCodec="none" %> This will render all the html strings in the page as HTML....

Difference between Grails Respond and Grails Render

First things that comes in mind Respond was introduced in Grails v2.3. Render is used by Grails to render different forms of responses from simple text response, to views to templates. Respond automatically attempts to return the most appropriate type for the requested content type. Respond is a better version of render, and can do everything render does. Example In case you want to send data to the view in "xml" or in "json" format then you will have to do the following render :  // renders text for a specified content-type/encoding render(text: " some xml ", contentType: "text/xml", encoding: "UTF-8" render(text: " some json ", contentType: "text/json", encoding: "UTF-8" respond :  by using respond, it will automatically select the correct return type respond( text: "some text in json or xml" [formats : ['xml' , 'json']]) it will automatically send the required respond depending ...