java.lang.NoSuchMethodError: No such DSL method 'warnings' found among steps - jenkins-pipeline

We are migrating the jobs from older jenkins environment (version 2.48) to new jenkins environment (2.263), job execution with "jenkinsFile" failed with this below exception, and below is the detail of the jenkinsFile, "basic pipeline" plugin was already installed inthe jenkins yet, its failing. Any solution is appreciated.
#!groovy
pipeline {
agent { label 'acme-label' }
options {
buildDiscarder(logRotator(numToKeepStr: '10'))
disableConcurrentBuilds()
timestamps()
}
stages {
stage("Checkout") {
steps {
checkout scm
}
}
stage("Install Dependencies") {
steps {
sh "bundle install --deployment"
}
}
stage("Lint") {
steps {
sh "bundle exec rake"
}
}
}
post {
always {
warnings canRunOnFailed: true, consoleParsers: [[parserName: 'Foodcritic']]
}
failure {
script {
mailer.send('acme')
}
}
}
}
> 11:49:33 java.lang.NoSuchMethodError: No such DSL method 'warnings'
> found among steps [addEmbeddableBadgeConfiguration, ansiColor,
> archive, bat, build, catchError, checkout, checkpoint,
> compareVersions, container, containerLog, copyRemoteArtifacts,
> deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, echo,
> emailext, emailextrecipients, envVarsForTool, error, fileExists,
> findFiles, getContext, git, httpRequest, input, isUnix, jiraComment,
> jiraIssueSelector, jiraSearch, junit, library, libraryResource, load,
> mail, milestone, node, nodesByLabel, parallel, podTemplate,
> powershell, properties, publishChecks, publishEvent, publishHTML,
> publishIssues, pwd, pwsh, readCSV, readFile, readJSON, readManifest,
> readMavenPom, readProperties, readTrusted, readYaml, recordIssues,
> resolveScm, retry, sauce, sauceconnect, scanForIssues, script, sh,
> sha1, sleep, stage, stash, step, tee, throttle, timeout, timestamps,
> tm, tool, touch, triggerRemoteJob, unarchive, unstable, unstash,
> unzip, validateDeclarativePipeline, waitForQualityGate, waitUntil,
> warnError, withContext, withCredentials, withDockerContainer,
> withDockerRegistry, withDockerServer, withEnv, withMaven, wrap,
> writeCSV, writeFile, writeJSON, writeMavenPom, writeYaml, ws, xunit,
> zip] or symbols [AUnit, BoostTest, CTest, CUnit, Check, CppTest,
> CppUnit, Custom, FPCUnit, GoogleTest, JUnit, MSTest, MbUnit, NUnit2,
> NUnit3, PHPUnit, PVSStudio, QtTest, UnitTest, Valgrind,
> abstractItemDirectoryComponent, acuCobol,
> agentDumpExportTableComponent, agentJVMProcessSystemMetricsComponent,
> agentSystemConfigurationComponent, agentsConfigFileComponent, ajc,
> all, allBranchesSame, allOf, always, androidLintParser,
> anonymizeSupportBundle, ansibleLint, ant, antFromApache, antOutcome,
> antPath, antTarget, any, anyOf, apiToken, architecture,
> archiveArtifacts, armCc, artifactManager, artifactsPublisher,
> authorizationMatrix, aws, awsCredentials, axivion, axivionSuite,
> batchFile, bitbucket, bitbucketBranchDiscovery,
> bitbucketForkDiscovery, bitbucketPublicRepoPullRequestFilter,
> bitbucketPullRequestDiscovery, bitbucketSshCheckout,
> bitbucketTagDiscovery, bitbucketTrustEveryone, bitbucketTrustNobody,
> bitbucketTrustProject, bitbucketTrustTeam,
> bitbucketWebhookConfiguration, bitbucketWebhookRegistration,
> blindlyTrust, booleanParam, branch, brokenBuildSuspects,
> brokenTestsSuspects, buckminster, buildAllBranches, buildAnyBranches,
> buildButton, buildChangeRequests, buildDescription, buildDiscarder,
> buildDiscarders, buildFailureAnalyzer, buildName, buildNamedBranches,
> buildNoneBranches, buildRegularBranches, buildRetention, buildTags,
> buildingTag, cadence, cargo, caseInsensitive, caseSensitive, ccm,
> certificate, changeRequest, changelog, changeset, checkStyle,
> checkoutToSubdirectory, choice, choiceParam, clair, clang,
> clangAnalyzer, clangTidy, cleanWs, clock,
> cloudBeesPipelineTemplatesFolder, cloudBeesRoleBasedAccessControl,
> cmake, cobertura, coberturaAdapter, codeAnalysis, codeNarc, command,
> concordionPublisher, configFile, configFileProvider, configMapVolume,
> containerEnvVar, containerLivenessProbe, containerTemplate, coolflux,
> cpd, cppCheck, cppLint, credentials, cron, crumb, cssLint, cssText,
> cssUrl, culprits, customProbe, default, defaultFolderConfiguration,
> defaultView, demand, dependenciesFingerprintPublisher, detekt,
> developers, diabC, disableConcurrentBuilds, disableResume, docFx,
> docker, dockerCert, dockerLint, dockerServer, dockerTool, dockerfile,
> downstream, doxygen, drMemory, dscanner, dumb, dupFinder,
> durabilityHint, dynamicPVC, eclipse, embUnit, emptyDirVolume,
> emptyDirWorkspaceVolume, envInject, envVar, envVars, envVarsFilter,
> environment, equals, erlc, errorProne, esLint, eventTrigger, exact,
> excludeCategory, excludeFile, excludeMessage, excludeModule,
> excludeNamespace, excludePackage, excludeType, expression, failed,
> faviconUrl, file, fileParam, filePath, findBugs, findbugs,
> findbugsPublisher, fingerprint, fingerprints, flake8, flawfinder,
> flexSdk, frameOptions, freeStyle, freeStyleJob, fromDocker, fromScm,
> fromSource, fromTemplateFactory, fxcop, gcc, gcc3, gcc4, gendarme,
> ghsMulti, git, gitBranchDiscovery, gitHubBranchDiscovery,
> gitHubBranchHeadAuthority, gitHubExcludeArchivedRepositories,
> gitHubExcludePublicRepositories, gitHubForkDiscovery,
> gitHubPullRequestDiscovery, gitHubSshCheckout, gitHubTagDiscovery,
> gitHubTopicsFilter, gitHubTrustContributors, gitHubTrustEveryone,
> gitHubTrustNobody, gitHubTrustPermissions, gitTagDiscovery, github,
> githubPush, globalConfigFiles, gnat, gnuFortran, goLint, goVet,
> groovyScript, gtester, hadoLint, headRegexFilter, headWildcardFilter,
> hostPathVolume, hostPathWorkspaceVolume, hyperlink, hyperlinkToModels,
> iar, iarCstat, ibLinter, ideaInspection, includeCategory, includeFile,
> includeMessage, includeModule, includeNamespace, includePackage,
> includeType, infer, inheriting, inheritingGlobal, installSource,
> intel, invalids, invokerPublisher, isRestartedRun, issues,
> istanbulCobertura, istanbulCoberturaAdapter, jacoco, jacocoAdapter,
> jacocoPublisher, java, javaDoc, javadoc, jcReport, jclouds, jdk,
> jdkInstaller, jgit, jgitapache, jgivenPublisher, jmespathQuery, jnlp,
> jobBuildDiscarder, jobDsl, jobName, jsHint, jsLint, jsUrl, jsonEvent,
> junitParser, junitPublisher, junitTestResultStorage, klocWork,
> knownHosts, kotlin, ktLint, kubeconfig, kubernetes,
> kubernetesPodTemplates, label, lastDuration, lastFailure,
> lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM,
> list, local, location, logRotator, loggedInUsersCanDoAnything, mailer,
> manualLaunchOnly, manually, masterBuild,
> masterJVMProcessSystemMetricsComponent,
> masterSystemConfigurationComponent, maven, maven3Mojos, mavenConsole,
> mavenErrors, mavenLinkerPublisher, mavenMojos, mavenWarnings, merge,
> metrowerksCodeWarrior, mineRepository, modelsim, modernSCM, msBuild,
> myPy, myView, nagFortran, namedBranchesDifferent, never,
> newContainerPerStage, nfsVolume, nfsWorkspaceVolume, nioSsh, node,
> nodeProperties, nodeRemoteDirectoryComponent, nonInheriting, none,
> not, onFailure, openTasks, openTasksPublisher, override,
> overrideIndexTriggers, owners, paneStatus, parallelsAlwaysFailFast,
> parameters, passed, password, pattern, pcLint, pep8, perforce,
> perlCritic, permanent, persistentVolumeClaim,
> persistentVolumeClaimWorkspaceVolume, php, phpCodeSniffer, phpStan,
> pipeline-model, pipeline-model-docker, pipelineGraphPublisher,
> pipelineMaven, pipelineTriggers, pit, plainText, plugin, pmdParser,
> podAnnotation, podEnvVar, podLabel, pollSCM, portMapping, prefast,
> preserveStashes, projectNamingStrategy, protoLint, proxy, pruneTags,
> publishCoverage, publishEvent, puppetLint, pyDocStyle, pyLint,
> qacSourceCodeAnalyser, queueItemAuthenticator, quietPeriod, rateLimit,
> rateLimitBuilds, recipients, recordIssues, regex, requestor,
> resharperInspectCode, resourceRoot, retainOnlyVariables, rfLint,
> robocopy, ruboCop, run, runDirectoryComponent, runParam, s3,
> saucePublisher, scala, schedule, scmRetryCount, script,
> scriptApproval, scriptApprovalLink, search, secretEnvVar,
> secretVolume, security, shell, simian, simple-theme-plugin,
> simpleBuildDiscarder, simpleEvent, simpleMatch, skipDefaultCheckout,
> skipStagesAfterUnstable, skipped, slave, snapshotDependencies,
> sonarQube, sourceFiles, sourceRegexFilter, sourceWildcardFilter,
> sphinxBuild, spotBugs, spotbugsPublisher, sshPublicKey,
> sshUserPrivateKey, standard, status, string, stringParam, styleCop,
> sunC, suppressAutomaticTriggering, swapSpace, swiftLint, tag, tagList,
> taskScanner, taskingVx, teamSlugFilter, text, textParam,
> threadDumpsComponent, throttleJobProperty, tiCss, timestamper,
> timestamperConfig, timezone, tmpSpace, tnsdl, toolLocation,
> triggeredBy, trustInitial, tsLint, unsecured, untrusted, upstream,
> upstreamDevelopers, url, usageStatisticsCloudBees, userSeed,
> usernameColonPassword, usernamePassword, viewsTabBar, warningsParsers,
> warningsPlugin, weather, wildcards, withAnt, withAwsCli,
> withSonarQubeEnv, x509ClientCert, xUnitDotNet, xlc, xmlLint, yamlLint,
> yuiCompressor, zfs, zip, zptLint] or globals [btools, currentBuild,
> currentJob, docker, duration, env, generateTestGroup, jenkins, log,
> mailer, mavenBuild, params, pipeline, runTestGroup, scm, shell, slack]
> 11:49:33 at
> org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:202)
> 11:49:33 at
> org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
> 11:49:33 at sun.reflect.GeneratedMethodAccessor1136.invoke(Unknown
> Source) 11:49:33 at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
> 11:49:33 at java.lang.reflect.Method.invoke(Method.java:498)
> 11:49:33 at
> org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
> 11:49:33 at
> groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)

