I am getting this error, and cannot figure out what wrong I am doing:
Error invoking bsh method: eval In file: inline evaluation of: ``import java.util.Set; import java.util.Map; import java.util.List; try { // Map . . . '' Encountered "String" at line 17, column 9.
This is the code that I am using:
import java.util.Set;
import java.util.Map;
import java.util.List;
try
{
// Map<String,List<String>> map = new HashMap<String,List<String>>();
// map = vars.getObject("headerMap");
boolean isHeaderValid = false;
// String apiKeySent = "${x_api_key}"
// String clientIdSent = "${X_IBM_Client_id}"
// String clientSecretSent = "${X_IBM_Client_Secret}"
String apiKeySent = vars.get("x_api_key")
String clientIdSent = vars.get("X_Client_id")
String clientSecretSent = vars.get("X_Client_Secret")
log.info("apiKeySent: " + vars.get("x_api_key"))
log.info("clientIdSent: " + vars.get("X_Client_id"))
log.info("clientSecretSent: " + vars.get("X_Client_Secret"))
if(apiKeySent != "")
{
apiKeyRec = vars.get("apiKeyRec")
isHeaderValid = apiKeySent.equals(apiKeyRec)
}
Failure = isHeaderValid
}
catch(Exception e)
{
log.debug("Error in verification: ",e)
}
Could anyone please help me in figuring this out? Have been stuck at this for ages.
You need to add semicolons like this
import java.util.Set;
import java.util.Map;
import java.util.List;
try
{
// Map<String,List<String>> map = new HashMap<String,List<String>>();
// map = vars.getObject("headerMap");
boolean isHeaderValid = false;
// String apiKeySent = "${x_api_key}"
// String clientIdSent = "${X_IBM_Client_id}"
// String clientSecretSent = "${X_IBM_Client_Secret}"
String apiKeySent = vars.get("x_api_key");
String clientIdSent = vars.get("X_Client_id");
String clientSecretSent = vars.get("X_Client_Secret");
log.info("apiKeySent: " + vars.get("x_api_key"));
log.info("clientIdSent: " + vars.get("X_Client_id"));
log.info("clientSecretSent: " + vars.get("X_Client_Secret"));
if(apiKeySent != "")
{
apiKeyRec = vars.get("apiKeyRec");
isHeaderValid = apiKeySent.equals(apiKeyRec);
}
Failure = isHeaderValid;
}
catch(Exception e)
{
log.debug("Error in verification: ",e);
}
Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting so consider migrating to JSR223 Assertion and Groovy
Your script can be simplified to
AssertionResult.setFailure(vars.get('x_api_key') == vars.get('apiKeyRec'))
And you don't even need any scripting for comparing 2 variables, it can be done using "normal" Response Assertion
It looks like you are forgetting to end all of your statements with semicolons from line 12 on. Add semicolons and let me know how that works!
Related
I have the following JSR223 Sampler which reads the image changes it a bit and sends a POST multipart/form-data request. I see that it is extensively using CPU compared to HTTP Sampler but I can't use HTTP sampler as it doesn't support changing the image without saving to file system.
Appreciate if anyone has any input to optimize the script in JSR223 sampler so it doesn't extensively lot of CPU.
import org.apache.http.HttpHeaders
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.client.methods.RequestBuilder
import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.conn.ssl.TrustStrategy
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.ssl.SSLContextBuilder
import org.apache.http.util.EntityUtils
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.io.ByteArrayOutputStream;
import org.apache.http.entity.ContentType;
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
List<String> sendRequest(String url, String method, String body) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(40000)
.setSocketTimeout(50000)
.build();
BufferedImage image = ImageIO.read(new File("/home/4567/loadtest/Bank.JPG"));
Graphics graphics = image.getGraphics();
graphics.setFont(graphics.getFont().deriveFont(16f));
graphics.drawString("User " + ctx.getThreadNum() + '-' + Math.random() +"; iteration: " + ctx.getVariables().getIteration(), 50, 50);
graphics.dispose();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", bytes);
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.STRICT);
multipartEntity.addBinaryBody("File", bytes.toByteArray(),ContentType.IMAGE_JPEG, "Bank.JPG");
HttpUriRequest request = RequestBuilder.create(method)
.setConfig(requestConfig)
.setUri(url)
.setHeader("x-ibm-client-id","248a20f3-c39b-45d0-b26a-9019c26e9be8")
.setHeader("X-Client-Id","2861D410-773B-4DD9-AE74-882116B08856")
.setHeader("ResponseMinLatencyMs","45")
.setHeader("ResponseMaxLatencyMs","55")
.setEntity(multipartEntity.build())
.build();
// String req = "REQUEST:" + "User " + ctx.getThreadNum() + "; iteration: " + ctx.getVariables().getIteration() + " " + request.getRequestLine() + "\n";
def builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
def trustAllFactory = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
HttpClients.custom().setSSLSocketFactory(trustAllFactory).build().withCloseable { httpClient ->
httpClient.execute(request).withCloseable { response ->
// String res = "RESPONSE:" + "User " + ctx.getThreadNum() + "; iteration: " + ctx.getVariables().getIteration() + " " + response.getStatusLine() + (response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "") + "\n";
// log.info(req + "\n" + res);
// return Arrays.asList(req, res);
response.close()
}
httpClient.close()
}
image.flush()
bytes.flush()
bytes.close()
}
sendRequest("https://test-server.com/upload", "POST", "");
I believe normal HTTP Request sampler doesn't change the images before sending the request that's why it is not that CPU intensive.
Looking into Beanshell vs JSR223 vs Java JMeter Scripting: The Performance-Off You've Been Waiting For! article it seems that Java it still the best choice in terms of performance and resources usage so you might want to re-implement your code in Java and use JUnit or Java request samplers
If you run up above 85% of CPU on your JMeter machine most probably you won't get accurate results because JMeter won't be able to send requests fast enough, consider going for Distributed Testing
I have the following code in JSR223 Sampler and I get following errors when I run this jmeter command. Can anyone please advise if something is wrong with my code? I'm basically reading a image and changing it little bit and sending a multipart/form-data POST request.
jmeter -n -Jthreads=20 -Jrampup=30 -Jduration=60 -Jiterations=-1 -t script.jmx
javax.script.ScriptException: java.net.SocketTimeoutException: Read timed out
Uncaught Exception java.lang.OutOfMemoryError: Java heap space in thread Thread[Thread Group 1-10,5,main]
import org.apache.http.HttpHeaders
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.client.methods.RequestBuilder
import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.conn.ssl.TrustStrategy
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.ssl.SSLContextBuilder
import org.apache.http.util.EntityUtils
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.io.ByteArrayOutputStream;
import org.apache.http.entity.ContentType;
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
List<String> sendRequest(String url, String method, String body) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(3000)
.build();
BufferedImage image = ImageIO.read(new File("C:/Users/bd3249/Pictures/5.JPG"));
Graphics graphics = image.getGraphics();
graphics.setFont(graphics.getFont().deriveFont(16f));
graphics.drawString("User " + ctx.getThreadNum() + '-' + Math.random() +"; iteration: " + ctx.getVariables().getIteration(), 50, 50);
graphics.dispose();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", bytes);
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.STRICT);
multipartEntity.addBinaryBody("File", bytes.toByteArray(),ContentType.IMAGE_JPEG, "5.JPG");
HttpUriRequest request = RequestBuilder.create(method)
.setConfig(requestConfig)
.setUri(url)
.setHeader("x-ibm-client-id","248a20f3-c39b-45d0-b26a-9019c26e9be8")
.setHeader("X-Client-Id","2861D410-773B-4DD9-AE74-882116B08856")
.setEntity(multipartEntity.build())
.build();
String req = "REQUEST:" + "User " + ctx.getThreadNum() + "; iteration: " + ctx.getVariables().getIteration() + " " + request.getRequestLine() + "\n";
def builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
def trustAllFactory = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
HttpClients.custom().setSSLSocketFactory(trustAllFactory).build().withCloseable { httpClient ->
httpClient.execute(request).withCloseable { response ->
String res = "RESPONSE:" + "User " + ctx.getThreadNum() + "; iteration: " + ctx.getVariables().getIteration() + " " + response.getStatusLine() + (response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "") + "\n";
log.info(req + "\n" + res);
return Arrays.asList(req, res);
}
}
}
List test1 = sendRequest("https://test.com/upload", "POST", "");
The error you're getting clearly indicates that you don't have sufficient Java Heap space, by default JMeter 5.3 comes with 1 GB of heap and depending on your image size and response size it might be not enough for your test.
Use i.e. Active Threads Over Time listener to see how many virtual users were online when the error occurs and increase the heap size proportionally.
More information: 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure
In my JMeter test plan, I have a HttpRequest, I want to extract the link from its response only if the response code is 200.
I can add an XPathExtractor post processor under HttpRequest and it works.
But I want to have an IfCondition first so that the extractor won't try to work on invalid content. But the IfController can't be added as a postprocessor.
Maybe I can have a BeanShell sampler to do it but I don't know how to use XPathExtractor in BeanShell.
"Short and easy" way - use an additional Sampler
Add If Controller after the HTTP Request
Use ${JMeterThread.last_sample_ok} as "Condition"
Put Beanshell Sampler under the If Controller
Use the following code in Beanshell Sampler "Script" area:
SampleResult.setResponseData(ctx.getPreviousResult().getResponseData());
Put XPath Extractor as a child of the Beanshell Sampler
The above Beanshell script will return the same response as preceding HTTP Request sampler
"Long and hard" way - extract XPath directly in Beanshell.
Put Beanshell PostProcessor instead of XPath Extractor
Use the following script as a reference:
import org.apache.jmeter.util.PropertiesBasedPrefixResolver;
import org.apache.jmeter.util.XPathUtil;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
InputStream in = new ByteArrayInputStream(prev.getResponseData());
boolean useNameSpace = false;
boolean isTolerant = true;
boolean isQuiet = true;
boolean showWarnings = true;
boolean reportErrors = true;
boolean isXML = false;
boolean isDownloadDTDs = false;
if (prev.isResponseCodeOK()) {
InputStream in = new ByteArrayInputStream(prev.getResponseData());
boolean useNameSpace = false;
boolean isTolerant = true;
boolean isQuiet = true;
boolean showWarnings = true;
boolean reportErrors = true;
boolean isXML = false;
boolean isDownloadDTDs = false;
String query = "//a[text()='JMeter FAQ (Wiki)']";
List matchStrings = new ArrayList();
//matchStrings.add("-1");
boolean returnFragment = false;
Document doc = XPathUtil.makeDocument(in, false, false, useNameSpace, isTolerant, isQuiet, showWarnings, reportErrors
, isXML, isDownloadDTDs);
String val = null;
XObject xObject = XPathAPI.eval(doc, query, new PropertiesBasedPrefixResolver(doc.getDocumentElement());
int objectType = xObject.getType();
if (objectType == xObject.CLASS_NODESET) {
NodeList matches = xObject.nodelist();
int length = matches.getLength();
for (int i = 0; i < length; ++i) {
Node match = matches.item(i);
if (match instanceof Element) {
if (returnFragment) {
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(match), new StreamResult(sw));
val = sw.toString();
} else {
Node firstChild = match.getFirstChild();
if (firstChild != null) {
val = firstChild.getNodeValue();
} else {
val = match.getNodeValue();
}
}
} else {
val = match.getNodeValue();
}
matchStrings.add(val);
}
} else if (objectType != xObject.CLASS_NULL && objectType != xObject.CLASS_UNKNOWN && objectType != xObject.CLASS_UNRESOLVEDVARIABLE) {
val = xObject.toString();
matchStrings.add(val);
} else {
log.warn("Unexpected object type: " + xObject.getTypeString() + " returned for: " + query);
}
for (String match : matchStrings) {
log.info("Match -----> " + match);
}
}
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell in JMeter scripts
I have made an ontology on Protege. it has . owl extension. I am trying to import this ontology in oracle 12c using jena. but model. Read method requires an rdf file. I am giving the code as well as error. Kindly help me in this case.
error
Exception in thread "main" com.hp.hpl.jena.shared.JenaException: java.lang.UnsatisfiedLinkError: no ocijdbc11 in java.library.path
at oracle.spatial.rdf.client.jena.Oracle.<init>(Oracle.java:207)
at test.TestClass.main(TestClass.java:26)
code package test;
import java.io.InputStream;
import com.hp.hpl.jena.rdf.model.*;
import oracle.spatial.rdf.client.jena.GraphOracleSem;
import oracle.spatial.rdf.client.jena.ModelOracleSem;
import oracle.spatial.rdf.client.jena.Oracle;
import oracle.spatial.rdf.client.jena.OracleUtils;
import com.hp.hpl.jena.graph.GraphUtil;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;
public class TestJena{
public static void main(String[] args) throws Exception
{
//String szJdbcURL = args[0];
//String szUser = args[1];
//String szPasswd = args[2];
//String szModelName = args[3];
// in memory Jena Model
Model model = ModelFactory.createDefaultModel();
InputStream is = FileManager.get().open("E:/abcd.owl");
model.read(is, "", "RDF/XML");
is.close();
Oracle oracle = new Oracle("jdbc:oracle:oci8:#", "c##hr_admin","Hira123");
ModelOracleSem modelDest = ModelOracleSem.createOracleSemModel(oracle,"M1");
GraphOracleSem g = modelDest.getGraph();
g.dropApplicationTableIndex();
int method = 2; // try bulk loader
String tbs = "SYSAUX"; // can be customized
if (method == 0) {
System.out.println("start incremental");
modelDest.add(model);
System.out.println("end size " + modelDest.size());
}
else if (method == 1) {
System.out.println("start batch load");
g.getBulkUpdateHandler().addInBatch(
GraphUtil.findAll(model.getGraph()), tbs);
System.out.println("end size " + modelDest.size());
}
else {
System.out.println("start bulk load");
g.getBulkUpdateHandler().addInBulk(
GraphUtil.findAll(model.getGraph()), tbs);
System.out.println("end size " + modelDest.size());
}
g.rebuildApplicationTableIndex();
long lCount = g.getCount(Triple.ANY);
System.out.println("Asserted triples count: " + lCount);
model.close();
OracleUtils.dropSemanticModel(oracle, "M1");
oracle.dispose();
}
}
You can rename the file to RDF: under the assumption that the format you used for the ontology is RDF/XML (the default), all that is needed is changing the file extension.
Regarding the error you post, you are missing a binary library. You need to set java.library.path to point at the folder containing the library mentioned in the error.
See for example how to set java library path for processing for how to do this.
What is the better way to parse such xml:
<FindLicensesResponse xmlns="http://abc.com">
<FindLicensesResult>
<Licensies>
<ActivityLicense>
<id>1</id>
<DateIssue>2011-12-29T00:00:00</DateIssue>
<ActivityType xmlns:s01="http://www.w3.org/2001/XMLSchema-instance" s01:type="ActivityType">
<code>somecode1</code>
</ActivityType>
<ActivityTerritory xmlns:s02="http://www.w3.org/2001/XMLSchema-instance" s02:type="Territory">
<code>somecode2</code>
</ActivityTerritory>
<ActivityLicenseAttachments />
</ActivityLicense>
<ActivityLicense>
<id>2</id>
<DateIssue>2011-12-21T00:00:00</DateIssue>
<ActivityType xmlns:s01="http://www.w3.org/2001/XMLSchema-instance" s01:type="ActivityType">
<code>somecode3</code>
</ActivityType>
<ActivityTerritory xmlns:s02="http://www.w3.org/2001/XMLSchema-instance" s02:type="Territory">
<code>somecode4</code>
</ActivityTerritory>
<ActivityLicenseAttachments />
</ActivityLicense>
</Licensies>
</FindLicensesResult>
I need to get values from each ActivityLicense: id, DateIssue and inner ActivityType: code and inner ActivityTerritory: code.
Now I do it like this:
CachedXPathAPI xpathAPI = new CachedXPathAPI();
Element nsctx = result.getSOAPPart().createElementNS(null, "nsctx");
nsctx.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:el","http://abc.com");
NodeList activityLicenses = xpathAPI.selectNodeList(result.getSOAPPart(),"//el:ActivityLicense", nsctx);
for (int i = 0; i < activityLicenses.getLength(); i++) {
Node id = xpathAPI.selectSingleNode(activityLicenses.item(i), "//el:id", nsctx);
Node dateIssue = xpathAPI.selectSingleNode(activityLicenses.item(i), "//el:DateIssue",nsctx);
System.out.println("id: " + id.getTextContent());
System.out.println("dateIssue: " + dateIssue.getTextContent());
}
But I can't get values from ActivityType/code and ActivityTerritory/code
check out this solution
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
public class StringTest {
public static void main(String[] args) throws Exception {
String xml = "";
java.util.Scanner sc = new java.util.Scanner(new File("xml.xml"));
while(sc.hasNextLine()){
xml+=sc.nextLine();
}
javax.xml.parsers.DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputStream is = new ByteArrayInputStream(xml.getBytes());
org.w3c.dom.Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
XPath xpath = XPathFactory.newInstance().newXPath();
org.w3c.dom.NodeList nodeList = doc.getElementsByTagName("ActivityLicense");
for(int i=0;i<nodeList.getLength();i++){
org.w3c.dom.Node node = nodeList.item(i);
System.out.println(xpath.evaluate("ActivityTerritory/code/text()", node, XPathConstants.STRING));
}
}
}