User Guide

Payara Platform and PaaS with Platform.sh

The Payara® Platform - Production-Ready, Cloud Native and Aggressively Compatible. Payara Platform and PaaS with Platform.sh

Contents

1. What’s the Cloud? 1 2. What’s Cloud Native? 3 What Are Cloud-Native Best Practices? 4 3. What is the Payara Platform? 5 Payara Server 5 Payara Micro 5 4. What’s Platform.sh? 6 Git Driven Infrastructure 6 Infrastructure as Code 6 Structure 7 Router 7 Service 8 Application 8 5. Together We’re Great! 8 6. Hello World with Payara Micro and Platform.sh 9 7. Payara Platform with JPA 11 8. Payara Platform with NoSQL 19 9. Payara Micro, Platform.sh, and Microservices 26 10. About Platform.sh 28 11. About Payara Services Limited 29 Payara Platform and PaaS with Platform.sh

1. What’s the Cloud?

Software is everywhere. No matter where you look, there is software running. In human history, we’ve seen the number of machines/software increase with time, from one machine shared by a bunch of people, to a single person using thousands of software programs. Now, we can see software interact- ing with other software, such as when you buy a flight ticket: a system sends an email, another reads it and fires an event into your calendar. This new approach opens more business perspectives and opportunities for everybody, including machine learning. Make no mistake, Skynet is coming soon.

It’s not just the amount of software that has increased, but also the number of interactions in a program itself. More users, more requirements, more feedback. It doesn’t make sense to wait years to release a product, the time-to-market and the user feedback are vital to drive the product in the right direction. That’s why in 2001, a small group of people, tired of the traditional approach to man- aging software development projects, designed the agile manifesto, which gave birth to the agile methodology. Agile is a process that helps teams provide quick and unpredictable responses to the feedback they receive on their project. It creates opportunities to assess a project’s direction during the development cycle. Organizations evaluate the project in regular meetings called sprints or iter- ations. In a more technical aspect aligning with Agile, the Domain-Driven Design (DDD) approach to developing software for complex needs deeply connects the implementation to an evolving model of the core business concepts. Techniques such as Ubiquitous Language are used to having the code closer to the business, decreasing the barrier between the developer and the user, and therefore, having more interactions than with an agile development.

More and more companies understand that all companies are software companies. As a result of relying heavily on software, companies frequently need to hire software developers. The question of how to handle several people working on just one project then arises. To solve this modern question, we can look at an ancient Roman military strategy: divide and conquer. Yes, divide a highly com- plex issue into small blocks of problems, split the team into small groups and divide the monolithic project into smaller ones. The Microservice architectural style is an approach to developing a single application into a suite of small services so that, for example, instead of an e-commerce company working with just one code-base and one implementation, it can split the teams/code in financial, product stock, marketing and so on. One thing to point out, the DDD context is still there. Indeed, it works alongside the approach for how to create useful services based on some of its bounded concepts; we’re not discarding or deprecating that notion, but aggregating it into microservices.

Microservices, beyond making the team more agile, also bring several advantages such as inde- pendent scaling-up and releasing discrete services. However, it carries more twists in the operations side. Finalised code is not enough if it does not go to production. Thus the operations must follow the development team to release what the system needs to deploy every day. This is why: DevOps is a set of software development practices that combine software development (Dev) and informa- tion-technology operations (Ops) to shorten the systems development life cycle while delivering features, fixes, and updates frequently in close alignment with business objectives.

1 Payara Platform and PaaS with Platform.sh

With both development and operations teams integrated and working together with the DevOps methodology, we’re ready to handle software and operations. But how about hardware? Integrating the team means that equipment does not exist. What happens when a team needs more computer power? Does it make sense for somebody to go buy a new server? It isn’t fast enough. In the global market and with the milliseconds battle to get less response time, a closer server to the client means less throughput time, but how do we buy/keep servers in several continents?

