grails,plugins , Export plugin on Grails 2.4.4


Export plugin on Grails 2.4.4

Question:

Tag: grails,plugins

I want to make an app that can upload Excel and read them. and create PDF, Excel and Word on the fly. I use Grails 2.4.4. and Export v 1.6.

Here's my code

class AuthUserController {
    def exportService
    def grailsApplication
    ....
    def list = {
        if(!params.max) params.max = 10

        if(params?.format && params.format != "html"){
            response.contentType = grailsApplication.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=AuthUser.${params.extension}")
            List fields = ["username", "email"]
            Map labels = ["username": "username", "email": "email"]

            /* Formatter closure in previous releases
            def upperCase = { value ->
                return value.toUpperCase()
            }
            */

            // Formatter closure
            def upperCase = { domain, value ->
                return value.toUpperCase()
            }

            Map formatters = [username: upperCase]
            Map parameters = [username: "admin", "column.widths": [0.2, 0.3, 0.5]]
            exportService.export(params.format, response.outputStream,  response.outputStream,AuthUser.list(params), [:], fields, labels, formatters, parameters)
        }

        [ authUserInstanceList: AuthUser.list( params ) ]
    }

and on the model

class AuthUser {

    transient springSecurityService

    String username
    String password
    String email
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired

    static transients = ['springSecurityService']

    static hasMany = [madeBillings:Billing, goodsBillings:GoodsBill, approvedRequest:TenantRequest, journals:Journal]

    static constraints = {
        username blank: false, unique: true
        password blank: false
        email blank: false, unique: true, email: true
    }

    static mapping = {
        password column: '`password`'
        tablePerHierarchy false
    }

    Set<AuthRole> getAuthorities() {
        AuthUserAuthRole.findAllByAuthUser(this).collect { it.authRole }
    }

    def beforeInsert() {
        encodePassword()
    }

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
    }

    String toString() {
        username
    }
}

I try to use http://localhost:8080/myapp/authUser/list?format=csv&extension=csv

I have found the solution from the documentation on the official plugin page

def list = {
    if(!params.max) params.max = 10

    if(params?.exportFormat && params.exportFormat != "html"){ //must change to exportFormat cause format is reserved for the default grails format
        response.contentType = grailsApplication.config.grails.mime.types[params.exportFormat]
        response.setHeader("Content-disposition", "attachment; filename=AuthUser.${params.extension}")

        exportService.export(params.exportFormat, response.outputStream,AuthUser.list(params), [:], [:])
    }

    //   [ authUserInstanceList: AuthUser.list( params ) ] you have to comment this or give an else clause since  the response already called before
}

Answer:

You could use the grails export plugin to export data to excel, csv, pdf, etc. It's easy to configure and use.

Here is the link: http://grails.org/plugin/export


Related:


Intercepting login calls with Spring-Security-Rest plugin in Grails


rest,grails,spring-security
I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts. As I am quite new to Spring Security...

grails one to many with additional column


grails,relationship,one-to-many
In my Grails project I need to have a 1:N relationship between two domain classes. So, I've created the following domain class: class Receipt_HealthService { Receipt receipt HealthService healthService int quantity = 1 static constraints = { } } and in Receipt I have the following: @NotNull static hasMany =...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline


grails,grails-plugin
Since there is no deferred option for: <asset:javascript src="custom_view_script.js"/> What else can be used, outside of resource plugin, to place view specific script right before the closing body tag and without declaring it globally in layout? I do know about: <asset:deferredScripts/> but that only handles on page script and not...

Testing for the Default Value


grails,spock
I am just starting to write tests for a Grails app and I have watched this and read this and would like to use the tests to check that the constraints have been set properly. Now, while at it, I would figure one should also test if the default value...

Grails: Carry forward params on hyperlink is clicked


