Java ASSERTION error in grails - java

I am getting the following error:
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at ../../../src/share/instrument/JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at ../../../src/share/instrument/JPLISAgent.c line: 844
| Error 2014-08-28 09:25:11,399 [http-bio-8080-exec-5] ERROR errors.GrailsExceptionResolver - StackOverflowError occurred when processing request: [GET] /api/getProduct - parameters:
id: 14
Stacktrace follows:
Message: Executing action [getProduct] of controller [project.ApiController] caused exception: Runtime error executing action
Line | Method
->> 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
my domains are as follows:
class Product {
String name
String comments
static hasMany = [components:Components]
public asJSON(){
println "product: "+this.id
def builder = new groovy.json.JsonBuilder()
def root = builder {
id this.id
name this.name
comments this.comments
components this.components.collect {it.asJSON()}
}
return builder.toString().replaceAll(/\\"/, '"').replaceAll(/\"\{/,'{').replaceAll(/\}\"/,'}')
}
}
Component:
class Components {
Product part_of
static hasMany = [alternatives:Alternatives]
public String asJSON(){
def builder = new groovy.json.JsonBuilder()
def root = builder {
id this.id
product (this.part_of)?this.part_of.asJSON():null
// alternatives (this.alternatives)?this.alternatives.collect {it.product.productAsJSON()} :null
}
return builder.toString()
}
}
When I do the following I get the exception
Product.get(1).asJSON()
I have checked that it is not recursively calling itself.
Product 1 have one Component which has a Product instance called part_of which is product with the ID 5

Related

My grails project facing error"TransactionRequiredException:no transaction" using domain.save(flush:true).save() it can is saving but updating

package com.fhjony.ocbt
import grails.web.servlet.mvc.GrailsParameterMap
class MemberService {
def save(GrailsParameterMap params) {
Member member = new Member(params)
def response = AppUtil.saveResponse(false, member)
if (member.validate()) {
member.save(true)
if (!member.hasErrors()){
response.isSuccess = true
}
}
return response
}
def update(Member member, GrailsParameterMap params) {
member.properties = params
def response = AppUtil.saveResponse(false, member)
if (member.validate()) {
member.save(flush: true)
if (!member.hasErrors()){
response.isSuccess = true
}
}
return response
}
def getById(Serializable id) {
return Member.get(id)
}
def list(GrailsParameterMap params) {
params.max = params.max ?: GlobalConfig.itemPerPage()
List<Member> memberList = Member.createCriteria().list(params) {
if (params?.colName && params?.colValue) {
like(params.colName, "%" + params.colValue + "%")
}
if (!params.sort) {
order("id", "desc")
}
}
return [list: memberList, count: memberList.totalCount]
}
def delete(Member member) {
try {
member.delete(flush: true,failOnError:true)
} catch (Exception e) {
println(e.getMessage())
return false
}
return true
}
}
Error message:
URI /member/update Class
javax.persistence.TransactionRequiredException Message null Caused by
no transaction is in progress
Line | Method
->> 211 | invoke in org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 188 | invoke in org.grails.core.DefaultGrailsControllerClass | 90 | handle . . . .
. in org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter | 1039
| doDispatch in
org.springframework.web.servlet.DispatcherServlet | 942 | doService
. . . in '' | 1005 | processRequest in
org.springframework.web.servlet.FrameworkServlet | 908 | doPost . .
. . . in '' | 882 | service in '' | 77 |
doFilterInternal in
You want your database interactions to be happening in a transactional context. One simple piece of that is you can mark your service class with #grails.gorm.transactions.Transactional.
Separate from that, and this isn't really related to your question, but passing GrailsParameterMap map around as a method argument is an unusual thing to do. What the right thing to do is depends on some factors in your app and you may want to pass values into your service rather than the whole map but if you really want the whole map in the service, one way to get there is by way of WebAttributes.
import grails.gorm.transactions.Transactional
import grails.web.api.WebAttributes
#Transactional
class MemberService implements WebAttributes {
def serviceMethod() {
// you can access params here because
// WebAttributes provides access to it
Member member = new Member(params)
// ...
}
}

How can I update User's details in grails with spring security before login With Remember Me Check?

I am using grails where authetication is done by Spring Security.I need to unlock User's account before login
#Transactional(readOnly=true, noRollbackFor=[IllegalArgumentException, UsernameNotFoundException])
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = User.findByUsername(username)
// Check and unlock account if 24 Hrs has been passed
userService.checkAndUnlockAccountAfter24Hrs(user.id);
if (!user) throw new NoStackUsernameNotFoundException()
def roles = user.authorities
// or if you are using role groups:
// def roles = user.authorities.collect { it.authorities }.flatten().unique()
def authorities = roles.collect {
new SimpleGrantedAuthority(it.authority)
}
return new MyUserDetails(user.username, user.password, user.enabled,
!user.accountExpired, !user.passwordExpired,
!user.accountLocked, authorities ?: NO_ROLES, user.id,
user.name)
}
Now when I do login with Remember Me check, Then It shows error:
-
| Error 2017-04-18 12:24:40,426 [http-bio-8080-exec-3] ERROR
[/].[default] - Servlet.service() for servlet [default] in context
with path [] threw exception
Message: retrieveUser returned null - a violation of the interface contract
Line | Method
->> 76 | attemptAuthentication in grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 49 | doFilter in ''
| 82 | doFilter . . . . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 100 | doFilter in com.brandseye.cors.CorsFilter
| 1145 | runWorker . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . . . . in java.lang.Thread
You have three options:
Comment out that code in boostrap in every run; except first time.
Drop database and create database for every single run
Hacky way:
Use condition(ternary operator) like this:
def adminRole = Role.findByAuthority('ROLE_ADMIN') ? : new Role(authority: 'ROLE_ADMIN').save(flush: true)
def userRole = Role.findByAuthority('ROLE_USER') ? : new Role(authority: 'ROLE_USER').save(flush: true)
def adminUser = User.findByUsername('admin') ? : new User(username: 'admin', password: 'admin', enabled: true).save(flush: true)
def user = User.findByUsername('user') ? : new User(username: 'user', password: 'user', enabled: true).save(flush: true)
if (!adminUser.authorities.contains('ROLE_ADMIN')) {
UserRole.create(adminUser, adminRole)
}
if (!user.authorities.contains('ROLE_USER')) {
UserRole.create(user, userRole)
}

