When try to create AntBuidler object in groovy file I am getting below exception
java.lang.NoClassDefFoundError: org/apache/tools/ant/BuildException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2493)
at java.lang.Class.getDeclaredConstructors(Class.java:1901)
.....
at at features.step_definitions.RewardEventsGeneration.GetEventXML(RewardEventsGeneration.groovy:40)
at ✽.Then updateLoyaltyInfo event should be generated
I have added relevant jar to my lib folder and then placed below code under the build.gradle
repositories {
mavenCentral()
flatDir {
dirs 'lib'
}
}
My code as below
def GetEventXML (userId, eventTypeIn)
{
def Host = "10.77.69.14"
def UserName = "system"
def Password = "password"
def Path = "/temp"
def eventTypeToLookFor = "eventType=\"$eventTypeIn\""
def resultAsString = "" as String
def commandToRun = "grep -lH $userId $Path/*.xml | xargs grep -l '$eventTypeToLookFor' | cut -d: -f1"
def antEventCheck = new AntBuilder(); ********** Error line ******************
antEventCheck.sshexec( trust:'true',
host:Host,
username:UserName,
password:Password,
command:commandToRun,
verbose:'true',
timeout:'10000',
failonerror:'false',
outputproperty:'eventCheckResult');
resultAsString = antEventCheck.properties.eventCheckResult.toString()
return resultAsString
}
build.gradle
dependencies {
ext.groovyVersion = "2.0.4"
ext.cucumberJvmVersion = "1.1.5"
ext.httpclientVersion = "4.2.1"
cucumberRuntime files("${jar.archivePath}")
compile ('com.jcraft:jsch:0.1.49')
compile('com.github.groovy-wslite:groovy-wslite:0.8.0')
groovy("org.codehaus.groovy:groovy-all:${groovyVersion}")
compile("org.apache.httpcomponents:httpmime:4.1.2")
compile("org.codehaus.groovy.modules.http-builder:http-builder:0.5.2") {
exclude group: "org.codehaus.groovy", module: "groovy"
}
compile("net.sf.json-lib:json-lib:2.4:jdk15")
compile("javax.mail:mail:1.4.5")
compile("org.apache.httpcomponents:httpclient:${httpclientVersion}")
compile("org.codehaus.geb:geb-core:0.7.2") {
exclude group: "org.codehaus.geb", module: "geb-implicit-assertions"
}
drivers.each { driver ->
testCompile "org.seleniumhq.selenium:selenium-$driver-driver:$version.selenium"
}
compile("org.seleniumhq.selenium:selenium-support:2.25.0")
compile("log4j:log4j:1.2.17")
testCompile("junit:junit:4.10")
testCompile("info.cukes:cucumber-groovy:${cucumberJvmVersion}")
testCompile("info.cukes:cucumber-junit:${cucumberJvmVersion}")
}
Appreciate your comments
Following works perfectly
As specified by Peter's answer adding flatDir is not gonna be enough. Need to add same to the dependencies as well
repositories {
mavenCentral()
flatDir {
dirs 'lib'
}
}
dependencies {
compile("ant:ant:1.7.0")
}
Thanks Peter
Related
I want to create a pipeline that can use the hostnames in the Ansible inventory file.
Path: ansible/inventories/preprod/hosts
[client-app]
client-app-preprod-01.aws
client-app-preprod-02.aws
client-app-preprod-03.aws
client-app-preprod-04.aws
[server-app]
server-app-preprod-01.aws
server-app-preprod-02.aws
server-app-preprod-03.aws
server-app-preprod-04.aws
I created a script that works functionally, but uses a list of hosts from itself (hardcode).
Groovy Script:
if (ENVIRONMENT=="preprod") {
if (SERVICE=="client-app") {
hostsList = ['client-app-preprod-01.aws','client-app-preprod-02.aws','client-app-preprod-03.aws','client-app-preprod-04.aws']
} else {
hostsList = ['server-app-preprod-01.aws','server-app-preprod-02.aws','server-app-preprod-03.aws','server-app-preprod-04.aws']
}
}
return hostsList
but I can't find a solution to create a script that can read hosts from the Ansible repository and inventory file.
I would be grateful for any information that can help me write this script. Courses, books, examples and more.
In addition, the pipeline should look like this:
Here is a sample function you can use to process the Inventory file and get the host entries.
def getHostList(def appName, def filePath) {
def hosts = []
def content = readFile(file: filePath)
def startCollect = false
for(def line : content.split('\n')) {
if(line.contains("["+ appName +"]")){ // This is a starting point of host entries
startCollect = true
continue
} else if(startCollect) {
if(!line.allWhitespace && !line.contains('[')){
hosts.add(line.trim())
} else {
break
}
}
}
return hosts
}
You can call this function like below.
def hosts = getHostList("client-app", "ansible/inventories/preprod/hosts")
I am trying to augment the 'load' pipeline step function and I keep getting an error. I have found the code it executes based on the stack trace but I can't for the life of me figure out why it wouldn't just call the code as written.
I have written lots-and-lots of Java code so I know what it's trying to do. I just don't understand why it's trying to do it or how to convince it to stop! The groovy sample works perfectly! BTW: if there is an idiomatic way to do this in groovy/jenkins, I am all in.
Jenkins version: 2.176.1
Groovy plugin: 2.2
test.groovy
def someFunction(def params){
println("someFunction ${params}")
}
def someFunction2(def params){
println("someFunction2 ${params}")
}
def mainFunc(def stuff){
}
def somemainThingrunFunmain(){
}
def ___cps___21685(){
}
def ___cps___21688(){
}
this
main.groovy
def loaded = evaluate('test.groovy' as File)
def toAugment = loaded.class.declaredMethods*.name.findAll { !(it =~ '^(main|run)$|^[$]|^(___cps___)') }
def proxy = new Script(this.binding) {
#Override
Object run() {
monad.run()
}
}
toAugment.each {
proxy.metaClass."${it}" = { "logging ${it}".tap { println(it)} } >> loaded.&"${it}"
}
proxy.someFunction('hello world1')
proxy.someFunction2('hello world2')
outputs:
called
someFunction hello world1
called
someFunction2 hello world2
Now in Jenkins:
Jenkinsfile:
library 'common-libraries#chb0'
node('java') {
stage('SCM') {
checkout scm
}
def loaded = load('test.groovy')
stage('experiment') {
loaded.someFunction('hello world1')
loaded.someFunction2('hello world2')
}
}
adapted library (in common-library:vars/load.groovy):
def call(String path) {
def loaded = steps.load(path)
def proxy = new Script(this.getBinding()) { // error here
#Override
Object run() {
loaded.run()
}
}
// remove groovy and jenkins generated functions. Don't touch those
def toAugment = loaded.class.declaredMethods*.name.findAll { !(it =~ '^(main|run)$|^[$]|^(___cps___)') }
toAugment.each {
proxy.metaClass."${it}" = { "logging ${it}".tap { println(it) } } >> loaded.&"${it}"
}
}
exception:
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: load$1(load, Script1, groovy.lang.Binding)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1732)
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1532)
at org.codehaus.groovy.runtime.callsite.MetaClassConstructorSite.callConstructor(MetaClassConstructorSite.java:49)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.constructorCall(DefaultInvoker.java:25)
I would like to run different versions of my Grails (2.3.5) app at the same time in the same tomcat using different DBs.
At the moment I am having an external configuration file where I specify my DB configurations.
The filename is hardcoded:
<tomcat-home>/conf/sc.conf
"sc.war" is the name of my war-file. As I now want/need to run multiple versions I would like to make the name of the conf file variable.
<tomcat-home>/conf/<warfilename>.conf
Is there a way to get the war-file-name at runtime?
I am open for other ways to solve my problem. Thanks for your help.
You just need to give applicationBaseDir path into external config file
applicationBaseDir = ""
println "Bootstrapping application"
println ">>>>>>>>Environment >>>>>"+GrailsUtil.environment
Environment.executeForCurrentEnvironment {
development {
println "Keeping applicationBaseDir "+grailsApplication.config.applicationBaseDir+" as is."
}
production {
//Following code finds your project path and set applicationBaseDir
Process findPresentWorkingDirectory = "pwd".execute()
def pwd = findPresentWorkingDirectory.text
def pwdTokens = pwd.tokenize("/")
pwdTokens.pop()
applicationBaseDir = pwdTokens.join("/")
println ">>>> applicationBaseDir "+applicationBaseDir
applicationBaseDir = "/"+applicationBaseDir+"/webapps/applicationDir/"
println 'grailsApplication.config.applicationBaseDir '+applicationBaseDir
}
}
Or you directly set applicationBaseDir in external config file
applicationBaseDir = "/home/tomcat/webapps/applicationDir/"
Now, to refer specific external config file add into your project file Config.groovy file following code
environments {
development {
String codeSystemClassFilePath = AnyDomainClassNameFromYourApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath()
// Here AnyDomainClassNameFromYourApplication change to your application domain class name e.g.I have domain class Student then I replace it with Student
def arrayWithLastValueAsProjectName = codeSystemClassFilePath.split('/target/classes/')[0].split('/')
String projectName = arrayWithLastValueAsProjectName[arrayWithLastValueAsProjectName.size()-1]
println "App name in dev==>"+projectName
grails.logging.jul.usebridge = true
grails.config.locations = [
"file:${userHome}/grails/${projectName}.groovy"
]
grails.assets.storagePath = ""
}
production {
String codeSystemClassFilePath = AnyDomainClassNameFromYourApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath()
def arrayWithLastValueAsProjectName = codeSystemClassFilePath.split('/WEB-INF/classes/')[0].split('/')
String projectName = arrayWithLastValueAsProjectName[arrayWithLastValueAsProjectName.size()-1]
println "App name in production==>"+projectName
grails.logging.jul.usebridge = false
grails.config.locations = [
"file:${userHome}/grails/${projectName}.groovy"
]
}
}
//here grails/ is my default folder use to store exernal-config-files
I hope this helps you!
I'm getting an error when i try to execute a custom gradle task to pre-compile jsp files.
My task looks like:
task compile_jsp(dependsOn: 'compileJava') << {
//Define master classpath
def masterpath = ant.path(id: 'master-classpath') {
fileset(dir: "${rootDir}/build/libs"){
include(name: '**.jar')
}
fileset(dir: sourceSets.main.output.classesDir) {
include(name: '**/*.class')
}
fileset(dir: "${rootDir}/src/main"){
include(name: '**/*.java')
}
}
ant.taskdef(classname: 'org.apache.jasper.JspC', name: 'jasper', classpath: configurations.jasper.asPath + masterpath)
ant.jasper(uriRoot: "${rootDir}/src/main/webapp/", outputDir: "${rootDir}/src/main/webapp/WEB-INF/" + "${compileJspOutputDir}/", webXmlFragment: "${rootDir}/src/main/webapp/WEB-INF/generated_web.xml", addWebXmlMappings: "true")
}
The error that i get is something like:
The value for the useBean class attribute <class> is invalid.
I think its related to the classes location in the project because the task works well if i define the sourceSets.main.output.classesDir like:
sourceSets.main.output.classesDir = "${rootDir}/src/main/webapp/WEB-INF/classes"
Otherwise, i get the mentioned error.
Is there any way to run this without change the classes dir?
I am using Grails version 2.2.4 and I have installed kickstart plugin as compile ":kickstart-with-bootstrap:0.9.6".
BuildConfig.groovy
plugins {
runtime ":hibernate:$grailsVersion"
runtime ":jquery:1.8.3"
runtime ":resources:1.1.6"
compile ":kickstart-with-bootstrap:0.9.6"
build ":tomcat:$grailsVersion"
runtime ":database-migration:1.3.2"
compile ':cache:1.0.1'
}
I found "KickstartFilters.groovy" filter with following directory structure
plugin
-> kickstart-with-bootstrap:0.9.6
-> conf
-> kickstart
-> KickstartFilters.groovy
my "KickstartFilters.groovy" file contains following information
package kickstart
class KickstartFilters {
def filters = {
all() {
before = {
// Small "logging" filter for controller & actions
log.info(!params.controller ? '/: ' + params : params.controller +"."+(params.action ?: "index")+": "+params)
}
after = {
}
afterView = {
}
}
}
}
while log.info are printed in logs at that time if password is passed as params then password information are visible on log so how can I prevent only password Information?
I have a work around for this...
https://github.com/joergrech/KickstartWithBootstrap/issues/84
Basically create your filter under conf/kickstart/YourAppFilters.groovy
package kickstart
class YourAppFilters extends KickstartFilters {
def filters = {
kickstartLogger() {
before = {
// Small "logging" filter for controller & actions
if (log.infoEnabled) {
if (!params.controller.equals('chat')) {
if (!params.password ) {
log.info(!params.controller ? '/: ' + params : params.controller +"."+(params.action ?: "index")+": "+params)
}else{
log.info (params.controller+","+params.action+":"+params?.username)
}
}
}
}
}
}
}
Now under conf/spring/resources.groovy under beans add:
yourAppFilters(KickstartFilters)
This should now override kickstarts filter