I had to add a job in a multibranch pipeline.
The goal was to automatically install a plugin in jira.
The code runs perfectly fine because I tested it in a Unit Test.
But when I put it as a scripted pipeline on Jenkins, it does not do what it should do.
The goal is to install the plugin on jira, but when I run it on Jenkins it will not be installed.
Also I do not get any json Response, which I get in my JUnit Test.
I really do not know what is different on Jenkins. I already found it weird that I have to approve every single method in my script. Did someone have a similar issue on jenkins before.
I really appreciate your help.
#Test
public void test_install_plugin() throws IOException {
String jsonBody = "{\"pluginUri\": \"http://myServer/job/element/job/mybranch\", \"pluginName\": \"myPlugin\"}";
String token = "-6485649001990379871";
String jiraPath="myServer/rest/plugins/1.0/";
String query = "token="+token;
String url = jiraPath+"?"+query;
URL jiraURL = new URL(url);
HttpURLConnection jiraURLConnection = (HttpURLConnection)jiraURL.openConnection();
jiraURLConnection.setDoOutput(true);
jiraURLConnection.setDoInput(true);
jiraURLConnection.setRequestProperty ("Content-Length",String.valueOf(jsonBody.length()));
jiraURLConnection.setRequestProperty ("Accept", "application/json");
jiraURLConnection.setRequestProperty ("Content-Type", "application/vnd.atl.plugins.install.uri+json");
jiraURLConnection.setRequestProperty ("Authorization", "Basic YWRXXXXXXtaW4=");
jiraURLConnection.setRequestMethod("POST");
OutputStream os = null;
try {
os = jiraURLConnection.getOutputStream();
byte[] input = jsonBody.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
}
catch(IOException ex)
{
System.out.println("Exception: " + ex.getMessage());
}
finally
{
os.close();
System.out.println("responseCode of install request: " + jiraURLConnection.getResponseCode());
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(jiraURLConnection.getInputStream(), "utf-8"));
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response: " + response.toString());
}
catch(IOException ex)
{
System.out.println("Exception: " + ex.getMessage());
}
finally
{
br.close();
jiraURLConnection.disconnect();
}
}
Related
I'm trying to run scheduled Groovy script on Jenkins but I got into some trouble - It won't finish runnning although it reaches the "return" statement.
I'm using in-house dependencies and Classes and I've found the line of code that if omitted, the script returns successfully. But I can't omit this line unfortunately :(
Do you have any idea what could cause a Jenkins build step too stay stuck?
I've noticed that the "culprit" line of code, internally runs the following:
this.executorService.scheduleWithFixedDelay(this.eventsPublisher, 3L, 3L, TimeUnit.SECONDS);
Is it possible that playing with the Executor, messes around with the Jenkins build steps?
I'd love some help,
Thanks a lot :)
UPDATE:
Code:
import java.sql.DriverManager
import java.sql.ResultSet
import java.text.DateFormat
import java.text.SimpleDateFormat
import hudson.model.*
def verticaConn = null
def verticaStmt = null
def mongoConnection = null
try {
println("start script: vertica_to_kafka")
// get params
def verticaHostName = System.getenv("verticaHostName") //dev=192.168.247.11:5433 prod=192.168.251.120:5433
def verticaDbName = System.getenv("verticaDbName")
def verticaTBName = System.getenv("verticaTBName")
def bootstrapServers = System.getenv("bootstrapServers")
def limitNum = System.getenv("limitNum").toInteger()
def startTime = System.getenv("startTime")
MyKafkaStringProducer producer = new MyKafkaStringProducer();
producer.init()
MyEventDao eventDao = new MyEventDao();
eventDao.setStringProducer(stringProducer);
Class.forName("com.vertica.jdbc.Driver")
String verticaConnectionString = "jdbc:vertica://${verticaHostName}/${verticaDbName}"
Properties verticaProp = new Properties();
verticaProp.put("user", "user");
verticaProp.put("password", "password");
verticaProp.put("ConnectionLoadBalance", 1);
verticaConn = DriverManager.getConnection(verticaConnectionString, verticaProp);
verticaStmt = verticaConn.createStatement()
// vertica execution timestamp
long currentTS = System.currentTimeMillis()
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startTS = "1970-01-01 00:00:00";
String command= "select * from ${verticaTBName} where ts >'${startTS}' "
if (limitNum > 0) command += "limit ${limitNum}"
println("querying vertica")
verticaStmt.execute(command)
ResultSet results = verticaStmt.getResultSet()
println("start to send data to kafka")
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
while(results.next()){
long id = results.getLong("id");
String domain = results.getString("domain");
String text = results.getString("text");
Date ts = dateFormat.parse(results.getString("ts"));
MyEntity myEntity = new MyEntity(id, domain, text, ts);
eventDao.saveEntity(myEntity);
}
} catch (Exception e){
println(e.printStackTrace())
} finally {
println("going to release resources");
if (verticaStmt != null){
try{
verticaStmt.close()
println("vertica statement closed successfully!");
} catch (Exception e) {
//println("error in close the vertica statement {}", e.getMessage());
}
}
if (verticaConn != null){
try{
verticaConn.close()
println("vertica connection closed successfully!");
} catch (Exception e) {
//println("error in close the vertica connection {}", e.getMessage());
}
}
if (mongoConnection != null){
try {
mongoConnection.getMongo().close();
println("mongo connection closed successfully!");
} catch (Exception e) {
//println("error in close the mongo connection {}", e.getMessage());
}
}
println("end script: vertica_to_kafka")
}
return
System.exit(0)
And in MyKafkaStringProducer I found the following:
public synchronized void init() {
if(this.active) {
this.initKafkaProducer();
this.executorService.scheduleWithFixedDelay(this.eventsPublisher, 3L, 3L, TimeUnit.SECONDS);
}
}
How to parse.Pst file using apache tika
1.2?
How can I get entire body, attachment, and all Metadata of email while searching with ljcene?
for (File file : docs.listFiles()) {
Metadata metadata = new Metadata();
ContentHandler handler = new BodyContentHandler();
ParseContext context = new ParseContext();
Parser parser = new AutoDetectParser();
InputStream stream = new FileInputStream(file);
try {
parser.parse(stream, handler, metadata, context);
}
catch (TikaException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
If you're stuck with 1.2, you might try the recommendation here
If you're able to upgrade, we added that as the RecursiveParserWrapper in 1.7 ...just upgrade to 1.12 if you can, or wait a week or two and 1.13 should be out.
Via commandline:
java -jar tika-app.jar -J -t -i input_directory -o output_directory
Or in code:
Parser p = new AutoDetectParser();
RecursiveParserWrapper wrapper = new RecursiveParserWrapper(p,
new BasicContentHandlerFactory(
BasicContentHandlerFactory.HANDLER_TYPE.XML, -1));
try (InputStream is = Files.newInputStream(file)) {
wrapper.parse(is, new DefaultHandler(), new Metadata(), context);
}
int i = 0;
for (Metadata metadata : wrapper.getMetadata()) {
for (String name : metadata.names()) {
for (String value : metadata.getValues(name)) {
System.out.println(i + " " + name +": " + value);
}
}
i++;
}
How to solve this, help me out I'm new
Please explain your question... If you want to fetch from http, below code will help you. you may need to add some libraries too.
HttpClient httpclient = new DefaultHttpClient();
Httppost httppost = new HttpPost("www.example.com");
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
JSONObject jsonObj = new JSONObject(result);
continue your code after this...
Add the libraries to the gradle file.
Look for this line:
dependencies {
...
}
and add this:
dependencies {
...
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4'
}
In my application i have to integrate API. I am not getting code for how to check whether internet is available or not. How to send JSON Data to server. Please help me out. As in android we call API in AsyncTask class. In blackberry i did not found like this.
Suggest me some link or ideas so that i can integrate code. I am googling. But did not getting result .
What I have tried is here:
JSONObject postData = new JSONObject();
postData.put("userId", "24");
postData.put("messageTime","06:00:00");
postData.put("language", language[lang_Ocf.getSelectedIndex()]);
System.out.println("********json********"+postData);
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
conDesc = conFactory.getConnection(url+";deviceside=true");
}
catch(Exception e)
{
System.out.println(e.toString()+":"+e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if(null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection)conDesc.getConnection();
//set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length", Integer.toString(postData.length()));
connection.setRequestProperty("Content-Type","application/json");
OutputStream out = connection.openOutputStream();
out.write(postData.get);
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK){
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while((read = in.read())!= -1)
buf.append((char)read);
response = buf.toString();
}
Dialog.inform(response);
connection.close();
} catch(Exception e) {
}
}
return response;
Thanks
I solved this problem
Error:
Error: Cannot run program "jar": CreateProcess error=2, The system cannot find the file specified Packaging project HelaBibleWhereUR failed (took 10.715 seconds)
I simply put jar.exe that is under java bin folder in the jre bin folder.
I'm trying to download xml files using httpwebrequest using the code below based on this example here. Now it works partially in that it doesn't download all the xml file's contents. Any idea why?
public void download(String url)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.AllowReadStreamBuffering = false;
request.Method = "GET";
request.BeginGetResponse(a =>
{
StringBuilder data=null;
using (WebResponse response = request.EndGetResponse(a))
{
int expected = (int)response.ContentLength;
try
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
int read = 0;
data = new StringBuilder(expected);
char[] buffer = new char[1024];
while ((read = reader.Read(buffer, 0, buffer.Length)) != 0)
{
data.Append(new string(buffer, 0, read));
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("exception caught: " + ex.Message);
}
}
System.Diagnostics.Debug.WriteLine("Got \n " + data.ToString());
}, null);
}
If all you're getting is XML, you can use XDocument.Load(stream) to load the result to a XDocument instance
Your problem may be with the applied Encoding, and this method should solve any Encoding issue!