Related

Getting error with Toaster form using cypress end 2 end

I am new in the use of cypress, which makes me face concern.
I would like to automate actions in order to test some Progressive Web App (PWA) and so I have recorded actions using the cypress extension of google chrome and when I create specs in cypress locally in order to reproduce the captures, I get errors especially when I am facing toasters.
cy.get('.h-full > #app > .layout--full > div > .hover\\3Aopacity-90').click()
cy.get('#app > .layout > .my-10 > .list-item:nth-child(3) > .text').click()
**cy.get('.h-full > #app > .pt-4 > .transform > .svg-inline--fa').click()**
cy.wait(15000)
cy.get('.form > .flex > div > .mt-6 > #mark').click()
cy.get('.form > .flex > div > .mt-6 > #mark').select('other')
The toaster pops up and then I get this error.
I even added a wait but without success

How can I ask gradle for the value of a property from the command line?

For example, if I wanted a shell script to be able to get the value of rootProject.name, how could I do this? Ideally, I'd like to invoke ./gradlew with some set of arguments and have it print the property value (and nothing else) to stdout.
For clarity, here is my Gradle wrapper version:
$ ./gradlew --version
------------------------------------------------------------
Gradle 5.4.1
------------------------------------------------------------
Build time: 2019-04-26 08:14:42 UTC
Revision: 261d171646b36a6a28d5a19a69676cd098a4c19d
Kotlin: 1.3.21
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 11.0.2 (Oracle Corporation 11.0.2+9-LTS)
OS: Mac OS X 10.14.4 x86_64
This is an existing task to give you an idea of the properties available:
$ ./gradlew properties
> Task :properties
------------------------------------------------------------
Root project
------------------------------------------------------------
allprojects: [root project 'myProject', project ':otherProject', ...]
...
rootDir: /path/to/rootDir
rootProject: root project 'myProject'
...
version: 2.3.0
...
Here is a custom task I've built to print out a project property
class ResolveProperties extends DefaultTask {
#Input
String prop
ResolveProperties() {
// if no --prop=<property> is provided, default to spitting out all properties
prop = "properties"
}
#Option(option = 'prop', description = 'Set the property to be evaluated for the project.')
void setProp(final String prop) {
this.prop = prop
}
#TaskAction
void resolveProp() {
List<String> propPath = this.prop.tokenize('.')
int n = propPath.size()
def currentProp = project
propPath.eachWithIndex { p, i ->
if(currentProp.hasProperty(p)) {
currentProp = currentProp.property(p)
}
else {
throw new GradleException("failed to resolve property: ${this.prop}")
}
}
println "${this.prop} -> ${currentProp}"
}
}
task resolveProperties(type: ResolveProperties)
And this is how I use my custom task with a --prop parameter (indicated by #Option(option = 'prop'. I'm using the -q (quiet) Gradle option to suppress some of the extra output.
$ ./gradlew -q resolveProperties --prop=rootProject.name
rootProject.name -> onestop
resolveProperties took 0 seconds
$ ./gradlew -q resolveProperties --prop=rootProject.version
rootProject.version -> 2.3.0
resolveProperties took 0 seconds
$ ./gradlew -q resolveProperties --prop=rootProject.group
rootProject.group -> org.cedar.onestop
resolveProperties took 0 seconds
Because we are throwing a GradleException when we can't find the property, in Bash you can check the return code of the command to know when to parse out the value. The formatting of a successful output is up to you and you could make it easily parsed.
$ ./gradlew -q resolveProperties --prop=does.not.exist
resolveProperties took 0 seconds
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/elliott/Documents/GitHub/onestop/build.gradle' line: 259
* What went wrong:
Execution failed for task ':resolveProperties'.
> failed to resolve property: does.not.exist
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
In case of a failure like the one above, we get a non-zero return code in Bash, and we know we don't need to try and parse out the value:
$ echo $?
1
Unfortunately, I don't know a simple way in Gradle to only give the value you are concerned with to stdout (prevent some parsing), but this gets you most of the way there with some flexibility.
If it is still relevant ...
Possible Solution A: print value of "rootProject.name" on cmd line
Add task in build.gradle:
/**
* Prints value of property "rootProject.name" to stdout.
*
* Usage: ./gradlew -q printRootProjectName
*/
task printRootProjectName {
doLast {
println(project.findProperty('rootProject').name)
}
}
Possible Solution B: print a property value as provided on cmd line
Add task in build.gradle:
/**
* Print value of property provided in "-Pprop" on command line to stdout.
*
* Usage Example: ./gradlew -q printProperty -Pprop=rootProject.name
*/
task printProperty {
doLast {
// get the "property name" in question from commandline:
String prop = project.findProperty('prop')
if (prop == null) {
return // or use println ...
}
// treat as property name:
Object theProperty = project.findProperty(prop)
if (null == theProperty) {
// try to handle provided information as "nested property"
List < String > thePropPath = prop.split('\\.').toList()
theProperty = project.findProperty(thePropPath.head())
// aux. closure to travel "property path"
def pp = {
s,
t - >
if (s != null && s.hasProperty(t).is(true)) {
return s.property(t)
}
return null
}
thePropPath.tail().each {
item - >
theProperty = pp(theProperty, item)
}
}
println(theProperty ? : "") // or print "null" ...
}
}

Multiple #EnsuresNonNullIf should be ok; but the compiler complains

The manual of the Checker Framework claims "You can write multiple #EnsuresNonNullIf annotations on a single method", however I observe the following message if I try this:
#EnsuresNonNullIf(expression="getFieldNames()", result=true)
#EnsuresNonNullIf(expression="getFieldName(i)", result=true)
public boolean hasFieldNames() {
return fFieldNames != null;
}
The resulting error message by the Eclipse Java compiler:
Duplicate annotation of non-repeatable type #EnsuresNonNullIf. Only annotation types marked #Repeatable can be used multiple times at one target.
The resulting error message by the MVN javac compiler:
[ERROR] Blabla.java:[?,?] org.checkerframework.checker.nullness.qual.EnsuresNonNullIf is not a repeatable annotation type
I'm annotating 10-year-old code, so I'm hoping some configuration trick can safe the day :-) Without the multiple #EnsuresNonNullIf I'm up for quite a bit of manual code annotation to fix false positives that I'm not interested in...
PS: I tried using both checker-framework-2.8.1 and 2.9.0 with similar results, and always using <maven.compiler.source>1.8</maven.compiler.source>
I found this issue on the Checker Framework issue tracker: https://github.com/typetools/checker-framework/issues/1307
It explains an "enhancement" request for adding #Repeatable to the following CF annotations:
> #DefaultQualifier -- DONE
> #EnsuresKeyFor
> #EnsuresKeyForIf
> #EnsuresLockHeldIf
> #EnsuresLTLengthOf
> #EnsuresLTLengthOfIf
> #EnsuresMinLenIf
> #EnsuresNonNullIf
> #EnsuresQualifier -- DONE
> #EnsuresQualifierIf -- DONE
> #FieldInvariant
> #GuardSatisfied
> #HasSubsequence
> #MethodVal
> #MinLenFieldInvariant
> #RequiresQualifier -- DONE
> #SubstringIndexFor
And the discussion contains a workaround, since EnsuresQualifiersIf is already repeatable:
#EnsuresQualifiersIf({
#EnsuresQualifierIf(result=true, qualifier=NonNull.class, expression="getFoo()"),
#EnsuresQualifierIf(result=false, qualifier=NonNull.class, expression="getBar()")
})
boolean hasFoo();
And in my case that works out to:
#EnsuresQualifiersIf({
#EnsuresQualifierIf(result=true, qualifier=NonNull.class, expression="getFieldNames()"),
#EnsuresQualifierIf(result=true, qualifier=NonNull.class, expression="getFieldName(i)")
})
public boolean hasFieldNames() {
return fFieldNames != null;
}

