Unable to resolve class com.cloudbees.hudson.plugins.folder.Folder - java

I am trying to gather data from jenkins using groovy script and getting an error:
unable to resolve class com.cloudbees.hudson.plugins.folder.Folder
Below is the code:
import jenkins.model.*
import hudson.model.*
import groovy.time.TimeCategory
use ( TimeCategory ) {
// e.g. find jobs not run in last 1 year
sometimeago = (new Date() - 1.year)
}
jobs = Jenkins.instance.getAllItems()
lastabort = null
jobs.each { j ->
if (j instanceof com.cloudbees.hudson.plugins.folder.Folder) { return }
numbuilds = j.builds.size()
if (numbuilds == 0) {
println 'JOB: ' + j.fullName
println ' -> no build'
return
}
lastbuild = j.builds[numbuilds - 1]
if (lastbuild.timestamp.getTime() < sometimeago) {
println 'JOB: ' + j.fullName
println ' -> lastbuild: ' + lastbuild.displayName + ' = ' + lastbuild.result + ', time: ' + lastbuild.timestampString2
}
}
The error is:
rg.codehaus.groovy.control.MultipleCompilationErrorsExceptio‌​n:
startup failed: Script1.groovy: 12: unable to resolve class
com.cloudbees.hudson.plugins.folder.Folder # line 12, column 20. if (j
instanceof com.cloudbees.hudson.plugins.folder.Folder) { return } ^ 1
error at
org.codehaus.groovy.control.ErrorCollector.failIfErrors(Erro‌​rCollector.java:302)

I see Folder.java in jenkinsci/cloudbees-folder-plugin.
That means you need to:
check if you do have JENKINS/CloudBees Folders Plugin installed, or your groovy script would not be able to resolve that dependency.
Add "import com.cloudbees.hudson.plugins.folder.*" to be sure the script is able to make the instanceOf work.

When running groovy scripts that import libraries in Jenkins, check that your Jenkins build step is an "Execute system Groovy script", not a plain old "Execute Groovy script".
The 'system' scripts run on the existing JVM, as opposed to spawning a new one and therefore losing access to the shared libraries available to the original Jenkins JVM instance.
Groovy Script vs System Groovy Script - https://plugins.jenkins.io/groovy/

Related

vscode coderunner has trouble executing java code

