As mentioned in my previous articles about using VAVR together with Spring, use the following classes to make VAVRs Option and all Collection types based on Seq work correctly with SpringDoc. Just place them in a package that gets scanned by Spring!

import com.fasterxml.jackson.databind.JavaType;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverter;
import io.swagger.v3.core.converter.ModelConverterContext;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.Schema;
import java.util.Iterator;
import org.springframework.stereotype.Component;
@Component
public class VavrOptionSupportConverter implements ModelConverter {
@Override
public Schema resolve(
AnnotatedType annotatedType, ModelConverterContext context, Iterator<ModelConverter> chain) {
JavaType javaType = Json.mapper().constructType(annotatedType.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (io.vavr.control.Option.class.equals(cls)) {
annotatedType =
new AnnotatedType()
.type(javaType.containedType(0))
.ctxAnnotations(annotatedType.getCtxAnnotations())
.parent(annotatedType.getParent())
.schemaProperty(annotatedType.isSchemaProperty())
.name(annotatedType.getName())
.resolveAsRef(annotatedType.isResolveAsRef())
.jsonViewAnnotation(annotatedType.getJsonViewAnnotation())
.propertyName(annotatedType.getPropertyName())
.skipOverride(true);
return this.resolve(annotatedType, context, chain);
}
}
return (chain.hasNext()) ? chain.next().resolve(annotatedType, context, chain) : null;
}
}

import com.fasterxml.jackson.databind.JavaType;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.core.converter.ModelConverter;
import io.swagger.v3.core.converter.ModelConverterContext;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import java.util.Iterator;
import org.springframework.stereotype.Component;
@Component
public class VavrSeqSupportConverter implements ModelConverter {
@Override
public Schema resolve(
AnnotatedType annotatedType, ModelConverterContext context, Iterator<ModelConverter> chain) {
JavaType javaType = Json.mapper().constructType(annotatedType.getType());
if (javaType != null) {
Class<?> cls = javaType.getRawClass();
if (io.vavr.collection.Seq.class.isAssignableFrom(cls)) {
annotatedType =
new AnnotatedType()
.type(javaType.containedType(0))
.ctxAnnotations(annotatedType.getCtxAnnotations())
.parent(annotatedType.getParent())
.schemaProperty(annotatedType.isSchemaProperty())
.name(annotatedType.getName())
.resolveAsRef(annotatedType.isResolveAsRef())
.jsonViewAnnotation(annotatedType.getJsonViewAnnotation())
.propertyName(annotatedType.getPropertyName())
.skipOverride(true);
return new ArraySchema().items(this.resolve(annotatedType, context, chain));
}
}
return (chain.hasNext()) ? chain.next().resolve(annotatedType, context, chain) : null;
}
}

A big shoutout to bnasslahsen who provided me with the VavrOptionSupportConverter that I adjusted to work with the collection types (see this issue)

During the Corona crisis, I was in urgent need of a Webcam. While I thought I ordered a Logitech C930e Business webcam, I got shipped a C930c which is basically the same one but the chinese version.

As it is now the second time I was spending time to find drivers / controller software for this piece of hardware, I’ll save the driver links here (for myself and whoever finds this):

MacOSX: LogiCameraSettings_3.0.12.pkg taken from here: https://support.logi.com/hc/en-001/articles/360024693154-Downloads-Webcam-C930e – yes I know it says c930e), but the software works:

For Windows 10, this package worked for me:

https://download01.logi.com/web/ftp/pub/techsupport/cameras/Webcams/LogiCameraSettings_2.10.4.exe

I’m not really sure why Logitech has different versions for europe and china, or why they don’t let us flash the european firmware on the china one, but they’ll probably have their reasons. As my right the return the camera is already over, I’ll be sticking with it for now and just handle the few chinese characters.

As already documented in my previous article about Spring and VAVR, I’m using the Future’s provided by VAVR as return types in my controller.

What I’m also using, is the SpringDoc OpenAPI library to generate my OpenAPI specification. By default, SpringDoc has no clue about VAVR and how to handle its Future type.