grails,redirect,controller
How to carry forward the parameters when hyperlink is clicked? Here is my gsp code: <g:link class="grid_link" controller="user" action="delete" id="${userInstance.id}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure, want to delete?')}');">Delete</g:link> Here is my controller code: def delete() { try { def userInstance = User.get(params.id) //deleting the user //successful. redirect(action: "list",...

Intellij IDEA long processing for grails app with warning “too much output to process”


grails,intellij-idea,jvm
I new to Intellij for Grails app while run the app it execute lot of thing with the warning "Too much output to process" & takes comparatively more time to start the server. Below is the log screen (AbstractAutowireCapableBeanFactory.java:539) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) at...

grails message as argument of other message


grails,internationalization,taglib
I have this for example in my i18n messages_es.properties birds.label=Aves mammals.label=mamiferos reptiles.label=reptiles default.no.items.found=No se encontraron {0} And then I want to use the message, inside the template argument in my Grails .gsp Views: <g:message code="default.no.items.found" args="<g:message code='birds.label'/>"/> This of course doesn't work. But is there a way to make this...

Why store the function on the element using data()?


javascript,jquery,plugins
I am trying to understand some code from the Swipebox plugin. There is a function declared. $.swipebox = function( elem, options ){ // plugin Jquery codes.. } Now this codes below I really do not understand. What is the main purpose of this code? Why does it save function to...

[B cannot be cast to java.sql.Blob


grails,gorm
This is my domain class class TimesheetSubmission { Date submissionDate=new Date() String foreman String shift String jobId Date date byte[] xmlSubmission String xmlResponse static constraints = { submissionDate nullable: false foreman nullable: false shift nullable: false jobId nullable: false date nullable: false xmlSubmission nullable: true xmlResponse nullable: false } static...

grails 3.0.1 scaffolded view does not show domain relationship


grails,scaffolding
I am following the example in the book "Grails a Quick-Start Guide" using Grails 3.0.1 with following domains package com.tekdays class TekEvent { static constraints = { name() city() description maxSize:5000 organizer() venue() startDate() endDate() } String city String name TekUser organizer String venue Date startDate Date endDate String description...

Fluentd parser plugin


plugins,fluentd
I am trying to implement a parser plugin for fluentd. Below are the configuration file and the plugin file. Fluentd config file. <source> type syslog port 9010 bind x.x.x.x tag flog format flog_message </source> Plugin file module Fluent class TextParser class ElogParser < Parser Plugin.register_parser("flog_message", self) config_param :delimiter, :string, :default...

How to update a server side datatable on change a checkbox from outside of datatable


grails,datatables,datatables-1.10,grails-2.4
I am using data table with Grails. I have a check box outside the data table and on its event I want to load the table again with the check box value. Here are my attempts below : In my view where the check box is >> <g:checkBox id="wrapCheck" name="wrapCheck"/>...

Grails: Intercept form request


grails
My Grails domain model consists of something like the following: Competition - with name String property Club - with name String property Team - with club and competition properties Game - with teamOne and teamTwo properties I'm looking to create a Game form that contains the following: a competition drop-down...

Grails: Carry forward params on g:actionSubmit is clicked


grails,gsp
How to carry forward the parameters when g:actionSubmit button is clicked? Here is my gsp code: <g:checkBox name="msgCheck" checked="" value="${userInstance.emailId}"></g:checkBox> ... <g:actionSubmit class="update" action="delete" value="Delete" params="${params}"></g:actionSubmit> Here is my controller code: def delete() { try { def user_list = params.msgCheck //deleting the user //successful. redirect(action: "list", params: params) } catch...

Grails logging auto inject


grails,logback
I use grails 3.0.2 and logback. How can I use this logger in my code, can I somehow autoinject it, like log.debug() in grails 2.x which was using org.apache.commons.logging.Log?

Error when using angular with Grails


angularjs,grails
Here is my index.gsp <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src="/js/angular.min.js"></script> </html> When I build an app, There is an error like this, Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=myApp&p1=Error%3A%…20at%20d%20(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fangular.min.js%3A17%3A381)...

Grails: Do addTo* and removeFrom* require a call to save?


grails,gorm,grails-2.0,grails-domain-class
In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

How to make a discourse plugin available for public posts?


ruby-on-rails,plugins,discourse
I've developed a discourse plugin successfully. However, I need to be logged in into discourse in order to see the plugin working. Any ideas?...

File upload with grails and jquery


jquery,grails
I have a form with multiple inputs plus a doc or pdf file upload. //Multiple input fields are here then upload -> <div class="controls"> <div class="fileupload ${ person?.attachment ? 'fileupload-exists' : 'fileupload-new' }" id="attachment" data-provides="fileupload" data-name="attachment"> <span class="btn btn-file"> <span class="fileupload-new">Add</span> <span class="fileupload-exists">Change</span> <input type="file" /> </span> <span class="fileupload-preview"></span>...

How to analyze code from other class than currently analyzed in SonarQube?


java,plugins,sonarqube
Case: I'm writing SonarQube rule that needs to check if manually created object is being closed. When it's not, issue should be raised. Let's assume that part related to determining if object is created manually (or not) is easy and not relevant. For purpose of this example it'll be...

How to inactivate an eclipse plug-in without uninstall it?


eclipse,plugins,eclipse-plugin,kepler
How to inactivate an plug-in in Eclipse Kepler SR2 without uninstalling it? I have a plug-in for Android, which is pretty big and causes eclipse starting slow. But I need the plug-in on some other projects. In Help -> About Eclipse > Installation Details -> Installed Software, there is only...

Decode base64 image in Grails [duplicate]


grails,groovy
This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Render a controller into a String


grails,grails-2.0
I can render a template or a view into a String, but how can I render a controller into a String ? I would like to perform this kind of operation: def myAction = { ... def html = renderToString(controller: 'myController', action: 'myAction', params: [what:'ever']) render modify(html) ... } ...

passing backbone collection to view


grails,backbone.js,handlebars
I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...

Can i use font-awesome in android's edittext?


android,plugins,font-awesome
I have added font-awesome .tff file to the assets folder, initlaized some of the icons in the strings.xml file, changed the typefaces of the entities i will use font-awesome in and tried using font-awesome on buttons and it worked, but i did the same for edittexts but there are strings...

Display artifact in Jenkins Build description


plugins,jenkins
I would like to automatically display a artifact as part of the build description. Now I can do this by manually editing the build description but that would mean I have to do this for every build. Is there a way to automate this? This is what I would like...

Hibernate proxies - classes with unusual names


grails
While doing some GORM research to better my understanding of GORM, I was using a practice Grails project where I had a Pet domain class. I came across a casting error where I noticed in the error message there was a class with a name like Pet_$$_javassist_3. Is this a...

NullPointerException when publishing a Grails 3 plugin


grails
I'm trying to publish this Grails 3 plugin to Bintray, by following the steps in this guide. The final step is to run gradle bintrayUpload on the command-line from the project root dir. When I do this, I get the following error message FAILURE: Build failed with an exception. *...

unable to resolve class org.apache.commons.net.ftp in grails


grails,apache-commons
I am developing a module in which some file need to be uploaded on a ftp server for that I have added the "commons-net-3.3.jar" in my grails app & while using it import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPClientConfig import org.apache.commons.net.ftp.FTPFile import org.apache.commons.net.ftp.FTPReply It is throwing the error unable to resolve...

Import jQuery Plugin with JSPM


jquery,plugins,shim,jspm
I'm trying to import the jQuery plugin jQuery.scrollTo with JSPM. So far I installed it with jspm install npm:jquery.scrollto and now I'm trying to import it with import $ from 'jquery'; import scrollTo from 'jquery.scrollto'; Now I'm only getting $(...).scrollTo is not a function errors. I tried to shim it,...

Grails 3.0.2 missing generate-views


java,grails,command-line,ide,ggts
I'm new to grails and I'm trying to get my first HelloWorld from it. I can generate it with the controller, but I can't create a view because it isn't listed in the Grails (3.0.2) list of command. Because any IDE support grails 3.*, I can't create it by that...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types


grails,groovy,jax-rs
While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Update Joda-Time in Grails


grails,jodatime,localtime
I use Joda-Time via joda-time plugin in Grails to input time data, but its constructor shows time, which is one hour ahead then in my time zone. Compulsory timezone setting in constructor as like: new LocalTime(DateTimeZone.forID("Europe/Moscow")) doesn't help. I've heard, what it happens, because I've outdated timezone data containing old...

need wordpress plugin to show 3 type of different kind of text, image and 2 buttons


wordpress,plugins,wordpress-plugin
I have slider image on http://techturners.com/arman-badwal/ page in "featured work" section. I need plugin to create dynamic slider like image in section.I use many sliders like cyclone-slider but they show only title, description and image.

Retrieving Array of Object from params on Grails


arrays,ajax,grails
I'm passing an Array on a POST request using an AJAX call, but not a simple one, rather an Array of Objects: var param = { ..., branches: { 0: { address: "...", telephone: "...", fax: "...", ... }, ... nth: { address: "...", telephone: "...", fax: "...", ... }...

Encryption of strings using AES 128 in Java/grails


java,grails,encryption,aes
I would like to encrypt 3 strings using AES 128 in Java / Grails, and using the code below, but i get the error "An error occurred when encrypting", can someone tell me what is wrong with my code, how to fix it. thanks in advance and to Stackoverflow. String...

Minecraft plugin sign reading


java,plugins,minecraft
I've got problem trying to get values of sign lines in minecraft plugin. Here is my code: package pl.maccraft.regssal; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; public final class rgs...

Grails 3.0 Searchable plugin


maven,grails
I've tried to use the searchable plugin in grails 3.0, but I am not sure wheather it is compatible or not. I've added compile "org.grails.plugins:searchable" to the dependencies. The build completes but yields a NotSearializableException: > Configuring > 1/1 projects > Resolving dependencies ':agent' > Resolving dependencies ': BUILD SUCCESSFUL...

showing null point exception when findAllBy - for session object


grails,gsp
I have already checked that session.parent_id and session.id_of_project is not null in the below code in gsp <g:if test="$session.parent_id"> <g:set var="permission" value="${Project_permission.findAllById_of_projectAndParent_id(session.id_of_project, session.parent_id)}"/> <g:each var="emp" in="${permission}"> <g:set var="employee2" value="${Employee.findById(emp.id_of_employee)}"/> <li class="parent_li"> <span class="badge red" title="Collapse this branch"> <i class="fa fa-minus-sign">...

Log Grails Pre 3.0 startup time


grails
In Grails 2.x.x is it somehow possible to log the startup time? We are currently trying to optimize the application startup and having the startup time logged would help tremendously.

Use data-* attribute in grails g.link generated in tagLib


grails
Is there a way to use data- attributes in g.link generated by a tagLib? I want to store some DOM info instead of using params in the g.link which results in query parameters. Example: out << g.link(controller: "calendar", action: "info", params: [id: cal_id], data-info: "abc") { "click me " }...

Eclipse extension point for Open Resource/Open Type dialogs


eclipse,plugins,eclipse-plugin
Is there an extension point where I can customize the search behavior of these dialog boxes? Or am I better off making an extensions that just overrides those hotkeys with dialog boxes that subclass FilteredResourcesSelectionDialog?...

Execute controller function in Grails via Ajax


javascript,jquery,ajax,grails,gsp
I am a novice with ajax in Grails. I want to try to execute a controller method from gsp-code from ajax. This is part of my gsp-code: <g:select optionKey="id" name="region.id" id="region" from="${region}" noSelection="[null:' ']" onchange="categoryChanged(this.value);" ></g:select> <div> <b>Sub-Category: </b> <span id="subContainer"></span> </div> <script> function categoryChanged(regionId) { $.ajax({type:'POST',data:'regionId='+regionId,...

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

alert grails pagination current offset value


grails,pagination
I am using Grails 2.4.2. I have a list which is using pagination. When I mouse hover a number or next page icon it shows current offset number as tool tip. Can I alert this offset number or get my list's current page offset number?

Implementing one page scroll by Pete R


jquery,css,plugins,scroll
Im not good with jquery, js, scripts overall and i´m trying implementing this onepagescroll puglin by Pete R. but till now no sucess. https://github.com/peachananr/onepage-scroll Thinks i´ve done: body { margin: 0; font-family: 'Open Sans', Helvetica, sans-serif; min-width: 900px; } .header { background-image: url("img/fundo1.jpg"); background-size: cover; background-color: rgb(21, 21, 21); color:...

grails DataSource.groovy refer bean for decoding password


grails
Referring https://jira.grails.org/browse/GRAILS-3620, we need to specify a class with static methods to decode the encrypted password in DataSource config. For passwordEncryptionCodec property, is it possible to refer to a bean defined in resources.xml or any other grails bean definition files? For ex: having a decrypted Properties bean in resoures.xml or...

Grails 2.3.9 - Error: ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType


grails,grails-plugin,spock,grails-2.3
Whenever I enter the grails command: test-app I get this error: Error executing script TestApp: java.lang.ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType (Use --stacktrace to see the full trace) In my BuildConfig.groovy I have: grails.project.dependency.resolution = { ... plugins { ... test ":spock:0.7" } } I've tried replacing it with compile ":spock:0.7" . I've also...

Grails 2.4.4 spring security role doesn't apply to user


java,spring,grails,spring-security,spring-annotations
I have controller: class AdminController { def springSecurityService @Secured(['ROLE_ADMIN', 'ROLE_USER']) def index() { render "test"; } And user with role ROLE_ADMIN in the table: But, when I use: springSecurityService.getPrincipal().getAuthorities() There is only one role: ROLE_NO_ROLES Why? def loggedInUser = springSecurityService.currentUser; returns correct user. Config: ... grails.plugin.springsecurity.userLookup.userDomainClassName = '...' grails.plugin.springsecurity.userLookup.authorityJoinClassName =...

Error when executing Grails application in Spring Tool Suite


grails,spring-tool-suite
I get the following error when executing my Grails application in Spring Tool Suite: | Error 2015-06-12 18:19:18,357 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - Unsuccessful: alter table meta_data_master_template add index FK6FD57D1CFA081AA2 (protocol_id), add constraint FK6FD57D1CFA081AA2 foreign key (protocol_id) references protocol (protocol_id) | Error 2015-06-12 18:19:18,357 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate - Cannot add or...