With cloud computing that is available on-demand for computer system resources, especially data storage and computing power, without direct active management by the user, Cloud computing means: we don’t care about the hardware itself. These services are broadly divided into three cate- gories: Infrastructure-as-a-Service (IaaS), Platform-as-a-Service (PaaS) and Software-as-a-Service (SaaS).

These categories bring a new business concept to the market. Furthermore, each service brings new facilities, mainly fast delivery.

There is a fantastic article that explains the benefits of cloud computing with the most popular and delicious food in the world as an example. That’s right, pizza!

Pizza as a Service Traditional On-Premises (On Prem) Infrastructure as a Service Platform as a Service (PaaS) Software as a Service (SaaS)

Dining Dining Table Dining Table Dining Table

Soda Soda Soda Soda

Electric/Gas Electric/Gas Electric/Gas Electric/Gas

Oven Oven Oven Oven

Fire Fire Fire Fire

Pizza Dough Pizza Dough Pizza Dough Pizza Dough

Tomato Sauce Tomato Sauce Tomato Sauce Tomato Sauce

Toppings Toppings Toppings Toppings

Cheese Cheese Cheese Cheese

Made at Home Take & Bake Pizza Delivered Dined Out

You Manage Vendor Manages

2 Payara Platform and PaaS with Platform.sh

In short:

Benefits of IaaS:

• No need to invest in your own hardware • Infrastructure scales on-demand to support dynamic workloads

Benefits of PaaS:

• Develop applications and get to market faster • Reduce complexity with middleware as a service

Benefits of SaaS:

• Apps and data are accessible from any connected computer. • No data is lost if your laptop breaks because the information is in the cloud.

A software project has fast delivery as the best strategic approach. A quick-release brings several benefits, such as receiving feedback, fixing bugs, and mainly driving the product in the right direction based on the user needs. That’s why several methodologies/technologies such as Agile, micros- ervices, DevOps, or cloud were born. Nowadays, it is hard to think of waiting one year to release a project, running the risk of missing the right timing. The Community has decided to push a release every six months, and Jakarta EE seeks the same path. Platform.sh has the goal of making it easier to move your project to cloud-computing, allowing you to deploy anywhere and anytime, including on a sunny Friday.

2. What’s Cloud Native?

Cloud computing has brought many methodologies and techniques that have revolutionized both the business and technical worlds. Among the terms that came up was cloud-native. To meet and cover these expectations in the Java universe, Jakarta EE emerged.

Like any new concept, there are several concepts with the same name; if you read books or articles about cloud-native, you may not find consensus about it. For example:

> Cloud-native is an approach to building and running applications that exploits the advantages of the cloud computing model.

From Pivotal

> Cloud-native is a different way of thinking and reasoning about software systems. It embodies the following concepts: powered by disposable infrastructure, composed of bounded, scales globally, embraces disposable architecture.

3 Payara Platform and PaaS with Platform.sh

Architecting Cloud Native Applications: Design high-performing and cost-effective applications for the cloud

> In general usage, "cloud-native" is an approach to building and running applications that exploits the advantages of the cloud-computing delivery model. "Cloud-native" is about how applications are created and deployed, not where.

InfoWorld

In a mutual consensus around the definitions from several articles, we can say that cloud-native is a term used to describe container-based environments. So cloud-native isn’t related to specific programming languages or frameworks or even to a cloud provider company, but to containers.

What Are Cloud-Native Best Practices?

When we start to learn a new concept, we usually run to read about best practices to avoid mistakes and any code smell. With Object-Oriented Programming (OOP), we have the design patterns from the gang of four, in Java we have Effective Java, and when talking about architecture, we have both Clean Code and Clean Architecture. So the question is: what are the best practices for cloud-native?

As far as we know, there aren’t best practices related specifically to cloud-native. But since the cloud is close to Agile methodology, there are several practices we can leverage to have a healthy, pain-free application:

• Manifesto for Agile Software Development • Continuous integration • Continuous delivery • Domain-Driven Design