Thus, by default, SpringDoc transfers the VAVR-Future into a wrapper and thus creates a Swagger/OpenAPI-Component for this wrapper, having all the methods of VAVRs Future instead of the type it is wrapping.

To disable this, I added the following call to the class configuring my SpringDoc integration:

package com.dominikdorn.sample.configuration;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.vavr.concurrent.Future;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.converters.ConverterUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPIConfiguration {
static {
ConverterUtils.addResponseWrapperToIgnore(Future.class);
}
@Bean
public GroupedOpenApi publicOpenAPI( ) {
return GroupedOpenApi
.builder()
.setGroup("web")
.packagesToScan("com.dominikdorn.sample.web")
.build();
}
@Bean
public GroupedOpenApi v3OpenAPI() {
return GroupedOpenApi
.builder()
.setGroup("v3")
.packagesToScan("com.dominikdorn.sample.v3.web")
.build();
}
}

I’ve specified it in a static block in the component so that it calls the also static method “addResponseWrapperToIgnore” in SpringDocs’ ConverterUtils, telling it to treat VAVRs Future as a wrapper (or better to ignore it and look at the underlying value).

As I’m using VAVR (formerly known as JavaSLang) in my current Spring-Boot project, I was looking for a way to use the futures returned by my services directly instead of converting them to CompletionStages.

My old controller code looked like this:

import io.micrometer.core.annotation.Timed;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.vavr.control.Option;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
@RestController
@Slf4j
@Validated
@AllArgsConstructor
public class ControllerOld implements ControllerHelpers {
final Service service;
@Timed
@GetMapping(path = "${mvc.context-path}/v3/scenario/{scenarioId}/assets/", name = "getAssetList")
@Operation(operationId = "getAssetList", method = "GET",
responses = {
@ApiResponse(responseCode = "200", ref = "#/components/schemas/GetAssetListResponse", description = "success"),
@ApiResponse(responseCode = "400", description = "failure")
},
tags = {"assets"}
)
public CompletableFuture<ResponseEntity<GetAssetListResponse>> getAssetList(
@PathVariable("scenarioId") @Valid ScenarioId scenarioId
) {
val correlationId = CorrelationId.random();
val userId = UserId.of("STATIC") ;
val serviceResponse = service.getScenarioAssets(
new GetScenarioAssetsQuery(
correlationId,
userId,
scenarioId,
)
);
return serviceResponse.map(either > either.map(GetAssetListController.GetAssetListResponse::fromServiceResponse)
.getOrElseThrow(left > badRequest(correlationId, "Failed to get asset list", left.getError())))
.map(ResponseEntity::ok)
.toCompletableFuture(); // converting to completableFuture for spring support
}
}
view raw ControllerOld.java hosted with ❤ by GitHub

as you can see, the return type of the controller is set to be a CompletionStage and we have to convert the vavr-future to that data type manually.

Wouldn’t it be much nicer, to simple be able to return the Future<T> type of vavr directly? This is how the controller should look like!

import io.micrometer.core.annotation.Timed;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.vavr.concurrent.Future;
import io.vavr.control.Option;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Date;
@RestController
@Slf4j
@Validated
@AllArgsConstructor
public class ControllerNew implements ControllerHelpers {
final Service service;
@Timed
@GetMapping(path = "${mvc.context-path}/v3/scenario/{scenarioId}/assets/", name = "getAssetList")
@Operation(operationId = "getAssetList", method = "GET",
responses = {
@ApiResponse(responseCode = "200", ref = "#/components/schemas/GetAssetListResponse", description = "success"),
@ApiResponse(responseCode = "400", description = "failure")
},
tags = {"assets"}
)
public Future<ResponseEntity<GetAssetListResponse>> getAssetList(
@PathVariable("scenarioId") @Valid ScenarioId scenarioId
) {
val correlationId = CorrelationId.random();
val userId = UserId.of("STATIC") ;
val serviceResponse = service.getScenarioAssets(
new GetScenarioAssetsQuery(
correlationId,
userId,
scenarioId,
)
);
return serviceResponse.map(either > either.map(GetAssetListController.GetAssetListResponse::fromServiceResponse)
.getOrElseThrow(left > badRequest(correlationId, "Failed to get asset list", left.getError())))
.map(ResponseEntity::ok)
; // no more converting to completableFuture
}
….
}
view raw ControllerNew.java hosted with ❤ by GitHub

