diff --git a/.classpath b/.classpath deleted file mode 100644 index cc9b24a..0000000 --- a/.classpath +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 19e4f86..356e116 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ *.class *.DS_Store *.log +*.classpath # Package Files # *.jar @@ -8,3 +9,4 @@ *.ear /bin /target +/lib diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 104c8ec..a74a93a 100644 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -1,4 +1,6 @@ eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test=UTF-8 +encoding//src/test/java=UTF-8 encoding/=UTF-8 encoding/src=UTF-8 -encoding/test=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 9dc5cdd..04ecf1b 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,8 +1,12 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate @@ -13,19 +17,20 @@ org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.APILeak=warning org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=warning org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning org.eclipse.jdt.core.compiler.problem.deadCode=warning org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=enabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=warning org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=warning -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning @@ -43,7 +48,7 @@ org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=default org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=warning org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=enabled org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning @@ -62,40 +67,49 @@ org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=warni org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=warning org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=warning org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=warning org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning +org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=warning org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled +org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=disabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=disabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=enabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedImport=warning org.eclipse.jdt.core.compiler.problem.unusedLabel=warning org.eclipse.jdt.core.compiler.problem.unusedLocal=warning @@ -105,6 +119,7 @@ org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference= org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index 8e61d94..8905fc9 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -1,4 +1,5 @@ + diff --git a/README.md b/README.md index ee9e779..a94ee71 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # ImageOptimization - Library for losslessly optimizing images # -Copyright (c) 2016, Salesforce.com. All rights reserved. +Copyright (c) 2018, Salesforce.com. All rights reserved. Created by - + ## Summary ## @@ -15,9 +15,9 @@ Apart from optimizing an image, it also supports a few other things * Create a Chrome (browser) specific version, [WebP](https://developers.google.com/speed/webp/?csw=1) * Automated validation of images. -## Installation ## +## Compilation ## -### Prerequisites ### +Aside from using maven for compilation, we also require a few binaries that need to be compiled. Please download and compile these apps. * Some version of **Git** * If you are on the Mac, you should already have the command line version of git installed. @@ -60,13 +60,16 @@ OS name: "mac os x", version: "10.10.1", arch: "x86_64", family: "mac" ## Usage ## -There are 2 ways that the library can be used: +Before starting there are a few prerequisites +* ImageMagick needs to be installed on the system (used for converting images because JAVA cannot handle certain file types) +* This only works on Linux and has only been tested on Ubuntu. There are a number of non-java binaries that come with this project and they have only been compiled for Linux, specifically Ubuntu. +
There are 2 ways that the library can be used:
Calling the main method from the commandline with a list of files or folders. java -jar ImageOptimization-1.2.jar -DbinariesDirectory= path/to/image.png path/to/folder/of/images/ -The `` is the path where the binaries exist that are used to optimize the images. By default the code will look for the binaries in the `./lib/binary/linux/` directory +The `` is the path where the binaries exist that are used to optimize the images. The binaries are currently in the [`lib/binary/linux/`](https://git.soma.salesforce.com/perfeng/ImageOptimization/tree/master/lib/binary/linux) directory You can also call this code programmatically from existing JAVA code by using the API, `com.salesforce.perfeng.uiperf.imageoptimization.service.ImageOptimizationService.optimizeAllImages(FileTypeConversion, boolean, Collection)`. @@ -85,9 +88,9 @@ The function returns a list of `OptimizationResult` objects. ### How is the Optimization Actually Accomplished? ### -The heavy lifing is done by 6 different binary applications: [advpng](http://advancemame.sourceforge.net/doc-advpng.html), [gifsicle](http://www.lcdf.org/gifsicle/), [jfifremove](https://lyncd.com/files/imgopt/jfifremove.c), [jpegtran](http://jpegclub.org/jpegtran/), [optipng](http://optipng.sourceforge.net/), [pngout](http://advsys.net/ken/utils.htm), [pngquant](https://pngquant.org/). +The heavy lifting is done by 7 different binary applications: [advpng](http://advancemame.sourceforge.net/doc-advpng.html), [gifsicle](https://www.lcdf.org/gifsicle/), [jfifremove](https://lyncd.com/files/imgopt/jfifremove.c), [jpegtran](http://jpegclub.org/jpegtran/), [optipng](http://optipng.sourceforge.net/), [pngout](http://advsys.net/ken/utils.htm), [pngquant](https://pngquant.org/). -The JAVA code calls out to these binaries and using the appropriate ones for the image format. The code does this twice. For some reason passing in an already optimized image will result in a few bytes reduction the second time it is optimized. +The JAVA code calls out to these binaries and uses the appropriate ones for the image format. The code does this twice. For some reason, passing in an already optimized image will result in a few bytes reduction the second time it is optimized. For converting the images we use 3 binaries: [ImageMagick](http://www.imagemagick.org/), [cwebp](https://developers.google.com/speed/webp/docs/cwebp), [gif2webp](https://developers.google.com/speed/webp/docs/gif2webp). @@ -98,4 +101,4 @@ The way it works is 1. It will take the original image, render it, and gather all of the pixels in an array. 2. It does the same thing for the optimized image. -3. Iterate over each array and compare the RGBA values of the pixel at spot `i`. If the pixels are identical, it passes. If the pixels are different and the alpha channel on both pixels is 100% transparent then the color does not matter and the pixels are considered identical. Any other difference will be considered a failure. +3. Iterate over each array and compare the RGBA values of the pixel at spot `i`. If the pixels are identical then it passes. If the pixels are different and the alpha channel on both pixels is 100% transparent then the color does not matter and the pixels are considered identical. Any other difference will be considered a failure. diff --git a/pom.xml b/pom.xml index 1400fd4..fa96b60 100644 --- a/pom.xml +++ b/pom.xml @@ -1,117 +1,252 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.salesforce.perfeng.uiperf - ImageOptimization - 1.5.0 - jar + com.salesforce.perfeng.uiperf + ImageOptimization + 1.6.0 + jar - ImageOptimization - https://github.com/SalesforceEng/ImageOptimization + ImageOptimization + https://github.com/salesforce/ImageOptimization - - Salesforce - https://www.salesforce.com - - Library used to optimize images so that they are smaller in size (less bytes) while maintaining the exact same quality. + + Salesforce + https://www.salesforce.com + + Library used to optimize images so that they are smaller in size (less bytes) while maintaining the exact same quality. It can also... 1) convert gif to png 2) convert images to webp -Note: It only runs on Linux and requires additional binaries - 2013 - - scm:git:git://github.com/SalesforceEng/ImageOptimization - scm:git:github.com/SalesforceEng/ImageOptimization - https://github.com/SalesforceEng/ImageOptimization - - - - - The BSD 3-Clause License - http://opensource.org/licenses/BSD-3-Clause - repo - - +Note: It only runs on Linux and requires additional binaries from https://github.com/salesforce/ImageOptimization/tree/master/lib/binary/linux + 2013 + + scm:git:https://github.com/salesforce/ImageOptimization + scm:git:git@github.com:salesforce/ImageOptimization.git + https://github.com/salesforce/ImageOptimization + HEAD + - - - eperret - Eric Perret - eperret@salesforce.com - - + + + The BSD 3-Clause License + http://opensource.org/licenses/BSD-3-Clause + repo + + - - UTF-8 - UTF-8 - 1.8 - 1.8 - + + + eperret + Eric Perret + eperret@salesforce.com + Salesforce + https://www.salesforce.com + + owner + developer + + -8 + + - - - junit - junit - 4.12 - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - - org.slf4j - slf4j-simple - 1.7.13 - - - commons-io - commons-io - 2.4 - - - org.apache.httpcomponents - httpclient - 4.5.1 - - - org.webjars - svgo - 0.3.7-1 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - 8 - 8 - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - - jar - - - - - - src - test - bin - bin - - + + GitHub Issues + https://github.com/salesforce/ImageOptimization/issues + + + + UTF-8 + UTF-8 + 1.8 + 1.8 + true + + + + + org.slf4j + slf4j-simple + 1.7.25 + + + commons-io + commons-io + 2.6 + + + org.apache.httpcomponents + httpclient + 4.5.4 + + + + com.twelvemonkeys.imageio + imageio-batik + 3.3.2 + + + + org.apache.xmlgraphics + xmlgraphics-commons + 2.2 + + + org.apache.xmlgraphics + batik-transcoder + 1.9.1 + + + org.apache.xmlgraphics + batik-codec + 1.9.1 + + + org.junit.jupiter + junit-jupiter-api + 5.1.0-M1 + test + + + + org.junit.platform + junit-platform-launcher + 1.1.0-M1 + test + + + + org.junit.jupiter + junit-jupiter-engine + 5.1.0-M1 + test + + + + org.apiguardian + apiguardian-api + 1.0.0 + test + + + org.hamcrest + java-hamcrest + 2.0.0.0 + test + + + + + + maven-compiler-plugin + 3.7.0 + + + default-testCompile + test-compile + + testCompile + + + 8 + 8 + + + + default-compile + compile + + compile + + + 8 + 8 + + + + + 8 + 8 + + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + attach-sources + post-integration-test + + jar + + + + + + maven-javadoc-plugin + 3.0.0 + + true + -Xdoclint:-html + + + + attach-docs + post-integration-test + + jar + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + + + com.salesforce.perfeng.uiperf.imageoptimization.Main + + + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + ${skip.unit.tests} + + + + org.junit.platform + junit-platform-surefire-provider + 1.1.0-M1 + + + org.junit.jupiter + junit-jupiter-engine + 5.1.0-M1 + + + + + + +
\ No newline at end of file diff --git a/src/META-INF/MANIFEST.MF b/src/META-INF/MANIFEST.MF deleted file mode 100644 index 5e94951..0000000 --- a/src/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - diff --git a/src/log4j2.xml b/src/log4j2.xml deleted file mode 100644 index 83b804d..0000000 --- a/src/log4j2.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/src/com/salesforce/perfeng/uiperf/ThirdPartyBinaryNotFoundException.java b/src/main/java/com/salesforce/perfeng/uiperf/ThirdPartyBinaryNotFoundException.java similarity index 100% rename from src/com/salesforce/perfeng/uiperf/ThirdPartyBinaryNotFoundException.java rename to src/main/java/com/salesforce/perfeng/uiperf/ThirdPartyBinaryNotFoundException.java diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/Main.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/Main.java similarity index 89% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/Main.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/Main.java index e8298b8..a2d4421 100644 --- a/src/com/salesforce/perfeng/uiperf/imageoptimization/Main.java +++ b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/Main.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014, Salesforce.com, Inc. + * Copyright (c) 2017, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -35,6 +35,8 @@ import static com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService.JPEG_MIME_TYPE; import static com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService.PNG_EXTENSION; import static com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService.PNG_MIME_TYPE; +import static com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService.SVG_EXTENSION; +import static com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService.SVG_MIME_TYPE; import java.io.BufferedInputStream; import java.io.File; @@ -52,7 +54,6 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; -import org.apache.http.annotation.Immutable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,12 +64,11 @@ import com.salesforce.perfeng.uiperf.imageoptimization.utils.ImageFileOptimizationException; /** - * Class to run the image optimization against a specified directory. Used - * primarily for testing. + * Class to run the image optimization against a specified directory. Used primarily for testing. This class is + * immutable. * * @author eperret (Eric Perret) */ -@Immutable public class Main { /** @@ -136,16 +136,20 @@ public static void main(final String[] args) throws ImageFileOptimizationExcepti * {@code false}. */ private static final boolean isValidContentType(final String contentType, final String extension) { - if(PNG_EXTENSION.equals(extension)) { - return PNG_MIME_TYPE.equals(contentType); + switch(extension) { + case PNG_EXTENSION: + return PNG_MIME_TYPE.equals(contentType); + case GIF_EXTENSION: + return GIF_MIME_TYPE.equals(contentType); + case JPEG_EXTENSION: + case JPEG_EXTENSION2: + case JPEG_EXTENSION3: + return JPEG_MIME_TYPE.equals(contentType); + case SVG_EXTENSION: + return SVG_MIME_TYPE.equals(contentType) || (contentType == null); + default: + return false; } - if(GIF_EXTENSION.equals(extension)) { - return GIF_MIME_TYPE.equals(contentType); - } - if(JPEG_EXTENSION.equals(extension) || JPEG_EXTENSION2.equals(extension) || JPEG_EXTENSION3.equals(extension)) { - return JPEG_MIME_TYPE.equals(contentType); - } - return false; } /** @@ -161,11 +165,10 @@ private static List getAllImages(final String... rootDirectories) throws I final List images = new ArrayList<>(); for(final String rootDirectory : rootDirectories) { logger.info("Starting with {} at {}", rootDirectory, new Date()); - InputStream is = null; + final Collection c = FileUtils.listFiles(new File(rootDirectory), IImageOptimizationService.SUPPORTED_FILE_EXTENSIONS, true); for(final File image : c) { - try { - is = new BufferedInputStream(new FileInputStream(image)); + try(final InputStream is = new BufferedInputStream(new FileInputStream(image))) { final String contentType = URLConnection.guessContentTypeFromStream(is); if(isValidContentType(contentType, FilenameUtils.getExtension(image.getName()).toLowerCase())) { @@ -173,19 +176,10 @@ private static List getAllImages(final String... rootDirectories) throws I } else if(image.length() > 0) { logger.warn("Skipping file. Unexpected content type for file\n\tfile: {}\n\tcontentType: {}", image.getPath(), contentType); } - } finally { - if(is != null) { - try { - is.close(); - } catch (final IOException ignore) { - // If we can't close it then there is nothing we can - // do and should move on. - } - } } } - logger.info("Done with {} at {}", rootDirectory, new Date()); + logger.info("Done with {} at {}.", rootDirectory, new Date()); logger.info("Found {} images.", Integer.valueOf(images.size())); } diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/dto/OptimizationResult.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/dto/OptimizationResult.java similarity index 100% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/dto/OptimizationResult.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/dto/OptimizationResult.java diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/service/IImageOptimizationService.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/service/IImageOptimizationService.java similarity index 94% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/service/IImageOptimizationService.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/service/IImageOptimizationService.java index 036d8f2..30953d0 100644 --- a/src/com/salesforce/perfeng/uiperf/imageoptimization/service/IImageOptimizationService.java +++ b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/service/IImageOptimizationService.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014, Salesforce.com, Inc. + * Copyright (c) 2017, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -84,6 +84,14 @@ public interface IImageOptimizationService { * The WebP mime type. */ public final static String WEBP_MIME_TYPE = "image/webp"; + /** + * The SVG extension. + */ + public final static String SVG_EXTENSION = "svg"; + /** + * The SVG mime type. + */ + public final static String SVG_MIME_TYPE = "image/svg+xml"; /** *

Used by the image optimization service to indicate if and how images @@ -129,7 +137,7 @@ public final static boolean isEnabled(final FileTypeConversion fileTypeConversio * The complete list of supported file extensions that the service will * optimize. */ - public final static String[] SUPPORTED_FILE_EXTENSIONS = {PNG_EXTENSION, JPEG_EXTENSION, GIF_EXTENSION, JPEG_EXTENSION2, JPEG_EXTENSION3, PNG_EXTENSION.toUpperCase(), JPEG_EXTENSION.toUpperCase(), GIF_EXTENSION.toUpperCase(), JPEG_EXTENSION2.toUpperCase(), JPEG_EXTENSION3.toUpperCase()}; + public final static String[] SUPPORTED_FILE_EXTENSIONS = {PNG_EXTENSION, JPEG_EXTENSION, GIF_EXTENSION, JPEG_EXTENSION2, JPEG_EXTENSION3, SVG_EXTENSION, PNG_EXTENSION.toUpperCase(), JPEG_EXTENSION.toUpperCase(), GIF_EXTENSION.toUpperCase(), JPEG_EXTENSION2.toUpperCase(), JPEG_EXTENSION3.toUpperCase(), SVG_EXTENSION.toUpperCase()}; /** * This method will try to optimize all of the passed in images. diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationService.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationService.java similarity index 86% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationService.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationService.java index 7b61f10..67e7a50 100644 --- a/src/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationService.java +++ b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationService.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014, Salesforce.com, Inc. + * Copyright (c) 2017, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,6 +31,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; @@ -56,8 +57,6 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; -import org.apache.http.annotation.Immutable; -import org.apache.http.annotation.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,16 +65,15 @@ import com.salesforce.perfeng.uiperf.imageoptimization.utils.FixedFileUtils; import com.salesforce.perfeng.uiperf.imageoptimization.utils.ImageFileOptimizationException; import com.salesforce.perfeng.uiperf.imageoptimization.utils.ImageUtils; +import com.salesforce.perfeng.uiperf.imageoptimization.utils.ImagesEqual; /** - * Service used to perform the optimization of images. + * Service used to perform the optimization of images. This class is Immutable and ThreadSafe. * * @author eperret (Eric Perret) * @since 186.internal * @param Contains the changeList information. */ -@Immutable -@ThreadSafe public class ImageOptimizationService implements IImageOptimizationService { /** @@ -98,6 +96,11 @@ public class ImageOptimizationService implements IImageOptimizationService * image. */ static final String PNG_ERROR_MESSAGE; + /** + * Internal error message used when an error occurred while optimizing a PNG + * image. + */ + static final String SVG_ERROR_MESSAGE; /** * Internal error message used when an error occurred while converting an * image to WEBP. @@ -109,74 +112,77 @@ public class ImageOptimizationService implements IImageOptimizationService GIF_ERROR_MESSAGE = String.format(common, "optimizing", IImageOptimizationService.GIF_EXTENSION.toUpperCase()); JPEG_ERROR_MESSAGE = String.format(common, "optimizing", IImageOptimizationService.JPEG_EXTENSION.toUpperCase()); PNG_ERROR_MESSAGE = String.format(common, "optimizing", IImageOptimizationService.PNG_EXTENSION.toUpperCase()); + SVG_ERROR_MESSAGE = String.format(common, "optimizing", IImageOptimizationService.SVG_EXTENSION.toUpperCase()); WEBP_ERROR_MESSAGE = String.format(common, "converting to", IImageOptimizationService.WEBP_EXTENSION.toUpperCase()); } /** - * Name of the "cwebp" binary application used to convert a - * non-{@value IImageOptimizationService#GIF_MIME_TYPE} file to a - * {@value IImageOptimizationService#WEBP_MIME_TYPE} file. + * Name of the "cwebp" binary application used to convert a non-{@value IImageOptimizationService#GIF_MIME_TYPE} + * file to a {@value IImageOptimizationService#WEBP_MIME_TYPE} file. */ protected static final String CWEBP_BINARY = "cwebp"; /** - * Name of the {@value #GIF2WEBP_BINARY} binary application used to convert - * a {@value IImageOptimizationService#GIF_MIME_TYPE} file to a - * {@value IImageOptimizationService#WEBP_MIME_TYPE} file. + * Name of the {@value #GIF2WEBP_BINARY} binary application used to convert a + * {@value IImageOptimizationService#GIF_MIME_TYPE} file to a {@value IImageOptimizationService#WEBP_MIME_TYPE} + * file. */ protected static final String GIF2WEBP_BINARY = "gif2webp"; /** - * Name of the {@value #GIFSICLE_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#GIF_MIME_TYPE} file. + * Name of the {@value #GIFSICLE_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#GIF_MIME_TYPE} file. */ protected static final String GIFSICLE_BINARY = "gifsicle"; /** - * Name of the {@value #JPEGTRAN_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#JPEG_MIME_TYPE} file. On linux this - * app requires libjpeg62 to be installed. Run + * Name of the {@value #JPEGTRAN_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#JPEG_MIME_TYPE} file. On linux this app requires libjpeg62 to be installed. Run * "sudo apt-get install libjpeg62:i386". */ protected static final String JPEGTRAN_BINARY = "jpegtran"; /** - * Name of the {@value #JFIFREMOVE_BINARY} binary application used to - * optimize a {@value IImageOptimizationService#JPEG_MIME_TYPE} file. + * Name of the {@value #JFIFREMOVE_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#JPEG_MIME_TYPE} file. */ protected static final String JFIFREMOVE_BINARY = "jfifremove"; /** - * Name of the {@value #ADVPNG_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Name of the {@value #ADVPNG_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected static final String ADVPNG_BINARY = "advpng"; /** - * Name of the {@value #OPTIPNG_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Name of the {@value #OPTIPNG_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected static final String OPTIPNG_BINARY = "optipng"; /** - * Name of the {@value #PNGOUT_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Name of the {@value #PNGOUT_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected static final String PNGOUT_BINARY = "pngout"; /** - * Name of the {@value #PNGQUANT_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Name of the {@value #PNGQUANT_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected static final String PNGQUANT_BINARY = "pngquant"; + /** + * Name of the {@value #SVGOP_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#SVG_MIME_TYPE} file. + */ + protected static final String SVGOP_BINARY = "svgop"; /** - * Path of the "cwebp" binary application used to convert a - * non-{@value IImageOptimizationService#GIF_MIME_TYPE} file to a - * {@value IImageOptimizationService#WEBP_MIME_TYPE} file. + * Path of the "cwebp" binary application used to convert a non-{@value IImageOptimizationService#GIF_MIME_TYPE} + * file to a {@value IImageOptimizationService#WEBP_MIME_TYPE} file. */ protected final String cwebpBinaryPath; /** - * Path of the {@value #GIF2WEBP_BINARY} binary application used to convert - * a {@value IImageOptimizationService#GIF_MIME_TYPE} file to a - * {@value IImageOptimizationService#WEBP_MIME_TYPE} file. + * Path of the {@value #GIF2WEBP_BINARY} binary application used to convert a + * {@value IImageOptimizationService#GIF_MIME_TYPE} file to a {@value IImageOptimizationService#WEBP_MIME_TYPE} + * file. */ protected final String gif2webpBinaryPath; /** - * Path of the {@value #GIFSICLE_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#GIF_MIME_TYPE} file. + * Path of the {@value #GIFSICLE_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#GIF_MIME_TYPE} file. */ protected final String gifsicleBinaryPath; /** @@ -190,25 +196,30 @@ public class ImageOptimizationService implements IImageOptimizationService */ protected final String jfifremoveBinaryPath; /** - * Path of the {@value #ADVPNG_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Path of the {@value #ADVPNG_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected final String advpngBinaryPath; /** - * Path of the {@value #OPTIPNG_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Path of the {@value #OPTIPNG_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected final String optipngBinaryPath; /** - * Path of the {@value #PNGOUT_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Path of the {@value #PNGOUT_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected final String pngoutBinaryPath; /** - * Path of the {@value #PNGQUANT_BINARY} binary application used to optimize - * a {@value IImageOptimizationService#PNG_MIME_TYPE} file. + * Path of the {@value #PNGQUANT_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#PNG_MIME_TYPE} file. */ protected final String pngquantBinaryPath; + /** + * Path of the {@value #SVGOP_BINARY} binary application used to optimize a + * {@value IImageOptimizationService#SVG_MIME_TYPE} file. + */ + protected final String svgopBinaryPath; private final int MAX_NUMBER_OF_THREADS = Runtime.getRuntime().availableProcessors(); @@ -272,11 +283,12 @@ public ImageOptimizationService(final File tmpWorkingDirectory, final File binar jpegtranBinaryPath = binaryDirectoryPath + JPEGTRAN_BINARY; // Needs to be quoted because it is passed as an argument to the bash // command. - jfifremoveBinaryPath = '\"' + binaryDirectoryPath + JFIFREMOVE_BINARY + '\"'; + jfifremoveBinaryPath = '"' + binaryDirectoryPath + JFIFREMOVE_BINARY + '"'; advpngBinaryPath = binaryDirectoryPath + ADVPNG_BINARY; optipngBinaryPath = binaryDirectoryPath + OPTIPNG_BINARY; pngoutBinaryPath = binaryDirectoryPath + PNGOUT_BINARY; pngquantBinaryPath = binaryDirectoryPath + PNGQUANT_BINARY; + svgopBinaryPath = binaryDirectoryPath + SVGOP_BINARY; } /** @@ -407,20 +419,29 @@ private final List>> submitExecuteOptimization(fina final List>> futures = new ArrayList<>(2); - if(PNG_EXTENSION.equals(ext)) { - futures.add(completionService.submit(new ExecutePngOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); - if(includeWebPConversion) { - futures.add(completionService.submit(new ExecuteWebpConversion(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(IImageOptimizationService.WEBP_EXTENSION).append(file.getCanonicalPath()).toString()), false))); - } - } else if(GIF_EXTENSION.equals(ext)) { - futures.add(completionService.submit(new ExecuteGifOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); - if(includeWebPConversion) { - futures.add(completionService.submit(new ExecuteWebpConversion(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(IImageOptimizationService.WEBP_EXTENSION).append(file.getCanonicalPath()).toString()), true))); - } - } else if(JPEG_EXTENSION.equals(ext) || JPEG_EXTENSION2.equals(ext) || JPEG_EXTENSION3.equals(ext)) { - futures.add(completionService.submit(new ExecuteJpegOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); - } else { - throw new IllegalArgumentException("The passed in file has an unsupported file extension."); + switch(ext) { + case PNG_EXTENSION: + futures.add(completionService.submit(new ExecutePngOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); + if(includeWebPConversion) { + futures.add(completionService.submit(new ExecuteWebpConversion(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(IImageOptimizationService.WEBP_EXTENSION).append(file.getCanonicalPath()).toString()), false))); + } + break; + case SVG_EXTENSION: + futures.add(completionService.submit(new ExecuteSvgOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); + break; + case GIF_EXTENSION: + futures.add(completionService.submit(new ExecuteGifOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); + if(includeWebPConversion) { + futures.add(completionService.submit(new ExecuteWebpConversion(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(IImageOptimizationService.WEBP_EXTENSION).append(file.getCanonicalPath()).toString()), true))); + } + break; + case JPEG_EXTENSION: + case JPEG_EXTENSION2: + case JPEG_EXTENSION3: + futures.add(completionService.submit(new ExecuteJpegOptimization(file.getCanonicalFile(), new File(new StringBuilder(tmpImageWorkingDirectory).append(file.getCanonicalPath()).toString()), conversionType))); + break; + default: + throw new IllegalArgumentException("The passed in file has an unsupported file extension."); } return futures; } catch (final Exception e) { @@ -467,7 +488,7 @@ private final static void handleOptimizationFailure(final Process ps, final Stri try(final StringWriter writer = new StringWriter(); final InputStream is = ps.getInputStream()) { try { - IOUtils.copy(is, writer); + IOUtils.copy(is, writer, Charset.defaultCharset()); final StringBuilder errorMessage = new StringBuilder("Optimization failed with edit code: ").append(ps.exitValue()).append(". ").append(writer); if(ps.exitValue() == 127 /* command not found */) { throw new ThirdPartyBinaryNotFoundException(binaryApplicationName, "Most likely this is due to required libraries not being installed on the OS. On Ubuntu run \"sudo apt-get install libjpeg62:i386\".", new RuntimeException(errorMessage.toString())); @@ -853,9 +874,8 @@ final File executeCWebp(final File workingFile, final String workingFilePath) th } /** - * Executes the binary {@value #GIF2WEBP_BINARY} to convert the input file - * to a smaller file. The resulting image is only supported by Chrome and - * Opera + * Executes the binary {@value #GIF2WEBP_BINARY} to convert the input file to a smaller file. The resulting image is + * only supported by Chrome and Opera * * @param workingFile The file to convert * @param workingFilePath The path to the file to convert @@ -890,6 +910,34 @@ final File executeGif2Webp(final File workingFile, final String workingFilePath) return webpFile; } + + /** + * Executes the binary {@value #SVGOP_BINARY}" to optimize the input file. + * + * @param workingFile The file to optimize + * @param workingFilePath The path to the file to optimize + * @return the optimized file + * @throws InterruptedException If the optimization was interrupted. + * @throws ThirdPartyBinaryNotFoundException Thrown if the "svgop" application does not exist. + */ + final File executeSvgop(final File workingFile, final String workingFilePath) throws InterruptedException, ThirdPartyBinaryNotFoundException { + + final Process ps; + try { + //Can't redirect the Error stream because it is already redirecting + //the output. + //ps = new ProcessBuilder("bash", "-c", new StringBuilder(jfifremoveBinaryPath).append(" < ").append(escapedWorkingFilePath).append(" > ").append(escapedWorkingFilePath).append(".tmp2").toString()).start(); + ps = new ProcessBuilder("bash", "-c", new StringBuilder(svgopBinaryPath).append(" < \"").append(workingFilePath).append("\" > \"").append(workingFilePath).append(".tmp\"").toString()).start(); + } catch(final IOException ioe) { + throw new ThirdPartyBinaryNotFoundException(SVGOP_BINARY, ioe); + } + + if(waitFor(ps) != 0) { + handleOptimizationFailure(ps, SVGOP_BINARY, workingFile); + } + + return new File(workingFilePath + ".tmp"); + } private final class ExecutePngOptimization implements Callable> { @@ -930,7 +978,7 @@ public OptimizationResult call() { if(finalFile == null) { return null; } - return new OptimizationResult<>(finalFile, finalFile.length(), masterFile, masterFileSize, false, !ImageUtils.visuallyCompare(optimizedFile, masterFile), false); + return new OptimizationResult<>(finalFile, finalFile.length(), masterFile, masterFileSize, false, !ImagesEqual.visuallyCompare(optimizedFile, masterFile), false); } } catch(final ThirdPartyBinaryNotFoundException tpbnfe) { throw tpbnfe; @@ -1004,7 +1052,7 @@ public OptimizationResult call() { return null; } - return new OptimizationResult<>(finalFile, finalFile.length(), masterFile, masterFileSize, false, !ImageUtils.visuallyCompare(finalFile, masterFile), false); + return new OptimizationResult<>(finalFile, finalFile.length(), masterFile, masterFileSize, false, !ImagesEqual.visuallyCompare(finalFile, masterFile), false); } } catch(final ThirdPartyBinaryNotFoundException tpbnfe) { throw tpbnfe; @@ -1197,7 +1245,7 @@ public OptimizationResult call() { } final boolean automatedOptimizationFailed; try { - automatedOptimizationFailed = fileTypeChanged ? false : !ImageUtils.visuallyCompare(masterFile, optimizedFile); + automatedOptimizationFailed = fileTypeChanged ? false : !ImagesEqual.visuallyCompare(masterFile, optimizedFile); } catch(final ImageFileOptimizationException ifoe) { final Throwable cause = ifoe.getCause(); if((cause instanceof NullPointerException) && "getImageTypes".equals(cause.getStackTrace()[0].getMethodName())) { @@ -1224,6 +1272,64 @@ public OptimizationResult call() { return null; } } + + private final class ExecuteSvgOptimization implements Callable> { + + private final File masterFile; + private final File workingFile; + //TODO Support type conversions + private final FileTypeConversion conversionType; + + /** + * @param masterFile The original image + * @param workingFile The copy of the file to optimize + * @param conversionType If and how to handle converting images from one + * type to another. + */ + public ExecuteSvgOptimization(final File masterFile, final File workingFile, final FileTypeConversion conversionType) { + this.workingFile = workingFile; + this.masterFile = masterFile; + this.conversionType = conversionType; + } + + /** + * @see java.util.concurrent.Callable#call() + */ + @Override + public OptimizationResult call() { + + File optimizedFile = null; + try { + FixedFileUtils.copyFile(masterFile, workingFile); + + optimizedFile = executeSvgop(workingFile, workingFile.getCanonicalPath()); + + final long masterFileSize = masterFile.length(); + + if(optimizedFile.length() < masterFileSize) { + final File finalFile = copyFileToMinifiedDirectory(masterFile, optimizedFile, false); + if(finalFile == null) { + return null; + } + + return new OptimizationResult<>(finalFile, finalFile.length(), masterFile, masterFileSize, false, !ImagesEqual.visuallyCompare(finalFile, masterFile), false); + } + } catch(final ThirdPartyBinaryNotFoundException tpbnfe) { + throw tpbnfe; + } catch (final Exception e) { + logger.warn(SVG_ERROR_MESSAGE, new ImageFileOptimizationException(masterFile.getPath(), e)); + } finally { + if(optimizedFile != null) { + try { + FileUtils.forceDelete(optimizedFile.getParentFile()); + } catch (final IOException ioe) { + logger.warn("Error deleting temp file.", ioe); + } + } + } + return null; + } + } /** * @see com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService#getFinalResultsDirectory() diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/utils/FixedFileUtils.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/FixedFileUtils.java similarity index 100% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/utils/FixedFileUtils.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/FixedFileUtils.java diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageFileOptimizationException.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageFileOptimizationException.java similarity index 100% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageFileOptimizationException.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageFileOptimizationException.java diff --git a/src/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtils.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtils.java similarity index 66% rename from src/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtils.java rename to src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtils.java index 53c2a30..ed8b5cb 100644 --- a/src/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtils.java +++ b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtils.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2017, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of Salesforce.com nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ package com.salesforce.perfeng.uiperf.imageoptimization.utils; import java.awt.Graphics2D; @@ -8,10 +35,10 @@ import java.awt.image.ColorConvertOp; import java.awt.image.PixelGrabber; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.nio.charset.Charset; import java.util.Iterator; import javax.imageio.ImageIO; @@ -20,21 +47,17 @@ import javax.swing.ImageIcon; import org.apache.commons.io.IOUtils; -import org.apache.http.annotation.Immutable; -import org.apache.http.annotation.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.salesforce.perfeng.uiperf.ThirdPartyBinaryNotFoundException; /** - * Utility methods used to interact with images. + * Utility methods used to interact with images. This class is immutable and threadsafe. * * @author eperret (Eric Perret) * @since 186.internal */ -@Immutable -@ThreadSafe public class ImageUtils { private final static Logger logger = LoggerFactory.getLogger(ImageUtils.class); @@ -46,56 +69,6 @@ public class ImageUtils { */ static final String CONVERT_BINARY = "convert"; - private static final boolean equals(final int[] data1, final int[] data2) { - final int length = data1.length; - if (length != data2.length) { - logger.debug("File lengths are different."); - return false; - } - for(int i = 0; i < length; i++) { - if(data1[i] != data2[i]) { - - //If the alpha is 0 for both that means that the pixels are 100% - //transparent and the color does not matter. Return false if - //only 1 is 100% transparent. - if((((data1[i] >> 24) & 0xff) == 0) && (((data2[i] >> 24) & 0xff) == 0)) { - logger.debug("Both pixles at spot {} are different but 100% transparent.", Integer.valueOf(i)); - } else { - logger.debug("The pixel {} is different.", Integer.valueOf(i)); - return false; - } - } - } - logger.debug("Both groups of pixels are the same."); - return true; - } - - private static final int[] getPixels(final BufferedImage img, final File file) { - - final int width = img.getWidth(); - final int height = img.getHeight(); - int[] pixelData = new int[width * height]; - - final Image pixelImg; - if (img.getColorModel().getColorSpace() == ColorSpace.getInstance(ColorSpace.CS_sRGB)) { - pixelImg = img; - } else { - pixelImg = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(img, null); - } - - final PixelGrabber pg = new PixelGrabber(pixelImg, 0, 0, width, height, pixelData, 0, width); - - try { - if(!pg.grabPixels()) { - throw new RuntimeException(); - } - } catch (final InterruptedException ie) { - throw new ImageFileOptimizationException(file.getPath(), ie); - } - - return pixelData; - } - /** * Gets the {@link BufferedImage} from the passed in {@link File}. * @@ -103,10 +76,11 @@ private static final int[] getPixels(final BufferedImage img, final File file) { * @return The resulting BufferedImage */ @SuppressWarnings("unused") - final static BufferedImage getBufferedImage(final File file) { + final static BufferedImage getBufferedImage(File file) { + Image image; - - try (final FileInputStream inputStream = new FileInputStream(file)) { + + try { // ImageIO.read(file) is broken for some images so I went this // route image = Toolkit.getDefaultToolkit().createImage(file.getCanonicalPath()); @@ -116,60 +90,59 @@ final static BufferedImage getBufferedImage(final File file) { } catch(final Exception e2) { throw new ImageFileOptimizationException(file.getPath(), e2); } - - final BufferedImage converted = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); - final Graphics2D g2d = converted.createGraphics(); - g2d.drawImage(image, 0, 0, null); - g2d.dispose(); + + final BufferedImage converted; + if((image != null) && (image.getWidth(null) > 0) && (image.getHeight(null) > 0)) { + converted = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); + final Graphics2D g2d = converted.createGraphics(); + g2d.drawImage(image, 0, 0, null); + g2d.dispose(); + } else { + try { + converted = ImageIO.read(file); + } catch(final Exception e2) { + throw new ImageFileOptimizationException(file.getPath(), e2); + } + } return converted; } /** - * Compares file1 to file2 to see if they are the same based on a visual - * pixel by pixel comparison. This has issues with marking images different - * when they are not. Works perfectly for all images. - * - * @param file1 First file to compare - * @param file2 Second image to compare - * @return true if they are equal, otherwise - * false. - */ - private final static boolean visuallyCompareJava(final File file1, final File file2) { - return equals(getPixels(getBufferedImage(file1), file1), getPixels(getBufferedImage(file2), file2)); - } - - /** - * Compares file1 to file2 to see if they are the same based on a visual - * pixel by pixel comparison. This has issues with marking images different - * when they are not. Works perfectly for all images. + * Gets the array of pixels from the passed in {@link BufferedImage}. * - * @param file1 Image 1 to compare - * @param file2 Image 2 to compare - * @return true if both images are visually the same. + * @param img The image to get the pixels from + * @param file The file containing the image + * @return An array containing the pixels */ - public final static boolean visuallyCompare(final File file1, final File file2) { - - logger.debug("Start comparing \"{}\" and \"{}\".", file1.getPath(), file2.getPath()); + static final int[] getPixels(final BufferedImage img, final File file) { - if(file1 == file2) { - return true; - } - - boolean answer = visuallyCompareJava(file1, file2); - - if(!answer) { - logger.info("The files \"{}\" and \"{}\" are not pixel by pixel the same image. Manual comparison required.", file1.getPath(), file2.getPath()); + final int width = img.getWidth(); + final int height = img.getHeight(); + int[] pixelData = new int[width * height]; + + final Image pixelImg; + if (img.getColorModel().getColorSpace() == ColorSpace.getInstance(ColorSpace.CS_sRGB)) { + pixelImg = img; + } else { + pixelImg = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(img, null); + } + + final PixelGrabber pg = new PixelGrabber(pixelImg, 0, 0, width, height, pixelData, 0, width); + + try { + if(!pg.grabPixels()) { + throw new RuntimeException(); + } + } catch (final InterruptedException ie) { + throw new ImageFileOptimizationException(file.getPath(), ie); } - logger.debug("Finish comparing \"{}\" and \"{}\".", file1.getPath(), file2.getPath()); - - return answer; + return pixelData; } /** * @param file The image to check - * @return true if the image contains one or more pixels with - * some percentage of transparency (Alpha) + * @return {@code true} if the image contains one or more pixels with some percentage of transparency (Alpha) */ public final static boolean containsAlphaTransparency(final File file) { logger.debug("Start Alpha pixel check for {}.", file.getPath()); @@ -196,7 +169,7 @@ private final static void handleOptimizationFailure(final Process ps, final Stri try(final StringWriter writer = new StringWriter(); final InputStream is = ps.getInputStream()) { try { - IOUtils.copy(is, writer); + IOUtils.copy(is, writer, Charset.defaultCharset()); final StringBuilder errorMessage = new StringBuilder("Image conversion failed with edit code: ").append(ps.exitValue()).append(". ").append(writer); if(ps.exitValue() == 127 /* command not found */) { throw new ThirdPartyBinaryNotFoundException(binaryApplicationName, "Most likely this is due to ImageMagick not being installed on the OS. On Ubuntu run \"sudo apt-get install imagemagick\".", new RuntimeException(errorMessage.toString())); @@ -231,7 +204,7 @@ public final static void convertImageNative(final File fromImage, final File toI try { ps = new ProcessBuilder(CONVERT_BINARY, fromImage.getCanonicalPath(), toImage.getCanonicalPath()).start(); } catch(final IOException ioe) { - throw new ThirdPartyBinaryNotFoundException(CONVERT_BINARY, "Most likely this is due to ImageMagic not being installed on the OS. On Ubuntu run \"sudo apt-get install imagemagick\".", ioe); + throw new ThirdPartyBinaryNotFoundException(CONVERT_BINARY, "Most likely this is due to ImageMagick not being installed on the OS. On Ubuntu run, \"sudo apt-get install imagemagick\".", ioe); } if((ps.waitFor() != 0) || !toImage.exists()) { diff --git a/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImagesEqual.java b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImagesEqual.java new file mode 100644 index 0000000..34cd027 --- /dev/null +++ b/src/main/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImagesEqual.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (c) 2017, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of Salesforce.com nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ +package com.salesforce.perfeng.uiperf.imageoptimization.utils; + +import static com.salesforce.perfeng.uiperf.imageoptimization.utils.ImageUtils.getBufferedImage; +import static com.salesforce.perfeng.uiperf.imageoptimization.utils.ImageUtils.getPixels; + +import java.io.File; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author eperret (Eric Perret) + * + */ +public final class ImagesEqual { + + private final static Logger logger = LoggerFactory.getLogger(ImagesEqual.class); + + private static final boolean equals(final int[] data1, final int[] data2) { + final int length = data1.length; + if (length != data2.length) { + logger.debug("File lengths are different."); + return false; + } + for(int i = 0; i < length; i++) { + if(data1[i] != data2[i]) { + + //If the alpha is 0 for both that means that the pixels are 100% + //transparent and the color does not matter. Return false if + //only 1 is 100% transparent. + if((((data1[i] >> 24) & 0xff) == 0) && (((data2[i] >> 24) & 0xff) == 0)) { + logger.debug("Both pixles at spot {} are different but 100% transparent.", Integer.valueOf(i)); + } else { + logger.debug("The pixel {} is different.", Integer.valueOf(i)); + return false; + } + } + } + logger.debug("Both groups of pixels are the same."); + return true; + } + + /** + * Compares file1 to file2 to see if they are the same based on a visual + * pixel by pixel comparison. This has issues with marking images different + * when they are not. Works perfectly for all images. + * + * @param file1 First file to compare + * @param file2 Second image to compare + * @return true if they are equal, otherwise + * false. + */ + private final static boolean visuallyCompareJava(final File file1, final File file2) { + return equals(getPixels(getBufferedImage(file1), file1), getPixels(getBufferedImage(file2), file2)); + } + + /** + * Compares file1 to file2 to see if they are the same based on a visual + * pixel by pixel comparison. This has issues with marking images different + * when they are not. Works perfectly for all images. + * + * @param file1 Image 1 to compare + * @param file2 Image 2 to compare + * @return true if both images are visually the same. + */ + public final static boolean visuallyCompare(final File file1, final File file2) { + + if(file1 == null || file2 == null) { + throw new IllegalArgumentException("The passed in files cannot be null."); + } + if(!file1.canRead()) { + throw new IllegalArgumentException("The passed in file, \"" + file1.getPath() + "\", cannot be read or does not exist."); + } + if(!file2.canRead()) { + throw new IllegalArgumentException("The passed in file, \"" + file2.getPath() + "\", cannot be read or does not exist."); + } + + logger.debug("Start comparing \"{}\" and \"{}\".", file1.getPath(), file2.getPath()); + + if(file1 == file2) { + return true; + } + + boolean answer = visuallyCompareJava(file1, file2); + + if(!answer) { + logger.info("The files \"{}\" and \"{}\" are not pixel by pixel the same image. Manual comparison required.", file1.getPath(), file2.getPath()); + } + + logger.debug("Finish comparing \"{}\" and \"{}\".", file1.getPath(), file2.getPath()); + + return answer; + } +} diff --git a/src/main/java/log4j2.xml b/src/main/java/log4j2.xml new file mode 100644 index 0000000..6f59763 --- /dev/null +++ b/src/main/java/log4j2.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/DroidSans.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/DroidSans.svg new file mode 100644 index 0000000..a411a37 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/DroidSans.svg @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SVG Open 2009 + !"#$%&'()*+,-./0123456789:;<>? + @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ + `abcdefghijklmnopqrstuvwxyz|{}~ + + diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationServiceTest.java b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationServiceTest.java similarity index 54% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationServiceTest.java rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationServiceTest.java index f594581..70e1b1e 100644 --- a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationServiceTest.java +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/ImageOptimizationServiceTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014, Salesforce.com, Inc. + * Copyright (c) 2017, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -27,16 +27,25 @@ ******************************************************************************/ package com.salesforce.perfeng.uiperf.imageoptimization.service; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.lessThan; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.io.FileMatchers.aFileNamed; +import static org.hamcrest.io.FileMatchers.aFileWithSize; +import static org.hamcrest.io.FileMatchers.anExistingFile; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -46,9 +55,10 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; +import org.hamcrest.collection.IsEmptyCollection; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.salesforce.perfeng.uiperf.imageoptimization.dto.OptimizationResult; import com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService.FileTypeConversion; @@ -65,151 +75,193 @@ public class ImageOptimizationServiceTest { private static final String WEBP_ID = "|webp"; - private static final String DEFAULT_BINARY_APP_LOCATION; - static { + private static String defaultBinaryAppLocation; + + private ImageOptimizationService imageOptimizationService; + + /** + * Used to initialize the default location of the Linux binaries used by all of the tests. + */ + @BeforeAll + public static final void beforeClass() { if ("linux".equals(System.getProperty("os.name").toLowerCase())) { - DEFAULT_BINARY_APP_LOCATION = "./lib/binary/linux/"; + defaultBinaryAppLocation = "./lib/binary/linux/"; } else { - throw new UnsupportedOperationException("Your OS is not supported by this application. Currently only linux is supported"); + throw new UnsupportedOperationException("Your OS is not supported by this application. Currently only linux is supported."); } } - private ImageOptimizationService imageOptimizationService; - /** - * Used to initialize the {@link ImageOptimizationService} used by all of - * the tests. + * Used to initialize the {@link ImageOptimizationService} used by all of the tests. * * @throws IOException Thrown if there is a problem trying to initialize the * directories used by * {@link ImageOptimizationService#ImageOptimizationService(File, File)}. */ - @Before + @BeforeEach public void setUp() throws IOException { final File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); - imageOptimizationService = new ImageOptimizationService<>(tmpDir, new File(DEFAULT_BINARY_APP_LOCATION)); + imageOptimizationService = new ImageOptimizationService<>(tmpDir, new File(defaultBinaryAppLocation)); } /** - * Test method for - * {@link ImageOptimizationService#ImageOptimizationService(File, File)}. + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File)} to test that files cause an + * error. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationServicePassInFile() { + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(File.createTempFile("qqq", "qqq"), new File(defaultBinaryAppLocation)); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File)} to test that files cause an + * error. * - * @throws IOException Can be thrown by the - * ImageOptimizationService constructor if - * its passed in file has an issue. + * @throws IOException Can be thrown by the {@code ImageOptimizationService} constructor if its passed in file has + * an issue. */ - @SuppressWarnings("unused") + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationServicePassInFile2() throws IOException { + final File file = File.createTempFile("qqq", "qqq"); + file.createNewFile(); + file.deleteOnExit(); + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(file, new File(defaultBinaryAppLocation)); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File)} to test that files cause an + * error. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationServicePassInNullFolder() { + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(null, new File(defaultBinaryAppLocation)); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File)} + * + * @throws IOException Can be thrown by the {@code ImageOptimizationService} constructor if its passed in file has + * an issue. + */ + @SuppressWarnings("static-method") @Test public void testImageOptimizationService() throws IOException { - try { - new ImageOptimizationService<>(File.createTempFile("qqq", "qqq"), new File(DEFAULT_BINARY_APP_LOCATION)); - fail("It is expected that the file does not exist."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // does not exist. - } - try { - new ImageOptimizationService<>(null, new File(DEFAULT_BINARY_APP_LOCATION)); - fail("It is expected that the file does not exist."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // does not exist. - } - try { - final File file = File.createTempFile("qqq", "qqq"); - file.createNewFile(); - file.deleteOnExit(); - new ImageOptimizationService<>(file, new File(DEFAULT_BINARY_APP_LOCATION)); - fail("failed because we expected tthe temp directory to be a file instead of a directory."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // is a file instead of a directory. - } - final File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); - assertNotNull(new ImageOptimizationService<>(tmpDir, new File(DEFAULT_BINARY_APP_LOCATION))); + assertThat(new ImageOptimizationService<>(tmpDir, new File(defaultBinaryAppLocation)), notNullValue()); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} to test that files cause an + * error. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationService2PassInFile() { + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(File.createTempFile("qqq", "qqq"), new File(defaultBinaryAppLocation), 1); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} to test that files cause an + * error. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationService2ZeroPassInFile() { + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(File.createTempFile("qqq", "qqq"), new File(defaultBinaryAppLocation), 0); }); } /** - * Test method for - * {@link ImageOptimizationService#ImageOptimizationService(File, File, int)}. + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} to test that files cause an + * error. * - * @throws IOException Can be thrown by the - * ImageOptimizationService constructor if - * its passed in file has an issue. + * @throws IOException Can be thrown by the {@code ImageOptimizationService} constructor if its passed in file has + * an issue. */ - @SuppressWarnings("unused") + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationService2PassInFile2() throws IOException { + final File file = File.createTempFile("qqq", "qqq"); + file.createNewFile(); + file.deleteOnExit(); + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(file, new File(defaultBinaryAppLocation), 1); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} to test that files cause an + * error. + * + * @throws IOException Can be thrown by the {@code ImageOptimizationService} constructor if its passed in file has + * an issue. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationService2ZeroPassInFile2() throws IOException { + final File file = File.createTempFile("qqq", "qqq"); + file.createNewFile(); + file.deleteOnExit(); + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(file, new File(defaultBinaryAppLocation), 0); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} to test that files cause an + * error. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationService2PassInNullFolder() { + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(null, new File(defaultBinaryAppLocation), 1); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} to test that files cause an + * error. + */ + @SuppressWarnings({ "unused", "static-method" }) + @Test + public void testImageOptimizationService2ZeroPassInNullFolder() { + assertThrows(IllegalArgumentException.class, () -> { new ImageOptimizationService<>(null, new File(defaultBinaryAppLocation), 0); }); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} + * + * @throws IOException Can be thrown by the {@code ImageOptimizationService} constructor if its passed in file has + * an issue. + */ + @SuppressWarnings("static-method") @Test public void testImageOptimizationService2() throws IOException { - try { - new ImageOptimizationService<>(File.createTempFile("qqq", "qqq"), new File(DEFAULT_BINARY_APP_LOCATION), 1); - fail("It is expected that the file does not exist."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // does not exist. - } - try { - new ImageOptimizationService<>(null, new File(DEFAULT_BINARY_APP_LOCATION), 1); - fail("It is expected that the file does not exist."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // does not exist. - } - try { - final File file = File.createTempFile("qqq", "qqq"); - file.createNewFile(); - file.deleteOnExit(); - new ImageOptimizationService<>(file, new File(DEFAULT_BINARY_APP_LOCATION), 1); - fail("failed because we expected tthe temp directory to be a file instead of a directory."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // is a file instead of a directory. - } - - File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); + final File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); - assertNotNull(new ImageOptimizationService<>(tmpDir, new File(DEFAULT_BINARY_APP_LOCATION), 1)); - - - try { - new ImageOptimizationService<>(File.createTempFile("qqq", "qqq"), new File(DEFAULT_BINARY_APP_LOCATION), 0); - fail("It is expected that the file does not exist."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // does not exist. - } - try { - new ImageOptimizationService<>(null, new File(DEFAULT_BINARY_APP_LOCATION), 0); - fail("It is expected that the file does not exist."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // does not exist. - } - try { - final File file = File.createTempFile("qqq", "qqq"); - file.createNewFile(); - file.deleteOnExit(); - new ImageOptimizationService<>(file, new File(DEFAULT_BINARY_APP_LOCATION), 0); - fail("failed because we expected tthe temp directory to be a file instead of a directory."); - } catch(final IllegalArgumentException ignore) { - // if this catch block is executed then the test passed and the File - // is a file instead of a directory. - } - - tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); + assertThat(new ImageOptimizationService<>(tmpDir, new File(defaultBinaryAppLocation), 1), notNullValue()); + } + + /** + * Test method for {@link ImageOptimizationService#ImageOptimizationService(File, File, int)} + * + * @throws IOException Can be thrown by the {@code ImageOptimizationService} constructor if its passed in file has + * an issue. + */ + @SuppressWarnings("static-method") + @Test + public void testImageOptimizationService2Zero() throws IOException { + final File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); - assertNotNull(new ImageOptimizationService<>(tmpDir, new File(DEFAULT_BINARY_APP_LOCATION), 0)); + assertThat(new ImageOptimizationService<>(tmpDir, new File(defaultBinaryAppLocation), 0), notNullValue()); } private static final void validateFileOptimization(final OptimizationResult result, final ImageOptimizationTestDTO imageOptimizationTestDTO, final boolean isWebP) throws IOException { @@ -217,46 +269,46 @@ private static final void validateFileOptimization(final OptimizationResult dto.isWebPCompatible()).count(); } private static final int getNumberOfOptimizedImages(final ImageOptimizationTestDTO[] imageOptimizationTestDTOList) { @@ -303,6 +348,7 @@ private static final int getNumberOfOptimizedImages(final ImageOptimizationTestD * @throws ImageFileOptimizationException Thrown if there is an error trying * to optimize an image. */ + @SuppressWarnings("static-method") @Test public void testOptimizeAllImagesALL() throws IOException, ImageFileOptimizationException, TimeoutException { @@ -314,7 +360,8 @@ public void testOptimizeAllImagesALL() throws IOException, ImageFileOptimization new ImageOptimizationTestDTO("no_transparency.gif", false, true, true), new ImageOptimizationTestDTO("doctype_16_sprite.png", false, false, false), new ImageOptimizationTestDTO("addCol.gif", false, true, true), - new ImageOptimizationTestDTO("s-arrow-bo.gif", false, true, true)}; + new ImageOptimizationTestDTO("s-arrow-bo.gif", false, true, true), + new ImageOptimizationTestDTO("noEvents.svg", false, false, true)}; final int numberOfOptimizedImages = getNumberOfOptimizedImages(imageOptimizationTestDTOList); @@ -324,29 +371,29 @@ public void testOptimizeAllImagesALL() throws IOException, ImageFileOptimization } //Testing with ALL and no WebP - List> results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.ALL, false, filesToOptimize); - assertNotNull(results); + List> results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.ALL, false, filesToOptimize); + assertThat(results, notNullValue()); Map> treasureMap = new HashMap<>(numberOfOptimizedImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); treasureMap.put(result.getOriginalFile().getName(), result); } for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfOptimizedImages, results.size()); - assertEquals(numberOfOptimizedImages, treasureMap.size()); + assertThat(results, hasSize(numberOfOptimizedImages)); + assertThat(treasureMap, aMapWithSize(numberOfOptimizedImages)); //Testing with ALL and YES WebP final int numberOfResultImages = numberOfOptimizedImages + getNumberOfWebPCompatibleImages(imageOptimizationTestDTOList); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.ALL, true, filesToOptimize); - assertNotNull(results); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.ALL, true, filesToOptimize); + assertThat(results, notNullValue()); treasureMap = new HashMap<>(numberOfResultImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); if(FilenameUtils.isExtension(result.getOptimizedFile().getName(), IImageOptimizationService.WEBP_EXTENSION)) { treasureMap.put(result.getOriginalFile().getName() + WEBP_ID, result); } else { @@ -357,39 +404,38 @@ public void testOptimizeAllImagesALL() throws IOException, ImageFileOptimization for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfResultImages, results.size()); - assertEquals(numberOfResultImages, treasureMap.size()); + assertThat(results, hasSize(numberOfResultImages)); + assertThat(treasureMap, aMapWithSize(numberOfResultImages)); //WebP Check for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { - if(imageOptimizationTestDTO.isJPEG()) { + if(!imageOptimizationTestDTO.isWebPCompatible()) { //JPEG is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); - } else if(imageOptimizationTestDTO.isAnimatedGif()) { //Animated GIF is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); + //SVG is not converted to WEBP + assertThat(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), nullValue()); } else { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), imageOptimizationTestDTO, true); } } //Testing a null list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.ALL, false, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.ALL, false, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.ALL, true, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.ALL, true, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); //Testing an empty list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.ALL, false, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.ALL, false, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.ALL, true, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.ALL, true, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); } /** @@ -405,18 +451,20 @@ public void testOptimizeAllImagesALL() throws IOException, ImageFileOptimization * @throws ImageFileOptimizationException Thrown if there is an error trying * to optimize an image. */ + @SuppressWarnings("static-method") @Test public void testOptimizeAllImagesNONE() throws IOException, ImageFileOptimizationException, TimeoutException { final ImageOptimizationTestDTO[] imageOptimizationTestDTOList = {new ImageOptimizationTestDTO("csv_120.png", false, false, true), new ImageOptimizationTestDTO("sharing_model2.jpg", false, false, true), new ImageOptimizationTestDTO("loading.gif", false, false, true), - new ImageOptimizationTestDTO("el_icon.gif", false, false, false), + new ImageOptimizationTestDTO("el_icon.gif", false, false, true), new ImageOptimizationTestDTO("safe32.png", false, false, true), new ImageOptimizationTestDTO("no_transparency.gif", false, false, true), new ImageOptimizationTestDTO("doctype_16_sprite.png", false, false, false), new ImageOptimizationTestDTO("addCol.gif", false, false, false), - new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true)}; + new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true), + new ImageOptimizationTestDTO("noEvents.svg", false, false, true)}; final int numberOfOptimizedImages = getNumberOfOptimizedImages(imageOptimizationTestDTOList); @@ -426,29 +474,29 @@ public void testOptimizeAllImagesNONE() throws IOException, ImageFileOptimizatio } //Testing with NONE - List> results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, false, filesToOptimize); - assertNotNull(results); + List> results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, false, filesToOptimize); + assertThat(results, notNullValue()); Map> treasureMap = new HashMap<>(numberOfOptimizedImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); treasureMap.put(result.getOriginalFile().getName(), result); } for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfOptimizedImages, treasureMap.size()); - assertEquals(numberOfOptimizedImages, results.size()); + assertThat(results, hasSize(numberOfOptimizedImages)); + assertThat(treasureMap, aMapWithSize(numberOfOptimizedImages)); //Testing with NONE and YES WebP final int numberOfResultImages = numberOfOptimizedImages + getNumberOfWebPCompatibleImages(imageOptimizationTestDTOList); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, true, filesToOptimize); - assertNotNull(results); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, true, filesToOptimize); + assertThat(results, notNullValue()); treasureMap = new HashMap<>(numberOfResultImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); if(FilenameUtils.isExtension(result.getOptimizedFile().getName(), IImageOptimizationService.WEBP_EXTENSION)) { treasureMap.put(result.getOriginalFile().getName() + WEBP_ID, result); } else { @@ -459,39 +507,38 @@ public void testOptimizeAllImagesNONE() throws IOException, ImageFileOptimizatio for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfResultImages, treasureMap.size()); - assertEquals(numberOfResultImages, results.size()); + assertThat(results, hasSize(numberOfResultImages)); + assertThat(treasureMap, aMapWithSize(numberOfResultImages)); //WebP Check for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { - if(imageOptimizationTestDTO.isJPEG()) { + if(!imageOptimizationTestDTO.isWebPCompatible()) { //JPEG is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); - } else if(imageOptimizationTestDTO.isAnimatedGif()) { //Animated GIF is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); + //SVG is not converted to WEBP + assertThat(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), nullValue()); } else { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), imageOptimizationTestDTO, true); } } //Testing a null list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, false, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, false, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, true, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, true, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); //Testing an empty list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, false, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, false, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, true, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, true, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); } /** @@ -507,18 +554,20 @@ public void testOptimizeAllImagesNONE() throws IOException, ImageFileOptimizatio * @throws ImageFileOptimizationException Thrown if there is an error trying * to optimize an image. */ + @SuppressWarnings("static-method") @Test public void testOptimizeAllImagesIE6SAFE() throws IOException, ImageFileOptimizationException, TimeoutException { final ImageOptimizationTestDTO[] imageOptimizationTestDTOList = {new ImageOptimizationTestDTO("csv_120.png", false, false, true), new ImageOptimizationTestDTO("sharing_model2.jpg", false, false, true), new ImageOptimizationTestDTO("loading.gif", false, false, true), - new ImageOptimizationTestDTO("el_icon.gif", false, false, false), + new ImageOptimizationTestDTO("el_icon.gif", false, false, true), new ImageOptimizationTestDTO("safe32.png", false, false, true), new ImageOptimizationTestDTO("no_transparency.gif", false, true, true), new ImageOptimizationTestDTO("doctype_16_sprite.png", false, false, false), new ImageOptimizationTestDTO("addCol.gif", false, false, false), - new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true)}; + new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true), + new ImageOptimizationTestDTO("noEvents.svg", false, false, true)}; final int numberOfOptimizedImages = getNumberOfOptimizedImages(imageOptimizationTestDTOList); @@ -528,29 +577,30 @@ public void testOptimizeAllImagesIE6SAFE() throws IOException, ImageFileOptimiza } //Testing with IE6SAFE - List> results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.IE6SAFE, false, filesToOptimize); - assertNotNull(results); + List> results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.IE6SAFE, false, filesToOptimize); + assertThat(results, notNullValue()); Map> treasureMap = new HashMap<>(numberOfOptimizedImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); treasureMap.put(result.getOriginalFile().getName(), result); } for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfOptimizedImages, treasureMap.size()); - assertEquals(numberOfOptimizedImages, results.size()); + + assertThat(treasureMap, aMapWithSize(numberOfOptimizedImages)); + assertThat(results, hasSize(numberOfOptimizedImages)); //Testing with IE6SAFE and YES WebP final int numberOfResultImages = numberOfOptimizedImages + getNumberOfWebPCompatibleImages(imageOptimizationTestDTOList); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.IE6SAFE, true, filesToOptimize); - assertNotNull(results); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.IE6SAFE, true, filesToOptimize); + assertThat(results, notNullValue()); treasureMap = new HashMap<>(numberOfResultImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); if(FilenameUtils.isExtension(result.getOptimizedFile().getName(), IImageOptimizationService.WEBP_EXTENSION)) { treasureMap.put(result.getOriginalFile().getName() + WEBP_ID, result); } else { @@ -561,39 +611,38 @@ public void testOptimizeAllImagesIE6SAFE() throws IOException, ImageFileOptimiza for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfResultImages, treasureMap.size()); - assertEquals(numberOfResultImages, results.size()); + assertThat(treasureMap, aMapWithSize(numberOfResultImages)); + assertThat(results, hasSize(numberOfResultImages)); //WebP Check for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { - if(imageOptimizationTestDTO.isJPEG()) { + if(!imageOptimizationTestDTO.isWebPCompatible()) { //JPEG is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); - } else if(imageOptimizationTestDTO.isAnimatedGif()) { //Animated GIF is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); + //SVG is not converted to WEBP + assertThat(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), nullValue()); } else { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), imageOptimizationTestDTO, true); } } //Testing a null list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.IE6SAFE, false, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.IE6SAFE, false, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.IE6SAFE, true, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.IE6SAFE, true, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); //Testing an empty list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.IE6SAFE, false, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.IE6SAFE, false, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.IE6SAFE, true, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.IE6SAFE, true, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); } /** @@ -610,6 +659,7 @@ public void testOptimizeAllImagesIE6SAFE() throws IOException, ImageFileOptimiza * to optimize an image. * @throws TimeoutException Thrown if optimizing an image timed out. */ + @SuppressWarnings("static-method") @Test public void testOptimizeAllImagesNONEWithTimeoutFailure() throws IOException, ImageFileOptimizationException, TimeoutException { @@ -622,45 +672,36 @@ public void testOptimizeAllImagesNONEWithTimeoutFailure() throws IOException, Im new ImageOptimizationTestDTO("doctype_16_sprite.png", false, false, false), new ImageOptimizationTestDTO("addCol.gif", false, false, false), new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true), - new ImageOptimizationTestDTO("imagebomb.png", false, false, true)}; + new ImageOptimizationTestDTO("imagebomb.png", false, false, true), + new ImageOptimizationTestDTO("noEvents.svg", false, false, true)}; final List filesToOptimize = new ArrayList<>(imageOptimizationTestDTOList.length); for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { filesToOptimize.add(imageOptimizationTestDTO.getMasterFile()); } + + //Testing with NONE + assertThrows(TimeoutException.class, () -> { new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 1).optimizeAllImages(FileTypeConversion.NONE, false, filesToOptimize); }); + + //Testing with NONE and YES WebP + assertThrows(TimeoutException.class, () -> { new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 1).optimizeAllImages(FileTypeConversion.NONE, true, filesToOptimize); }); - try { - //Testing with NONE - new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 1).optimizeAllImages(FileTypeConversion.NONE, false, filesToOptimize); - fail(); - } catch(final TimeoutException te) { - //expected the exception - } - - try { - //Testing with NONE and YES WebP - new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 1).optimizeAllImages(FileTypeConversion.NONE, true, filesToOptimize); - fail(); - } catch(final TimeoutException te) { - //expected the exception - } - - List> results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION)).optimizeAllImages(FileTypeConversion.NONE, false, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + List> results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation)).optimizeAllImages(FileTypeConversion.NONE, false, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 1).optimizeAllImages(FileTypeConversion.NONE, true, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 1).optimizeAllImages(FileTypeConversion.NONE, true, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); //Testing an empty list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 1).optimizeAllImages(FileTypeConversion.NONE, false, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 1).optimizeAllImages(FileTypeConversion.NONE, false, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 1).optimizeAllImages(FileTypeConversion.NONE, true, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 1).optimizeAllImages(FileTypeConversion.NONE, true, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); } /** @@ -677,18 +718,20 @@ public void testOptimizeAllImagesNONEWithTimeoutFailure() throws IOException, Im * to optimize an image. * @throws TimeoutException Thrown if optimizing an image timed out. */ + @SuppressWarnings("static-method") @Test public void testOptimizeAllImagesNONEWithTimeoutSuccess() throws IOException, ImageFileOptimizationException, TimeoutException { final ImageOptimizationTestDTO[] imageOptimizationTestDTOList = {new ImageOptimizationTestDTO("csv_120.png", false, false, true), new ImageOptimizationTestDTO("sharing_model2.jpg", false, false, true), new ImageOptimizationTestDTO("loading.gif", false, false, true), - new ImageOptimizationTestDTO("el_icon.gif", false, false, false), + new ImageOptimizationTestDTO("el_icon.gif", false, false, true), new ImageOptimizationTestDTO("safe32.png", false, false, true), new ImageOptimizationTestDTO("no_transparency.gif", false, false, true), new ImageOptimizationTestDTO("doctype_16_sprite.png", false, false, false), new ImageOptimizationTestDTO("addCol.gif", false, false, false), - new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true)}; + new ImageOptimizationTestDTO("s-arrow-bo.gif", false, false, true), + new ImageOptimizationTestDTO("noEvents.svg", false, false, true)}; final int numberOfOptimizedImages = getNumberOfOptimizedImages(imageOptimizationTestDTOList); @@ -698,29 +741,29 @@ public void testOptimizeAllImagesNONEWithTimeoutSuccess() throws IOException, Im } //Testing with NONE - List> results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 60).optimizeAllImages(FileTypeConversion.NONE, false, filesToOptimize); - assertNotNull(results); + List> results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 60).optimizeAllImages(FileTypeConversion.NONE, false, filesToOptimize); + assertThat(results, notNullValue()); Map> treasureMap = new HashMap<>(numberOfOptimizedImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); treasureMap.put(result.getOriginalFile().getName(), result); } for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfOptimizedImages, treasureMap.size()); - assertEquals(numberOfOptimizedImages, results.size()); + assertThat(treasureMap, aMapWithSize(numberOfOptimizedImages)); + assertThat(results, hasSize(numberOfOptimizedImages)); //Testing with NONE and YES WebP final int numberOfResultImages = numberOfOptimizedImages + getNumberOfWebPCompatibleImages(imageOptimizationTestDTOList); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 60).optimizeAllImages(FileTypeConversion.NONE, true, filesToOptimize); - assertNotNull(results); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 60).optimizeAllImages(FileTypeConversion.NONE, true, filesToOptimize); + assertThat(results, notNullValue()); treasureMap = new HashMap<>(numberOfResultImages); for(final OptimizationResult result : results) { - assertNotNull(result); + assertThat(result, notNullValue()); if(FilenameUtils.isExtension(result.getOptimizedFile().getName(), IImageOptimizationService.WEBP_EXTENSION)) { treasureMap.put(result.getOriginalFile().getName() + WEBP_ID, result); } else { @@ -731,39 +774,38 @@ public void testOptimizeAllImagesNONEWithTimeoutSuccess() throws IOException, Im for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName()), imageOptimizationTestDTO, false); } - assertEquals(numberOfResultImages, treasureMap.size()); - assertEquals(numberOfResultImages, results.size()); + assertThat(treasureMap, aMapWithSize(numberOfResultImages)); + assertThat(results, hasSize(numberOfResultImages)); //WebP Check for(final ImageOptimizationTestDTO imageOptimizationTestDTO : imageOptimizationTestDTOList) { - if(imageOptimizationTestDTO.isJPEG()) { + if(!imageOptimizationTestDTO.isWebPCompatible()) { //JPEG is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); - } else if(imageOptimizationTestDTO.isAnimatedGif()) { //Animated GIF is not converted to WEBP - assertNull(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID)); + //SVG is not converted to WEBP + assertThat(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), nullValue()); } else { validateFileOptimization(treasureMap.get(imageOptimizationTestDTO.getMasterFile().getName() + WEBP_ID), imageOptimizationTestDTO, true); } } //Testing a null list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 60).optimizeAllImages(FileTypeConversion.NONE, false, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 60).optimizeAllImages(FileTypeConversion.NONE, false, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 60).optimizeAllImages(FileTypeConversion.NONE, true, (Collection)null); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 60).optimizeAllImages(FileTypeConversion.NONE, true, (Collection)null); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); //Testing an empty list of images - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 60).optimizeAllImages(FileTypeConversion.NONE, false, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 60).optimizeAllImages(FileTypeConversion.NONE, false, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); - results = new ImageOptimizationService<>(getTempDir(), new File(DEFAULT_BINARY_APP_LOCATION), 60).optimizeAllImages(FileTypeConversion.NONE, true, Collections.EMPTY_LIST); - assertNotNull(results); - assertTrue(results.isEmpty()); + results = new ImageOptimizationService<>(getTempDir(), new File(defaultBinaryAppLocation), 60).optimizeAllImages(FileTypeConversion.NONE, true, Collections.EMPTY_LIST); + assertThat(results, notNullValue()); + assertThat(results, IsEmptyCollection.empty()); } /** @@ -774,52 +816,53 @@ public void testOptimizeAllImagesNONEWithTimeoutSuccess() throws IOException, Im * @throws InterruptedException Can be thrown by the optimization service * when optimizing the files. */ + @SuppressWarnings("boxing") @Test public void testExecuteAdvpng() throws IOException, InterruptedException { //Test 1 File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "owner_key_icon.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executeAdvpng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertEquals(workingFileSize, optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 2 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "csv_120.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeAdvpng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//1099 //Test 3 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "doctype_16_sprite.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeAdvpng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertEquals(workingFileSize, optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 4 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sprite arrow enlarge max min shrink x blue.gif.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeAdvpng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//4386 } /** @@ -830,73 +873,74 @@ public void testExecuteAdvpng() throws IOException, InterruptedException { * @throws InterruptedException Can be thrown by the optimization service * when optimizing the files. */ + @SuppressWarnings("boxing") @Test public void testExecutePngquant() throws IOException, InterruptedException { //Test 1 File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "owner_key_icon.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executePngquant(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue()); - assertThat(Boolean.valueOf(optimizedFile.exists()), Matchers.equalTo(Boolean.TRUE)); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.equalTo(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 2 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "csv_120.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngquant(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue()); - assertThat(Boolean.valueOf(optimizedFile.exists()), Matchers.equalTo(Boolean.TRUE)); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.lessThan(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//1144 //Test 3 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "csv_120.2png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.2png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.2png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngquant(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue()); - assertThat(Boolean.valueOf(optimizedFile.exists()), Matchers.equalTo(Boolean.TRUE)); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.lessThan(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//1144 //Test 4 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "safe32.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngquant(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue()); - assertThat(Boolean.valueOf(optimizedFile.exists()), Matchers.equalTo(Boolean.TRUE)); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.equalTo(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 5 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "doctype_16_sprite.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngquant(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue()); - assertThat(Boolean.valueOf(optimizedFile.exists()), Matchers.equalTo(Boolean.TRUE)); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.equalTo(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 6 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sprite arrow enlarge max min shrink x blue.gif.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngquant(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue()); - assertThat(Boolean.valueOf(optimizedFile.exists()), Matchers.equalTo(Boolean.TRUE)); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.lessThan(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//4168 } /** @@ -907,56 +951,61 @@ public void testExecutePngquant() throws IOException, InterruptedException { * @throws InterruptedException Can be thrown by the optimization service * when optimizing the files. */ + @SuppressWarnings("boxing") @Test public void testExecutePngout() throws IOException, InterruptedException { //Test 1 File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "owner_key_icon.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executePngout(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertEquals(workingFileSize, optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 2 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "csv_120.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngout(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//1034 //Test 3 - workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "doctype_16_sprite.png"); - - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); - workingFileSize = workingFile.length(); - - try { - optimizedFile = imageOptimizationService.executePngout(workingFile, workingFile.getCanonicalPath()); - fail("Exepected a RuntimeException"); - } catch(final ImageFileOptimizationException ifoe) { - assertEquals("Error while optimizing the file \"" + workingFile.getCanonicalPath() + "\"", ifoe.getMessage()); - } - - //Test 4 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sprite arrow enlarge max min shrink x blue.gif.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executePngout(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//4018 } + /** + * Test method for + * {@link ImageOptimizationService#executePngout(File, String)}. + * + * @throws IOException Can be thrown when interacting with various files. + */ + @Test + public void testExecutePngoutException() throws IOException { + + final File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "doctype_16_sprite.png"); + + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); + final ImageFileOptimizationException ifoe = assertThrows(ImageFileOptimizationException.class, () -> { imageOptimizationService.executePngout(workingFile, workingFile.getCanonicalPath()); }); + assertThat(ifoe, hasProperty("message", equalTo("Error while optimizing the file \"" + workingFile.getCanonicalPath() + '"'))); + } + + @SuppressWarnings("boxing") private final void testExecuteCWebpHelper(final File fileToConvert) throws IOException, InterruptedException { final File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + fileToConvert.getName()); @@ -965,14 +1014,14 @@ private final void testExecuteCWebpHelper(final File fileToConvert) throws IOExc final long workingFileSize = workingFile.length(); final File optimizedFile = imageOptimizationService.executeCWebp(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); if(IImageOptimizationService.JPEG_EXTENSION.equalsIgnoreCase(FilenameUtils.getExtension(fileToConvert.getName()))) { - assertTrue(optimizedFile.length() > workingFileSize); + assertThat(optimizedFile, aFileWithSize(greaterThan(workingFileSize))); } else { - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//18082,900,8942,1194,3870,3870,3870 } - assertEquals(IImageOptimizationService.WEBP_EXTENSION, FilenameUtils.getExtension(optimizedFile.getName())); + assertThat(optimizedFile, aFileNamed(endsWith(IImageOptimizationService.WEBP_EXTENSION))); } /** @@ -985,14 +1034,15 @@ private final void testExecuteCWebpHelper(final File fileToConvert) throws IOExc */ @Test public void testExecuteCWebp() throws IOException, InterruptedException { - testExecuteCWebpHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png")); - testExecuteCWebpHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png")); - testExecuteCWebpHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png")); - testExecuteCWebpHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png")); - testExecuteCWebpHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg")); - testExecuteCWebpHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png")); + testExecuteCWebpHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png")); + testExecuteCWebpHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png")); + testExecuteCWebpHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png")); + testExecuteCWebpHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png")); + testExecuteCWebpHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg")); + testExecuteCWebpHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png")); } + @SuppressWarnings("boxing") private final void testExecuteGif2WebHelper(final File fileToConvert) throws IOException, InterruptedException { final File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + fileToConvert.getName()); @@ -1001,10 +1051,10 @@ private final void testExecuteGif2WebHelper(final File fileToConvert) throws IOE final long workingFileSize = workingFile.length(); final File optimizedFile = imageOptimizationService.executeGif2Webp(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); - assertEquals(IImageOptimizationService.WEBP_EXTENSION, FilenameUtils.getExtension(optimizedFile.getName())); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//1042,2840,31934,246,122 + assertThat(optimizedFile, aFileNamed(endsWith(IImageOptimizationService.WEBP_EXTENSION))); } /** @@ -1017,11 +1067,11 @@ private final void testExecuteGif2WebHelper(final File fileToConvert) throws IOE */ @Test public void testExecuteGif2Web() throws IOException, InterruptedException { - testExecuteGif2WebHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif")); - testExecuteGif2WebHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif")); - testExecuteGif2WebHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif")); - testExecuteGif2WebHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif")); - testExecuteGif2WebHelper(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif")); + testExecuteGif2WebHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif")); + testExecuteGif2WebHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif")); + testExecuteGif2WebHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif")); + testExecuteGif2WebHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif")); + testExecuteGif2WebHelper(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif")); } /** @@ -1032,38 +1082,39 @@ public void testExecuteGif2Web() throws IOException, InterruptedException { * @throws InterruptedException Can be thrown by the optimization service * when optimizing the files. */ + @SuppressWarnings("boxing") @Test public void testExecuteOptipng() throws IOException, InterruptedException { File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "owner_key_icon.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executeOptipng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertEquals(workingFileSize, optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "csv_120.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeOptipng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//1220 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "doctype_16_sprite.png"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeOptipng(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//15784 } /** @@ -1079,24 +1130,24 @@ public void testExecuteJpegtran() throws IOException, InterruptedException { //Test 1 File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sharing_model2.jpg"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executeJpegtran(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertEquals(workingFileSize, optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 2 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sharin g model2.jpg"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeJpegtran(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertEquals(workingFileSize, optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); } /** @@ -1107,30 +1158,31 @@ public void testExecuteJpegtran() throws IOException, InterruptedException { * @throws InterruptedException Can be thrown by the optimization service * when optimizing the files. */ + @SuppressWarnings("boxing") @Test public void testExecuteJfifremove() throws IOException, InterruptedException { //Test 1 File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sharing_model2.jpg"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executeJfifremove(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//123496 //Test 2 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "sharin g model2.jpg"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeJfifremove(workingFile, workingFile.getCanonicalPath()); - assertNotNull(optimizedFile); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//123496 } /** @@ -1140,73 +1192,129 @@ public void testExecuteJfifremove() throws IOException, InterruptedException { * @throws InterruptedException Can be thrown by the optimization service * when optimizing the files. */ + @SuppressWarnings("boxing") @Test public void testExecuteGifsicle() throws IOException, InterruptedException { //Test 1 File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "el_icon.gif"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif"), workingFile); long workingFileSize = workingFile.length(); File optimizedFile = imageOptimizationService.executeGifsicle(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue(File.class)); - assertTrue(optimizedFile.exists()); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.equalTo(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue(File.class)); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//245 //Test 2 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "loading.gif"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeGifsicle(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue(File.class)); - assertTrue(optimizedFile.exists()); - assertTrue(workingFileSize > optimizedFile.length()); + assertThat(optimizedFile, notNullValue(File.class)); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//2290 //Test 3 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "no_transparency.gif"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeGifsicle(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue(File.class)); - assertTrue(optimizedFile.exists()); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.lessThan(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue(File.class)); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//43608 //Test 4 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "addCol.gif"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeGifsicle(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue(File.class)); - assertTrue(optimizedFile.exists()); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.equalTo(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue(File.class)); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(workingFileSize)); //Test 5 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "s-arrow-bo.gif"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/s-arrow-bo.gif"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s-arrow-bo.gif"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeGifsicle(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue(File.class)); - assertTrue(optimizedFile.exists()); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.lessThan(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue(File.class)); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//174 //Test 6 workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "s arrow bo.gif"); - FixedFileUtils.copyFile(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif"), workingFile); + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif"), workingFile); workingFileSize = workingFile.length(); optimizedFile = imageOptimizationService.executeGifsicle(workingFile, workingFile.getCanonicalPath()); - assertThat(optimizedFile, Matchers.notNullValue(File.class)); - assertTrue(optimizedFile.exists()); - assertThat(Long.valueOf(optimizedFile.length()), Matchers.lessThan(Long.valueOf(workingFileSize))); + assertThat(optimizedFile, notNullValue(File.class)); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize)));//174 + } + + /** + * Test for {@link ImageOptimizationService#executeSvgop(File, String)}. + * + * @throws IOException Can be thrown when interacting with various files. + * @throws InterruptedException Can be thrown by the optimization service when optimizing the files. + */ + @SuppressWarnings("boxing") + @Test + public void testExecuteSvgop() throws IOException, InterruptedException { + + //Test 1 + File workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "noEvents.svg"); + + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/noEvents.svg"), workingFile); + long workingFileSize = workingFile.length(); + + File optimizedFile = imageOptimizationService.executeSvgop(workingFile, workingFile.getCanonicalPath()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize))); + + //Test 2 + workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "car.svg"); + + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/car.svg"), workingFile); + workingFileSize = workingFile.length(); + + optimizedFile = imageOptimizationService.executeSvgop(workingFile, workingFile.getCanonicalPath()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize))); + + //Test 3 + workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "decimal.svg"); + + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/car.svg"), workingFile); + workingFileSize = workingFile.length(); + + optimizedFile = imageOptimizationService.executeSvgop(workingFile, workingFile.getCanonicalPath()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize))); + + //Test 4 + workingFile = new File(getTempDir().getCanonicalFile() + File.separator + "DroidSans.svg"); + + FixedFileUtils.copyFile(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/DroidSans.svg"), workingFile); + workingFileSize = workingFile.length(); + + optimizedFile = imageOptimizationService.executeSvgop(workingFile, workingFile.getCanonicalPath()); + assertThat(optimizedFile, notNullValue()); + assertThat(optimizedFile, anExistingFile()); + assertThat(optimizedFile, aFileWithSize(lessThan(workingFileSize))); } /** @@ -1214,20 +1322,22 @@ public void testExecuteGifsicle() throws IOException, InterruptedException { * * @throws IOException Can be thrown when interacting with various files. */ + @SuppressWarnings("static-method") @Test public void testGetFinalResultsDirectory() throws IOException { final File tmpDir = getTempDir(); - assertEquals(tmpDir.getCanonicalPath() + File.separator + "final", (new ImageOptimizationService<>(tmpDir, new File(DEFAULT_BINARY_APP_LOCATION))).getFinalResultsDirectory()); + assertThat((new ImageOptimizationService<>(tmpDir, new File(defaultBinaryAppLocation))).getFinalResultsDirectory(), equalTo(tmpDir.getCanonicalPath() + File.separator + "final")); } - private static class ImageOptimizationTestDTO { + private static final class ImageOptimizationTestDTO { private final File masterFile; private final long masterFileChecksum; private final boolean failedAutomatedTest; private final boolean fileTypeChanged; private final boolean isJPEG; + private final boolean isSVG; private final boolean isAnimatedGif; private final boolean isOptimized; @@ -1242,12 +1352,14 @@ private static class ImageOptimizationTestDTO { * @throws IOException Thrown when calculating the masterFileChecksum */ ImageOptimizationTestDTO(final String fileName, final boolean failedAutomatedTest, final boolean fileTypeChanged, final boolean isOptimized) throws IOException { - masterFile = new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service" + File.separator + fileName); - assertTrue(masterFile.exists()); + masterFile = new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service" + File.separator + fileName); + assertThat("Issue with test setup. Looks like the required file for the test is not present.", masterFile, anExistingFile()); masterFileChecksum = FileUtils.checksumCRC32(masterFile); this.failedAutomatedTest = failedAutomatedTest; this.fileTypeChanged = fileTypeChanged; - this.isJPEG = (IImageOptimizationService.JPEG_EXTENSION.equalsIgnoreCase(FilenameUtils.getExtension(fileName))); + final String extension = FilenameUtils.getExtension(fileName); + this.isJPEG = (IImageOptimizationService.JPEG_EXTENSION.equalsIgnoreCase(extension)); + this.isSVG = (IImageOptimizationService.SVG_EXTENSION.equalsIgnoreCase(extension)); this.isAnimatedGif = ImageUtils.isAminatedGif(masterFile); this.isOptimized = isOptimized; } @@ -1273,5 +1385,11 @@ public boolean isAnimatedGif() { public boolean isOptimized() { return isOptimized; } + public boolean isSVG() { + return isSVG; + } + public boolean isWebPCompatible() { + return !isAnimatedGif() && !isJPEG() && !isSVG(); + } } } \ No newline at end of file diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/car.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/car.svg new file mode 100644 index 0000000..00f5143 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/car.svg @@ -0,0 +1,7415 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/check.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/check.svg new file mode 100644 index 0000000..fd681eb --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/check.svg @@ -0,0 +1,3 @@ + + + diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.2png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.2png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.2png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.2png diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/csv_120.png diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/decimal.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/decimal.svg new file mode 100644 index 0000000..c5d763e --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/decimal.svg @@ -0,0 +1,3 @@ + + 10 + diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/doctype_16_sprite.png diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/einstein-header-narrow.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/einstein-header-narrow.svg new file mode 100644 index 0000000..ddb8f0f --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/einstein-header-narrow.svg @@ -0,0 +1,46 @@ + + + + einstein-header-narrow + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/imagebomb.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/imagebomb.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/imagebomb.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/imagebomb.png diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/noEvents.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/noEvents.svg new file mode 100644 index 0000000..6033258 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/noEvents.svg @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/no_transparency.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/owner_key_icon.png diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s arrow bo.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/s-arrow-bo.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s-arrow-bo.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/s-arrow-bo.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/s-arrow-bo.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/safe32.png diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharin g model2.jpg diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sharing_model2.jpg diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/sprite arrow enlarge max min shrink x blue.gif.png diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.min.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.min.svg new file mode 100644 index 0000000..f131356 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.min.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.svg new file mode 100644 index 0000000..6033258 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.svg @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtilsTest.java b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtilsTest.java new file mode 100644 index 0000000..897723b --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtilsTest.java @@ -0,0 +1,204 @@ +/******************************************************************************* + * Copyright (c) 2017, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * Neither the name of Salesforce.com nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ +package com.salesforce.perfeng.uiperf.imageoptimization.utils; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.notNullValue; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLConnection; + +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.Test; + +import com.salesforce.perfeng.uiperf.ThirdPartyBinaryNotFoundException; +import com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService; +import com.salesforce.perfeng.uiperf.imageoptimization.service.ImageOptimizationServiceTest; + +/** + * @author eperret (Eric Perret) + * @since 186.internal + */ +public class ImageUtilsTest { + + /** + * Test for {@link ImagesEqual#visuallyCompare(File, File)}. + * + * @throws ThirdPartyBinaryNotFoundException Thrown if the 3rd party binary used for optimizing images does not + * exist. + */ + @SuppressWarnings({ "boxing", "static-method" }) + @Test + public void testVisuallyCompare() throws ThirdPartyBinaryNotFoundException { + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg")), equalTo(false)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png")), equalTo(false)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.svg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.min.svg")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.svg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.svg")), equalTo(true)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.diff.svg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.svg")), equalTo(false)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.svg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.min.svg")), equalTo(false)); + + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.svg"), + new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/1/noEvents.min.svg")), equalTo(true)); + } + + /** + * Test for {@link ImageUtils#containsAlphaTransparency(File)}. + */ + @SuppressWarnings({ "static-method", "boxing" }) + @Test + public void testContainsAlphaTransparency() { + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg")), equalTo(false)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg")), equalTo(false)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg")), equalTo(false)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif")), equalTo(false)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp")), equalTo(false)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif")), equalTo(true)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png")), equalTo(true)); + assertThat(ImageUtils.containsAlphaTransparency(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png")), equalTo(true)); + } + + /** + * Test for {@link ImageUtils#getBufferedImage(File)}. + * + * @since 188.internal + */ + @SuppressWarnings("static-method") + @Test + public void testGetBufferedImage() { + + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png")), notNullValue()); + assertThat(ImageUtils.getBufferedImage(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png")), notNullValue()); + } + + /** + * Test for {@link ImageUtils#convertImageNative(File, File)}. + * + * @throws IOException Thrown if there is an issue trying to create temp files. + * @throws InterruptedException Thrown if there is a problem trying to convert the image. + * @throws ThirdPartyBinaryNotFoundException Thrown if the 3rd party binary used for optimizing images does not + * exist. + * @since 188.internal + */ + @SuppressWarnings({ "static-method", "boxing" }) + @Test + public void testConvertImageNative() throws IOException, ThirdPartyBinaryNotFoundException, InterruptedException { + + final File fileToConvert = new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"); + final long fileToConvertHash = FileUtils.checksumCRC32(fileToConvert); + + File convertedFile = File.createTempFile(ImageOptimizationServiceTest.class.getName(), "." + IImageOptimizationService.PNG_EXTENSION); + ImageUtils.convertImageNative(fileToConvert, convertedFile); + + assertThat(convertedFile.exists(), equalTo(true)); + assertThat(convertedFile.canRead(), equalTo(true)); + assertThat(convertedFile.canWrite(), equalTo(true)); + assertThat(convertedFile.isFile(), equalTo(true)); + assertThat(convertedFile.isDirectory(), equalTo(false)); + assertThat(convertedFile.isHidden(), equalTo(false)); + assertThat(convertedFile.length(), greaterThan(0L)); + assertThat(FileUtils.checksumCRC32(fileToConvert), equalTo(fileToConvertHash)); + + try(final InputStream is = new BufferedInputStream(new FileInputStream(convertedFile))) { + assertThat(URLConnection.guessContentTypeFromStream(is), equalTo(IImageOptimizationService.PNG_MIME_TYPE)); + } + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"), convertedFile), equalTo(true)); + + final File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); + tmpDir.delete(); + tmpDir.mkdir(); + tmpDir.deleteOnExit(); + + convertedFile = new File(tmpDir.getCanonicalPath() + "/forceapp_bg." + IImageOptimizationService.PNG_EXTENSION); + ImageUtils.convertImageNative(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"), convertedFile); + + assertThat(convertedFile.exists(), equalTo(true)); + assertThat(convertedFile.canRead(), equalTo(true)); + assertThat(convertedFile.canWrite(), equalTo(true)); + assertThat(convertedFile.isFile(), equalTo(true)); + assertThat(convertedFile.isDirectory(), equalTo(false)); + assertThat(convertedFile.isHidden(), equalTo(false)); + assertThat(convertedFile.length(), greaterThan(0L)); + assertThat(FileUtils.checksumCRC32(fileToConvert), equalTo(fileToConvertHash)); + + try(final InputStream is = new BufferedInputStream(new FileInputStream(convertedFile))) { + assertThat(URLConnection.guessContentTypeFromStream(is), equalTo(IImageOptimizationService.PNG_MIME_TYPE)); + } + assertThat(ImagesEqual.visuallyCompare(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"), convertedFile), equalTo(true)); + } + + /** + * Test for {@link ImageUtils#isAminatedGif(File)}. + */ + @SuppressWarnings({ "static-method", "boxing" }) + @Test + public void testIsAminatedGif() { + assertThat(ImageUtils.isAminatedGif(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif")), equalTo(true)); + assertThat(ImageUtils.isAminatedGif(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif")), equalTo(false)); + assertThat(ImageUtils.isAminatedGif(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif")), equalTo(false)); + assertThat(ImageUtils.isAminatedGif(new File("./src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.diff.svg")), equalTo(false)); + } +} \ No newline at end of file diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.diff.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.diff.svg new file mode 100644 index 0000000..986d506 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.diff.svg @@ -0,0 +1 @@ + diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.svg new file mode 100644 index 0000000..b418b98 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.min.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.svg new file mode 100644 index 0000000..fd681eb --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/check.svg @@ -0,0 +1,3 @@ + + + diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.min.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.min.svg new file mode 100644 index 0000000..398e433 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.min.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.svg new file mode 100644 index 0000000..ddb8f0f --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/einstein-header-narrow.svg @@ -0,0 +1,46 @@ + + + + einstein-header-narrow + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.png diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.min.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.min.svg new file mode 100644 index 0000000..25eea3a --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.min.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.svg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.svg new file mode 100644 index 0000000..6033258 --- /dev/null +++ b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/noEvents.svg @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg b/src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg similarity index 100% rename from test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg rename to src/test/java/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/AllTests.java b/test/com/salesforce/perfeng/uiperf/imageoptimization/AllTests.java deleted file mode 100644 index f6ab7bb..0000000 --- a/test/com/salesforce/perfeng/uiperf/imageoptimization/AllTests.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Salesforce.com nor the names of its contributors may be - * used to endorse or promote products derived from this software without - * specific prior written permission. - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ -package com.salesforce.perfeng.uiperf.imageoptimization; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -import com.salesforce.perfeng.uiperf.imageoptimization.service.ImageOptimizationServiceTest; -import com.salesforce.perfeng.uiperf.imageoptimization.utils.ImageUtilsTest; - -/** - * Test Suite for the ImageOptimization project - * - * @author eperret (Eric Perret) - * @since 188.internal - */ -@RunWith(Suite.class) -@SuiteClasses({ ImageOptimizationServiceTest.class, ImageUtilsTest.class}) -public class AllTests { - //Nothing is needed in here. -} \ No newline at end of file diff --git a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtilsTest.java b/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtilsTest.java deleted file mode 100644 index b227425..0000000 --- a/test/com/salesforce/perfeng/uiperf/imageoptimization/utils/ImageUtilsTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Salesforce.com nor the names of its contributors may be - * used to endorse or promote products derived from this software without - * specific prior written permission. - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ -package com.salesforce.perfeng.uiperf.imageoptimization.utils; - -import static org.junit.Assert.*; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URLConnection; - -import org.apache.commons.io.FileUtils; -import org.junit.Test; - -import com.salesforce.perfeng.uiperf.ThirdPartyBinaryNotFoundException; -import com.salesforce.perfeng.uiperf.imageoptimization.service.IImageOptimizationService; -import com.salesforce.perfeng.uiperf.imageoptimization.service.ImageOptimizationServiceTest; - -/** - * @author eperret (Eric Perret) - * @since 186.internal - */ -public class ImageUtilsTest { - - /** - * Test for {@link ImageUtils#visuallyCompare(File, File)}. - * - * @throws ThirdPartyBinaryNotFoundException Thrown if the 3rd party binary - * used for optimizing images does - * not exist. - */ - @Test - public void testVisuallyCompare() throws ThirdPartyBinaryNotFoundException { - - assertTrue(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg"), - new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg"))); - - assertFalse(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg"), - new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg"))); - - assertTrue(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif"), - new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif"))); - - assertFalse(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png"), - new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png"))); - - assertTrue(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif"), - new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp"))); - - assertTrue(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo.gif"), - new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/s-arrow-bo2.gif"))); - } - - /** - * Test for {@link ImageUtils#containsAlphaTransparency(File)}. - */ - @Test - public void testContainsAlphaTransparency() { - assertFalse(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg"))); - assertFalse(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg"))); - assertFalse(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg"))); - assertFalse(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif"))); - assertFalse(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp"))); - assertTrue(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif"))); - assertTrue(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png"))); - assertTrue(ImageUtils.containsAlphaTransparency(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png"))); - } - - /** - * Test for {@link ImageUtils#getBufferedImage(File)}. - * - * @since 188.internal - */ - @Test - public void testGetBufferedImage() { - - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small.jpg"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_smushit.jpg"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/sergey_reasonably_small_jpegmini.jpg"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/no_transparency.gif.tmp"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/2013_summer_force.gif"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_optimized.png"))); - assertNotNull(ImageUtils.getBufferedImage(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/safe32_unoptimized.png"))); - } - - /** - * Test for {@link ImageUtils#convertImageNative(File, File)}. - * - * @throws IOException Thrown if there is an issue trying to create temp - * files. - * @throws InterruptedException Thrown if there is a problem trying to - * convert the image. - * @throws ThirdPartyBinaryNotFoundException Thrown if the 3rd party binary - * used for optimizing images does - * not exist. - * @since 188.internal - */ - @Test - public void testConvertImageNative() throws IOException, ThirdPartyBinaryNotFoundException, InterruptedException { - - final File fileToConvert = new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"); - final long fileToConvertHash = FileUtils.checksumCRC32(fileToConvert); - - File convertedFile = File.createTempFile(ImageOptimizationServiceTest.class.getName(), "." + IImageOptimizationService.PNG_EXTENSION); - ImageUtils.convertImageNative(fileToConvert, convertedFile); - - assertTrue(convertedFile.exists()); - assertTrue(convertedFile.canRead()); - assertTrue(convertedFile.canWrite()); - assertTrue(convertedFile.isFile()); - assertFalse(convertedFile.isDirectory()); - assertFalse(convertedFile.isHidden()); - assertTrue(convertedFile.length() > 0); - assertEquals(fileToConvertHash, FileUtils.checksumCRC32(fileToConvert)); - - try(final InputStream is = new BufferedInputStream(new FileInputStream(convertedFile))) { - assertEquals(IImageOptimizationService.PNG_MIME_TYPE, URLConnection.guessContentTypeFromStream(is)); - } - assertTrue(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"), convertedFile)); - - final File tmpDir = File.createTempFile(ImageOptimizationServiceTest.class.getName(), ""); - tmpDir.delete(); - tmpDir.mkdir(); - tmpDir.deleteOnExit(); - - convertedFile = new File(tmpDir.getCanonicalPath() + "/forceapp_bg." + IImageOptimizationService.PNG_EXTENSION); - ImageUtils.convertImageNative(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"), convertedFile); - - assertTrue(convertedFile.exists()); - assertTrue(convertedFile.canRead()); - assertTrue(convertedFile.canWrite()); - assertTrue(convertedFile.isFile()); - assertFalse(convertedFile.isDirectory()); - assertFalse(convertedFile.isHidden()); - assertTrue(convertedFile.length() > 0); - assertEquals(fileToConvertHash, FileUtils.checksumCRC32(fileToConvert)); - - try(final InputStream is = new BufferedInputStream(new FileInputStream(convertedFile))) { - assertEquals(IImageOptimizationService.PNG_MIME_TYPE, URLConnection.guessContentTypeFromStream(is)); - } - assertTrue(ImageUtils.visuallyCompare(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/utils/forceapp_bg.gif"), convertedFile)); - } - - /** - * Test for {@link ImageUtils#isAminatedGif(File)}. - */ - @Test - public void testIsAminatedGif() { - assertTrue(ImageUtils.isAminatedGif(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/loading.gif"))); - assertFalse(ImageUtils.isAminatedGif(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/el_icon.gif"))); - assertFalse(ImageUtils.isAminatedGif(new File("./test/com/salesforce/perfeng/uiperf/imageoptimization/service/addCol.gif"))); - } -} \ No newline at end of file