JAVA-13855 Create new microservices-modules (#12612)
This commit is contained in:
7
microservices-modules/helidon/README.md
Normal file
7
microservices-modules/helidon/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Helidon
|
||||
|
||||
This module contains articles about Helidon
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Microservices with Oracle Helidon](https://www.baeldung.com/microservices-oracle-helidon)
|
||||
33
microservices-modules/helidon/helidon-mp/pom.xml
Normal file
33
microservices-modules/helidon/helidon-mp/pom.xml
Normal file
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>helidon-mp</artifactId>
|
||||
<name>helidon-mp</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.helidon</groupId>
|
||||
<artifactId>helidon</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.helidon.microprofile.bundles</groupId>
|
||||
<artifactId>helidon-microprofile-1.2</artifactId>
|
||||
<version>${helidon-microprofile.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-json-binding</artifactId>
|
||||
<version>${jersey-media-json-binding.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<helidon-microprofile.version>0.10.4</helidon-microprofile.version>
|
||||
<jersey-media-json-binding.version>2.26</jersey-media-json-binding.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.microprofile;
|
||||
|
||||
import com.baeldung.microprofile.web.BookEndpoint;
|
||||
import io.helidon.common.CollectionsHelper;
|
||||
import io.helidon.microprofile.server.Server;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationPath("/library")
|
||||
public class LibraryApplication extends Application {
|
||||
|
||||
@Override
|
||||
public Set<Class<?>> getClasses() {
|
||||
return CollectionsHelper.setOf(BookEndpoint.class);
|
||||
}
|
||||
|
||||
public static void main(String... args) {
|
||||
Server server = Server.builder()
|
||||
.addApplication(LibraryApplication.class)
|
||||
.port(9080)
|
||||
.build();
|
||||
server.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.microprofile.model;
|
||||
|
||||
public class Book {
|
||||
|
||||
private String id;
|
||||
private String isbn;
|
||||
private String name;
|
||||
private String author;
|
||||
private Integer pages;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
public void setIsbn(String isbn) {
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public Integer getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public void setPages(Integer pages) {
|
||||
this.pages = pages;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.microprofile.providers;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.util.BookMapper;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonWriter;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.MessageBodyWriter;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
|
||||
@Provider
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class BookListMessageBodyWriter implements MessageBodyWriter<List<Book>> {
|
||||
|
||||
@Override
|
||||
public boolean isWriteable(Class<?> clazz, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
|
||||
JsonWriter jsonWriter = Json.createWriter(entityStream);
|
||||
JsonArray jsonArray = BookMapper.map(books);
|
||||
jsonWriter.writeArray(jsonArray);
|
||||
jsonWriter.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.microprofile.providers;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.util.BookMapper;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.MessageBodyReader;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
@Provider
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class BookMessageBodyReader implements MessageBodyReader<Book> {
|
||||
|
||||
@Override
|
||||
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return type.equals(Book.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Book readFrom(Class<Book> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
|
||||
return BookMapper.map(entityStream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.microprofile.providers;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.util.BookMapper;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
import javax.json.JsonWriter;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.MessageBodyWriter;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
@Provider
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class BookMessageBodyWriter implements MessageBodyWriter<Book> {
|
||||
@Override
|
||||
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return type.equals(Book.class);
|
||||
}
|
||||
|
||||
/*
|
||||
Deprecated in JAX RS 2.0
|
||||
*/
|
||||
@Override
|
||||
public long getSize(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marsahl Book to OutputStream
|
||||
*
|
||||
* @param book
|
||||
* @param type
|
||||
* @param genericType
|
||||
* @param annotations
|
||||
* @param mediaType
|
||||
* @param httpHeaders
|
||||
* @param entityStream
|
||||
* @throws IOException
|
||||
* @throws WebApplicationException
|
||||
*/
|
||||
@Override
|
||||
public void writeTo(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
|
||||
JsonWriter jsonWriter = Json.createWriter(entityStream);
|
||||
JsonObject jsonObject = BookMapper.map(book);
|
||||
jsonWriter.writeObject(jsonObject);
|
||||
jsonWriter.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.microprofile.repo;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@ApplicationScoped
|
||||
public class BookManager {
|
||||
|
||||
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
|
||||
private AtomicInteger bookIdGenerator = new AtomicInteger(0);
|
||||
|
||||
private ConcurrentMap<String, Book> inMemoryStore = new ConcurrentHashMap<>();
|
||||
|
||||
public BookManager() {
|
||||
Book book = new Book();
|
||||
book.setId(getNextId());
|
||||
book.setName("Building Microservice With Eclipse MicroProfile");
|
||||
book.setIsbn("1");
|
||||
book.setAuthor("baeldung");
|
||||
book.setPages(420);
|
||||
inMemoryStore.put(book.getId(), book);
|
||||
}
|
||||
|
||||
private String getNextId() {
|
||||
String date = LocalDate.now().format(formatter);
|
||||
return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date);
|
||||
}
|
||||
|
||||
public String add(Book book) {
|
||||
String id = getNextId();
|
||||
book.setId(id);
|
||||
inMemoryStore.put(id, book);
|
||||
return id;
|
||||
}
|
||||
|
||||
public Book get(String id) {
|
||||
return inMemoryStore.get(id);
|
||||
}
|
||||
|
||||
public List<Book> getAll() {
|
||||
List<Book> books = new ArrayList<>();
|
||||
books.addAll(inMemoryStore.values());
|
||||
return books;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.microprofile.util;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
|
||||
import javax.json.*;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
public class BookMapper {
|
||||
|
||||
public static JsonObject map(Book book) {
|
||||
JsonObjectBuilder builder = Json.createObjectBuilder();
|
||||
addValue(builder, "id", book.getId());
|
||||
addValue(builder, "isbn", book.getIsbn());
|
||||
addValue(builder, "name", book.getName());
|
||||
addValue(builder, "author", book.getAuthor());
|
||||
addValue(builder, "pages", book.getPages());
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static void addValue(JsonObjectBuilder builder, String key, Object value) {
|
||||
if (value != null) {
|
||||
builder.add(key, value.toString());
|
||||
} else {
|
||||
builder.addNull(key);
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonArray map(List<Book> books) {
|
||||
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
|
||||
books.forEach(book -> {
|
||||
JsonObject jsonObject = map(book);
|
||||
arrayBuilder.add(jsonObject);
|
||||
});
|
||||
return arrayBuilder.build();
|
||||
}
|
||||
|
||||
public static Book map(InputStream is) {
|
||||
try(JsonReader jsonReader = Json.createReader(is)) {
|
||||
JsonObject jsonObject = jsonReader.readObject();
|
||||
Book book = new Book();
|
||||
book.setId(getStringFromJson("id", jsonObject));
|
||||
book.setIsbn(getStringFromJson("isbn", jsonObject));
|
||||
book.setName(getStringFromJson("name", jsonObject));
|
||||
book.setAuthor(getStringFromJson("author", jsonObject));
|
||||
book.setPages(getIntFromJson("pages",jsonObject));
|
||||
return book;
|
||||
}
|
||||
}
|
||||
|
||||
private static String getStringFromJson(String key, JsonObject json) {
|
||||
String returnedString = null;
|
||||
if (json.containsKey(key)) {
|
||||
JsonString value = json.getJsonString(key);
|
||||
if (value != null) {
|
||||
returnedString = value.getString();
|
||||
}
|
||||
}
|
||||
return returnedString;
|
||||
}
|
||||
|
||||
private static Integer getIntFromJson(String key, JsonObject json) {
|
||||
Integer returnedValue = null;
|
||||
if (json.containsKey(key)) {
|
||||
JsonNumber value = json.getJsonNumber(key);
|
||||
if (value != null) {
|
||||
returnedValue = value.intValue();
|
||||
}
|
||||
}
|
||||
return returnedValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.microprofile.web;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.repo.BookManager;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
|
||||
@Path("books")
|
||||
@RequestScoped
|
||||
public class BookEndpoint {
|
||||
|
||||
@Inject
|
||||
private BookManager bookManager;
|
||||
|
||||
@GET
|
||||
@Path("{id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getBook(@PathParam("id") String id) {
|
||||
Book book = bookManager.get(id);
|
||||
return Response.ok(book).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAllBooks() {
|
||||
return Response.ok(bookManager.getAll()).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public Response add(Book book) {
|
||||
String bookId = bookManager.add(book);
|
||||
return Response.created(
|
||||
UriBuilder.fromResource(this.getClass()).path(bookId).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||
version="2.0"
|
||||
bean-discovery-mode="annotated">
|
||||
</beans>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
61
microservices-modules/helidon/helidon-se/pom.xml
Normal file
61
microservices-modules/helidon/helidon-se/pom.xml
Normal file
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>helidon-se</artifactId>
|
||||
<name>helidon-se</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.helidon</groupId>
|
||||
<artifactId>helidon</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!--Config -->
|
||||
<dependency>
|
||||
<groupId>io.helidon.config</groupId>
|
||||
<artifactId>helidon-config-yaml</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
</dependency>
|
||||
<!--WebServer -->
|
||||
<dependency>
|
||||
<groupId>io.helidon.webserver</groupId>
|
||||
<artifactId>helidon-webserver</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.helidon.webserver</groupId>
|
||||
<artifactId>helidon-webserver-netty</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.helidon.webserver</groupId>
|
||||
<artifactId>helidon-webserver-json</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
</dependency>
|
||||
<!--Security -->
|
||||
<dependency>
|
||||
<groupId>io.helidon.security</groupId>
|
||||
<artifactId>helidon-security</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.helidon.security</groupId>
|
||||
<artifactId>helidon-security-provider-http-auth</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.helidon.security</groupId>
|
||||
<artifactId>helidon-security-integration-webserver</artifactId>
|
||||
<version>${helidon.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<helidon.version>0.10.4</helidon.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.helidon.se.config;
|
||||
|
||||
import io.helidon.config.Config;
|
||||
import io.helidon.config.ConfigSources;
|
||||
import io.helidon.config.spi.ConfigSource;
|
||||
|
||||
public class ConfigApplication {
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
||||
ConfigSource configSource = ConfigSources.classpath("application.yaml").build();
|
||||
Config config = Config.builder()
|
||||
.disableSystemPropertiesSource()
|
||||
.disableEnvironmentVariablesSource()
|
||||
.sources(configSource)
|
||||
.build();
|
||||
|
||||
int port = config.get("server.port").asInt();
|
||||
int pageSize = config.get("web.page-size").asInt();
|
||||
boolean debug = config.get("web.debug").asBoolean();
|
||||
String userHome = config.get("user.home").asString();
|
||||
|
||||
System.out.println("port: " + port);
|
||||
System.out.println("pageSize: " + pageSize);
|
||||
System.out.println("debug: " + debug);
|
||||
System.out.println("userHome: " + userHome);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.helidon.se.routing;
|
||||
|
||||
public class Book {
|
||||
private String id;
|
||||
private String isbn;
|
||||
private String name;
|
||||
private String author;
|
||||
private Integer pages;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
public void setIsbn(String isbn) {
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public Integer getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public void setPages(Integer pages) {
|
||||
this.pages = pages;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.helidon.se.routing;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class BookManager {
|
||||
|
||||
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
|
||||
private AtomicInteger bookIdGenerator = new AtomicInteger(0);
|
||||
|
||||
private ConcurrentMap<String, Book> inMemoryStore = new ConcurrentHashMap<>();
|
||||
|
||||
public BookManager() {
|
||||
Book book = new Book();
|
||||
book.setId(getNextId());
|
||||
book.setName("Building Microservice With Oracle Helidon");
|
||||
book.setIsbn("11223344");
|
||||
book.setAuthor("baeldung");
|
||||
book.setPages(560);
|
||||
inMemoryStore.put(book.getId(), book);
|
||||
}
|
||||
|
||||
private String getNextId() {
|
||||
String date = LocalDate.now().format(formatter);
|
||||
return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date);
|
||||
}
|
||||
|
||||
public String add(Book book) {
|
||||
String id = getNextId();
|
||||
book.setId(id);
|
||||
inMemoryStore.put(id, book);
|
||||
return id;
|
||||
}
|
||||
|
||||
public Book get(String id) {
|
||||
return inMemoryStore.get(id);
|
||||
}
|
||||
|
||||
public List<Book> getAll() {
|
||||
List<Book> books = new ArrayList<>();
|
||||
books.addAll(inMemoryStore.values());
|
||||
return books;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.helidon.se.routing;
|
||||
|
||||
import io.helidon.webserver.Routing;
|
||||
import io.helidon.webserver.ServerRequest;
|
||||
import io.helidon.webserver.ServerResponse;
|
||||
import io.helidon.webserver.Service;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonArrayBuilder;
|
||||
import javax.json.JsonObject;
|
||||
import java.util.List;
|
||||
|
||||
public class BookResource implements Service {
|
||||
|
||||
private BookManager bookManager = new BookManager();
|
||||
|
||||
@Override
|
||||
public void update(Routing.Rules rules) {
|
||||
rules
|
||||
.get("/", this::books)
|
||||
.get("/{id}", this::bookById);
|
||||
}
|
||||
|
||||
private void bookById(ServerRequest serverRequest, ServerResponse serverResponse) {
|
||||
//get the book with the given id
|
||||
String id = serverRequest.path().param("id");
|
||||
Book book = bookManager.get(id);
|
||||
JsonObject jsonObject = from(book);
|
||||
serverResponse.send(jsonObject);
|
||||
}
|
||||
|
||||
private void books(ServerRequest serverRequest, ServerResponse serverResponse) {
|
||||
//get all books
|
||||
List<Book> books = bookManager.getAll();
|
||||
JsonArray jsonArray = from(books);
|
||||
serverResponse.send(jsonArray);
|
||||
}
|
||||
|
||||
private JsonObject from(Book book) {
|
||||
JsonObject jsonObject = Json.createObjectBuilder()
|
||||
.add("id", book.getId())
|
||||
.add("isbn", book.getIsbn())
|
||||
.add("name", book.getName())
|
||||
.add("author", book.getAuthor())
|
||||
.add("pages", book.getPages())
|
||||
.build();
|
||||
return jsonObject;
|
||||
}
|
||||
|
||||
private JsonArray from(List<Book> books) {
|
||||
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
|
||||
books.forEach(book -> {
|
||||
jsonArrayBuilder.add(from(book));
|
||||
});
|
||||
return jsonArrayBuilder.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.helidon.se.routing;
|
||||
|
||||
import io.helidon.webserver.Routing;
|
||||
import io.helidon.webserver.ServerConfiguration;
|
||||
import io.helidon.webserver.WebServer;
|
||||
import io.helidon.webserver.json.JsonSupport;
|
||||
|
||||
public class WebApplicationRouting {
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
||||
ServerConfiguration serverConfig = ServerConfiguration.builder()
|
||||
.port(9080)
|
||||
.build();
|
||||
|
||||
Routing routing = Routing.builder()
|
||||
.register(JsonSupport.get())
|
||||
.register("/books", new BookResource())
|
||||
.get("/greet", (request, response) -> response.send("Hello World !"))
|
||||
.build();
|
||||
|
||||
WebServer.create(serverConfig, routing)
|
||||
.start()
|
||||
.thenAccept(ws ->
|
||||
System.out.println("Server started at: http://localhost:" + ws.port())
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.helidon.se.security;
|
||||
|
||||
import io.helidon.security.provider.httpauth.UserStore;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public class MyUser implements UserStore.User {
|
||||
|
||||
private String login;
|
||||
private char[] password;
|
||||
private Collection<String> roles;
|
||||
|
||||
public MyUser(String login, char[] password, Collection<String> roles) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
@Override
|
||||
public char[] getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.helidon.se.security;
|
||||
|
||||
import io.helidon.config.Config;
|
||||
import io.helidon.security.Security;
|
||||
import io.helidon.security.SubjectType;
|
||||
import io.helidon.security.provider.httpauth.HttpBasicAuthProvider;
|
||||
import io.helidon.security.provider.httpauth.UserStore;
|
||||
import io.helidon.security.webserver.WebSecurity;
|
||||
import io.helidon.webserver.Routing;
|
||||
import io.helidon.webserver.ServerConfiguration;
|
||||
import io.helidon.webserver.WebServer;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class WebApplicationSecurity {
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
||||
Config config = Config.create();
|
||||
ServerConfiguration serverConfig =
|
||||
ServerConfiguration.fromConfig(config.get("server"));
|
||||
|
||||
Map<String, MyUser> users = new HashMap<>();
|
||||
users.put("user", new MyUser("user", "user".toCharArray(), Arrays.asList("ROLE_USER")));
|
||||
users.put("admin", new MyUser("admin", "admin".toCharArray(), Arrays.asList("ROLE_USER", "ROLE_ADMIN")));
|
||||
UserStore store = user -> Optional.ofNullable(users.get(user));
|
||||
|
||||
HttpBasicAuthProvider httpBasicAuthProvider = HttpBasicAuthProvider.builder()
|
||||
.realm("myRealm")
|
||||
.subjectType(SubjectType.USER)
|
||||
.userStore(store)
|
||||
.build();
|
||||
|
||||
//1. Using Builder Pattern or Config Pattern
|
||||
Security security = Security.builder()
|
||||
.addAuthenticationProvider(httpBasicAuthProvider)
|
||||
.build();
|
||||
//Security security = Security.fromConfig(config);
|
||||
|
||||
//2. WebSecurity from Security or from Config
|
||||
// WebSecurity webSecurity = WebSecurity.from(security)
|
||||
// .securityDefaults(WebSecurity.authenticate());
|
||||
|
||||
WebSecurity webSecurity = WebSecurity.from(config);
|
||||
|
||||
Routing routing = Routing.builder()
|
||||
.register(webSecurity)
|
||||
.get("/user", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_USER"))
|
||||
.get("/admin", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_ADMIN"))
|
||||
.build();
|
||||
|
||||
WebServer webServer = WebServer.create(serverConfig, routing);
|
||||
|
||||
webServer.start().thenAccept(ws ->
|
||||
System.out.println("Server started at: http://localhost:" + ws.port())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.helidon.se.webserver;
|
||||
|
||||
import io.helidon.webserver.Routing;
|
||||
import io.helidon.webserver.ServerConfiguration;
|
||||
import io.helidon.webserver.WebServer;
|
||||
|
||||
public class SimpleWebApplication {
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
||||
ServerConfiguration serverConfig = ServerConfiguration.builder()
|
||||
.port(9001)
|
||||
.build();
|
||||
|
||||
Routing routing = Routing.builder()
|
||||
.get("/greet", (request, response) -> response.send("Hello World !"))
|
||||
.build();
|
||||
|
||||
WebServer.create(serverConfig, routing)
|
||||
.start()
|
||||
.thenAccept(ws ->
|
||||
System.out.println("Server started at: http://localhost:" + ws.port())
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
@@ -0,0 +1,4 @@
|
||||
server.port=9080
|
||||
web.debug=true
|
||||
web.page-size=15
|
||||
user.home=C:/Users/app
|
||||
@@ -0,0 +1,33 @@
|
||||
server:
|
||||
port: 9080
|
||||
web:
|
||||
debug: true
|
||||
page-size: 15
|
||||
user:
|
||||
home: C:/Users/app
|
||||
|
||||
#Config 4 Security ==> Mapped to Security Object
|
||||
security:
|
||||
providers:
|
||||
- http-basic-auth:
|
||||
realm: "myRealm"
|
||||
principal-type: USER # Can be USER or SERVICE, default is USER
|
||||
users:
|
||||
- login: "user"
|
||||
password: "user"
|
||||
roles: ["ROLE_USER"]
|
||||
- login: "admin"
|
||||
password: "admin"
|
||||
roles: ["ROLE_USER", "ROLE_ADMIN"]
|
||||
|
||||
#Config 4 Security Web Server Integration ==> Mapped to WebSecurity Object
|
||||
web-server:
|
||||
securityDefaults:
|
||||
authenticate: true
|
||||
paths:
|
||||
- path: "/user"
|
||||
methods: ["get"]
|
||||
roles-allowed: ["ROLE_USER", "ROLE_ADMIN"]
|
||||
- path: "/admin"
|
||||
methods: ["get"]
|
||||
roles-allowed: ["ROLE_ADMIN"]
|
||||
22
microservices-modules/helidon/pom.xml
Normal file
22
microservices-modules/helidon/pom.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.helidon</groupId>
|
||||
<artifactId>helidon</artifactId>
|
||||
<name>helidon</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>helidon-se</module>
|
||||
<module>helidon-mp</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
1
microservices-modules/micronaut/.mvn/jvm.config
Normal file
1
microservices-modules/micronaut/.mvn/jvm.config
Normal file
@@ -0,0 +1 @@
|
||||
-noverify -XX:TieredStopAtLevel=1
|
||||
109
microservices-modules/micronaut/.mvn/wrapper/MavenWrapperDownloader.java
vendored
Normal file
109
microservices-modules/micronaut/.mvn/wrapper/MavenWrapperDownloader.java
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
*/
|
||||
|
||||
import java.net.*;
|
||||
import java.io.*;
|
||||
import java.nio.channels.*;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MavenWrapperDownloader {
|
||||
|
||||
/**
|
||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||
*/
|
||||
private static final String DEFAULT_DOWNLOAD_URL =
|
||||
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar";
|
||||
|
||||
/**
|
||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||
* use instead of the default one.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||
".mvn/wrapper/maven-wrapper.properties";
|
||||
|
||||
/**
|
||||
* Path where the maven-wrapper.jar will be saved to.
|
||||
*/
|
||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||
".mvn/wrapper/maven-wrapper.jar";
|
||||
|
||||
/**
|
||||
* Name of the property which should be used to override the default download url for the wrapper.
|
||||
*/
|
||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println("- Downloader started");
|
||||
File baseDirectory = new File(args[0]);
|
||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||
|
||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||
// wrapperUrl parameter.
|
||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||
String url = DEFAULT_DOWNLOAD_URL;
|
||||
if(mavenWrapperPropertyFile.exists()) {
|
||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||
try {
|
||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||
Properties mavenWrapperProperties = new Properties();
|
||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||
} catch (IOException e) {
|
||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||
} finally {
|
||||
try {
|
||||
if(mavenWrapperPropertyFileInputStream != null) {
|
||||
mavenWrapperPropertyFileInputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Ignore ...
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading from: : " + url);
|
||||
|
||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||
if(!outputFile.getParentFile().exists()) {
|
||||
if(!outputFile.getParentFile().mkdirs()) {
|
||||
System.out.println(
|
||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||
}
|
||||
}
|
||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||
try {
|
||||
downloadFileFromURL(url, outputFile);
|
||||
System.out.println("Done");
|
||||
System.exit(0);
|
||||
} catch (Throwable e) {
|
||||
System.out.println("- Error downloading");
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||
URL website = new URL(urlString);
|
||||
ReadableByteChannel rbc;
|
||||
rbc = Channels.newChannel(website.openStream());
|
||||
FileOutputStream fos = new FileOutputStream(destination);
|
||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||
fos.close();
|
||||
rbc.close();
|
||||
}
|
||||
}
|
||||
1
microservices-modules/micronaut/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
1
microservices-modules/micronaut/.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@@ -0,0 +1 @@
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip
|
||||
4
microservices-modules/micronaut/Dockerfile
Normal file
4
microservices-modules/micronaut/Dockerfile
Normal file
@@ -0,0 +1,4 @@
|
||||
FROM java:openjdk-8u111-alpine
|
||||
RUN apk --no-cache add curl
|
||||
COPY build/libs/*-all.jar hello-world-server.jar
|
||||
CMD java ${JAVA_OPTS} -jar hello-world-server.jar
|
||||
7
microservices-modules/micronaut/README.md
Normal file
7
microservices-modules/micronaut/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Micronaut
|
||||
|
||||
This module contains articles about Micronaut.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to Micronaut Framework](https://www.baeldung.com/micronaut)
|
||||
- [Micronaut vs. Spring Boot](https://www.baeldung.com/micronaut-vs-spring-boot)
|
||||
5
microservices-modules/micronaut/micronaut-cli.yml
Normal file
5
microservices-modules/micronaut/micronaut-cli.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
profile: service
|
||||
defaultPackage: hello.world.server
|
||||
---
|
||||
testFramework: junit
|
||||
sourceLanguage: java
|
||||
286
microservices-modules/micronaut/mvnw
vendored
Normal file
286
microservices-modules/micronaut/mvnw
vendored
Normal file
@@ -0,0 +1,286 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven2 Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
# TODO classpath?
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
curl -o "$wrapperJarPath" "$jarUrl"
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
||||
161
microservices-modules/micronaut/mvnw.cmd
vendored
Normal file
161
microservices-modules/micronaut/mvnw.cmd
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven2 Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.0/maven-wrapper-0.4.0.jar"
|
||||
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
echo Found %WRAPPER_JAR%
|
||||
) else (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
||||
148
microservices-modules/micronaut/pom.xml
Normal file
148
microservices-modules/micronaut/pom.xml
Normal file
@@ -0,0 +1,148 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.micronaut</groupId>
|
||||
<artifactId>micronaut</artifactId>
|
||||
<version>0.1</version>
|
||||
<name>micronaut</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${micronaut.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>http-client</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>http-server-netty</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>inject</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>runtime</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>${annotation.api.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>inject-java</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core</artifactId>
|
||||
<version>${reactor.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>${shade.plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>${exec.mainClass}</mainClass>
|
||||
</transformer>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<argument>${exec.mainClass}</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${compiler.plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${jdk.version}</source>
|
||||
<target>${jdk.version}</target>
|
||||
<compilerArgs>
|
||||
<arg>-parameters</arg>
|
||||
</compilerArgs>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>io.micronaut</groupId>
|
||||
<artifactId>inject-java</artifactId>
|
||||
<version>${micronaut.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- <exec.mainClass>com.baeldung.micronaut.helloworld.server.ServerApplication</exec.mainClass> -->
|
||||
<exec.mainClass>com.baeldung.micronaut.vs.springboot.CompareApplication</exec.mainClass>
|
||||
<micronaut.version>1.0.0.RC2</micronaut.version>
|
||||
<jdk.version>1.8</jdk.version>
|
||||
<annotation.api.version>1.3.2</annotation.api.version>
|
||||
<reactor.version>3.1.6.RELEASE</reactor.version>
|
||||
<compiler.plugin.version>3.7.0</compiler.plugin.version>
|
||||
<shade.plugin.version>3.1.0</shade.plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.micronaut.helloworld.client;
|
||||
|
||||
import io.micronaut.http.HttpRequest;
|
||||
import io.micronaut.http.client.annotation.Client;
|
||||
import io.micronaut.http.client.RxHttpClient;
|
||||
import io.reactivex.Single;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
@Singleton
|
||||
public class ConcreteGreetingClient
|
||||
{
|
||||
private RxHttpClient httpClient;
|
||||
|
||||
public ConcreteGreetingClient(@Client("/") RxHttpClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
public String greet(String name) {
|
||||
HttpRequest<String> req = HttpRequest.GET("/greet/" + name);
|
||||
return httpClient.retrieve(req).blockingFirst();
|
||||
}
|
||||
|
||||
public Single<String> greetAsync(String name) {
|
||||
HttpRequest<String> req = HttpRequest.GET("/async/greet/" + name);
|
||||
return httpClient.retrieve(req).first("An error as occurred");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.micronaut.helloworld.client;
|
||||
|
||||
import io.micronaut.http.annotation.Get;
|
||||
import io.micronaut.http.client.annotation.Client;
|
||||
|
||||
@Client("/greet")
|
||||
public interface GreetingClient {
|
||||
|
||||
@Get("/{name}")
|
||||
String greet(String name);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.micronaut.helloworld.server;
|
||||
|
||||
import io.micronaut.runtime.Micronaut;
|
||||
|
||||
public class ServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Micronaut.run(ServerApplication.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.micronaut.helloworld.server.controller;
|
||||
|
||||
import com.baeldung.micronaut.helloworld.server.service.GreetingService;
|
||||
import io.micronaut.http.annotation.Controller;
|
||||
import io.micronaut.http.annotation.Get;
|
||||
import io.reactivex.Single;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
@Controller("/async/greet")
|
||||
public class AsyncGreetController {
|
||||
|
||||
@Inject
|
||||
private GreetingService greetingService;
|
||||
|
||||
@Get("/{name}")
|
||||
public Single<String> greet(String name) {
|
||||
return Single.just(greetingService.getGreeting() + name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.micronaut.helloworld.server.controller;
|
||||
|
||||
import com.baeldung.micronaut.helloworld.server.service.GreetingService;
|
||||
import io.micronaut.http.MediaType;
|
||||
import io.micronaut.http.annotation.Body;
|
||||
import io.micronaut.http.annotation.Controller;
|
||||
import io.micronaut.http.annotation.Get;
|
||||
import io.micronaut.http.annotation.Post;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
@Controller("/greet")
|
||||
public class GreetController {
|
||||
|
||||
@Inject
|
||||
private GreetingService greetingService;
|
||||
|
||||
@Get("/{name}")
|
||||
public String greet(String name) {
|
||||
return greetingService.getGreeting() + name;
|
||||
}
|
||||
|
||||
@Post(value = "/{name}", consumes = MediaType.TEXT_PLAIN)
|
||||
public String setGreeting(@Body String name)
|
||||
{
|
||||
return greetingService.getGreeting() + name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.micronaut.helloworld.server.service;
|
||||
|
||||
import io.micronaut.context.annotation.Primary;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
@Primary
|
||||
@Singleton
|
||||
public class EnglishGreetingService implements GreetingService {
|
||||
@Override
|
||||
public String getGreeting() {
|
||||
return "Hello ";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.micronaut.helloworld.server.service;
|
||||
|
||||
public interface GreetingService {
|
||||
|
||||
String getGreeting();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.micronaut.helloworld.server.service;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
@Singleton
|
||||
public class SpanishGreetingService implements GreetingService {
|
||||
@Override
|
||||
public String getGreeting() {
|
||||
return "Hola ";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.micronaut.vs.springboot;
|
||||
|
||||
import io.micronaut.runtime.Micronaut;
|
||||
|
||||
public class CompareApplication {
|
||||
public static void main(String[] args) {
|
||||
Micronaut.run(CompareApplication.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.micronaut.vs.springboot.client;
|
||||
|
||||
import io.micronaut.http.annotation.Get;
|
||||
import io.micronaut.http.client.annotation.Client;
|
||||
|
||||
@Client("/math")
|
||||
public interface ArithmeticClient {
|
||||
|
||||
@Get("/sum/{number1}/{number2}")
|
||||
String sum(float number1, float number2);
|
||||
|
||||
@Get("/subtract/{number1}/{number2}")
|
||||
String subtract(float number1, float number2);
|
||||
|
||||
@Get("/multiply/{number1}/{number2}")
|
||||
String multiply(float number1, float number2);
|
||||
|
||||
@Get("/divide/{number1}/{number2}")
|
||||
String divide(float number1, float number2);
|
||||
|
||||
@Get("/memory")
|
||||
String memory();
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.micronaut.vs.springboot.client;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import io.micronaut.http.HttpRequest;
|
||||
import io.micronaut.http.client.RxHttpClient;
|
||||
import io.micronaut.http.client.annotation.Client;
|
||||
|
||||
@Singleton
|
||||
public class ArithmeticClientImpl {
|
||||
private RxHttpClient httpClient;
|
||||
|
||||
public ArithmeticClientImpl(@Client("/") RxHttpClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
public String sum(float number1, float number2) {
|
||||
HttpRequest<String> req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2);
|
||||
return httpClient.retrieve(req)
|
||||
.blockingFirst();
|
||||
}
|
||||
|
||||
public String subtract(float number1, float number2) {
|
||||
HttpRequest<String> req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2);
|
||||
return httpClient.retrieve(req)
|
||||
.blockingFirst();
|
||||
}
|
||||
|
||||
public String multiply(float number1, float number2) {
|
||||
HttpRequest<String> req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2);
|
||||
return httpClient.retrieve(req)
|
||||
.blockingFirst();
|
||||
}
|
||||
|
||||
public String divide(float number1, float number2) {
|
||||
HttpRequest<String> req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2);
|
||||
return httpClient.retrieve(req)
|
||||
.blockingFirst();
|
||||
}
|
||||
|
||||
public String memory() {
|
||||
HttpRequest<String> req = HttpRequest.GET("/math/memory");
|
||||
return httpClient.retrieve(req)
|
||||
.blockingFirst();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.micronaut.vs.springboot.controller;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryMXBean;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import com.baeldung.micronaut.vs.springboot.service.ArithmeticService;
|
||||
|
||||
import io.micronaut.http.annotation.Controller;
|
||||
import io.micronaut.http.annotation.Get;
|
||||
|
||||
@Controller("/math")
|
||||
public class ArithmeticController {
|
||||
@Inject
|
||||
private ArithmeticService arithmeticService;
|
||||
|
||||
@Get("/sum/{number1}/{number2}")
|
||||
public float getSum(float number1, float number2) {
|
||||
return arithmeticService.add(number1, number2);
|
||||
}
|
||||
|
||||
@Get("/subtract/{number1}/{number2}")
|
||||
public float getDifference(float number1, float number2) {
|
||||
return arithmeticService.subtract(number1, number2);
|
||||
}
|
||||
|
||||
@Get("/multiply/{number1}/{number2}")
|
||||
public float getMultiplication(float number1, float number2) {
|
||||
return arithmeticService.multiply(number1, number2);
|
||||
}
|
||||
|
||||
@Get("/divide/{number1}/{number2}")
|
||||
public float getDivision(float number1, float number2) {
|
||||
return arithmeticService.divide(number1, number2);
|
||||
}
|
||||
|
||||
@Get("/memory")
|
||||
public String getMemoryStatus() {
|
||||
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
|
||||
String memoryStats = "";
|
||||
|
||||
String init = String.format("Initial: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
|
||||
.getInit() / 1073741824);
|
||||
String usedHeap = String.format("Used: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
|
||||
.getUsed() / 1073741824);
|
||||
String maxHeap = String.format("Max: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
|
||||
.getMax() / 1073741824);
|
||||
String committed = String.format("Committed: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
|
||||
.getCommitted() / 1073741824);
|
||||
memoryStats += init;
|
||||
memoryStats += usedHeap;
|
||||
memoryStats += maxHeap;
|
||||
memoryStats += committed;
|
||||
|
||||
return memoryStats;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.micronaut.vs.springboot.service;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
@Singleton
|
||||
public class ArithmeticService {
|
||||
public float add(float number1, float number2) {
|
||||
return number1 + number2;
|
||||
}
|
||||
|
||||
public float subtract(float number1, float number2) {
|
||||
return number1 - number2;
|
||||
}
|
||||
|
||||
public float multiply(float number1, float number2) {
|
||||
return number1 * number2;
|
||||
}
|
||||
|
||||
public float divide(float number1, float number2) {
|
||||
if (number2 == 0) {
|
||||
throw new IllegalArgumentException("'number2' cannot be zero");
|
||||
}
|
||||
return number1 / number2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
micronaut:
|
||||
application:
|
||||
name: hello-world-server
|
||||
server:
|
||||
port: ${random.port}
|
||||
@@ -0,0 +1,14 @@
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<!-- encoders are assigned the type
|
||||
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.micronaut.helloworld.client;
|
||||
|
||||
import io.micronaut.context.ApplicationContext;
|
||||
import io.micronaut.runtime.server.EmbeddedServer;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class ConcreteGreetingClientUnitTest
|
||||
{
|
||||
private EmbeddedServer server;
|
||||
private ConcreteGreetingClient client;
|
||||
|
||||
@Before
|
||||
public void setup()
|
||||
{
|
||||
server = ApplicationContext.run(EmbeddedServer.class);
|
||||
client = server.getApplicationContext().getBean(ConcreteGreetingClient.class);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup()
|
||||
{
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGreeting() {
|
||||
assertEquals(client.greet("Mike"), "Hello Mike");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGreetingAsync() {
|
||||
assertEquals(client.greetAsync("Mike").blockingGet(), "Hello Mike");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.micronaut.helloworld.client;
|
||||
|
||||
import io.micronaut.context.ApplicationContext;
|
||||
import io.micronaut.runtime.server.EmbeddedServer;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class GreetingClientUnitTest {
|
||||
private EmbeddedServer server;
|
||||
private GreetingClient client;
|
||||
|
||||
@Before
|
||||
public void setup()
|
||||
{
|
||||
server = ApplicationContext.run(EmbeddedServer.class);
|
||||
client = server.getApplicationContext().getBean(GreetingClient.class);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup()
|
||||
{
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGreeting() {
|
||||
assertEquals(client.greet("Mike"), "Hello Mike");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.micronaut.vs.springboot;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
import io.micronaut.context.ApplicationContext;
|
||||
import io.micronaut.runtime.server.EmbeddedServer;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.micronaut.vs.springboot.client.ArithmeticClientImpl;
|
||||
|
||||
public class ArithmeticClientUnitTest {
|
||||
private EmbeddedServer server;
|
||||
private ArithmeticClientImpl client;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
server = ApplicationContext.run(EmbeddedServer.class);
|
||||
client = server.getApplicationContext()
|
||||
.getBean(ArithmeticClientImpl.class);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() {
|
||||
String expected = Float.valueOf(10 + 20).toString();
|
||||
assertEquals(expected, client.sum(10, 20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() {
|
||||
String expected = Float.valueOf(20 - 10).toString();
|
||||
assertEquals(expected, client.subtract(20, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() {
|
||||
String expected = Float.valueOf(10 * 20).toString();
|
||||
assertEquals(expected, client.multiply(10, 20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() {
|
||||
String expected = Float.valueOf(30 / 10).toString();
|
||||
assertEquals(expected, client.divide(30, 10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMemory_thenCorrectAnswerReturned() {
|
||||
String expected = "Initial:";
|
||||
assertThat(client.memory(), containsString(expected));
|
||||
}
|
||||
}
|
||||
7
microservices-modules/microprofile/README.md
Normal file
7
microservices-modules/microprofile/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Eclipse MicroProfile
|
||||
|
||||
This module contains articles about Eclipse MicroProfile.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Building Microservices with Eclipse MicroProfile](https://www.baeldung.com/eclipse-microprofile)
|
||||
91
microservices-modules/microprofile/pom.xml
Normal file
91
microservices-modules/microprofile/pom.xml
Normal file
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>microprofile</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>microprofile</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.microprofile</groupId>
|
||||
<artifactId>microprofile</artifactId>
|
||||
<version>${microprofile.version}</version>
|
||||
<scope>provided</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<configuration>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<packagingExcludes>pom.xml</packagingExcludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||
<artifactId>liberty-maven-plugin</artifactId>
|
||||
<version>${liberty-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<assemblyArtifact>
|
||||
<groupId>io.openliberty</groupId>
|
||||
<artifactId>openliberty-runtime</artifactId>
|
||||
<version>${openliberty-runtime.version}</version>
|
||||
<type>zip</type>
|
||||
</assemblyArtifact>
|
||||
<configFile>${basedir}/src/main/liberty/config/server.xml</configFile>
|
||||
<packageFile>${package.file}</packageFile>
|
||||
<include>${packaging.type}</include>
|
||||
<looseApplication>false</looseApplication>
|
||||
<installAppPackages>project</installAppPackages>
|
||||
<bootstrapProperties>
|
||||
<app.context.root>/</app.context.root>
|
||||
<app.location>${project.artifactId}-${project.version}.war</app.location>
|
||||
<default.http.port>9080</default.http.port>
|
||||
<default.https.port>9443</default.https.port>
|
||||
</bootstrapProperties>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>install-server</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>install-server</goal>
|
||||
<goal>create-server</goal>
|
||||
<goal>install-feature</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>package-server-with-apps</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>install-apps</goal>
|
||||
<goal>package-server</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<app.name>library</app.name>
|
||||
<package.file>${project.build.directory}/${app.name}-service.jar</package.file>
|
||||
<packaging.type>runnable</packaging.type>
|
||||
<microprofile.version>1.2</microprofile.version>
|
||||
<liberty-maven-plugin.version>2.1.2</liberty-maven-plugin.version>
|
||||
<openliberty-runtime.version>17.0.0.4</openliberty-runtime.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.microprofile;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
|
||||
@ApplicationPath("/library")
|
||||
public class LibraryApplication extends Application {
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.microprofile.model;
|
||||
|
||||
public class Book {
|
||||
|
||||
private String id;
|
||||
private String isbn;
|
||||
private String name;
|
||||
private String author;
|
||||
private Integer pages;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
public void setIsbn(String isbn) {
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public Integer getPages() {
|
||||
return pages;
|
||||
}
|
||||
|
||||
public void setPages(Integer pages) {
|
||||
this.pages = pages;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.microprofile.providers;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.util.BookMapper;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonArray;
|
||||
import javax.json.JsonWriter;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.MessageBodyWriter;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
|
||||
@Provider
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class BookListMessageBodyWriter implements MessageBodyWriter<List<Book>> {
|
||||
|
||||
@Override
|
||||
public boolean isWriteable(Class<?> clazz, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(List<Book> books, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
|
||||
JsonWriter jsonWriter = Json.createWriter(entityStream);
|
||||
JsonArray jsonArray = BookMapper.map(books);
|
||||
jsonWriter.writeArray(jsonArray);
|
||||
jsonWriter.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.microprofile.providers;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.util.BookMapper;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.MessageBodyReader;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
@Provider
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class BookMessageBodyReader implements MessageBodyReader<Book> {
|
||||
|
||||
@Override
|
||||
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return type.equals(Book.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Book readFrom(Class<Book> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
|
||||
return BookMapper.map(entityStream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.microprofile.providers;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.util.BookMapper;
|
||||
|
||||
import javax.json.Json;
|
||||
import javax.json.JsonObject;
|
||||
import javax.json.JsonWriter;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.WebApplicationException;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.ext.MessageBodyWriter;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
@Provider
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class BookMessageBodyWriter implements MessageBodyWriter<Book> {
|
||||
@Override
|
||||
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return type.equals(Book.class);
|
||||
}
|
||||
|
||||
/*
|
||||
Deprecated in JAX RS 2.0
|
||||
*/
|
||||
@Override
|
||||
public long getSize(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marsahl Book to OutputStream
|
||||
*
|
||||
* @param book
|
||||
* @param type
|
||||
* @param genericType
|
||||
* @param annotations
|
||||
* @param mediaType
|
||||
* @param httpHeaders
|
||||
* @param entityStream
|
||||
* @throws IOException
|
||||
* @throws WebApplicationException
|
||||
*/
|
||||
@Override
|
||||
public void writeTo(Book book, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
|
||||
JsonWriter jsonWriter = Json.createWriter(entityStream);
|
||||
JsonObject jsonObject = BookMapper.map(book);
|
||||
jsonWriter.writeObject(jsonObject);
|
||||
jsonWriter.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.microprofile.repo;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
|
||||
import javax.enterprise.context.ApplicationScoped;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@ApplicationScoped
|
||||
public class BookManager {
|
||||
|
||||
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
|
||||
private AtomicInteger bookIdGenerator = new AtomicInteger(0);
|
||||
|
||||
private ConcurrentMap<String, Book> inMemoryStore = new ConcurrentHashMap<>();
|
||||
|
||||
public BookManager() {
|
||||
Book book = new Book();
|
||||
book.setId(getNextId());
|
||||
book.setName("Building Microservice With Eclipse MicroProfile");
|
||||
book.setIsbn("1");
|
||||
book.setAuthor("baeldung");
|
||||
book.setPages(420);
|
||||
inMemoryStore.put(book.getId(), book);
|
||||
}
|
||||
|
||||
private String getNextId() {
|
||||
String date = LocalDate.now().format(formatter);
|
||||
return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date);
|
||||
}
|
||||
|
||||
public String add(Book book) {
|
||||
String id = getNextId();
|
||||
book.setId(id);
|
||||
inMemoryStore.put(id, book);
|
||||
return id;
|
||||
}
|
||||
|
||||
public Book get(String id) {
|
||||
return inMemoryStore.get(id);
|
||||
}
|
||||
|
||||
public List<Book> getAll() {
|
||||
List<Book> books = new ArrayList<>();
|
||||
books.addAll(inMemoryStore.values());
|
||||
return books;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.microprofile.util;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
|
||||
import javax.json.*;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
public class BookMapper {
|
||||
|
||||
public static JsonObject map(Book book) {
|
||||
JsonObjectBuilder builder = Json.createObjectBuilder();
|
||||
addValue(builder, "id", book.getId());
|
||||
addValue(builder, "isbn", book.getIsbn());
|
||||
addValue(builder, "name", book.getName());
|
||||
addValue(builder, "author", book.getAuthor());
|
||||
addValue(builder, "pages", book.getPages());
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static void addValue(JsonObjectBuilder builder, String key, Object value) {
|
||||
if (value != null) {
|
||||
builder.add(key, value.toString());
|
||||
} else {
|
||||
builder.addNull(key);
|
||||
}
|
||||
}
|
||||
|
||||
public static JsonArray map(List<Book> books) {
|
||||
final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
|
||||
books.forEach(book -> {
|
||||
JsonObject jsonObject = map(book);
|
||||
arrayBuilder.add(jsonObject);
|
||||
});
|
||||
return arrayBuilder.build();
|
||||
}
|
||||
|
||||
public static Book map(InputStream is) {
|
||||
try(JsonReader jsonReader = Json.createReader(is)) {
|
||||
JsonObject jsonObject = jsonReader.readObject();
|
||||
Book book = new Book();
|
||||
book.setId(getStringFromJson("id", jsonObject));
|
||||
book.setIsbn(getStringFromJson("isbn", jsonObject));
|
||||
book.setName(getStringFromJson("name", jsonObject));
|
||||
book.setAuthor(getStringFromJson("author", jsonObject));
|
||||
book.setPages(getIntFromJson("pages",jsonObject));
|
||||
return book;
|
||||
}
|
||||
}
|
||||
|
||||
private static String getStringFromJson(String key, JsonObject json) {
|
||||
String returnedString = null;
|
||||
if (json.containsKey(key)) {
|
||||
JsonString value = json.getJsonString(key);
|
||||
if (value != null) {
|
||||
returnedString = value.getString();
|
||||
}
|
||||
}
|
||||
return returnedString;
|
||||
}
|
||||
|
||||
private static Integer getIntFromJson(String key, JsonObject json) {
|
||||
Integer returnedValue = null;
|
||||
if (json.containsKey(key)) {
|
||||
JsonNumber value = json.getJsonNumber(key);
|
||||
if (value != null) {
|
||||
returnedValue = value.intValue();
|
||||
}
|
||||
}
|
||||
return returnedValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.microprofile.web;
|
||||
|
||||
import com.baeldung.microprofile.model.Book;
|
||||
import com.baeldung.microprofile.repo.BookManager;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
|
||||
@Path("books")
|
||||
@RequestScoped
|
||||
public class BookEndpoint {
|
||||
|
||||
@Inject
|
||||
private BookManager bookManager;
|
||||
|
||||
@GET
|
||||
@Path("{id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getBook(@PathParam("id") String id) {
|
||||
Book book = bookManager.get(id);
|
||||
return Response.ok(book).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAllBooks() {
|
||||
return Response.ok(bookManager.getAll()).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public Response add(Book book) {
|
||||
String bookId = bookManager.add(book);
|
||||
return Response.created(
|
||||
UriBuilder.fromResource(this.getClass()).path(bookId).build())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<server description="OpenLiberty MicroProfile server">
|
||||
<featureManager>
|
||||
<feature>jaxrs-2.0</feature>
|
||||
<feature>cdi-1.2</feature>
|
||||
<feature>jsonp-1.0</feature>
|
||||
</featureManager>
|
||||
<httpEndpoint httpPort="${default.http.port}" httpsPort="${default.https.port}"
|
||||
id="defaultHttpEndpoint" host="*"/>
|
||||
<applicationManager autoExpand="true"/>
|
||||
<webApplication context-root="${app.context.root}" location="${app.location}"/>
|
||||
</server>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
7
microservices-modules/msf4j/README.md
Normal file
7
microservices-modules/msf4j/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## MSF4J
|
||||
|
||||
This module contains articles about MSF4J.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Java Microservices with MSF4J](https://www.baeldung.com/msf4j)
|
||||
46
microservices-modules/msf4j/pom.xml
Normal file
46
microservices-modules/msf4j/pom.xml
Normal file
@@ -0,0 +1,46 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.msf4j</groupId>
|
||||
<artifactId>msf4j</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>msf4j</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wso2.msf4j</groupId>
|
||||
<artifactId>msf4j-service</artifactId>
|
||||
<version>${msf4j.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wso2.msf4j</groupId>
|
||||
<artifactId>msf4j-spring</artifactId>
|
||||
<version>${msf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.msf4j</groupId>
|
||||
<artifactId>msf4j-mustache-template</artifactId>
|
||||
<version>${msf4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<microservice.mainClass>com.baeldung.msf4j.msf4jintro.Application</microservice.mainClass>
|
||||
<msf4j.version>2.6.3</msf4j.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.msf4j.msf4japi;
|
||||
|
||||
import org.wso2.msf4j.MicroservicesRunner;
|
||||
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
new MicroservicesRunner()
|
||||
.deploy(new MenuService())
|
||||
.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.msf4j.msf4japi;
|
||||
|
||||
public class Meal {
|
||||
private String name;
|
||||
private Float price;
|
||||
|
||||
public Meal(String name, Float price) {
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Float getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.msf4j.msf4japi;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
@Path("/menu")
|
||||
public class MenuService {
|
||||
|
||||
private List<Meal> meals = new ArrayList<Meal>();
|
||||
|
||||
public MenuService() {
|
||||
meals.add(new Meal("Java beans",42.0f));
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/")
|
||||
@Produces({ "application/json" })
|
||||
public Response index() {
|
||||
return Response.ok()
|
||||
.entity(meals)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{id}")
|
||||
@Produces({ "application/json" })
|
||||
public Response meal(@PathParam("id") int id) {
|
||||
return Response.ok()
|
||||
.entity(meals.get(id))
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
@POST
|
||||
@Path("/")
|
||||
@Consumes("application/json")
|
||||
@Produces({ "application/json" })
|
||||
public Response create(Meal meal) {
|
||||
meals.add(meal);
|
||||
return Response.ok()
|
||||
.entity(meal)
|
||||
.build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/{id}")
|
||||
@Consumes("application/json")
|
||||
@Produces({ "application/json" })
|
||||
public Response update(@PathParam("id") int id, Meal meal) {
|
||||
meals.set(id, meal);
|
||||
return Response.ok()
|
||||
.entity(meal)
|
||||
.build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{id}")
|
||||
@Produces({ "application/json" })
|
||||
public Response delete(@PathParam("id") int id) {
|
||||
Meal meal = meals.get(id);
|
||||
meals.remove(id);
|
||||
return Response.ok()
|
||||
.entity(meal)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.msf4j.msf4jintro;
|
||||
|
||||
import org.wso2.msf4j.MicroservicesRunner;
|
||||
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
new MicroservicesRunner()
|
||||
.deploy(new SimpleService())
|
||||
.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.msf4j.msf4jintro;
|
||||
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
|
||||
@Path("/")
|
||||
public class SimpleService {
|
||||
|
||||
@GET
|
||||
public String index() {
|
||||
return "Default content";
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/say/{name}")
|
||||
public String say(@PathParam("name") String name) {
|
||||
return "Hello " + name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.msf4j.msf4jspring;
|
||||
|
||||
import org.wso2.msf4j.spring.MSF4JSpringApplication;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
MSF4JSpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.msf4j.msf4jspring.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.wso2.msf4j.spring.transport.HTTPTransportConfig;
|
||||
|
||||
@Configuration
|
||||
public class PortConfiguration {
|
||||
|
||||
@Bean
|
||||
public HTTPTransportConfig http() {
|
||||
return new HTTPTransportConfig(9090);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.msf4j.msf4jspring.domain;
|
||||
|
||||
public class Meal {
|
||||
private String name;
|
||||
private Float price;
|
||||
|
||||
public Meal(String name, Float price) {
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Float getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.msf4j.msf4jspring.repositories;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.baeldung.msf4j.msf4jspring.domain.Meal;
|
||||
|
||||
@Component
|
||||
public class MealRepository {
|
||||
|
||||
private List<Meal> meals = new ArrayList<Meal>();
|
||||
|
||||
public MealRepository() {
|
||||
meals.add(new Meal("Salad", 4.2f));
|
||||
meals.add(new Meal("Litre of cola", 2.99f));
|
||||
}
|
||||
|
||||
public void create(Meal meal) {
|
||||
meals.add(meal);
|
||||
}
|
||||
|
||||
public void remove(Meal meal) {
|
||||
meals.remove(meal);
|
||||
}
|
||||
|
||||
public Meal find(int id) {
|
||||
return meals.get(id);
|
||||
}
|
||||
|
||||
public List<Meal> findAll() {
|
||||
return meals;
|
||||
}
|
||||
|
||||
public void update(int id, Meal meal) {
|
||||
meals.set(id, meal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.msf4j.msf4jspring.resources;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.wso2.msf4j.template.MustacheTemplateEngine;
|
||||
|
||||
import com.baeldung.msf4j.msf4jspring.services.MealService;
|
||||
|
||||
@Component
|
||||
@Path("/meal")
|
||||
public class MealResource {
|
||||
|
||||
@Autowired
|
||||
private MealService mealService;
|
||||
|
||||
@GET
|
||||
@Path("/")
|
||||
public Response all() {
|
||||
Map map = Collections.singletonMap("meals", mealService.findAll());
|
||||
String html = MustacheTemplateEngine.instance()
|
||||
.render("meals.mustache", map);
|
||||
return Response.ok()
|
||||
.type(MediaType.TEXT_HTML)
|
||||
.entity(html)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{id}")
|
||||
@Produces({ "text/xml" })
|
||||
public Response meal(@PathParam("id") int id) {
|
||||
return Response.ok()
|
||||
.entity(mealService.find(id))
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.msf4j.msf4jspring.services;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.msf4j.msf4jspring.domain.Meal;
|
||||
import com.baeldung.msf4j.msf4jspring.repositories.MealRepository;
|
||||
|
||||
@Service
|
||||
public class MealService {
|
||||
@Autowired
|
||||
private MealRepository mealRepository;
|
||||
|
||||
public Meal find(int id) {
|
||||
return mealRepository.find(id);
|
||||
}
|
||||
|
||||
public List<Meal> findAll() {
|
||||
return mealRepository.findAll();
|
||||
}
|
||||
|
||||
public void create(Meal meal) {
|
||||
mealRepository.create(meal);
|
||||
}
|
||||
}
|
||||
13
microservices-modules/msf4j/src/main/resources/logback.xml
Normal file
13
microservices-modules/msf4j/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<head>
|
||||
<title>Meals</title>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
<h1>Today's Meals</h1>
|
||||
{{#meals}}
|
||||
<div>{{name}}: {{price}}$ </div>
|
||||
{{/meals}}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
3
microservices-modules/open-liberty/README.md
Normal file
3
microservices-modules/open-liberty/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Open Liberty](https://www.baeldung.com/java-open-liberty)
|
||||
127
microservices-modules/open-liberty/pom.xml
Normal file
127
microservices-modules/open-liberty/pom.xml
Normal file
@@ -0,0 +1,127 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>open-liberty</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>jakarta.platform</groupId>
|
||||
<artifactId>jakarta.jakartaee-web-api</artifactId>
|
||||
<version>${version.jakarta.jakartaee-web-api}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.microprofile</groupId>
|
||||
<artifactId>microprofile</artifactId>
|
||||
<version>${version.microprofile}</version>
|
||||
<type>pom</type>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derby</artifactId>
|
||||
<version>${version.derby}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- For tests -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse</groupId>
|
||||
<artifactId>yasson</artifactId>
|
||||
<version>${version.yasson}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${version.cxf-rt-rs-client}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish</groupId>
|
||||
<artifactId>javax.json</artifactId>
|
||||
<version>${version.javax.json}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-mp-client</artifactId>
|
||||
<version>${version.cxf-rt-rs-mp-client}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<!-- Enable liberty-maven plugin -->
|
||||
<plugin>
|
||||
<groupId>io.openliberty.tools</groupId>
|
||||
<artifactId>liberty-maven-plugin</artifactId>
|
||||
<version>${version.liberty-maven-plugin}</version>
|
||||
<configuration>
|
||||
<copyDependencies>
|
||||
<location>${project.build.directory}/liberty/wlp/usr/shared/resources/</location>
|
||||
<dependency>
|
||||
<groupId>org.apache.derby</groupId>
|
||||
<artifactId>derby</artifactId>
|
||||
<version>${version.derby}</version>
|
||||
</dependency>
|
||||
</copyDependencies>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${version.maven-war-plugin}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
<!-- versions -->
|
||||
<version.jakarta.jakartaee-web-api>8.0.0</version.jakarta.jakartaee-web-api>
|
||||
<version.microprofile>3.2</version.microprofile>
|
||||
<version.derby>10.14.2.0</version.derby>
|
||||
<version.liberty-maven-plugin>3.3-M3</version.liberty-maven-plugin>
|
||||
<version.maven-war-plugin>3.2.3</version.maven-war-plugin>
|
||||
<version.yasson>1.0.5</version.yasson>
|
||||
<version.cxf-rt-rs-client>3.2.6</version.cxf-rt-rs-client>
|
||||
<version.javax.json>1.0.4</version.javax.json>
|
||||
<version.cxf-rt-rs-mp-client>3.3.1</version.cxf-rt-rs-mp-client>
|
||||
<!-- Liberty configuration -->
|
||||
<liberty.var.app.context.root>openliberty</liberty.var.app.context.root>
|
||||
<liberty.var.default.http.port>9080</liberty.var.default.http.port>
|
||||
<liberty.var.default.https.port>9443</liberty.var.default.https.port>
|
||||
<testServerHttpPort>7070</testServerHttpPort>
|
||||
<junit-jupiter.version>5.8.1</junit-jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.openliberty.person.dao;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
|
||||
import com.baeldung.openliberty.person.model.Person;
|
||||
|
||||
@RequestScoped
|
||||
public class PersonDao {
|
||||
|
||||
@PersistenceContext(name = "jpa-unit")
|
||||
private EntityManager em;
|
||||
|
||||
public Person createPerson(Person person) {
|
||||
em.persist(person);
|
||||
return person;
|
||||
}
|
||||
|
||||
public Person readPerson(int personId) {
|
||||
return em.find(Person.class, personId);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.openliberty.person.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.validation.constraints.Email;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
@Entity
|
||||
public class Person {
|
||||
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
private String username;
|
||||
private String email;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Person(int id, @NotBlank String username, @Email String email) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Person() {
|
||||
super();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.id + ":" +this.username;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.openliberty.person.resource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.enterprise.context.RequestScoped;
|
||||
import javax.inject.Inject;
|
||||
import javax.transaction.Transactional;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import com.baeldung.openliberty.person.dao.PersonDao;
|
||||
import com.baeldung.openliberty.person.model.Person;
|
||||
|
||||
@RequestScoped
|
||||
@Path("persons")
|
||||
public class PersonResource {
|
||||
|
||||
@Inject
|
||||
private PersonDao personDao;
|
||||
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public List<Person> getAllPersons() {
|
||||
return Arrays.asList(new Person(1, "normanlewis", "normanlewis@email.com"));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Transactional
|
||||
public Response addPerson(Person person) {
|
||||
personDao.createPerson(person);
|
||||
String respMessage = "Person #" + person.getId() + " created successfully.";
|
||||
return Response.status(Response.Status.CREATED).entity(respMessage).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("{id}")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Transactional
|
||||
public Person getPerson(@PathParam("id") int id) {
|
||||
Person person = personDao.readPerson(id);
|
||||
return person;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.openliberty.rest;
|
||||
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.core.Application;
|
||||
|
||||
@ApplicationPath("/api")
|
||||
public class ApiApplication extends Application {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.openliberty.rest.consumes;
|
||||
|
||||
import javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
public class RestConsumer {
|
||||
|
||||
public static String consumeWithJsonb(String targetUrl) {
|
||||
Client client = ClientBuilder.newClient();
|
||||
Response response = client.target(targetUrl).request().get();
|
||||
String result = response.readEntity(String.class);
|
||||
response.close();
|
||||
client.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.openliberty.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet(urlPatterns="/app")
|
||||
public class AppServlet extends HttpServlet {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
String htmlOutput = "<html><h2>Hello! Welcome to Open Liberty</h2></html>";
|
||||
response.getWriter().append(htmlOutput);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
doGet(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<server description="Baeldung Open Liberty server">
|
||||
<featureManager>
|
||||
<feature>mpHealth-2.0</feature>
|
||||
<feature>servlet-4.0</feature>
|
||||
<feature>jaxrs-2.1</feature>
|
||||
<feature>jsonp-1.1</feature>
|
||||
<feature>jsonb-1.0</feature>
|
||||
<feature>cdi-2.0</feature>
|
||||
<feature>jpa-2.2</feature>
|
||||
</featureManager>
|
||||
|
||||
<webApplication location="open-liberty.war" contextRoot="/" />
|
||||
|
||||
<logging traceSpecification="com.ibm.ws.microprofile.health.*=all" hideMessage="SRVE9967W" />
|
||||
|
||||
<httpEndpoint host="*" httpPort="${default.http.port}" httpsPort="${default.https.port}" id="defaultHttpEndpoint" />
|
||||
|
||||
<library id="derbyJDBCLib">
|
||||
<fileset dir="${shared.resource.dir}" includes="derby*.jar"/>
|
||||
</library>
|
||||
|
||||
<!-- Datasource Configuration -->
|
||||
<dataSource id="jpadatasource" jndiName="jdbc/jpadatasource">
|
||||
<jdbcDriver libraryRef="derbyJDBCLib" />
|
||||
<properties.derby.embedded databaseName="libertyDB" createDatabase="create" />
|
||||
</dataSource>
|
||||
|
||||
</server>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence version="2.2"
|
||||
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
|
||||
<persistence-unit name="jpa-unit" transaction-type="JTA">
|
||||
<jta-data-source>jdbc/jpadatasource</jta-data-source>
|
||||
<properties>
|
||||
<property name="eclipselink.ddl-generation" value="create-tables"/>
|
||||
<property name="eclipselink.ddl-generation.output-mode" value="both" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.openliberty;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.json.bind.JsonbBuilder;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.openliberty.person.model.Person;
|
||||
import com.baeldung.openliberty.rest.consumes.RestConsumer;
|
||||
|
||||
public class RestClientLiveTest {
|
||||
|
||||
private static String BASE_URL;
|
||||
|
||||
private final String API_PERSON = "api/persons";
|
||||
|
||||
@BeforeClass
|
||||
public static void oneTimeSetup() {
|
||||
BASE_URL = "http://localhost:9080/";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuite() {
|
||||
//run the test only when liberty server is started
|
||||
//this.whenConsumeWithJsonb_thenGetPerson();
|
||||
}
|
||||
|
||||
public void whenConsumeWithJsonb_thenGetPerson() {
|
||||
String url = BASE_URL + API_PERSON + "/1";
|
||||
String result = RestConsumer.consumeWithJsonb(url);
|
||||
|
||||
Person person = JsonbBuilder.create().fromJson(result, Person.class);
|
||||
assertEquals(1, person.getId());
|
||||
assertEquals("normanlewis", person.getUsername());
|
||||
assertEquals("normanlewis@email.com", person.getEmail());
|
||||
}
|
||||
|
||||
}
|
||||
24
microservices-modules/pom.xml
Normal file
24
microservices-modules/pom.xml
Normal file
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>microservices-modules</artifactId>
|
||||
<name>microservices-modules</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>helidon</module>
|
||||
<module>micronaut</module>
|
||||
<module>microprofile</module>
|
||||
<module>msf4j</module>
|
||||
<module>open-liberty</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
Reference in New Issue
Block a user