Awesome, so no more converting to CompletableFuture. But how do we get there?

As long as there is no published project containing the following file, we have to add it ourselves:

package com.dominikdorn.web.configuration;
import io.vavr.concurrent.Future;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
// implementing AsyncHandlerMethodReturnValueHandler makes sure that this ReturnValueHandler is processed before
// normal value handlers (which would transform the future to a json value)
// see https://github.com/spring-projects/spring-framework/issues/17674 for details
public class VavrFutureHandlerMethodReturnValueHandler implements AsyncHandlerMethodReturnValueHandler {
public VavrFutureHandlerMethodReturnValueHandler() {
}
@Override
public boolean supportsReturnType(MethodParameter returnType) {
Class<?> type = returnType.getParameterType();
return Future.class.isAssignableFrom(type);
}
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
DeferredResult<?> result;
if (returnValue instanceof Future) {
result = adaptVavrFuture((Future<?>) returnValue);
} else {
// Should not happen…
throw new IllegalStateException("Unexpected return value type: " + returnValue);
}
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer);
}
private DeferredResult<Object> adaptVavrFuture(Future<?> future) {
DeferredResult<Object> result = new DeferredResult<>();
future
.onSuccess(result::setResult)
.onFailure(result::setErrorResult);
return result;
}
@Override
public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) {
return returnValue instanceof Future;
}
}

We’re specifying our own “HandlerMethodReturnValueHandler” . Important here is that it implements the “AsyncHandlerMethodReturnValueHandler” interface which makes sure that Spring will handle this handler before normal handlers that e.g. transform values to json.

After that, we simply need to register this Handler with Spring. Most likely, you already have a WebMvcConfigurer in your project. If yes, just add the “addReturnValueHandlers” method to your existing one or create a completely new one like I did here:

package com.dominikdorn.web.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebMvcConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
// … configure all kinds of things here, like how to handle cors etc.
return new WebMvcConfigurer() {
@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
handlers.add(new VavrFutureHandlerMethodReturnValueHandler());
}
};
}
}

Enjoy using your vavr-futures in your Spring Boot applications now.

In an upcoming post I’ll probably look on how to effectively work with the Either type of Vavr (because I can’t stand these nasty exceptions just to return expected error states!)

Like what you see? Let me know in the comments!

If you’re developing Scala apps and let them be checked by Codacy, you might have enabled the check “Imports should be sorted alphabetically“.
What sounds easy, isn’t in fact.

Here are my findings, summarised as example imports.

import akka.actor.ActorRef import akka.Done // upper/lowercase doesn't matter import akka.streams.Source import java.util.ArrayList // this needs to be in the middle of the packages, most IDEs put it into an extra block import mycompany.mypackage._ // underscore is always before import mycompany.mypackage.mysubpackage.mysubsubpackage.A import mycompany.mypackage.{ClassA, ClassB, ClassC} import mycompany.otherpackage.SomeProtocol // space before dot import mycompany.otherpackage.SomeProtocol.{MessageA, MessageB} import org.slf4j.LoggerFactory import pureconfig._ // again, underscore before import pureconfig.generic.{ExportMacros, ProductHint} import scala.concurrent.{ExecutionContext, Future} import scala.collection.JavaConverters._ import scala.io.Source import scala.util.{Failure, Success} // normal IDEs put all scala.* classes into an extra block at the end of all import statements import slick.basic.DatabaseConfig import slick.jdbc.JdbcProfile

I hope this helps someone.. I’m sure, I’ll check back on this page in about a week again….

