Unable to append to next line in a file through beanshell assertion sampler in Jmeter - jmeter

Have 2 steps in my JMeter script. Login and Second getting the orders, inside the login thread group I am using a bean shell assertion to validating few conditions and once I hit with an error I am writing the error to a log file. So for the first thread, it is writing it correctly but when it reaches the next assertion it overwrites the same file without appending it.
First Assertion:
import org.apache.jmeter.assertions.AssertionResult;
String failureMessage = "";
String successMessage = "";
String ResCode =SampleResult.getResponseDataAsString();
if (!ResCode.contains("Admin") )
{
failureMessage = "Got Response Code" + ResCode;
log.warn("Creation of a new record failed: Response code " + ResCode);
AssertionResult result = new AssertionResult("Expected Response 200");
result.setFailure(true);
result.setFailureMessage(failureMessage);
prev.addAssertionResult(result);
prev.setSuccessful(false);
SampleResult.setStartNextThreadLoop(true);
}
else {
successMessage = "Got Response Code" + ResCode;
log.info("----->"+successMessage);
FileOutputStream logfile = new FileOutputStream(vars.get("LogFile"));
PrintStream printtoFile = new PrintStream(logfile);
printtoFile.println( successMessage );
printtoFile.close();
logfile.close();
}
Second Assertion:
import org.apache.jmeter.assertions.AssertionResult;
String failureOrderMessage = "";
String successOrderMessage = "";
OrderId = vars.get("workOrderId");
log.info("----->"+OrderId);
if (OrderId == null){
failureOrderMessage = "The Order Id :"+OrderId;
log.info("----->"+failureOrderMessage);
FileOutputStream logfile = new FileOutputStream(vars.get("LogFile"));
PrintStream printtoFile = new PrintStream(logfile);
printtoFile.println( failureOrderMessage );
printtoFile.close();
logfile.close();
}
else {
successOrderMessage = "Getting few order id";
log.info("----->"+successOrderMessage);
}
The above assertion is working fine, but every time its overwrite the log file but I want to append it.
Second
FileOutputStream logfile = new FileOutputStream(vars.get("LogFile"));
PrintStream printtoFile = new PrintStream(logfile);
printtoFile.println( successMessage );
printtoFile.close();
logfile.close();
Do I need to every time declare the above code snippet to write to the log file?

You need to create FileOutputStream with append flag:
FileOutputStream logfile = new FileOutputStream(vars.get("LogFile"), true);
append - if true, then bytes will be written to the end of the file rather than the beginning

Related

Rename a recorded file every time I save a record in xamarin

