Quarkus - Resource with #Path("/") ignored, instead loading content from resources - quarkus

Trying to configure a JAX-RS resource with #Path("/"), however, the resource is ignored and the first file found in resources is loaded.
Any idea how to prevent this and allow the resource to work?
When clearing META-INF/resources, the JAX-RS resource loads correctly.
Using:
Quarkus 1.4.2.Final
openjdk version "11.0.6" 2020-01-14 LTS
OpenJDK Runtime Environment Zulu11.37+52-SA (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.37+52-SA (build 11.0.6+10-LTS, mixed mode)
Resource:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/")
public class LandingResource {
#GET
#Produces(MediaType.TEXT_HTML)
public String getLandingPage() {
return "<html><head><title>Hello World</title></head><body>Hello!</body></html>";
}
}
Testing:
curl --location --request GET 'http://localhost:8080/'
Response:
<!doctype html>
<html lang="en">
<head>
<title>Internal Server Error - Error handling cee4cff3-551d-44e1-9102-5c9ada9d8fb2-7, java.nio.file.InvalidPathException: Illegal char &lt;:&gt; at index 97: <tempdir>\vertx-cache\file-cache-71fbfca9-5ba3-4a3e-8020-8501379cbf2b\<project dir>\src\main\resources\META-INF\resources\assets\icons\icon-128x128.png</title>
<meta charset="utf-8">
<style>
html, body {
margin: 0;
padding: 0;
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
font-size: 100%;
font-weight: 100;
line-height: 1.4;
}
...

Achieved the desired outcome by adding a vertx web route:
import io.quarkus.vertx.web.Route;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.RoutingContext;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class LandingRoute {
#Route(path = "/", methods = HttpMethod.GET)
public void landing(RoutingContext rc) {
rc.response().end("hello ");
}
}
In order to use #Route annotation you need to add quarkus-reactive-routes extension (io.quarkus:quarkus-reactive-routes) to project.
You can find more information about reactive routes in Quarkus documentation at:
https://quarkus.io/guides/reactive-routes

By default Quarkus will serve static resources from the root context.
That means that the resources inside src/main/resources/META-INF/resources/ are already mapped to root (http://localhost:8080/). This means that you can not map a standard JAX-RS on the root easily.
See the documentation for further information: https://quarkus.io/guides/http-reference
In your case you are returning a fixed HTML landing page. As a solution you could remove the LandingResource class and serve the landing page from the static resources.
This can be achieved by placing the HTML snippet in src/main/resources/META-INF/resources/index.html.
This is also how the default Quarkus default landing page is served.

Related

How to change swagger-ui.html default path

I wanna change my swagger-ui path from localhost:8080/swagger-ui.html to
localhost:8080/myapi/swagger-ui.html in springboot
redirect is helpless to me
In the application.properties of Spring Boot
springdoc.swagger-ui.path=/swagger-ui-custom.html
in your case it will be
springdoc.swagger-ui.path=/myapi/swagger-ui.html
if for some reason you don't want redirect to /swagger-ui.html you can set itself contents as home view, setting an index.html at resources/static/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to another awesome Microservice</title>
</head>
<body>
<script>
document.body.innerHTML = '<object type="text/html" data="/swagger-ui.html" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"></object>';
</script>
</body>
</html>
then accessing to your http://localhost:8080/ you will see your swagger docs.
finally you can customize path and .html file using:
registry.addViewController("/swagger").setViewName("forward:/index.html");
like suggests this answer
You can modify springfox properties in application.properties
For example, to edit the base-url
springfox.documentation.swagger-ui.base-url=documentation
For e.g. setting it to /documentation will put swagger-ui at /documentation/swagger-ui/index.html
If you want to add, for example, documentation prefix - You can do like this for path http://localhost:8080/documentation/swagger-ui.html:
kotlin
#Configuration
#EnableSwagger2
#ConfigurationPropertiesScan("your.package.config")
#Import(value = [BeanValidatorPluginsConfiguration::class])
class SwaggerConfiguration(
private val swaggerContactProp: SwaggerContactProp, private val swaggerProp: SwaggerProp
) : WebMvcConfigurationSupport() {
// https://springfox.github.io/springfox/docs/current/
#Bean
fun api(): Docket = Docket(DocumentationType.SWAGGER_2)
.groupName("Cards")
.apiInfo(getApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("your.controllers.folder"))
.paths(PathSelectors.any())
.build()
private fun getApiInfo(): ApiInfo {
val contact = Contact(swaggerContactProp.name, swaggerContactProp.url, swaggerContactProp.mail)
return ApiInfoBuilder()
.title(swaggerProp.title)
.description(swaggerProp.description)
.version(swaggerProp.version)
.contact(contact)
.build()
}
override fun addViewControllers(registry: ViewControllerRegistry) {
with(registry) {
addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true)
addRedirectViewController(
"/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui"
)
addRedirectViewController(
"/documentation/swagger-resources/configuration/security", "/swagger-resources/configuration/security"
)
addRedirectViewController("/documentation/swagger-resources", "/swagger-resources")
}
}
override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
registry.addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/")
}
}
#ConfigurationProperties(prefix = "swagger")
#ConstructorBinding
data class SwaggerProp(val title: String, val description: String, val version: String)
#ConfigurationProperties(prefix = "swagger.contact")
#ConstructorBinding
data class SwaggerContactProp(val mail: String, val url: String, val name: String)
and in applicatiom.yml:
swagger:
title: Cards
version: 1.0
description: Documentation for API
contact:
mail: email#gmail.com
url: some-url.com
name: COLABA card
Also don't forget to add in build.gradle.kts:
implementation("io.springfox:springfox-swagger2:$swagger")
implementation("io.springfox:springfox-swagger-ui:$swagger")
implementation("io.springfox:springfox-bean-validators:$swagger")
I've found several possible solutions for myself. Maybe it will be helpful for somebody else.
Set springdoc.swagger-ui.path directly
The straightforward way is to set property springdoc.swagger-ui.path=/custom/path. It will work perfectly if you can hardcode swagger path in your application.
Override springdoc.swagger-ui.path property
You can change default swagger-ui path programmatically using ApplicationListener<ApplicationPreparedEvent>. The idea is simple - override springdoc.swagger-ui.path=/custom/path before your Spring Boot application starts.
#Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {
#Override
public void onApplicationEvent(final ApplicationPreparedEvent event) {
ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
Properties props = new Properties();
props.put("springdoc.swagger-ui.path", swaggerPath());
environment.getPropertySources()
.addFirst(new PropertiesPropertySource("programmatically", props));
}
private String swaggerPath() {
return "/swagger/path"; //todo: implement your logic here.
}
}
In this case, you must register the listener before your application start:
#SpringBootApplication
#OpenAPIDefinition(info = #Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class App {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(App.class);
application.addListeners(new SwaggerConfiguration());
application.run(args);
}
}
Redirect using controller
You can also register your own controller and make a simple redirect as suggested there.
Redirect code for Spring WebFlux applications:
#RestController
public class SwaggerEndpoint {
#GetMapping("/custom/path")
public Mono<Void> api(ServerHttpResponse response) {
response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
response.getHeaders().setLocation(URI.create("/swagger-ui.html"));
return response.setComplete();
}
}
The problem with such an approach - your server will still respond if you call it by address "/swagger-ui.html".
You can use this code, it worked for me
package com.swagger.api.redirect;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class SwaggerApiReDirector implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs");
registry.addRedirectViewController("/documentation/configuration/ui", "/configuration/ui");
registry.addRedirectViewController("/documentation/configuration/security", "/configuration/security");
registry.addRedirectViewController("/documentation/swagger-resources", "/swagger-resources");
registry.addRedirectViewController("/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
registry.addRedirectViewController("/documentation", "/documentation/swagger-ui.html");
registry.addRedirectViewController("/documentation/", "/documentation/swagger-ui.html");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/");
}
}
If you are using spring boot then please update
application.properties file and write here
server.servlet.context-path=/myapi
it will redirect you as you want.