RabbitMQ Messaging with QPID 0.32 client

Using QPID Java Client i can only get messages delivered through the exchange to the bound queue using the following expanded syntax of AMQAnyDestination
Destination queue = new AMQAnyDestination( new AMQShortString("onms2"),
new AMQShortString("direct"),
new AMQShortString("Simon"),
true,
true,
new AMQShortString(""),
false,
bindvars);
If i attempt to use the different form which just specifies the address as follows it doesnt work:-
Destination queue = new AMQAnyDestination("onms2/Simon");
The message hits RabbitMQ ok but is not delivered.
Qpid 0.32 Client
Rabbit MQ 3.5.7
Exchange onms
Routing Key Simon
I have been using the qpid examples and modifying the ListSender example as below
package org.apache.qpid.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.qpid.client.AMQAnyDestination;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.jms.ListMessage;
public class ListSender {
public static void main(String[] args) throws Exception
{
Connection connection =
new AMQConnection("amqp://simon:simon#localhost/test?brokerlist='tcp://localhost:5672'");
AMQShortString a1 = new AMQShortString("");
AMQShortString a2 = new AMQShortString("");
AMQShortString[] bindvars = new AMQShortString[]{a1,a2};
boolean is_durable = true;
/*
Destination queue = new AMQAnyDestination( new AMQShortString("onms2"),
new AMQShortString("direct"),
new AMQShortString("Simon"),
true,
true,
new AMQShortString(""),
false,
bindvars);
*/
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination queue = new AMQAnyDestination("onms2/Simon");
//Destination queue = new AMQAnyDestination("amqp:OpenNMSExchange/Taylor; {create: always}");
//Destination queue = new AMQAnyDestination("OpenNMSExchange; {create: always}");
MessageProducer producer = session.createProducer(queue);
ListMessage m = ((org.apache.qpid.jms.Session)session).createListMessage();
m.setIntProperty("Id", 987654321);
m.setStringProperty("name", "WidgetSimon");
m.setDoubleProperty("price", 0.99);
List<String> colors = new ArrayList<String>();
colors.add("red");
colors.add("green");
colors.add("white");
m.add(colors);
Map<String,Double> dimensions = new HashMap<String,Double>();
dimensions.put("length",10.2);
dimensions.put("width",5.1);
dimensions.put("depth",2.0);
m.add(dimensions);
List<List<Integer>> parts = new ArrayList<List<Integer>>();
parts.add(Arrays.asList(new Integer[] {1,2,5}));
parts.add(Arrays.asList(new Integer[] {8,2,5}));
m.add(parts);
Map<String,Object> specs = new HashMap<String,Object>();
specs.put("colours", colors);
specs.put("dimensions", dimensions);
specs.put("parts", parts);
m.add(specs);
producer.send((Message)m);
System.out.println("Sent: " + m);
connection.close();
}
}
When it works using the expanded format of AMQAnyDestination the debug logs looks like this:-
163 [main] INFO org.apache.qpid.client.AMQConnection - Connection 1 now connected from /127.0.0.1:43298 to localhost/127.0.0.1:5672
163 [main] DEBUG org.apache.qpid.client.AMQConnection - Are we connected:true
163 [main] DEBUG org.apache.qpid.client.AMQConnection - Connected with ProtocolHandler Version:0-91
166 [main] DEBUG org.apache.qpid.client.AMQDestination - Based on direct://onms2/Simon/?routingkey='Simon'&exclusive='true'&autodelete='true' the selected destination syntax is BURL
169 [main] DEBUG org.apache.qpid.client.AMQConnectionDelegate_8_0 - Write channel open frame for channel id 1
184 [main] DEBUG org.apache.qpid.client.AMQSession - Created session:org.apache.qpid.client.AMQSession_0_8#1d251891
186 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.apache.qpid.client.protocol.AMQProtocolHandler - (1028176102)Method frame received: [ChannelOpenOkBody]
189 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.apache.qpid.client.protocol.AMQProtocolHandler - (1028176102)Method frame received: [BasicQosOkBodyImpl: ]
195 [main] DEBUG org.apache.qpid.client.BasicMessageProducer_0_8 - MessageProducer org.apache.qpid.client.BasicMessageProducer_0_8#668bc3d5 using publish mode : ASYNC_PUBLISH_ALL
206 [main] DEBUG org.apache.qpid.client.BasicMessageProducer_0_8 - Sending content body frames to direct://onms2/Simon/?routingkey='Simon'&exclusive='true'&autodelete='true'
206 [main] DEBUG org.apache.qpid.client.BasicMessageProducer_0_8 - Sending content header frame to direct://onms2/Simon/?routingkey='Simon'&exclusive='true'&autodelete='true'
207 [main] DEBUG org.apache.qpid.framing.FieldTable - FieldTable::writeToBuffer: Writing encoded length of 67...
When it fails using the shorter syntax the debug log looks like this:-
149 [main] INFO org.apache.qpid.client.AMQConnection - Connection 1 now connected from /127.0.0.1:36940 to localhost/127.0.0.1:5672
149 [main] DEBUG org.apache.qpid.client.AMQConnection - Are we connected:true
149 [main] DEBUG org.apache.qpid.client.AMQConnection - Connected with ProtocolHandler Version:0-91
153 [main] DEBUG org.apache.qpid.client.AMQConnectionDelegate_8_0 - Write channel open frame for channel id 1
169 [main] DEBUG org.apache.qpid.client.AMQSession - Created session:org.apache.qpid.client.AMQSession_0_8#6bdf28bb
170 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.apache.qpid.client.protocol.AMQProtocolHandler - (472294496)Method frame received: [ChannelOpenOkBody]
171 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.apache.qpid.client.protocol.AMQProtocolHandler - (472294496)Method frame received: [BasicQosOkBodyImpl: ]
179 [main] DEBUG org.apache.qpid.client.AMQDestination - Based on onms2/Simon the selected destination syntax is ADDR
182 [main] DEBUG org.apache.qpid.client.AMQConnectionDelegate_8_0 - supportsIsBound: false
182 [main] DEBUG org.apache.qpid.client.AMQConnectionDelegate_8_0 - supportsIsBound: false
182 [main] DEBUG org.apache.qpid.client.AMQConnectionDelegate_8_0 - supportsIsBound: false
184 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.apache.qpid.client.protocol.AMQProtocolHandler - (472294496)Method frame received: [ExchangeDeclareOkBodyImpl: ]
184 [main] DEBUG org.apache.qpid.client.BasicMessageProducer_0_8 - MessageProducer org.apache.qpid.client.BasicMessageProducer_0_8#15975490 using publish mode : ASYNC_PUBLISH_ALL
195 [main] DEBUG org.apache.qpid.client.BasicMessageProducer_0_8 - Sending content body frames to 'onms2'/'Simon'; None
195 [main] DEBUG org.apache.qpid.client.BasicMessageProducer_0_8 - Sending content header frame to 'onms2'/'Simon'; None
196 [main] DEBUG org.apache.qpid.framing.FieldTable - FieldTable::writeToBuffer: Writing encoded length of 90...
196 [main] DEBUG org.apache.qpid.framing.FieldTable - {Id=[INT: 987654321], name=[LONG_STRING: WidgetSimon], price=[DOUBLE: 0.99], qpid.subject=[LONG_STRING: Simon], JMS_QPID_DESTTYPE=[INT: 2]}
198 [main] DEBUG org.apache.qpid.client.AMQSession - Closing session: org.apache.qpid.client.AMQSession_0_8#6bdf28bb
198 [main] DEBUG org.apache.qpid.client.protocol.AMQProtocolSession - closeSession called on protocol session for session 1
Ideally i need the shorter syntax to work as this is what is used by another application I am using which is posting messages using AMQP.
I suspect there is something incorrect with the syntax i am using to define the address but i cant see what it is.
I have tried:-
amqp:onms2/Simon
ADDR:onms2/Simon
I have confirmed the rabbit config is correct by testing using both a standalone java client using qpid and also using both perl (using net_amqp) and python (using pika). So i dont think its that.
Any gudiance appreciated.
EDIT:-
Found some extra configuration parameters on the QPID website i had missed
When i configure the address as follows it works!
onms3/Simon; {'create':'always','node':{'type':'topic'} }
Detail
<name> [ / <subject> ] ; {
create: always | sender | receiver | never,
delete: always | sender | receiver | never,
assert: always | sender | receiver | never,
mode: browse | consume,
node: {
type: queue | topic,
durable: True | False,
x-declare: { ... <declare-overrides> ... },
x-bindings: [<binding_1>, ... <binding_n>]
},
link: {
name: <link-name>,
durable: True | False,
reliability: unreliable | at-most-once | at-least-once | exactly-once,
x-declare: { ... <declare-overrides> ... },
x-bindings: [<binding_1>, ... <binding_n>],
x-subscribe: { ... <subscribe-overrides> ... }
}
}
Simon
EDIT:-
Found some extra configuration parameters on the QPID website i had missed
When i configure the address as follows it works!
onms3/Simon; {'create':'always','node':{'type':'topic'} }
Detail
<name> [ / <subject> ] ; {
create: always | sender | receiver | never,
delete: always | sender | receiver | never,
assert: always | sender | receiver | never,
mode: browse | consume,
node: {
type: queue | topic,
durable: True | False,
x-declare: { ... <declare-overrides> ... },
x-bindings: [<binding_1>, ... <binding_n>]
},
link: {
name: <link-name>,
durable: True | False,
reliability: unreliable | at-most-once | at-least-once | exactly-once,
x-declare: { ... <declare-overrides> ... },
x-bindings: [<binding_1>, ... <binding_n>],
x-subscribe: { ... <subscribe-overrides> ... }
}
}

