Extend XMLHttpRequest in Scala.js - xmlhttprequest

I'm extending XMLHttpRequest in Scala.js:
class ReasonerHttpRequest(val reasonerId: String) extends XMLHttpRequest {}
Then, I try to create:
val http = new ReasonerHttpRequest(reasonerId)
This result in the following error:
TypeError: $g.ReasonerHttpRequest is not a constructor
What am I doing wrong? Thanks!

Related

How to customise the response body when "401 Unauthorized" occurred?

Instead of an empty response body when "401 Unauthorized" occurs, I want to add the other information into the response (e.g timestamp, a message), how can I override it?
Expectation:
HTTP status: 401 Unauthorized
Response body:
{
"timestamp": 1234567890,
"message": "Your access token was expired"
}
I'm using the Helidon MP v2.5.5
To customize the response body when a "401 Unauthorized" error occurs in Helidon, you can handle the error in the error handling mechanism provided by Helidon. You can write your custom logic inside the error handling mechanism to return the desired response.
Here is an example code to demonstrate the same:
server.addErrorHandler(401, ex ->
ServerResponse
.status(401)
.header("Content-Type", "text/plain")
.send("Unauthorized Error Occurred!")
);
This code will return a response with a 401 status code and the response body "Unauthorized Error Occurred!" whenever a 401 error is encountered in the server.
Take a look at ExceptionMapper class in javax/jakarta. You can create a Provider that implements the ExceptionMapper using BadRequestException. Then override the toResponse method of ExceptionMapper. That way you can customize the response.
Some code doing this could look like this:
#Provider
#NoArgsConstructor
public class <YourExceptionHandler> implements ExceptionMapper<BadRequestException> {
#Override
public Response toResponse(BadRequestException exception){
<custom code>
return Response.status(<status>).entity(<custom code>).build()
}
}
In my case, for the custom code part I instance a class that handles the error's status, error message, etc...

Bad Request Error (400) or Not Found Error (404) during extracting request parameters in jax-rs

In docs.oracle ( https://docs.oracle.com/javaee/7/tutorial/jaxrs002.htm ) about Extracting Request Parameters we have:
If the URI path template variable cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 400 (“Bad Request”) error to the client.
If the #PathParam annotation cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 404 (“Not Found”) error to the client.
Could someone explain the difference, maybe give an example?
I don't know why, but if you define method with path param and it fails on cast string to custom type, jax-rs (in my case jersey servlet) returns 404 error, and it's very strange and unexpected.
package com.example.jaxrs.api;
...
#GET
#Path("/{id}/info")
public Response info(#PathParam UUID id) { ... }
curl -X GET http://127.0.0.1:8080/api/123/info --> HTTP ERROR 404 Not Found
This behavior can be changed. Just create simple ExceptionMapper, catch the ParamException, and return correct "400 Bad Request" response.
package com.example.jaxrs.errors;
#Provider
public class PathParamExceptionMapper implements ExceptionMapper<ParamException> {
#Override
public Response toResponse(ParamException exception) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
Do not forgot annotation #Provider and add the package with error handler to servlet init param.
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.example.jaxrs.api;com.example.jaxrs.errors</param-value>
</init-param>
</servlet>

Is it possible to possible to achieve with Jersey a polymorphic deserialisation of json payloads on POST resources

I'd like a endpoint to accept on a single verb and path a json payload that varies by a tiny bit and that can be mapped to different objects. The variation is usually on the field value like the grant_type in the OAuth world.
I scrapped stackoverflow and google on this, I found this among other
JAX-RS polymorphic POST request: how should I write my JSON?
Polymorphism in JSON, Jersey and Jackson
But those question don't seem to be relevant to me, jackson deserialisation alone works fine for this payloads, but Jersey always refuses to init the servlet with an error that let me thinks there's no way around it.
#Path("parent")
interface Resource {
#POST
#Path("test")
String test(Payload1 payload1);
#POST
#Path("test")
String test(Payload2 payload1);
#Data
#JsonTypeName("payload1")
class Payload1 extends BasePayload {
String a;
}
#Data
#JsonTypeName("payload2")
class Payload2 extends BasePayload {
String b;
}
// #JsonTypeInfo(use= Id.MINIMAL_CLASS, include=As.PROPERTY, property="#class")
#JsonTypeInfo(use= Id.NAME, include=As.PROPERTY, property="#payload")
#JsonSubTypes({
#JsonSubTypes.Type(value = Payload1.class),
#JsonSubTypes.Type(value = Payload2.class)
})
class BasePayload {
}
However I get this message in an exception upon servlet initialisation. (edited message for clarity)
</pre><p><b>root cause</b></p><pre>
org.glassfish.jersey.server.model.ModelValidationException:
Validation of the application resource model has failed during application initialization.
[[FATAL] A resource model has
ambiguous (sub-)resource method for HTTP method POST and input mime-types as defined by
"#Consumes" and "#Produces" annotations
at Java methods
public java.lang.String xxx.Service.test(xxx.Resource$Payload1)
and
public java.lang.String xxx.Service.test(xxx.Resource$Payload2)
at matching regular expression /test.
These two methods produces and consumes exactly the same mime-types and
therefore their invocation as a resource methods will always fail.;
source='org.glassfish.jersey.server.model.RuntimeResource#59b668bf']
Note however that having a endpoint with the parent class of the payload works, but you have to handle the dispatch yourself.
#POST
#Path("test")
String test(BasePayload payload);
I'm using Spring-Boot 1.4 / Jersey 2.23.2 / Jackson 2.8.5
The JAX-RS runtime uses the following for matching requests to resource methods:
URI: Defined in the #Path annotation.
Request method: Defined by a resource method designator such as #GET, #POST, etc).
Media type: Defined in Accept and Content-Type headers, that are matched with the values defined in the #Produces and #Consumes annotations, respectively.
The content of the payload is not taken into account, so it makes your first method definition ambiguous.
As you already figured out, the following approach is the way to go:
#POST
#Path("test")
String test(BasePayload payload);

Retrofit 2.0 Header Interceptor vs Method Headers

There seems to be some discrepancy between using method headers and intercepting headers with OKHTTP and retrofit.
I'm looking to intercept each retrofit request going through my retrofit interface. I've written an Interceptor to go through OKHTTP like so:
OkHttpClient client = new OkHttpClient();
client.interceptors()
.add(ThisClass::onRequestIntercept);
...
private static Response onRequestIntercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", "auth")
.header("Accept", "json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
But the server throws a 401 error unless I also add the following above each and every method in the retrofit interface:
#Headers({
"Authorization: auth",
"Accept: json"
})
The logs are identical for both headers with and without the second header annotation - only that the one with the second header directly above the method goes through with 200, and if only the intercepted code is used it returns a 401 error code.
What could be the discrepancy?

Permission denied: cannot call non-public or static methods remotely

in my code there are no "non-public" or "static" methods. All are public.I'm creating a Custom tool class, but However when I try to invoke a method from this class on the remote object I get stuck with an exception:
Permission denied: cannot call non-public or static methods remotely.
Fails at the following line everytime.
public ref class CustomTool : public Tool
{
public:
CustomTool():Tool()
{
}
};
CustomTool ^cs = gcnew CustomTool();
window->SetTool(cs); // here
Maybe the issue is with the method "SetTool" rather than the object "cs".
How does SetTool looks like?