Skip to content

Commit

Permalink
FBHAJ-57 Initial commit to branch: Major enhancements
Browse files Browse the repository at this point in the history
- Utility class renamed
- Tabulation fixed in main class
- Version updates in pom.xml
- Examples updated
- New example app created for v0.9
  • Loading branch information
peter-szrnka committed Sep 14, 2024
1 parent 5f86c90 commit 9ba7bd5
Show file tree
Hide file tree
Showing 20 changed files with 194 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ buildNumber.properties
/examples/version_0.7/src/main/resources/service-account.json
/examples/version_0.8/.idea
examples/version_0.8/src/main/resources/service-account.json
.idea
15 changes: 13 additions & 2 deletions code/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<google-auth-library.version>1.20.0</google-auth-library.version>
<google-auth-library.version>1.23.0</google-auth-library.version>

<junit.jupiter.version>5.8.2</junit.jupiter.version>
<junit.platform.version>1.8.2</junit.platform.version>
Expand All @@ -25,7 +25,7 @@

<jackson-databind.version>2.14.0</jackson-databind.version>
<gson.version>2.8.9</gson.version>
<moshi.version>1.11.0</moshi.version>
<moshi.version>1.15.1</moshi.version>

<sonar.organization>peter-szrnka</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
Expand Down Expand Up @@ -85,6 +85,17 @@
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>${google-auth-library.version}</version>
<exclusions>
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.16.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import java.util.Set;
import java.util.stream.Collectors;

