Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge remote-tracking branch 'origin/master'

  • Loading branch information...
commit 8de4a387a07fbf77794b07d5437417634b5424d3 2 parents 4bd87ec + e474359
@charroch charroch authored
Showing with 1,122 additions and 237 deletions.
  1. +47 −2 core/pom.xml
  2. +11 −7 core/src/main/java/com/novoda/imageloader/core/ImageManager.java
  3. +7 −1 core/src/main/java/com/novoda/imageloader/core/LoaderSettings.java
  4. +12 −9 core/src/main/java/com/novoda/imageloader/core/file/BasicFileManager.java
  5. +54 −0 core/src/main/java/com/novoda/imageloader/core/file/util/AndroidFileContext.java
  6. +22 −34 core/src/main/java/com/novoda/imageloader/core/file/util/FileUtil.java
  7. +7 −7 core/src/main/java/com/novoda/imageloader/core/loader/util/BitmapDisplayer.java
  8. +8 −3 core/src/main/java/com/novoda/imageloader/core/model/ImageTagFactory.java
  9. +6 −0 core/src/main/java/com/novoda/imageloader/core/network/NetworkManager.java
  10. +20 −6 core/src/main/java/com/novoda/imageloader/core/network/{UrlNetworkLoader.java → UrlNetworkManager.java}
  11. +7 −3 core/src/main/java/com/novoda/imageloader/core/util/DirectLoader.java
  12. +23 −0 core/src/main/java/com/novoda/imageloader/core/util/Log.java
  13. +63 −0 core/src/test/java/com/novoda/imageloader/core/ImageManagerTest.java
  14. +0 −21 core/src/test/java/com/novoda/imageloader/core/Util.java
  15. +31 −24 core/src/test/java/com/novoda/imageloader/core/file/BasicFileManagerTest.java
  16. +42 −0 core/src/test/java/com/novoda/imageloader/core/file/FileTestCase.java
  17. +0 −94 core/src/test/java/com/novoda/imageloader/core/file/FileUtilTest.java
  18. +182 −0 core/src/test/java/com/novoda/imageloader/core/file/util/FileUtilTest.java
  19. +74 −0 core/src/test/java/com/novoda/imageloader/core/loader/util/BitmapDisplayerTest.java
  20. +96 −0 core/src/test/java/com/novoda/imageloader/core/model/ImageTagFactoryTest.java
  21. +88 −0 core/src/test/java/com/novoda/imageloader/core/model/ImageWrapperTest.java
  22. +145 −0 core/src/test/java/com/novoda/imageloader/core/network/UrlNetworlManagerTest.java
  23. +18 −18 core/src/test/java/com/novoda/imageloader/core/{util → network}/UrlUtilTest.java
  24. +78 −0 core/src/test/java/com/novoda/imageloader/core/util/DirectLoaderTest.java
  25. +2 −0  core/src/test/resources/testFile1
  26. +18 −6 demo/res/layout/single_table_base_list_activity.xml
  27. +2 −1  demo/src/com/novoda/imageloader/demo/DemoApplication.java
  28. +15 −0 demo/src/com/novoda/imageloader/demo/activity/BigImages.java
  29. +15 −0 demo/src/com/novoda/imageloader/demo/activity/ImageLongList.java
  30. +16 −0 demo/src/com/novoda/imageloader/demo/activity/LongSmallImageList.java
  31. +13 −1 demo/src/com/novoda/imageloader/demo/activity/base/SingleTableBaseListActivity.java