The most well-known practices related to any application that includes cloud computing are inspired by Martin Fowler’s Patterns of Enterprise Application Architecture and Refactoring.

The Twelve-Factor App 1. Codebase One codebase tracked in revision control, many deploys 2. Dependencies Explicitly declare and isolate dependencies 3. Config Store config in the environment 4. Backing services Treat backing services as attached resources 5. Build, release, run Strictly separate build and run stages 6. Processes Execute the app as one or more stateless processes

4 Payara Platform and PaaS with Platform.sh

7. Port binding Export services via port binding 8. Concurrency Scale out via the process model 9. Disposability Maximize robustness with fast startup and graceful shutdown 10. Dev/prod parity Keep development, staging, and production as similar as possible 11. Logs Treat logs as event streams 12. Admin processes Run admin/management tasks as one-off processes In summary, there aren’t specific best practices for cloud-native yet, but there are patterns from Agile, microservices, and the twelve-factor app that are useful to follow.

3. What is the Payara Platform?

Payara Platform Enterprise is stable, supported software for enterprise designed for mission critical production systems and containerized Jakarta EE (Java EE) and MicroProfile applications.

Payara Server

Payara Server is a cloud-native middleware application platform that supports reliable and secure deployments of Jakarta EE applications on premise, in the cloud, or hybrid environments. A stable platform with monthly releases, bug fixes, and a 10-year software lifecycle, Payara Server is aggres- sively compatible with the ecosystem, cloud vendors, Docker, and Kubernetes.

An official Jakarta EE compatible implementation, Payara Server is developed in collaboration with an industry-leading DevOps team and the global Payara community to ensure Payara Server is the best option for production jakarta EE applications today and in the future.

Payara Micro

Payara Micro is the lightweight middleware platform of choice for containerized Jakarta EE appli- cation deployments. Less than 70mb, Payara Micro requires no installation, configuration, or code rewrites - so you can build and deploy a working app within minutes.

Compatible with MicroProfile, Payara Micro is the microservices-ready version of Payara Server. It comes with a Java AP to embed and launch from your own Java applications and offers the ability to run files from the command line without any installation. Automatic and elastic clustering makes Payara Micro the platform of choice for running Jakarta EE applications in a modern virtualized infrastructure.

5 Payara Platform and PaaS with Platform.sh

4. What’s Platform.sh?

Platform.sh is a second-generation Platform-as-a-Service built especially for continuous deployment. It allows you to host web applications on the cloud while making your development and testing workflows more productive.

If you’re new to Platform.sh, we recommend starting with the Big Picture, in particular Structure, and Build & Deploy will get you started on the right track to best leverage Platform.sh.

The main requirement of Platform.sh is that you use Git to manage your application code. Your pro- ject’s configuration is driven almost entirely by a small number of YAML files in your Git repository. The Configuration section covers those in more detail and can serve as both tutorial and quick-reference.

Platform.sh supports a number of different programming Languages and environments, and it fea- tures recommended optimizations for a number of Featured Frameworks.

Finally, you can also get tips for setting up your own Development workflow and Administering your Platform.sh account.

Git Driven Infrastructure

As a Platform as a Service, or PaaS, Platform.sh automatically manages everything your application needs in order to run. That means you can, and should, view your infrastructure needs as part of your application, and version-control it as part of your application.

Infrastructure as Code

Platform.sh covers not only all of your hosting needs but also most of your DevOps needs. It is a simple, single tool that covers the application life-cycle from development to production and scaling.

You only need to write your code, including a few YAML files that specify your desired infrastructure, commit it to Git, and push. You don’t need to setup anything manually. The web server is already setup and configured, as is any database, search engine, or cache that you specify.

Every branch you push is a fully independent environment—complete with your application code, a copy of your database, a copy of your search index, a copy of your user files, everything—and its automatically generated URL can be sent to stakeholders or to automated CI systems. It really is "what would my site look like if I merged this to production?" Every time.

You can use these concepts to replicate a traditional development/staging/production workflow or even to give every feature its own effective staging environment before merging to production