I am saving my records using this code:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
public string fileName { get; set; }
fileName = Path.Combine(path, "sample.wav");
if (!recorder.IsRecording)
{
recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;
//Start recording
var audioRecordTask = await recorder.StartRecording();
BtnDoneRec.IsEnabled = false;
await audioRecordTask;
RecEditor.IsEnabled = true;
BtnDoneRec.IsEnabled = false;
PlayButton.IsEnabled = true;
var filePath = recorder.GetAudioFilePath();
if (filePath != null)
{
var stream = recorder.GetAudioFileStream();
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
}
else
{
//stop recording ...
await recorder.StopRecording();
}
I want my record to have a specific name which is labeled with my RecEditor
using (var streamReader = new StreamReader(fileName))
{
File.Move("sample.wav", RecEditor.Text + ".wav");
}
So it will rename "sample.wav" to "RecEditor text.wav" every time I click my save button.
But when I click save, it gives me this record
System.IO.FileNotFoundException: 'Could not find file '/sample.wav'.'
The record is stored in /storage/emulated/0/sample.wav
The sample.wav is created in my device but I don't know why it give me 'Could not find file '/sample.wav'.' error. What am i doing wrong here?
I believe that what you're looking is something like this:
if(File.Exists(fileName))
{
var newFileName = Path.Combine(path, $"{RecEditor.Text}.wav");
File.Move(fileName, newFileName);
}
You don't need to open a new Stream as you are doing. Also, you need to put the full file path not only the file name.
You might want to validate that RecEditor.Text is not empty before using its value for the newfileName
Hope this helps.-

How to write the data from Mysql into a file using jdbc code and file writer?

String selectTableSQL = "select JobID, MetadataJson from raasjobs join metadata using (JobID) where JobCreatedDate > '2014-07-01';";
File file = new File("/users/t_shetd/file.txt");
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
System.out.println(selectTableSQL);
// execute select SQL stetement
ResultSet rs = statement.executeQuery(selectTableSQL);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while (rs.next()) {
String JobID = rs.getString("JobID");
String Metadata = rs.getString("MetadataJson");
bw.write(selectTableSQL);
bw.close();
System.out.println("Done");
// Now i am only getting the output done
If I understand your question, then this
while (rs.next()) {
String JobID = rs.getString("JobID");
String Metadata = rs.getString("MetadataJson");
bw.write(selectTableSQL);
bw.close();
System.out.println("Done");
}
Should be something like (following Java capitalization conventions),
while (rs.next()) {
String jobId = rs.getString("JobID");
String metaData = rs.getString("MetadataJson");
bw.write(String.format("Job ID: %s, MetaData: %s", jobId, metaData));
}
bw.close(); // <-- finish writing first!
System.out.println("Done");
In your version, you close the output after printing the first line from the ResultSet. After that, nothing else will write (because the File is closed).

Writing CSV to MemoryStream using LinqToCSV does not return any data

I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.
However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.
Here is my Action Method
public FileStreamResult Export(){
var results = _service.GetProperties().Take(3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter txt = new System.IO.StreamWriter(ms);
CsvFileDescription inputFileDescription = new CsvFileDescription{
SeparatorChar =',',
FirstLineHasColumnNames = true
}
;
CsvContext csv = new CsvContext();
csv.Write(results,txt,inputFileDescription);
return File(ms , "application/x-excel");
}
I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.
Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.
Calling the Web API method to return CVS file from JavaScript.
public HttpResponseMessage Bidreport([FromBody]int formData).....
Fill in your IEnumerable<YourObject>query = from LINQ query
....
This is how to return it:
using (var ms = new MemoryStream())
{
using (TextWriter txt = new StreamWriter(ms))
{
var cc = new CsvContext();
cc.Write(query, txt, outputFileDescription);
txt.Flush();
ms.Position = 0;
var fileData = Encoding.ASCII.GetString(ms.ToArray());
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
return result;
}
}

Export C# List to Csv file

I was trying to export my C# list to Csv file. All is set well. But the thing is field seperator is not working properly. its showing like, my string with " at the end (eg: 0000324df"). Here is my Controller code.
IEnumerable stockexpo = stockexp; // Assign value
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("ItemNo,");
writer.Write("Repeat Count");
writer.WriteLine();
foreach (StockResult order in stockexpo)
{
writer.Write(String.Format("{0:d}", order.ItemNumber));
writer.Write("\"");
writer.Write(",");
writer.Write("\"");
writer.Write(order.Count);
writer.Write("\"");
writer.Write(",");
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "stockexp.csv");
I need to know how i can seperate the field values appropriately. Anyone can help me for this.
writer.Write("\"");
This line of code will be outputting a " every time. Why have it at all?
Also, I wouldn't have a comma before the WriteLine, since there is no need to delimit the end of the file.
IEnumerable stockexpo = stockexp; // Assign value
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("ItemNo,");
writer.Write("Repeat Count");
writer.WriteLine();
foreach (StockResult order in stockexpo)
{
writer.Write(order.ItemNumber);
writer.Write(",");
writer.Write(order.Count);
writer.WriteLine();
}
writer.Flush();
output.Position = 0;
return File(output, "text/comma-separated-values", "stockexp.csv");

Jmeter value to variable in string

How do i replace a variable defined in a file (a.xml) after the file is read into Jmeter ?
eg. a.xml has a content.
<Shipment Action="MODIFY" OrderNo="${vOrderNo}" >
The entire file is read into a string using
str_Input=${__FileToString(/a.xml)}
In the Jmx file, a http Request is made to get output from a webservice as
Using Xpath Extractor the value of OrderNo is read into a Variable vOrderNo.
Now, wanted to use the value of variable vOrderNo in the str_Input.. ? How do i ?
You can easily achieve this using beanshell (~java) code from any jmeter's sampler which allows beanshell code execution - BeanShell Sampler e.g..
The following works:
import java.io.*;
try
{
// reading file into buffer
StringBuilder data = new StringBuilder();
BufferedReader in = new BufferedReader(new FileReader("d:\\test.xml"));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = in.read(buf)) != -1) {
data.append(buf, 0, numRead);
}
in.close();
// replacing stub with actual value
String vOrderNo = vars.get("vOrderNo");
String temp = data.toString().replaceAll("\\$\\{vOrderNo\\}", vOrderNo);
// writing back into file
Writer out = new BufferedWriter(new FileWriter("d:\\test.xml"));
out.write(temp);
out.close();
}
catch (Exception ex) {
IsSuccess = false;
log.error(ex.getMessage());
System.err.println(ex.getMessage());
}
catch (Throwable thex) {
System.err.println(thex.getMessage());
}
This code doesn't require read file into string via ${__FileToString(...)}.
As well, you can combine both methods.

Resources