grails,spring-security,many-to-many , Grails with custom many to many relationship, relational table with parameters


Grails with custom many to many relationship, relational table with parameters

Question:

Tag: grails,spring-security,many-to-many

I have domains: Comments, Secuser and Rating.

I would like that each comment can be rated once by SecUser +1 or -1. In the view of related comments (to the domain discussion) I would like to have a button to up-vote or down-vote the comment and refresh the view. The code I have so far: The comments view:

<tbody>
    <g:each in="${comments}" var="comm">
        <tr>
            <td>${comm.comment}</td>
            <td>${comm.commentBy}</td>
            <td><g:formatDate format="dd.MM.yyyy HH:mm" date="${comm.createDate}"/> </td>
            <td><button type="button" class="btn btn-default btn-lg" onclick="${remoteFunction(action: 'ratePositiveComment', update: 'content', params:[commentID:"${comm.id}"])}"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="false" style="float:right">${comm.numberPositiveRatings}</span></button>
                &nbsp;
                <button type="button" class="btn btn-default btn-lg" onclick="${remoteFunction(action: 'rateNegativeComment', update: 'content', params:[commentID:"${comm.id}"])}"><span class="glyphicon glyphicon-thumbs-down" aria-hidden="false" onclick="addRating(-1, ${comm.id})" style="float:right">${comm.numberNegativeRatings}</span></button>
            </td>
        </tr>
    </g:each>
</tbody>

The comments controller:

class Comments {
    static belongsTo = Discussion
    Discussion discussion
    SecUser commentBy
    String comment
    Date createDate = new Date()
    static hasMany = [commRatings : Rating]

    public long getNumberPositiveRatings() {
    return  Rating.countByCommentRatedAndRate(this, 1);
    }

    public long getNumberNegativeRatings() {
        return  Rating.countByCommentRatedAndRate(this, -1);
    }

    List raters() {
        return commRatings.collect{it.ratingUser}
    }

    List addToPosRatingUser(SecUser user) {
        Rating.positiveRating(user, this)
        //return raters()
    }

    List addToNegRatingUser(SecUser user) {
        Rating.negativeRating(user, this)
       // return raters()
    }

Rating domain:

class Rating {
    static belongsTo = Comments
    int rate
    SecUser ratingUser
    Comments commentRated

    static Rating positiveRating(ratingUser, commentRated) {
        def m = Rating.findByRatingUserAndCommentRated(ratingUser, commentRated)
        if (!m) {
            m = new Rating()
            ratingUser?.addToRating(m)
            commentRated?.addToRating(m)
            m.rate = 1;
            m.save()
        }
        return m
    }

    static Rating negativeRating(ratingUser, commentRated) {
        def m = Rating.findByRatingUserAndCommentRated(ratingUser, commentRated)
        if (!m) {
            m = new Rating()
            ratingUser?.addToRating(m)
            commentRated?.addToRating(m)
            m.rate = -1;
            m.save()
        }
        return m
    }
}

In the domain SecUser (Spring security plugin) I added:

class SecUser {

    transient springSecurityService

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

    static hasMany = [ratings:Rating]

    List ratedComments() {
        return ratings.collect{it.commentRated}
    }

    List addPosCommentRating(Comments comm) {
        Rating.positiveRating(this, comm)
        return ratedComments()
    }

    List addNegCommentRating(Comments comm) {
        Rating.negativeRating(this, comm)
        return ratedComments()
    }

The CommentsController was scaffolded, the only added functions are:

def ratePositiveComment() {
    def rater = SecUser.findById(springSecurityService.currentUser.id);
    if(rater!=null) {
        Comments comm = Comments.get(params.commentID);
        comm.addToPosRatingUser(rater);
        comm.save();
    }
}


def rateNegativeComment() {
    def rater = SecUser.findById(springSecurityService.currentUser.id);
    if(rater!=null) {
        Comments comm = Comments.get(params.commentID);
        comm.addToNegRatingUser(rater);
        comm.save();
    }
}

Error code that I am getting is:

No signature of method: ForumProject.SecUser.addToRating() is applicable for argument types: (ForumProject.Rating) values: [ForumProject.Rating : (unsaved)]
Possible solutions: addToRatings(java.lang.Object). Stacktrace follows:
Message: No signature of method: ForumProject.SecUser.addToRating() is applicable for argument types: (ForumProject.Rating) values: [ForumProject.Rating : (unsaved)]
Possible solutions: addToRatings(java.lang.Object)

Answer:

The addTo (and removeFrom) methods are derived from the name in the hasMany map. If you had declared

static hasMany = [rating:Rating]

then the addTo method would be addToRating and your code would be correct. As it is now you just need to change the calls to addToRatings.

p.s. This is bad:

def rater = SecUser.findById(springSecurityService.currentUser.id);

springSecurityService.currentUser is already what you want, the SecUser that was used to create the Authentication when logging in, and it's retrieved from the database via a query, not from some cache. But you discard it after getting its id so you can load it again using an inefficient dynamic finder. Always use get instead of findById. So your code there should just be

def rater = springSecurityService.currentUser

Related:


Spring Security OAuth2 - Add parameter to Authorization URL


spring,spring-security,oauth-2.0,spring-security-oauth2
I am using Spring Security with OAuth2 for authentication/authorization using following project. http://projects.spring.io/spring-security-oauth/ I have a requirement to add parameter to OAuth2 authorization url. I am not sure how should I add it to AuthorizationCodeResourceDetails bean? The problem is I want to start the user journey by login or registration...

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>...

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) ... } ...

