How to write webservice response to a json file? - java

I am getting the response from webservice request which I am able to print on the console. I want to write this response to a json file. I tried with buffereWriter but it did not write.
String cwd = System.getProperty("user.dir");
buffereWriter writer = new buffereWriter (new File writer(cwd + "filepath"));
Writer.write(response);
// This response is being currently displayed in the console correctly.
There are no error or exception but the content is not getting written in the file.

You can use FileWriter for that. Also a try block with resources which will guarantee your file will be closed.
try(FileWriter fw = new FileWriter(cwd + "filepath")){
fw.write(response); //I guess the response is a String.
}catch(Exception ignored){}

Related

RestAssured + Java - how can I save to string or to file the Request that sent to the server?

Using intellij, Java and restassured:
I am sending the request as needed and I added this to my code:
public static Response PostInstinctQuery() throws IOException, ParseException {
PrintStream fileOutPutStream = new PrintStream(new File("request_log.txt"));
config = config().logConfig(new LogConfig().defaultStream(fileOutPutStream));
RestAssured.baseURI = BASEURI;
RequestSpecification request = RestAssured.given();
//Headers
request.header("Key",key);
request.body(getJson());
request.log().all();
Response response = request.post(PATH);
return response;
}
That is save the request in "request_log.txt" file.
so what is the problem ? the file shows the same request over and over.
If I use TestNG diff data then I would expect that the file will contain all the diff request.
And I really want the request to be able to save in a String variable for assert / report purposes also.
Thanks!
I think you can use RequestLoggingFilter to config one time, no need log().all().
OutputStream file = new FileOutputStream("request_log.txt");
PrintStream stream = new PrintStream(file, true);
RestAssured.filters(RequestLoggingFilter.logRequestTo(stream));

Sending xls via API with Java apache poi and React

I'm trying to send a xls file from my java spring server to react client.
Using default Apache POI constructors creates xlsx file, that's not good. In order to override it I have to create the file using FileOutputStream.
FileOutputStream outputStream = new FileOutputStream("file.xls");
But I cannot sent the file over the web. I've tried using the following answer: https://stackoverflow.com/a/54765335/10319765 I quote: "While downloading a file , your code needs to stream a file chunk by chunk - thats what Java streams are for."
return ResponseEntity.ok().contentLength(inputStreamWrapper.getByteCount())
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.cacheControl(CacheControl.noCache())
.header("Content-Disposition", "attachment; filename=" + "file.xls")
.body(new InputStreamResource(inputStreamWrapper.getByteArrayInputStream()));
so my controller is sending InputStreamResource.
How can I construct InputStreamResource using my FileOutputStream?
P.S this is my React client:
axios.get('/issues/export', { responseType: 'arraybuffer' }).then(response => {
if (response && !response.error) {
const blob = new Blob([response.payload.data], {type: 'application/vnd.ms-excel'});
saveAs(blob);
}
});
Source: https://stackoverflow.com/a/46331201/10319765
Edit:
I've managed to do that with a trick, right after I've written to the FileOutputStream I've opened a FileInputStream and returned the value.
FileOutputStream outputStream = new FileOutputStream("file.xls");
workbook.write(outputStream);
workbook.close();
final InputStream fileInputStream = new FileInputStream("file.xls");
return fileInputStream;
but now, the xls file returned as response to the client is corrupted and has weird characters inside:
The excel file should look the following (taken from my java server after sending it):
Issue solved. Eventually what I did in order to solve the corrupted xls file is to work with byte arrays. the controller looks exactly the same but now the return type is ResponseEntity<byte[]>. To convert the InputStream to byte array I've used IOUtils.toByteArray() method.
Client side code has also changed a bit because now the type is no longer responseType: 'arraybuffer' but 'blob'.
axios.get('/issues/export', { responseType: 'blob' }).then(response => {
if (response && !response.error) {
const blob = new Blob([response.payload.data]);
saveAs(blob);
}
});
That's all.

Appending data in a CSV in selenium automation

