Java

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:

  • 8
  • 11
  • 12

To select a Java version, specify a type such as java:11:

# .platform.app.yaml
type: "java:11"

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:

Accessing services

To access various services with Java, see the following examples. The individual service pages have more information on configuring each service.

MongoDB
MySQL
PostgreSQL
Redis
Memcached
Elasticsearch
Solr
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.getMessage());
        }
    }
}
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.getMessage());
        }
    }
}
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 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 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.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.getMessage());
        }

        return logger.toString();
    }
}

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.

Applications

Maven Spring