6 Payara Platform and PaaS with Platform.sh

(empowering you to use git-flow like methodologies even better). You could also have an interme- diary integration branch for several other branches.

Platform.sh respects the structure of branches. It’s entirely up to you.

Structure

Every application you deploy on Platform.sh is built as a virtual cluster, containing a set of containers. The master branch of your Git repository is always deployed as the production cluster. Any other branch can be deployed as a development cluster. By default, you can have up to three live devel- opment clusters at once, but you can buy more on a per-project basis.

There are three types of containers within your cluster:

• one Router • one or more Application containers • zero or more Service containers

All of those containers are managed by three special files in your Git repository:

• .platform/routes.yaml • .platform/services.yaml • .platform.app.yaml In most cases, that means your repository will look like this:

yourproject/ .git/ .platform/ services.yaml routes.yaml .platform.app.yaml

Router

There is always exactly one Router per cluster.

The Router of a cluster is a single nginx process. It is configured by theroutes.yaml file. It maps incoming requests to the appropriate Application container and provides basic caching of responses, if so configured. It has no persistent storage.

7 Payara Platform and PaaS with Platform.sh

Service

Service containers are configured by theservices.yaml file.

There may be zero or more Service containers in a cluster, depending on the services.yaml file. The code for a Service is provided by Platform.sh in a pre-built container image, along with a default configuration. Depending on the service it may also include user-provided configuration in the services.yaml file. Examples of services include MySQL/MariaDB, Elasticsearch, Redis, and RabbitMQ.

Application

There always must be one Application container in a cluster, but there may be more.

Each Application container corresponds to a .platform.app.yaml file in the repository. If there are 3 .platform.app.yaml files, there will be three Application containers. Application containers hold the code you provide via your Git repository. Application containers are always built off of one of the Platform.sh-provided language-specific images, such as "Java 8", "Java 11". It is also possible to have multiple Application containers running different languages or versions.

For typical applications, there is only one .platform.app.yaml file, which is generally placed at the repository root.

5. Together We’re Great!

Now that we’ve introduced both Payara and Platform.sh, we can get them to work together.

Platform.sh has support for several build tools such as Maven, Gradle, and Ant. For an easy start, we might start with a template using a powerful and intuitive wizard to make it happen, and on that template includes a Payara Micro one.

8 Payara Platform and PaaS with Platform.sh

6. Hello World with Payara Micro and Platform.sh

In this section we will cover how to create your first REST project with Payara Micro, and then move that project to Platform.sh using the Maven Archetype, which is a Maven project templating toolkit. An archetype is defined as an original pattern or model from which all other things of the same kind are made. You can generate with the following command:

''' mvn archetype:generate -DarchetypeGroupId=sh.platform.archetype -DarchetypeArtifactId=payara -DarchetypeVersion=0.0.1 -DgroupId=my.company -DartifactId=hello -Dversion=0.0.1 -DinteractiveMode=false '''

The next step is to convert it into a Git project, so:

''' cd hello git init git add . git commit -m "hello world with Payara" '''

Then, finally, create a new project on Platform.sh, take the git repository address and push your code to master. As soon you push this code to master it will generate the containers that you need to make your application available.

''' git remote add cloud git push cloud master '''

As soon we push the code to remove, it will create the maven build and deploy the application. In the end, it will generate the IP address, take this address and make a request in the server.

9 Payara Platform and PaaS with Platform.sh

''' curl hello from Platform.sh '''

After you push, Platform.sh will start two containers: one Router container that handles requests to the app, and one Application container using the Java 8 runtime.

The Maven Archetype we’ll generate includes the maven dependencies and the three files that Platform.sh requires to move this application to the cloud. Now, let’s go deep into this file and talk about one by one. To point out, these files represent the concept of infrastructure as code - the pro- cess of managing and provisioning computer data centers through machine-readable definition files.

