Problem with grails web app running in production: "No such property: save for class: JsecRole" - sql-server

I've got a grails 1.1 web app running great in development but when I try and run it in production with
an sqlserver database it crashes in a weird way.
The relevant part of my datasource.groovy is as follows:
environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
url = "jdbc:hsqldb:mem:devDB"
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
endUsername = "sa"
password = "pw4db"
url = "jdbc:sqlserver://localhost:1433;databaseName=ReleasePlanner;selectMethod=cursor"
The error message I receive is:
Message: No such property: save for class: JsecRole
Caused by: groovy.lang.MissingPropertyException: No such property: save for class: JsecRole
Class: ProjectController
At Line: [28]
Code Snippet:
27: println "###about to create project roles"
28: userManagerService.createProjectRoles(project)
29: userManagerService.addUserToProject(session.user.id.toString(), project, 'owner')
}
}
}
The stacktrace is as follows:
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingPropertyException: No such property: save for class: JsecRole
at org.jsecurity.web.servlet.JSecurityFilter.doFilterInternal(JSecurityFilter.java:382)
at org.jsecurity.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:180)
Caused by: groovy.lang.MissingPropertyException: No such property: save for class: JsecRole
at UserManagerService.createProjectRoles(UserManagerService.groovy:9)
at UserManagerService$$FastClassByCGLIB$$6fa73713.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
at UserManagerService$$EnhancerByCGLIB$$fcf60984.createProjectRoles(<generated>)
at UserManagerService$createProjectRoles.call(Unknown Source)
at ProjectController$_closure4.doCall(ProjectController.groovy:28)
at ProjectController$_closure4.doCall(ProjectController.groovy)
... 2 more
Any help is appreciated.
Thanks
Sarah

I fixed my problem by deleting my database and creating a new database. I think some of the fields in my database weren't mapping correctly as I changed my domain objects. The error didn't really point me in this direction though!
Sarah

This problem is discussed in this thread on the Grails mailing list. It is supposed to be fixed in Grails 1.2. A workaround for earlier versions of Grails is to add the following to Bootstrap.groovy
JsecRole.get(-1)

Related

Phpstan doctrine database connection error

I'm using doctrine in a project (not symfony). In this project I also use phpstan, i installed both phpstan/phpstan-doctrine and phpstan/extension-installer.
My phpstan.neon is like this:
parameters:
level: 8
paths:
- src/
doctrine:
objectManagerLoader: tests/object-manager.php
Inside tests/object-manager.php it return the result of a call to a function that return the entity manager.
Here is the code that create the entity manager
$database_url = $_ENV['DATABASE_URL'];
$isDevMode = $this->isDevMode();
$proxyDir = null;
$cache = null;
$useSimpleAnnotationReader = false;
$config = Setup::createAnnotationMetadataConfiguration(
[$this->getProjectDirectory() . '/src'],
$isDevMode,
$proxyDir,
$cache,
$useSimpleAnnotationReader
);
// database configuration parameters
$conn = [
'url' => $database_url,
];
// obtaining the entity manager
$entityManager = EntityManager::create($conn, $config);
When i run vendor/bin/phpstan analyze i get this error:
Internal error: An exception occurred in the driver: SQLSTATE[08006] [7] could not translate host name "postgres_db" to address: nodename nor servname provided, or not known
This appear because i'm using docker and my database url is postgres://user:password#postgres_db/database postgres_db is the name of my database container so the hostname is known inside the docker container.
When i run phpstan inside the container i do not have the error.
So is there a way to run phpstan outside docker ? Because i'm pretty sure that when i'll push my code the github workflow will fail because of this
Do phpstan need to try to reach the database ?
I opened an issue on the github of phpstan-doctrine and i had an answer by #jlherren that explained :
The problem is that Doctrine needs to know what version of the DB server it is working with in order to instantiate the correct AbstractPlatform implementation, of which there are several available for the same DB vendor (e.g. PostgreSQL94Platform or PostgreSQL100Platform for postgres, and similarly for other DB drivers). To auto-detect this information, it will simply connect to the DB and query the version.
I just changed my database url from:
DATABASE_URL=postgres://user:password#database_ip/database
To:
DATABASE_URL=postgres://user:password#database_ip/database?serverVersion=14.2

