Eclipse MicroProfile (#3608)

* initial commit

* change path value

* change path value

* clean

* model to json mapper

* Model to Json mapper

* json to model

* rename

* clean

* clean

* Open Liberty runtime

* clean

* OpenLiberty Config File

* OpenLiberty maven plugin

* clean

* clean

* clean

* clean
This commit is contained in:
eelhazati 2018-02-22 11:40:58 +00:00 committed by pauljervis
parent b89b1cab6d
commit d172168ace
10 changed files with 452 additions and 0 deletions

87
microprofile/pom.xml Normal file
View File

@ -0,0 +1,87 @@
<?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</groupId>
<artifactId>microprofile</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<app.name>library</app.name>
<package.file>${project.build.directory}/${app.name}-service.jar</package.file>
<packaging.type>runnable</packaging.type>
</properties>
<dependencies>
<dependency>
<groupId>org.eclipse.microprofile</groupId>
<artifactId>microprofile</artifactId>
<version>1.2</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>2.1.2</version>
<configuration>
<assemblyArtifact>
<groupId>io.openliberty</groupId>
<artifactId>openliberty-runtime</artifactId>
<version>17.0.0.4</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>
</project>

View File

@ -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 {
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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>