''' name: app type: "java:8" disk: 1024 hooks: build: mvn -DskipTests clean package payara-micro:bundle web: commands: start: java -jar -Xmx512m target/microprofile-microbundle.jar --port $PORT '''

10 Payara Platform and PaaS with Platform.sh

The application file has the configuration to create the application container. The build is defined by a Maven command which creates an uberjar. To create the application container, the file has the following attributes:

• name (required) - Sets the unique name of the application container. • type (required) - Sets the container base image to use, including application language and it’s version. • disk and mounts (required) - Defines writable file directories for the application. • build, dependencies, and hooks - Control how the application gets compiled. Note that this compilation happens before the application is copied into different instances, so any steps here will apply to all web and worker instances. • web - Controls how the is served.

A plain hello world app is ready, so let’s move forward and create a JAX-RS integrated with a SQL database.

7. Payara Platform with JPA

After creating the first plain hello world with Payara Micro and Platform.sh, it’s time to create the first application connected with a SQL database. Payara has support for Jakarta technologies that includes JPA, Jakarta Persistence API.

Jakarta Persistence defines a standard for management of persistence and object/relational map- ping in Java(R) environments.

On this point, we’ll create a REST application this time connect to a relational database; we have support to MySQL, Maria and PostgreSQL, but on this application we’ll use PostgreSQL.

The first step is to create a new Java project, which we can either create from a template or create from Maven archetype that we mentioned previously.

''' mvn archetype:generate -DarchetypeGroupId=sh.platform.archetype -DarchetypeArtifactId=payara -DarchetypeVersion=0.0.1 -DgroupId=my.compary -DartifactId=jpa -Dversion=0.0.1 -DinteractiveMode=false ''' Then, we need to add a PostgreSQL Driver as a dependency in pom..

'''xml

11 Payara Platform and PaaS with Platform.sh

org.postgresql postgresql 42.2.9 '''

The next step is set data source in your 'web.xml' add the following:

'''xml java:global/JPAExampleDataSource org.postgresql.ds.PGSimpleDataSource ${server.host} 5432 ${server.database} ${server.user} ${server.password} '''

Environment variables, system properties and aliases are supported in the web.xml, so for example, instead of specifying localhost as the server name you could do the following:

'''xml ${server.name} '''

These can be supplied to Payara Micro when starting it as '-Dserver.name=localhost'. On our application, we’ll set server-name, database, user, and password. It allows to set it outside the code, thus it follows the third aspect in the Twelve Factor App.

12 Payara Platform and PaaS with Platform.sh

With the data source defined, we’ll create a'persistence.xml' file at'src/main/resources/ META-INF´. In JPA, the 'persistence.xml' file is the central piece of configuration on this application that we’ll use to make the relationship between the data source and the PersistenceUnit.

'''xml java:global/JPAExampleDataSource false '''

The Java Configuration is done, let’s move it to create our entity, let’s create a 'Fish' entity.

'''

import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;

@Entity public class Fish {

@Id @GeneratedValue(strategy = GenerationType.AUTO) private String id;

@Column private String name;

13 Payara Platform and PaaS with Platform.sh

//getter and setter }

'''

To integrate to an EntityManager, we’ll create a facade. The facade pattern is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex underlying or structural code.

'''

import java.util.List; import javax.persistence.EntityManager;

public abstract class AbstractFacade {

private Class entityClass;

public AbstractFacade(Class entityClass) { this.entityClass = entityClass; }

protected abstract EntityManager getEntityManager();

public void create(T entity) { getEntityManager().persist(entity); }

public void edit(T entity) { getEntityManager().merge(entity); }

public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); }

public T find(Object id) { return getEntityManager().find(entityClass, id); }

14 Payara Platform and PaaS with Platform.sh

public List findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager(). getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); }

} '''

The last class is the interaction with the rest-client, our resource. This 'FishResource' is where the client pings to create, update, delete and retrieve the fish which are in the PostgreSQL database. To point it out, we’re simplifying removing necessary layers such as DTO, and we are joining EBJ with JAX-RS that isn’t the best solution. It is for demo and not production-ready code.

