Using an external Groovy file with Jenkins pipeline - java

I have two questions here regarding Jenkins pipeline and Groovy methods. Firstly I have multiple build that share common methods so thought best to have all these in a single class and then import the file for each build.
A snippet from my Groovy script looks like
import groovy.json.JsonSlurperClassic;
import groovy.json.JsonSlurper;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.HashSet;
import java.util.Set;
import java.io.Serializable;
Map get_var() {
def gradleVars = readFile "${env.WORKSPACE}/gradle-client/gradle.properties"
Properties properties = new Properties();
InputStream is = new ByteArrayInputStream(gradleVars.getBytes());
properties.load(is)
def sdk_version = "SDKVersion"
def SDK_VERSION = properties."$sdk_version"
return [sdk_version: "$SDK_VERSION"}
}
And in my pipeline script I have
def groovyMethod = load("release_pipeline.groovy")
// Call method
groovyMethod.getVar()
The first problem I have is how do I use ${env.WORKSPACE} within my method, and secondly how do I use readFile within my script as I get the error
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: Helpers.readFile()
I am really new to Groovy and Java.

Would you please try the below :
def getVar() {
def properties = new Properties()
File propertiesFile = new File("${System.getenv['WORKSPACE']}/gradle-client/gradle.properties")
properties.load(propertiesFile.newDataInputStream())
return [sdk_version: properties.SDKVersion]
}
May be it appears that, you have different method name get_var() and you are trying to use getVar().
And I am not really sure where that error coming from above script
groovy.lang.MissingMethodException: No signature of method: Helpers.readFile()
EDIT: based on OP comment
Please see if the this helps:
def workspace = Thread.currentThread().executable.workspace.toString()

Related

is it normal that the AclEntry.add () method does not change a permanent access permission?

I tried to add a read permission for a given file to a user on windows 10 using the AclEntry.add () method in java, the process runs normally. However, this change does not occur in windows.
I want to know if this method should assign permission permanently or only during the execution of the program.
NOTE: I am using the AclFileAttributeView interface of the Nio.File package.
In addition I packaged this jar using Launch4j to be able to run it as an administrator.
below the code I'm using.
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.*;
import java.util.List;
public class Inicial {
public Inicial() throws IOException {
Path path = Paths.get("C:\\Windows\\System32\\config\\journal");
UserPrincipal usercop =
FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName("Gilderlei");
AclFileAttributeView aclFileAttributeView = Files.getFileAttributeView(path,
AclFileAttributeView.class);
List<AclEntry> aclEntries = aclFileAttributeView.getAcl();
AclEntry.Builder aclEntry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(usercop)
.setPermissions(AclEntryPermission.READ_DATA);
AclEntry entry = aclEntry.build();
aclEntries.clear();
aclEntries.add(entry);
}
public static void main(String[] args) throws IOException {
new Inicial();
}
}
You just add the created permission to the aclEntries list. Java is not an ORM mapped system that automatically writes back any data changes.
Therefore you have to call at least setAcl
aclFileAttributeView.setAcl(aclEntries);
at the end of your code.

Java program not working using the command line