I have the following structure:
java_projects > chapter9
usually i cd to a directory a level above java_projects, and do code java_projects to create a workspace directory from that location. Now, inside chapter 9, i have the folloiwng files:
Tv.java, TestTv.java
Inside TestTv.java i have the following code:
package chapter9;
public class TestTv {
public static void main(String[] args){
Tv tv = new Tv();
tv.turnOn();
tv.setChannel(30);
tv.setVolume(3);
System.out.println("Tv channel is: " + tv.channel);
// testing java date class
java.util.Date date = new java.util.Date();
System.out.println("time elapsed since jan 1, 1970 is: " + date.getTime() + "milliseconds");
System.out.println(date.toString());
}
}
when i run this via code-runner, i get the following error:
TestTv.java:5: error: cannot find symbol
Tv tv = new Tv();
^
symbol: class Tv
location: class TestTv
TestTv.java:5: error: cannot find symbol
Tv tv = new Tv();
^
symbol: class Tv
location: class TestTv
I'm not too sure why this is happening. Upon further investigating, i learned this has to do with compiling the Tv Class first before its being used in java program. Ok, so i looked into my settings.json inside vscode and changed it to:
"java": cd $dir && javac *.java && java $fileName"
This still gives me the same error.
So i cd'd out of the chapter9 directory and tried java chapter9/TestTv.java and it worked!!
How do i tell vscode's executor map to go back one level up and execute it?
Thanks
{
"code-runner.clearPreviousOutput": true,
"code-runner.ignoreSelection": true,
"code-runner.saveAllFilesBeforeRun": true,
"java.autobuild.enabled": true,
"code-runner.fileDirectoryAsCwd": false,
"java.configuration.updateBuildConfiguration": "automatic",
"code-runner.executorMap": {
"java": "cd $dir && javac *.java && java $fileName"
},
"code-runner.runInTerminal": true,
}
Attached is my tvclass
public class Tv {
// instance variables
int channel = 1; // default channel is 1
int volumeLevel = 1;
boolean on = false; // Tv is off
public Tv(){};
public void turnOn(){
on = true;
}
public void turnOff(){
on = false;
}
public void setChannel(int newChannel){
if (on && newChannel >= 1 && newChannel <= 120)
channel = newChannel;
}
public void setVolume(int newVolumeLevel){
if (on && newVolumeLevel >= 1 && newVolumeLevel <= 7){
volumeLevel = newVolumeLevel;
}
}
public void channelUp(){
if (on && channel < 120)
channel++;
}
public void channelDown(){
if (on && channel > 1)
channel--;
}
public void volumeUp(){
if (on && volumeLevel < 7)
volumeLevel++;
}
public void volumeDown(){
if (on && volumeLevel > 1)
volumeLevel--;
}
Im looking for something like this?
"java": cd $dir && javac *.java && java (go back one directory up) $dir[my_folder_name]fileName"
so something like this...
"java": cd $dir && javac *.java && cd .. java chapter9/TestTv.java"
I don't know i can't make it any more clearer. I have a mac OSX, sierra, javaSE11. I don't think it has to do with the operating system. Its more of a compilation issue. going to the vscode's github doesn't help as they don't reply to any thing.
I am also not very familiar with the topic. I did some trial and error and managed it to work with the following:
"code-runner.executorMap": {
"java": "cd $dir && javac *.java && cd .. && java \"$(basename $dir)/$fileNameWithoutExt\""
}
Notable parts/changes:
&& cd .. moves one directory up.
$(basename $dir) returns the most inner directory. chapter9 in your example, but if you change to another directory you don't have to change it.
$fileNameWithoutExt: The base name of the code file being run without its extension, as documented here under Configuration.
I'm less familiar with this topic, but based looking at this syntax in your problem/answer and seeing the "&&" syntax as a series of scripts, it looks like you need one more "&&" in the mix so the "cd .." moves up to the parent directory BEFORE calling the java-interpreter as the last thing.
so:
"java": cd $dir && javac *.java && cd .. && java chapter9.TestTv"
Also I'm less familiar with mac requirements, but I know some systems don't mind "cd.." and some only take "cd .." with the space, so be cautious as you type it in..

ASE is terminating this process when trying to install the jar file (Msg 5702, Level 10, State 1)

I have an SAP ASE 16 server on a Windows OS.
I have enabled the java service:
sp_configure 'enable java'
Parameter Name Default Memory Used Config Value Run Value Unit Type
-------------- ----------- ----------- ------------ ------------ ------ ------
enable java 0 0 1 1 switch static
Rows affected (1) Time (0.094 s)
I have created a basic class to test the service (JDBCExamples.java):
import java.sql.*; // JDBC
public class JDBCExamples {
public static void main(String args[]){
if (args.length != 2) {
System.out.println("\n Usage: " + "name secondName \n");
return;
}
try {
String name = args[0];
String secondName = args[1].toLowerCase();
System.out.println("\n HOLA " + name + " " + secondName +" FUNCIONO!!!\n");
} catch (Exception e) {
System.out.println("\n Exception: ");
e.printStackTrace();
}
}
}
I have the class file JDBCExamples.class and I make a file JDBCExamples.jar.
When I try to install the jar file it shows the error message:
instjava -f JDBCExamples.jar -SDEFAULT -Uuser -Ppassword -Ddatabase -new
Server Message: - Msg 5702, Level 10, State 1:
ASE is terminating this process.
I don't see any in log database.
Any idea what the problem is?
Update:
I posted the same problem in https://answers.sap.com/questions/13241081/ase-is-terminating-this-process-when-trying-to-ins.html
In this post suspect the issue is caused by an ASE bug fixed in PL06:
2687973 - NTPCI__exit(1); Native Thread failed to unwind - SAP ASE http://service.sap.com/sap/support/notes/2687973
I have a trial version and I can not download a newer patch (PL06 at least but recommend PL09 as most recent)
Does anyone have this patch?

Drools Function unable to resolve method using strict-mode

I have a Drools file that I'm using for business logic on a Tomcat6 server running Java 1.7.0_131 inside a Docker container. When I run the code bellow:
package org.fosstrak.capturingapp
import org.fosstrak.capturingapp.util.Util;
import org.fosstrak.ale.xsd.ale.epcglobal.ECReport;
import org.fosstrak.ale.xsd.ale.epcglobal.ECReports;
import org.fosstrak.ale.xsd.ale.epcglobal.ECReportGroupListMember;
import org.fosstrak.ale.xsd.epcglobal.EPC;
import org.fosstrak.capturingapp.util.SimpleEPCISDocument;
import org.fosstrak.epcis.model.ActionType;
import java.util.List;
import java.util.LinkedList;
import function org.fosstrak.capturingapp.util.Util.extractEPC;
import function org.fosstrak.capturingapp.util.Util.extractReportMembers;
// the global collector for all the EPCIS documents for further processing.
global java.util.List epcisResults
function List warehouseReportHandler(List reports, String reportName){
// List of ECReports
List epcs = new LinkedList();
for(Object rs : reports){
if(rs instanceof ECReports){
ECReports rsc = (ECReports) rs;
for(ECReport report : rsc.getReports().getReport()){
if(report.getReportName() == reportName){
ecps.addAll(extractEPC(Util.selectTag, report));
}
}
}
}
return epcs;
}
rule "ADDITIONS Rule Tags from reader 'Reader_Warehouse_Shelve1' from the specName 'ECSpec'"
dialect "java"
when
$reports : ECReports( reports != null)
$epcs : LinkedList( size > 0 ) from collect (
EPC() from warehouseReportHandler($reports, "additions")
)
then
SimpleEPCISDocument simpleDocument = new SimpleEPCISDocument();
simpleDocument.addObjectEvent(
$epcs,
ActionType.OBSERVE,
"urn:epcglobal:cbv:bizstep:storing",
"urn:epcglobal:cbv:disp:sellable_not_accessible",
"urn:epc:id:sgln:76300544.00000.1",
"urn:epc:id:sgln:76300544.00000.0"
);
System.out.println("\n=====================================================");
System.out.println("Additions tags seen:");
for (Object o : $epcs) System.out.println(((EPC)o).getValue());
System.out.println("=====================================================\n");
epcisResults.add(simpleDocument.getDocument());
end
I get the following error message:
21146 [Thread-2] DEBUG org.fosstrak.capturingapp.ECReportsHandler - Unable to build expression for 'from' : Failed to compile: 1 compilation error(s):
capture | - (1,45) unable to resolve method using strict-mode: java.lang.Object.warehouseReportHandler(org.fosstrak.ale.xsd.ale.epcglobal.ECReports, java.lang.String) 'warehouseReportHandler($reports, "additions")' : [Rule name='ADDITIONS Rule Tags from reader 'Reader_Warehouse_Shelve1' from the specName 'ECSpec'']
capture | Error importing : 'org.fosstrak.capturingapp.WarehouseReportHandler.warehouseReportHandler'[ warehouseReportHandler : Function Compilation error
capture | warehouseReportHandler (line:28): ecps cannot be resolved
capture | ][ warehouseReportHandler : Function Compilation error
capture | warehouseReportHandler (line:28): ecps cannot be resolved
capture | ]Rule Compilation error : [Rule name='ADDITIONS Rule Tags from reader 'Reader_Warehouse_Shelve1' from the specName 'ECSpec'']
capture | org/fosstrak/capturingapp/Rule_ADDITIONS_Rule_Tags_from_reader__Reader_Warehouse_Shelve1__from_the_specName__ECSpec__0.java (2:489) : The import org.fosstrak.capturingapp.WarehouseReportHandler cannot be resolved
I'm new to Drools. I am not sure if it's a syntax problem.
Update: I've removed the generics I had previously and tried to follow the examples given in the project, without success. (https://github.com/Fosstrak/fosstrak/tree/master/capturingapp/trunk/src/main/resources/drools)
Thank you everyone for your time
This line
function List warehouseReportHandler(List reports, String reportName){
defines the function with the parameter as a list. However the invocation
$reports : ECReports( reports != null)
$epcs : LinkedList( size > 0 ) from collect (
EPC() from warehouseReportHandler($reports, "additions")
)
shows a parameter of type ECReports is being sent in to the method. Can you fix this and try?

Changing Java version in Bazel

I am using Bazel as the build tool for my Java project. I have JDK 11 installed on my mac, but Bazel uses Java 8 to build the binaries. Does anyone know how I could change this?
BUILD.bazel
java_binary(
name = 'JavaBinary',
srcs = ['JavaBinary.java'],
main_class = 'JavaBinary',
)
load(
"#bazel_tools//tools/jdk:default_java_toolchain.bzl",
"default_java_toolchain",
)
default_java_toolchain(
name = "default_toolchain",
visibility = ["//visibility:public"],
)
JavaBinary.java
public class JavaBinary {
public static void main(String[] args) {
System.out.println("Successfully executed JavaBinary!");
System.out.println("Version: " + System.getProperty("java.version"));
}
}
WORKSPACE.bazel
load("#bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_java",
sha256 = "220b87d8cfabd22d1c6d8e3cdb4249abd4c93dcc152e0667db061fb1b957ee68",
url = "https://github.com/bazelbuild/rules_java/releases/download/0.1.1/rules_java-0.1.1.tar.gz",
)
load("#rules_java//java:repositories.bzl", "rules_java_dependencies", "rules_java_toolchains")
rules_java_dependencies()
rules_java_toolchains()
Run it this way:
bazel run :JavaBinary \
--java_toolchain=:default_toolchain \
--javabase=#bazel_tools//tools/jdk:remote_jdk11
You can also create .bazelrc file an then execute bazel run :JavaBinary:
.bazelrc
build --java_toolchain=:default_toolchain
build --javabase=#bazel_tools//tools/jdk:remote_jdk11

Updating module version when updating version in dependencies (multi-module maven )

My problem: versions-maven-plugin helps me to up version in some module (let's call it A) in my multi-module maven project.
Some modules (let's call it B and C) in this project have in dependencies module A. I need to up versions for this modules (B and C) too. Sometimes, i also need to up version in other module (B-parent) where B (or C) in dependencies (A version up -> B version up -> B-parent version up). Other problem is the modules can be at different levels of nesting.
Example:
root:
---B-parent:
---B (A in dependencies)
---C-parent
---C (A in dependencies)
---A-parent:
---A
Process: A version up -> A-parent version up, C version-up -> C-parent version-up, B version-up -> B-parent version up.
This plugin can't do this.
Is there any idea how this can be done?
Or my strategy of updating versions is not good enough?
I've made a script for increasing version numbers in all dependent modules recursively with a versions-maven-plugin.
Algorithm is as follows:
Run versions:set in target module
Run versions:set in all modules which have been updated by versions:set from previous step. If the module has been already processed - skip it.
Repeat step 2
Python 2.7 code
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
# How To
#
# Run script and pass module path as a first argument.
# Or run it without arguments in module dir.
#
# Script will request the new version number for each module.
# If no version provided - last digit will be incremented (1.0.0 -> 1.0.1).
# cd <module-path>
# <project-dir>/increment-version.py
# ...
# review changes and commit
from subprocess import call, Popen, PIPE, check_output
import os
import re
import sys
getVersionCommand = "mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate " \
"-Dexpression=project.version 2>/dev/null | grep -v '\['"
def getCurrentModuleVersion():
return check_output(getVersionCommand, shell=True).decode("utf-8").split("\n")[0]
def incrementLastDigit(version):
digits = version.split(".")
lastDigit = int(digits[-1])
digits[-1] = str(lastDigit+1)
return ".".join(digits)
def isUpdatedVersionInFile(version, file):
return "<version>" + version + "</version>" in \
check_output("git diff HEAD --no-ext-diff --unified=0 --exit-code -a --no-prefix {} "
"| egrep \"^\\+\"".format(file), shell=True).decode("utf-8")
def runVersionSet(version):
process = Popen(["mvn", "versions:set", "-DnewVersion="+version, "-DgenerateBackupPoms=false"], stdout=PIPE)
(output, err) = process.communicate()
exitCode = process.wait()
if exitCode is not 0:
print "Error setting the version"
exit(1)
return output, err, exitCode
def addChangedPoms(version, dirsToVisit, visitedDirs):
changedFiles = check_output(["git", "ls-files", "-m"]) \
.decode("utf-8").split("\n")
changedPoms = [f for f in changedFiles if f.endswith("pom.xml")]
changedDirs = [os.path.dirname(os.path.abspath(f)) for f in changedPoms if isUpdatedVersionInFile(version, f)]
changedDirs = [d for d in changedDirs if d not in visitedDirs and d not in dirsToVisit]
print "New dirs to visit:", changedDirs
return changedDirs
if __name__ == "__main__":
visitedDirs = []
dirsToVisit = []
if len(sys.argv) > 1:
if os.path.exists(os.path.join(sys.argv[1], "pom.xml")):
dirsToVisit.append(os.path.abspath(sys.argv[1]))
else:
print "Error. No pom.xml file in dir", sys.argv[1]
exit(1)
else:
dirsToVisit.append(os.path.abspath(os.getcwd()))
pattern = re.compile("aggregation root: (.*)")
while len(dirsToVisit) > 0:
dirToVisit = dirsToVisit.pop()
print "Visiting dir", dirToVisit
os.chdir(dirToVisit)
currentVersion = getCurrentModuleVersion()
defaultVersion = incrementLastDigit(currentVersion)
version = raw_input("New version for {}:{} ({}):".format(dirToVisit, currentVersion, defaultVersion))
if not version.strip():
version = defaultVersion
print "New version:", version
output, err, exitcode = runVersionSet(version)
rootDir = pattern.search(output).group(1)
visitedDirs = visitedDirs + [dirToVisit]
os.chdir(rootDir)
print "Adding new dirs to visit"
dirsToVisit = dirsToVisit + addChangedPoms(version, dirsToVisit, visitedDirs)

Categories

Resources