What are the current dependencies for a standalone GORM script? - grails

I am trying to following Graeme Rocher's example from Github:
https://gist.github.com/graemerocher/c25ec929d9bcd1adcbea
#Grab("org.grails:grails-datastore-gorm-hibernate4:3.0.0.RELEASE")
#Grab("org.grails:grails-spring:2.3.6")
#Grab("com.h2database:h2:1.3.164")
import grails.orm.bootstrap.*
import grails.persistence.*
import org.springframework.jdbc.datasource.DriverManagerDataSource
import org.h2.Driver
init = new HibernateDatastoreSpringInitializer(Person)
def dataSource = new DriverManagerDataSource(Driver.name, "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE", 'sa', '')
init.configureForDataSource(dataSource)
new Person(name: "Fred Flintstone").save(flush: true, failOnError: true)
println "Total people = ${Person.count()}"
#Entity
class Person {
String name
static constraints = {
name blank:false
}
}
I am getting
java.lang.RuntimeException: Error grabbing Grapes -- [download failed: >com.googlecode.concurrentlinkedhashmap#concurrentlinkedhashmap->lru;1.3.1!concurrentlinkedhashmap-lru.jar, download failed: >javax.transaction#jta;1.1!jta.jar, download failed: org.jboss.logging#jboss->logging;3.1.3.GA!jboss-logging.jar, download failed: org.javassist#javassist;3.18.1->GA!javassist.jar(bundle)]
I presume that this means that some set of dependencies has changed/gone away.
Is there a current working version of this code?

I had already tried using #GrabResolver() with various URLs (should have said, apologies).
I tried Jeff Beck's answer but to no avail.
I went through a bit of a debugging cycle by setting a few debug flags to see what was going on (-Dgroovy.grape.report.downloads=true -Divy.message.logger.level=4).
Eventually I had to create a custom ~/.groovy/grapeConfig.xml (as per http://groovy.codehaus.org/Grape#Grape-CustomizeIvysettings) and added the mavencentral URL Jeff gave as a further 'ibiblio' entry.
THEN all was fine.
Don't know why #GrabResolver() isn't resolving but this is a workaround.

I got the following to work fine:
#GrabResolver(name='mvncentral', root='http://central.maven.org/maven2/')
#Grab("org.grails:grails-datastore-gorm-hibernate4:3.1.1.RELEASE")
#Grab("org.grails:grails-spring:2.4.3")
#Grab("com.h2database:h2:1.3.164")
import grails.orm.bootstrap.*
import grails.persistence.*
import org.springframework.jdbc.datasource.DriverManagerDataSource
import org.h2.Driver
init = new HibernateDatastoreSpringInitializer(Person)
def dataSource = new DriverManagerDataSource(Driver.name, "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE", 'sa', '')
init.configureForDataSource(dataSource)
println "Total people = " + Person.count()
#Entity
class Person {
String name
static constraints = {
name blank:false
}
}
I added a different resolver from the default jcenter that is in the latest version of groovy. Also you may need to clear cached versions of what was tried to download. Here is a blog post about that.

Related

How to Reference A Jenkins Global Shared Library

After reviewing the docs, a number of questions here on SO, and trying a dozen or so different script configurations, I cannot figure out how to reference a shared Groovy library. I've added the library like so:
This appears to be working. I'm referencing the script like so:
You can see the error message therein:
Script1: 1: unable to resolve class Library , unable to find class
for annotation # line 1, column 1. #Library('sonarQubeAPI')_
The script code, not I think it matters, looks like this:
import groovy.json.JsonSlurper
class SonarQubeAPI{
static string getVersion(){
return "1.0";
}
static void getSonarStatus(projectKey){
def sonarQubeUserToken = "USERTOKEN";
def projectStatusUrl = "pathtosonarqube/api/qualitygates/project_status?projectKey=" + projectKey;
println("Retrieving project status for " + projectKey);
def json = getJson(sonarQubeUserToken, projectStatusUrl);
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(json);
println(object.projectStatus.status);
}
static string getJson(userToken, url){
def authString = "${userToken}:".getBytes().encodeBase64().toString();
def conn = url.toURL().openConnection();
conn.setRequestProperty( "Authorization", "Basic ${authString}" );
return conn.content.text;
}
}
I'm probably just a magic character off, but I can't seem to lock it down.
Shared libraries are a feature of Jenkins Pipelines, not of Jenkins (core) itself. You can use them only in Pipeline jobs (and child types like Multibranch Pipeline).

Jenkins: Configure ActiveDirectorySecurityRealm Plugin using Groovy

I'm currently spending some time setting up a generic configuration using Jenkins AD-SecurityRealm (ActiveDirectorySecurityRealm) Plugin (v2.6) and stuck over a nasty issue: It seems that my approach to (auto) set up a valid AD-connection (following the corresponding documentation) is not working at all. Every time I'll re-init my Jenkins instance an incomplete config.xml will provide - the "bindName" property (XML-node) is always missing. This property is required by the ad-server I'll use and so I've to override the config manually to solve this issue.
I haven't the vaguest idea why this still happens.
my groovy code (excerpt)
String _domain = 'my-primary-ad-server-running.acme.org'
String _site = 'jenkins.acme.org'
String _bindName = 'ad-bind-user'
String _bindPassword = 'ad-bind-password-super-secret-123'
String _server = 'my-primary-ad-server-running.acme.org'
def hudsonActiveDirectoryRealm = new ActiveDirectorySecurityRealm(_domain, _site, _bindName, _bindPassword, _server)
def instance = Jenkins.getInstance()
instance.setSecurityRealm(hudsonActiveDirectoryRealm)
instance.save()
my config.xml result (excerpt)
<securityRealm class="hudson.plugins.active_directory.ActiveDirectorySecurityRealm" plugin="active-directory#2.6">
<domains>
<hudson.plugins.active__directory.ActiveDirectoryDomain>
<name>my-primary-ad-server-running.acme.org</name>
<servers>my-primary-ad-server-running.acme.org:3268</servers>
<bindPassword>{###-fancy-crypted-super-password-nobody-can-decrypt-anymore-###}</bindPassword>
</hudson.plugins.active__directory.ActiveDirectoryDomain>
</domains>
<startTls>true</startTls>
<groupLookupStrategy>AUTO</groupLookupStrategy>
<removeIrrelevantGroups>false</removeIrrelevantGroups>
<tlsConfiguration>TRUST_ALL_CERTIFICATES</tlsConfiguration>
</securityRealm>
my config.xml required (excerpt)
<securityRealm class="hudson.plugins.active_directory.ActiveDirectorySecurityRealm" plugin="active-directory#2.6">
<domains>
<hudson.plugins.active__directory.ActiveDirectoryDomain>
<name>my-primary-ad-server-running.acme.org</name>
<servers>my-primary-ad-server-running.acme.org:3268</servers>
<bindName>ad-bind-user</bindName>
<bindPassword>{###-fancy-crypted-super-password-nobody-can-decrypt-anymore-###}</bindPassword>
</hudson.plugins.active__directory.ActiveDirectoryDomain>
</domains>
<startTls>true</startTls>
<groupLookupStrategy>AUTO</groupLookupStrategy>
<removeIrrelevantGroups>false</removeIrrelevantGroups>
<tlsConfiguration>TRUST_ALL_CERTIFICATES</tlsConfiguration>
</securityRealm>
Thanks #kosta.
Following script also works using active-directory 2.10 and jenkins 2.150.1
This also include site information.
import hudson.plugins.active_directory.ActiveDirectoryDomain
import hudson.plugins.active_directory.ActiveDirectorySecurityRealm
import hudson.plugins.active_directory.GroupLookupStrategy
String _domain = 'dev.test.com'
String _site = 'HQ'
String _bindName = 'dev\jenkins'
String _bindPassword = 'test'
String _server = 'dev.test.com:2328'
def hudsonActiveDirectoryRealm = new ActiveDirectorySecurityRealm(_domain, _site, _bindName, _bindPassword, _server)
hudsonActiveDirectoryRealm.getDomains().each({
it.bindName = hudsonActiveDirectoryRealm.bindName
it.bindPassword = hudsonActiveDirectoryRealm.bindPassword
it.site = hudsonActiveDirectoryRealm.site
})
def instance = Jenkins.getInstance()
instance.setSecurityRealm(hudsonActiveDirectoryRealm)
instance.save()
Check this screenshot: Configure Global Security
If you look at the source code for ActiveDirectorySecurityRealm you will see that the bindName is marked as transient, thus it won't be persisted as part of the config XML.
The only solution to get the desired config.xml is to force the config.xml by providing a custom static one and not use the init script.
I was able to solve this issue by adding the following code at the end (Tested on 2.6 and 2.8). You also need to make sure that your credentials are valid because the plugin is doing an initial connectivity check https://issues.jenkins-ci.org/browse/JENKINS-48513
hudsonActiveDirectoryRealm.getDomains().each({
it.bindName = hudsonActiveDirectoryRealm.bindName
it.bindPassword = hudsonActiveDirectoryRealm.bindPassword
})
instance.setSecurityRealm(hudsonActiveDirectoryRealm)
instance.save()

Jira custom script validator: check if input textbox exists

I am totally new to Jira. In fact I don't even know where to start. I went to the jira atlassian website but got nothing solid enough to help me. I would like to validate if the information entered into a textbox already exists. I clicked around jira and ended up on the screen below:
Now I would like to find out the following:
Which programming language should be used for validation ? Is it Java
If the name of the custom field(of type Textbox) is XYZ and I wanna if check if value entered into XYZ already exist, how do I go about doing that ? Can I just write conditional statements in Java ?
I wrote some stuff and nothing worked.
That's a screenshot from the Script Runner add-on.
There are some documentation and examples for custom validators here.
You can also find an example here that shows how to query the JIRA (or an external) database from a groovy script. Ie.:
import com.atlassian.jira.component.ComponentAccessor
import groovy.sql.Sql
import org.ofbiz.core.entity.ConnectionFactory
import org.ofbiz.core.entity.DelegatorInterface
import java.sql.Connection
def delegator = (DelegatorInterface) ComponentAccessor.getComponent(DelegatorInterface)
String helperName = delegator.getGroupHelperName("default");
def sqlStmt = """
SELECT project.pname, COUNT(*) AS kount
FROM project
INNER JOIN jiraissue ON project.ID = jiraissue.PROJECT
GROUP BY project.pname
ORDER BY kount DESC
"""
Connection conn = ConnectionFactory.getConnection(helperName);
Sql sql = new Sql(conn)
try {
StringBuffer sb = new StringBuffer()
sql.eachRow(sqlStmt) {
sb << "${it.pname}\t${it.kount}\n"
}
log.debug sb.toString()
}
finally {
sql.close()
}
For anything that gets a bit complex it's easier to implement your script in a groovy file and make it available to Script Runner via the file system. That also allows you use a vcs like git to easily push/pull your changes. More info about how to go about that, is here.

Access sub-project application properties in grails/groovy

I have a singleton class
#Singleton
class CustomerBundleSingleton {
def grailsApplication = Holders.getGrailsApplication()
String projName
private CustomerBundleSingleton() {
line 10: projName = // how to get sub-project name here ???
}
}
application.properties // my project is running
-----------------------
app.name = MyNewProject
application.properties // located in sub project
-----------------------
app.name = MySubProject
I tried grailsApplication.metadata['app.name'] in "line 10:" it returns "MyNewProject".Whereas I want a way to get the project name of the UserBundleSingleton located (MySubProjectName). Something like grailsApplication.current.metadata['app.name'] ???? .
So that it can give me back MySubProjectName instead of MyNewProject??
I have 3 suggestions depending on your requirements and your 'bundling'.
1) You don't have a bundle marker/descriptor
Assuming that you know the sub-project(Grails plugin) name, your life gets easier, instead of having to loop through all plugins...
You can probably use something among these lines.
// Plugin name is 'hibernate' in this example
import org.codehaus.groovy.grails.plugins.PluginManagerHolder
def hibernateVersion = PluginManagerHolder.pluginManager.getGrailsPlugin('hibernate').version
// Loop through all plugins
// PluginManagerHolder.pluginManager.getAllPlugins()
2) Using custom plugin properties to lookup plugins of interest
Other strategy, if you must lookup the bundle dynamically.
Create a custom marker property in each of your plugin descriptors
def specialProperty = "whatever"
Then inside your CustomerBundleSingleton
PluginManagerHolder.pluginManager.getAllPlugins().each {
if (it.properties.specialProperty) {
def subProjectName = it.name
def subProjectVersion = it.version
}
}
3) Custom bundle info resolution
You may also want to consider some metadata via META-INF/MANIFEST.MF or similar mechanism.
Hope it helps...

Grails: importing plugin classes to _Events.groovy

I've created a Grails plugin which adds a custom test type class (extending GrailsTestTypeSupport) and custom test result class (extending GrailsTestTypeResult) to support a custom test type that I run during the other phase of the test-app script. Testing this on my local machine has gone swimmingly but...
When I packaged the plugin to use in my app, the tests are blowing up on our CI server (Jenkins). Here's the error that Jenkins is spitting out:
unable to resolve class CustomTestResult # line 58, column 9.
new CustomTestResult(tests.size() - failed, failed)
It appears that I cannot simply import these classes into _Events.groovy, and the classes are not otherwise on the classpath. But I'll be damned if I can figure out how to get them onto the classpath. Here's what I have so far (in _Events.groovy):
import java.lang.reflect.Constructor
eventAllTestsStart = {
if (!otherTests) otherTests = []
loadCustomTestResult()
otherTests << createCustomTestType()
}
private def createCustomTestType(String name = 'js', String relativeSourcePath = 'js') {
ClassLoader parent = getClass().getClassLoader()
GroovyClassLoader loader = new GroovyClassLoader(parent)
Class customTestTypeClass = loader.parseClass(new File("${customTestPluginDir}/src/groovy/custom/test/CustomTestType.groovy"))
Constructor customTestTypeConstructor = customTestTypeClass.getConstructor(String, String)
def customTestType = customTestTypeConstructor.newInstance(name, relativeSourcePath)
customTestType
}
private def loadCustomTestResult() {
ClassLoader parent = getClass().getClassLoader()
GroovyClassLoader loader = new GroovyClassLoader(parent)
Class customTestResultClass = loader.parseClass(new File("${customTestPluginDir}/src/groovy/custom/test/CustomTestResult.groovy"))
}
Currently: CustomTestResult is only referenced from within CustomTestType. As far as I can tell, _Events.groovy is loading CustomTestType but it is failing because it then insists that CustomTestResult is not on the classpath.
Putting aside for a moment that it seems crazy that there's this much overhead to get plugin-furnished classes onto the classpath for the test cycle to begin with... I'm not quite sure where I've gotten tripped up. Any help or pointers would be greatly appreciated.
Have you tried simply loading the class in question via the ClassLoader that is accessible via the classLoader variable in _Events.groovy?
Class customTestTypeClass = classLoader.loadClass('custom.test.CustomTestType')
// use nice groovy overloading of Class.newInstance
return customTestTypeClass.newInstance(name, relativeSourcePath)
You should be late enough in the process at eventAllTestsStart for this to be valid.
#Ian Roberts' answer got me pointed in roughly the right direction, and combined with the _Events.groovy script from this grails-cucumber plugin, I managed to come through with this solution:
First, _Events.groovy became this:
eventAllTestsStart = { if (!otherTests) otherTests = [] }
eventTestPhasesStart = { phases ->
if (!phases.contains('other')) { return }
// classLoader.loadClass business per Ian Roberts:
otherTests << classLoader.loadClass('custom.test.CustomTestType').newInstance('js', 'js')
}
Which is far more readable than where I was at the start of this thread. But: I was in roughly the same position: my ClassNotFoundException moved from being thrown in _Events.groovy to being thrown from within CustomTestType when it tried to create an instance of custom.test. CustomTestResult. So within CustomTestType, I added the following method:
private GrailsTestTypeResult createResult(passed, failed) {
try {
return new customTestResult(passed, failed)
} catch(ClassNotFoundException cnf) {
Class customTestResult = buildBinding.classLoader.loadClass('custom.test.CustomTestResult')
return customTestResult.newInstance(passed, failed)
}
}
So Ian was right, inasmuch as classLoader came to the rescue -- I just wound up needing its magic in two places.

Resources