How to run Java code in in beashell of jmeter and pass vairables in Jmeter script - jar

Hi I am getting the following error:
2020-05-22 18:46:34,329 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: ``import java.io.File; import java.io.FileInputStream; import java.util.Base64; im . . . '' Encountered "[" at line 16, column 40.
Here is the code:
import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
String imageString = null;
String pathImageFolder = "/home/sarvesh/Desktop/sgi/10";
File file = new File(pathImageFolder);
int filecount = file.list().length;
File[] files = file.listFiles();
for (File f : files) {
f = new File(f.getPath());
FileInputStream fis = new FileInputStream(f);
byte byteArray[] = new byte[(int) f.length()];
fis.read(byteArray);
imageString = Base64.getEncoder().encodeToString(byteArray);
System.out.println("***********************************************");
System.out.println("File Path : " + f.getAbsolutePath());
System.out.println("Base 64 Image : " + imageString);
System.out.println("***********************************************");
}
How can I resolve this?

Be aware that staring from JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting therefore consider migrating to the JSR223 Sampler on next available opportunity, the equivalent code would be something like:
String pathImageFolder = "/home/sarvesh/Desktop/sgi/10";
new File(pathImageFolder).listFiles().each { file ->
imageString = file.bytes.encodeBase64().toString();
log.info("File Path :" + file.getAbsolutePath());
log.info("Base 64 Image :" + imageString);
}
Demo:
More information:
Groovy Goodness: Base64 Encoding
Apache Groovy - Why and How You Should Use It

Related

How to Read Data from report.html file in Robotic Framework

I have a use case to read data from report.html (Example Test case name & Elapsed time) and store into MySQL, then implement Grafana dashboard wrt test case name & Elapsed time)
How can I achieve it ? How can I read data from report.html ?
Read output.xml,
You can use Python methods with this lib "xml.etree.ElementTree".
I already parse the output.xml from robotFramework for personal usage, this is an exemple for the beginning of parsing:
# -*- coding: utf:8 -*-
import os, sys
import xml.etree.ElementTree as ET
class OutputAnalyser() :
def __init__(self) :
self.xml_report_file = '/Logs/output.xml'
self.root_full_report = self.load_output_xml_results_file()
self.all_test_by_suite = self.get_all_tests_by_suite()
def load_output_xml_results_file(self):
try:
root_full_report = ET.parse(self.xml_report_file).getroot()
except FileNotFoundError as e:
raise FileNotFoundError({'errorCode' : 'FileNotFoundError', 'errorMessage' : 'File : ' + str(self.xml_report_file) + ' inexisting. Error : ' + str(e)})
return root_full_report
def get_all_tests_by_suite(self):
all_suite = [item for elem in self.root_full_report.findall('.//suite') for item in elem]
all_test_by_suite = []
for suite in all_suite:
sublist_test = {}
sublist_test["suiteName"] = suite.get('name')
sublist_test["tests"] = suite.findall('./test')
all_test_by_suite.append(sublist_test)
return all_test_by_suite

Encoding problem with GET requests in Haskell