I have a CSV file in Resources of my automation script and I need to amend one cell value to a parameter value I get by creating a folder in a site, I ran this code but then an error comes:
"(The process cannot access the file because it is being used by another process)".
Can anyone let me know how to write my parameter value to CSV file cell, please.
TIA
Method:
public static void writeCSV(String filePath, String separator) throws IOException {
try (OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(filePath));
Writer outStreamWriter = new OutputStreamWriter(fileStream, StandardCharsets.UTF_8);
BufferedWriter buffWriter = new BufferedWriter(outStreamWriter)) {
buffWriter.append("https://mobile/sample_v4.zip");
buffWriter.append(separator);
buffWriter.append(createdTitle);
buffWriter.append(separator);
buffWriter.append("http://2-title-conversion/documentlibrary");
buffWriter.append(separator);
buffWriter.append("TRUE");
buffWriter.append(separator);
buffWriter.append("TRUE");
buffWriter.flush();
}
#Test segment,
loginPg.writeCSV("C:\\Users\\urathya\\Documents\\Automation\\03-11\\resources\\CS.csv",",");
You are not closing the output stream, please close it, it will close file and you can use the same file to append the data.

Java JSON - gson - appending new data, malformed JSON

I am using Gson to write to and read from a file.
each time a user is created, I append a line which shows Username and ID.
I do this with the following (UserAccount being my pojo class, br is my buffered reader)::
UserAccount accountObj = new UserAccount();
FileWriter writer = new FileWriter("store.json", true);
accountObj.setUser(NewUserMethod());
accountObj.setID(NewIDMethod());
String json = gson.toJson(accountObj);
writer.write(json);
writer.close();
This makes the json file, which works - like this ::
{"USER":"noob123","ID":"99"}
When a new user does it, It will append the next line like so ::
{"USER":"noob123","ID":99}{"USER":"pro321","ID":100}
When I attempt to read this json file, I got the following error ::
"use JsonReader.setLenient(true) to accept malformed JSON at line 1, column 36"
So I understand it may be incorrect format and may need something like ::
{"ACCOUNT":{"USER":"noob123","ID":99},"ACCOUNT":{"USER":"pro321","ID":100}}
I have spent some time trying to create JSON in this format, or at least reference to the correct USER key when the matching USER name is used. Any help is greatly appreciated.
Thanks
You should use JSONArray to save this information into file. Then you can read content of file into list of UserAccount, add new object into this list.
Then you should override content of file.
E.g. :
UserAccount accountObj = new UserAccount();
accountObj.setUser(NewUserMethod());
accountObj.setID(NewIDMethod());
List<UserAccount> userAccounts = gson.fromJson(<jsonContent>, new TypeToken<List<UserAccount>>() {
}.getType());
userAccounts.add(accountObj);
String json = gson.toJson(userAccounts);
writer.write(json);
writer.close();

Write an array of bytes representing an IP packet to a pcap file

I capture an IPv4 packet in an app like ToyVpn To make sure I handle the read packet correctly I was told to save it and the response I create to a pcap file and open it in WireShark.
I use jnetpcap-1.3.0-1.win64
As for writing to the file, I found an answer on https://stackoverflow.com/a/19170377/1065835
Both examples from http://jnetpcap.com/node/69 throw the same NPE here:
PcapDumper dumper = pcap.dumpOpen(ofile); // output file
Is it possible to do what I'm trying to do?
This is my code:
StringBuilder errbuf = new StringBuilder();
String fname = "test-afs.pcap";
new File(fname).createNewFile();
Pcap pcap = Pcap.openOffline(fname, errbuf);
String ofile = "tmp-capture-file.cap";
new File(ofile).createNewFile();
PcapDumper dumper = pcap.dumpOpen(ofile); // output file
pcap.loop(10, dumper); // Special native dumper call to loop
File file = new File(ofile);
System.out.printf("%s file has %d bytes in it!\n", ofile, file.length());
dumper.close(); // Won't be able to delete without explicit close
pcap.close();
The JavaDoc for Pcap.dumpOpen() states
Parameters: fname - specifies the name of the file to open; currently the libpcap option to open stdout by using "-" as a string, is not supported by jNetPcap
You're creating the very file that Pcap is going to open in the next LoC. That's not going to work, I think...:
String ofile = "tmp-capture-file.cap";
new File(ofile).createNewFile();
PcapDumper dumper = pcap.dumpOpen(ofile); // output file - BUT IT EXISTS!
In either case, you might get lucky surrounding the line with a try-catch and see if Pcap.getErr() has anything meaningful in the catch clause, but I'm betting on an already-exists issue.
Cheers,

Categories