diff --git a/.github/workflows/publish-to-maven.yml b/.github/workflows/publish-to-maven.yml index 9eab69c..472ea44 100644 --- a/.github/workflows/publish-to-maven.yml +++ b/.github/workflows/publish-to-maven.yml @@ -1,12 +1,10 @@ -# This workflow will publish Trend Vision One File Security Java SDK to Maven Central with OSSRH +# This workflow will publish AMaaS Java SDK to Maven Central with OSSRH name: Java with Maven on: - push: - -permissions: - contents: read + release: + types: [published] jobs: build: @@ -28,8 +26,6 @@ jobs: # Setup Envvar for build - name: Set env run: | - VERSION=$(cat ./VERSION) - echo "AMAAS_JAVA_MODULE_VERSION_ID=$VERSION" >> $GITHUB_ENV if [[ "${{ github.ref }}" == "refs/tags/v"* ]]; then echo "PACK_CMD=deploy" >> $GITHUB_ENV @@ -40,11 +36,9 @@ jobs: # package and optionally publish Java SDK to Maven Central - name: Package and optionally deploy with Maven run: | - sed -i 's/__PACKAGE_VERSION__/${{env.AMAAS_JAVA_MODULE_VERSION_ID}}/' pom.xml mkdir -p src/main/proto/ cp protos/scan.proto src/main/proto/ mvn -B clean ${{env.PACK_CMD}} - sed -i 's/${{env.AMAAS_JAVA_MODULE_VERSION_ID}}/__PACKAGE_VERSION__/' pom.xml env: MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml new file mode 100644 index 0000000..664847a --- /dev/null +++ b/.github/workflows/unit-test.yml @@ -0,0 +1,26 @@ +# This workflow will publish AMaaS Java SDK to Maven Central with OSSRH + +name: Java SDK Unit Tests + +on: + pull_request: + branches: + - main + +jobs: + unit-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Maven and Java + uses: actions/setup-java@v3 + with: + java-version: '8' + distribution: 'adopt' + + - name: Run unit tests + run: | + mkdir -p src/main/proto/ + cp protos/scan.proto src/main/proto/ + mvn test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e63760f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +# general things to ignore +**/target/ +**/output/ +*~ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5552bc1..bd60a6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,7 @@ # CHANGELOG -## 1.0.0 - 2023-11-7 +## 1.0.1 - 2023-11-23 +* Update to latest code + +## 1.0.0 - 2023-11-21 * Initial release diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index a5c076d..c580d41 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -56,7 +56,7 @@ a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at amaas@trendmicro.com. All +reported by contacting the project team at legal_notice@trendmicro.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. diff --git a/examples/filescan/App.java b/examples/filescan/App.java index 680c1bc..3961ba3 100644 --- a/examples/filescan/App.java +++ b/examples/filescan/App.java @@ -13,14 +13,17 @@ import com.trend.cloudone.amaas.AMaasException; -public class App { +public final class App { private static final Logger logger = Logger.getLogger(App.class.getName()); - private static void info(String msg, Object... params) { + private App() { + } + + private static void info(final String msg, final Object... params) { logger.log(Level.INFO, msg, params); } - public static String[] listFiles(String pathName) { + private static String[] listFiles(final String pathName) { File fObj = new File(pathName); if (!fObj.isDirectory()) { return new String[]{pathName}; @@ -31,7 +34,7 @@ public static String[] listFiles(String pathName) { .collect(Collectors.toList()).toArray(new String[] {}); } - static void scanFilesInSequential(AMaasClient client, String[] fList) { + static void scanFilesInSequential(final AMaasClient client, final String[] fList) { for (String fileName: fList) { try { info("===============> Scanning file {0}", fileName); @@ -43,7 +46,7 @@ static void scanFilesInSequential(AMaasClient client, String[] fList) { } catch (AMaasException err) { info("Exception {0}", err.getMessage()); } - } + } } private static Options getCmdOptions() { @@ -54,16 +57,16 @@ private static Options getCmdOptions() { optionList.addOption("t", "timeout", true, "Per scan timeout in seconds"); return optionList; } - - /* - * The program takes 4 options and respecive values to configure the AMaaS SDK client. - * @param String[] Input options: + + /** + * The program takes 4 options and respective values to configure the AMaaS SDK client. + * @param args Input options: * -f a file or a directory to be scanned * -k the API key or bearer authentication token * -r region where the key/token was applied. eg, us-east-1 * -t optional client maximum waiting time in seconds for a scan. 0 or missing means default. */ - public static void main(String[] args) { + public static void main(final String[] args) { String pathname = ""; String apikey = null; String region = ""; @@ -90,9 +93,9 @@ public static void main(String[] args) { AMaasClient client = new AMaasClient(region, apikey, timeout); String[] listOfFiles = listFiles(pathname); long totalStartTs = System.currentTimeMillis(); - + scanFilesInSequential(client, listOfFiles); - + long totalEndTs = System.currentTimeMillis(); info("*************** Total scan time {0}", totalEndTs - totalStartTs); } catch (ParseException err) { diff --git a/examples/parallelscan/ConcurrentApp.java b/examples/parallelscan/ConcurrentApp.java index b84a3df..902a03c 100644 --- a/examples/parallelscan/ConcurrentApp.java +++ b/examples/parallelscan/ConcurrentApp.java @@ -1,4 +1,4 @@ -import java.io.File; +import java.io.File; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionService; @@ -22,15 +22,20 @@ import com.trend.cloudone.amaas.AMaasClient; import com.trend.cloudone.amaas.AMaasException; -public class ConcurrentApp { +public final class ConcurrentApp { private static final Logger logger = Logger.getLogger(ConcurrentApp.class.getName()); private static final int MAX_NUM_OF_THREADS = 5; + private static final int MILLISEC_PER_SEC = 1000; + private static final int DELAY_MILLISEC = 500; - private static void info(String msg, Object... params) { + private ConcurrentApp() { + } + + private static void info(final String msg, final Object... params) { logger.log(Level.INFO, msg, params); } - public static String[] listFiles(String pathName) { + private static String[] listFiles(final String pathName) { File fObj = new File(pathName); if (!fObj.isDirectory()) { return new String[]{pathName}; @@ -45,14 +50,15 @@ public static String[] listFiles(String pathName) { * Value object class for tracking a scan result. */ private static final class ScanResult { - String scanResult; - long scanTime; - public ScanResult(String result, long scanTime) { + private String scanResult; + private long scanTime; + ScanResult(final String result, final long scanTime) { this.scanResult = result; this.scanTime = scanTime; } - @Override - public String toString(){ + + @Override + public String toString() { return scanResult + " " + scanTime; } } @@ -64,12 +70,12 @@ private static final class Task implements Callable { private final String fileName; private final AMaasClient client; - Task(AMaasClient client, String fileName){ + Task(final AMaasClient client, final String fileName) { this.fileName = fileName; this.client = client; } - - @Override + + @Override public ScanResult call() throws Exception { ScanResult result = null; try { @@ -84,10 +90,10 @@ public ScanResult call() throws Exception { } return result; } - + } - static void scanFilesInParallel(AMaasClient client, String[] fList, long timeout) { + static void scanFilesInParallel(final AMaasClient client, final String[] fList, final long timeout) { info("Scan files in Parallel"); int numThreads = MAX_NUM_OF_THREADS; if (fList.length < numThreads) { @@ -97,14 +103,14 @@ static void scanFilesInParallel(AMaasClient client, String[] fList, long timeout try { executor = Executors.newFixedThreadPool(numThreads); CompletionService scanService = new ExecutorCompletionService<>(executor); - for(String file : fList){ + for (String file : fList) { Task task = new Task(client, file); scanService.submit(task); } - - for(int i = 0; i < fList.length; i++){ + + for (int i = 0; i < fList.length; i++) { Future future = scanService.take(); - ScanResult result = future.get(timeout * 1000 + 500, TimeUnit.MILLISECONDS); + ScanResult result = future.get(timeout * MILLISEC_PER_SEC + DELAY_MILLISEC, TimeUnit.MILLISECONDS); if (result != null) { info(future.get().toString()); } @@ -128,16 +134,16 @@ private static Options getCmdOptions() { optionList.addOption("t", "timeout", true, "Per scan timeout in seconds"); return optionList; } - - /* - * The program takes 4 options and respecive values to configure the AMaaS SDK client. - * @param String[] Input options: + + /** + * The program takes 4 options and respective values to configure the AMaaS SDK client. + * @param args Input options: * -f a file or a directory to be scanned * -k the API key or bearer authentication token * -r region where the key/token was applied. eg, us-east-1 * -t optional client maximum waiting time in seconds for a scan. 0 or missing means default. */ - public static void main(String[] args) { + public static void main(final String[] args) { String pathName = ""; String apikey = null; String region = ""; @@ -160,12 +166,12 @@ public static void main(String[] args) { if (cmd.hasOption("t")) { timeout = Long.parseLong(cmd.getOptionValue("t")); } - + AMaasClient client = new AMaasClient(region, apikey, timeout); String[] listOfFiles = listFiles(pathName); long totalStartTs = System.currentTimeMillis(); scanFilesInParallel(client, listOfFiles, timeout); - + long totalEndTs = System.currentTimeMillis(); info("*************** Total scan time {0}", totalEndTs - totalStartTs); } catch (ParseException err) { diff --git a/examples/s3app/S3App.java b/examples/s3app/S3App.java index 58a31e1..efa5aab 100644 --- a/examples/s3app/S3App.java +++ b/examples/s3app/S3App.java @@ -18,19 +18,22 @@ import com.trend.cloudone.amaas.AMaasClient; import com.trend.cloudone.amaas.AMaasException; -public class S3App { +public final class S3App { private static final Logger logger = Logger.getLogger(S3App.class.getName()); + private static final int BUFFER_LENGTH = 16483; + private S3App() { + } - private static void info(String msg, Object... params) { + private static void info(final String msg, final Object... params) { logger.log(Level.INFO, msg, params); } - - public static byte[] serialize(ResponseInputStream data) { + + private static byte[] serialize(final ResponseInputStream data) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - + int nRead; - byte[] byteArray = new byte[16384]; - + byte[] byteArray = new byte[BUFFER_LENGTH]; + try { while ((nRead = data.read(byteArray, 0, byteArray.length)) != -1) { buffer.write(byteArray, 0, nRead); @@ -38,12 +41,12 @@ public static byte[] serialize(ResponseInputStream data) { } catch (IOException e) { info("I/O error while serializing data: {} | {}", e.getMessage(), e); } - + return buffer.toByteArray(); } - public static byte[] downloadS3Object(String regionstr, String bucketName, String key) throws Exception { - + private static byte[] downloadS3Object(final String regionstr, final String bucketName, final String key) throws Exception { + S3Client s3 = S3Client.builder() .credentialsProvider(ProfileCredentialsProvider.create()) .region(Region.of(regionstr)) @@ -69,17 +72,17 @@ private static Options getCmdOptions() { return optionList; } - /* + /** * The program takes 6 options and respecive values to configure the AMaaS SDK client. - * @param String[] Input options: - * -a AWS region + * @param args Input options: + * -a AWS region * -b S3 bucket name * -f S3 key to be scanned * -k the API key or bearer authentication token * -r region where the C1 key/token was applied. eg, us-east-1 * -t optional client maximum waiting time in seconds for a scan. 0 or missing means default. */ - public static void main(String[] args) { + public static void main(final String[] args) { String awsRegion = ""; String bucketName = ""; String keyName = ""; @@ -97,7 +100,7 @@ public static void main(String[] args) { } if (cmd.hasOption("b")) { bucketName = cmd.getOptionValue("b"); - } + } if (cmd.hasOption("f")) { keyName = cmd.getOptionValue("f"); } @@ -110,14 +113,14 @@ public static void main(String[] args) { if (cmd.hasOption("t")) { timeout = Long.parseLong(cmd.getOptionValue("t")); } - + info("Downloading S3 Object...."); byte[] bytes = downloadS3Object(awsRegion, bucketName, keyName); info("Completed downloading S3 Object...."); AMaasClient client = new AMaasClient(amaasRegion, apikey, timeout); long totalStartTs = System.currentTimeMillis(); client.scanBuffer(bytes, keyName); - + long totalEndTs = System.currentTimeMillis(); info("*************** Total scan time {0}", totalEndTs - totalStartTs); } catch (ParseException err) { diff --git a/examples/s3lambda/S3Lambda.java b/examples/s3lambda/S3Lambda.java index 68f68b6..14fc985 100644 --- a/examples/s3lambda/S3Lambda.java +++ b/examples/s3lambda/S3Lambda.java @@ -6,7 +6,6 @@ import java.util.logging.Logger; import software.amazon.awssdk.core.ResponseInputStream; -import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; @@ -14,25 +13,26 @@ import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.services.s3.S3Client; -import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.trend.cloudone.amaas.AMaasClient; import com.trend.cloudone.amaas.AMaasException; -public class S3Lambda implements RequestHandler { +public final class S3Lambda implements RequestHandler { private static final Logger logger = Logger.getLogger(S3Lambda.class.getName()); + private static final int BUFFER_LENGTH = 16483; - private static void info(String msg, Object... params) { + private static void info(final String msg, final Object... params) { logger.log(Level.INFO, msg, params); } - - public static byte[] serialize(ResponseInputStream data) { + + private static byte[] serialize(final ResponseInputStream data) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - + int nRead; - byte[] byteArray = new byte[16384]; - + byte[] byteArray = new byte[BUFFER_LENGTH]; + try { while ((nRead = data.read(byteArray, 0, byteArray.length)) != -1) { buffer.write(byteArray, 0, nRead); @@ -40,11 +40,11 @@ public static byte[] serialize(ResponseInputStream data) { } catch (IOException e) { info("I/O error while serializing data: {} | {}", e.getMessage(), e); } - + return buffer.toByteArray(); } - public static byte[] downloadS3Object(S3Client s3client, String bucketName, String key) throws S3Exception { + private static byte[] downloadS3Object(final S3Client s3client, final String bucketName, final String key) throws S3Exception { GetObjectRequest getObjectRequest = GetObjectRequest.builder() .bucket(bucketName) @@ -55,14 +55,14 @@ public static byte[] downloadS3Object(S3Client s3client, String bucketName, Stri return serialize(response); } - public static ArrayList listAllS3Keys(S3Client s3client, String bucketName, String folderName) { + private static ArrayList listAllS3Keys(final S3Client s3client, final String bucketName, final String folderName) { ArrayList arrayList = new ArrayList<>(); ListObjectsRequest.Builder builder = ListObjectsRequest .builder() .bucket(bucketName); if (folderName != null && folderName != "") { builder.prefix(folderName); - } + } ListObjectsRequest listObjects = builder.build(); try { @@ -80,8 +80,8 @@ public static ArrayList listAllS3Keys(S3Client s3client, String bucketNa return arrayList; } - public static void sequentialScan(AMaasClient client, S3Client s3client, String bucketName, ArrayList keyList, String[] tagList) { - + private static void sequentialScan(final AMaasClient client, final S3Client s3client, final String bucketName, final ArrayList keyList, final String[] tagList) { + for (String keyName: keyList) { try { byte[] bytes = downloadS3Object(s3client, bucketName, keyName); @@ -110,7 +110,7 @@ public static void sequentialScan(AMaasClient client, S3Client s3client, String * TM_AM_AUTH_KEY the API key or bearer authentication token * TM_AM_REGION region where the C1 key/token was applied. eg, us-east-1 * TM_AM_SCAN_TIMEOUT_SECS client maximum waiting time in seconds for a scan. 0 or missing means default. - * + * * S3_BUCKET_NAME S3 bucket name * S3_FOLDER_NAME S3 key prefix as folder name * S3_KEY_NAME a particular S3 key to be scanned @@ -120,21 +120,21 @@ public static void sequentialScan(AMaasClient client, S3Client s3client, String * */ @Override - public String handleRequest(Object input, Context context) { + public String handleRequest(final Object input, final Context context) { info("Testing scanning"); - - String apikey = System.getenv("TM_AM_AUTH_KEY") ; - String region = System.getenv("TM_AM_REGION") ; + + String apikey = System.getenv("TM_AM_AUTH_KEY"); + String region = System.getenv("TM_AM_REGION"); String timeoutStr = System.getenv("TM_AM_SCAN_TIMEOUT_SECS"); - String bucketName = System.getenv("S3_BUCKET_NAME") ; - String folderName = System.getenv("S3_FOLDER_NAME") ; - String keyName = System.getenv("S3_KEY_NAME") ; + String bucketName = System.getenv("S3_BUCKET_NAME"); + String folderName = System.getenv("S3_FOLDER_NAME"); + String keyName = System.getenv("S3_KEY_NAME"); // tags separated by comma. This is user defined tags to be used to tag scan items. - String tags = System.getenv("USER_TAG_LIST") ; + String tags = System.getenv("USER_TAG_LIST"); long timeout = 0; try { - timeout = Integer.parseInt(timeoutStr); + timeout = Integer.parseInt(timeoutStr); } catch (NumberFormatException err) { info("Timeout setting ignored."); } @@ -145,7 +145,7 @@ public String handleRequest(Object input, Context context) { if (keyName == null || keyName == "") { keyList = listAllS3Keys(s3client, bucketName, folderName); } else { - keyList = new ArrayList(){{add(keyName);}}; + keyList = new ArrayList() {{ add(keyName); }}; } if (keyList == null || keyList.isEmpty()) { @@ -157,10 +157,10 @@ public String handleRequest(Object input, Context context) { info("tags to used {0}", tags); tagList = tags.split(","); } - + AMaasClient client = new AMaasClient(region, apikey, timeout); long totalStartTs = System.currentTimeMillis(); - + sequentialScan(client, s3client, bucketName, keyList, tagList); long totalEndTs = System.currentTimeMillis(); info("*************** Total scan time {0}", totalEndTs - totalStartTs); diff --git a/pom.xml b/pom.xml index 06b9940..95d8378 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ com.trend file-security-java-sdk - __PACKAGE_VERSION__ + 1.0.1 file-security-java-sdk https://github.com/trendmicro/tm-v1-fs-java-sdk @@ -20,7 +20,7 @@ - Trendmicro + Trend Micro http://www.trendmicro.com @@ -44,18 +44,6 @@ 1.8 - - - - software.amazon.awssdk - bom - 2.20.66 - pom - import - - - - junit diff --git a/protos/scan.proto b/protos/scan.proto index b553bc9..4c32e8f 100644 --- a/protos/scan.proto +++ b/protos/scan.proto @@ -20,13 +20,15 @@ enum Stage { message C2S { Stage stage = 1; string file_name = 2; - int32 rs_size = 3; + uint32 rs_size = 3; int32 offset = 4; bytes chunk = 5; bool trendx = 6; string file_sha1 = 7; string file_sha256 = 8; repeated string tags = 9; + bool bulk = 10; + bool spn_feedback = 11; } enum Command { @@ -40,4 +42,7 @@ message S2C { int32 offset = 3; int32 length = 4; string result = 5; + repeated int32 bulk_offset = 6; + repeated int32 bulk_length = 7; + string session_id = 8; } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasBaseReader.java b/src/main/java/com/trend/cloudone/amaas/AMaasBaseReader.java index 750af47..8f878ca 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasBaseReader.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasBaseReader.java @@ -4,10 +4,15 @@ * The abstract base class implements the hash methods of the AMaasReader interface. */ public abstract class AMaasBaseReader implements AMaasReader { - byte[] sha1; - byte[] sha256; + private byte[] sha1; + private byte[] sha256; - public static String bytesToHex(byte[] bytes) { + /* + * Method to convert a bytes array to Hex string. + * @param bytes the given byte array to convert. + * @return the converted hex string. + */ + private static String bytesToHex(final byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); @@ -15,7 +20,8 @@ public static String bytesToHex(byte[] bytes) { return sb.toString(); } - public String getHash(HashType htype) { + @Override + public final String getHash(final HashType htype) { switch (htype) { case HASH_SHA1: return "sha1:" + bytesToHex(this.sha1); @@ -25,4 +31,20 @@ public String getHash(HashType htype) { return null; } } + + /* + * Method to set the reader with a hash of the given type. + * @param htype the type of the hash value. + * @param hash the value of the hash to set. + */ + protected final void setHash(final HashType htype, final byte[] hash) { + switch (htype) { + case HASH_SHA1: + this.sha1 = hash; + case HASH_SHA256: + this.sha256 = hash; + default: + break; + } + } } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasBufferReader.java b/src/main/java/com/trend/cloudone/amaas/AMaasBufferReader.java index 8796bb5..289da69 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasBufferReader.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasBufferReader.java @@ -12,14 +12,14 @@ final class AMaasBufferReader extends AMaasBaseReader { private String identifier; private byte[] readerBuf; - AMaasBufferReader(byte[] byteBuf, String identifier) throws AMaasException { + AMaasBufferReader(final byte[] byteBuf, final String identifier) throws AMaasException { this.readerBuf = byteBuf; this.identifier = identifier; try { MessageDigest md = MessageDigest.getInstance("SHA1"); - this.sha1 = md.digest(this.readerBuf); + this.setHash(HashType.HASH_SHA1, md.digest(this.readerBuf)); md = MessageDigest.getInstance("SHA-256"); - this.sha256 = md.digest(this.readerBuf); + this.setHash(HashType.HASH_SHA256, md.digest(this.readerBuf)); } catch (NoSuchAlgorithmException err) { // this exception is not possible as the algorithms are hard coded. } @@ -33,7 +33,7 @@ public String getIdentifier() { return this.identifier; } - public int readBytes(int offset, byte[] buf) throws IOException { + public int readBytes(final int offset, final byte[] buf) throws IOException { int chunkLength = buf.length; if (chunkLength + offset > this.readerBuf.length) { chunkLength = this.readerBuf.length - offset; diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasCallCredentials.java b/src/main/java/com/trend/cloudone/amaas/AMaasCallCredentials.java index ba3ed84..e02c5d5 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasCallCredentials.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasCallCredentials.java @@ -1,7 +1,6 @@ package com.trend.cloudone.amaas; import java.util.concurrent.Executor; -import java.util.regex.*; import io.grpc.CallCredentials; import io.grpc.Metadata; import io.grpc.Status; @@ -19,17 +18,17 @@ public AMaasConstants.TokenType getTokenType() { return tokenType; } - AMaasCallCredentials(String token, String appName) { - this.token = token; - this.appName = appName; + AMaasCallCredentials(final String authToken, final String applicationName) { + this.token = authToken; + this.appName = applicationName; this.tokenType = AMaasConstants.TokenType.AUTH_TYPE_APIKEY; } @Override public void applyRequestMetadata( - RequestInfo requestInfo, - Executor executor, - MetadataApplier metadataApplier) { + final RequestInfo requestInfo, + final Executor executor, + final MetadataApplier metadataApplier) { executor.execute(() -> { try { Metadata headers = new Metadata(); diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasClient.java b/src/main/java/com/trend/cloudone/amaas/AMaasClient.java index d991583..4d14046 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasClient.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasClient.java @@ -19,10 +19,10 @@ import com.trend.cloudone.amaas.scan.ScanOuterClass.Stage; /** - * AMaaS Client connecting to AMaaS gRPC server to provide API for malware scanning services. User can use the API + * AMaaS Client connecting to AMaaS gRPC server to provide API for malware scanning services. User can use the API * to scan a file or a byte buffer. */ -public class AMaasClient { +public final class AMaasClient { private static final Logger logger = Logger.getLogger(AMaasClient.class.getName()); private static final long DEFAULT_SCAN_TIMEOUT = 180; private static final int MAX_NUM_OF_TAGS = 8; @@ -33,7 +33,7 @@ public class AMaasClient { private AMaasCallCredentials cred; private long timeoutSecs = DEFAULT_SCAN_TIMEOUT; // 3 minutes - + /** * AMaaSClient constructor. The enabledTLS is default to true and the appName is default to V1FS. * @param region region you obtained your api key @@ -42,12 +42,12 @@ public class AMaasClient { * @throws AMaasException if an exception is detected, it will convert to AMassException. * */ - public AMaasClient(String region, String apiKey, long timeoutInSecs) throws AMaasException { + public AMaasClient(final String region, final String apiKey, final long timeoutInSecs) throws AMaasException { this(region, apiKey, timeoutInSecs, true, AMaasConstants.V1FS_APP); } /** - * AMaaSClient constructor + * AMaaSClient constructor. * @param region region we obtained your api key * @param apiKey api key to be used * @param timeoutInSecs number in seconds to wait for a scan. 0 default to 180 seconds. @@ -56,7 +56,7 @@ public AMaasClient(String region, String apiKey, long timeoutInSecs) throws AMaa * @throws AMaasException if an exception is detected, it will convert to AMassException. * */ - public AMaasClient(String region, String apiKey, long timeoutInSecs, boolean enabledTLS, String appName) throws AMaasException { + public AMaasClient(final String region, final String apiKey, final long timeoutInSecs, final boolean enabledTLS, final String appName) throws AMaasException { String target = this.identifyHostAddr(region); if (target == null || target == "") { throw new AMaasException(AMaasErrorCode.MSG_ID_ERR_INVALID_REGION, region, AMaasRegion.getAllRegionsAsString()); @@ -88,16 +88,16 @@ protected void finalize() { } } - private String identifyHostAddr(String region) { + private String identifyHostAddr(final String region) { // overwrite region setting with host setting String target = System.getenv("TM_AM_SERVER_ADDR"); - if (target==null||target=="") { + if (target == null || target == "") { target = AMaasRegion.getServiceFqdn(region); } return target; } - private static void log(Level level, String msg, Object... params) { + private static void log(final Level level, final String msg, final Object... params) { logger.log(level, msg, params); } @@ -123,7 +123,7 @@ private AMaasException processError() { if (this.grpcStatus == Status.Code.UNAUTHENTICATED) { err = new AMaasException(AMaasErrorCode.MSG_ID_ERR_KEY_AUTH_FAILED); } else { - err = new AMaasException( AMaasErrorCode.MSG_ID_GRPC_ERROR, this.grpcStatus.value(), this.grpcStatus.toString()); + err = new AMaasException(AMaasErrorCode.MSG_ID_GRPC_ERROR, this.grpcStatus.value(), this.grpcStatus.toString()); } return err; } @@ -136,22 +136,22 @@ protected String waitTilExit() throws AMaasException { } catch (InterruptedException err) { throw new AMaasException(AMaasErrorCode.MSG_ID_ERR_UNEXPECTED_INTERRUPT); } - - if (this.grpcStatus ==Status.Code.OK) { + + if (this.grpcStatus == Status.Code.OK) { return this.scanResult; } else { throw this.processError(); - } + } } - protected void setConext(StreamObserver requestObserver, AMaasReader reader) { + protected void setConext(final StreamObserver requestObserver, final AMaasReader reader) { this.requestObserver = requestObserver; this.reader = reader; this.done = false; } @Override - public void onNext(ScanOuterClass.S2C s2cMsg) { + public void onNext(final ScanOuterClass.S2C s2cMsg) { log(Level.FINE, "Got message {0} at {1}, {2}", s2cMsg.getCmdValue(), s2cMsg.getOffset(), s2cMsg.getLength()); switch (s2cMsg.getCmd()) { case CMD_RETR: @@ -182,7 +182,7 @@ public void onNext(ScanOuterClass.S2C s2cMsg) { } @Override - public void onError(Throwable t) { + public void onError(final Throwable t) { log(Level.WARNING, "scan Failed: {0}", Status.fromThrowable(t)); this.done = true; this.grpcStatus = Status.fromThrowable(t).getCode(); @@ -198,7 +198,7 @@ public void onCompleted() { } } - static AMaasException getTagListErrors(String[] tagList) { + static AMaasException getTagListErrors(final String[] tagList) { AMaasException except = null; if (tagList.length > MAX_NUM_OF_TAGS) { except = new AMaasException(AMaasErrorCode.MSG_ID_ERR_MAX_NUMBER_OF_TAGS, MAX_NUM_OF_TAGS); @@ -220,20 +220,20 @@ static AMaasException getTagListErrors(String[] tagList) { * @return String the scanned result in JSON format. * @throws AMaasException if an exception is detected, it will convert to AMassException. */ - private String scanRun(AMaasReader reader, String[] tagList) throws AMaasException { - + private String scanRun(final AMaasReader reader, final String[] tagList) throws AMaasException { + long fileSize = reader.getLength(); AMaasServerCallback serverCallback = new AMaasServerCallback(); StreamObserver requestObserver = this.asyncStub.withDeadlineAfter(this.timeoutSecs, TimeUnit.SECONDS).run(serverCallback); - + // initialize the callback context before proceeding serverCallback.setConext(requestObserver, reader); String sha1Str = reader.getHash(AMaasReader.HashType.HASH_SHA1); String sha256Str = reader.getHash(AMaasReader.HashType.HASH_SHA256); - ScanOuterClass.C2S.Builder builder = ScanOuterClass.C2S.newBuilder().setStage(Stage.STAGE_INIT).setFileName(reader.getIdentifier()).setRsSize((int)fileSize).setOffset(0).setFileSha1(sha1Str).setFileSha256(sha256Str); + ScanOuterClass.C2S.Builder builder = ScanOuterClass.C2S.newBuilder().setStage(Stage.STAGE_INIT).setFileName(reader.getIdentifier()).setRsSize((int) fileSize).setOffset(0).setFileSha1(sha1Str).setFileSha256(sha256Str); if (tagList != null) { AMaasException except = getTagListErrors(tagList); if (except != null) { @@ -247,49 +247,48 @@ private String scanRun(AMaasReader reader, String[] tagList) throws AMaasExcepti String scanResult = serverCallback.waitTilExit(); - return scanResult; - + } /** - * Scan a file and return the scanned result + * Scan a file and return the scanned result. * * @param fileName Full path of a file to be scanned. * @return String the scanned result in JSON format. * @throws AMaasException if an exception is detected, it will convert to AMassException. */ - public String scanFile(String fileName) throws AMaasException { + public String scanFile(final String fileName) throws AMaasException { return this.scanFile(fileName, null); } /** - * Scan a file and return the scanned result + * Scan a file and return the scanned result. * * @param fileName Full path of a file to be scanned. * @param tagList List of tags * @return String the scanned result in JSON format. * @throws AMaasException if an exception is detected, it will convert to AMassException. */ - public String scanFile(String fileName, String[] tagList) throws AMaasException { + public String scanFile(final String fileName, final String[] tagList) throws AMaasException { AMaasFileReader fileReader = new AMaasFileReader(fileName); return this.scanRun(fileReader, tagList); } /** - * Scan a buffer and return the scanned result + * Scan a buffer and return the scanned result. * * @param buffer the buffer to be scanned * @param identifier A unique name to identify the buffer. * @return String the scanned result in JSON format. * @throws AMaasException if an exception is detected, it will convert to AMassException. */ - public String scanBuffer(byte[] buffer, String identifier) throws AMaasException { + public String scanBuffer(final byte[] buffer, final String identifier) throws AMaasException { return this.scanBuffer(buffer, identifier, null); } /** - * Scan a buffer and return the scanned result + * Scan a buffer and return the scanned result. * * @param buffer the buffer to be scanned * @param identifier A unique name to identify the buffer. @@ -297,7 +296,7 @@ public String scanBuffer(byte[] buffer, String identifier) throws AMaasException * @return String the scanned result in JSON format. * @throws AMaasException if an exception is detected, it will convert to AMassException. */ - public String scanBuffer(byte[] buffer, String identifier, String[] tagList) throws AMaasException { + public String scanBuffer(final byte[] buffer, final String identifier, final String[] tagList) throws AMaasException { AMaasBufferReader bufReader = new AMaasBufferReader(buffer, identifier); return this.scanRun(bufReader, tagList); } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasConstants.java b/src/main/java/com/trend/cloudone/amaas/AMaasConstants.java index e2959e0..2aa37cf 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasConstants.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasConstants.java @@ -9,6 +9,10 @@ final class AMaasConstants { public static final String V1FS_APP = "V1FS"; + private AMaasConstants() { + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } + /* * Enum class for AMaaS authentication token types. */ diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasErrorCode.java b/src/main/java/com/trend/cloudone/amaas/AMaasErrorCode.java index 155f786..5c36858 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasErrorCode.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasErrorCode.java @@ -8,32 +8,32 @@ public enum AMaasErrorCode { * Scan file cannot be found. */ MSG_ID_ERR_FILE_NOT_FOUND("MSG_ID_ERR_FILE_NOT_FOUND", "Failed to open file. No such file or directory %s."), - + /** * Have no permission to open the scan file. */ MSG_ID_ERR_FILE_NO_PERMISSION("MSG_ID_ERR_FILE_NO_PERMISSION", "Failed to open file. Permission denied to open %s."), - + /** * Incorrect region is given. */ MSG_ID_ERR_INVALID_REGION("MSG_ID_ERR_INVALID_REGION", "%s is not a supported region, region value should be one of %s"), - + /** * Cloudone credetial is not given. */ - MSG_ID_ERR_MISSING_AUTH("MSG_ID_ERR_MISSING_AUTH","Must provide an API key to use the client."), - + MSG_ID_ERR_MISSING_AUTH("MSG_ID_ERR_MISSING_AUTH", "Must provide an API key to use the client."), + /** * An GRPC error was reported. */ MSG_ID_GRPC_ERROR("MSG_ID_GRPC_ERROR", "Received gRPC status code: %d, msg: %s."), - + /** * Authentication failed using the given Cloudone credential. */ MSG_ID_ERR_KEY_AUTH_FAILED("MSG_ID_ERR_KEY_AUTH_FAILED", "Authorization key cannot be authenticated."), - + /** * Java SDK client received an unexpected interrupt. */ @@ -63,7 +63,7 @@ public enum AMaasErrorCode { * @param errorCode error code to be used * @param message template to be used. */ - AMaasErrorCode(String errorCode, String message) { + AMaasErrorCode(final String errorCode, final String message) { this.errorCode = errorCode; this.message = message; } @@ -89,7 +89,7 @@ public String getMessage() { * @param params objects to be used to format the template. * @return message prepared from the templates using the parameters. */ - public String getMessage(Object... params) { + public String getMessage(final Object... params) { return String.format(this.message, params); } } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasException.java b/src/main/java/com/trend/cloudone/amaas/AMaasException.java index 90f83a9..74590bd 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasException.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasException.java @@ -13,7 +13,7 @@ public final class AMaasException extends Exception { * @param erroCode error code to be reported. * @param params optional parameters used to format the template associated with the error code. */ - public AMaasException(AMaasErrorCode erroCode, Object... params) { + public AMaasException(final AMaasErrorCode erroCode, final Object... params) { super(erroCode.getMessage(params)); this.erroCode = erroCode; } @@ -24,7 +24,7 @@ public AMaasException(AMaasErrorCode erroCode, Object... params) { * @param cause the caught thowable object. * @param params optional parameters used to format the template associated with the error code. */ - public AMaasException(AMaasErrorCode erroCode, Throwable cause, Object... params) { + public AMaasException(final AMaasErrorCode erroCode, final Throwable cause, final Object... params) { super(erroCode.getMessage(params), cause); this.erroCode = erroCode; } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasFileReader.java b/src/main/java/com/trend/cloudone/amaas/AMaasFileReader.java index b650046..f2e40f6 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasFileReader.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasFileReader.java @@ -18,7 +18,9 @@ final class AMaasFileReader extends AMaasBaseReader { private String fileName; private long fileSize; - AMaasFileReader (String fileName) throws AMaasException { + private static final int ONE_KBYTE = 1024; + + AMaasFileReader(final String fileName) throws AMaasException { try { this.fileName = fileName; File targetFile = new File(fileName); @@ -29,19 +31,19 @@ final class AMaasFileReader extends AMaasBaseReader { throw new AMaasException(AMaasErrorCode.MSG_ID_ERR_FILE_NO_PERMISSION, this.fileName); } this.fileSize = targetFile.length(); - + MessageDigest md = MessageDigest.getInstance("SHA1"); MessageDigest md256 = MessageDigest.getInstance("SHA-256"); try (FileInputStream is = new FileInputStream(targetFile)) { - byte[] bytesBuffer = new byte[1024]; + byte[] bytesBuffer = new byte[ONE_KBYTE]; int bytesRead = -1; - + while ((bytesRead = is.read(bytesBuffer)) != -1) { md.update(bytesBuffer, 0, bytesRead); md256.update(bytesBuffer, 0, bytesRead); } - this.sha1 = md.digest(); - this.sha256 = md256.digest(); + this.setHash(HashType.HASH_SHA1, md.digest()); + this.setHash(HashType.HASH_SHA256, md256.digest()); } catch (IOException e) { throw new IllegalArgumentException(e); } @@ -61,7 +63,7 @@ protected void finalize() { try { this.randomFile.close(); } catch (IOException err) { - logger.log(Level.INFO,"unexpected exception {0}", err); + logger.log(Level.INFO, "unexpected exception {0}", err); } } @@ -73,7 +75,7 @@ public long getLength() { return this.fileSize; } - public int readBytes(int offset, byte[] buff) throws IOException { + public int readBytes(final int offset, final byte[] buff) throws IOException { this.randomFile.seek(offset); return this.randomFile.read(buff); } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasReader.java b/src/main/java/com/trend/cloudone/amaas/AMaasReader.java index 4e03279..e7eb2e2 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasReader.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasReader.java @@ -6,7 +6,7 @@ * Interface for implementing a reader class to be scanned. */ interface AMaasReader { - public enum HashType { + enum HashType { HASH_SHA1, HASH_SHA256 } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasRegion.java b/src/main/java/com/trend/cloudone/amaas/AMaasRegion.java index c954dcb..6926d64 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasRegion.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasRegion.java @@ -34,40 +34,44 @@ final class AMaasRegion { static final String C1_TREND_REGION = "trend-us-1"; static final String C1_GB_REGION = "gb-1"; - static final List C1Regions = Arrays.asList(new String[]{C1_AU_REGION, C1_CA_REGION, C1_DE_REGION, C1_GB_REGION, C1_IN_REGION, C1_JP_REGION, C1_SG_REGION, C1_US_REGION, C1_TREND_REGION}); - static final List V1Regions = Arrays.asList(new String[]{AWS_AU_REGION, AWS_CA_REGION, AWS_DE_REGION, AWS_GB_REGION, AWS_IN_REGION, AWS_JP_REGION, AWS_SG_REGION, AWS_US_REGION}); - static final List SupportedV1Regions = Arrays.asList(new String[]{AWS_AU_REGION, AWS_DE_REGION, AWS_JP_REGION, AWS_SG_REGION, AWS_US_REGION}); - static final List SupportedC1Regions = Arrays.asList(new String[]{C1_AU_REGION, C1_CA_REGION, C1_DE_REGION, C1_GB_REGION, C1_IN_REGION, C1_JP_REGION, C1_SG_REGION, C1_US_REGION}); + static final List C1_REGIONS = Arrays.asList(new String[]{C1_AU_REGION, C1_CA_REGION, C1_DE_REGION, C1_GB_REGION, C1_IN_REGION, C1_JP_REGION, C1_SG_REGION, C1_US_REGION, C1_TREND_REGION}); + static final List V1_REGIONS = Arrays.asList(new String[]{AWS_AU_REGION, AWS_CA_REGION, AWS_DE_REGION, AWS_GB_REGION, AWS_IN_REGION, AWS_JP_REGION, AWS_SG_REGION, AWS_US_REGION}); + static final List SUPPORTED_V1_REGIONS = Arrays.asList(new String[]{AWS_AU_REGION, AWS_DE_REGION, AWS_JP_REGION, AWS_SG_REGION, AWS_US_REGION}); + static final List SUPPORTED_C1_REGIONS = Arrays.asList(new String[]{C1_AU_REGION, C1_CA_REGION, C1_DE_REGION, C1_GB_REGION, C1_IN_REGION, C1_JP_REGION, C1_SG_REGION, C1_US_REGION}); - static final Map V1ToC1RegionMapping = new HashMap() { + static final Map V1_TO_C1_REGION_MAPPING = new HashMap() { { - put(AWS_AU_REGION, C1_AU_REGION); - put(AWS_DE_REGION, C1_DE_REGION); - put(AWS_IN_REGION, C1_IN_REGION); - put(AWS_JP_REGION, C1_JP_REGION); - put(AWS_SG_REGION, C1_SG_REGION); - put(AWS_US_REGION, C1_US_REGION); + put(AWS_AU_REGION, C1_AU_REGION); + put(AWS_DE_REGION, C1_DE_REGION); + put(AWS_IN_REGION, C1_IN_REGION); + put(AWS_JP_REGION, C1_JP_REGION); + put(AWS_SG_REGION, C1_SG_REGION); + put(AWS_US_REGION, C1_US_REGION); } }; - static final Map C1Region2HostMapping = new HashMap(){ - { + static final Map C1_REGION_2_HOST_MAPPING = new HashMap() { + { put(C1_US_REGION, "antimalware.us-1.cloudone.trendmicro.com"); - put(C1_IN_REGION, "antimalware.in-1.cloudone.trendmicro.com"); - put(C1_DE_REGION, "antimalware.de-1.cloudone.trendmicro.com"); - put(C1_SG_REGION, "antimalware.sg-1.cloudone.trendmicro.com"); - put(C1_AU_REGION, "antimalware.au-1.cloudone.trendmicro.com"); - put(C1_JP_REGION, "antimalware.jp-1.cloudone.trendmicro.com"); - put(C1_GB_REGION, "antimalware.gb-1.cloudone.trendmicro.com"); - put(C1_CA_REGION, "antimalware.ca-1.cloudone.trendmicro.com"); - put(C1_TREND_REGION, "antimalware.trend-us-1.cloudone.trendmicro.com"); + put(C1_IN_REGION, "antimalware.in-1.cloudone.trendmicro.com"); + put(C1_DE_REGION, "antimalware.de-1.cloudone.trendmicro.com"); + put(C1_SG_REGION, "antimalware.sg-1.cloudone.trendmicro.com"); + put(C1_AU_REGION, "antimalware.au-1.cloudone.trendmicro.com"); + put(C1_JP_REGION, "antimalware.jp-1.cloudone.trendmicro.com"); + put(C1_GB_REGION, "antimalware.gb-1.cloudone.trendmicro.com"); + put(C1_CA_REGION, "antimalware.ca-1.cloudone.trendmicro.com"); + put(C1_TREND_REGION, "antimalware.trend-us-1.cloudone.trendmicro.com"); } - }; + }; + + private AMaasRegion() { + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } - private static List concat(List array1, List array2) { + private static List concat(final List array1, final List array2) { - List result = new ArrayList(AMaasRegion.C1Regions); - result.addAll(V1Regions); + List result = new ArrayList(AMaasRegion.C1_REGIONS); + result.addAll(V1_REGIONS); return result; } @@ -76,30 +80,30 @@ private static List concat(List array1, List array2) { * @param targetRegion region to use * @return the FQDN of the given region. */ - public static String getServiceFqdn(String targetRegion) { + public static String getServiceFqdn(final String targetRegion) { // ensure the region exists in v1 or c1 - String region = targetRegion; - if (!SupportedV1Regions.contains(region)) { - logger.log(Level.INFO,"{0} is not a supported region", region); + String region = targetRegion; + if (!SUPPORTED_V1_REGIONS.contains(region)) { + logger.log(Level.INFO, "{0} is not a supported region", region); return ""; } else { // if it is a supported V1 region, map it to a C1 region - String c1_region = AMaasRegion.V1ToC1RegionMapping.get(region); - if (c1_region == "") { - logger.log(Level.INFO,"{0} is not a supported region", region); + String c1Region = AMaasRegion.V1_TO_C1_REGION_MAPPING.get(region); + if (c1Region == "") { + logger.log(Level.INFO, "{0} is not a supported region", region); return ""; } - region = c1_region; + region = c1Region; } - String fqdn = AMaasRegion.C1Region2HostMapping.get(region); + String fqdn = AMaasRegion.C1_REGION_2_HOST_MAPPING.get(region); if (fqdn == null) { - logger.log(Level.INFO,"{0} is not a supported region", region); + logger.log(Level.INFO, "{0} is not a supported region", region); return ""; } return fqdn; } public static String getAllRegionsAsString() { - return String.join(",", AMaasRegion.SupportedV1Regions); + return String.join(",", AMaasRegion.SUPPORTED_V1_REGIONS); } } diff --git a/src/main/java/com/trend/cloudone/amaas/AMaasScanResult.java b/src/main/java/com/trend/cloudone/amaas/AMaasScanResult.java index 52b36a6..4f60a92 100644 --- a/src/main/java/com/trend/cloudone/amaas/AMaasScanResult.java +++ b/src/main/java/com/trend/cloudone/amaas/AMaasScanResult.java @@ -20,8 +20,8 @@ public class AMaasScanResult { * @param fileName identifier of a file * @param foundMalwares an array of found malwares */ - public AMaasScanResult(String version, int scanResult, String scanId, String scanTimestamp, String fileName, - MalwareItem[] foundMalwares) { + public AMaasScanResult(final String version, final int scanResult, final String scanId, final String scanTimestamp, final String fileName, + final MalwareItem[] foundMalwares) { this.version = version; this.scanResult = scanResult; this.scanId = scanId; @@ -82,7 +82,7 @@ public MalwareItem[] getFoundMalwares() { * Set schema version number of a json scan result. * @param version AMaaS scan result json schema version to set */ - public void setVersion(String version) { + public void setVersion(final String version) { this.version = version; } @@ -90,7 +90,7 @@ public void setVersion(String version) { * Set a scan result. * @param scanResult scan outcome to set. 0 for fail and 1 for success. */ - public void setScanResult(int scanResult) { + public void setScanResult(final int scanResult) { this.scanResult = scanResult; } @@ -98,7 +98,7 @@ public void setScanResult(int scanResult) { * Set the Id to identify a scan. * @param scanId scanId to set */ - public void setScanId(String scanId) { + public void setScanId(final String scanId) { this.scanId = scanId; } @@ -106,7 +106,7 @@ public void setScanId(String scanId) { * Set timestamp a scan was performed. * @param scanTimestamp timestamp to set */ - public void setScanTimestamp(String scanTimestamp) { + public void setScanTimestamp(final String scanTimestamp) { this.scanTimestamp = scanTimestamp; } @@ -114,7 +114,7 @@ public void setScanTimestamp(String scanTimestamp) { * Set the identifier of a file. * @param fileName file identifier to set */ - public void setFileName(String fileName) { + public void setFileName(final String fileName) { this.fileName = fileName; } @@ -122,7 +122,7 @@ public void setFileName(String fileName) { * Set an array of found MalwareItem objects. * @param foundMalwares array of MalwareItem to set */ - public void setFoundMalwares(MalwareItem[] foundMalwares) { + public void setFoundMalwares(final MalwareItem[] foundMalwares) { this.foundMalwares = foundMalwares; } } diff --git a/src/main/java/com/trend/cloudone/amaas/MalwareItem.java b/src/main/java/com/trend/cloudone/amaas/MalwareItem.java index 361c1e3..cc5293b 100644 --- a/src/main/java/com/trend/cloudone/amaas/MalwareItem.java +++ b/src/main/java/com/trend/cloudone/amaas/MalwareItem.java @@ -12,7 +12,7 @@ public class MalwareItem { * @param malwareName name of detected malware * @param fileName file name that the malware was detected */ - public MalwareItem(String malwareName, String fileName) { + public MalwareItem(final String malwareName, final String fileName) { this.malwareName = malwareName; this.fileName = fileName; } @@ -37,15 +37,15 @@ public String getFileName() { * Set malware name. * @param malwareName malware name to set */ - public void setMalwareName(String malwareName) { + public void setMalwareName(final String malwareName) { this.malwareName = malwareName; } - + /** * Set file name that the malware was detected. * @param fileName file name to set */ - public void setFileName(String fileName) { + public void setFileName(final String fileName) { this.fileName = fileName; } @@ -67,24 +67,32 @@ public int hashCode() { * @return true if equal; false otherwise. */ @Override - public boolean equals(Object obj) { - if (this == obj) + public boolean equals(final Object obj) { + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } MalwareItem other = (MalwareItem) obj; if (malwareName == null) { - if (other.malwareName != null) + if (other.malwareName != null) { return false; - } else if (!malwareName.equals(other.malwareName)) + } + } else if (!malwareName.equals(other.malwareName)) { return false; + } if (fileName == null) { - if (other.fileName != null) + if (other.fileName != null) { return false; - } else if (!fileName.equals(other.fileName)) + } + } else if (!fileName.equals(other.fileName)) { return false; + + } return true; } } diff --git a/src/main/java/com/trend/cloudone/amaas/package-info.java b/src/main/java/com/trend/cloudone/amaas/package-info.java new file mode 100644 index 0000000..2bc36c5 --- /dev/null +++ b/src/main/java/com/trend/cloudone/amaas/package-info.java @@ -0,0 +1,6 @@ +/** + * This module implements the File Security SDK. + * + * @since 1.0 + */ +package com.trend.cloudone.amaas; diff --git a/src/test/java/com/trend/cloudone/amaas/AMaasClientTest.java b/src/test/java/com/trend/cloudone/amaas/AMaasClientTest.java index 1ca0c6b..d5fb1da 100644 --- a/src/test/java/com/trend/cloudone/amaas/AMaasClientTest.java +++ b/src/test/java/com/trend/cloudone/amaas/AMaasClientTest.java @@ -27,19 +27,25 @@ public class AMaasClientTest { + private static final int TIMEOUT_SEC = 5000; + private static final int BUFF_LENGTH = 64; private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); private ScanGrpc.ScanStub client; - protected Gson gson; - + private Gson gson; + /** + * Rule for grpc cleanup. + */ @Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - + /** + * Rule for expected exception. + */ @Rule public ExpectedException exceptionRule = ExpectedException.none(); - + @Before public void setUp() throws Exception { this.gson = new GsonBuilder().create(); @@ -52,14 +58,13 @@ public void setUp() throws Exception { this.client = ScanGrpc.newStub(grpcCleanup.register( InProcessChannelBuilder.forName(serverName).directExecutor().build())); - } - private void prepareTestObj(AMaasClient.AMaasServerCallback serverCallback, AMaasReader reader, String[] tagList) { + private void prepareTestObj(final AMaasClient.AMaasServerCallback serverCallback, final AMaasReader reader, final String[] tagList) { MockScanServicer servicer = new MockScanServicer(); serviceRegistry.addService(servicer); - + StreamObserver requestObserver = this.client.run(serverCallback); // initialize the callback context before proceeding @@ -68,7 +73,7 @@ private void prepareTestObj(AMaasClient.AMaasServerCallback serverCallback, AMaa String sha256Str = reader.getHash(AMaasReader.HashType.HASH_SHA256); serverCallback.setConext(requestObserver, reader); - ScanOuterClass.C2S.Builder builder = ScanOuterClass.C2S.newBuilder().setStage(Stage.STAGE_INIT).setFileName(reader.getIdentifier()).setRsSize((int)fileSize).setOffset(0).setFileSha1(sha1Str).setFileSha256(sha256Str); + ScanOuterClass.C2S.Builder builder = ScanOuterClass.C2S.newBuilder().setStage(Stage.STAGE_INIT).setFileName(reader.getIdentifier()).setRsSize((int) fileSize).setOffset(0).setFileSha1(sha1Str).setFileSha256(sha256Str); if (tagList != null) { builder.addAllTags(Arrays.asList(tagList)); } @@ -88,7 +93,6 @@ public void testGrpcClientRetrieveCorrectly() { String scanResultjson = serverCallback.waitTilExit(); AMaasScanResult scanResult = this.gson.fromJson(scanResultjson, AMaasScanResult.class); assertEquals(scanResult.getScanResult(), 0); - } catch (AMaasException err) { System.out.println(err.getMessage()); err.printStackTrace(); @@ -108,7 +112,6 @@ public void testGrpcServerReceiveHashCorrectly() { String scanResultjson = serverCallback.waitTilExit(); AMaasScanResult scanResult = this.gson.fromJson(scanResultjson, AMaasScanResult.class); assertEquals(scanResult.getScanResult(), 0); - } catch (AMaasException err) { err.printStackTrace(); assert false; @@ -128,7 +131,6 @@ public void testGrpcServerReceiveWrongHash() { this.gson.fromJson(scanResultjson, AMaasScanResult.class); //assertEquals(scanResult.getScanResult(), 0); assert false; - } catch (AMaasException err) { err.printStackTrace(); assert true; @@ -152,7 +154,6 @@ public void testGrpcDetectedVirusCorrectly() { assertEquals(scanResult.getFoundMalwares().length, 2); assertEquals(scanResult.getFoundMalwares()[0].getMalwareName(), "virus1"); assertEquals(scanResult.getFoundMalwares()[1].getMalwareName(), "virus2"); - } catch (AMaasException err) { System.out.println(err.getMessage()); assert false; @@ -167,7 +168,7 @@ public void testWrongRegion() throws AMaasException { String region = "aa-1"; exceptionRule.expect(AMaasException.class); exceptionRule.expectMessage(AMaasErrorCode.MSG_ID_ERR_INVALID_REGION.getMessage(region, AMaasRegion.getAllRegionsAsString())); - new AMaasClient(region, "AAAPPPKet", (long)5000, false, AMaasConstants.V1FS_APP); + new AMaasClient(region, "AAAPPPKet", (long) TIMEOUT_SEC, false, AMaasConstants.V1FS_APP); } @@ -175,7 +176,7 @@ public void testWrongRegion() throws AMaasException { public void testMissingAuthentication() throws Exception { exceptionRule.expect(AMaasException.class); exceptionRule.expectMessage(AMaasErrorCode.MSG_ID_ERR_MISSING_AUTH.getMessage()); - new AMaasClient("us-east-1", null, (long)5000, false, AMaasConstants.V1FS_APP); + new AMaasClient("us-east-1", null, (long) TIMEOUT_SEC, false, AMaasConstants.V1FS_APP); } @@ -215,7 +216,6 @@ public void testTags() { System.out.println(scanResultjson); AMaasScanResult scanResult = this.gson.fromJson(scanResultjson, AMaasScanResult.class); assertEquals(scanResult.getScanResult(), 0); - } catch (Exception err) { err.printStackTrace(); assert false; @@ -228,7 +228,7 @@ public void testGetTagListErrors() { AMaasException err = AMaasClient.getTagListErrors(taglist); assertEquals(err.getErrorCode(), AMaasErrorCode.MSG_ID_ERR_MAX_NUMBER_OF_TAGS); - String space64 = new String(new char[64]); + String space64 = new String(new char[BUFF_LENGTH]); taglist = new String[]{space64}; err = AMaasClient.getTagListErrors(taglist); assertEquals(err.getErrorCode(), AMaasErrorCode.MSG_ID_ERR_LENGTH_OF_TAG); diff --git a/src/test/java/com/trend/cloudone/amaas/AMaasExceptionTest.java b/src/test/java/com/trend/cloudone/amaas/AMaasExceptionTest.java index eb4cc45..14aa0cc 100644 --- a/src/test/java/com/trend/cloudone/amaas/AMaasExceptionTest.java +++ b/src/test/java/com/trend/cloudone/amaas/AMaasExceptionTest.java @@ -18,7 +18,7 @@ public void testGetErrorCode() { @Test public void testGetErrorCodeThrowable() { - FileNotFoundException except = new FileNotFoundException("abc.txt not found"); + FileNotFoundException except = new FileNotFoundException("abc.txt not found"); AMaasException err = new AMaasException(AMaasErrorCode.MSG_ID_GRPC_ERROR, except, 2, "UNKNOWN"); assertEquals(AMaasErrorCode.MSG_ID_GRPC_ERROR, err.getErrorCode()); assertEquals("Received gRPC status code: 2, msg: UNKNOWN.", err.getMessage()); diff --git a/src/test/java/com/trend/cloudone/amaas/AMaasFileBufferTest.java b/src/test/java/com/trend/cloudone/amaas/AMaasFileBufferTest.java index 3c82ebe..1c528ce 100644 --- a/src/test/java/com/trend/cloudone/amaas/AMaasFileBufferTest.java +++ b/src/test/java/com/trend/cloudone/amaas/AMaasFileBufferTest.java @@ -22,13 +22,13 @@ public void testReadBytes() { AMaasBufferReader bufReader = new AMaasBufferReader(data, DataFileCreator.TEST_DATA_FILE_NAME); long len = bufReader.getLength(); Random rand = new Random(); - int offset = rand.nextInt((int)len); - int size = rand.nextInt((int)len - offset); + int offset = rand.nextInt((int) len); + int size = rand.nextInt((int) len - offset); byte[] buf = new byte[size]; bufReader.readBytes(offset, buf); assertEquals(bufReader.getIdentifier(), DataFileCreator.TEST_DATA_FILE_NAME); assertEquals(bufReader.getLength(), data.length); - DataFileCreator.verifyBufWithData(buf, offset); + DataFileCreator.verifyBufWithData(buf, offset); } catch (Exception err) { assert false; } diff --git a/src/test/java/com/trend/cloudone/amaas/AMaasFileReaderTest.java b/src/test/java/com/trend/cloudone/amaas/AMaasFileReaderTest.java index 01f4114..0008e5f 100644 --- a/src/test/java/com/trend/cloudone/amaas/AMaasFileReaderTest.java +++ b/src/test/java/com/trend/cloudone/amaas/AMaasFileReaderTest.java @@ -16,7 +16,7 @@ public class AMaasFileReaderTest { @Test - public void testAMaasFileReader_FileNotFound() { + public void testAMaasFileReaderFileNotFound() { String fileName = "abc.txt"; try { new AMaasFileReader(fileName); @@ -25,24 +25,24 @@ public void testAMaasFileReader_FileNotFound() { assertEquals(AMaasErrorCode.MSG_ID_ERR_FILE_NOT_FOUND, err.getErrorCode()); } } - + @Test - public void testAMaasFileReader_FileNoPermission() { + public void testAMaasFileReaderFileNoPermission() { String fileName = DataFileCreator.TEST_DATA_FILE_NAME; File newFile = null; try { newFile = new File(fileName); - newFile.setReadable(false); + newFile.setReadable(false); new AMaasFileReader(fileName); fail(); } catch (AMaasException err) { assertEquals(AMaasErrorCode.MSG_ID_ERR_FILE_NO_PERMISSION, err.getErrorCode()); } finally { - newFile.setReadable(true); + newFile.setReadable(true); } } - + @Test public void testReadBytes() { @@ -51,11 +51,11 @@ public void testReadBytes() { assertEquals(fileReader.getIdentifier(), DataFileCreator.TEST_DATA_FILE_NAME); long len = fileReader.getLength(); Random rand = new Random(); - int offset = rand.nextInt((int)len); - int size = rand.nextInt((int)len - offset); + int offset = rand.nextInt((int) len); + int size = rand.nextInt((int) len - offset); byte[] buf = new byte[size]; fileReader.readBytes(offset, buf); - DataFileCreator.verifyBufWithData(buf, offset); + DataFileCreator.verifyBufWithData(buf, offset); } catch (Exception err) { err.printStackTrace(); assert false; @@ -66,7 +66,7 @@ public void testReadBytes() { public void testFileHashes() { try { String fileName = "data.txt"; - String path = getClass(). getClassLoader(). getResource(""). getPath(); + String path = getClass().getClassLoader().getResource("").getPath(); String sha1 = "sha1:98026e8c073707b779b0c4b922884d078cf6e110"; String sha256 = "sha256:67ee709d8a925003d817a98eae4c12f98193f7a44bc262d93e6265c41bf096f5"; diff --git a/src/test/java/com/trend/cloudone/amaas/AMaasScanResultTest.java b/src/test/java/com/trend/cloudone/amaas/AMaasScanResultTest.java index fb8eacc..ee2f0b2 100644 --- a/src/test/java/com/trend/cloudone/amaas/AMaasScanResultTest.java +++ b/src/test/java/com/trend/cloudone/amaas/AMaasScanResultTest.java @@ -29,7 +29,7 @@ public void testBadResult() { String fileName = "file1"; String scanId = "scan123"; int scanResult = 1; - MalwareItem[] foundMalwares = new MalwareItem[] { new MalwareItem("malware1", "file1"), new MalwareItem("malware1", "file1")}; + MalwareItem[] foundMalwares = new MalwareItem[] {new MalwareItem("malware1", "file1"), new MalwareItem("malware1", "file1")}; AMaasScanResult result = new AMaasScanResult(version, scanResult, scanId, ts, fileName, foundMalwares); assertEquals(version, result.getVersion()); assertEquals(scanResult, result.getScanResult()); @@ -46,7 +46,7 @@ public void testSetBadResult() { String scanId = "scan123"; int scanResult = 0; AMaasScanResult result = new AMaasScanResult(version, scanResult, scanId, ts, fileName, null); - MalwareItem[] foundMalwares = new MalwareItem[] { new MalwareItem("malware1", "file1"), new MalwareItem("malware1", "file1")}; + MalwareItem[] foundMalwares = new MalwareItem[] {new MalwareItem("malware1", "file1"), new MalwareItem("malware1", "file1")}; result.setFoundMalwares(foundMalwares); result.setScanResult(1); assertEquals(version, result.getVersion()); diff --git a/src/test/java/com/trend/cloudone/amaas/DataFileCreator.java b/src/test/java/com/trend/cloudone/amaas/DataFileCreator.java index e652529..4c1e473 100644 --- a/src/test/java/com/trend/cloudone/amaas/DataFileCreator.java +++ b/src/test/java/com/trend/cloudone/amaas/DataFileCreator.java @@ -6,15 +6,24 @@ import java.io.IOException; -public class DataFileCreator { +public final class DataFileCreator { + /** + * Name of test data file. + */ public static final String TEST_DATA_FILE_NAME = "test_data.bin"; private static final int NUM_DATA_LOOP = 10; + private static final int MAX_POSN_OFFSET = 256; + private DataFileCreator() { + } + /** + * Create a data file for testing. + */ public static void createDataFile() { try (FileOutputStream binaryFile = new FileOutputStream(TEST_DATA_FILE_NAME)) { for (int j = 0; j < NUM_DATA_LOOP; j++) { - for (int i = 0; i < 256; i++) { + for (int i = 0; i < MAX_POSN_OFFSET; i++) { // Convert the number to a single byte and write to the file byte byteValue = (byte) i; binaryFile.write(byteValue); @@ -25,20 +34,26 @@ public static void createDataFile() { } } - + /** + * Delete a data file. + */ public static void deleteDataFile() { - File file = new File(TEST_DATA_FILE_NAME); - if (file.exists()){ + File file = new File(TEST_DATA_FILE_NAME); + if (file.exists()) { file.delete(); - } + } } - - public static void verifyBufWithData(byte[] buf, int offset) { + /** + * Verify the content in the data buffer. + * @param buf Buffer to be verified. + * @param offset the offset to used. + */ + public static void verifyBufWithData(final byte[] buf, final int offset) { int blen = buf.length; int cnt = 0; for (int posn = offset; posn < blen; posn++) { - int val = posn % 256; + int val = posn % MAX_POSN_OFFSET; byte byteValue = (byte) val; //System.out.println(byteValue); //System.out.println(buf[cnt] ); diff --git a/src/test/java/com/trend/cloudone/amaas/MalwareItemTest.java b/src/test/java/com/trend/cloudone/amaas/MalwareItemTest.java index f940bf6..930462b 100644 --- a/src/test/java/com/trend/cloudone/amaas/MalwareItemTest.java +++ b/src/test/java/com/trend/cloudone/amaas/MalwareItemTest.java @@ -42,7 +42,7 @@ public void testSetMalwareName() { public void testMalwareNameEquality() { MalwareItem item1 = new MalwareItem("malware1", "file1"); MalwareItem item2 = new MalwareItem("malware1", "file1"); - assert(item1.equals(item2)); + assert (item1.equals(item2)); assertEquals(item1.hashCode(), item2.hashCode()); item2.setFileName("file3"); assertFalse(item1.equals(item2)); @@ -50,15 +50,14 @@ public void testMalwareNameEquality() { //reset item2.setFileName("file1"); - assert(item1.equals(item2)); + assert (item1.equals(item2)); item1.setMalwareName("malware3"); assertFalse(item1.equals(item2)); - + item1.setMalwareName(null); assertFalse(item1.equals(item2)); item2.setMalwareName(null); - assert(item1.equals(item2)); - + assert (item1.equals(item2)); } } diff --git a/src/test/java/com/trend/cloudone/amaas/MockScanServicer.java b/src/test/java/com/trend/cloudone/amaas/MockScanServicer.java index eb9f977..e0d6e70 100644 --- a/src/test/java/com/trend/cloudone/amaas/MockScanServicer.java +++ b/src/test/java/com/trend/cloudone/amaas/MockScanServicer.java @@ -16,18 +16,18 @@ import static org.junit.Assert.assertEquals; -public class MockScanServicer extends ScanGrpc.ScanImplBase { - final static String IDENTIFIER_VIRUS = "virus"; - final static String IDENTIFIER_UNKNOWN_CMD = "unknown_cmd"; - final static String IDENTIFIER_MISMATCHED = "mismatched"; - final static String IDENTIFIER_GRPC_ERROR = "grpc_error"; - final static String IDENTIFIER_EXCEED_RATE = "exceed_rate"; - final static String IDENTIFIER_CHECK_HASH = "check_hash"; - final static Command UNKNOWN_CMD = Command.UNRECOGNIZED; - final static String[] MYTAGS = new String[] {"tag1" , "tag2"}; +public final class MockScanServicer extends ScanGrpc.ScanImplBase { + static final String IDENTIFIER_VIRUS = "virus"; + static final String IDENTIFIER_UNKNOWN_CMD = "unknown_cmd"; + static final String IDENTIFIER_MISMATCHED = "mismatched"; + static final String IDENTIFIER_GRPC_ERROR = "grpc_error"; + static final String IDENTIFIER_EXCEED_RATE = "exceed_rate"; + static final String IDENTIFIER_CHECK_HASH = "check_hash"; + static final Command UNKNOWN_CMD = Command.UNRECOGNIZED; + static final String[] MYTAGS = new String[] {"tag1", "tag2"}; private static final int MAX_RUN = 5; - private final S2C FINAL_MSG = S2C.newBuilder() + private final S2C finalMsg = S2C.newBuilder() .setStage(Stage.STAGE_FINI) .setCmd(Command.CMD_QUIT) .build(); @@ -60,7 +60,7 @@ private S2C getUnknwonCmd() { .setLength(end - start) .build(); } - + private S2C getMismatchedCmdStage() { int start = random.nextInt(fsize); @@ -73,7 +73,7 @@ private S2C getMismatchedCmdStage() { .build(); } - private S2C processRequest(C2S req) { + private S2C processRequest(final C2S req) { S2C msg = null; if (req.getStage() == Stage.STAGE_INIT) { this.fsize = req.getRsSize(); @@ -84,7 +84,7 @@ private S2C processRequest(C2S req) { assertEquals(req.getTags(indx), MYTAGS[indx]); } } - + if (this.identifier == IDENTIFIER_CHECK_HASH) { String sha1 = "sha1:e4d5a3a79140b1c141f947efef6a7372c8f2bbc4"; String sha256 = "sha256:c24f43025bc40b53e4e5948cf69cb59498b47d2127cf358de846cda6fefccc63"; @@ -107,9 +107,9 @@ private S2C processRequest(C2S req) { //context.set_details("Http Error Code: 429"); //context.set_code(grpc.StatusCode.INTERNAL); //msg = ""; - + msg = null; } else if (this.count >= MAX_RUN) { - msg = FINAL_MSG.toBuilder() + msg = finalMsg.toBuilder() .setResult(getResultJson()) .build(); } else { @@ -126,14 +126,14 @@ private S2C processRequest(C2S req) { } @Override - public StreamObserver run(StreamObserver responseObserver) { - + public StreamObserver run(final StreamObserver responseObserver) { + return new StreamObserver() { @Override - public void onNext(C2S request) { + public void onNext(final C2S request) { S2C resp = processRequest(request); - if (resp==null) { + if (resp == null) { Status status = Status.INTERNAL; responseObserver.onError(status.asRuntimeException()); } @@ -141,7 +141,7 @@ public void onNext(C2S request) { } @Override - public void onError(Throwable t) { + public void onError(final Throwable t) { responseObserver.onError(t); } diff --git a/src/test/java/com/trend/cloudone/amaas/TestRunner.java b/src/test/java/com/trend/cloudone/amaas/TestRunner.java index 14f2e77..a093e27 100644 --- a/src/test/java/com/trend/cloudone/amaas/TestRunner.java +++ b/src/test/java/com/trend/cloudone/amaas/TestRunner.java @@ -6,15 +6,17 @@ import org.junit.runner.notification.Failure; -public class TestRunner { +public final class TestRunner { + private TestRunner() { + } - public static void main(String[] args) { + public static void main(final String[] args) { Result result = JUnitCore.runClasses(TestSuite.class); - + for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } - + System.out.println(result.wasSuccessful()); } } diff --git a/src/test/java/com/trend/cloudone/amaas/TestSuite.java b/src/test/java/com/trend/cloudone/amaas/TestSuite.java index cf038a6..85e7815 100644 --- a/src/test/java/com/trend/cloudone/amaas/TestSuite.java +++ b/src/test/java/com/trend/cloudone/amaas/TestSuite.java @@ -22,22 +22,22 @@ }) -public class TestSuite { - +public final class TestSuite { + private TestSuite() { + } + @BeforeClass public static void setUpClass() throws Exception { - + DataFileCreator.createDataFile(); MockScanServicer servicer = new MockScanServicer(); String uniqueName = InProcessServerBuilder.generateName(); InProcessServerBuilder.forName(uniqueName).directExecutor().addService(servicer).build().start(); } - + @AfterClass public static void tearDownClass() { - DataFileCreator.deleteDataFile(); } - }