Short story :
When I run my java application through the Intellij it's all working.
When I run it through the command line I have some issues.
Long story:
First, I have to say that I have a 'lib' folder inside my project with all the Jars I need and I added it as a Library to the project.
When I compile it from the command line I have to specify a '-cp' to the lib folder, otherwise it doesn't load the jars. Even though it looks good, when I run my java application, I get a 'Error: Could not find or load main class awsUpdater' error
My commands :
For compiling -
javac -cp "../../../../lib/*" awsUpdater.java
For executing -
java -cp "../../../../lib/*" awsUpdater
Here's my class (besides the methods)
package AWSUpdater;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class awsUpdater {
public static void main(String[] args) throws IOException {
String bucketName = "bucket";
String key = "ket";
//AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
AmazonS3 s3Client = new AmazonS3Client(DefaultAWSCredentialsProviderChain.getInstance());
System.out.println("Downloading an object");
S3Object s3object = s3Client.getObject(new GetObjectRequest(
bucketName, key));
//Get new version of android
String newAndroidVersion = getNewAndroidVersion();
//Download current versions.json
String currentJson = displayTextInputStream(s3object.getObjectContent());
//Edit versions.json with new android version
String editedJson = editJsonWithCurrentAndroidVersion(currentJson, newAndroidVersion);
//String editedJson = editJsonDummyCheck(currentJson);
//Create new file to upload to S3
createFileWithNewJson(editedJson);
//Upload new file to S3
updateVersion(bucketName, key, "versions.json");
}
Would appreciate any help with how to compile and execute my program through the command line. thanks !
you need to add package name
java -cp "../../../../lib/*" AWSUpdater.awsUpdater
I notice that the class awsUpdater is under the package AWSUpdater, so you can not use java -cp "../../../../lib/*" awsUpdater directly.
For Example:
I create a project like this:
|-test
|-AWSUpdater
|-awsUpdater.java
Detail of the awsUpdater.java:
public class awsUpdater {
public static void main(String[] args) {
System.out.println("hello");
}
}
then(now I'm in test/AWSUpdater):
javac awsUpdater.java
java awsUpdater
Everything goes well!
If I add the class to the package, like this:
package AWSUpdater;
public class awsUpdater {
public static void main(String[] args) {
System.out.println("hello");
}
}
then(now I'm in test/AWSUpdater):
javac awsUpdater.java
java awsUpdater
here, it will got the error which is same with yours.
Now, you can go to the package's root dir. (here is test), and then:
javac AWSUpdater/awsUpdater.java
java AWSUpdater/awsUpdater
Now, you will get the correct result.

Unable to import a Scala object into the Java project

I created a Scala object:
package myapp.data
import java.io.File
import myapp.models.NodeViewModel
import com.thoughtworks.xstream.XStream
import com.thoughtworks.xstream.io.xml.DomDriver
object ForumSerializer {
def openFile(file : File) : NodeViewModel = {
// doing something
}
def saveToFile(model : NodeViewModel) : Unit = {
// doing something
}
}
Then I tried to import it in another Java file
import myapp.ForumSerializer;
The error I get is:
Import myapp.ForumSerializer cannot be resolved.
What am I doing wrong?
Import it as ForumSerializer$.
Scala adds a $, so the compiler doesn't get confused with the class, when you have both an object and a class of the same name. You can then access the singleton object using the generated MODULE$.

Instantiating object in Python same as Java using jython

In Java I was able to run my code as:
(This are just sample naming)
import com.projectname.api.APIOne;
import com.projectname.api.APITwo;
import com.projectname.api.APIThree;
import com.projectname.api.APIFour;
import com.projectname.api.MainAPI;
public class TestMain {
public static void main(String[] args) {
APIOne a = APIOne.getName();
APITwo b = APIThree.getAddress();
APIFour d = b.getEmail();
MainAPI mainapi = new MainAPI();
mainapi.setEmail(d)
}
}
It is running okay, I tried converting this to Python as:
import com.projectname.api.APIOne as APIOne;
import com.projectname.api.APITwo as APITwo;
import com.projectname.api.APIThree as APIThree;
import com.projectname.api.APIFour as APIFour;
def test():
a = APIOne.getName();
b = APIThree.getAddress();
d = b.getEmail();
mainapi = MainAPI();
mainapi.setEmail(d)
test()
But is this the right way of instantiating? It make me confuse on instantiating.
Hope you could help me.
Importing a class from a java package or python module is normally written as:
from java.lang import Math
Rather than:
import java.lang.Math as Math
But, your code is correct.
I don't understand why you are confused, but this is correct, you could check the Jython documentation about instantiating Java objects using Jython and instantiates the objects the same way as you do.

Post data from Matlab to Pachube (Cosm) using Java Methods

I am using JPachube.jar and Matlab in order to send data to my datastream. This java code works on my machine:
package smartclassroom;
import Pachube.Data;
import Pachube.Feed;
//import Pachube.FeedFactory;
import Pachube.Pachube;
import Pachube.PachubeException;
public class SendFeed {
public static void main(String arsg[]) throws InterruptedException{
SendFeed s = new SendFeed(0.0);
s.setZainteresovanost(0.3);
double output = s.getZainteresovanost();
System.out.println("zainteresovanost " + output);
try {
Pachube p = new Pachube("MYAPIKEY");
Feed f = p.getFeed(MYFEED);
f.updateDatastream(0, output);
} catch (PachubeException e) {
System.out.println(e.errorMessage);
}
}
private double zainteresovanost;
public SendFeed(double vrednost) {
zainteresovanost = vrednost;
}
public void setZainteresovanost(double vrednost) {
zainteresovanost = vrednost;
}
public double getZainteresovanost() {
return zainteresovanost;
}
}
but I need to do this from Matlab. I have tried rewriting example (example from link is working on my machine): I have compile java class with javac and added JPachube.jar and SendFeed.class into path and then utilize this code in Matlab:
javaaddpath('C:\work')
javaMethod('main','SendFeed','');
pachubeValue = SendFeed(0.42);
I get an error:
??? Error using ==> javaMethod
No class SendFeed can be located on Java class path
Error in ==> post_to_pachube2 at 6
javaMethod('main','SendFeed','');
This is strange because, as I said example from the link is working.
Afterwards, I decided to include JPachube directly in Matlab code and to write equivalent code in Matlab:
javaaddpath('c:\work\JPachube.jar')
import Pachube.Data.*
import Pachube.Feed.*
import Pachube.Pachube.*
import Pachube.PachubeException.*
pachube = Pachube.Pachube('MYAPIKEY');
feed = pachube.getFeed(MYFEED);
feed.updateDatastream(0, 0.54);
And I get this error:
??? No method 'updateDatastream' with matching signature found for class 'Pachube.Feed'.
Error in ==> post_to_pachube2 at 12
feed.updateDatastream(0, 0.54);
So I have tried almost everything and nothing! Any method making this work will be fine for me. Thanks for help in advance!
This done trick for me (answer from here)
javaaddpath('c:\work\httpcore-4.2.2.jar');
javaaddpath('c:\work\httpclient-4.2.3.jar');
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
httpclient = DefaultHttpClient();
httppost = HttpPost('http://api.cosm.com/v2/feeds/FEEDID/datastreams/0.csv?_method=put');
httppost.addHeader('Content-Type','text/plain');
httppost.addHeader('X-ApiKey','APIKEY');
params = StringEntity('0.7');
httppost.setEntity(params);
response = httpclient.execute(httppost);
I would rather use built-in methods. Matlab hasurlread/urlwrite, which could work if all you wish to do is request some CSV data from Cosm API. If you do need to use JSON, it can be handled in Matlab via a plugin.
Passissing the Cosm API key, that can be done via key parameter like so:
cosm_feed_url = "https://api.cosm.com/v2/feeds/61916.csv?key=<API_KEY>"
cosm_feed_csv = urlread(cosm_feed_url)
However, the standard library methods urlread/urlwrite are rather limited. In fact, the urlwrite function is only designed for file input, and I cannot even see any official example of how one could use a formatted string instead. Creating a temporary file would reasonable, unless it's only a few lines of CSV.
You will probably need to use urlread2 for anything more serious.
UPDATE: it appears that urlread2 can be problematic.

Categories