While executing below code in eclipse its working but not working in bean shell ? it displaying error near writer.write(data);
So please help me out how can we pass string array from beanshell to csv
import java.io.*;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.List;
int i;
File file = new File("/home/sarvesh/Desktop/sgi/10");
int filecount = file.list().length;
File[] files = file.listFiles();
String[] imageString = new String[filecount];
for ( i =0;i<filecount;i++) {
File f = new File(files[i].getAbsolutePath());
FileInputStream fis = new FileInputStream(f);
byte [] byteArray = new byte[(int) f.length()];
fis.read(byteArray);
imageString[i] = Base64.getEncoder().encodeToString(byteArray);
//vars.put("imagData",imageString[i]);
FileWriter writer = new FileWriter("/home/sarvesh/Desktop/sgi/base64_csv.csv");
// List<String> data = new ArrayList<String>();
ArrayList data = new ArrayList();
data.add(new String[] {imageString[i] });
**writer.write(data);**
// writer.write(imageString[i]);
// writer.close();
System.out.println("***********************************************");
System.out.println("Base 64 conversion of Image : " + i + " ::" + imageString[i]);
System.out.println("File Path : " + f.getAbsolutePath());
System.out.println("***********************************************");
}
Beanshell is not Java, it doesn't support diamond operators therefore you need to change this line:
List<String> data = new ArrayList<String>();
to this one:
List data = new ArrayList();
Starting from JMeter 3.1 you should rather be using JSR223 Test Elements and Groovy language for scripting
Your approach will work given you run your test with 1 thread (virtual user), if there will be more users - you'll run into the race condition resulting into file corruption/data loss so if you need to write some specific data into some specific file it's better to go for the Flexible File Writer. Alternatively you can use Critical Section Controller but it will slow down your test
Related
Exp -
In a text file we have the following topics with some description.
#Repeat the annotation
It is the major topic for .....
#Vector analysis
It covers all the aspects of sequential....
#Cloud Computing
Create header accounts for all the users
We have to add / append new Tags to the Topics in specific line
For exp-
#Repeat the annotation #Maven build
#Cloud Computing #SecondYear
File f = new File("/user/imp/value/GSTR.txt");
FileReader fr = new FileReader(f);
Object fr1;
while((fr1 = fr.read()) != null) {
if(fr1.equals("#Repeat the annotation")) {
FileWriter fw = new FileWriter(f,true);
fw.write("#Maven build");
fw.close();
}
}
****** #Maven is getting added to the last line of the text file but not at the specific position next to the topic
The output is written to the file GSTR_modified.txt. The code along with an example input file is also available here. The code in the github repository reads the file "input.txt" and writes to the file "output.txt".
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
// Create a list to store the file content.
ArrayList<String> list = new ArrayList<>();
// Store the file content in the list. Each line becomes an element in the list.
try (BufferedReader br = new BufferedReader(new FileReader("/user/imp/value/GSTR.txt""))) {
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
}
// Iterate the list of lines.
for (int i = 0; i < list.size(); i++) {
// line is the element at the index i.
String line = list.get(i);
// Check if a line is equal to "#Repeat the annotation"
if (line.contains("#Repeat the annotation")){
// Set the list element at index i to the line itself concatenated with
// the string " #Maven build".
list.set(i,line.concat(" #Maven build"));
}
// Same pattern as above.
if (line.contains("#Cloud Computing")){
list.set(i,line.concat(" #SecondYear"));
}
}
// Write the contents of the list to a file.
FileWriter writer = new FileWriter("GSTR_modified.txt");
for(String str: list) {
// Append newline character \n to each element
// and write it to file.
writer.write(str+"\n");
}
writer.close();
}
}
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.
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;
}
}
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");
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.