Highcharts-Export Server for Java JSON parsing issue - highcharts

I configured the highchart export server for Java from the current master in GitHub. When I tried to export an image using the demo page a corrupted file was returned. I have debugged to code and found out the following message is returned as the result in validate method in ServerObjectFactory.java
String result = server.request("{\"status\":\"isok\"}");
The value of the result String is "Failed rendering:SyntaxError: Unable to parse JSON string"
What can be the cause for this issue.
Thank You

That's very strange. The syntax of the JSON string is syntactically correct. I can point out where from the error is generated.
In the highcharts-convert.js file in highcharts-ecport-convert/src/main/resources/phantomjs the incoming request is expected to be a JSON string and is parsed, see Line 469
function (request, response) {
var jsonStr = request.post,
params,
msg;
try {
params = JSON.parse(jsonStr); // L469
if (params.status) {
// for server health validation
response.statusCode = 200;
response.write('OK');
response.close();
} else {
....
Set in a console.log(jsonStr) before JSON.parse(jsonStr) . I hope this give you a clue of why it's throwing a error.

Related

Checking response code of all URLs in a column [Airtable database]

We have an airtable database of over 24000 records. These records are websites, and many now have errors in them (missing "/", extra space...). We are trying to detect the websites that have these errors before manually fixing them.
What we have tried
So far, we have used the fetch method to call each URL and report back on the error status . This is the script we have used:
const inputConfig = input.config();
const url = inputConfig.url;
let status;
try {
const response = await fetch(url);
status = response.status; } catch (error) {
status = 'error'; }
output.set('status', status);
Issues we ran into
The script won't follow redirects, so it reports "error" back if there is a redirect even if the URL is working.
The output now is either "200" meaning the URL works, or "error". We don't get the actual response code of the error, which we ideally would like to get.
Any help would be appreciated! Thanks
There's some nuance to how fetch works. If you review Mozilla's documentation they say:
The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn't in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing.
So you have to do an extra check in your code to determine if the request was successful or not and throw your own error. In your case, you don't necessarily need to throw an error at all and can just rely on ok property of the response.
const config = input.config();
const url = config.url;
let status = null;
const response = await fetch(url);
if(response.ok) {
status = response.status
} else {
status = 'error'
}
output.set('status', status);

Rest Assured Json Path returns Exception

I´m reading json from a file in order to compare it to an http request body´s json.
I´m doing
JsonPath expectedJson = new JsonPath(new File("response.json"));
// some more code
assertThat().body("", equalTo(expectedJson.getMap("")));
which results in JsonPathException: Failed to parse the JSON document
This is the response.json file, which I copied from the response in Postman:
{
"screenDefinition":{
"taskId":"account-type",
"parameters":null
},
"prospect":{
"initializationType":"FIRST_HOLDER",
"jointAccount":{
"jointAccountId":655
},
"emailConfirmed":false,
"addressConfirmed":false,
"emailValidated":false,
"smsCodeAttemptsLeft":0,
"mobilePhoneValidated":false,
"paragraphsAccepted":false,
"termsConditionsAccepted":false,
"changedToAutonomousMethod":false,
"changedToIdentificationMethod":false,
"contractAccepted":false,
"prospectOnboardContactType":"NONE",
"secondAccountHolder":false,
"evidencesUploaded":false,
"uploadEvidencesLater":false
}
}
Any ideas?
That JsonPathException you got is probably caused by java.io.FileNotFoundException which means that path to your file is incorrect.
Try checking if file exists first:
File file = new File("response.json");
System.out.println("File exists: " + file.exists());
JsonPath jsonPath = new JsonPath(file);

Gatling Load test Error : 406 not acceptable on Response

I am new to the gatling load test. And i want to load test my simple project.But I got the error on response(406 not acceptable) and my gatling code is below
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class simu extends Simulation {
val httpConf = http
.baseURL("http://172.24.15.225:10050/sample")
.header(HttpHeaderNames.Accept, HttpHeaderValues.ApplicationJson)
.acceptHeader("application/json, text/plain, */*")
.acceptEncodingHeader("gzip, deflate")
.acceptLanguageHeader("en-US,en;q=0.5")
val scn = scenario("Scenario Name")
.exec(
http("request_1")
.post("http://172.24.15.225:10050/sample")
.header(HttpHeaderNames.Accept, HttpHeaderValues.ApplicationJson)
//.check(status.is(406))
.body(StringBody("""{ "inputData": "Wonderful" }""")).asJSON
)
setUp(scn.inject(atOnceUsers(30)).protocols(httpConf))
}
And the response for the above is
failed in Response
Errors ------------------------------------------------------------
status.find.in(200,304,201,202,203,204,205,206,207,208,209),
but actually found 406
someone please correct my code.
But the RestAPI(postman) returns response correctly.
finally i found an answer. There is no error in the gatling load test. But the problem is my backend coding. I have changed my response from String type into the JSON format like below
object ServiceJsonProtocol extends DefaultJsonProtocol {
implicit val RequestProtocol : RootJsonFormat[Text] = jsonFormat1(Text)//request json format
implicit val ResponseProtocol : RootJsonFormat[SampleText] = jsonFormat1(SampleText) // response json format
}
It works fine

Facing Exception of MessageBodyWriter while sending JSONObject to Rest web service

I am newbie to web service. Due to requirement I have to send a file[most probably in txt format] to server through REST web service.
I am getting the exception like below.
MessageBodyWriter not found for media type=application/json, type=class gvjava.org.json.JSONObject, genericType=class gvjava.org.json.JSONObject.
Here is my web service method.
#Path("{c}")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String convert(#PathParam("c") JSONObject object) throws JSONException {
String result = "";
return "<ctofservice>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>";
}
Now client code is like below
JSONObject data_file = new JSONObject();
data_file.put("file_name", uploadFile.getName());
data_file.put("description", "Something about my file....");
data_file.put("file", uploadFile);
Client client = ClientBuilder.newClient();
webTarget = client.target(uploadURL).path("ctofservice").path("convert");
Response value = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(data_file,MediaType.APPLICATION_JSON_TYPE),
Response.class);
Please help me with this.
Thanks in advance.
------------------------------------------------------------------------
As suggested by peeskillet in the answer below, I tried to send file through multipart. Still I am facing exception of no octet stream found.
Below is my rest api
#Path("{c}")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response convert(#FormDataParam("file") FormDataContentDisposition file) {
String result = "";
Some operation with attached parameter ...
return Response.status(200).entity(result).build();
}
Here is my test client
FormDataMultiPart multiPart = new FormDataMultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
uploadFile,MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(fileDataBodyPart);
Client client = Client.create();
WebResource webResource = client
.resource(uploadURL).path("ctofservice");
ClientResponse response = webResource.accept("application/json")
.post(ClientResponse.class,multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
And I am getting the exception below
I am not able to understand why I need to send data as MediaType.APPLICATION_OCTET_STREAM_TYPE ? As I have used multipart as media type before ...
I appreciate your help..
Without needing to configuring anything else, the easiest way to get around this is to just use a String instead of the actual JSONObject (i.e. just passing toString())
.post(Entity.json(data_file.toString()))
The problem with using JSONObject is that there is no provider that knows how to handle the conversion. You will have the same problem on the server side, where there is no provider to handle the conversion to JSONObject. So you will need to just do
#POST
public Response post(String json) {
JSONObject jsonObject = new JSONObject(json);
}
If you really want to be able to just use JSONObject without needing to use a String, then you should check out this post.
As an aside, this is not valid JSON (it's XML)
"<ctofservice>" + "<ctofoutput>" + result + "</ctofoutput>" + "</ctofservice>"
but you are saying that the endpoint returns JSON

URL encoding in java and decoding in javascript

I have an URL to encode on my java serveur and then to decode with javascript.
I try to retrieve a String I send in param with java. It is an error message from a form validation function.
I do it like that (server side. Worker.doValidateForm() return a String) :
response.sendRedirect(URLEncoder.encode("form.html?" + Worker.doValidateForm(), "ISO-8859-1"));
Then, in my javascript, I do that :
function retrieveParam() {
var error = window.location.search;
decodeURIComponent(error);
if(error)
alert(error);
}
Of course it doesn't work. Not the same encoding I guess.
So my question is : which method can I use in Java to be able to decode my URL with javascript ?
It's ok ! I have found a solution.
Server side with Java :
URI uri = null;
try {
uri = new URI("http", "localhost:8080", "/PrizeWheel/form.html", Worker.doValidateForm(), null);
} catch (URISyntaxException e) {
this.log.error("class Worker / method doPost:", e); // Just writing the error in my log file
}
String url = uri.toASCIIString();
response.sendRedirect(url);
And in the Javascript (function called in the onload of the redirected page) :
function retrieveParam() {
var error = decodeURI(window.location.search).substring(1);
if(error)
alert(error);
}
You don't use URLEncoder to encode URLs, it us used to encode form data to application/x-www-form-urlencoded MIME format. You use URIEncoder instead, see http://contextroot.blogspot.fi/2012/04/encoding-urls-in-java-is-quite-trivial.html

Resources