Java
Contents:
Java is a general-purpose programming language, and one of the most popular in the world today. Platform.sh supports Java runtimes that can be used with build management tools such as Gradle, Maven, and Ant.
Supported versions
OpenJDK versions:
Grid | Dedicated |
---|---|
|
None available |
To specify a Java container, use the type
property in your .platform.app.yaml
.
type: 'java:13'
Support libraries
While it is possible to read the environment directly from your application, it is generally easier and more robust to use the platformsh/config-reader
which handles decoding of service credential information for you.
Support build automation
Platform.sh supports the most common project management tools in the Java ecosystem, including:
Other JVM languages
It’s worth remembering that the JVM by its specification does not read Java code, but bytecode. So within the JVM, it’s possible to run several languages. Platform.sh supports several of them, such as Kotlin, Groovy, and Scala, so long as that language works with any build automation that Platform.sh supports.
Article | Link |
---|---|
Kotlin and Spring | Source |
Scala and Spring | Source |
Groovy and Spring | Source |
Accessing services
To access various services with Java, see the following examples. The individual service pages have more information on configuring each service.
package sh.platform.languages.sample;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import sh.platform.config.Config;
import sh.platform.config.Elasticsearch;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static java.util.concurrent.ThreadLocalRandom.current;
public class ElasticsearchSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
Elasticsearch elasticsearch = config.getCredential("elasticsearch", Elasticsearch::new);
// Create an Elasticsearch client object.
RestHighLevelClient client = elasticsearch.get();
try {
String index = "animals";
String type = "mammals";
// Index a few document.
final List<String> animals = Arrays.asList("dog", "cat", "monkey", "horse");
for (String animal : animals) {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", animal);
jsonMap.put("age", current().nextInt(1, 10));
jsonMap.put("is_cute", current().nextBoolean());
IndexRequest indexRequest = new IndexRequest(index, type)
.id(animal).source(jsonMap);
client.index(indexRequest, RequestOptions.DEFAULT);
}
RefreshRequest refresh = new RefreshRequest(index);
// Force just-added items to be indexed
RefreshResponse refreshResponse = client.indices().refresh(refresh, RequestOptions.DEFAULT);
// Search for documents.
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("name", "dog"));
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
searchRequest.source(sourceBuilder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits()) {
String id = hit.getId();
final Map<String, Object> source = hit.getSourceAsMap();
logger.append(String.format("result id %s source: %s", id, source)).append('\n');
}
// Delete documents.
for (String animal : animals) {
client.delete(new DeleteRequest(index, type, animal), RequestOptions.DEFAULT);
}
} catch (IOException exp) {
throw new RuntimeException("An error when execute Elasticsearch: " + exp.getMessage());
}
return logger.toString();
}
}
package sh.platform.languages.sample;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import sh.platform.config.Config;
import sh.platform.config.Kafka;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class KafkaSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
try {
// Get the credentials to connect to the Kafka service.
final Kafka kafka = config.getCredential("kafka", Kafka::new);
Map<String, Object> configProducer = new HashMap<>();
configProducer.putIfAbsent(ProducerConfig.CLIENT_ID_CONFIG, "animals");
final Producer<Long, String> producer = kafka.getProducer(configProducer);
// Sending data into the stream.
RecordMetadata metadata = producer.send(new ProducerRecord<>("animals", "lion")).get();
logger.append("Record sent with to partition ").append(metadata.partition())
.append(" with offset ").append(metadata.offset()).append('\n');
metadata = producer.send(new ProducerRecord<>("animals", "dog")).get();
logger.append("Record sent with to partition ").append(metadata.partition())
.append(" with offset ").append(metadata.offset()).append('\n');
metadata = producer.send(new ProducerRecord<>("animals", "cat")).get();
logger.append("Record sent with to partition ").append(metadata.partition())
.append(" with offset ").append(metadata.offset()).append('\n');
// Consumer, read data from the stream.
final HashMap<String, Object> configConsumer = new HashMap<>();
configConsumer.put(ConsumerConfig.GROUP_ID_CONFIG, "consumerGroup1");
configConsumer.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
Consumer<Long, String> consumer = kafka.getConsumer(configConsumer, "animals");
ConsumerRecords<Long, String> consumerRecords = consumer.poll(Duration.ofSeconds(3));
// Print each record.
consumerRecords.forEach(record -> {
logger.append("Record: Key " + record.key());
logger.append(" value " + record.value());
logger.append(" partition " + record.partition());
logger.append(" offset " + record.offset()).append('\n');
});
// Commits the offset of record to broker.
consumer.commitSync();
return logger.toString();
} catch (Exception exp) {
throw new RuntimeException("An error when execute Kafka", exp);
}
}
}
package sh.platform.languages.sample;
import net.spy.memcached.MemcachedClient;
import sh.platform.config.Config;
import java.util.function.Supplier;
import sh.platform.config.Memcached;
public class MemcachedSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
// Get the credentials to connect to the Memcached service.
Memcached memcached = config.getCredential("memcached", Memcached::new);
final MemcachedClient client = memcached.get();
String key = "cloud";
String value = "platformsh";
// Set a value.
client.set(key, 0, value);
// Read it back.
Object test = client.get(key);
logger.append(String.format("Found value %s for key %s.", test, key));
return logger.toString();
}
}
package sh.platform.languages.sample;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import sh.platform.config.Config;
import sh.platform.config.MongoDB;
import java.util.function.Supplier;
import static com.mongodb.client.model.Filters.eq;
public class MongoDBSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
// The 'database' relationship is generally the name of primary database of an application.
// It could be anything, though, as in the case here here where it's called "mongodb".
MongoDB database = config.getCredential("mongodb", MongoDB::new);
MongoClient mongoClient = database.get();
final MongoDatabase mongoDatabase = mongoClient.getDatabase(database.getDatabase());
MongoCollection<Document> collection = mongoDatabase.getCollection("scientist");
Document doc = new Document("name", "Ada Lovelace")
.append("city", "London");
collection.insertOne(doc);
Document myDoc = collection.find(eq("_id", doc.get("_id"))).first();
logger.append(myDoc.toJson()).append('\n');
logger.append(collection.deleteOne(eq("_id", doc.get("_id"))));
return logger.toString();
}
}
package sh.platform.languages.sample;
import sh.platform.config.Config;
import sh.platform.config.MySQL;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.Supplier;
public class MySQLSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
// The 'database' relationship is generally the name of primary SQL database of an application.
// That's not required, but much of our default automation code assumes it.
MySQL database = config.getCredential("database", MySQL::new);
DataSource dataSource = database.get();
// Connect to the database
try (Connection connection = dataSource.getConnection()) {
// Creating a table.
String sql = "CREATE TABLE JAVA_PEOPLE (" +
" id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY," +
"name VARCHAR(30) NOT NULL," +
"city VARCHAR(30) NOT NULL)";
final Statement statement = connection.createStatement();
statement.execute(sql);
// Insert data.
sql = "INSERT INTO JAVA_PEOPLE (name, city) VALUES" +
"('Neil Armstrong', 'Moon')," +
"('Buzz Aldrin', 'Glen Ridge')," +
"('Sally Ride', 'La Jolla')";
statement.execute(sql);
// Show table.
sql = "SELECT * FROM JAVA_PEOPLE";
final ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String city = resultSet.getString("city");
logger.append(String.format("the JAVA_PEOPLE id %d the name %s and city %s", id, name, city));
logger.append('\n');
}
statement.execute("DROP TABLE JAVA_PEOPLE");
return logger.toString();
} catch (SQLException exp) {
throw new RuntimeException("An error when execute MySQL", exp);
}
}
}
package sh.platform.languages.sample;
import sh.platform.config.Config;
import sh.platform.config.MySQL;
import sh.platform.config.PostgreSQL;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.function.Supplier;
public class PostgreSQLSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
// The 'database' relationship is generally the name of primary SQL database of an application.
// It could be anything, though, as in the case here here where it's called "postgresql".
PostgreSQL database = config.getCredential("postgresql", PostgreSQL::new);
DataSource dataSource = database.get();
// Connect to the database
try (Connection connection = dataSource.getConnection()) {
// Creating a table.
String sql = "CREATE TABLE JAVA_FRAMEWORKS (" +
" id SERIAL PRIMARY KEY," +
"name VARCHAR(30) NOT NULL)";
final Statement statement = connection.createStatement();
statement.execute(sql);
// Insert data.
sql = "INSERT INTO JAVA_FRAMEWORKS (name) VALUES" +
"('Spring')," +
"('Jakarta EE')," +
"('Eclipse JNoSQL')";
statement.execute(sql);
// Show table.
sql = "SELECT * FROM JAVA_FRAMEWORKS";
final ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
logger.append(String.format("the JAVA_FRAMEWORKS id %d the name %s ", id, name));
logger.append('\n');
}
statement.execute("DROP TABLE JAVA_FRAMEWORKS");
return logger.toString();
} catch (SQLException exp) {
throw new RuntimeException("An error when execute PostgreSQL", exp);
}
}
}
package sh.platform.languages.sample;
import sh.platform.config.Config;
import sh.platform.config.RabbitMQ;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.function.Supplier;
public class RabbitMQSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
try {
// Get the credentials to connect to the RabbitMQ service.
final RabbitMQ credential = config.getCredential("rabbitmq", RabbitMQ::new);
final ConnectionFactory connectionFactory = credential.get();
// Connect to the RabbitMQ server.
final Connection connection = connectionFactory.createConnection();
connection.start();
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("cloud");
MessageConsumer consumer = session.createConsumer(queue);
// Sending a message into the queue.
TextMessage textMessage = session.createTextMessage("Platform.sh");
textMessage.setJMSReplyTo(queue);
MessageProducer producer = session.createProducer(queue);
producer.send(textMessage);
// Receive the message.
TextMessage replyMsg = (TextMessage) consumer.receive(100);
logger.append("Message: ").append(replyMsg.getText());
// close connections.
producer.close();
consumer.close();
session.close();
connection.close();
return logger.toString();
} catch (Exception exp) {
throw new RuntimeException("An error when execute RabbitMQ", exp);
}
}
}
package sh.platform.languages.sample;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import sh.platform.config.Config;
import sh.platform.config.Redis;
import java.util.Set;
import java.util.function.Supplier;
public class RedisSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
// The 'database' relationship is generally the name of primary database of an application.
// It could be anything, though, as in the case here here where it's called "redis".
Redis database = config.getCredential("redis", Redis::new);
JedisPool dataSource = database.get();
// Get a Redis Client
final Jedis jedis = dataSource.getResource();
// Set a values
jedis.sadd("cities", "Salvador");
jedis.sadd("cities", "London");
jedis.sadd("cities", "São Paulo");
// Read it back.
Set<String> cities = jedis.smembers("cities");
logger.append("cities: " + cities);
jedis.del("cities");
return logger.toString();
}
}
package sh.platform.languages.sample;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import sh.platform.config.Config;
import sh.platform.config.Solr;
import java.io.IOException;
import java.util.function.Supplier;
public class SolrSample implements Supplier<String> {
@Override
public String get() {
StringBuilder logger = new StringBuilder();
// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
Config config = new Config();
Solr solr = config.getCredential("solr", Solr::new);
try {
final HttpSolrClient solrClient = solr.get();
solrClient.setParser(new XMLResponseParser());
// Add a document
SolrInputDocument document = new SolrInputDocument();
final String id = "123456";
document.addField("id", id);
document.addField("name", "Ada Lovelace");
document.addField("city", "London");
solrClient.add(document);
final UpdateResponse response = solrClient.commit();
logger.append("Adding one document. Status (0 is success): ")
.append(response.getStatus()).append('\n');
SolrQuery query = new SolrQuery();
query.set("q", "city:London");
QueryResponse queryResponse = solrClient.query(query);
SolrDocumentList results = queryResponse.getResults();
logger.append(String.format("Selecting documents (1 expected): %d \n", results.getNumFound()));
// Delete one document
solrClient.deleteById(id);
logger.append(String.format("Deleting one document. Status (0 is success): %s \n",
solrClient.commit().getStatus()));
} catch (SolrServerException | IOException exp) {
throw new RuntimeException("An error when execute Solr ", exp);
}
return logger.toString();
}
}
Note:
These samples use the Configuration Reader library that Platform.sh provides. However, if your favorite Java frameworks allow you to overwrite the configurations following The Twelve-Factor App (such as Spring, Micronaut, Quarkus, Jakarta EE/MicroProfile), then as a developer you have the option to not use the library, removing the need for an additional dependency.
Project templates
A number of project templates for major Java applications are available on GitHub. Not all of them are proactively maintained but all can be used as a starting point or reference for building your own website or web application.
Apache Tomcat
This project provides a starter kit for Apache Tomcat hosted on Platform.sh. Tomcat itself is downloaded on the fly in the build hook based on the provided `pom.xml` file.
Apache Tomcat is an open-source implementation of the Java Servlet, JavaServer Pages, Java Expression Language and WebSocket technologies.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.
Apache TomEE
This project provides a starter kit for Apache TomEE Eclipse MicroProfile projects hosted on Platform.sh. It includes a minimalist application skeleton that is intended for you to use as a starting point and modify for your own needs, along with the Platform.sh Config Reader to simplify accessing Platform.sh environment variables.
Apache TomEE is the Eclipse MicroProfile implementation that uses several Apache Project flavors such as Apache Tomcat, Apache OpenWebBeans and so on.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.
Helidon
This project provides a starter kit for Helidon Eclipse MicroProfile projects hosted on Platform.sh. It includes a minimalist application skeleton that is intended for you to use as a starting point and modify for your own needs, along with the Platform.sh Config Reader to simplify accessing Platform.sh environment variables.
Helidon is a collection of Java libraries for writing microservices that run on a fast web core powered by Netty.
Helidon is designed to be simple to use, with tooling and examples to get you going quickly. Since Helidon is just a collection of libraries running on a fast Netty core, there is no extra overhead or bloat.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.
Jenkins
This project provides a starter kit for Jenkins projects hosted on Platform.sh. The Jenkins `.war` file is downloaded during the build hook and not included in the repository.
Jenkins is an open source automation server written in Java. Jenkins helps to automate the non-human part of the software development process, with continuous integration and facilitating technical aspects of continuous delivery.
Features:
- Java 11
- Automatic TLS certificates
- Jenkins downloaded on the fly during build
View the repository on GitHub.
Jetty
This template provides an Eclipse Jetty Web server and javax.servlet container, plus support for HTTP/2, WebSocket, OSGi, JMX, JNDI, JAAS and many other integrations. Jetty itself is downloaded on the fly in the build hook based on the provided `pom.xml` file.
Eclipse Jetty is used in a wide variety of projects and products, both in development and production. Jetty can be easily embedded in devices, tools, frameworks, application servers, and clusters.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.
KumuluzEE
This project provides a starter kit for KumuluzEE Eclipse MicroProfile projects hosted on Platform.sh. It includes a minimalist application skeleton that is intended for you to use as a starting point and modify for your own needs, along with the Platform.sh Config Reader to simplify accessing Platform.sh environment variables.
KumuluzEE is a lightweight framework for developing microservices using standard Java, Java EE / Jakarta EE technologies and migrating existing Java applications to microservices. KumuluzEE packages microservices as standalone JARs. KumuluzEE microservices are lightweight and optimized for size and start-up time.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.
Micronaut
This project provides a starter kit for Micronaut projects hosted on Platform.sh. It includes a minimalist application skeleton that is intended for you to use as a starting point and modify for your own needs, along with the Platform.sh Config Reader to simplify accessing Platform.sh environment variables.
Micronaut is a modern, JVM-based, full-stack framework for building modular, easily testable microservice and serverless applications.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.
Open Liberty
This project provides a starter kit for Open Liberty Eclipse MicroProfile projects hosted on Platform.sh. It includes a minimalist application skeleton that is intended for you to use as a starting point and modify for your own needs, along with the Platform.sh Config Reader to simplify accessing Platform.sh environment variables.
Open Liberty is a highly composable, fast to start, dynamic application server runtime environment.
Features:
- Java 11
- Automatic TLS certificates
- Maven-based build
View the repository on GitHub.