OSGi bundle installation using pax-exam issue - osgi

I'm trying to write spock pax exam extension, but figured out a problem with bundle installation using server mode.
Here is my code
void visitSpecAnnotation(RunPax annotation, SpecInfo sp) {
sp.addListener(new AbstractRunListener() {
private TestContainer container
#Override
void beforeSpec(SpecInfo spec) {
ExamSystem system = PaxExamRuntime.createServerSystem(
CoreOptions.options(
karafDistributionConfiguration("mvn:org.apache.servicemix/apache-servicemix/4.4.1-fuse-03-06/tar.gz", // artifact to unpack and use
"servicemix", // name; display only
"2.2.4")
.unpackDirectory(new File("target/paxexam/unpack/"))
.useDeployFolder(false),
//debugConfiguration("5005", true),
keepRuntimeFolder(),
configureConsole().ignoreLocalConsole(),
when(isEquinox()).useOptions(
editConfigurationFilePut(
KARAF_FRAMEWORK, "equinox"),
systemProperty("pax.exam.framework").value(
System.getProperty("pax.exam.framework")),
//systemProperty("osgi.console").value("6666"),
//systemProperty("osgi.console.enable.builtin").value("true")
),
logLevel(WARN),
mavenBundle("org.sdo.coding", "words", "1.0")
))
container = PaxExamRuntime.createContainer(system)
container.start()
Thread.sleep(100000)
def ant = new AntBuilder()
ant.sshexec(host: "localhost",
port: '8101',
username: "smx",
password: 'smx',
trust: "yes",
command: "list",
outputproperty: 'result',
knownhosts: '/dev/null')
def result = ant.project.properties.'result'
println "result is $result"
def installed = result =~ /(?m)^(.*Installed.*)$/
println "installed ${installed[0]}"
}
Even if i increase delay i cannot find my bundle installed. I can see that the option mavenBundle doesn't affect karaf start, because if i place wrong version or artifactId, pax won't notify me about it.
Anyone has any clue on this problem?

Related

groovy command curl on windows Jenkins

I have a groovy script that work on Linux Jenkins
import groovy.json.JsonSlurper
try {
List<String> artifacts = new ArrayList<String>()
//jira get summery for list by issue type story and label demo and project 11411
def artifactsUrl = 'https://companyname.atlassian.net/rest/api/2/search?jql=project=11411%20and%20issuetype%20in%20(Story)%20and%20labels%20in%20(demo)+&fields=summary' ;
def artifactsObjectRaw = ["curl", "-u", "someusername#xxxx.com:tokenkey" ,"-X" ,"GET", "-H", "Content-Type: application/json", "-H", "accept: application/json","-K", "--url","${artifactsUrl}"].execute().text;
def parser = new JsonSlurper();
def json = parser.parseText(artifactsObjectRaw );
//insert all result into list
for(item in json.issues){
artifacts.add( item.fields.summary);
}
//return list to extended result
return artifacts ;
}catch (Exception e) {
println "There was a problem fetching the artifacts " + e.message;
}
This script return all the names from Jira jobs by the API ,
But when I tried to run this groovy on Windows Jenkins the script will not work because windows do not have the command curl
def artifactsObjectRaw = ["curl", "-u","someusername#xxxx.com:tokenkey" ,"-X" ,"GET", "-H", "Content-Type: application/json", "-H", "accept: application/json","-K","--url","${artifactsUrl}"].execute().text;
how should I preform this command?
The following code:
import groovy.json.JsonSlurper
try {
def baseUrl = 'https://companyname.atlassian.net'
def artifactsUrl = "${baseUrl}/rest/api/2/search?jql=project=MYPROJECT&fields=summary"
def auth = "someusername#somewhere.com:tokenkey".bytes.encodeBase64()
def headers = ['Content-Type': "application/json",
'Authorization': "Basic ${auth}"]
def response = artifactsUrl.toURL().getText(requestProperties: headers)
def json = new JsonSlurper().parseText(response)
// the below will implicitly return a list of summaries, no
// need to define an 'artifacts' list beforehand
def artifacts = json.issues.collect { issue -> issue.fields.summary }
} catch (Exception e) {
e.printStackTrace()
}
is pure groovy, i.e. no need for curl. It gets the items from the jira instance and returns a List<String> of summaries. Since we don't want any external dependencies like HttpBuidler (as you are doing this from jenkins) we have to manually do the basic auth encoding.
Script tested (the connecting and getting json part, did not test the extraction of summary fields) with:
Groovy Version: 2.4.15 JVM: 1.8.0_201 Vendor: Oracle Corporation OS: Linux
against an atlassian on demand cloud instance.
I removed your jql query as it didn't work for me but you should be able to add it back as needed.
Install curl and set the path in environment variable of windows.
Please follow the link to download curl on windows.
I would consider using HTTP request plugin when making HTTP Requests.
Since you are using a plugin, it does not matter if you are running in Windows or .
Linux as your Jenkins Host

Jenkins declarative pipe, download latest upload (build) from Artifactory and get properties

Any sugesstions on this litle problem is very welcome! :)
It works fine to download the latest build but the object does not contain any properties.
Is it possible to get the properties from a downloaded build?
The gool is to get an inputbox with a predefined value displaying previous version i.e. "R1G" and give the user the option to edit the value to i.e. R2A or any other value or only abort (abort meaning there will be no version).
The user also have the option to do nothing withch will led to a timeoute and finaly an abort.
I want to
download latest build from Artifactory repo
store the build.number in "def prev_build"
display the prev_build in an input for the user to be updated (a customized number)
'''some code
echo 'Publiching Artifact.....'
script{
def artifactory_server_down=Artifactory.server 'Artifactory'
def downLoad = """{
"files":
[
{
"pattern": "reponame/",
"target": "${WORKSPACE}/prev/",
"recursive": "false",
"flat" : "false"
}
]
}"""
def buildInfodown=artifactory_server_down.download(downLoad)
//Dont need to publish because I only need the properties
//Grab the latest revision name here and use it again
echo 'Retriving revision from last uploaded build.....'
env.LAST_BUILD_NAME=buildInfodown.build.number
//Yes its a map and I have tried with ['build.number'] but the map is empty
}
echo "Previous build name is $env.LAST_BUILD_NAME" //Will not contain the old (latest)
''' End of snipet
The output is null or the default value I have given the var, not the expected version number.
Yes, firstly the properties should be present in the artifacts you are trying to download.
The build.number etc are part of the buildinfo.json file of the artifacts. these are not properties but metadata of some kind. this info would be visible under "Builds" menu in artifactory. Select the repo and build number.
At the last column/tab there would be buildinfo. Click on that - this file will hold all the info you need corresponding to the artifacts.
The build.number and other info will be pushed/uploaded to artifactory by the CI.
For example in case of Jenkins there is an option available when trying to push to artifactory "Capture and publish build info" --> this step does the work
Thanks a lot for your help.
I see your suggestion works but I had when I got your answer already implemented another solution that also works well
I am using the available query language.
https://www.jfrog.com/confluence/display/RTF/Artifactory+Query+Language
Just before my pipeline declaration in the pipeline file I added
def artifactory_url = 'https://lote.corp.saab.se:8443/artifactory/api/search/aql'
def artifactory_search = 'items.find({ "repo":"my_repo"},{"#product.productNumber":
{"$match":"produktname"}}).sort({"$desc":["created"]})'
pipeline
{
and ...
stage('Get latest revision') {
steps {
script {
def json_text = sh(script: "curl -H 'X-JFrog-Art-Api:${env.RECIPE_API_KEY}' -X POST '${artifactory_url}' -d '${artifactory_search}' -H 'Content-Type: text/plain' -k", returnStdout: true).trim()
def response = readJSON text: json_text
VERSION = response.results[0].path;
echo "${VERSION}"
println 'using each & entry'
response[0].each{ entry ->
println 'Key:' + entry.key + ', Value:' +
entry.value
}
}
}
}
stage('Do relesase on master')
{
when
{
branch "master"
}
options {
timeout(time: 1, unit: 'HOURS')
}
steps {
script{
RELEASE_SCOPE = input message: 'User input
required', ok: 'Ok to go?!',
parameters: [
choice(name: 'RELEASE_TYPE', choices:
'Artifactory\nClearCaseAndArtifactory\nAbort',
description: 'What is the release scope?'),
string(name: 'VERSION', defaultValue:
VERSION, description: '''Edit release name please!!''',
trim: false)
]
}
echo 'Build both RPM and Zip packages'
... gradlew -Pversion=${RELEASE_SCOPE['VERSION']} clean buildPackages"
script {
def artifactory_server = Artifactory.server 'Artifactory'
def buildInfo = Artifactory.newBuildInfo()
def uploadSpec = """{
"files":[
{
"pattern": "${env.WORKSPACE}/prodname/release/build/distributions/prodname*.*",
"target": "test_repo/${RELEASE_SCOPE['VERSION']}/",
"props": "product.name=ProdName;build.name=${JOB_NAME};build.number=${env.BUILD_NUMBER};product.revision=${RELEASE_SCOPE['VERSION']};product.productNumber=produktname"
}
]
}"""
println(uploadSpec)
artifactory_server.upload(uploadSpec)
}
}
}

Configure swagger in gradle build script with kotlin dsl

I'm trying to switch my simple project from Groovy to Kotlin in build scripts.
I'm using this plugin:
https://github.com/gigaSproule/swagger-gradle-plugin
I have this configuration in my build script:
swagger{
apiSource {
springmvc = false
locations = ['my.location']
schemes = ['https']
host = 'test.com:8080'
info {
title = 'My Service'
version = 'v1'
}
swaggerDirectory = "$buildDir/swagger"
}
To where shall I refer to in this situations?
Shall I do something like?
task( "swagger" ) {
...
}
It is not quite familiar for me.
Thanks.
In case anyone is still looking for this information, this is how you would do it using Gradle Kotlin DSL:
import com.benjaminsproule.swagger.gradleplugin.model.*
plugins {
id("com.benjaminsproule.swagger") version "1.0.0"
}
swagger {
apiSource(closureOf<ApiSourceExtension> {
springmvc = false
schemes = mutableListOf("https")
host = "test.com:8080"
info(closureOf<InfoExtension> {
title = "My Service"
version = "v1"
description = "My Service Description"
termsOfService = "http://www.example.com/termsOfService"
contact(closureOf<ContactExtension> {
email = "email#internet.com"
name = "A Developer"
url = "http://www.internet.com"
})
license(closureOf<LicenseExtension> {
url = "http://www.apache.org/licenses/LICENSE-2.0.html"
name = "Apache 2.0"
})
})
locations = mutableListOf("com.foo.fighting")
swaggerDirectory = "$buildDir/swagger"
})
}
I've tested it using Gradle v4.6.

URISyntaxException in gradle environment variable while testing

I have a build.gradle as follows
task setDockerHost {
group 'Docker'
description 'Gets the docker host ip from your OS'
def stdout = new ByteArrayOutputStream()
exec {
commandLine './src/main/resources/scripts/get-docker-host.sh', '60'
standardOutput = stdout
}
project.ext.set('DOCKERHOST', "$stdout")
}
tasks.withType(Test) {
doFirst { println "DockerHost is $project.DOCKERHOST" }
environment 'DOCKERHOST', "$project.DOCKERHOST"
outputs.upToDateWhen { false }
testLogging {
events 'passed', 'skipped', 'failed', 'standardOut'
}
reports.html.destination = file("${reporting.baseDir}/${name}")
}
I define a DOCKERHOST env variable as above and want to use in my groovy test class:
class MyClass extends Specification {
RESTClient client = new RESTClient("http://"+System.getenv('DOCKERHOST')+":9090/")
...
}
In the execution my println works: DockerHost is 192.168.99.100
But when I run the this test it throws:
I already tried replacing \n, \r and spaces by "". I also try removing the protocol from the URL (aka 192.168.99.10:9090) and it tells me that the same error occurs at index 0
How can I solve this?
I didn't figure it out in which char was the problem but I was able to solve it but replacing strings like crazy:
String url = ("http://" + System.getenv('DOCKERHOST') + ":9090/").replace("\n", "").replace("\r", "").replace(" ", "")
RESTClient client = new RESTClient(url)
I've spent like a day trying to figure this out... hopefully for someone else will be quicker.

Groovy SwingBuilder() apple.awt.CToolkit exception

I am using newest Mac OS X and I am creating a GUI element inside a Gradle file. I am currently using jdk1.7.0_55 and I have imported groovy.swing.SwingBuilder, when I run the project I am getting the following error:
java.awt.AWTError: "Toolkit not found: apple.awt.CToolkit
I have tried running the script as a headless server using System.setProperty('java.awt.headless', 'true')
I would like to have a solution that I can include directly in the Gradle project file, instead of trying to figure out what is in my accesibilities.properties file (that may not exist on a particular system, like it does not on my system).
Also the project must use an internal solution, external libraries are not allowed.
Would really appreciate any help on this matter.
Edited: Sample Code
gradle.taskGraph.whenReady { taskGraph ->
if(taskGraph.hasTask(':CustomApp:assembleRelease')) {
def pass = ''
if(System.console() == null) {
new SwingBuilder().edt { // Error occurs here.
dialog(modal: true,
alwaysOnTop: true,
resizable: false,
locationRelativeTo: null,
pack: true,
show: true
)
{
vbox {
label(text: "Enter password:")
input = passwordField()
button(defaultButton: true, text: 'OK', actionPerformed: {
pass = input.password;
dispose();
})
}
}
}
}
}
I've faced same issue with Android Studio 0.8.6 and solved it with custom gradle installation.
Just downloaded gradle 1.12 and set path to it in preferences.
The question is a few years old, but with the following gradle build file (which is essentially the same as the OPs):
import groovy.swing.SwingBuilder
task doit {}
gradle.taskGraph.whenReady { taskGraph ->
if(taskGraph.hasTask(doit)) {
def pass = ''
new SwingBuilder().edt { // Error occurs here.
dialog(modal: true,
alwaysOnTop: true,
resizable: false,
locationRelativeTo: null,
pack: true,
show: true)
{ vbox
{ label(text: "Enter password:")
input = passwordField()
button(defaultButton: true, text: 'OK', actionPerformed: {
pass = input.password;
dispose();
})
}
}
}
}
}
executing:
~> gradle doit
results in the following screen:
in other words, at least with this version of gradle, operating system, java etc this seems to work.

Resources