In an event-sourced environment, you sometimes have to introduce an artificial delay to some actions to make sure read-sides had the time to update themselves. If you’re using the classic routing mechanism with a routes-file, you can add such a delay declaratively, like here:

+ delay800 PUT /products/:productId controllers.ProductCRUDController.update(productId: UUID)

This would delay the response of the update-action by 800 Milliseconds, hopefully giving the other consuming services enough time to catch up.

To make this work, you have to add a filter to your application, like this one:

import akka.actor.ActorSystem import akka.stream.Materializer import play.api.mvc.{Filter, RequestHeader, Result} import play.api.routing.Router import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future} class DelayFilter(val mat: Materializer, implicit val ec: ExecutionContext, actorSystem: ActorSystem) extends Filter { override def apply(nextFilter: RequestHeader => Future[Result])(rh: RequestHeader): Future[Result] = { val handler = rh.attrs.get(Router.Attrs.HandlerDef) val delay: Option[Int] = handler .flatMap( _.modifiers .find(s => s.startsWith("delay"))) .map(s => Integer.parseInt(s.substring("delay".length))) .filter(_ > 0) val result = nextFilter.apply(rh) delay match { case Some(d) => akka.pattern.after(d.millis, actorSystem.scheduler)(result) case None => result } } }

and of course, enable the filter in your application.conf

play.filters.enabled+=mypackage.filters.DelayFilter

Did this help you in your project? Let me know in the comments!

If you have to create a stored procedure in your PlayFramework Database Evolution Script, make sure to properly escape your semicolons (by using two semicolons):

CREATE OR REPLACE FUNCTION user_insert_update_query_function() RETURNS TRIGGER AS $$ BEGIN NEW.query := lower(NEW.firstname) || '|' || lower(NEW.lastname);; RETURN NEW;; END;; $$ LANGUAGE 'plpgsql';

I recently wanted to play a DVD, where I only had the bare folder structure. KODI is supposed to support this, but its not working yet, so I ended up creating the dvd-image on my server myself.

This assumes, that you have stored the VIDEO_TS folder in my_dvd

# add an additional AUDIO_TS folder mkdir my_dvd/AUDIO_TS # create a iso from the folders genisoimage -dvd-video -v -o my.iso my_dvd/

Thanks to Ron999 in the Ubuntu-Forums

Recently, I’ve implemented a Swagger-API with Play. As I’ve published a new version of the API, I wanted to make a CHANGELOG available.

So the question was, where to store this file.. a blog or some other external resource felt plainly wrong, so I decided to put it right next to the code.

class ChangeLogController (cc: ControllerComponents) extends AbstractController(cc) { implicit val ec: ExecutionContext = cc.executionContext def changeLog = cc.actionBuilder.apply { req => val clazz = this.getClass val resource = Option(clazz.getResourceAsStream(“/de/some/package/structure/api/v1_1/CHANGELOG.txt”)) resource .map(s => StreamConverters.fromInputStream(() => s)) .map(source => { Result( header = ResponseHeader(play.api.http.Status.OK, Map.empty, None), body = HttpEntity.Streamed(source, None, Some(“text/plain”)) ) }) .getOrElse(Results.InternalServerError(“failed to load file from classpath”)) } }

I have a MacBook Pro 15″ Mid-2015 Retina. It uses a 85W MagSafe 2 Power Adapter, which is emitting max 4.25 Ampere at 20 Volts.




According to

https://omnicharge.zendesk.com/hc/en-us/articles/115000623608-Step-3-How-to-use-DC-output, that means,
I’ll have to configure my OmniCharge to 20V DC Output

 

To do this:

  • Turn the Omnicharge on
  • Double Click the Power button, Menu appears
  • Click the Power Button to enter DC Configuration
  • Use the UP-DOWN Arrows to select “Presets”, press Power Button to enter
  • Select 20V, use Power Button to select
  • Change to “Yes”, use Power Button to confirm
  • Done

 

top