''' import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; 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.MediaType; import java.util.List;

@Path("fishes") @Stateless @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class FishResource extends AbstractFacade {

@PersistenceContext(unitName = "JPADatasourceExamplePU") private EntityManager entityManager;

public FishResource() { super(Fish.class); }

15 Payara Platform and PaaS with Platform.sh

@Override protected EntityManager getEntityManager() { return entityManager; }

@POST @Override public void create(Fish entity) { super.create(entity); }

@PUT @Path("{id}") public void edit(@PathParam("id") String id, Fish entity) { super.edit(entity); }

@DELETE @Path("{id}") public void remove(@PathParam("id") String id) { super.remove(super.find(id)); }

@GET @Path("{id}") public Fish find(@PathParam("id") String id) { return super.find(id); }

@GET @Override public List findAll() { return super.findAll(); }

} '''

On the Java side, the configuration is ready to go. We need to create a PostgreSQL database instance, so we go to the '.platform/services.yaml' and append the database configuration.

16 Payara Platform and PaaS with Platform.sh

''' db: type: postgresql:11 disk: 512 '''

The last step is on the '.platform.app.yaml' to both grant access to the database and to set the database configuration on the startup of the application.

Platform.sh provides a series of variables by default. These inform an application about its runtime configuration. The most important of these is relationship information, which tells the application how to connect to databases and other services defined inservices.yaml . In this configuration, we’ll use the 'PLATFORM_RELATIONSHIPS' that is a base64-encoded JSON object whose keys are the relationship name and the values are arrays of relationship endpoint definitions. To extract the database configuration from the Platform.sh variable we’ll set the jq which is a lightweight and flexible command-line JSON processor.

''' name: app type: "java:8"

disk: 1024

hooks: build: | wget https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 mv jq-linux64 jq chmod +x jq mvn -DskipTests clean package payara-micro:bundle

relationships: database: "db:postgresql"

web: commands: start: | export HOST='echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|./jq -r ".database[0].host"' export PASSWORD='echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|./ jq -r ".database[0].password"'

17 Payara Platform and PaaS with Platform.sh

export USER='echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|./jq -r ".database[0].username"' export DATABASE='echo $PLATFORM_RELATIONSHIPS|base64 -d|json_pp|./ jq -r ".database[0].path"' java -jar -Xmx512m \ -Dserver.host=$HOST \ -Dserver.database=$DATABASE \ -Dserver.user=$USER \ -Dserver.password=$PASSWORD \ target/microprofile-microbundle.jar --port $PORT '''

Finally, the last step is to create a Platform.sh project and then either push the code to the private or synchronize to any GitHub repository.

Our Platform.sh Service Graph now looks different than it did previously. The virtual cluster still contains our Router and Java Application containers, but now a third service container for the PostgreSQL database instance has been added.

18 Payara Platform and PaaS with Platform.sh

''' curl -X POST -k -H 'Content-Type: application/json' -i '' --data '{"name": "Payara"}' '''

''' curl -X GET -k -i '' '''

8. Payara Platform with NoSQL

The NoSQL DB is a database that provides a mechanism for storage and retrieval of data, which is modeled by means other than the tabular relations used in relational databases. These databases have speed and high scalability. This kind of database is becoming more popular in several applica- tions, which include financial ones. As a result of the increase, the number of users and vendors is increasing too. In the Jakarta EE world, there is the Jakarta NoSQL.

We’ll create a similar rest application, but using MongoDB instead of relational database.

The first step is to create a new Java project, we can either create from a template or create from Maven archetype that we mentioned previously.

''' mvn archetype:generate -DarchetypeGroupId=sh.platform.archetype -DarchetypeArtifactId=payara -DarchetypeVersion=0.0.1 -DgroupId=my.compary -DartifactId=nosql -Dversion=0.0.1 -DinteractiveMode=false '''

