Tuesday, December 29, 2020

Create deployment to Firebase Hosting with Java

In this article I'd like to introduce "firebase-hosting-api-java", which is an API library for Firebase Hosting REST API written in Java 8. It supports all available V1Beta1 services, such as query the releases, delete deployment versions and so on. From version 0.4, theres a common service called createDeploy(), which is a combination of all deployment related function, and this is the recommended function for deployment.

Maven setup

First step is to create a new Maven project in your preferred IDE. Open your pom.xml and add the following lines into <dependencies></dependencies> tag:

<dependency>

<groupId>io.github.szrnka-peter</groupId>

<artifactId>firebase-hosting-api-java</artifactId>

<version>0.4</version>

</dependency>


This'll downloads the library into your local repository.

Firebase setup

A service account holder JSON file is required as well, so open your project in Firebase Console, and open:

Settings -> Project Settings -> Service Accounts -> Firebase Admin SDK

and press "Generate new Private key" button


A download popup will be available, and you can save the generated JSON file.

Copy this file into the root folder of your project, or wherever you want.

Configuration

Create a main() function, and copy the following lines into this method:

        FirebaseHostingApiConfig config = FirebaseHostingApiConfigBuilder.builder()
.withConfigStream(new FileInputStream("firebase-adminsdk.json"))
.build();
FirebaseHostingApiClient client = new FirebaseHostingApiClient(config);


Deploy example

This creates a new Firebase Hosting API client instance. Next, add a sample file called test0.txt into the root folder of your sample project.

Add the following lines into the main() method after the configuration:

        DeployRequest request = new DeployRequest();
        request.setCleanDeploy(false);
        DeployItem di1 = new DeployItem();
        di1.setName("test0.txt");
        di1.setContent(Files.readAllBytes(new File("test0.txt").toPath()));
        Set<DeployItem> fileList = new HashSet<>();
        fileList.add(di1);
        request.setFiles(fileList);
        client.createDeploy(request);

These lines of code will call the following Firebase Hosting Rest API functions:

- createVersion

- populateFiles

- uploadFile

- finalizeVersion

- createRelease

If everything goes fine, this'll creates a new deployment, and you can check it in your Firebase Console.

Configure and use VSCode for Java web development

Embarking on Java web development often starts with choosing the right tools that streamline the coding process while enhancing productivity...