Returning Boolean value in Groovy function when Maven build fails in shell script

I have wrote a Jenkins Pipeline Groovy for executing multiple project maven sonar analysis. The code is working fine but the issue is that sometimes build fails for some projects which I need to track it properly. My executeMavenSonarBuild function is given as below
def executeMavenSonarBuild(projectName) {
stage ('Execute Maven Build for '+projectName)
{
sh """ {
cd ${projectName}/
mvn clean install verify sonar:sonar
} || {
echo 'Build Failed'
}
"""
}
return true;
}
If build fails it prints echo 'Build Failed' but how we can return a false Boolean as the return to the function.
You have to get the status from the mvn call itself..which should look like this:
def result = sh ( script: 'mvn ...', returnStatus: true)

Gradle: How to run test with status each line?

When I run gradle test, it output as following:
:test
> Building 80% > :test > 86 tests completed
and it rewrite the line > Building 80% > :test > 86 tests completed as it's progressing forward.
What I want is to prevent gradle from replacing this line and make it output line by line, for example:
:test
:test > 86 tests completed
:test > 87 tests completed
:test > 88 tests completed
Is there any way to do this?
You can configure the test block
apply plugin: 'java'
repositories {
jcenter()
}
dependencies {
testCompile 'junit:junit:4.12'
}
test {
// show standard out and standard error of the test JVM(s) on the console, without this
// the text output printed by the tests won't show.
// ref: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.testing.Test.html
testLogging.showStandardStreams = true
def testCount = 0
afterTest { descriptor, result ->
// descriptor is of type TestDescriptor, result is of type TestResult
// ref: https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/testing/TestDescriptor.html
// ref: https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/testing/TestResult.html
logger.lifecycle("Test {count: ${++testCount} name: $descriptor.name result: $result.resultType}")
}
}
Then you will see your output during the test task. Of course you could us another logging level depending on what you want but info, debug, error are also available. The lifecycle will always show, unless -q command line arg is passed.
$ ./gradlew clean test
Configuration on demand is an incubating feature.
:clean
:compileJava
:processResources UP-TO-DATE
:classes
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
Test {count: 1 name: testSomeLibraryMethod result: SUCCESS}
BUILD SUCCESSFUL
Total time: 1.229 secs

Resources