diff options
Diffstat (limited to 'app/src/androidTest/java')
16 files changed, 138 insertions, 141 deletions
diff --git a/app/src/androidTest/java/de/test/antennapod/gpodnet/GPodnetServiceTest.java b/app/src/androidTest/java/de/test/antennapod/gpodnet/GPodnetServiceTest.java index 3ca7906cb..a880c330b 100644 --- a/app/src/androidTest/java/de/test/antennapod/gpodnet/GPodnetServiceTest.java +++ b/app/src/androidTest/java/de/test/antennapod/gpodnet/GPodnetServiceTest.java @@ -11,6 +11,8 @@ import de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetDevice; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetTag; +import static java.util.Collections.singletonList; + /** * Test class for GpodnetService */ @@ -38,14 +40,14 @@ public class GPodnetServiceTest extends AndroidTestCase { public void testUploadSubscription() throws GpodnetServiceException { authenticate(); - ArrayList<String> l = new ArrayList<String>(); + ArrayList<String> l = new ArrayList<>(); l.add("http://bitsundso.de/feed"); service.uploadSubscriptions(USER, "radio", l); } public void testUploadSubscription2() throws GpodnetServiceException { authenticate(); - ArrayList<String> l = new ArrayList<String>(); + ArrayList<String> l = new ArrayList<>(); l.add("http://bitsundso.de/feed"); l.add("http://gamesundso.de/feed"); service.uploadSubscriptions(USER, "radio", l); @@ -55,7 +57,7 @@ public class GPodnetServiceTest extends AndroidTestCase { authenticate(); String[] URLS = {"http://bitsundso.de/feed", "http://gamesundso.de/feed", "http://cre.fm/feed/mp3/", "http://freakshow.fm/feed/m4a/"}; List<String> subscriptions = Arrays.asList(URLS[0], URLS[1]); - List<String> removed = Arrays.asList(URLS[0]); + List<String> removed = singletonList(URLS[0]); List<String> added = Arrays.asList(URLS[2], URLS[3]); service.uploadSubscriptions(USER, "radio", subscriptions); service.uploadChanges(USER, "radio", added, removed); diff --git a/app/src/androidTest/java/de/test/antennapod/handler/FeedHandlerTest.java b/app/src/androidTest/java/de/test/antennapod/handler/FeedHandlerTest.java index ee454ce8a..39abe4b7a 100644 --- a/app/src/androidTest/java/de/test/antennapod/handler/FeedHandlerTest.java +++ b/app/src/androidTest/java/de/test/antennapod/handler/FeedHandlerTest.java @@ -32,8 +32,8 @@ import de.test.antennapod.util.syndication.feedgenerator.RSS2Generator; public class FeedHandlerTest extends InstrumentationTestCase { private static final String FEEDS_DIR = "testfeeds"; - File file = null; - OutputStream outputStream = null; + private File file = null; + private OutputStream outputStream = null; protected void setUp() throws Exception { super.setUp(); @@ -165,7 +165,7 @@ public class FeedHandlerTest extends InstrumentationTestCase { Feed feed = new Feed(0, null, "title", "http://example.com", "This is the description", "http://example.com/payment", "Daniel", "en", null, "http://example.com/feed", image, file.getAbsolutePath(), "http://example.com/feed", true); - feed.setItems(new ArrayList<FeedItem>()); + feed.setItems(new ArrayList<>()); for (int i = 0; i < numItems; i++) { FeedItem item = new FeedItem(0, "item-" + i, "http://example.com/item-" + i, diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java b/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java index 5e5eb1e8b..5cd4e9906 100644 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java +++ b/app/src/androidTest/java/de/test/antennapod/storage/DBCleanupTests.java @@ -27,12 +27,12 @@ import static de.test.antennapod.storage.DBTestUtils.saveFeedlist; public class DBCleanupTests extends InstrumentationTestCase { private static final String TAG = "DBTasksTest"; - protected static final int EPISODE_CACHE_SIZE = 5; + static final int EPISODE_CACHE_SIZE = 5; private final int cleanupAlgorithm; - protected Context context; + Context context; - protected File destFolder; + private File destFolder; public DBCleanupTests() { this.cleanupAlgorithm = UserPreferences.EPISODE_CLEANUP_DEFAULT; @@ -104,9 +104,9 @@ public class DBCleanupTests extends InstrumentationTestCase { } } - protected void populateItems(final int numItems, Feed feed, List<FeedItem> items, - List<File> files, int itemState, boolean addToQueue, - boolean addToFavorites) throws IOException { + void populateItems(final int numItems, Feed feed, List<FeedItem> items, + List<File> files, int itemState, boolean addToQueue, + boolean addToFavorites) throws IOException { for (int i = 0; i < numItems; i++) { Date itemDate = new Date(numItems - i); Date playbackCompletionDate = null; @@ -145,9 +145,9 @@ public class DBCleanupTests extends InstrumentationTestCase { final int NUM_ITEMS = EPISODE_CACHE_SIZE * 2; Feed feed = new Feed("url", null, "title"); - List<FeedItem> items = new ArrayList<FeedItem>(); + List<FeedItem> items = new ArrayList<>(); feed.setItems(items); - List<File> files = new ArrayList<File>(); + List<File> files = new ArrayList<>(); populateItems(NUM_ITEMS, feed, items, files, FeedItem.UNPLAYED, false, false); DBTasks.performAutoCleanup(context); diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java b/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java index 785d32e93..93a9408b7 100644 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java +++ b/app/src/androidTest/java/de/test/antennapod/storage/DBTasksTest.java @@ -18,6 +18,8 @@ import de.danoeh.antennapod.core.storage.DBReader; import de.danoeh.antennapod.core.storage.DBTasks; import de.danoeh.antennapod.core.storage.PodDBAdapter; +import static java.util.Collections.singletonList; + /** * Test class for DBTasks */ @@ -100,7 +102,7 @@ public class DBTasksTest extends InstrumentationTestCase { assertTrue(feed.getId() != 0); final long feedID = feed.getId(); feed.setId(0); - List<Long> itemIDs = new ArrayList<Long>(); + List<Long> itemIDs = new ArrayList<>(); for (FeedItem item : feed.getItems()) { assertTrue(item.getId() != 0); itemIDs.add(item.getId()); @@ -125,7 +127,7 @@ public class DBTasksTest extends InstrumentationTestCase { public void testUpdateFeedMediaUrlResetState() { final Feed feed = new Feed("url", null, "title"); FeedItem item = new FeedItem(0, "item", "id", "link", new Date(), FeedItem.PLAYED, feed); - feed.setItems(Arrays.asList(item)); + feed.setItems(singletonList(item)); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); @@ -138,7 +140,7 @@ public class DBTasksTest extends InstrumentationTestCase { FeedMedia media = new FeedMedia(item, "url", 1024, "mime/type"); item.setMedia(media); - feed.setItems(Arrays.asList(item)); + feed.setItems(singletonList(item)); final Feed newFeed = DBTasks.updateFeed(context, feed)[0]; assertTrue(feed != newFeed); diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBTestUtils.java b/app/src/androidTest/java/de/test/antennapod/storage/DBTestUtils.java index d02efa521..c9c715a86 100644 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBTestUtils.java +++ b/app/src/androidTest/java/de/test/antennapod/storage/DBTestUtils.java @@ -19,7 +19,7 @@ import de.danoeh.antennapod.core.util.flattr.FlattrStatus; /** * Utility methods for DB* tests. */ -public class DBTestUtils { +class DBTestUtils { /** * Use this method when tests don't involve chapters. diff --git a/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java b/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java index 40083e507..b1cc807ea 100644 --- a/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java +++ b/app/src/androidTest/java/de/test/antennapod/storage/DBWriterTest.java @@ -138,7 +138,7 @@ public class DBWriterTest extends InstrumentationTestCase { image.setOwner(feed); feed.setImage(image); - List<File> itemFiles = new ArrayList<File>(); + List<File> itemFiles = new ArrayList<>(); // create items with downloaded media files for (int i = 0; i < 10; i++) { FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed, true); @@ -151,7 +151,7 @@ public class DBWriterTest extends InstrumentationTestCase { FeedMedia media = new FeedMedia(0, item, 1, 1, 1, "mime_type", enc.getAbsolutePath(), "download_url", true, null, 0, 0); item.setMedia(media); - item.setChapters(new ArrayList<Chapter>()); + item.setChapters(new ArrayList<>()); item.getChapters().add(new SimpleChapter(0, "item " + i, item, "example.com")); } @@ -207,7 +207,7 @@ public class DBWriterTest extends InstrumentationTestCase { feed.setImage(null); - List<File> itemFiles = new ArrayList<File>(); + List<File> itemFiles = new ArrayList<>(); // create items with downloaded media files for (int i = 0; i < 10; i++) { FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); @@ -418,7 +418,7 @@ public class DBWriterTest extends InstrumentationTestCase { image.setOwner(feed); feed.setImage(image); - List<File> itemFiles = new ArrayList<File>(); + List<File> itemFiles = new ArrayList<>(); // create items with downloaded media files for (int i = 0; i < 10; i++) { FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); @@ -444,7 +444,7 @@ public class DBWriterTest extends InstrumentationTestCase { } - List<FeedItem> queue = new ArrayList<FeedItem>(); + List<FeedItem> queue = new ArrayList<>(); queue.addAll(feed.getItems()); adapter.open(); adapter.setQueue(queue); @@ -482,7 +482,7 @@ public class DBWriterTest extends InstrumentationTestCase { assertNotNull(destFolder); Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<FeedItem>()); + feed.setItems(new ArrayList<>()); // create Feed image File imgFile = new File(destFolder, "image"); @@ -490,7 +490,7 @@ public class DBWriterTest extends InstrumentationTestCase { image.setOwner(feed); feed.setImage(image); - List<File> itemFiles = new ArrayList<File>(); + List<File> itemFiles = new ArrayList<>(); // create items with downloaded media files for (int i = 0; i < 10; i++) { FeedItem item = new FeedItem(0, "Item " + i, "Item" + i, "url", new Date(), FeedItem.PLAYED, feed); @@ -539,7 +539,7 @@ public class DBWriterTest extends InstrumentationTestCase { private FeedMedia playbackHistorySetup(Date playbackCompletionDate) { final Context context = getInstrumentation().getTargetContext(); Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<FeedItem>()); + feed.setItems(new ArrayList<>()); FeedItem item = new FeedItem(0, "title", "id", "link", new Date(), FeedItem.PLAYED, feed); FeedMedia media = new FeedMedia(0, item, 10, 0, 1, "mime", null, "url", false, playbackCompletionDate, 0, 0); feed.getItems().add(item); @@ -598,7 +598,7 @@ public class DBWriterTest extends InstrumentationTestCase { for (FeedItem item : feed.getItems()) { assertTrue(item.getId() != 0); } - List<Future<?>> futures = new ArrayList<Future<?>>(); + List<Future<?>> futures = new ArrayList<>(); for (FeedItem item : feed.getItems()) { futures.add(DBWriter.addQueueItem(context, item)); } @@ -791,7 +791,7 @@ public class DBWriterTest extends InstrumentationTestCase { public void testMarkFeedRead() throws InterruptedException, ExecutionException, TimeoutException { final int NUM_ITEMS = 10; Feed feed = new Feed("url", null, "title"); - feed.setItems(new ArrayList<FeedItem>()); + feed.setItems(new ArrayList<>()); for (int i = 0; i < NUM_ITEMS; i++) { FeedItem item = new FeedItem(0, "title " + i, "id " + i, "link " + i, new Date(), FeedItem.UNPLAYED, feed); feed.getItems().add(item); diff --git a/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java b/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java index bd9057b47..6156da926 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/MainActivityTest.java @@ -15,6 +15,7 @@ import java.util.List; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.MainActivity; import de.danoeh.antennapod.activity.OnlineFeedViewActivity; +import de.danoeh.antennapod.activity.PreferenceActivity; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.storage.PodDBAdapter; @@ -22,7 +23,6 @@ import de.danoeh.antennapod.fragment.DownloadsFragment; import de.danoeh.antennapod.fragment.EpisodesFragment; import de.danoeh.antennapod.fragment.PlaybackHistoryFragment; import de.danoeh.antennapod.fragment.QueueFragment; -import de.danoeh.antennapod.preferences.PreferenceController; /** * User interface tests for MainActivity @@ -96,7 +96,7 @@ public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActiv public void testClickNavDrawer() throws Exception { uiTestUtils.addLocalFeedData(false); - UserPreferences.setHiddenDrawerItems(new ArrayList<String>()); + UserPreferences.setHiddenDrawerItems(new ArrayList<>()); // queue openNavDrawer(); @@ -155,11 +155,11 @@ public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActiv public void testGoToPreferences() { openNavDrawer(); solo.clickOnText(solo.getString(R.string.settings_label)); - solo.waitForActivity(PreferenceController.getPreferenceActivity()); + solo.waitForActivity(PreferenceActivity.class); } public void testDrawerPreferencesHideSomeElements() { - UserPreferences.setHiddenDrawerItems(new ArrayList<String>()); + UserPreferences.setHiddenDrawerItems(new ArrayList<>()); openNavDrawer(); solo.clickLongOnText(solo.getString(R.string.queue_label)); solo.waitForDialogToOpen(); @@ -190,7 +190,7 @@ public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActiv } public void testDrawerPreferencesHideAllElements() { - UserPreferences.setHiddenDrawerItems(new ArrayList<String>()); + UserPreferences.setHiddenDrawerItems(new ArrayList<>()); String[] titles = getInstrumentation().getTargetContext().getResources().getStringArray(R.array.nav_drawer_titles); openNavDrawer(); @@ -209,7 +209,7 @@ public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActiv } public void testDrawerPreferencesHideCurrentElement() { - UserPreferences.setHiddenDrawerItems(new ArrayList<String>()); + UserPreferences.setHiddenDrawerItems(new ArrayList<>()); openNavDrawer(); String downloads = solo.getString(R.string.downloads_label); diff --git a/app/src/androidTest/java/de/test/antennapod/ui/PlaybackSonicTest.java b/app/src/androidTest/java/de/test/antennapod/ui/PlaybackSonicTest.java index bfbeedd83..293ed2848 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/PlaybackSonicTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/PlaybackSonicTest.java @@ -33,8 +33,8 @@ import de.danoeh.antennapod.core.storage.PodDBAdapter; public class PlaybackSonicTest extends ActivityInstrumentationTestCase2<MainActivity> { private static final String TAG = PlaybackTest.class.getSimpleName(); - public static final int EPISODES_DRAWER_LIST_INDEX = 1; - public static final int QUEUE_DRAWER_LIST_INDEX = 0; + private static final int EPISODES_DRAWER_LIST_INDEX = 1; + private static final int QUEUE_DRAWER_LIST_INDEX = 0; private Solo solo; private UITestUtils uiTestUtils; diff --git a/app/src/androidTest/java/de/test/antennapod/ui/PlaybackTest.java b/app/src/androidTest/java/de/test/antennapod/ui/PlaybackTest.java index 661c2200b..74d59abd7 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/PlaybackTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/PlaybackTest.java @@ -30,8 +30,8 @@ import de.danoeh.antennapod.core.storage.PodDBAdapter; public class PlaybackTest extends ActivityInstrumentationTestCase2<MainActivity> { private static final String TAG = PlaybackTest.class.getSimpleName(); - public static final int EPISODES_DRAWER_LIST_INDEX = 1; - public static final int QUEUE_DRAWER_LIST_INDEX = 0; + private static final int EPISODES_DRAWER_LIST_INDEX = 1; + private static final int QUEUE_DRAWER_LIST_INDEX = 0; private Solo solo; private UITestUtils uiTestUtils; diff --git a/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java b/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java index e18c9ca16..fb74378c7 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/PreferencesTest.java @@ -96,10 +96,10 @@ public class PreferencesTest extends ActivityInstrumentationTestCase2<Preference solo.clickOnText(solo.getString(R.string.pref_compact_notification_buttons_title)); solo.waitForDialogToOpen(1000); // First uncheck every checkbox - for (int i=0; i<buttons.length; i++) { - assertTrue(solo.searchText(buttons[i])); - if (solo.isTextChecked(buttons[i])) { - solo.clickOnText(buttons[i]); + for (String button : buttons) { + assertTrue(solo.searchText(button)); + if (solo.isTextChecked(button)) { + solo.clickOnText(button); } } // Now try to check all checkboxes @@ -110,8 +110,8 @@ public class PreferencesTest extends ActivityInstrumentationTestCase2<Preference assertTrue(!solo.isTextChecked(buttons[2])); solo.clickOnText(solo.getString(R.string.confirm_label)); solo.waitForDialogToClose(1000); - assertTrue(solo.waitForCondition(() -> UserPreferences.showRewindOnCompactNotification(), Timeout.getLargeTimeout())); - assertTrue(solo.waitForCondition(() -> UserPreferences.showFastForwardOnCompactNotification(), Timeout.getLargeTimeout())); + assertTrue(solo.waitForCondition(UserPreferences::showRewindOnCompactNotification, Timeout.getLargeTimeout())); + assertTrue(solo.waitForCondition(UserPreferences::showFastForwardOnCompactNotification, Timeout.getLargeTimeout())); assertTrue(solo.waitForCondition(() -> !UserPreferences.showSkipOnCompactNotification(), Timeout.getLargeTimeout())); } @@ -134,7 +134,7 @@ public class PreferencesTest extends ActivityInstrumentationTestCase2<Preference public void testHeadPhonesReconnect() { if(UserPreferences.isPauseOnHeadsetDisconnect() == false) { solo.clickOnText(solo.getString(R.string.pref_pauseOnHeadsetDisconnect_title)); - assertTrue(solo.waitForCondition(() -> UserPreferences.isPauseOnHeadsetDisconnect(), Timeout.getLargeTimeout())); + assertTrue(solo.waitForCondition(UserPreferences::isPauseOnHeadsetDisconnect, Timeout.getLargeTimeout())); } final boolean unpauseOnHeadsetReconnect = UserPreferences.isUnpauseOnHeadsetReconnect(); solo.clickOnText(solo.getString(R.string.pref_unpauseOnHeadsetReconnect_title)); @@ -146,7 +146,7 @@ public class PreferencesTest extends ActivityInstrumentationTestCase2<Preference public void testBluetoothReconnect() { if(UserPreferences.isPauseOnHeadsetDisconnect() == false) { solo.clickOnText(solo.getString(R.string.pref_pauseOnHeadsetDisconnect_title)); - assertTrue(solo.waitForCondition(() -> UserPreferences.isPauseOnHeadsetDisconnect(), Timeout.getLargeTimeout())); + assertTrue(solo.waitForCondition(UserPreferences::isPauseOnHeadsetDisconnect, Timeout.getLargeTimeout())); } final boolean unpauseOnBluetoothReconnect = UserPreferences.isUnpauseOnBluetoothReconnect(); solo.clickOnText(solo.getString(R.string.pref_unpauseOnBluetoothReconnect_title)); diff --git a/app/src/androidTest/java/de/test/antennapod/ui/UITestUtils.java b/app/src/androidTest/java/de/test/antennapod/ui/UITestUtils.java index 11e033e51..3af22af9d 100644 --- a/app/src/androidTest/java/de/test/antennapod/ui/UITestUtils.java +++ b/app/src/androidTest/java/de/test/antennapod/ui/UITestUtils.java @@ -1,9 +1,7 @@ package de.test.antennapod.ui; -import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; -import android.os.Build; import android.util.Log; import junit.framework.Assert; @@ -20,7 +18,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.MainActivity; import de.danoeh.antennapod.core.event.QueueEvent; import de.danoeh.antennapod.core.feed.EventDistributor; @@ -39,27 +36,25 @@ import de.test.antennapod.util.syndication.feedgenerator.RSS2Generator; * Utility methods for UI tests. * Starts a web server that hosts feeds, episodes and images. */ -@TargetApi(Build.VERSION_CODES.HONEYCOMB) -public class UITestUtils { +class UITestUtils { private static final String TAG = UITestUtils.class.getSimpleName(); private static final String DATA_FOLDER = "test/UITestUtils"; - public static final int NUM_FEEDS = 5; - public static final int NUM_ITEMS_PER_FEED = 10; + private static final int NUM_FEEDS = 5; + private static final int NUM_ITEMS_PER_FEED = 10; - public static final int HOME_VIEW = (Build.VERSION.SDK_INT >= 11) ? android.R.id.home : R.id.home; - public static final String TEST_FILE_NAME = "3sec.mp3"; + private static final String TEST_FILE_NAME = "3sec.mp3"; - private Context context; - private HTTPBin server = new HTTPBin(); + private final Context context; + private final HTTPBin server = new HTTPBin(); private File destDir; private File hostedFeedDir; private File hostedMediaDir; - public List<Feed> hostedFeeds = new ArrayList<Feed>(); + public final List<Feed> hostedFeeds = new ArrayList<>(); public UITestUtils(Context context) { this.context = context; @@ -149,7 +144,7 @@ public class UITestUtils { image.setOwner(feed); // create items - List<FeedItem> items = new ArrayList<FeedItem>(); + List<FeedItem> items = new ArrayList<>(); for (int j = 0; j < NUM_ITEMS_PER_FEED; j++) { FeedItem item = new FeedItem(j, "Feed " + (i+1) + ": Item " + (j+1), "item" + j, "http://example.com/feed" + i + "/item/" + j, new Date(), FeedItem.UNPLAYED, feed); diff --git a/app/src/androidTest/java/de/test/antennapod/util/service/download/HTTPBin.java b/app/src/androidTest/java/de/test/antennapod/util/service/download/HTTPBin.java index 2f2c3fe5b..cde93fd7e 100644 --- a/app/src/androidTest/java/de/test/antennapod/util/service/download/HTTPBin.java +++ b/app/src/androidTest/java/de/test/antennapod/util/service/download/HTTPBin.java @@ -45,11 +45,11 @@ public class HTTPBin extends NanoHTTPD { private static final String MIME_HTML = "text/html"; private static final String MIME_PLAIN = "text/plain"; - private List<File> servedFiles; + private final List<File> servedFiles; public HTTPBin() { super(PORT); - this.servedFiles = new ArrayList<File>(); + this.servedFiles = new ArrayList<>(); } /** diff --git a/app/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java b/app/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java index 28ff6694e..61ff65809 100644 --- a/app/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java +++ b/app/src/androidTest/java/de/test/antennapod/util/service/download/NanoHTTPD.java @@ -88,15 +88,15 @@ public abstract class NanoHTTPD { * This is required as the Keep-Alive HTTP connections would otherwise * block the socket reading thread forever (or as long the browser is open). */ - public static final int SOCKET_READ_TIMEOUT = 5000; + private static final int SOCKET_READ_TIMEOUT = 5000; /** * Common mime type for dynamic content: plain text */ - public static final String MIME_PLAINTEXT = "text/plain"; + private static final String MIME_PLAINTEXT = "text/plain"; /** * Common mime type for dynamic content: html */ - public static final String MIME_HTML = "text/html"; + private static final String MIME_HTML = "text/html"; /** * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing. */ @@ -104,7 +104,7 @@ public abstract class NanoHTTPD { private final String hostname; private final int myPort; private ServerSocket myServerSocket; - private Set<Socket> openConnections = new HashSet<Socket>(); + private final Set<Socket> openConnections = new HashSet<>(); private Thread myThread; /** * Pluggable strategy for asynchronously executing requests. @@ -118,14 +118,14 @@ public abstract class NanoHTTPD { /** * Constructs an HTTP server on given port. */ - public NanoHTTPD(int port) { + NanoHTTPD(int port) { this(null, port); } /** * Constructs an HTTP server on given hostname and port. */ - public NanoHTTPD(String hostname, int port) { + private NanoHTTPD(String hostname, int port) { this.hostname = hostname; this.myPort = port; setTempFileManagerFactory(new DefaultTempFileManagerFactory()); @@ -168,44 +168,38 @@ public abstract class NanoHTTPD { myServerSocket = new ServerSocket(); myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); - myThread = new Thread(new Runnable() { - @Override - public void run() { - do { - try { - final Socket finalAccept = myServerSocket.accept(); - registerConnection(finalAccept); - finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); - final InputStream inputStream = finalAccept.getInputStream(); - asyncRunner.exec(new Runnable() { - @Override - public void run() { - OutputStream outputStream = null; - try { - outputStream = finalAccept.getOutputStream(); - TempFileManager tempFileManager = tempFileManagerFactory.create(); - HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); - while (!finalAccept.isClosed()) { - session.execute(); - } - } catch (Exception e) { - // When the socket is closed by the client, we throw our own SocketException - // to break the "keep alive" loop above. - if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { - e.printStackTrace(); - } - } finally { - safeClose(outputStream); - safeClose(inputStream); - safeClose(finalAccept); - unRegisterConnection(finalAccept); - } + myThread = new Thread(() -> { + do { + try { + final Socket finalAccept = myServerSocket.accept(); + registerConnection(finalAccept); + finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); + final InputStream inputStream = finalAccept.getInputStream(); + asyncRunner.exec(() -> { + OutputStream outputStream = null; + try { + outputStream = finalAccept.getOutputStream(); + TempFileManager tempFileManager = tempFileManagerFactory.create(); + HTTPSession session = new HTTPSession(tempFileManager, inputStream, outputStream, finalAccept.getInetAddress()); + while (!finalAccept.isClosed()) { + session.execute(); } - }); - } catch (IOException e) { - } - } while (!myServerSocket.isClosed()); - } + } catch (Exception e) { + // When the socket is closed by the client, we throw our own SocketException + // to break the "keep alive" loop above. + if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { + e.printStackTrace(); + } + } finally { + safeClose(outputStream); + safeClose(inputStream); + safeClose(finalAccept); + unRegisterConnection(finalAccept); + } + }); + } catch (IOException e) { + } + } while (!myServerSocket.isClosed()); }); myThread.setDaemon(true); myThread.setName("NanoHttpd Main Listener"); @@ -232,7 +226,7 @@ public abstract class NanoHTTPD { * * @param socket the {@link Socket} for the connection. */ - public synchronized void registerConnection(Socket socket) { + private synchronized void registerConnection(Socket socket) { openConnections.add(socket); } @@ -242,14 +236,14 @@ public abstract class NanoHTTPD { * @param socket * the {@link Socket} for the connection. */ - public synchronized void unRegisterConnection(Socket socket) { + private synchronized void unRegisterConnection(Socket socket) { openConnections.remove(socket); } /** * Forcibly closes all connections that are open. */ - public synchronized void closeAllConnections() { + private synchronized void closeAllConnections() { for (Socket socket : openConnections) { safeClose(socket); } @@ -259,7 +253,7 @@ public abstract class NanoHTTPD { return myServerSocket == null ? -1 : myServerSocket.getLocalPort(); } - public final boolean wasStarted() { + private boolean wasStarted() { return myServerSocket != null && myThread != null; } @@ -294,7 +288,7 @@ public abstract class NanoHTTPD { * @param session The HTTP session * @return HTTP response, see class Response for details */ - public Response serve(IHTTPSession session) { + Response serve(IHTTPSession session) { Map<String, String> files = new ArrayMap<>(); Method method = session.getMethod(); if (Method.PUT.equals(method) || Method.POST.equals(method)) { @@ -318,7 +312,7 @@ public abstract class NanoHTTPD { * @param str the percent encoded <code>String</code> * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" */ - protected String decodePercent(String str) { + private String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); @@ -347,8 +341,8 @@ public abstract class NanoHTTPD { * @param queryString a query string pulled from the URL. * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied). */ - protected Map<String, List<String>> decodeParameters(String queryString) { - Map<String, List<String>> parms = new ArrayMap<String, List<String>>(); + private Map<String, List<String>> decodeParameters(String queryString) { + Map<String, List<String>> parms = new ArrayMap<>(); if (queryString != null) { StringTokenizer st = new StringTokenizer(queryString, "&"); while (st.hasMoreTokens()) { @@ -356,7 +350,7 @@ public abstract class NanoHTTPD { int sep = e.indexOf('='); String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); if (!parms.containsKey(propertyName)) { - parms.put(propertyName, new ArrayList<String>()); + parms.put(propertyName, new ArrayList<>()); } String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null; if (propertyValue != null) { @@ -378,7 +372,7 @@ public abstract class NanoHTTPD { * * @param asyncRunner new strategy for handling threads. */ - public void setAsyncRunner(AsyncRunner asyncRunner) { + private void setAsyncRunner(AsyncRunner asyncRunner) { this.asyncRunner = asyncRunner; } @@ -393,7 +387,7 @@ public abstract class NanoHTTPD { * * @param tempFileManagerFactory new strategy for handling temp files. */ - public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { + private void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { this.tempFileManagerFactory = tempFileManagerFactory; } @@ -448,9 +442,9 @@ public abstract class NanoHTTPD { * themselves up when no longer needed.</p> */ public interface TempFile { - OutputStream open() throws Exception; + OutputStream open(); - void delete() throws Exception; + void delete(); String getName(); } @@ -490,7 +484,7 @@ public abstract class NanoHTTPD { public DefaultTempFileManager() { tmpdir = System.getProperty("java.io.tmpdir"); - tempFiles = new ArrayList<TempFile>(); + tempFiles = new ArrayList<>(); } @Override @@ -528,12 +522,12 @@ public abstract class NanoHTTPD { } @Override - public OutputStream open() throws Exception { + public OutputStream open() { return fstream; } @Override - public void delete() throws Exception { + public void delete() { safeClose(fstream); file.delete(); } @@ -563,7 +557,7 @@ public abstract class NanoHTTPD { /** * Headers for the HTTP response. Use addHeader() to add lines. */ - private Map<String, String> header = new ArrayMap<String, String>(); + private final Map<String, String> header = new ArrayMap<>(); /** * The request method that spawned this response. */ @@ -616,7 +610,7 @@ public abstract class NanoHTTPD { /** * Sends given response to the socket. */ - protected void send(OutputStream outputStream) { + void send(OutputStream outputStream) { String mime = mimeType; SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); @@ -661,13 +655,13 @@ public abstract class NanoHTTPD { } } - protected void sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, int size) { + void sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, int size) { if (!headerAlreadySent(header, "content-length")) { pw.print("Content-Length: "+ size +"\r\n"); } } - protected void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) { + void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) { if (!headerAlreadySent(header, "connection")) { pw.print("Connection: keep-alive\r\n"); } @@ -694,7 +688,7 @@ public abstract class NanoHTTPD { outputStream.write(buff, 0, read); outputStream.write(CRLF); } - outputStream.write(String.format("0\r\n\r\n").getBytes()); + outputStream.write("0\r\n\r\n".getBytes()); } private void sendAsFixedLength(OutputStream outputStream, int pending) throws IOException { @@ -844,7 +838,7 @@ public abstract class NanoHTTPD { public static final int BUFSIZE = 8192; private final TempFileManager tempFileManager; private final OutputStream outputStream; - private PushbackInputStream inputStream; + private final PushbackInputStream inputStream; private int splitbyte; private int rlen; private String uri; @@ -865,7 +859,7 @@ public abstract class NanoHTTPD { this.inputStream = new PushbackInputStream(inputStream, BUFSIZE); this.outputStream = outputStream; String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString(); - headers = new ArrayMap<String, String>(); + headers = new ArrayMap<>(); headers.put("remote-addr", remoteIp); headers.put("http-client-ip", remoteIp); @@ -909,16 +903,16 @@ public abstract class NanoHTTPD { inputStream.unread(buf, splitbyte, rlen - splitbyte); } - parms = new ArrayMap<String, String>(); + parms = new ArrayMap<>(); if(null == headers) { - headers = new ArrayMap<String, String>(); + headers = new ArrayMap<>(); } // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); // Decode the header into parms and header java properties - Map<String, String> pre = new ArrayMap<String, String>(); + Map<String, String> pre = new ArrayMap<>(); decodeHeader(hin, pre, parms, headers); method = Method.lookup(pre.get("method")); @@ -1116,7 +1110,7 @@ public abstract class NanoHTTPD { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); } boundarycount++; - Map<String, String> item = new ArrayMap<String, String>(); + Map<String, String> item = new ArrayMap<>(); mpline = in.readLine(); while (mpline != null && mpline.trim().length() > 0) { int p = mpline.indexOf(':'); @@ -1131,7 +1125,7 @@ public abstract class NanoHTTPD { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); } StringTokenizer st = new StringTokenizer(contentDisposition, ";"); - Map<String, String> disposition = new ArrayMap<String, String>(); + Map<String, String> disposition = new ArrayMap<>(); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); int p = token.indexOf('='); @@ -1144,17 +1138,19 @@ public abstract class NanoHTTPD { String value = ""; if (item.get("content-type") == null) { + StringBuilder tmp = new StringBuilder(); while (mpline != null && !mpline.contains(boundary)) { mpline = in.readLine(); if (mpline != null) { int d = mpline.indexOf(boundary); if (d == -1) { - value += mpline; + tmp.append(mpline); } else { - value += mpline.substring(0, d - 2); + tmp.append(mpline.substring(0, d - 2)); } } } + value = tmp.toString(); } else { if (boundarycount > bpositions.length) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request"); @@ -1196,7 +1192,7 @@ public abstract class NanoHTTPD { private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { int matchcount = 0; int matchbyte = -1; - List<Integer> matchbytes = new ArrayList<Integer>(); + List<Integer> matchbytes = new ArrayList<>(); for (int i = 0; i < b.limit(); i++) { if (b.get(i) == boundary[matchcount]) { if (matchcount == 0) @@ -1326,7 +1322,9 @@ public abstract class NanoHTTPD { } public static class Cookie { - private String n, v, e; + private final String n; + private final String v; + private final String e; public Cookie(String name, String value, String expires) { n = name; @@ -1366,8 +1364,8 @@ public abstract class NanoHTTPD { * @author LordFokas */ public class CookieHandler implements Iterable<String> { - private ArrayMap<String, String> cookies = new ArrayMap<String, String>(); - private ArrayList<Cookie> queue = new ArrayList<Cookie>(); + private final ArrayMap<String, String> cookies = new ArrayMap<>(); + private final ArrayList<Cookie> queue = new ArrayList<>(); public CookieHandler(Map<String, String> httpHeaders) { String raw = httpHeaders.get("cookie"); diff --git a/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/AtomGenerator.java b/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/AtomGenerator.java index bd3df0f9d..afe15f1b2 100644 --- a/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/AtomGenerator.java +++ b/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/AtomGenerator.java @@ -19,7 +19,7 @@ public class AtomGenerator implements FeedGenerator{ private static final String NS_ATOM = "http://www.w3.org/2005/Atom"; - public static final long FEATURE_USE_RFC3339LOCAL = 1; + private static final long FEATURE_USE_RFC3339LOCAL = 1; @Override public void writeFeed(Feed feed, OutputStream outputStream, String encoding, long flags) throws IOException { diff --git a/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/FeedGenerator.java b/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/FeedGenerator.java index 142e3cb57..b63159384 100644 --- a/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/FeedGenerator.java +++ b/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/FeedGenerator.java @@ -24,5 +24,5 @@ public interface FeedGenerator { * @param encoding The encoding to use. Must not be null. * @param flags Optional argument for enabling implementation-dependent features. */ - public void writeFeed(Feed feed, OutputStream outputStream, String encoding, long flags) throws IOException; + void writeFeed(Feed feed, OutputStream outputStream, String encoding, long flags) throws IOException; } diff --git a/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/GeneratorUtil.java b/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/GeneratorUtil.java index e7cbb1b42..7f6f0fb0f 100644 --- a/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/GeneratorUtil.java +++ b/app/src/androidTest/java/de/test/antennapod/util/syndication/feedgenerator/GeneratorUtil.java @@ -7,7 +7,7 @@ import java.io.IOException; /** * Utility methods for FeedGenerator */ -public class GeneratorUtil { +class GeneratorUtil { public static void addPaymentLink(XmlSerializer xml, String paymentLink, boolean withNamespace) throws IOException { String ns = (withNamespace) ? "http://www.w3.org/2005/Atom" : null; |