Then, we need to Jakarta NoSQL and MongoDB driver as a dependency on maven dependency on pom.xml.

'''xml org.eclipse.jnosql.artemis artemis-document ${jnosql.version}

19 Payara Platform and PaaS with Platform.sh

org.eclipse.jnosql.diana mongodb-driver ${jnosql.version} '''

You can set the configuration and overwrite at startup time as we did on JPA. We also have the option to use the Platform.sh Java Configuration reader, which we can use to read from the environment and return a client, such as MongoDB Datasource.

''' import com.mongodb.MongoClient; import jakarta..document.DocumentCollectionManager; import org.eclipse.jnosql.diana.mongodb.document. MongoDBDocumentCollectionManagerFactory; import org.eclipse.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration; import sh.platform.config.Config; import sh.platform.config.MongoDB;

import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces;

@ApplicationScoped public class DocumentProducer {

@Produces @ApplicationScoped public DocumentCollectionManager getDocumentCollectionManager() { Config config = new Config(); final MongoDB mongo = config.getCredential("mongodb", MongoDB::new); final MongoClient mongoClient = mongo.get(); MongoDBDocumentConfiguration configuration = new MongoDBDocumentConfiguration(); MongoDBDocumentCollectionManagerFactory factory = configuration. get(mongoClient); return factory.get(mongo.getDatabase()); }

20 Payara Platform and PaaS with Platform.sh

public void close(@Disposes DocumentCollectionManager manager) { manager.close(); }

} '''

The Java Configuration is done, let’s move it to create our entity, let’s create a'Fish' entity.

''' import jakarta.nosql.mapping.Column; import jakarta.nosql.mapping.Convert; import jakarta.nosql.mapping.Entity;

import jakarta.nosql.mapping.Id; import java.util.Objects;

@Entity public class Fish {

@Id @Convert(ObjectIdConverter.class) private String id;

@Column private String name;

//getter and setter }

'''

To integrate into the MongoDB database, we have the repository interface. It creates smooth integra- tion between the Java application and the database, and we don’t need to worry about the queries Jakarta NoSQL will handle that for us.

21 Payara Platform and PaaS with Platform.sh

''' import jakarta.nosql.mapping.Repository;

import java.util.List;

public interface FishRepository extends Repository { List findAll(); } import jakarta.nosql.mapping.Repository;

import java.util.List;

public interface FishRepository extends Repository { List findAll(); }

'''

The last class is the interaction with the rest-client, our resource. This 'FishResource' is where the client pings to create, update, delete and retrieve the fish which are in the MongoDB database.

'''

import javax.inject.Inject; 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.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List;

@Path("fishes") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)

22 Payara Platform and PaaS with Platform.sh

public class FishResource {

@Inject private FishRepository repository;

@POST public void create(Fish entity) { repository.save(entity); }

@PUT @Path("{id}") public void edit(@PathParam("id") String id, Fish entity) { repository.save(entity); }

@DELETE @Path("{id}") public void remove(@PathParam("id") String id) { repository.deleteById(id); }

@GET @Path("{id}") public Fish find(@PathParam("id") String id) { return repository.findById(id) .orElseThrow(() -> new WebApplicationException(Response.Status.NOT_ FOUND)); }

@GET public List findAll() { return repository.findAll(); }

}

'''

23 Payara Platform and PaaS with Platform.sh

On the Java side, the configuration is ready to go, we need to create a MongoDB database instance, so we go to the 'services.yaml' and append the database configuration.

''' database: type: mongodb:3.6 disk: 1024 '''

The last step is on the '.platform.app.yaml' to both to grant access to the database by defining a relationship and to set the database configuration on the startup of the application.

''' name: app type: "java:8" disk: 1024 hooks: build: mvn -DskipTests clean package payara-micro:bundle relationships: mongodb: 'database:mongodb' web: commands: start: java -jar -Xmx512m target/microprofile-microbundle.jar --port $PORT

'''

24 Payara Platform and PaaS with Platform.sh

