Cucumber\Rest Assured: How to get the request specs? - cucumber

I have the following step:
#Given("Request specifications are set with base uri {string}")
public void setRequestsSpec(String baseUri){
requestSpecification = new RequestSpecBuilder()
.setBaseUri(baseUri)
.addFilter(new ResponseLoggingFilter())//log request and response for better debugging. You can also only log if a requests fails.
.addFilter(new RequestLoggingFilter())
.addFilter(new RcAllureFilter())
.build();
Then I have:
#When("^Azure Login Request Executed$")
public void azureLoginExecuted() {
response =
given() //Add x-www-form-urlencoded body params:
.spec(testContext().getRequestSpec())
.formParam(GRANT_TYPE_KEY, GRANT_TYPE_VALUE)
.formParam(AUTO_TEAM_CLIENT_ID_KEY, AUTO_TEAM_CLIENT_ID_VALUE)
.formParam(AUTO_TEAM_CLIENT_SECRET_KEY, AUTO_TEAM_CLIENT_SECRET_VALUE)
.formParam(RESOURCE_KEY, RESOURCE_VALUE)
.when()
.post(AUTO_TEAM_TENANT_ID + RESOURCE); //Send the request along with the resource
setAuthorizationToken();
}
How can I extract the request's details like URI, headers and parameters from it?
I cannot find a class from which I can extract the request details.
In RequestSpecification class, I hardly can find any getter functions in this class.
I need this values in order to build a formatted log message.
Is there another way?

if you are trying to get the details from requestspecification, then you can use like this .
RequestSpecification spec = new RequestSpecBuilder().setContentType(ContentType.JSON).addHeader("h1", "h2")
.build();
QueryableRequestSpecification queryable = SpecificationQuerier.query(spec);
System.out.println(" Content is " + queryable.getContentType());
System.out.println(" Header is " + queryable.getHeaders().getValue("h1"));
But in your scenario, you want request details too. so , best way would be to use a requestlogging filter, which accepts a PrintStream (which in turn can work With ByteArrayOutPutStream which can convert to a String ) . Basic idea is, to use RequestLoggingFilter with a PRintStream and then use any code to save PrintStream to a String. You can usr StringWriter too.
RequestSpecification spec = new RequestSpecBuilder().build();
StringWriter requestWriter = new StringWriter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(baos);
Response response = given().spec(spec).contentType(ContentType.JSON)
.filter(new RequestLoggingFilter(printStream)).get("https://jsonplaceholder.typicode.com/todos/1");
printStream.flush();
System.out.println(baos);

Related

facing issues in executing Azure vision api

Hello All I am using Azure's vision analyze api to extract text from my documents,
here is the example code for your reference
//My main function fi.fullfile is the path of my uploaded document
AzureAnalyzeRequest(System.IO.File.ReadAllBytes(fi.FullName));
analyze function
static async void AzureAnalyzeRequest(byte[] byteData)
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "MyKey");
// Request parameters
queryString["language"] = "en";
queryString["pages"] = "1,2";
var uri = "https://url-ocr.cognitiveservices.azure.com/vision/v3.2/read/analyze?" + queryString;
HttpResponseMessage response;
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
}
}
when the above function executed I am getting the error of 400 bad request
but when I tested my api on the below URL
Azure Vision api
it worked fine.
what I am doing wrong here?
According to this MSDOCS the api needs a Json object in the following form:
{
"url":""
}
I think you are passing a byte array, you need a Json object which will contain a URL of the image you want to process.
So here I have created a class called Poco which will host the URL variable.
public class Poco
{
public string url { get; set; }
}
Then I initialized the class and passed the URL then convert that object into a Json object.
Poco p = new Poco();
p.url = "<URL OF YOUR IMAGE>";
string json = JsonConvert.SerializeObject(p);
// Here we are converting the json string to stringcontent which we can pass to httpclient
StringContent data = new StringContent(json, Encoding.UTF8, "application/json");
Now all you have to do is call the Api:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<YOURKEY>");
var response = client.PostAsync(url, data);
Console.WriteLine(response.Result.StatusCode);
Console.WriteLine(response.Result);
If you want to use the byte array of image, then I think the content-type header should be application/octet-stream according to this MSDOC

