If else statement in Jmeter Beanshell post-processor - jmeter

I get response from my request containing request id and if something goes wrong there is a err code.
I want to write a beanshell script that would look firstly if there is any err code, if not it would wirte request id into the csv file. I am not able to find anything about if else statements in beanshell
if (there is an err code){
write it to the csv file}
else {write request id to csv}
is it possible in beanshell or better to use assertions ?
Problem with java
2016/08/09 13:38:38 ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.jmeter.threads.JMeterContextService; import java.io.PrintWrite . . . '' : Command not found: regexMethod( java.lang.String, java.lang.String )
2016/08/09 13:38:38 WARN - jmeter.extractor.BeanShellPostProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.jmeter.threads.JMeterContextService; import java.io.PrintWrite . . . '' : Command not found: regexMethod( java.lang.String, java.lang.String )

I think this will do the job... You just need to get regex expressions for your data.
import org.apache.jmeter.threads.JMeterContextService;
import java.io.PrintWriter;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String prevResponse = JMeterContextService.getContext().getPreviousResult().
getResponseDataAsString();
public void writeToFile(String toWrite) {
String path = "/home/username/Desktop/TSO_test_failure.csv";
File file = new File(path);
try {
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.print(toWrite);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String regexMethod (String regex, String text) {
String regResult;
try {
Pattern pat = Pattern.compile(regex);
Matcher mac = pat.matcher(text);
mac.find();
regResult = mac.group(1);
} catch (Exception e) {
e.printStackTrace();
}
return regResult;
}
String result = null;
if (prevResponse.contains("errorCode")) {
String errRegex = "findErrorID"; // change this to meet your needs!
result = regexMethod(errRegex, prevResponse);
} else {
String reqRegex = "findRequestID"; // change this to meet your needs!
result = regexMethod(reqRegex, prevResponse);
}
writeToFile(result);

Related

Validate Request in Ktor

I have an API maked with Ktor and when som field of the request failed, it returns 500 error and I want to check all request data and return, in this case, 422.
Request class:
#Serializable
data class LoginRequest (
val email: String,
val password: String
)
Routing
route("v1/auth/login") {
post {
val loginRequest = call.receive<LoginRequest>()
//LOGIN METHOD
}
}
The error that now Ktor shows is:
[eventLoopGroupProxy-4-1] ERROR Application - Unhandled: POST - /v1/auth/login
kotlinx.serialization.MissingFieldException: Field 'password' is required for type with serial name
What is the best way to ensure that the system does not fail and respond with a BadRequest?
If you wanna catch an exception in a specific place, you can use try/catch:
try {
val loginRequest = call.receive<LoginRequest>()
...
} catch (e: SerializationException) {
// serialization exceptions
call.respond(HttpStatusCode.UnprocessableEntity)
} catch (t: Throwable) {
// other exceptions
call.respond(HttpStatusCode.InternalServerError)
}
If you wanna some global try/catch, Ktor has StatusPages feature for such case: it'll catch all exceptions during calls processing.
Same as with try/catch, you can catch a specific exception, like SerializationException, or use Exception/Throwable for any other exception.
install(StatusPages) {
exception<SerializationException> { cause ->
// serialization exceptions
call.respond(HttpStatusCode.UnprocessableEntity)
}
exception<Throwable> { cause ->
// other exceptions
call.respond(HttpStatusCode.InternalServerError)
}
}
You can make fields nullable with the default null value, ignore errors when unknown properties are encountered and validate the result object manually. Here is an example:
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.serialization.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
#Serializable
data class LoginRequest (
val email: String? = null,
val password: String? = null
)
suspend fun main() {
embeddedServer(Netty, port = 8080) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true
})
}
routing {
post("/") {
val request = call.receive<LoginRequest>()
if (request.email == null || request.password == null) {
call.respond(HttpStatusCode.UnprocessableEntity)
return#post
}
call.respond(HttpStatusCode.OK)
}
}
}.start()
}
post {
try {
val customer = call.receive<Customer>()
customerStorage.add(customer)
call.respondText("Customer stored correctly", status = HttpStatusCode.Created)
} catch (e: SerializationException) {
call.respondText(e.localizedMessage, status = HttpStatusCode.UnprocessableEntity)
} catch (e: Exception) {
call.respondText(e.localizedMessage, status = HttpStatusCode.InternalServerError)
}
}

Filter CSV file and create a new file with filtered rows

