Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update for MicroProfile 1.3 #1

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,60 @@
# getting-started-microprofile
Getting Started with Eclipse MicroProfile
# Getting Started with Eclipse MicroProfile

This is a sample application showcasing MicroProfile features

# How to build

To compile, execute

```
mvn install
```

This will also build a JAR file. To run the JAR file, you need to run it with a MicroProfile implementation that can run JAR files.

To build a WAR file that can be deployed to a server, execute

```
mvn install war:war
```

# How to run

Because MicroProfile provides only an interface, it's necessary to run the built application with one of the runtimes or libraries that provide the implementation. Have a look at the [list of MicroProfile implementations](https://wiki.eclipse.org/MicroProfile/Implementation) and consult with their documentation.

## Required configuration

The book service requires the following configuration values to be known to the MicroProfile container:

- `ws.ament.microprofile.gettingstarted.AuthorService/mp-rest/url` - the base URL of author service

The following properties can be optionally defined:

- `max.books.per.page` - maximum number of books in the response if no book id is specified, default is 20


## Run a mock author service

Run a mock author REST service that listens on port 8081 (requires maven version at least 3.3.1):

```
mvn -Dport=8081 org.codehaus.gmaven:groovy-maven-plugin:execute@author-service
```

## An example how to run with Payara Micro

Payara Micro is one of the MicroProfile implementations. It can run standard WAR files. It doesn't require any special set up to get started - it's just a JAR file that you can execute with the `java` command.

First, build a WAR file as described earlier.

Then download Payara Micro v182 or later from [https://www.payara.fish/downloads](https://www.payara.fish/downloads) and save it into the directory `target` in the project as `payara-micro.jar`.

Switch to the `target` directory and execute the following command line:

```
java -D'ws.ament.microprofile.gettingstarted.AuthorService/mp-rest/url=http://localhost:8081' -jar payara-micro.jar microprofile-get-started.war
```

Then access the URL [http://localhost:8080/microprofile-get-started/api/books](http://localhost:8080/microprofile-get-started/api/books) to access the `BooksController` REST endpoint. You should see "HTTP Status 401 - Unauthorized" because the resource is secured with the JWT mechanism.

In order to authenticate and access the service, you also need to generate a JWT token and use it when with the REST call. Consult [Payara documentation about JWT](https://docs.payara.fish/documentation/microprofile/jwt.html) how to do that.
41 changes: 40 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<groupId>ws.ament.microprofile</groupId>
<artifactId>getting-started-microprofile</artifactId>
<version>1.0-SNAPSHOT</version>
<name>MicroProfile - Getting started example</name>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
Expand All @@ -15,7 +16,8 @@
<dependency>
<groupId>org.eclipse.microprofile</groupId>
<artifactId>microprofile</artifactId>
<version>1.2</version>
<version>1.3</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<dependency>
Expand All @@ -24,4 +26,41 @@
<version>2.2</version>
</dependency>
</dependencies>
<build>
<finalName>microprofile-get-started</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>groovy-maven-plugin</artifactId>
<executions>
<execution>
<id>author-service</id>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>${project.basedir}/runMockAuthorService.groovy</source>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.4.9.v20180320</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
36 changes: 36 additions & 0 deletions runMockAuthorService.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;

import java.io.IOException;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

class AuthorServlet extends AbstractHandler
{
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("\"This is a mock author\"");
}
}

def startJetty() {
int port = Integer.parseInt(properties.getProperty("port", "8080"))
def server = new Server(port)

server.handler = new AuthorServlet()
server.start()
server.join()
}

println "Starting Jetty, press Ctrl+C to stop."
startJetty()
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package ws.ament.microprofile.gettingstarted;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;

/**
*
* @author Ondrej Mihalyi
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RegisterRestClient
public interface AuthorConnector {
@GET
Author get(String id);
}

Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,21 @@
import javax.ws.rs.core.MediaType;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.eclipse.microprofile.rest.client.inject.RestClient;

@ApplicationScoped
public class AuthorService {
@Inject
@ConfigProperty(name = "author.service.url")
private String authorUrl;
@RestClient
AuthorConnector authorConnector;

private ConcurrentMap<String, Author> authorCache = new ConcurrentHashMap<>();

@Retry
@CircuitBreaker
@Fallback(fallbackMethod = "getCachedAuthor")
public Author findAuthor(String id) {
Author author = ClientBuilder.newClient()
.target(authorUrl)
.path("/{id}")
.resolveTemplate("id", id)
.request(MediaType.APPLICATION_JSON)
.get(Author.class);
Author author = authorConnector.get(id);
authorCache.put(id, author);
return author;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import javax.enterprise.context.RequestScoped;

@Path("/api/books")
@Counted
@RequestScoped
public class BookPublishController {
@Inject
private PublishBookService publishBookService;

@POST
public Response publish(PublishBook publishBook) {
BookId bookId = publishBookService.publish(publishBook);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package ws.ament.microprofile.gettingstarted;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.eclipse.microprofile.auth.LoginConfig;

/**
*
* @author Ondrej Mihalyi
*/
@LoginConfig(authMethod = "MP-JWT", realmName = "admin-realm")
@ApplicationScoped
@ApplicationPath("/")
public class BookServiceConfig extends Application {

}

Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import org.eclipse.microprofile.metrics.annotation.Counted;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/api/books")
@Counted
@RequestScoped
public class BooksController {
@Inject
private BookService bookService;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package ws.ament.microprofile.gettingstarted;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
*
* @author Ondrej Mihalyi
*/
@ApplicationScoped
public class JPAProducer {
@Produces
@PersistenceContext
private EntityManager em;
}

Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public class PublishBookService {
private AuthorService authorService;
@Inject
private EntityManager entityManager;

@Timeout(500)
public BookId publish(PublishBook publishBook) {
if(!publishBook.getAuthor().equals(jsonWebToken.getSubject())) {
Expand All @@ -31,4 +32,5 @@ public BookId publish(PublishBook publishBook) {
Book book = entityManager.merge(new Book(publishBook.getIsbn(), publishBook.getAuthor()));
return new BookId(book.getIsbn(), book.getAuthor());
}

}