Using Spring Security, what's the right way to manage authorization to query responses?


java,spring,spring-security
Using Spring Security (v. 3.2.5), what's the right way to manage authorization to query responses? I have configured Spring Security to regulate access to different parts of the system based on user roles. But in many places, the principal is querying for data (e.g. looking up previously persisted details "owned"...

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...

Spring Data Rest: Return Resources of User


java,spring,spring-security,spring-data-rest
I'm creating a simple CRUD-App (a shoppinglist) with Spring Boot and Spring Data Rest. I have a resource: ShoppingItem. Is there an easy way to only return the resources which belong to the user who send the request? (Multiple User support) So a User only get his own ShoppingItems and...

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?

Spring Boot - How to kill current Spring Security session?


spring,spring-security,spring-boot
Currently I know that my setup is working because I was able to login properly using the basic HTTP authentication. I used these properties: security.basic.enabled=true security.user.name=user security.user.password=1qaz2wsx security.user.role=USER However, I want to relogin again. I tried clearing cookies (I assumed it was saved there), I checked my local/session storage and...

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...

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?...

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",...

Trouble with Login using Spring Boot and JDBC Security


spring,spring-security,spring-boot
My build.gradle file: task wrapper(type: Wrapper) { gradleVersion = '2.4' } buildscript { repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.3.RELEASE") } } apply plugin: 'java' apply plugin: 'spring-boot' repositories { mavenCentral() maven { url "http://repo.spring.io/release" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-jdbc")...

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...

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 =...

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: 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?

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: "...", ... }...

Spring Security login with UserDetailsService and Java config


java,spring,spring-mvc,spring-security
I am trying to add login functionality with a database lookup with Spring Security, and I am really struggling. I want to look up the user by implementing the UserDetailsService interface. I have read a ton of documentation and Googled for hours, but I am still stuck. Most of the...

multiple antMatcher in spring security


spring,spring-mvc,spring-security
I work on content management system, that has three antmatcher like the following http.authorizeRequests() .antMatchers("/", "/*.html").permitAll() .antMatchers("/user/**").hasRole("USER") .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/admin/login").permitAll() .antMatchers("/user/login").permitAll() .anyRequest().authenticated() .and() .csrf().disable(); which mean the visitors can see all site at root path (/*), and users can see only (/user), admin can see only (/admin), and there are two...

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...

SEVERE: Exception starting filter springSecurityFilterChain


spring,spring-security
I am trying to write spring application, and I have this code, but when run this code using Tomcat 8, This error appeared, I don't know what is the root cause of error, please help Error: 01:15:02.681 [localhost-startStop-1] INFO o.s.web.context.ContextLoader - Root WebApplicationContext: initialization started 01:15:02.756 [localhost-startStop-1] DEBUG o.s.w.c.s.StandardServletEnvironment -...

Is it possible to login from a winforms application to a website which uses spring security?


java,c#,winforms,spring-mvc,spring-security
I want to call a web service from my winforms application. My application is written on c# and the webservice is secured using spring security. Is it possible to login to the website and call that web service?. If it is possible how to do that?...

Difference between isAuthenticated and isFullyAuthenticated


spring,spring-security
I'm trying to learn spring security, and I have question: what is the difference between isAuthenticated and isFullyAuthenticated in spring security

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 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...

Spring security throws javax.servlet.ServletException: Could not resolve view with name 'j_spring_security_check'


java,spring,spring-mvc,spring-security,tiles-3
I am trying to add Spring security with customized login page and access to database to my Spring MVC application. It seems like my mapping is wrong as it can not map j_spring_security_check. To solve the issue I had a look at following pages 1,2,3 but could not solve the...

Spring OAuth2 not giving refresh token


java,spring,spring-security,spring-security-oauth2
I am running a OAuth Provider using Spring and "password" grant type. Running this (provider is on port 8080): curl -u "app:appclientsecret" "http://localhost:8080/oauth/token" --data "grant_type=password&username=marissa&password=koala" returns: {"access_token":"56da4d2b-7e66-483e-b88d-c1a58ee5a453","token_type":"bearer","expires_in":43199,"scope":"read"} For some reason there is no refresh token. I know according to the spec, the refresh token is optional; is there some way...

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 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...

Spring Security 4 with custom provider and handlers not caching the url before authentication


java,spring,spring-security
I've configured a custom authentication provider, a success handler and a failure handler in Spring Security (v4.0.1). When using the default ones, after displaying the login page, the user was redirected to the previously requested url. However, I lost that behaviour when implementing my own ones, so I'm trying to...

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?

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.

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 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 =...

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...

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. *...

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...

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 " }...

Is it possible to permit all users except anonymous one?


java,spring,spring-security
How can I permit access to URL such that only anonymous one can't get the page? I'm using Spring security. <intercept-url pattern="/pattern/page.html" access="__WHAT_SHOULD_BE_HERE__"/> ...

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...

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...

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...

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,...

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...

[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...

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...

Spring Resttemplate login fails


java,spring,spring-mvc,spring-security,csrf
after an update to spring-4.1.6 i'am not able to login to my rest services any more. I looked on different sides, but couldn't solve the problem... so i ask for help. Here is my my web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- The definition of the...

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"/>...