Spring Boot, static resources and mime type configuration

I'm facing a Spring Boot configuration issue I can't deal with...
I'm trying to build an HelloWorld example for HbbTV with Spring Boot, so I need to serve my "index.html" page with mime-type="application/vnd.hbbtv.xhtml+xml"
my index.html will be accessed as a static page, for instance http://myserver.com/index.html?param=value.
with the following code, no matter how hard I try, I get a text/html content type.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//HbbTV//1.1.1//EN" "http://www.hbbtv.org/dtd/HbbTV-1.1.1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>MyApp HBBTV</title>
<meta http-equiv="content-type" content="Content-Type: application/vnd.hbbtv.xhtml+xml; charset=UTF-8" />
</head>
<body>
...
</body>
</html>
So I tried to add a "home()" endpoint into a #Controller to force the correct mime-type, and that works.
#RestController
public class HbbTVController {
#RequestMapping(value = "/hbbtv", produces = "application/vnd.hbbtv.xhtml+xml")
String home() {
return "someText";
}
...
}
"That works" mean the jetty server serves me a html file with the correct content-type containing the test someText.
My next try were to replace the #RestController by #Controller (same produce config), and replace "someText" by index.html
#Controller
public class HbbTVController {
#RequestMapping(value = "/hbbtv", produces = "application/vnd.hbbtv.xhtml+xml")
String home() {
return "index.html";
}
...
}
Well, it serves my index.html correctly, but the Content-Type is wrong : text/html instead of application/vnd.hbbtv.xhtml+xml.
Furthermore, I don't want to access to myserver.com/hbbtv to get index.html, but directly to myserver.com/index.html.
How could I do that ?
Thanks...
Well, finally, I found the "Spring boot compliant solution". It's the same as Jamie Birch suggested, but realized with Spring mechanisms.
Spring Boot 1:
#Configuration
public class HbbtvMimeMapping implements EmbeddedServletContainerCustomizer {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("html", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
mappings.add("xhtml", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
container.setMimeMappings(mappings);
}
}
Spring Boot 2:
#Configuration
public class HbbtvMimeMapping implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
#Override
public void customize(ConfigurableServletWebServerFactory factory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("html", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
mappings.add("xhtml", "application/vnd.hbbtv.xhtml+xml; charset=utf-8");
factory.setMimeMappings(mappings);
}
}
I'll extend comment providen by #Cheloute
Sping boot have default mime types
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/MimeMappings.java
to override already setted mime type you should remove it first
Here is example what I used to override js and css
#Configuration
public class CustomServletConfiguration implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
#Override
public void customize(ConfigurableServletWebServerFactory factory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.remove("js");
mappings.add("js", "application/javascript;charset=utf-8");
mappings.remove("css");
mappings.add("css", "text/css;charset=utf-8");
factory.setMimeMappings(mappings);
factory.setPort(9000);
}
}
Can't help with the Spring Boot side, but if you get no other responses, try these:
Set the file-type as .xhtml rather than .html.
Provide a mapping from .xhtml to MIME type application/vnd.hbbtv.xhtml+xml on your Jetty server's mime.properties file. A few more details on how to do that here.