Our Platform.sh Service Graph now looks different than it did previously. The virtual cluster still contains our Router and Java Application containers, but now a third service container for the MongoDB database instance has been added.

Finally, the last step is to create a Platform.sh project and then either push the code to the private or synchronize to any GitHub repository.

''' curl -X POST -k -H 'Content-Type: application/json' -i '' --data '{"name": "Payara"}' '''

''' curl -X GET -k -i '' '''

25 Payara Platform and PaaS with Platform.sh

9. Payara Micro, Platform.sh, and Microservices

Microservices are a software architecture, where the systems are a collection of several independ- ent services. Each service has a specific business focus and communicates with the others with a language-agnostic protocol, such as REST. The Eclipse MicroProfile initiative optimizes Enterprise Java for the microservices architecture. It’s based on a subset of Jakarta EE .

In the end, every time that you deploy on Platform.sh is built as a virtual cluster, containing a set of containers. That allows you to create several applications on this cluster. A good point is that you can grant access to a database to a specific application and revoke to another. E.g., You can cre- ate several microservices, where each application is connected to a particular database and only exposes the client API.

''' yourproject/ .git/ .platform/ services.yaml routes.yaml service/ .platform.app.yaml service-b/ .platform.app.yaml service-c/ .platform.app.yaml client/ .platform.app.yaml

'''

26 Payara Platform and PaaS with Platform.sh

In the microservice configuration, the cluster now contains four Application containers and one shared Router container. Additionally, there are our three Service containers. The middle Application only has relationships defined to other Applications in the cluster, whereas the other apps have relationships to Service containers.

Eclipse MicroProfile has a bright future integrated with Jakarta EE to allow Java developers to create several application styles—like microservices and monoliths—that use either JPA or NoSQL. Besides that, these projects offer scalability and straightforward Java applications for your business thanks to Payara. Platform.sh delivers on the promise of a NoOps pipeline for your Java microservices.

Check out the source on this tutorial: https://github.com/platformsh-examples/payara-micro

27 Payara Platform and PaaS with Platform.sh

10. About Platform.sh

Our mission is to enable organizations to focus 100% of their time on building amazing experiences— and zero time managing infrastructure.

We take care of your infrastructure—from hosting and technology to global deployment and sup- port—so you’re free to explore new ideas. Ideas you can turn quickly into apps and experiences that customers everywhere love. And that can increase your organization’s revenue potential.

Nearly a decade ago, our founders began with a core belief: there’s a better, simpler way to develop and deploy code. That companies of any size should be able to deploy anytime, anywhere without breakage. That it’s possible to build cloud infrastructure that abstracts away complexities, but not power or flexibility. That vision became Platform.sh—now adopted by more than 62,000 developers and thousands of companies (and growing rapidly) around the world.

We have offices in Paris and San Francisco. But our distributed team reaches across 5 continents, 13 time zones, and 22 languages. What do we all have in common? Our mission (of course). And a passionate commitment to helping our customers succeed.    

28 Payara Platform and PaaS with Platform.sh

11. About Payara Services Limited

Payara Services is a global open source company and a recognized leader in the creation of innova- tive infrastructure software for today and tomorrow. We are proud to nurture and grow an open and collaborative community that builds on the needs of all to advance our software and services while providing support, stability, and security.

Our engaged team operates with the freedom and support to develop industry-leading products and services that enable our users to create world-class solutions across a diverse range of industries.

We help shape the future of the industry through our direct contributions to Jakarta EE and Eclipse MicroProfile® as Eclipse Foundation Solutions Members and members of the Project Management Committee.

Learn more about the Payara Platform and our services at Payara.fish    youtube-square

  

[email protected] +44 207 754 0481 www.payara.fish

Payara Services Ltd 2020 All Rights Reserved. Registered in England and Wales; Registration Number 09998946 Registered Office: Malvern Hills Science Park, Geraldine Road, Malvern, United Kingdom, WR14 3SZ

29