downloading file from Spring Rest Controller

I am trying to download a file through Spring REST Controller. Below is my code -
#RequestMapping(value="/aaa",method=RequestMethod.GET,produces=MediaType.APPLICATION_OCTATE_STREAM_VALUE)
public ResponseEntity<byte[]> testMethod(#RequestParam("test") String test) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentDispositionFromData("attachment","testExcel.xlsx");
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
File file = new File("C:\\testExcel.xlsx");
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllbytes(path));
return new ResposeEntity<byte[]>(resource.getByteArray(),responseHeaders,HttpStatus.OK);
}
This is called in a button click. After I click the button nothing happens. While debugging this java, I could see the bytestream. In developer tools of Mozilla, I could see successful HTTP response(response in bytestream of that excel file). As per resources available on internet, browser should automatically download the file, but that's not happening.
Why downloading is not happening in browser? What's more I need to do to make it work?
NOTE : This is just for POC purpose. In actual time, I have to generate the excel file from database details, through Apache POI or some other APIs.
The below works for me:
#RequestMapping("/")
public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
FileInputStream inputStream = new FileInputStream(new File("C:\\work\\boot\\pom.xml"));
response.setHeader("Content-Disposition", "attachment; filename=\"testExcel.xlsx\"");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.copy(inputStream, outputStream);
outputStream.close();
inputStream.close();
}
What worked in my case was to make server send the following header:
Access-Control-Expose-Headers: Content-Disposition
So my problem had to do with CSRF issue.
Change the code like this:
public HttpEntity<byte[]> testMethod(#RequestParam("test") String test) {
File file = new File("C:\\testExcel.xlsx");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] array = IOUtils.toByteArray(fileInputStream);
HttpHeaders header = new HttpHeaders();
header.set("Content-type","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header.set("Content-Disposition", "attachment; filename=" + nameyouwantsaveyourfile + ".xlsx");
header.setContentLength(array.length);
fileInputStream.close();
return new HttpEntity<byte[]>(array, header);
}

how get JSON from URL