I am looking to filter rows by the description column. I want to filter out all rows that contain 'Free WiFi' and then create a csv file and make it comma separated.
HOTELID|AMENITYCODE|DESCRIPTION
722602|8|24-hour front desk
722602|109|Air conditioning
722602|23|Dry cleaning
722602|81|Fax/photocopying
722602|107|Free WiFi
723303|11|Fitness centre
723303|107|Free WiFi
723303|205|Fruits
723303|79|Hammam
723303|80|Heating
723303|44|Ironing service
723303|176|Kid meals
What shell/Java/C# script can I use in order to do this and be used by a task scheduler in Windows.
Thanks,
Spencer
You could use a PowerShell pipeline like this
Import-Csv .\input.txt -Delimiter '|' | ? { $_.Description -notlike '*Free Wifi*' } | Export-Csv -NoTypeInformation processed.csv
where input.txt is your input file and processed.csv will contain your new CSV without the WiFi stuff.
In basic Java we can do with the below code:
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVWriter;
public class Test {
public static void main(String[] args) {
String readFile = "C:\\test.txt";
String line = "";
String cvsSplitBy = "\\|";
String filter1="Free WiFi";
List<String[]> output = new ArrayList<String[]>();
String writeFile = "C:\\testout.csv";
try (BufferedReader br = new BufferedReader(new FileReader(readFile))) {
output.add(0, br.readLine().split(cvsSplitBy));
while ((line = br.readLine()) != null) {
String[] input = line.split(cvsSplitBy);
if(input[2].contains(filter1)) {
output.add(input);
}
}
File file = new File(writeFile);
FileWriter outputfile = new FileWriter(file);
CSVWriter writer = new CSVWriter(outputfile);
writer.writeAll(output);
writer.close();
System.out.println("Program ended");
} catch (IOException e) {
e.printStackTrace();
}
}
}

ERROR 2078: Caught error from UDF