grails javax.servlet.ServletException: Could not resolve view with name '/index' in servlet with name 'grailsDispatcherServlet'

i'm trying to run my app using this tutorial :
http://guides.grails.org/building-a-react-app/guide/index.html
there is the the git repository
https://github.com/tetar998/building-a-react-app/tree/master/complete
but i m stuck with this error
Could not resolve view with name '/index' in servlet with name 'grailsDispatcherServlet'
i am currently working with
- groovy 2.4.11
- java 8u152
- grails 3.3.0
and in there is my controller/demo/urlmappings
package demo
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/"(view: '/index')
"500"(view: '/error')
"404"(view: '/notFound')
}
}
Any suggestion?

No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available

In Java project, I am using Sprig Boot 1.5.3.RELEASE. It is connecting with two databases i.e. MongoDB and Microsoft SQLServer. When I run it with spring-boot:run goal, it works fine. However, when I try to run it with package goal then below error is reported by test cases despite the fact that those test cases are not connecting to SQL Server database:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
.....
.....
MediationTest.java (Java class containing test cases generating above error)
#RunWith(SpringRunner.class)
#DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
#SpringBootTest(classes = { Application.class })
public class MediationTest {
#Autowired
private SwiftFormat swiftFormat;
......................
......................
MsqlDbConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "msqlEntityManagerFactory", transactionManagerRef = "msqlTransactionManager", basePackages = { "com.msql.data" })
public class MsqlDbConfig {
#Bean(name = "msqlDataSource")
#ConfigurationProperties(prefix = "msql.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "msqlEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean msqlEntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("msqlDataSource") DataSource dataSource) {
return builder.dataSource(dataSource)
.packages("com.utils.msql.info")
.persistenceUnit("msql").build();
}
#Bean(name = "msqlTransactionManager")
public PlatformTransactionManager msqlTransactionManager(
#Qualifier("msqlEntityManagerFactory") EntityManagerFactory msqlEntityManagerFactory) {
return new JpaTransactionManager(msqlEntityManagerFactory);
}
}
application.properties
spring.data.mongodb.uri=mongodb://dev-abc-123:27017/db
msql.datasource.url=jdbc:sqlserver://ABC-SQL14-WXX;databaseName=dev
msql.datasource.username=dev
msql.datasource.password=*****
msql.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
msql.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
spring.jpa.show-sql=true
The spring-boot:run goal is defined by the Mojo included within the spring-boot-maven-plugin project. You can find it here. https://github.com/spring-projects/spring-boot/blob/8e3baf3130220a331d540cb07e1aca263b721b38/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java.
The requiresDependencyResolution scope is set to Test. This will include the dependencies from each phase on the classpath. Take a look at the specification here. https://maven.apache.org/developers/mojo-api-specification.html
The package goal provided by Maven wouldn't include these additional dependencies on the classpath and I believe that is the cause of your issues.
Spring Boot provides a repackage goal which is what should be used for building out executable spring-boot applications.
However, to get more to the point. I think if you update your test to exclude an additional class it might fix your problem.
#DataMongoTest(excludeAutoConfiguration = {EmbeddedMongoAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

Database name containd dot in jdbc url spring boot

Dear all I am in the unfortunate sitution to connect to an sqlserver 2005 databae that was provided to me and contains o dot (.)
I have setup a configuration for spring boot like
#Configuration
public class CustomConfig {
#Bean
#Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("myuname")
.password("mypass")
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName=REALLY_BAD_NAME_V3.5;")
.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.build();
}
}
And of course I get an exception stating com.microsoft.sqlserver.jdbc.SQLServerException: Database '5' does not exist. Make sure that the name is entered correctly.
I have tried in vain the following
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName={REALLY_BAD_NAME_V3.5};")
that gives the same error and
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName=REALLY_BAD_NAME_V3{.}5;")
And gives a malformed url exception after reading these instructions.
Any ideas?

No suitable driver found for jdbc:sqlserver