I'm trying to get some Json data from a Jira server using Haskell. I'm counting this as "me having problems with Haskell" rather than encodings or Jira because my problem is when doing this in Haskell.
The problem occurs when the URL (or query) has plus signs. After building my request for theproject+order+by+created, Haskell prints it as:
Request {
host = "myjiraserver.com"
port = 443
secure = True
requestHeaders = [("Content-Type","application/json"),("Authorization","<REDACTED>")]
path = "/jira/rest/api/2/search"
queryString = "?jql=project%3Dtheproject%2Border%2Bby%2Bcreated"
method = "GET"
proxy = Nothing
rawBody = False
redirectCount = 10
responseTimeout = ResponseTimeoutDefault
requestVersion = HTTP/1.1
}
But the request fails with this response:
- 'Error in the JQL Query: The character ''+'' is a reserved JQL character. You must
enclose it in a string or use the escape ''\u002b'' instead. (line 1, character
21)'
So it seems like Jira didn't like Haskell's %2B. Do you have any suggestions on what I can do to fix this, or any resources that might be helpful? The same request sans the +order+by+created part is successful.
The code (patched together from these examples):
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import qualified Data.ByteString.Char8 as S8
import qualified Data.Yaml as Yaml
import Network.HTTP.Simple
import System.Environment (getArgs)
-- auth' is echo -e "username:passwd" | base64
foo urlBase proj' auth' = do
let proj = S8.pack (proj' ++ "+order+by+created")
auth = S8.pack auth'
request'' <- parseRequest urlBase
let request'
= setRequestMethod "GET"
$ setRequestPath "/jira/rest/api/2/search"
$ setRequestHeader "Content-Type" ["application/json"]
$ request''
request
= setRequestQueryString [("jql", Just (S8.append "project=" proj))]
$ setRequestHeader "Authorization" [S8.append "Basic " auth]
$ request'
return request
main :: IO ()
main = do
args <- getArgs
case args of
(urlBase:proj:auth:_) -> do
request <- foo urlBase proj auth
putStrLn $ show request
response <- httpJSON request
S8.putStrLn $ Yaml.encode (getResponseBody response :: Value) -- apparently this is required
putStrLn ""
_ -> putStrLn "usage..."
(If you know a simpler way to do the above then I'd take such suggestions as well, I'm just trying to do something analogous to this Python:
import requests
import sys
if len(sys.argv) >= 4:
urlBase = sys.argv[1]
proj = sys.argv[2]
auth = sys.argv[3]
urlBase += "/jira/rest/api/2/search?jql=project="
proj += "+order+by+created"
h = {}
h["content-type"] = "application/json"
h["authorization"] = "Basic " + auth
r = requests.get(urlBase + proj, headers=h)
print(r.json())
)
project+order+by+created is the URL-encoded string for the actual request project order by created (with spaces instead of +). The function setRequestQueryString expects a raw request (with spaces, not URL-encoded), and URL-encodes it.
The Python script you give for comparison essentially does the URL-encoding by hand.
So the fix is to put the raw request in proj:
foo urlBase proj' auth' = do
let proj = S8.pack (proj' ++ " order by created") -- spaces instead of +
...

How to download JIRA attachment files with Python

I want to download attachment files of an issue in JIRA Python.
I use jira python lib ,you can use pip install JIRA
# -- coding: UTF-8 --
from jira import JIRA
import requests
url = 'https://jira.1234.com'
jira = JIRA(server=url, basic_auth=('admin', 'password'))
attachment=jira.attachment(12345) #12345 is attachment_key
image = attachment.get()
with open("Image.png", 'wb') as f:
f.write(image)
JIRA exposes its REST services and through that and some python you can download any attachment.
It worked for me like this (you'll need to adjust the variables):
#!/usr/bin/python
# miguel ortiz
# Requests module: http://docs.python-requests.org/en/latest/
# Documentation: <url>
#----------------------------------------------------------------Modules
import sys
import csv, json
import requests
#----------------------------------------------------------------Variables
myTicket= sys.argv[1] # Your ticket: ABC-123
user = 'miguel' # JIRA user
pasw = 'password' # JIRA password
jiraURL = 'https://yourinstance.jira.com/rest/api/latest/issue/'
fileName = 'my_attached_file' # In this case we'll be looking for a specific file in the attachments
attachment_final_url="" # To validate if there are or not attachments
def main() :
print '\n\n [ You are checking ticket: ' + myTicket+ ' ]\n'
# Request Json from JIRA API
r = requests.get(jiraURL+myTicket, auth=(user, pasw),timeout=5)
# status of the request
rstatus = r.status_code
# If the status isn't 200 we leave
if not rstatus == 200 :
print 'Error accesing JIRA:' + str(rstatus)
exit()
else:
data = r.json()
if not data['fields']['attachment'] :
status_attachment = 'ERROR: Nothing attached, attach a file named: ' + fileName
attachment_final_url=""
else:
for i in data['fields']['attachment'] :
if i['filename'] == fileName :
attachment_final_url = i['content']
status_attachment_name = 'OK: The desired attachment exists: ' + fileName
attachment_name = False
attachment_amount = False
attachment_files = False
break
else :
attachment_files = False
status_attachment_name = + 'ERROR: None of the files has the desired name '
attachment_final_url=""
attachment_name = True
attachment_amount = True
continue
if attachment_final_url != "" :
r = requests.get(attachment_final_url, auth=(user, pasw), stream=True)
with open(fileName, "wb") as f:
f.write(r.content.decode('iso-8859-1').encode('utf8'))
f.close()
else:
print status_attachment
if __name__ == "__main__" :
main()
If you do not understand the code I've detailed it better in my blog.
EDIT: Be careful, in JIRA you can add many files with the same name.

How to set version number in sbt when building & publishing akka-http

I'm trying to experiment with a local copy of the akka-http library. I can publish it locally with sbt publishLocal, but I can't figure out how to change the version number. build.sbt contains an organization field but no simple version field - that seems to be generated from somewhere else and I can't figure out where. It's currently at 10.0.5but grepping that string in the source doesn't turn up anything obvious.
Seems like a simple question, but where is version defined? Thanks.
(I'm asking this because sbt docs tell me I should name my local version something like 0.1-SNAPSHOT. I assume there must be a simpler way to do this than by disabling the auto-generation logic and hardcoding it into build.sbt)
It seems that Akka-HTTP generates its version at run-time.
If you look at akka-http/akka-http-core/src/main/resources/reference.conf:
Akka HTTP version, checked against the runtime version of Akka HTTP.
Loaded from generated conf file.
And then look at akka-http/project/Version.scala:
/**
* Generate version.conf and akka/Version.scala files based on the version setting.
*/
object Version {
def versionSettings: Seq[Setting[_]] = inConfig(Compile)(Seq(
resourceGenerators += generateVersion(resourceManaged, _ / "akka-http-version.conf",
"""|akka.http.version = "%s"
|""").taskValue,
sourceGenerators += generateVersion(sourceManaged, _ / "akka" / "http" / "Version.scala",
"""|package akka.http
|
|import com.typesafe.config.Config
|
|object Version {
| val current: String = "%s"
| def check(config: Config): Unit = {
| val configVersion = config.getString("akka.http.version")
| if (configVersion != current) {
| throw new akka.ConfigurationException(
| "Akka JAR version [" + current + "] does not match the provided " +
| "config version [" + configVersion + "]")
| }
| }
|}
|""").taskValue
))
def generateVersion(dir: SettingKey[File], locate: File => File, template: String) = Def.task[Seq[File]] {
val file = locate(dir.value)
val content = template.stripMargin.format(version.value)
if (!file.exists || IO.read(file) != content) IO.write(file, content)
Seq(file)
}
}
I'm assuming after generating the current version you should see a akka-http-version.conf file somewhere in your filesystem.

R source file from RConnection (JRI) "could not find function"

I'm trying to source a R script file from an org.rosuda.REngine.Rserve.RConnection and then calling a function from that script, but am getting, "Error: could not find function "main".
Start Rserve from terminal
> require(Rserve)
Loading required package: Rserve
> Rserve()
Starting Rserve...
"C:\Users\slenzi\DOCUME~1\R\WIN-LI~1\3.3\Rserve\libs\x64\Rserve.exe"
> Rserve: Ok, ready to answer queries.
Error: could not find function "main"
External script rdbcTest1.R
require(RJDBC)
main <- function() {
jdbcDriver <- JDBC(driverClass = dbDriverClass, classPath = dbDriverPath)
jdbcConnection <- dbConnect(jdbcDriver, dbUrl, dbUser, dbPwd)
dbResult <- dbGetQuery(jdbcConnection, dbQuery)
dbDisconnect(jdbcConnection)
return(dbResult)
}
Java Code
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngine;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
REXP result = null;
RConnection c = null;
try {
c = new RConnection();
String driverPath = "C:/temp/ojbdc6.jar";
String scriptPath = "C:/temp/rdbcTest1.R";
c.assign("dbUser", "foo");
c.assign("dbPwd", "******");// commented out
c.assign("dbUrl", "jdbc:oracle:thin:#myhost:1511:ecogtst");
c.assign("dbDriverClass", "oracle.jdbc.driver.OracleDriver");
c.assign("dbDriverPath", driverPath);
// assign query to execute
c.assign("dbQuery", "SELECT count(*) FROM prs.members");
String evalSource = String.format("try(source(\"%s\", local=TRUE), silent=TRUE)", scriptPath);
c.eval("evalSource");
// debug
result = c.eval("ls()");
logger.info("REXP debug => " + result.toDebugString());
result = c.eval("main()");
} catch (RserveException e) {
logger.error("error running script test, " + e.getMessage());
} finally {
if(c != null){
c.close();
}
}
Output
evaluating => try(source("C:/temp/rdbcTest1.R", local=TRUE), silent=TRUE)
REXP debug => org.rosuda.REngine.REXPString#61c6bc05[6]{"dbDriverClass","dbDriverPath","dbPwd","dbQuery","dbUrl","dbUser"}
Error: could not find function "main"
error running oracle script test, eval failed, request status: error code: 127
Running the script directly from the R terminal it works fine. When ran from RConnection I can see the values of the variables I assign (c.assign(...)) but not the main() function from the sourced script.
What am I missing in regards to sourcing a script? How can I access a function from the script?
Thanks.
** UPDATE **
I got the following to work, but if anyone has any idea why source() doesn't seem to work in my example above, please let me know!
RConnection c = ...
REXP x = c.parseAndEval("try(eval(parse(file=\"C:/temp/rdbcTest3.R\")), silent=TRUE)")

Resources