Kotlin reactor MultiPart processing in RestController - kotlin

I'm trying to convert a Java Spring Reactive RestController to Kotlin coroutine based RestController. Here's the signature of the Java RestController.
#PostMapping(path = "/{db}/manifest/{asset_id}")
Mono<PushResult> pushManifest(
#PathVariable(name = "db") String db,
#PathVariable(name = "asset_id") String assetId,
#RequestPart(name = "manifest") Mono<FilePart> manifest,
#RequestPart(name = "head", required = false) Mono<FilePart> head
) {
}
While I can easily change Mono<FilePart> to just FilePart, to read the content of FilePart I have to deal with Flux<DataBuffer>, whereas in Kotlin it would be preferable to always deal with Flow<DataBuffer>.
Is there a Kotlin equivalent for dealing with multipart requests in Spring Reactive that uses the Kotlin native reactive types, such as Flow?

Related

Initialize SNSEvent.java with SNS Event String

I'm working with an in-house framework to consume S3Events. The current framework can handle plain S3EventNotifications by getting the events InputStream, and passing it like below...
String inputStream = CharStreams.toString( new InputStreamReader(eventInputStream, StandardCharsets.UTF_8));
S3EventNotification s3EventNotification = S3EventNotification.parseJson(inputStream);
For technical reasons, I now need to update this framework to use SNS Events, which are quite different from a raw JSON perspective. I'm hoping to find an SNSEvent equivelant of S3EventNotification so I can do something like below...
String inputStream = CharStreams.toString( new InputStreamReader(eventInputStream, StandardCharsets.UTF_8));
SNSEvent snsEvent = SomethingGoesHere.parseJson(inputStream);
Is there anything like that out there? I've looked through a few of the aws-java-sdk's as well as the aws-lambda-java-events artifacts out there in Maven world but can't seem to find anything suitable to this. Any ideas?
EDIT With Solution
Ended up settling with the SNSEvent.java object located in the aws-lambda-java-events jar from Maven. I used Gson with a DateTime adapter to handle the DateTime Timestamp within that object as well as the UPPER_CAMEL_CASE naming policy since the SNS Event from amazon is camel cased, seems to work fine!
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() {
#Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new DateTime(json.getAsString());
}
}).create();
SNSEvent snsEvent = gson.fromJson(event, SNSEvent.class);

How do you mock a URL connection in Kotlin?

I've seen a lot of examples on how to mock a connection in Java but haven't seen any explaining how to do it in Kotlin. A bit of code that I want mocked as an example:
val url = URL("https://google.ca")
val conn = url.openConnection() as HttpURLConnection
with(conn) {
//doStuff
}
conn.disconnect()
Similar to a question like this but for Kotlin:
how to mock a URL connection
Kotlin and Java can interop with one another, so you should be able to take your exact example (from the question) provided and convert it to Kotlin (or don't convert it and call the Java directly):
#Throws(Exception::class)
fun function() {
val r = RuleEngineUtil()
val u = PowerMockito.mock(URL::class.java)
val url = "http://www.sdsgle.com"
PowerMockito.whenNew(URL::class.java).withArguments(url).thenReturn(u)
val huc = PowerMockito.mock(HttpURLConnection::class.java)
PowerMockito.`when`(u.openConnection()).thenReturn(huc)
PowerMockito.`when`(huc.getResponseCode()).thenReturn(200)
assertTrue(r.isUrlAccessible(url))
}
It's worth noting that you should probably consider using an actual mocking HTTP server like HttpMocker for handling this as opposed to implement the behavior yourself.

Adding custom Response header to Spring WebFlux contoller endpoint

Is there a way to add a response header to spring webflux controller endpoint? for example to the following method I have to add a custom header say 'x-my-header'
#GetMapping(value = "/search/{text}")
#ResponseStatus(value = HttpStatus.OK)
public Flux<SearchResult> search(#PathVariable(
value = "text") String text){
return searchService().find(text);
}
In the functional API, this is really easy; the ServerResponse builder has builders for almost everything you need.
With the annotated controllers; you can return an ResponseEntity<Flux<T>> and set the headers:
#GetMapping(value = "/search/{text}")
public ResponseEntity<Flux<SearchResult>> search(#PathVariable(
value = "text") String text) {
Flux<SearchResult> results = searchService().find(text);
return ResponseEntity.ok()
.header("headername", "headervalue")
.body(results);
}
Note that the updated code doesn't need the #ResponseStatus annotation now.
UPDATE:
Apparently the solution above works; unless you have spring-cloud-starter-netflix-hystrix-dashboard dependency. In that case you can use the following code:
#GetMapping(value = "/search/{text}")
public Mono<ResponseEntity<List<SearchResult>>> search(#PathVariable(
value = "text") String text) {
return searchService().find(text)
.collectList()
.map(list -> ResponseEntity.ok()
.header("Header-Name", "headervalue")
.body(list));
}
A couple of things to note:
Outer type should be Mono<ResponseEntity<T>>: There is one response for request. If you declare it to be a Flux, Spring will try to deserialize the ResponseEntity as if it was a POJO.
You need to use an operator to transform the Flux into a Mono: collectList() or single() will do the job for you.
Checked with Spring Boot 2.0.3.RELEASE

Http query parameters needs to be extract in Java for Mule Application?

I am new to Mule. My question is how to extract HTTP parameters inside a java component. I tried this in Java class of Mule application. The query param name is id But it's not actually working
So far I tried the following: ---
MuleMessage message = eventContext.getMessage();
String id = message.getInboundProperty("id");
I am getting null value. How to extract that in Java class. An example will be great
This is very easy. You can use following in your Java:
MuleMessage muleMessage = eventContext.getMessage();
Map<String, String> queryParams = muleMessage.getInboundProperty("http.query.params");
String id=queryParams.get("id");
System.out.println(id);
return muleMessage;

object de/serialization using dart

I have to serialize some WebRTC-related dart objects to send them over a signaling channel. As example I have to encode RtcSessionDescription and RtcIceCandidate instances. Both classes offer a constructor to build them in context of a given map, but no one offers a method to create such a Map out of the original object.
How can I generate strings? Do I have to make a detour over Map-objects?
As Example:
RtcSessionDescription -> Map -> String -(send_over_signalingChannel)-> String -> Map -> RtcSessionDescription
You can easily convert between Map and String using the dart:convert package.
https://www.dartlang.org/articles/json-web-service/
I don't know about RtcSessionDescription <-> Map though.
See also this question: Can I automatically serialize a Dart object to send over a Web Socket?
Finally I found a solution (using dart:convert as Günther Zöchbauer suggested):
RtcSessionDescription original = ...;
//serialize
final String serialized_sdp = JSON.encode({
'sdp':original.sdp,
'type':original.type
});
//decode
final Map sdp_map = JSON.decode(serialized_sdp);
RtcSessionDescription sdp = new RtcSessionDescription(sdp_map);