I am getting the error "ERROR 2078: Caught error from UDF: com.Hadoop.pig.SplitRec [Caught exception processing input row [1]]". I am sure that the input string is going out of bound, but I am not sure which record(record number) is causing the problem.
I am trying to create log for displaying the record which is causing the problem, but I am not sure about debugging to print/log the error record.
The input looks like:
**PXW01YIN 12000099PGEN PXW01YINFFFFFFFF PXW01YINIMFGUIPY04301Y301 JFK 00888JFK 008880001 PIMF 0000N/ACTRC5/TXN08/SCR301\/SEQ/TEX021\#
PXW01PIN 12000099PGEN PXW01PINFFFFFFFF PXW01PINIMFGUIAV04301P301 PER 03615PER 036150001 PIMF 0000N/ACTRCK/TXN08/SCR301\/SEQ/TEX021\#**
The above lines are two records and I have tested them(using LIMIT), and they are not causing problem. I have more than 150kb of input data.
The script that I am using:
SPLT_REC1 = load '/user/hduser/output/realdata/pig_out6/part-m-00000' as (tran_array:chararray);
register /home/cloudera/workspace/SplitRec.jar;
define SplitRec com.Hadoop.pig.SplitRec();
SPLT_REC2 = foreach SPLT_REC1 generate SplitRec(tran_array);
store SPLT_REC2 into '/user/hduser/output/realdata/pig_out7';
package com.Hadoop.pig;
import java.io.IOException;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.util.WrappedIOException;
#SuppressWarnings("deprecation")
public class SplitRec extends EvalFunc<String> {
public String exec(Tuple input) throws IOException {
if (input == null || input.size() == 0)
return null;
try {
String Str1 = (String)input.get(0);
String delim1 = "PIMF+";
String[] tokens1 = Str1.split(delim1);
String part3 = tokens1[0];
String part4 = tokens1[1];
int len1 = part4.length();
String part5 = part4.substring(8,len1);
String conCat1 = part3+":"+part5;
return conCat1;
}
catch(Exception e) {
throw WrappedIOException.wrap("Caught exception processing input row ", e);
}
}

Why is my break label erroring?

Hey guys I am trying to break out of a for loop that searches thru all files and breaks once it finds the file. The best thing I have found is the labeling break but its giving an error saying it doesn't exist can you guys take a look and see what I am doing wrong?
import java.nio.file.Files;
import java.nio.file.Paths;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.jaxen.dom4j.*;
public class Load
{
static String info = "";
public static String LoadSum(String projNum)
{
info = "";
try
{
searching:
Files.walk(Paths.get("D:/workspace/Project Program/Projects/")).forEach(filePath ->
{
if(Files.isRegularFile(filePath))
{
try
{
System.out.println("Checking");
SAXReader reader = new SAXReader();
Document document = reader.read(filePath.toFile());
Node node = document.selectSingleNode("//Project/Info/ProjectNumber");
String projectNumber = node.getStringValue();
if(projNum.equals(projectNumber))
{
System.out.println("Found it");
node = document.selectSingleNode("//Project/Info/Name");
info += node.getStringValue() + " : ";
//node = document.selectSingleNode("//Project/Info/Owner");
info += "Owner" + " : ";
node = document.selectSingleNode("//Project/Info/Status");
info += node.getStringValue() + " : ";
break searching; // error here searching doe not exist
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return info;
}
}
}
The break statement is not into a loop, so you cannot use it.
To forEach statement accepts an Anonymous function that is applied to all the elements found by the Paths.get("D:/workspace/Project Program/Projects/")) statement.
You can stop the operation by throwing an exception, if it's suitable for you.
Source: Java Docs
Edit: considering the fact that what you are passing is an anonymous function you can wrap all the function block with an if statement that depends on a boolean variable defined outside the function: if you find the element you toggle the variable so for the next elements it will be just a no-op. If you wanna know more about Java lambda expressions look here.

Getting attachments from document

This is all I need, nothing too fancy:
I'm creating an url from files that have been attached in the document, but the document is not opened. I have an xpage where I want to show attachments from specific document. How do I do this?
Thank you in advance.
The easiest way is to use #AttachmentNames (in a view column) to get the names of the files. Then you can construct the url using db.nsf/0/unid/$file/[filename] -- that's classic, won't run in XPiNC. There is a second URL syntax (need to check) that is XPages specific:
http(s)://[yourserver]/[application.nsf]/xsp/.ibmmodres/domino/OpenAttachment/[application.nsf]/[UNID|/$File/[AttachmentName]?Open
Read my full article on it here: http://www.wissel.net/blog/d6plinks/SHWL-86QKNM
(includes SSJS sample)
I found that DominoDocument.AttachmentValueHolder.getHref() works for getting the URL to an attached file or image, if you have a handle to the document. For example:
<xp:image
id="image1">
<xp:this.url>
<![CDATA[#{javascript:document1.getAttachmentList("Body").get(0).getHref()}]]>
</xp:this.url>
</xp:image>
You would need to handle multiple attachments by iterating over the elements returned from getAttachmentList().
If you can use Java (like in XPages) then
import com.ibm.xsp.extlib.util.ExtLibUtil;
import lotus.domino.MIMEEntity;
import lotus.domino.Document;
import lotus.domino.Session;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import lotus.domino.Database;
import lotus.domino.DocumentCollection;
import lotus.domino.EmbeddedObject;
import lotus.domino.Item;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.RichTextNavigator;
import lotus.domino.RichTextItem;
import lotus.domino.Stream;
import lotus.domino.View;
// ...
private String fileSeparator = File.separator;
private String tempPath = System.getProperty("java.io.tmpdir") + fileSeparator + "Temp" + fileSeparator;
// ...
private void saveFilesFromDoc(Document doc) throws NotesException {
if (doc.hasEmbedded()) {
RichTextItem body = null;
try {
body = (RichTextItem) doc.getFirstItem("body");
} catch (ClassCastException e) {
// save file from MIME (Rich text is converted to MIME)
MIMEEntity mime = doc.getMIMEEntity();
findMimeWithFile(mime);
return;
}
if (body != null) {
// save file from richtext
RichTextNavigator rtnav = body.createNavigator();
if (rtnav.findFirstElement(RichTextItem.RTELEM_TYPE_FILEATTACHMENT)) {
do {
EmbeddedObject att = (EmbeddedObject) rtnav.getElement();
String fileName = att.getSource();
fileName = notConflictFileName(fileName );
String path = tempPath + fileName ;
att.extractFile(path);
} while (rtnav.findNextElement());
}
} else {
// ("BODY is NULL");
}
}
Get file from richtext converted to Mime
private void findMimeWithFile(MIMEEntity mime) {
try {
askMimeForFiles(mime, "");
MIMEEntity child = mime.getFirstChildEntity();
while (child != null) {
askMimeForFiles(child, "child");
// String encoding = "ISO-8859-2";
String c = child.getContentType();
MIMEEntity subChild = child.getFirstChildEntity();
askMimeForFiles(subChild, "subChild");
if ("multipart".equals(c)) {
while (subChild != null) {
askMimeForFiles(subChild, "subChild2");
// String sc = subChild.getContentType();
subChild = subChild.getNextSibling();
}
}
child = child.getNextSibling();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Find out, if MIME Entity is file attachment (or some text)
private void askMimeForFiles(MIMEEntity mime, String prefix) throws NotesException {
if (mime != null) {
boolean thisMimeHasFile = false;
String fileName = "noname";
Vector<MIMEHeader> headers = mime.getHeaderObjects();
for (MIMEHeader header : headers) {
// (prefix + "-header: " + header.getHeaderName() + " :: " + header.getHeaderValAndParams());
if ("Content-Transfer-Encoding".equals(header.getHeaderName())) {
if ("binary".equals(header.getHeaderVal())) {
thisMimeHasFile = true;
}
}
if ("Content-Disposition".equals(header.getHeaderName())) {
String val = header.getHeaderValAndParams();
int odd = val.indexOf("filename=") + "filename=".length();
int doo = val.length();
fileName = val.substring(odd, doo);
this.fileNames.add(fileName);
}
}
if (thisMimeHasFile) {
safeFilesFromMIME(mime, fileName);
}
}
}
If MIME is file attachment, then save it
private void safeFilesFromMIME(MIMEEntity mime, String fileName) throws NotesException {
Session session = ExtLibUtil.getCurrentSession(); // or user variableResolver
Stream stream = session.createStream();
String pathname = tempPath + fileName;
stream.open(pathname, "binary");
mime.getContentAsBytes(stream);
stream.close();
}

Resources