Microservice with Spring Boot

I'm working in Windows 7. I've Spring CLI v1.5.3.RELEASE installed. In a working directory, using command
spring init --build maven --groupId com.redhat.examples
--version 1.0 --java-version 1.8 --dependencies web
--name hola-springboot hola-springboot
I created holo-springboot app. Then navigated to hola-springboot directory,ran
$ mvn spring-boot:run
The application run. Going to http://localhost:8080, I do see Whitelabel error page. Whereafter, I tried to add helloworld fuctionality. That is, in the app, in the packeage com.example, I included the following java class.
#RestController
#RequestMapping("/api")
public class HolaRestController {
#RequestMapping(method = RequestMethod.GET, value = "/hola",
produces = "text/plain")
public String hola() throws UnknownHostException {
String hostname = null;
try {
hostname = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
hostname = "unknown";
}
return "Hola Spring Boot de " + hostname;
}
}
Re-built from hola-springboot dircetory,
mvn clean package
I get build failure as at
https://pastebin.com/77Ru0w52
I'm unable to figure out. Could somebody help?
I'm following the book Microservices for Java Developers by Christian Posta, Chapter 2, available free at developers Redhat.
Looks like you are missing a dependency on spring boot starter web in your maven pom.xml file https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web/1.5.3.RELEASE.
Or you are not importing the classes correctly.
You are accessing http://localhost:8080 but you have defined a mapping in your rest controller "/hola". So you will have to access the url http://localhost:8080/hola as you do not have any default method in your rest controller.
BuildFailure shows that you have not given import statements in you Class. statements missing are the below
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.net.InetAddress;
import java.net.UnknownHostException;
include these and you will be fine.

Run Livy Job in a Kerberos-enabled Hadoop Cluster