Grails - Hibernate - cannot create model class / table

i have Grails(2.2.1) project and want to with Hibernate create simple "model" class
#Entity
#Table(name="User")
class User {
static mapping = {
datasource 'system'
}
#Id
#GeneratedValue
#Column(name="id")
private Long userId;
#Column(name="email", nullable=false)
private String email;
public User(){
}
#Transient
public Long getUserId(){
return this.userId;
}
#Transient
public String getEmail(){
return this.email;
}
}
but i getting this follow error :
Caused by MappingException: Could not determine type for: org.springframework.validation.Errors, at table: user, for columns: [org.hibernate.mapping.Column(errors)]
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
When i remove all hibernate annotations, app is deployed on server but table User has only two attributes (id, version).
Thank you for your help !
Move your domain class to grails-app/domain and change it to this:
class User {
String email
static mapping = {
datasource 'system'
}
static constraints = {
email nullable: false
}
}
11 lines vs. 31 lines. Groovy.

Json as parameter to Grails controller

I am trying to pass a Json array to a Grails controller and then to a Java class. I can't figure out how to properly pass my params to the Java class though. Here is the relavent code.
AJAX POST:
$('#matrixForm').submit(function(e) {
e.preventDefault();
var matrixArray = $(this).serializeArray();
$.ajax({
type: "POST",
data: matrixArray,
url: "/turingpages/factorize/create",
success: function(data) {
//USE DATA
}
});
});
Grails Controller:
...
def create() {
MatrixFactorization m = new MatrixFactorization(params)
Gson gson = new Gson()
def jsonMatrix = gson.toJson(m.answer)
render jsonMatrix
}
...
MatrixFactorization Constructor:
public MatrixFactorization(JsonElement jsonarray) {
BlockRealMatrix R = GsonMatrix.toMatrix(jsonarray);
this.run(R);
}
My console shows my Json array as:
[{name:"00", value:"1"}, {name:"01", value:"2"}, {name:"02", value:"3"}, {name:"10", value:"4"}, {name:"11", value:"0"}, {name:"12", value:"4"}, {name:"20", value:"0"}, {name:"21", value:"4"}, {name:"22", value:"2"}]
My stack trace is:
| Error 2013-01-18 00:30:23,792 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver - GroovyRuntimeException occurred when processing request: [POST] /turingpages/factorize/create - parameters:
21: 4
20: 0
10: 4
22: 2
00: 1
01: 2
11: 0
02: 3
12: 4
failed to invoke constructor: public matrices.MatrixFactorization(com.google.gson.JsonElement) with arguments: [] reason: java.lang.IllegalArgumentException: wrong number of arguments. Stacktrace follows:
Message: failed to invoke constructor: public matrices.MatrixFactorization(com.google.gson.JsonElement) with arguments: [] reason: java.lang.IllegalArgumentException: wrong number of arguments
Line | Method
->> 15 | create in turingpages.rest.MFController$$ENuqtska
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
I am very new to using JSON. Any help is appreciated. Thanks.
1.
jQuery will pass this data as request parameters, not JSON, by default. So you should build a JSON string to pass to jQuery. I can recommend you JSON 3 library. At this case it going to be:
$.ajax({
type: "POST",
data: JSON.stringify(matrixArray),
url: "/turingpages/factorize/create",
success: function(data) {
//USE DATA
}
});
2.
On server side you could also use standard Grails JSON converter (but you could use Gson, if you prefer), see http://grails.org/Converters+Reference.
At this case you can use
def create() {
MatrixFactorization m = new MatrixFactorization(request.JSON)
render m.answer as JSON
}

Categories

Resources