error during response creation elasticsearch response from file - java

I try create response from file for testing elasticsearch service
def "FounderHint"() {
setup:
URL url = getClass().getClassLoader().getResource("elastic_response/elastic-founders-hint-response.json")
SearchResponse response = new SearchResponse().readFrom(url.openStream()) // this is a 40 line error
when: "we ask for hint"
elasticClient.search(any()) >> response
metrics.measureHintSearchTime(_) >> response
then: "we get list of ObjectHint"
List<ObjectHint> result = advancedSearchFilter.founderHint("але").collect(Collectors.toList())
result[0].inn == "323500905646"
result[0].name == "Алешина Екатерина Леонидовна"
but i get error -
No signature of method: org.elasticsearch.action.search.SearchResponse.readFrom() is applicable for argument types: (java.io.BufferedInputStream) values: [java.io.BufferedInputStream#19f135ca]
Possible solutions: readFrom(org.elasticsearch.common.io.stream.StreamInput), readFrom(org.elasticsearch.common.io.stream.StreamInput), readFrom(org.elasticsearch.common.io.stream.StreamInput)
groovy.lang.MissingMethodException: No signature of method: org.elasticsearch.action.search.SearchResponse.readFrom() is applicable for argument types: (java.io.BufferedInputStream) values: [java.io.BufferedInputStream#19f135ca]
Possible solutions: readFrom(org.elasticsearch.common.io.stream.StreamInput), readFrom(org.elasticsearch.common.io.stream.StreamInput), readFrom(org.elasticsearch.common.io.stream.StreamInput)
at ru.esphere.informator.refbook.retriever.hint.SearchExternalHintServiceTest.test external hint method for receive correct result(SearchExternalHintServiceTest.groovy:40)
SearchResponse is a class elasticsearch and it does not have setters, are there other ways to create a response or where did I make a mistake?

BufferedInputStream stream = url.openStream()
SearchResponse response = new SearchResponse().readFrom(new StreamInput(stream))
The BufferedInputStream from the first line is transformed into StreamInput, before passing it to readFrom

Related

Spring Cloud Contract - Not able to create contract test with the 'fileAsBytes()' response body being different for consumer() and producer() sides

We do have a service that generates pdf documents dynamically(each request - slightly different PDF document). So I have to create a contract test for that service.
Problem statement
STUB side should return a predefined pdf file as a byte array. - OK
SERVER side should not check the response in assertions, or at least check if it matches by some regexp. - NOT WORKING
Here is my contract.groovy
import org.springframework.cloud.contract.spec.Contract
[
Contract.make {
request {
method "GET"
urlPath("/pdfEndpoint")
}
response {
status 200
headers {
contentType(applicationPdf())
}
body(value(
consumer(fileAsBytes("staticFileToSentOnStubResponse.pdf")),
producer(regex(nonBlank())) /*the issue is with that line*/
))
}
}
]
GenereatedTestClass.java
#Test
public void contractPdf() throws Exception {
// given:
MockMvcRequestSpecification request = given();
// when:
ResponseOptions response = given().spec(request)
.get("/pdfEndpoint");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/pdf.*");
// and:
String responseBody = response.getBody().asString();
assertThat(responseBody).isEqualTo("^\\s*\\S[\\S\\s]*"); // .isEqualTo() but needed matches()
}
Is there any way to update the groovy file to have in the generated class the folowing assertion
assertThat(responseBody).matches("^\\s*\\S[\\S\\s]*");
instead of
assertThat(responseBody).isEqualTo("^\\s*\\S[\\S\\s]*");
UPDATE:
Also, I have noticed that it generates assertThat(..).isEqualTo() in case i have contentType(applicationPdf()) in the response headers.
If I put 'application/json' instead - it will work as expected.
Resources:
org.springframework.cloud:spring-cloud-dependencies - Hoxton.SR8
java11

Posting data using simple JSON - get an error - UnsupportedMediaTypeError: unsupported charset "ISO-8859-1"<br> at jsonParser

I am trying to post data using the a simple JSON object.
First I tried reading the data from a file which was successful.
But when I tried posting data, I get the error.
Posted below is my code snippet for reference.
public static void main(String[] args) {
POJO_PostReq Data = new POJO_PostReq();
Data.setFirstName("Sambhaji");
Data.setLastName("Yadav");
Data.setDesignation("Tech Lead");
Data.setMentorName("Deepak Channa");
Data.setCourseName("API Testing");
Data.setID("1706");
Response Res =
given()
.contentType("application/json")
.body(Data)
.when()
.post("http://localhost:3000/friends");
System.out.println("Status Code for Post Request =: " + Res.getStatusCode());
System.out.println("Data posted is :");
System.out.println(Res.asString());
}
Need help in resolving the error.
This error is usually connected with Content-Type or Accept headers. Try to add and an Accept header.
Check if the two headers are set correctly!

RestAssured Post call with body throws an error "java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <415>."

#Test
public void testPost() throws URISyntaxException {
AgencyRequest agencyRequest = new AgencyRequest();
agencyRequest.setConnectorId(1);
agencyRequest.setJobConfig("/usr/local/workspace/test.config.xml");
agencyRequest.setConnectorName("/usr/local/workspace/test.kjb");
agencyRequest.setRequestId(1);
agencyRequest.setTenantId(1);
agencyRequest.setTenantName("Test Tenant");
agencyRequest.setTimeZone("UTC");
String json = new Gson().toJson(agencyRequest);
System.out.println(json);
System.out.println(uri + "/" + ResourceConstants.JOB_CONFIG);
given().
accept(ContentType.JSON).
body(json).
post(new URI(uri + "/" + ResourceConstants.JOB_CONFIG)).
then().
assertThat().
statusCode(HttpStatus.OK_200);
}
If I run the same test on Postman by choosing the post method and content type as json and with the body, it gave the response status code as 200. But my unit test is not passed. In the body, I have tried passing the json string as you see before as well as I tried passing the java object, both fails.
You need to define the content type of request while sending the request. Consider making the given change
.contentType(ContentType.JSON)
Try adding this line to the top of your code:
.log().all()
.config(RestAssured.config().encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
.header()....
This change will work, try it.
.header("Content-Type", "application/json").contentType(ContentType.JSON).accept(ContentType.JSON)

Respond to a Restful call

I am making a restful call to the servlet doGet() method from my grails code.The doGet() method is called successfully and i am able to see the print statements. Once the doGet() is called i need to send a response back to the restful call that the method has been invoked. How to set the response in the servlet so that it can be sent back to the grails
def getStatus(String tableName) {
try {
def result
def resultList = []
println "attempting to send START signal to http://localhost:9081/ServletSample/ServletSample"
result = rest.get("http://localhost:9081/ServletSample/ServletSample?tableName="+tableName)
println "length "+result.length()
println result.body
resultList.add(result)
log.debug "$result.body"
resultList.each {
println "$it.body"
if (it.status == 200) {
if (it.body == "Starting")
{
println ("starting up")
in the servlet i am trying to set the response as
response.setContentLength(5);
response.setStatus(200);
but it is not getting received. I am getting the following exception
Exception occured in rest service() groovy.lang.MissingMethodException: No signature of method: grails.plugins.rest.client.RestResponse.length() is applicable for argument types: () values: []
Possible solutions: getAt(java.lang.String), each(groovy.lang.Closure), with(groovy.lang.Closure), wait(), getXml(), every() from class java.net.URL
You need to convert java object into json string and write it into HttpServletResponse. Here is code:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
String json = new Gson().toJson(someObject);
out.write(json);
To convert java object into json string I used Google Gson
But you can manually create json string if it is easy

HTTP 500 error when invoking Apache Stanbol REST endpoint in Solr Analyzer

I am writing a Solr custom analyzer to post a value of a field to Apache Stanbol for enhancement during indexing phase.
In my custom analyzer's incrementToken() method I have below code. I'm posting the value of the token to Stanbol enhancer endpoint using a Jersey REST client. Instead of the expected enhacement result I always get a HTTP 500 error response when running the analyzer.
But the same REST client logic works when executing it in a Java application main method.
Can someone please help me identify where the problem is? Could it be a Java permission problem, invoking a web endpoint within the Solr analyzer?
public boolean incrementToken() throws IOException {
if (!input.incrementToken()) {
return false;
}
char[] buffer = charTermAttr.buffer();
String content = new String(buffer);
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/enhancer");
ClientResponse response = webResource.type("text/plain").accept(new MediaType("application", "rdf+xml")).post(ClientResponse.class, content);
int status = response.getStatus();
if (status != 200 && status != 201 && status != 202) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println(output);
charTermAttr.setEmpty();
char[] newBuffer = output.toCharArray();
charTermAttr.copyBuffer(newBuffer, 0, newBuffer.length);
return true;
}
This seems to be a weird intermittent issue when I use the Solr Analysis UI (http://localhost:8983/solr/#/collection1/analysis) for testing my Analyzer.
It works fine when I hard code the input value in the Analyzer and index. I gave the same input : "Tim Bernes Lee is a professor at MIT" hard coded in the Analyzer class and from the Solr Analysis UI. The UI response failed intermittently when I adjust the field value.
This could be a problem with character encoding of the field value it seems.

Categories

Resources