I realize this is what would be considered a duplicate topic, but I have followed the recommended steps in the other topics of this same nature with no success.
I am using GGTS 3.6.4 with
Grails 2.3.0
jdk1.7.0_80
Groovy compiler level 2.3
Microsoft SQL Server 2012
I have a grails-app which authenticates users logging in against an LDAP server with Apache Shiro and I have the following code (in the Shiro generated AuthController.groovy) to try and store some information from an external database in the session. (Note: With regards to usernames, passwords, and database names, I've changed all of them here for privacy reasons)
def signIn = {
Subject subject = SecurityUtils.getSubject();
String lowerCaseUserName=params.username.toLowerCase();
def authToken = new UsernamePasswordToken(lowerCaseUserName, params.password)
// Support for "remember me"
if (params.rememberMe) {
authToken.rememberMe = true
}
try{
subject.login(authToken)
if (subject.isAuthenticated())
{
session.username = lowerCaseUserName
// Attempting to get employee id from MS SQL
Sql Database = Sql.newInstance(
'jdbc:sqlserver://myserver;DatabaseName=mydatabase',
'user',
'password',
'com.microsoft.sqlserver.jdbc.SQLServerDriver'
);
Database.eachRow('select empid from table_name where username=${session.username}') { row ->
session.empid = row.empid
}
Database.close();
def targetUri = params.targetUri ?: "/home"
log.info "Redirecting to '${targetUri}'."
redirect(uri: targetUri)
}
}
...
}
However, I get the following error
SQLException occurred when processing request: [POST] /app/auth/signIn - parameters:
username: user
_rememberMe:
targetUri:
password: ***
No suitable driver found for jdbc:sqlserver://myserver;DatabaseName=mydatabase. Stacktrace follows:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://myserver;DatabaseName=mydatabase
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at app.AuthController$_closure3.doCall(AuthController.groovy:45)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I have tried the following with no success:
Added sqljdbc4.jar to /app/lib/
Manually added /app/lib/ to classpath (via .classpath)
Added sqljdbc4.jar to the classpath via the Properties > Java Build Path > Add JARs
I've tried these variations with sqljdbc4.jar, sqljdbc.jar, and sqlserverjdbc.jar and every combo thereof.
I'm basically stuck. None of the fixes I've read on here, or elsewhere, solve my error. Any help would be greatly appreciated!
Edit 1: Adding Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") above the newInstance call produces the following errors:
ClassNotFoundException occurred when processing request: [POST] /app/auth/signIn - parameters:
username: user
_rememberMe:
targetUri:
password: ***
com.microsoft.sqlserver.jdbc.SQLServerDriver. Stacktrace follows:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName(Class.java:195)
at isec.AuthController$_closure3.doCall(AuthController.groovy:45)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Is this a step forward, backward, or are we running in place?
Edit 2: What I ended up having to do was change my DataSource.groovy to this
dataSource {
pooled = true
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
//cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "validate"
url = "jdbc:sqlserver://myserver:1433;databaseName=mydatabase;"
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
username = "myusername"
password = "mypassword"
}
}
....
}
and changed my AuthController.groovy data access to
try{
subject.login(authToken)
if (subject.isAuthenticated())
{
ShiroUser currentUser = new ShiroUser()
def targetUri = params.targetUri ?: "/home"
log.info "Redirecting to '${targetUri}'."
redirect(uri: targetUri)
}
}
and I have successfully accessed my DB with a modified ShiroUser.groovy file
class ShiroUser {
static hasMany = [ roles: ShiroRole, permissions: String ]
User_Data userData;
static constraints = {
}
def getUsername() {
return userData.username
}
}
where User_Data.groovy is a new domain class containing
class User_Data {
static mapping = {
table "mytablename"
}
...
}
So now I'm onto messing with methods! Not sure why JDBC stuff didn't work out, but GORM is the path I'm taking now.
you definitely need to add sqljdbc4.jar to /app/lib/ which you have already done.
have you tried adding database connection to the BuildConfig.groovy
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
dialect = "org.hibernate.dialect.SQLServerDialect"
url = "jdbc:sqlserver://localhost:1433;databaseName=dbName"
username = "sa"
password = ""
}
Also make sure the SQL server is configured to accept connection on port 1433. It is disabled by default.

Resources