I need to read with the function SSJS fromJson() a URL.
For example the Data access API for a Notes View
http://{host}/{database}/api/data/collections/name/{name}
How can I do this ?
P.S I think (I don't know if is true) that if I use Java code
(for example the class URLReader from this blogger, I
lose authors/readers functionality because is my server and not the current user that execute the reading of the stream?
I'll explain why I'm trying to understand this...
I need to use this plugin JQuery Jquery Data Tables in my app.
I need a complete Server-side processing because I have over 10.000 documents for any view.
This jQueryPlugin send a parameters to a specif URL (I think my XAgent) so that I think to create a XAgent that read this parameter and parsing a JSON API Data for the output.
This because I need a fasted response.
The solution of Oliver Busse it very slow because load all entries of my view in a JSON (I have many entries) and I wait 30/40 seconds for this operation
I gather from the PS that you're specifically looking to fetch JSON on the server from itself, while retaining user authentication information. Sven's post there does a bit of that, but I think that the most reliable way would be to grab the Authorization and Cookie headers from the request and then pass them along in your URL request. This answer has a good basis for doing this with Java. You could expand that to do something like this (which, granted, I haven't tested, but it's a starting point):
HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String authorization = req.getHeader("Authorization");
String cookie = req.getHeader("Cookie");
URL myURL = new URL("http://foo.com");
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
if(StringUtil.isNotEmpty(authorization)) {
myURLConnection.setRequestProperty("Authorization", authorization);
}
if(StringUtil.isNotEmpty(cookie)) {
myURLConnection.setRequestProperty("Cookie", cookie);
}
myURLConnection.setRequestMethod("GET");
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.connect();
InputStream is = null;
try {
is = myURLConnection.getInputStream();
String result = StreamUtil.readString(is);
} finally {
StreamUtil.close(is);
myURLConnection.disconnect();
}
Ideally, you would also fetch the server host name, protocol, and port from the request.
Eric's comment is also wise: if this is something you can do with the normal classes, that's going to be more flexible and less problem-prone, due to how fiddly server-self HTTP calls can be.
As I mentioned in my comment, this approach forces that your call go through a client-side call to the Domino Data Service and otherwise complicates a normal handle to establish on a View (and it's contents) via a cross-NSF call (e.g.- var vwEnt:ViewEntryCollection = session.getDatabase("serverName", "path/myDb.nsf").getView("viewName").getAllEntries();).
As a blog post of mine previously outlines, you can definitely achieve this as Jesse's answer (curse you fast typer Jesse!) outlines. Something I include in my "grab bag" of tools is a Java class that's a starting point for getting JSON formatted content. Here's the link (here's one with basic authorization in a request header) and the class I generally start from:
package com.eric.awesome;
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import com.google.gson.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.commons.validator.routines.*;
/**
* Class with a single, public, static method to provide a REST consumer
* which returns data as a JsonObject.
*
* #author Eric McCormick, #edm00se
*
*/
public class CustJsonConsumer {
/**
* Method for receiving HTTP JSON GET request against a RESTful URL data source.
*
* #param myUrlStr the URL of the REST endpoint
* #return JsonObject containing the data from the REST response.
* #throws IOException
* #throws MalformedURLException
* #throws ParseException
*/
public static JsonObject GetMyRestData( String myUrlStr ) throws IOException, MalformedURLException {
JsonObject myRestData = new JsonObject();
try{
UrlValidator defaultValidator = new UrlValidator();
if(defaultValidator.isValid(myUrlStr)){
URL myUrl = new URL(myUrlStr);
URLConnection urlCon = myUrl.openConnection();
urlCon.setConnectTimeout(5000);
InputStream is = urlCon.getInputStream();
InputStreamReader isR = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isR);
StringBuffer buffer = new StringBuffer();
String line = "";
while( (line = reader.readLine()) != null ){
buffer.append(line);
}
reader.close();
JsonParser parser = new JsonParser();
myRestData = (JsonObject) parser.parse(buffer.toString());
return myRestData;
}else{
myRestData.addProperty("error", "URL failed validation by Apache Commmons URL Validator");
return myRestData;
}
}catch( MalformedURLException e ){
e.printStackTrace();
myRestData.addProperty("error", e.toString());
return myRestData;
}catch( IOException e ){
e.printStackTrace();
myRestData.addProperty("error", e.toString());
return myRestData;
}
}
}
To invoke from SSJS as a POJO, you would want do something like:
importPackage(com.eric.awesome);
var urlStr = "http://{host}/{database}/api/data/collections/name/{name}";
var myStuff:JsonObject = CustJsonConsumer.GetMyRestData(urlStr);

Tyrus - pass object from client to server

Is it posible to pass custom object from client to server, using Tyrus project for websocket communication. I want to build simple desktop application using JavaFX. How can I pass data that I "collect" on client side (e.g. Object Person with name and lastname fields) so I can save that data to database (on my server logic) ?
It is possible and the form of transferred data is completely your choice.
WebSocket can transfer text or binary data, that's it. You can serialize your obect to ObjectStream and send the data as binary stream, or You can use use JAXB to marshall and umarshall data to/from XML, or JSON-P for JSON (note that there are lots of other possibilities, like GSON, Jackson, ...).
If I would be in your position, I'd use JSON with whatever library I find usable - this way, when you'll extend the application scope to javascript clients, you'll be able to reuse (hopefully) everything.
In addition to Pavel Bucek explanation, sample code is here
Base64 for conversion
import java.util.Base64;
Serverendpoint
ArrayList listobj=new ArrayList();
listobj.add("data1");
listobj.add("data2");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(listobj);
String str = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
session.getBasicRemote().sendText(str);
Client (Tyrus)
#OnMessage
public void onMessage(Session session, final String message) throws IOException {
try {
byte data[] = Base64.getDecoder().decode(message);
bis = new ByteArrayInputStream(data);
ois = new ObjectInputStream(bis);
ArrayList list= (ArrayList) ois.readObject();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (Exception e) {
System.out.println("error : " + e.getMessage());
} finally {
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
}
}

Use AbstractJExcelView to generate excel file and send through MailSender in Spring Framework

Currently my project uses a Controller class and utilizes AbstractJExcelView Class to generate an Excel Report which gives a prompt to user to either open or save the excel file. Basicall it uses http protocol for calling the controller.
Now what I need to do is generate the same excel file during (Spring) batch jobs and send it as an attachment directly through email. We're using org.springframework.mail.MailSender for sending mails.
I'm not supposed to use any other external API and I have no clue where to start from.
This is a similar code of what we're doing :-
Controller
public class RevenueReportController extends AbstractController{
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String output =
ServletRequestUtils.getStringParameter(request, "output");
//dummy data
Map<String,String> revenueData = new HashMap<String,String>();
revenueData.put("Jan-2010", "$100,000,000");
revenueData.put("Feb-2010", "$110,000,000");
revenueData.put("Mar-2010", "$130,000,000");
revenueData.put("Apr-2010", "$140,000,000");
revenueData.put("May-2010", "$200,000,000");
if(output ==null || "".equals(output)){
//return normal view
return new ModelAndView("RevenueSummary","revenueData",revenueData);
}else if("EXCEL".equals(output.toUpperCase())){
//return excel view
return new ModelAndView("ExcelRevenueSummary","revenueData",revenueData);
}else{
//return normal view
return new ModelAndView("RevenueSummary","revenueData",revenueData);
}
}
View
public class ExcelRevenueReportView extends AbstractJExcelView{
#Override
protected void buildExcelDocument(Map model, WritableWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
WritableSheet sheet = workbook.createSheet("Revenue Report", 0);
sheet.addCell(new Label(0, 0, "Month"));
sheet.addCell(new Label(1, 0, "Revenue"));
int rowNum = 1;
for (Map.Entry<String, String> entry : revenueData.entrySet()) {
//create the row data
sheet.addCell(new Label(0, rowNum, entry.getKey()));
sheet.addCell(new Label(1, rowNum, entry.getValue()));
rowNum++;
}
}
}
Is there any way to do that ? I need to generate the excel sheet with passed and failed job data. I can handle populating and creating the file but I have no idea how to generate the excel in buffer or may be in some temp directory which could again be attached while sending the mail. The user is not required to respond to any prompts. Neither are we going to use any http request.
Thanks in advance!
There is an MimeMessageItemWriter in Spring Batch that you should be able to use to send the emails. You'll need to create an ItemProcessor that creates the MimeMessage. You can either create the Excel file and add it as an attachment within that ItemProcessor, or have one step generate all the Excel files that need to be sent, then in the next step, you can send them. I have an example of sending emails from Spring Batch in my book: Pro Spring Batch
I did the following in and it served the purpose :-
private ByteArrayOutputStream outputStream;
outputStream = new ByteArrayOutputStream();
WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
.
.
.
.
workbook.write();
workbook.close();
Now, a getter to fetch the value :-
public ByteArrayOutputStream getOutputStream()
{
return this.outputStream;
}
And finally, for email attachement :-
JavaMailSenderImpl sender = new JavaMailSenderImpl();
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(destiny);
helper.setSubject(subject);
helper.setText(msg);
helper.setFrom(from);
.
.
.
FileSystemResource fsr = new FileSystemResource(file);
helper.addAttachment("Sample.xls", fsr);
Thanks for the help guyz!

Resources