Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Java] Move storage init to init and get event queue for tests #72

Merged
merged 9 commits into from
Sep 22, 2023
25 changes: 8 additions & 17 deletions sdk-java/src/main/java/ly/count/sdk/java/internal/SDKStorage.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package ly.count.sdk.java.internal;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileLock;
Expand All @@ -21,11 +19,9 @@ public class SDKStorage {

private Log L;
private CtxCore ctx;

private static final String FILE_NAME_PREFIX = "[CLY]";
private static final String FILE_NAME_SEPARATOR = "_";

private static final String EVENT_QUEUE_FILE_NAME = "event_queue";
protected static final String FILE_NAME_PREFIX = "[CLY]";
protected static final String FILE_NAME_SEPARATOR = "_";
protected static final String EVENT_QUEUE_FILE_NAME = "event_queue";

protected SDKStorage() {

Expand All @@ -34,6 +30,7 @@ protected SDKStorage() {
public void init(CtxCore ctx, Log logger) {
this.L = logger;
this.ctx = ctx;
Storage.init();
}

public void stop(ly.count.sdk.java.internal.CtxCore ctx, boolean clear) {
Expand Down Expand Up @@ -302,21 +299,15 @@ protected String readEventQueue() {
L.d("[SDKStorage] Getting event queue");
File file = new File(ctx.getContext(), FILE_NAME_PREFIX + FILE_NAME_SEPARATOR + EVENT_QUEUE_FILE_NAME);

if (!file.exists()) {
return "";
}
String eventQueue = "";

StringBuilder eventQueue = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
eventQueue.append(line);
}
try {
eventQueue = Utils.readFileContent(file, L);
} catch (IOException e) {
// Handle the error if reading fails
L.e("[SDKStorage] Failed to read EQ from json file: " + e);
}

return eventQueue.toString();
return eventQueue;
}
}
12 changes: 8 additions & 4 deletions sdk-java/src/main/java/ly/count/sdk/java/internal/Storage.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package ly.count.sdk.java.internal;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
Expand All @@ -15,7 +13,11 @@

public class Storage {

private static final Tasks tasks = new Tasks("storage", null);
private static Tasks tasks;
ArtursKadikis marked this conversation as resolved.
Show resolved Hide resolved

static void init() {
tasks = new Tasks("storage", null);
}

public static String name(Storable storable) {
return storable.storagePrefix() + "_" + storable.storageId();
Expand Down Expand Up @@ -362,6 +364,8 @@ public Boolean call() throws Exception {
}

public static void stop() {
tasks.shutdown();
if (tasks != null) {
tasks.shutdown();
}
}
}
37 changes: 36 additions & 1 deletion sdk-java/src/main/java/ly/count/sdk/java/internal/Utils.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package ly.count.sdk.java.internal;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
Expand All @@ -16,7 +19,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* Utility class
Expand Down Expand Up @@ -291,6 +293,39 @@ public static boolean isValidDataType(Object value) {
value instanceof Float;
}

/**
* Read file content using UTF-8 encoding into a string and
* append lines to a "StringBuilder" and return it
* If file doesn't exist, return empty string
*
* @param file to read
* @param logger to log errors
* @return file contents or empty string
* @throws IOException if file exists but couldn't be read
*/
public static String readFileContent(File file, Log logger) throws IOException {
StringBuilder fileContent = new StringBuilder();

if (!file.exists()) {
logger.v("[Utils] readFileContent : File doesn't exist: " + file.getAbsolutePath() + ". returning empty string");
return fileContent.toString();
}

if (!file.canRead()) {
logger.v("[Utils] readFileContent : File exists but can't be read: " + file.getAbsolutePath() + ". returning empty string");
return fileContent.toString();
}

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
fileContent.append(line);
}
}

return fileContent.toString();
}

public static class Base64 {
public static String encode(byte[] bytes) {
return ly.count.sdk.java.internal.Base64.encodeBytes(bytes);
Expand Down
65 changes: 60 additions & 5 deletions sdk-java/src/test/java/ly/count/sdk/java/internal/TestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,24 @@

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Stream;

import static ly.count.sdk.java.internal.SDKStorage.EVENT_QUEUE_FILE_NAME;
import static ly.count.sdk.java.internal.SDKStorage.FILE_NAME_PREFIX;
import static ly.count.sdk.java.internal.SDKStorage.FILE_NAME_SEPARATOR;

public class TestUtils {

public TestUtils() {
private static String DELIMETER = ":::";

private TestUtils() {
}

/**
Expand All @@ -20,7 +29,7 @@ public TestUtils() {
* @param logger logger
* @return array of request params
*/
public Map<String, String>[] getCurrentRequestQueue(File targetFolder, Log logger) {
protected static Map<String, String>[] getCurrentRequestQueue(File targetFolder, Log logger) {

//check whether target folder is a directory or not
if (!targetFolder.isDirectory()) {
Expand Down Expand Up @@ -48,13 +57,59 @@ public Map<String, String>[] getCurrentRequestQueue(File targetFolder, Log logge
return resultMapArray;
}

/**
* Get current event queue from target folder
*
* @param targetFolder where events are stored
* @param logger logger
* @return array of json events
*/
protected static List<EventImpl> getCurrentEventQueue(File targetFolder, Log logger) {
List<EventImpl> events = new ArrayList<>();

if (!targetFolder.isDirectory()) {
logger.e("[TestUtils] " + targetFolder.getAbsolutePath() + " is not a directory");
return events;
}

File file = new File(targetFolder, FILE_NAME_PREFIX + FILE_NAME_SEPARATOR + EVENT_QUEUE_FILE_NAME);
String fileContent = "";
try {
fileContent = Utils.readFileContent(file, logger);
} catch (IOException e) {
//do nothing
}

//EventImplQueue.DELIMITER
Arrays.stream(fileContent.split(DELIMETER)).forEach(s -> {
final EventImpl event = EventImpl.fromJSON(s, (ev) -> {
}, logger);
if (event != null) {
events.add(event);
}
});

return events;
}

/**
* Get last item from list
*
* @param list
* @param <T> type of list
* @return last item from list
*/
public static <T> T getLastItem(List<T> list) {
return list.isEmpty() ? null : list.get(list.size() - 1);
}

/**
* Get request files from target folder, sorted by last modified
*
* @param targetFolder folder where requests are stored
* @return array of request files sorted by last modified
*/
private File[] getRequestFiles(File targetFolder) {
private static File[] getRequestFiles(File targetFolder) {

File[] files = targetFolder.listFiles();
if (files == null) {
Expand All @@ -76,7 +131,7 @@ private File[] getRequestFiles(File targetFolder) {
* @return map of request params
* @throws IOException if file cannot be read
*/
private Map<String, String> parseRequestParams(File file) throws IOException {
private static Map<String, String> parseRequestParams(File file) throws IOException {
try (Scanner scanner = new Scanner(file)) {
String firstLine = scanner.nextLine();
String urlDecodedStr = Utils.urldecode(firstLine);
Expand All @@ -96,4 +151,4 @@ private Map<String, String> parseRequestParams(File file) throws IOException {
return paramMap;
}
}
}
}
69 changes: 69 additions & 0 deletions sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsTests.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package ly.count.sdk.java.internal;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
Expand All @@ -18,6 +21,8 @@ public class UtilsTests {

Log logger;

static final String TEST_FILE_NAME = "testFile";

@Before
public void setupEveryTest() {
logger = new Log(Config.LoggingLevel.VERBOSE, null);
Expand Down Expand Up @@ -234,4 +239,68 @@ public void isValidDataType() {
Assert.assertFalse(Utils.isValidDataType(new ArrayList<>()));
Assert.assertFalse(Utils.isValidDataType(new HashMap<>()));
}

/**
* It checks if the "readFileContent" method is called.
* And if the created file is read correctly.
*/
@Test
public void readFileContent() throws IOException {
String fileName = "testFile";
String fileContent = "testContent";

File file = new File(fileName);
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(fileContent);
writer.close();

String result = Utils.readFileContent(file, logger);
//delete file
file.delete();
Assert.assertEquals(fileContent, result);
}

/**
* If the file does not exist,
* the method should return an empty string.
*/
@Test
public void readFileContent_fileNotExist() throws IOException {
String fileName = "testFile";
String fileContent = "testContent";

File file = new File(fileName);

String result = Utils.readFileContent(file, logger);

Assert.assertNotEquals(fileContent, result);
Assert.assertEquals("", result);
}

/**
* If the file is not readable for some reason,
* the method should return empty string.
*/
@Test
public void readFileContent_fileNotReadable() throws IOException {
try {
String fileContent = "testContent";

File file = new File(TEST_FILE_NAME);
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(fileContent);
writer.close();
file.setReadable(false);

String content = Utils.readFileContent(file, logger);
Assert.assertEquals("", content);
} finally {
File file = new File(TEST_FILE_NAME);
if (file.exists()) {
file.delete();
}
}
}
}