import static io.github.szrnkapeter.firebase.hosting.util.ConfigValidationUtils.preValidateConfig;
import static io.github.szrnkapeter.firebase.hosting.util.ConfigValidator.preValidateConfig;
import static io.github.szrnkapeter.firebase.hosting.util.FileUtils.generateFileListAndHash;
import static io.github.szrnkapeter.firebase.hosting.util.VersionUtils.getVersionId;
import static io.github.szrnkapeter.firebase.hosting.util.VersionUtils.getVersionName;
Expand All @@ -41,7 +41,6 @@
public class FirebaseHostingApiClient {

private final FirebaseHostingApiConfig config;

private final ReleaseService releaseService;
private final VersionService versionService;
private final FileService fileService;
Expand Down Expand Up @@ -95,14 +94,14 @@ protected FirebaseHostingApiClient(FirebaseHostingApiConfig firebaseRestApiConfi
public DeployResponse createDeploy(DeployRequest request) throws IOException, NoSuchAlgorithmException {
if(!request.isCleanDeploy()) {
GetReleasesResponse getReleases = getReleases();

if(getReleases == null || getReleases.getReleases() == null || getReleases.getReleases().isEmpty()) {
return null;
}

String versionId = getVersionId(getReleases.getReleases().get(0).getVersion().getName());
GetVersionFilesResponse getVersionFiles = getVersionFiles(versionId);

Set<String> newFileNames = request.getFiles().stream().map(DeployItem::getName).collect(Collectors.toSet());

for(FileDetails file : getVersionFiles.getFiles()) {
Expand Down Expand Up @@ -130,10 +129,10 @@ public DeployResponse createDeploy(DeployRequest request) throws IOException, No

// Finalize the new version
finalizeVersion(versionId);

// Create the release
Release newRelease = createRelease(versionId);

// Post delete earlier deployments
versionService.deletePreviousVersions(request, getReleases().getReleases());

Expand Down Expand Up @@ -237,7 +236,7 @@ public GetVersionFilesResponse getVersionFiles(String version) throws IOExceptio
public PopulateFilesResponse populateFiles(PopulateFilesRequest request, String version) throws IOException {
return fileService.populateFiles(request, version);
}

/**
* Uploads a file.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
* @author Peter Szrnka
* @since 0.8
*/
public class ConfigValidationUtils {
public class ConfigValidator {

private ConfigValidationUtils() {}
private ConfigValidator() {}

/**
* Pre-validation is essential to check the input configuration and avoid any unwanted issues.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ public static String getSHA256Checksum(byte[] fileContent) throws NoSuchAlgorith


StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & XFF) + X_100, 16).substring(1));
}
for (byte aByte : bytes) {
sb.append(Integer.toString((aByte & XFF) + X_100, 16).substring(1));
}

return sb.toString();
}
Expand Down Expand Up @@ -109,19 +109,19 @@ public static byte[] compressAndReadFile(byte[] fileContent) throws IOException
*/
public static byte[] getRemoteFile(String urlString) throws IOException {
URL url = new URL(urlString);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (InputStream is = url.openStream()) {
byte[] byteChunk = new byte[STREAM_BUFFER_SIZE]; // Or whatever size you want to read in at a time.
int n;

while ((n = is.read(byteChunk)) > 0) {
baos.write(byteChunk, 0, n);
outputStream.write(byteChunk, 0, n);
}
} catch (IOException e) {
logger.warning(String.format("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage()));
// Perform any other exception handling that's appropriate.
}

return baos.toByteArray();
return outputStream.toByteArray();
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package io.github.szrnkapeter.firebase.hosting.util;

import java.util.Arrays;

import com.google.auth.oauth2.GoogleCredentials;

import io.github.szrnkapeter.firebase.hosting.config.FirebaseHostingApiConfig;

import java.util.List;

/**
* Google credential helper class.
*
Expand All @@ -27,7 +26,7 @@ private GoogleCredentialUtils() {
*/
public static String getAccessToken(FirebaseHostingApiConfig config) {
try {
GoogleCredentials googleCredential = GoogleCredentials.fromStream(config.getServiceAccountFileStream()).createScoped(Arrays.asList(FIREBASE_DEFAULT_SCOPE));
GoogleCredentials googleCredential = GoogleCredentials.fromStream(config.getServiceAccountFileStream()).createScoped(List.of(FIREBASE_DEFAULT_SCOPE));
googleCredential.refreshIfExpired();
return googleCredential.getAccessToken().getTokenValue();
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import io.github.szrnkapeter.firebase.hosting.service.FileService;
import io.github.szrnkapeter.firebase.hosting.service.ReleaseService;
import io.github.szrnkapeter.firebase.hosting.service.VersionService;
import io.github.szrnkapeter.firebase.hosting.util.ConfigValidationUtils;
import io.github.szrnkapeter.firebase.hosting.util.ConfigValidator;
import io.github.szrnkapeter.firebase.hosting.util.FileUtils;
import io.github.szrnkapeter.firebase.hosting.util.GoogleCredentialUtils;
import io.github.szrnkapeter.firebase.hosting.util.VersionUtils;
Expand Down Expand Up @@ -69,7 +69,7 @@ void shouldCreateWithStaticMethod() {
setup();

try (MockedStatic<GoogleCredentialUtils> mockedGoogleCredentialUtils = mockStatic(GoogleCredentialUtils.class);
MockedStatic<ConfigValidationUtils> mockedConfigValidationUtil = mockStatic(ConfigValidationUtils.class)) {
MockedStatic<ConfigValidator> mockedConfigValidationUtil = mockStatic(ConfigValidator.class)) {
// arrange
mockedGoogleCredentialUtils.when(() -> GoogleCredentialUtils.getAccessToken(any(FirebaseHostingApiConfig.class))).thenReturn(ACCESS_TOKEN);

Expand All @@ -79,7 +79,7 @@ void shouldCreateWithStaticMethod() {
// assert
assertNotNull(response);
mockedGoogleCredentialUtils.verify(() -> GoogleCredentialUtils.getAccessToken(any(FirebaseHostingApiConfig.class)));
mockedConfigValidationUtil.verify(() -> ConfigValidationUtils.preValidateConfig(config));
mockedConfigValidationUtil.verify(() -> ConfigValidator.preValidateConfig(config));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,16 @@
* @author Peter Szrnka
* @since 0.8
*/
class ConfigValidationUtilsTest {
class ConfigValidatorTest {

@Test
void testPrivateConstructor() {
assertDoesNotThrow(() -> TestUtils.testPrivateConstructor(ConfigValidationUtilsTest.class));
assertDoesNotThrow(() -> TestUtils.testPrivateConstructor(ConfigValidatorTest.class));
}

@Test
@SneakyThrows
void shouldThrowErrorWhenConfigIsMissing() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidationUtils.preValidateConfig(null));
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidator.preValidateConfig(null));
assertEquals("FirebaseRestApiConfig is mandatory!", exception.getMessage());
}

Expand All @@ -35,7 +34,7 @@ void shouldThrowErrorWhenSiteIdIsMissing() {
config.setSiteId(null);

// act & assert
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidationUtils.preValidateConfig(config));
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidator.preValidateConfig(config));
assertEquals("Site ID is mandatory!", exception.getMessage());
}

Expand All @@ -48,7 +47,7 @@ void shouldThrowErrorWhenServiceAccountFileStreamIsMissing() {
config.setServiceAccountFileStream(null);

// act & assert
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidationUtils.preValidateConfig(config));
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidator.preValidateConfig(config));
assertEquals("Service account file stream is missing from the configuration!", exception.getMessage());
}

Expand All @@ -60,7 +59,7 @@ void shouldThrowErrorWhenSerializerIsMissing() {
config.setSerializer(null);

// act & assert
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidationUtils.preValidateConfig(config));
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> ConfigValidator.preValidateConfig(config));
assertEquals("Serializer is missing from the configuration!", exception.getMessage());
}

Expand All @@ -71,6 +70,6 @@ void shouldNotThrowError() {
FirebaseHostingApiConfig config = getFirebaseRestApiConfig();

// act & assert
assertDoesNotThrow(() -> ConfigValidationUtils.preValidateConfig(config));
assertDoesNotThrow(() -> ConfigValidator.preValidateConfig(config));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ public <T> void getResponse(String function, T response) {
}
})*/
// You have to define a site ID here -> will be renamed to withSiteId() in v0.7
.withSiteName("fir-hosting-api-java-test")
.build();
.withSiteName(System.getenv("FIREBASE_SITE_ID"))
.build();
FirebaseHostingApiClient client = new FirebaseHostingApiClient(firebaseRestApiConfig);

DeployRequest deployRequest = new DeployRequest();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public <T> void getResponse(String function, T response) {
System.out.println(function + " / " + response);
}
})*/
.withSiteId("hosting-api-java-test")
.withSiteId(System.getenv("FIREBASE_SITE_ID"))
.build();
FirebaseHostingApiClient client = new FirebaseHostingApiClient(firebaseRestApiConfig);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import java.util.Set;

/**
* Sample usage with v0.8-SNAPSHOT
* Sample usage with v0.8
*/
public class Main {

Expand All @@ -35,7 +35,7 @@ public <T> void getResponse(String function, T response) {
System.out.println(function + " / " + response);
}
})*/
.withSiteId("hosting-api-java-test")
.withSiteId(System.getenv("FIREBASE_SITE_ID"))
.build();
FirebaseHostingApiClient client = FirebaseHostingApiClient.newClient(firebaseRestApiConfig);

Expand Down
26 changes: 26 additions & 0 deletions examples/version_0.9/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# firebase-hosting-api-java v0.9 example
This is a working example of **firebase-hosting-api-java** library with unreleased version **0.9-SNAPSHOT**.

**Firebase setup: [link](https://github.com/peter-szrnka/firebase-hosting-api-java/wiki/Firebase-project-setup)**

**IMPORTANT:**

- You have to add a *"service-account.json"* file under *src/main/resources* folder!
- You will not see anything if you do not set any listener!
- Library does not catch all exceptions. The purpose of this approach is to give the control to your application instead of hiding and wrapping it.

# Sample log messages

## Missing service account file:
![missing_service_account_file.png](assets/missing_service_account_file.png)

## Invalid service account file:
![invalid_service_account_file.png](assets/invalid_service_account_file.png)

## With HTTP response listeners

![Example 1](assets/log_example.png)

## With HTTP and Service response listeners

![Example 2](assets/log_example2.png)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/version_0.9/assets/log_example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/version_0.9/assets/log_example2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 41 additions & 0 deletions examples/version_0.9/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>hu.szrnkapeter.sample</groupId>
<artifactId>firebase-hosting-api-java-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<java.version>17</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencies>
<dependency>
<groupId>io.github.szrnka-peter</groupId>
<artifactId>firebase-hosting-api-java</artifactId>
<version>0.9-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package hu.szrnkapeter.sample;

import com.google.gson.Gson;

import io.github.szrnkapeter.firebase.hosting.serializer.Serializer;

public class GsonSerializer implements Serializer {

private final Gson gson;

public GsonSerializer() {
gson = new Gson();
}

/*
* (non-Javadoc)
* @see hu.szrnkapeter.firebase.hosting.serializer.Serializer#getObject(java.lang.Class, java.lang.String)
*/
@Override
public <T> T getObject(Class<T> clazz, String obj) {
return gson.fromJson(obj, clazz);
}

/*
* (non-Javadoc)
* @see io.github.szrnkapeter.firebase.hosting.serializer.Serializer#toJson(java.lang.Class, java.lang.Object)
*/
@Override
public <T> String toJson(Class<T> clazz, T obj) {
return gson.toJson(obj);
}
}
Loading

0 comments on commit 9ba7bd5

Please sign in to comment.