View
49 core/pom.xml
@@ -6,11 +6,11 @@
<artifactId>imageloader-parent</artifactId>
<version>1.5.6-SNAPSHOT</version>
</parent>
-
+
<artifactId>imageloader-core</artifactId>
<name>imageloader-core</name>
<packaging>jar</packaging>
-
+
<dependencies>
<dependency>
<groupId>com.google.android</groupId>
@@ -42,9 +42,54 @@
<version>2.0.1</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4</artifactId>
+ <version>1.4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito</artifactId>
+ <version>1.4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4-rule</artifactId>
+ <version>1.4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-classloading-objenesis</artifactId>
+ <version>1.4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit-addons</groupId>
+ <artifactId>junit-addons</artifactId>
+ <version>1.4</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.5.1</version>
+ <configuration>
+ <formats>
+ <format>xml</format>
+ <format>html</format>
+ </formats>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
<plugins>
<plugin>
<groupId>com.mycila.maven-license-plugin</groupId>
View
18 core/src/main/java/com/novoda/imageloader/core/ImageManager.java
@@ -27,7 +27,7 @@
import com.novoda.imageloader.core.loader.Loader;
import com.novoda.imageloader.core.loader.SimpleLoader;
import com.novoda.imageloader.core.network.NetworkManager;
-import com.novoda.imageloader.core.network.UrlNetworkLoader;
+import com.novoda.imageloader.core.network.UrlNetworkManager;
/**
* ImageManager has the responsibility to provide a
@@ -49,18 +49,14 @@ public ImageManager(Context context, LoaderSettings settings) {
this.loaderContext = new LoaderContext();
loaderContext.setSettings(settings);
loaderContext.setFileManager(new BasicFileManager(settings));
- loaderContext.setNetworkManager(new UrlNetworkLoader(settings));
+ loaderContext.setNetworkManager(new UrlNetworkManager(settings));
loaderContext.setResBitmapCache(new SoftMapCache());
cacheManager = settings.getCacheManager();
if (cacheManager == null) {
cacheManager = new SoftMapCache();
}
loaderContext.setCache(cacheManager);
- if (settings.isUseAsyncTasks()) {
- this.loader = new ConcurrentLoader(loaderContext);
- } else {
- this.loader = new SimpleLoader(loaderContext);
- }
+ setLoader(settings);
verifyPermissions(context);
}
@@ -83,6 +79,14 @@ public CacheManager getCacheManager() {
public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
+
+ protected void setLoader(LoaderSettings settings) {
+ if (settings.isUseAsyncTasks()) {
+ this.loader = new ConcurrentLoader(loaderContext);
+ } else {
+ this.loader = new SimpleLoader(loaderContext);
+ }
+ }
private void verifyPermissions(Context context) {
verifyPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
View
8 core/src/main/java/com/novoda/imageloader/core/LoaderSettings.java
@@ -21,6 +21,7 @@
import android.os.Build;
import com.novoda.imageloader.core.cache.CacheManager;
+import com.novoda.imageloader.core.file.util.AndroidFileContext;
import com.novoda.imageloader.core.file.util.FileUtil;
/**
@@ -127,6 +128,10 @@ public boolean isUseAsyncTasks() {
public void setUseAsyncTasks(boolean useAsyncTasks) {
this.useAsyncTasks = useAsyncTasks;
}
+
+ public boolean isCleanOnSetup() {
+ return true;
+ }
/**
* Builder for the LoaderSettings.
@@ -175,7 +180,8 @@ public SettingsBuilder withCacheDir(File file) {
}
public LoaderSettings build(Context context) {
- settings.setCacheDir(new FileUtil().prepareCacheDirectory(context));
+ File dir = new FileUtil().prepareCacheDirectory(new AndroidFileContext(context));
+ settings.setCacheDir(dir);
settings.setSdkVersion(Build.VERSION.SDK);
return settings;
}
View
21 core/src/main/java/com/novoda/imageloader/core/file/BasicFileManager.java
@@ -23,6 +23,7 @@
import com.novoda.imageloader.core.LoaderSettings;
import com.novoda.imageloader.core.file.util.FileUtil;
import com.novoda.imageloader.core.network.UrlUtil;
+import com.novoda.imageloader.core.util.Log;
/**
* This is a basic implementation for the file manager.
@@ -31,11 +32,13 @@
*/
public class BasicFileManager implements FileManager {
- private LoaderSettings settings;
+ private LoaderSettings loaderSettings;
public BasicFileManager(LoaderSettings settings) {
- this.settings = settings;
- cleanOldFiles();
+ this.loaderSettings = settings;
+ if(settings.isCleanOnSetup()) {
+ cleanOldFiles();
+ }
}
/**
@@ -52,7 +55,7 @@ public void clean() {
*/
@Override
public void cleanOldFiles() {
- deleteOldFiles(settings.getExpirationPeriod());
+ deleteOldFiles(loaderSettings.getExpirationPeriod());
}
@Override
@@ -70,7 +73,7 @@ public void saveBitmap(String fileName, Bitmap b, int width, int height) {
FileOutputStream out = new FileOutputStream(fileName + "-" + width + "x" + height);
b.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
- e.printStackTrace();
+ Log.warning("" + e.getMessage());
}
}
@@ -78,25 +81,25 @@ public void saveBitmap(String fileName, Bitmap b, int width, int height) {
public File getFile(String url) {
url = processUrl(url);
String filename = String.valueOf(url.hashCode());
- return new File(settings.getCacheDir(), filename);
+ return new File(loaderSettings.getCacheDir(), filename);
}
@Override
public File getFile(String url, int width, int height) {
url = processUrl(url);
String filename = String.valueOf(url.hashCode()) + "-" + width + "x" + height;
- return new File(settings.getCacheDir(), filename);
+ return new File(loaderSettings.getCacheDir(), filename);
}
private String processUrl(String url) {
- if (settings.isQueryIncludedInHash()) {
+ if (loaderSettings.isQueryIncludedInHash()) {
return url;
}
return new UrlUtil().removeQuery(url);
}
private void deleteOldFiles(final long expirationPeriod) {
- final String cacheDir = settings.getCacheDir().getAbsolutePath();
+ final String cacheDir = loaderSettings.getCacheDir().getAbsolutePath();
Thread cleaner = new Thread(new Runnable() {
@Override
public void run() {
View
54 core/src/main/java/com/novoda/imageloader/core/file/util/AndroidFileContext.java
@@ -0,0 +1,54 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.file.util;
+
+import java.io.File;
+
+import android.content.Context;
+
+/**
+ * Internal class to abstract the dependency to specific implementation
+ * of android functionalities.
+ * This class is for internal usage of the imageLoader.
+ */
+public class AndroidFileContext {
+
+ private Context context;
+
+ public AndroidFileContext(Context context) {
+ this.context = context;
+ }
+
+ protected boolean isMounted() {
+ if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
+ return true;
+ }
+ return false;
+ }
+
+ protected String getPackageName() {
+ return context.getPackageName();
+ }
+
+ protected File getExternalStorageDirectory() {
+ return android.os.Environment.getExternalStorageDirectory();
+ }
+
+ protected File preparePhoneCacheDir() {
+ return context.getCacheDir();
+ }
+
+}
View
56 core/src/main/java/com/novoda/imageloader/core/file/util/FileUtil.java
@@ -23,20 +23,19 @@
import java.io.InputStream;
import java.io.OutputStream;
-import android.content.Context;
-import android.util.Log;
-
import com.novoda.imageloader.core.exception.ImageCopyException;
+import com.novoda.imageloader.core.util.Log;
+/**
+ * This class is internal to the imageLoader.
+ * If you want to used it make sure to prepare for changes to the interface.
+ */
public class FileUtil {
private static final String ANDROID_ROOT = "/Android/data/";
private static final String NOMEDIA_FILE_NAME = ".nomedia";
private static final String DEFAULT_IMAGE_FOLDER_NAME = "/cache/images";
- private static final String TAG = "ImageLoader";
-
private static final int BUFFER_SIZE = 60 * 1024;
- private static final byte[] BUFFER = new byte[BUFFER_SIZE];
public void closeSilently(Closeable c) {
try {
@@ -44,26 +43,26 @@ public void closeSilently(Closeable c) {
c.close();
}
} catch (Exception e) {
- Log.e(TAG, "Problem closing stream " + e.getMessage());
+ Log.warning("Problem closing stream " + e.getMessage());
}
}
public void copyStream(InputStream is, OutputStream os) {
try {
+ byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
- synchronized (BUFFER) {
- int amountRead = is.read(BUFFER);
- if (amountRead == -1) {
- break;
- }
- os.write(BUFFER, 0, amountRead);
+ int amountRead = is.read(buffer);
+ if (amountRead == -1) {
+ break;
}
+ os.write(buffer, 0, amountRead);
}
- } catch (Exception ex) {
- Log.e(TAG, "Exception : ", ex);
+ } catch (Exception e) {
+ Log.warning("Exception : " + e.getMessage());
}
}
+
public boolean deleteFileCache(String cacheDirFullPath) {
return reduceFileCache(cacheDirFullPath, -1);
}
@@ -101,42 +100,31 @@ public void copy(File src, File dst) throws ImageCopyException {
}
}
- public File prepareCacheDirectory(Context context) {
+ public File prepareCacheDirectory(AndroidFileContext fileContext) {
File dir = null;
- if (!isMounted()) {
- dir = preparePhoneCacheDir(context);
+ if (fileContext.isMounted()) {
+ dir = prepareExternalCacheDir(fileContext);
} else {
- dir = prepareExternalCacheDir(context);
+ dir = fileContext.preparePhoneCacheDir();
}
addNomediaFile(dir);
return dir;
}
- public boolean isMounted() {
- if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
- return true;
- }
- return false;
- }
-
- private File prepareExternalCacheDir(Context context) {
- String relativepath = ANDROID_ROOT + context.getPackageName() + DEFAULT_IMAGE_FOLDER_NAME;
- File file = new File(android.os.Environment.getExternalStorageDirectory(), relativepath);
+ private File prepareExternalCacheDir(AndroidFileContext fileContext) {
+ String relativepath = ANDROID_ROOT + fileContext.getPackageName() + DEFAULT_IMAGE_FOLDER_NAME;
+ File file = new File(fileContext.getExternalStorageDirectory(), relativepath);
if (!file.isDirectory()) {
file.mkdirs();
}
return file;
}
- private File preparePhoneCacheDir(Context context) {
- return context.getCacheDir();
- }
-
private void addNomediaFile(File dir) {
try {
new File(dir, NOMEDIA_FILE_NAME).createNewFile();
} catch (Exception e) {
- // Don't care if doesn't save the file
+ Log.warning("Problem creating .nomedia file : " + e.getMessage());
}
}
View
14 core/src/main/java/com/novoda/imageloader/core/loader/util/BitmapDisplayer.java
@@ -21,15 +21,15 @@
public class BitmapDisplayer implements Runnable {
private Bitmap bitmap;
- private ImageWrapper imageView;
+ private ImageWrapper imageWrapper;
- public BitmapDisplayer(Bitmap b, ImageWrapper i) {
- bitmap = b;
- imageView = i;
+ public BitmapDisplayer(Bitmap bitmap, ImageWrapper imageWrapper) {
+ this.bitmap = bitmap;
+ this.imageWrapper = imageWrapper;
}
public void runOnUiThread() {
- imageView.runOnUiThread(this);
+ imageWrapper.runOnUiThread(this);
}
@Override
@@ -37,9 +37,9 @@ public void run() {
if (bitmap == null) {
return;
}
- if(imageView.isUrlChanged()) {
+ if(imageWrapper.isUrlChanged()) {
return;
}
- imageView.setBitmap(bitmap);
+ imageWrapper.setBitmap(bitmap);
}
}
View
11 core/src/main/java/com/novoda/imageloader/core/model/ImageTagFactory.java
@@ -40,9 +40,7 @@ public ImageTagFactory(int width, int height, int defaultImageResId) {
}
public ImageTagFactory(Context context, int defaultImageResId) {
- Display d = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
- DisplayMetrics dm = new DisplayMetrics();
- d.getMetrics(dm);
+ Display d = prepareDisplay(context);
this.width = d.getWidth();
this.height = d.getHeight();
this.defaultImageResId = defaultImageResId;
@@ -78,5 +76,12 @@ public ImageTag build(String url) {
it.setPreviewWidth(previewImageWidth);
return it;
}
+
+ protected Display prepareDisplay(Context context) {
+ Display d = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
+ DisplayMetrics dm = new DisplayMetrics();
+ d.getMetrics(dm);
+ return d;
+ }
}
View
6 core/src/main/java/com/novoda/imageloader/core/network/NetworkManager.java
@@ -18,6 +18,12 @@
import java.io.File;
import java.io.InputStream;
+/**
+ * A network manager is responsible of downloading images
+ * given an http resource of url string.
+ * At the moment requested resources can be retrieved as InputStream
+ * or saved directly to a file.
+ */
public interface NetworkManager {
void retrieveImage(String url, File f);
View
26 ...loader/core/network/UrlNetworkLoader.java → ...oader/core/network/UrlNetworkManager.java
@@ -18,22 +18,32 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
import java.net.URL;
import com.novoda.imageloader.core.LoaderSettings;
import com.novoda.imageloader.core.exception.ImageNotFoundException;
import com.novoda.imageloader.core.file.util.FileUtil;
-public class UrlNetworkLoader implements NetworkManager {
+/**
+ * Basic implementation of the NetworkManager using URL connection.
+ */
+public class UrlNetworkManager implements NetworkManager {
- private FileUtil fileUtil = new FileUtil();
+ private FileUtil fileUtil;
private LoaderSettings settings;
- public UrlNetworkLoader(LoaderSettings settings) {
+ public UrlNetworkManager(LoaderSettings settings) {
+ this(settings, new FileUtil());
+ }
+
+ public UrlNetworkManager(LoaderSettings settings, FileUtil fileUtil) {
this.settings = settings;
+ this.fileUtil = fileUtil;
}
@Override
@@ -43,7 +53,7 @@ public void retrieveImage(String url, File f) {
HttpURLConnection conn = null;
applyChangeonSdkVersion(settings.getSdkVersion());
try {
- conn = (HttpURLConnection) new URL(url).openConnection();
+ conn = openConnection(url);
conn.setConnectTimeout(settings.getConnectionTimeout());
conn.setReadTimeout(settings.getReadTimeout());
is = conn.getInputStream();
@@ -61,12 +71,12 @@ public void retrieveImage(String url, File f) {
fileUtil.closeSilently(os);
}
}
-
+
@Override
public InputStream retrieveInputStream(String url) {
HttpURLConnection conn = null;
try {
- conn = (HttpURLConnection) new URL(url).openConnection();
+ conn = openConnection(url);
conn.setConnectTimeout(settings.getConnectionTimeout());
conn.setReadTimeout(settings.getReadTimeout());
return conn.getInputStream();
@@ -77,6 +87,10 @@ public InputStream retrieveInputStream(String url) {
return null;
}
}
+
+ protected HttpURLConnection openConnection(String url) throws IOException, MalformedURLException {
+ return (HttpURLConnection) new URL(url).openConnection();
+ }
private void applyChangeonSdkVersion(String sdkVersion) {
if (Integer.parseInt(sdkVersion) < 8) {
View
10 core/src/main/java/com/novoda/imageloader/core/util/DirectLoader.java
@@ -7,7 +7,7 @@
import com.novoda.imageloader.core.LoaderSettings;
import com.novoda.imageloader.core.bitmap.BitmapUtil;
import com.novoda.imageloader.core.network.NetworkManager;
-import com.novoda.imageloader.core.network.UrlNetworkLoader;
+import com.novoda.imageloader.core.network.UrlNetworkManager;
/**
* Direct loader make use of the NetworkManager and the BitmapUtil
@@ -19,8 +19,12 @@
private BitmapUtil bitmapUtil;
public DirectLoader() {
- networkManager = new UrlNetworkLoader(new LoaderSettings());
- bitmapUtil = new BitmapUtil();
+ this(new UrlNetworkManager(new LoaderSettings()), new BitmapUtil());
+ }
+
+ public DirectLoader(NetworkManager networkManager, BitmapUtil bitmapUtil) {
+ this.networkManager = networkManager;
+ this.bitmapUtil = bitmapUtil;
}
public Bitmap download(String url) {
View
23 core/src/main/java/com/novoda/imageloader/core/util/Log.java
@@ -0,0 +1,23 @@
+package com.novoda.imageloader.core.util;
+
+public class Log {
+
+ private static final String TAG = "ImageLoader";
+
+ public static final void info(String message) {
+ try {
+ android.util.Log.i(TAG, message);
+ } catch(Exception e) {
+ System.out.println(TAG + " " + message);
+ }
+ }
+
+ public static final void warning(String message) {
+ try {
+ android.util.Log.w(TAG, message);
+ } catch(Exception e) {
+ System.out.println(TAG + " " + message);
+ }
+ }
+
+}
View
63 core/src/test/java/com/novoda/imageloader/core/ImageManagerTest.java
@@ -0,0 +1,63 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core;
+
+import static org.mockito.Mockito.*;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+
+public class ImageManagerTest {
+
+ private LoaderSettings loaderSettings;
+ private Context context;
+
+ @Before
+ public void beforeEveryTest() {
+ loaderSettings = mock(LoaderSettings.class);
+ when(loaderSettings.isCleanOnSetup()).thenReturn(false);
+ context = mock(Context.class);
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void shouldComplaingIfInternetPermissionIsNotSet() {
+ PackageManager pm = mock(PackageManager.class);
+ when(pm.checkPermission(Manifest.permission.INTERNET, null))
+ .thenReturn(PackageManager.PERMISSION_DENIED);
+ when(context.getPackageManager()).thenReturn(pm);
+
+ new ImageManager(context, loaderSettings) {
+ protected void setLoader(LoaderSettings settings) {};
+ };
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void shouldComplaingIfWriteExternalStoragePermissionIsNotSet() {
+ PackageManager pm = mock(PackageManager.class);
+ when(pm.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, null))
+ .thenReturn(PackageManager.PERMISSION_DENIED);
+ when(context.getPackageManager()).thenReturn(pm);
+
+ new ImageManager(context, loaderSettings) {
+ protected void setLoader(LoaderSettings settings) {};
+ };
+ }
+
+}
View
21 core/src/test/java/com/novoda/imageloader/core/Util.java
@@ -1,21 +0,0 @@
-/**
- * Copyright 2012 Novoda Ltd
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.novoda.imageloader.core;
-
-public class Util {
-
- public static final String FOLDER_FOR_TEST_TMP_FILES = "target/unit-test/tmp";
-}
View
55 core/src/test/java/com/novoda/imageloader/core/file/BasicFileManagerTest.java
@@ -1,49 +1,54 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package com.novoda.imageloader.core.file;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
-import java.io.File;
-import java.io.IOException;
-
-import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mockito;
import com.novoda.imageloader.core.LoaderSettings;
-import com.novoda.imageloader.core.Util;
-public class BasicFileManagerTest {
+public class BasicFileManagerTest extends FileTestCase {
private BasicFileManager basicFileManager;
private LoaderSettings settings;
- private File cacheDir;
@Before
public void beforeEachTest() {
- settings = Mockito.mock(LoaderSettings.class);
- basicFileManager = new BasicFileManager(settings) {
- @Override
- public void cleanOldFiles() {
- //overriding to tests
- }
- };
- cacheDir = new File(Util.FOLDER_FOR_TEST_TMP_FILES);
- cacheDir.mkdirs();
+ settings = mock(LoaderSettings.class);
+ createCacheDir();
}
@After
- public void afterEachTest() throws IOException {
- FileUtils.deleteDirectory(cacheDir);
- }
+ public void afterEachTest() {
+ deleteCacheDir();
+ }
@Test
public void shouldDistinguishBetweenUrlWithQueryIfIsQueryIncludedInHashIsTrue() {
- Mockito.when(settings.getCacheDir()).thenReturn(cacheDir);
- Mockito.when(settings.isQueryIncludedInHash()).thenReturn(true);
+ when(settings.isCleanOnSetup()).thenReturn(false);
+ when(settings.getCacheDir()).thenReturn(cacheDir);
+ when(settings.isQueryIncludedInHash()).thenReturn(true);
+ basicFileManager = new BasicFileManager(settings);
String filePath1 = basicFileManager.getFile("http://googl.com?param=1").getAbsolutePath();
String filePath2 = basicFileManager.getFile("http://googl.com?param=2").getAbsolutePath();
@@ -52,9 +57,11 @@ public void shouldDistinguishBetweenUrlWithQueryIfIsQueryIncludedInHashIsTrue()
@Test
public void shouldNotDistinguishBetweenUrlWithQueryIfIsQueryIncludedInHashIsFalse() {
- Mockito.when(settings.getCacheDir()).thenReturn(cacheDir);
- Mockito.when(settings.isQueryIncludedInHash()).thenReturn(false);
+ when(settings.isCleanOnSetup()).thenReturn(false);
+ when(settings.getCacheDir()).thenReturn(cacheDir);
+ when(settings.isQueryIncludedInHash()).thenReturn(false);
+ basicFileManager = new BasicFileManager(settings);
String filePath1 = basicFileManager.getFile("http://googl.com?param=1").getAbsolutePath();
String filePath2 = basicFileManager.getFile("http://googl.com?param=2").getAbsolutePath();
View
42 core/src/test/java/com/novoda/imageloader/core/file/FileTestCase.java
@@ -0,0 +1,42 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.file;
+
+import java.io.File;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.Assert;
+
+public class FileTestCase {
+
+ private static final String FOLDER_FOR_TEST_TMP_FILES = "target/unit-test/tmp";
+
+ protected File cacheDir;
+
+ protected void createCacheDir() {
+ cacheDir = new File(FOLDER_FOR_TEST_TMP_FILES);
+ cacheDir.mkdirs();
+ }
+
+ protected void deleteCacheDir() {
+ try {
+ FileUtils.deleteDirectory(cacheDir);
+ } catch (Exception e) {
+ Assert.fail("Problem deleting the cachedir : " + e.getMessage());
+ }
+ }
+
+}
View
94 core/src/test/java/com/novoda/imageloader/core/file/FileUtilTest.java
@@ -1,94 +0,0 @@
-/**
- * Copyright 2012 Novoda Ltd
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.novoda.imageloader.core.file;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-
-import junit.framework.Assert;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.novoda.imageloader.core.Util;
-import com.novoda.imageloader.core.file.util.FileUtil;
-
-public class FileUtilTest {
-
- private FileUtil fileUtil = new FileUtil();
- private File cacheDir;
-
- @Before
- public void beforeEachTest() {
- cacheDir = new File(Util.FOLDER_FOR_TEST_TMP_FILES);
- cacheDir.mkdirs();
- }
-
- @After
- public void afterEachTest() throws IOException {
- FileUtils.deleteDirectory(cacheDir);
- }
-
- @Test
- public void shouldDeleteAllFiles() throws IOException {
- File f1 = createFile("1");
- File f2 = createFile("2");
-
- assertTrue(fileUtil.deleteFileCache(cacheDir.getAbsolutePath()));
-
- assertFalse(f1.exists());
- assertFalse(f2.exists());
- }
-
- @Test
- public void shouldReduceFiles() throws IOException {
- File f1 = createFile("1", 10000);
- File f2 = createFile("2");
- File f3 = createFile("3", 105000);
- File f4 = createFile("4", System.currentTimeMillis());
-
- assertTrue(fileUtil.reduceFileCache(cacheDir.getAbsolutePath(), 24*3600*1000));
-
- assertFalse(f1.exists());
- assertTrue(f2.exists());
- assertFalse(f3.exists());
- assertTrue(f4.exists());
- }
-
- private File createFile(String name) {
- return createFile(name, -1);
- }
-
- private File createFile(String name, long lastModified) {
- try {
- File f1 = new File(cacheDir, name + ".tmp");
- FileUtils.write(f1, name);
- if(lastModified != -1) {
- f1.setLastModified(lastModified);
- }
- return f1;
- } catch (Exception e) {
- Assert.fail("Can't crete file for the test" + e.getMessage());
- throw new RuntimeException("Can't crete file for the test " + e.getMessage());
- }
- }
-
-}
View
182 core/src/test/java/com/novoda/imageloader/core/file/util/FileUtilTest.java
@@ -0,0 +1,182 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.file.util;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import junit.framework.Assert;
+import junitx.framework.FileAssert;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.novoda.imageloader.core.exception.ImageCopyException;
+import com.novoda.imageloader.core.file.FileTestCase;
+
+public class FileUtilTest extends FileTestCase {
+
+ private FileUtil fileUtil = new FileUtil();
+
+ @Before
+ public void beforeEachTest() {
+ createCacheDir();
+ }
+
+ @After
+ public void afterEachTest() {
+ deleteCacheDir();
+ }
+
+ @Test
+ public void shouldDeleteAllFiles() throws IOException {
+ File f1 = createFile("1");
+ File f2 = createFile("2");
+
+ assertTrue(fileUtil.deleteFileCache(cacheDir.getAbsolutePath()));
+
+ assertFalse(f1.exists());
+ assertFalse(f2.exists());
+ }
+
+ @Test
+ public void shouldReduceFiles() throws IOException {
+ File f1 = createFile("1", 10000);
+ File f2 = createFile("2");
+ File f3 = createFile("3", 105000);
+ File f4 = createFile("4", System.currentTimeMillis());
+
+ assertTrue(fileUtil.reduceFileCache(cacheDir.getAbsolutePath(), 24*3600*1000));
+
+ assertFalse(f1.exists());
+ assertTrue(f2.exists());
+ assertFalse(f3.exists());
+ assertTrue(f4.exists());
+ }
+
+ @Test
+ public void shouldCloseNonNullCloseable() throws IOException {
+ Closeable closeable = mock(Closeable.class);
+
+ fileUtil.closeSilently(closeable);
+
+ verify(closeable, atLeastOnce()).close();
+ }
+
+ @Test
+ public void shouldCloseAvoidNullPointers() {
+ fileUtil.closeSilently(null);
+ }
+
+ @Test
+ public void shouldCloseFailSilently() throws IOException {
+ Closeable closeable = mock(Closeable.class);
+ doThrow(new IOException()).when(closeable).close();
+ fileUtil.closeSilently(closeable);
+ }
+
+ @Test
+ public void shouldCopyStream() throws ImageCopyException {
+ File from = new File("src/test/resources/testFile1");
+ assertTrue(from.exists());
+ File to = new File(cacheDir.getAbsolutePath() + "testFile1");
+
+ fileUtil.copy(from, to);
+
+ FileAssert.assertBinaryEquals(from, to);
+ }
+
+ @Test(expected = ImageCopyException.class)
+ public void shouldCopyStreamFailWithImageCopyException() throws ImageCopyException {
+ File from = new File("src/test/resources/testFileThatDoesNotExists");
+ File to = new File(cacheDir.getAbsolutePath() + "testFile2");
+
+ fileUtil.copy(from, to);
+ }
+
+ @Test
+ public void shouldCopyStreams() throws FileNotFoundException {
+ File from = new File("src/test/resources/testFile1");
+ assertTrue(from.exists());
+ File to = new File(cacheDir.getAbsolutePath() + "testFile3");
+ InputStream in = new FileInputStream(from);
+ OutputStream out = new FileOutputStream(to);
+
+ fileUtil.copyStream(in, out);
+
+ FileAssert.assertBinaryEquals(from, to);
+ }
+
+ @Test
+ public void shouldCopyStreamsFailSilently() throws IOException {
+ InputStream from = mock(InputStream.class);
+ when(from.read(any(byte[].class))).thenThrow(new IOException());
+ File to = new File(cacheDir.getAbsolutePath() + "testFile3");
+ OutputStream out = new FileOutputStream(to);
+
+ fileUtil.copyStream(from, out);
+ }
+
+ @Test
+ public void shouldPrepareCacheDirectoryOnFileSystemIfIsMounted() {
+ AndroidFileContext fileContext = mock(AndroidFileContext.class);
+ when(fileContext.isMounted()).thenReturn(true);
+ when(fileContext.getPackageName()).thenReturn("com.something");
+ when(fileContext.getExternalStorageDirectory()).thenReturn(cacheDir);
+
+ fileUtil.prepareCacheDirectory(fileContext);
+
+ File expected = new File(cacheDir.getAbsoluteFile() + "/Android/data/com.something/cache/images");
+ assertTrue(expected.exists());
+ assertTrue(expected.isDirectory());
+ }
+
+ private File createFile(String name) {
+ return createFile(name, -1);
+ }
+
+ private File createFile(String name, long lastModified) {
+ try {
+ File f1 = new File(cacheDir, name + ".tmp");
+ FileUtils.write(f1, name);
+ if(lastModified != -1) {
+ f1.setLastModified(lastModified);
+ }
+ return f1;
+ } catch (Exception e) {
+ Assert.fail("Can't crete file for the test" + e.getMessage());
+ throw new RuntimeException("Can't crete file for the test " + e.getMessage());
+ }
+ }
+
+}
View
74 core/src/test/java/com/novoda/imageloader/core/loader/util/BitmapDisplayerTest.java
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.loader.util;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import android.graphics.Bitmap;
+
+import com.novoda.imageloader.core.model.ImageWrapper;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ Bitmap.class })
+public class BitmapDisplayerTest {
+
+ private BitmapDisplayer bitmapDisplayer;
+ private Bitmap bitmap;
+ private ImageWrapper imageWrapper;
+
+ @Before
+ public void beforeEachTest() {
+ bitmap = PowerMockito.mock(Bitmap.class);
+ imageWrapper = mock(ImageWrapper.class);
+ }
+
+ @Test
+ public void shouldNotSetNullBitmap() {
+ bitmapDisplayer = new BitmapDisplayer(null, imageWrapper);
+ bitmapDisplayer.run();
+
+ verify(imageWrapper, never()).setBitmap(null);
+ }
+
+ @Test
+ public void shouldNotSetBitmapIfTheUrlHasChanged() {
+ when(imageWrapper.isUrlChanged()).thenReturn(true);
+ bitmapDisplayer = new BitmapDisplayer(bitmap, imageWrapper);
+ bitmapDisplayer.run();
+
+ verify(imageWrapper, never()).setBitmap(null);
+ }
+
+ @Test
+ public void shouldSetBitmap() {
+ when(imageWrapper.isUrlChanged()).thenReturn(false);
+ bitmapDisplayer = new BitmapDisplayer(bitmap, imageWrapper);
+ bitmapDisplayer.run();
+
+ verify(imageWrapper).setBitmap(bitmap);
+ }
+
+}
View
96 core/src/test/java/com/novoda/imageloader/core/model/ImageTagFactoryTest.java
@@ -0,0 +1,96 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.model;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import android.content.Context;
+import android.view.Display;
+
+public class ImageTagFactoryTest {
+
+ private ImageTagFactory imageTagFactory;
+ private int height = 12;
+ private int width = 9;
+ private int defaultResourceId = 1;
+ private String url = "google.com";
+
+ @Before
+ public void beforeEachTest() {
+ imageTagFactory = new ImageTagFactory(9, 12, 1);
+ }
+
+ @Test
+ public void shouldSetNormalPropertiesOnTheImageTag() {
+ ImageTag imageTag = imageTagFactory.build(url);
+
+ assertEquals(defaultResourceId, imageTag.getLoadingResourceId());
+ assertEquals(defaultResourceId, imageTag.getNotFoundResourceId());
+ assertEquals(height, imageTag.getHeight());
+ assertEquals(width, imageTag.getWidth());
+ assertEquals(url, imageTag.getUrl());
+ }
+
+ @Test
+ public void shouldSetPreviewProperties() {
+ int previewHeight = 1;
+ int previewWidth = 2;
+ imageTagFactory.usePreviewImage(previewWidth, previewHeight, true);
+ ImageTag imageTag = imageTagFactory.build(url);
+
+ assertEquals(previewHeight, imageTag.getPreviewHeight());
+ assertEquals(previewWidth, imageTag.getPreviewWidth());
+ }
+
+ @Test
+ public void shouldUseTheSameUrlForPreview() {
+ imageTagFactory.usePreviewImage(1, 1, true);
+ ImageTag imageTag = imageTagFactory.build(url);
+
+ assertEquals(url, imageTag.getPreviewUrl());
+ }
+
+ @Test
+ public void shouldNotUseTheSameUrlForPreview() {
+ imageTagFactory.usePreviewImage(1, 1, false);
+ ImageTag imageTag = imageTagFactory.build(url);
+
+ assertNull(imageTag.getPreviewUrl());
+ }
+
+ @Test
+ public void shouldUseDisplaySizes() {
+ final Display display = mock(Display.class);
+ when(display.getHeight()).thenReturn(21);
+ when(display.getWidth()).thenReturn(12);
+ imageTagFactory = new ImageTagFactory(null, 1) {
+ @Override
+ protected Display prepareDisplay(Context context) {
+ return display;
+ }
+ };
+ ImageTag imageTag = imageTagFactory.build(url);
+ assertEquals(21, imageTag.getHeight());
+ assertEquals(12, imageTag.getWidth());
+ }
+
+}
View
88 core/src/test/java/com/novoda/imageloader/core/model/ImageWrapperTest.java
@@ -0,0 +1,88 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.model;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import android.widget.ImageView;
+
+
+public class ImageWrapperTest {
+
+ private ImageWrapper imageWrapper;
+ private ImageView imageView;
+ private ImageTag imageTag;
+
+ @Before
+ public void beforeEachTest() {
+ imageView = mock(ImageView.class);
+ imageTag = mock(ImageTag.class);
+
+ }
+
+ @Test
+ public void shouldNotFailIfImageTagIsNull() {
+ imageWrapper = new ImageWrapper(imageView);
+ }
+
+ @Test
+ public void shouldSetLoadingResourceId() {
+ when(imageTag.getLoadingResourceId()).thenReturn(1);
+ when(imageView.getTag()).thenReturn(imageTag);
+
+ imageWrapper = new ImageWrapper(imageView);
+ assertEquals(1, imageWrapper.getLoadingResourceId());
+ }
+
+ @Test
+ public void shouldSetNotFoundResourceIdIfDefined() {
+ when(imageTag.getNotFoundResourceId()).thenReturn(2);
+ when(imageView.getTag()).thenReturn(imageTag);
+
+ imageWrapper = new ImageWrapper(imageView);
+ assertEquals(2, imageWrapper.getNotFoundResourceId());
+ }
+
+ @Test
+ public void shouldReturnTrueIfCurrentUrlHasChanged() {
+ when(imageTag.getUrl()).thenReturn("url1");
+ when(imageView.getTag()).thenReturn(imageTag);
+
+ imageWrapper = new ImageWrapper(imageView);
+ when(imageTag.getUrl()).thenReturn("url2");
+
+ assertTrue(imageWrapper.isUrlChanged());
+ }
+
+ @Test
+ public void shouldReturnFalseIfCurrentUrlHasNotChanged() {
+ when(imageTag.getUrl()).thenReturn("url1");
+ when(imageView.getTag()).thenReturn(imageTag);
+
+ imageWrapper = new ImageWrapper(imageView);
+ when(imageTag.getUrl()).thenReturn("url1");
+
+ assertFalse(imageWrapper.isUrlChanged());
+ }
+
+}
View
145 core/src/test/java/com/novoda/imageloader/core/network/UrlNetworlManagerTest.java
@@ -0,0 +1,145 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.network;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.novoda.imageloader.core.LoaderSettings;
+import com.novoda.imageloader.core.exception.ImageNotFoundException;
+import com.novoda.imageloader.core.file.FileTestCase;
+import com.novoda.imageloader.core.file.util.FileUtil;
+
+public class UrlNetworlManagerTest extends FileTestCase {
+
+ private UrlNetworkManager urlNetworkManager;
+ private LoaderSettings loaderSettings;
+ private HttpURLConnection httpURLConnection;
+ private FileUtil fileUtil;
+ private File imageFile;
+
+ @Before
+ public void beforeEachTest() throws IOException {
+ loaderSettings = mock(LoaderSettings.class);
+ fileUtil = mock(FileUtil.class);
+ when(loaderSettings.getSdkVersion()).thenReturn("8");
+ httpURLConnection = mock(HttpURLConnection.class);
+ urlNetworkManager = new UrlNetworkManager(loaderSettings, fileUtil) {
+ @Override
+ protected HttpURLConnection openConnection(String url) throws IOException, MalformedURLException {
+ return httpURLConnection;
+ }
+ };
+ createCacheDir();
+ imageFile = new File(cacheDir.getAbsolutePath() + "/test.jpg");
+ imageFile.createNewFile();
+ }
+
+ @After
+ public void afterEachTest() {
+ deleteCacheDir();
+ }
+
+ @Test(expected = ImageNotFoundException.class)
+ public void shouldThrowFileNotFoundExecptionIfFileDoesNotExists() throws IOException {
+ File imageFile = new File(cacheDir.getAbsolutePath() + "/");
+ imageFile.createNewFile();
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ }
+
+ @Test
+ public void shouldExecuteCopyStream() {
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ verify(fileUtil).copyStream(any(InputStream.class), any(FileOutputStream.class));
+ }
+
+ @Test
+ public void shouldAlwaysCallStreams() {
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ verify(fileUtil, atLeast(2)).closeSilently(any(Closeable.class));
+ }
+
+ @Test
+ public void shouldCallDisconnectIfDefinedInSettings() {
+ when(loaderSettings.getDisconnectOnEveryCall()).thenReturn(true);
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ verify(httpURLConnection).disconnect();
+ }
+
+ @Test
+ public void shouldAvoidToDisconnectIfNotDefinedInSettings() {
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ verify(httpURLConnection, never()).disconnect();
+ }
+
+ @Test
+ public void shouldFailGracefullyForUnknownExceptions() throws IOException {
+ when(httpURLConnection.getInputStream()).thenThrow(new IOException());
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ verify(httpURLConnection, never()).disconnect();
+ }
+
+ @Test
+ public void shouldSetKeepAliveSystemPropertyForApiLevelOlderThan8() {
+ System.setProperty("http.keepAlive", "true");
+ assertEquals("true", System.getProperty("http.keepAlive"));
+ when(loaderSettings.getSdkVersion()).thenReturn("4");
+
+ urlNetworkManager.retrieveImage("http://king.com", imageFile);
+ assertEquals("false", System.getProperty("http.keepAlive"));
+ }
+
+ @Test
+ public void shouldRetrieveInputStream() throws IOException {
+ InputStream expected = mock(InputStream.class);
+ when(httpURLConnection.getInputStream()).thenReturn(expected);
+ InputStream actual = urlNetworkManager.retrieveInputStream("http://king.com");
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void shouldRetrieveNullInputStreamForUnknownExceptions() throws IOException {
+ when(httpURLConnection.getInputStream()).thenThrow(new IOException());
+ InputStream actual = urlNetworkManager.retrieveInputStream("http://king.com");
+ assertNull(actual);
+ }
+
+ @Test(expected = ImageNotFoundException.class)
+ public void shouldThrowImageNotFoundExceptionForFileNotFoundException() throws IOException {
+ when(httpURLConnection.getInputStream()).thenThrow(new FileNotFoundException());
+ urlNetworkManager.retrieveInputStream("http://king.com");
+ }
+
+}
View
36 ...da/imageloader/core/util/UrlUtilTest.java → ...imageloader/core/network/UrlUtilTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.novoda.imageloader.core.util;
+package com.novoda.imageloader.core.network;
import static org.junit.Assert.assertEquals;
@@ -22,22 +22,22 @@
import com.novoda.imageloader.core.network.UrlUtil;
public class UrlUtilTest {
-
- private UrlUtil urlUtil = new UrlUtil();
-
- @Test
- public void SHOULD_removeQueryFromUrlReturnNul_WHEN_urlIsNull() {
- assertEquals(null, urlUtil.removeQuery(null));
- }
-
- @Test
- public void SHOULD_removeQueryFromUrlReturnUnmodifiedUrl_WHEN_qeryNotPresent() {
- assertEquals("http://www.google.com", urlUtil.removeQuery("http://www.google.com"));
- }
-
- @Test
- public void SHOULD_removeQueryFromUrl() {
- assertEquals("http://www.google.com", urlUtil.removeQuery("http://www.google.com?q=test"));
- }
+
+ private UrlUtil urlUtil = new UrlUtil();
+
+ @Test
+ public void SHOULD_removeQueryFromUrlReturnNul_WHEN_urlIsNull() {
+ assertEquals(null, urlUtil.removeQuery(null));
+ }
+
+ @Test
+ public void SHOULD_removeQueryFromUrlReturnUnmodifiedUrl_WHEN_qeryNotPresent() {
+ assertEquals("http://www.google.com", urlUtil.removeQuery("http://www.google.com"));
+ }
+
+ @Test
+ public void SHOULD_removeQueryFromUrl() {
+ assertEquals("http://www.google.com", urlUtil.removeQuery("http://www.google.com?q=test"));
+ }
}
View
78 core/src/test/java/com/novoda/imageloader/core/util/DirectLoaderTest.java
@@ -0,0 +1,78 @@
+/**
+ * Copyright 2012 Novoda Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.novoda.imageloader.core.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import java.io.InputStream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import android.graphics.Bitmap;
+
+import com.novoda.imageloader.core.bitmap.BitmapUtil;
+import com.novoda.imageloader.core.network.NetworkManager;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({ Bitmap.class })
+public class DirectLoaderTest {
+
+ private DirectLoader directLoader;
+ private NetworkManager networkManager;
+ private BitmapUtil bitmapUtil;
+ private String url = "http://www.google.com";
+
+ @Before
+ public void beforeEachTest() {
+ networkManager = Mockito.mock(NetworkManager.class);
+ bitmapUtil = Mockito.mock(BitmapUtil.class);
+ directLoader = new DirectLoader(networkManager, bitmapUtil);
+ }
+
+ @Test
+ public void shouldReturnNullIfUrlIsNull() {
+ assertNull(directLoader.download(null));
+ }
+
+ @Test
+ public void shouldReturnNullIfUrlIsEmpty() {
+ assertNull(directLoader.download(""));
+ }
+
+ @Test
+ public void shouldReturnNullIfIsNotPossibleToGetAnInputStreamFromNetwrokResource() {
+ Mockito.when(networkManager.retrieveInputStream(url)).thenReturn(null);
+ assertNull(directLoader.download(url));
+ }
+
+ @Test
+ public void shouldReturnBitmapFromHttpResource() {
+ InputStream is = Mockito.mock(InputStream.class);
+ Mockito.when(networkManager.retrieveInputStream(url)).thenReturn(is);
+ Bitmap expectedBitmap = PowerMockito.mock(Bitmap.class);
+ PowerMockito.when(bitmapUtil.decodeInputStream(is)).thenReturn(expectedBitmap);
+ Bitmap actualBitmap = directLoader.download(url);
+ assertEquals(expectedBitmap, actualBitmap);
+ }
+
+}
View
2  core/src/test/resources/testFile1
@@ -0,0 +1,2 @@
+this file is used by testing
+the content should be copied over to another file
View
24 demo/res/layout/single_table_base_list_activity.xml
@@ -1,8 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent"
+ android:orientation="vertical" >
-<ListView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@android:id/android:list"
- android:layout_height="match_parent"
- android:layout_width="match_parent"
- android:smoothScrollbar="true" />
+<!-- added by dwa012 -->
+ <Button
+ android:id="@+id/refresh_button"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="refresh" />
+
+ <ListView
+ android:id="@android:id/android:list"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:smoothScrollbar="true" />
+
+</LinearLayout>
View
3  demo/src/com/novoda/imageloader/demo/DemoApplication.java
@@ -57,7 +57,8 @@ private void verboseImageManagerSettings() {
settingsBuilder.withAsyncTasks(false);
//You can set a specific directory for caching files on the sdcard
- settingsBuilder.withCacheDir(new File("/something"));
+// settingsBuilder.withCacheDir(new File("/something"));
+
//Setting this to false means that file cache will use the url without the query part
//for the generation of the hashname
View
15 demo/src/com/novoda/imageloader/demo/activity/BigImages.java
@@ -3,6 +3,8 @@
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter.ViewBinder;
@@ -43,6 +45,19 @@ public void onCreate(Bundle savedInstanceState) {
imageTagFactory = new ImageTagFactory(this, R.drawable.bg_img_loading);
imageTagFactory.setErrorImageId(R.drawable.bg_img_notfound);
setAdapter();
+
+ //added by dwa012
+ Button button = (Button) this.findViewById(R.id.refresh_button);
+ button.setOnClickListener(new OnClickListener(){
+
+ @Override
+ public void onClick(View v) {
+ refreshData();
+
+
+ }
+
+ });
}
/**
View
15 demo/src/com/novoda/imageloader/demo/activity/ImageLongList.java
@@ -3,6 +3,8 @@
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter.ViewBinder;
@@ -47,6 +49,19 @@ public void onCreate(Bundle savedInstanceState) {
imageTagFactory.setErrorImageId(R.drawable.bg_img_notfound);
imageTagFactory.setSaveThumbnail(true);
setAdapter();
+
+ //added by dwa012
+ Button button = (Button) this.findViewById(R.id.refresh_button);
+ button.setOnClickListener(new OnClickListener(){
+
+ @Override
+ public void onClick(View v) {
+ refreshData();
+
+
+ }
+
+ });
}
/**
View
16 demo/src/com/novoda/imageloader/demo/activity/LongSmallImageList.java
@@ -3,7 +3,10 @@
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
import android.widget.ImageView;
+import android.widget.ListView;
import android.widget.SimpleCursorAdapter.ViewBinder;
import com.novoda.imageloader.core.ImageManager;
@@ -50,6 +53,19 @@ public void onCreate(Bundle savedInstanceState) {
imageTagFactory.setErrorImageId(R.drawable.bg_img_notfound);
imageTagFactory.setSaveThumbnail(true);
setAdapter();
+
+ //added by dwa012
+ Button button = (Button) this.findViewById(R.id.refresh_button);
+ button.setOnClickListener(new OnClickListener(){
+
+ @Override
+ public void onClick(View v) {
+ refreshData();
+
+
+ }
+
+ });
}
/**
View
14 demo/src/com/novoda/imageloader/demo/activity/base/SingleTableBaseListActivity.java
@@ -13,6 +13,9 @@
private static final String[] FROM = new String[] { "url" };
private static final int[] TO = new int[] { R.id.list_item_image };
+
+ //added by dwa012
+ private SimpleCursorAdapter adapter;
protected int getImageItem() {
return R.layout.image_item;
@@ -30,7 +33,10 @@ private Cursor getCursor() {
protected abstract String getTableName();
protected void setAdapter() {
- SimpleCursorAdapter adapter = initAdapter();
+
+ //changed by dwa012
+// SimpleCursorAdapter adapter = initAdapter();
+ adapter = initAdapter();
ListView lv = getListView();
ViewBinder binder = getViewBinder();
if (binder != null) {
@@ -38,6 +44,12 @@ protected void setAdapter() {
}
lv.setAdapter(adapter);
}
+
+ //added by dwa012
+ protected void refreshData(){
+ adapter.notifyDataSetChanged();
+ }
+
protected abstract ViewBinder getViewBinder();
Please sign in to comment.
Something went wrong with that request. Please try again.