I created an example Livy (Spark) application using the com.cloudera.livy.Job class for calculating an approximate value for Pi (Source: https://github.com/cloudera/livy#using-the-programmatic-api), exported as jar file to e.g. C:/path/to/the/pijob.jar.
Actually I'm running this job from another Main class like this (also copied from the link above and adapted):
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import com.cloudera.livy.LivyClient;
import com.cloudera.livy.LivyClientBuilder;
public class Main {
public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException, ExecutionException {
String livyUrl = "http://myserverIp:8998";
String piJar = "C:/path/to/the/pijob.jar";
int samples = 10000;
LivyClient client = new LivyClientBuilder().setURI(new URI(livyUrl)).build();
try {
System.err.printf("Uploading %s to the Spark context...\n", piJar);
client.uploadJar(new File(piJar)).get();
System.err.printf("Running PiJob with %d samples...\n", samples);
double pi = client.submit(new PiJob(samples)).get();
System.out.println("Pi is roughly: " + pi);
} finally {
client.stop(true);
}
}
}
This application works perfectly in an unsecured Hadoop cluster from outside (started from my client). But when I try to run it against a Kerberos-enabled Cluster, it fails.
I tried to set the corresponding Kerberos properties in the LivyClientBuilder class:
Properties props = new Properties();
props.put("livy.environment", "production");
props.put("livy.impersonation.enabled", "true");
props.put("livy.server.auth.kerberos.keytab", "/etc/security/keytabs/spnego.service.keytab");
props.put("livy.server.auth.kerberos.principal", "HTTP/_HOST#MYCLUSTER.DE");
props.put("livy.server.auth.type", "kerberos");
props.put("livy.server.csrf_protection.enabled", "true");
props.put("livy.server.kerberos.keytab", "/etc/security/keytabs/livy.service.keytab");
props.put("livy.server.kerberos.principal", "livy/_HOST#MYCLUSTER.DE");
props.put("livy.server.port", "8998");
props.put("livy.server.session.timeout", "3600000");
props.put("livy.superusers", "zeppelin-MyCluster");
LivyClient client = new LivyClientBuilder().setAll(props).setURI(new URI(livyUrl)).build();
But I still get an exception saying that authentication is required:
Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Authentication required: <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 401 </title>
</head>
<body>
<h2>HTTP ERROR: 401</h2>
<p>Problem accessing /sessions/. Reason:
<pre> Authentication required</pre></p>
<hr /><i><small>Powered by Jetty://</small></i>
</body>
</html>
at com.cloudera.livy.client.http.HttpClient.propagate(HttpClient.java:185)
at com.cloudera.livy.client.http.HttpClient.<init>(HttpClient.java:85)
at com.cloudera.livy.client.http.HttpClientFactory.createClient(HttpClientFactory.java:38)
at com.cloudera.livy.LivyClientBuilder.build(LivyClientBuilder.java:124)
at livy.Main.main(Main.java:34)
Caused by: java.io.IOException: Authentication required: <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 401 </title>
</head>
<body>
<h2>HTTP ERROR: 401</h2>
<p>Problem accessing /sessions/. Reason:
<pre> Authentication required</pre></p>
<hr /><i><small>Powered by Jetty://</small></i>
</body>
</html>
at com.cloudera.livy.client.http.LivyConnection.sendRequest(LivyConnection.java:230)
at com.cloudera.livy.client.http.LivyConnection.sendJSONRequest(LivyConnection.java:204)
at com.cloudera.livy.client.http.LivyConnection.post(LivyConnection.java:180)
at com.cloudera.livy.client.http.HttpClient.<init>(HttpClient.java:82)
... 3 more
The questions at this point are for me:
Are these all needed Kerberos settings that I need?
Or do I have to add something more to log-in?
Do I have to provide config files / keytabs on my client machine?
or can I still use the server paths (like I did so far)?
Is there some helpful documentation on the Kerberos stuff for Livy?

Flying saucer, Thymeleaf and Spring

I have a Spring application and need to build support for PDF generation. I'm thinking of using Flying-saucer together with Thymeleaf to render the PDF. However, I cannot find that much information about using Flying-saucer together with Thymeleaf. Have anyone else used those to technologies together?
I'm using Flyingsaucer-R8 with Thymeleaf 2.0.14 without problems (and I'm sure current version of Thymeleaf works as well).
I have separate TemplateEngine with classpath template resolver configured for this purpose. Using it to produce XHTML as String. Flyingsaucer creates PDF document from result then. Check example below.
Code below is example - NOT PRODUCTION ready code use it with NO WARRANTY. For sake of clarity there's no try-catch handling and no resources caching (creating PDF is quite expensive operation). Consider that.
Code
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.springframework.core.io.ClassPathResource;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
public class FlyingSoucerTestService {
public void test() throws DocumentException, IOException {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("META-INF/pdfTemplates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
templateResolver.setCharacterEncoding("UTF-8");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context ctx = new Context();
ctx.setVariable("message", "I don't want to live on this planet anymore");
String htmlContent = templateEngine.process("messageTpl", ctx);
ByteOutputStream os = new ByteOutputStream();
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = renderer.getFontResolver();
ClassPathResource regular = new ClassPathResource("/META-INF/fonts/LiberationSerif-Regular.ttf");
fontResolver.addFont(regular.getURL().toString(), BaseFont.IDENTITY_H, true);
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(os);
byte[] pdfAsBytes = os.getBytes();
os.close();
FileOutputStream fos = new FileOutputStream(new File("/tmp/message.pdf"));
fos.write(pdfAsBytes);
fos.close();
}
}
Template
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
div.border {
border: solid;
border-width: 1px 1px 0px 1px;
padding: 5px 20px 5px 20px;
}
</style>
</head>
<body style="font-family: Liberation Serif;">
<div class="border">
<h1 th:text="${message}">message</h1>
</div>
</body>
</html>

Resources