Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Use try-with-resources for some streams #6956

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -85,12 +85,12 @@ public void setUp() throws Exception {
assertTrue(cacheDir.canWrite());
assertTrue(cacheDir.canRead());
if (!dest.exists()) {
InputStream i = getInstrumentation().getContext().getAssets().open("3sec.mp3");
OutputStream o = new FileOutputStream(new File(cacheDir, PLAYABLE_DEST_URL));
IOUtils.copy(i, o);
o.flush();
o.close();
i.close();
try (final InputStream i = getInstrumentation().getContext().getAssets().open("3sec.mp3");
final OutputStream o = new FileOutputStream(new File(cacheDir, PLAYABLE_DEST_URL))
) {
IOUtils.copy(i, o);
o.flush();
}
}
PLAYABLE_LOCAL_URL = dest.getAbsolutePath();
assertEquals(0, httpServer.serveFile(dest));
Expand Down
14 changes: 7 additions & 7 deletions app/src/androidTest/java/de/test/antennapod/ui/UITestUtils.java
Expand Up @@ -80,10 +80,10 @@ public void tearDown() throws IOException {

public String hostFeed(Feed feed) throws IOException {
File feedFile = new File(hostedFeedDir, feed.getTitle());
FileOutputStream out = new FileOutputStream(feedFile);
Rss2Generator generator = new Rss2Generator();
generator.writeFeed(feed, out, "UTF-8", 0);
out.close();
try (final FileOutputStream out = new FileOutputStream(feedFile)) {
Rss2Generator generator = new Rss2Generator();
generator.writeFeed(feed, out, "UTF-8", 0);
}
int id = server.serveFile(feedFile);
Assert.assertTrue(id != -1);
return String.format(Locale.US, "%s/files/%d", server.getBaseUrl(), id);
Expand All @@ -106,9 +106,9 @@ private File newMediaFile(String name) throws IOException {
.getAssets().open(testFileName);
Assert.assertNotNull(in);

FileOutputStream out = new FileOutputStream(mediaFile);
IOUtils.copy(in, out);
out.close();
try (final FileOutputStream out = new FileOutputStream(mediaFile)) {
IOUtils.copy(in, out);
}

return mediaFile;
}
Expand Down
Expand Up @@ -276,9 +276,9 @@ private Response getGzippedResponse(int size) throws IOException {
random.nextBytes(buffer);

ByteArrayOutputStream compressed = new ByteArrayOutputStream(buffer.length);
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressed);
gzipOutputStream.write(buffer);
gzipOutputStream.close();
try (final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressed)) {
gzipOutputStream.write(buffer);
}

InputStream inputStream = new ByteArrayInputStream(compressed.toByteArray());
Response response = new Response(Response.Status.OK, MIME_PLAIN, inputStream);
Expand Down
Expand Up @@ -220,11 +220,9 @@ private void startImport() {
BOMInputStream bomInputStream = new BOMInputStream(opmlFileStream);
ByteOrderMark bom = bomInputStream.getBOM();
String charsetName = (bom == null) ? "UTF-8" : bom.getCharsetName();
Reader reader = new InputStreamReader(bomInputStream, charsetName);
OpmlReader opmlReader = new OpmlReader();
ArrayList<OpmlElement> result = opmlReader.readDocument(reader);
reader.close();
return result;
try (final Reader reader = new InputStreamReader(bomInputStream, charsetName)) {
return new OpmlReader().readDocument(reader);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
Expand Down
Expand Up @@ -4,7 +4,6 @@
import android.util.Log;

import de.danoeh.antennapod.BuildConfig;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
Expand Down Expand Up @@ -37,9 +36,7 @@ public void uncaughtException(Thread thread, Throwable ex) {

public static void write(Throwable exception) {
File path = getFile();
PrintWriter out = null;
try {
out = new PrintWriter(path, "UTF-8");
try (final PrintWriter out = new PrintWriter(path, "UTF-8")) {
out.println("## Crash info");
out.println("Time: " + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()));
out.println("AntennaPod version: " + BuildConfig.VERSION_NAME);
Expand All @@ -50,8 +47,6 @@ public static void write(Throwable exception) {
out.println("```");
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
IOUtils.closeQuietly(out);
}
}

Expand Down
Expand Up @@ -26,6 +26,7 @@
import java.io.Writer;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
Expand Down Expand Up @@ -73,10 +74,9 @@ public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,

try {
digester = MessageDigest.getInstance("MD5");
writer = new OutputStreamWriter(new DigestOutputStream(byteStream, digester),
Charset.forName("UTF-8"));
writer = new OutputStreamWriter(new DigestOutputStream(byteStream, digester), StandardCharsets.UTF_8);
} catch (NoSuchAlgorithmException e) {
writer = new OutputStreamWriter(byteStream, Charset.forName("UTF-8"));
writer = new OutputStreamWriter(byteStream, StandardCharsets.UTF_8);
}

try {
Expand Down Expand Up @@ -174,12 +174,10 @@ private void writeNewStateDescription(ParcelFileDescriptor newState, byte[] chec
return;
}

try {
FileOutputStream outState = new FileOutputStream(newState.getFileDescriptor());
try (final FileOutputStream outState = new FileOutputStream(newState.getFileDescriptor())) {
outState.write(checksum.length);
outState.write(checksum);
outState.flush();
outState.close();
} catch (IOException e) {
Log.e(TAG, "Failed to write new state description", e);
}
Expand Down
22 changes: 7 additions & 15 deletions core/src/main/java/de/danoeh/antennapod/core/storage/DBReader.java
Expand Up @@ -357,27 +357,19 @@ public static List<FeedItem> getPlaybackHistory(int offset, int limit) {
PodDBAdapter adapter = PodDBAdapter.getInstance();
adapter.open();

Cursor mediaCursor = null;
Cursor itemCursor = null;
try {
mediaCursor = adapter.getCompletedMediaCursor(offset, limit);
try (final Cursor mediaCursor = adapter.getCompletedMediaCursor(offset, limit)) {
String[] itemIds = new String[mediaCursor.getCount()];
for (int i = 0; i < itemIds.length && mediaCursor.moveToPosition(i); i++) {
int index = mediaCursor.getColumnIndex(PodDBAdapter.KEY_FEEDITEM);
itemIds[i] = Long.toString(mediaCursor.getLong(index));
}
itemCursor = adapter.getFeedItemCursor(itemIds);
List<FeedItem> items = extractItemlistFromCursor(adapter, itemCursor);
loadAdditionalFeedItemListData(items);
Collections.sort(items, new PlaybackCompletionDateComparator());
return items;
} finally {
if (mediaCursor != null) {
mediaCursor.close();
}
if (itemCursor != null) {
itemCursor.close();
try (final Cursor itemCursor = adapter.getFeedItemCursor(itemIds)) {
List<FeedItem> items = extractItemlistFromCursor(adapter, itemCursor);
loadAdditionalFeedItemListData(items);
Collections.sort(items, new PlaybackCompletionDateComparator());
return items;
}
} finally {
adapter.close();
}
}
Expand Down
42 changes: 21 additions & 21 deletions core/src/main/java/de/danoeh/antennapod/core/storage/DBTasks.java
Expand Up @@ -68,16 +68,16 @@ private DBTasks() {
public static void removeFeedWithDownloadUrl(Context context, String downloadUrl) {
PodDBAdapter adapter = PodDBAdapter.getInstance();
adapter.open();
Cursor cursor = adapter.getFeedCursorDownloadUrls();
long feedID = 0;
if (cursor.moveToFirst()) {
do {
if (cursor.getString(1).equals(downloadUrl)) {
feedID = cursor.getLong(0);
}
} while (cursor.moveToNext());
try (final Cursor cursor = adapter.getFeedCursorDownloadUrls()) {
if (cursor.moveToFirst()) {
do {
if (cursor.getString(1).equals(downloadUrl)) {
feedID = cursor.getLong(0);
}
} while (cursor.moveToNext());
}
}
cursor.close();
adapter.close();

if (feedID != 0) {
Expand Down Expand Up @@ -384,11 +384,11 @@ public static FutureTask<List<FeedItem>> searchFeedItems(final long feedID, fina
return new FutureTask<>(new QueryTask<List<FeedItem>>() {
@Override
public void execute(PodDBAdapter adapter) {
Cursor searchResult = adapter.searchItems(feedID, query);
List<FeedItem> items = DBReader.extractItemlistFromCursor(searchResult);
DBReader.loadAdditionalFeedItemListData(items);
setResult(items);
searchResult.close();
try (final Cursor searchResult = adapter.searchItems(feedID, query)) {
List<FeedItem> items = DBReader.extractItemlistFromCursor(searchResult);
DBReader.loadAdditionalFeedItemListData(items);
setResult(items);
}
}
});
}
Expand All @@ -397,15 +397,15 @@ public static FutureTask<List<Feed>> searchFeeds(final String query) {
return new FutureTask<>(new QueryTask<List<Feed>>() {
@Override
public void execute(PodDBAdapter adapter) {
Cursor cursor = adapter.searchFeeds(query);
List<Feed> items = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
items.add(FeedCursorMapper.convert(cursor));
} while (cursor.moveToNext());
try (final Cursor cursor = adapter.searchFeeds(query)) {
List<Feed> items = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
items.add(FeedCursorMapper.convert(cursor));
} while (cursor.moveToNext());
}
setResult(items);
}
setResult(items);
cursor.close();
}
});
}
Expand Down
Expand Up @@ -348,21 +348,14 @@ public void login() throws GpodnetServiceException {
private String executeRequest(@NonNull Request.Builder requestB) throws GpodnetServiceException {
Request request = requestB.build();
String responseString;
Response response;
ResponseBody body = null;
try {

response = httpClient.newCall(request).execute();
try (final Response response = httpClient.newCall(request).execute();
final ResponseBody body = response.body()
) {
checkStatusCode(response);
body = response.body();
responseString = getStringFromResponseBody(body);
} catch (IOException e) {
e.printStackTrace();
throw new GpodnetServiceException(e);
} finally {
if (body != null) {
body.close();
}
}
return responseString;
}
Expand Down
Expand Up @@ -26,11 +26,10 @@ public FeedHandlerResult parseFeed(Feed feed) throws SAXException, IOException,
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
File file = new File(feed.getFile_url());
Reader inputStreamReader = new XmlStreamReader(file);
InputSource inputSource = new InputSource(inputStreamReader);

saxParser.parse(inputSource, handler);
inputStreamReader.close();
try (final Reader inputStreamReader = new XmlStreamReader(file)) {
final InputSource inputSource = new InputSource(inputStreamReader);
saxParser.parse(inputSource, handler);
}
return new FeedHandlerResult(handler.state.feed, handler.state.alternateUrls, handler.state.redirectUrl);
}
}
Expand Up @@ -9,7 +9,6 @@
import android.util.Log;
import de.danoeh.antennapod.storage.database.PodDBAdapter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
Expand All @@ -23,37 +22,22 @@ public class DatabaseExporter {
private static final String TEMP_DB_NAME = PodDBAdapter.DATABASE_NAME + "_tmp";

public static void exportToDocument(Uri uri, Context context) throws IOException {
ParcelFileDescriptor pfd = null;
FileOutputStream fileOutputStream = null;
try {
pfd = context.getContentResolver().openFileDescriptor(uri, "wt");
fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
try (final ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "wt");
final FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor())
) {
exportToStream(fileOutputStream, context);
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
throw e;
} finally {
IOUtils.closeQuietly(fileOutputStream);

if (pfd != null) {
try {
pfd.close();
} catch (IOException e) {
Log.d(TAG, "Unable to close ParcelFileDescriptor");
}
}
}
}

public static void exportToStream(FileOutputStream outFileStream, Context context) throws IOException {
FileChannel src = null;
FileChannel dst = null;
try {
File currentDB = context.getDatabasePath(PodDBAdapter.DATABASE_NAME);

if (currentDB.exists()) {
src = new FileInputStream(currentDB).getChannel();
dst = outFileStream.getChannel();
final File currentDb = context.getDatabasePath(PodDBAdapter.DATABASE_NAME);
try (final FileChannel src = new FileInputStream(currentDb).getChannel();
final FileChannel dst = outFileStream.getChannel()
) {
if (currentDb.exists()) {
long srcSize = src.size();
dst.transferFrom(src, 0, srcSize);

Expand All @@ -70,17 +54,12 @@ public static void exportToStream(FileOutputStream outFileStream, Context contex
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
throw e;
} finally {
IOUtils.closeQuietly(src);
IOUtils.closeQuietly(dst);
}
}

public static void importBackup(Uri inputUri, Context context) throws IOException {
InputStream inputStream = null;
try {
try (final InputStream inputStream = context.getContentResolver().openInputStream(inputUri)) {
File tempDB = context.getDatabasePath(TEMP_DB_NAME);
inputStream = context.getContentResolver().openInputStream(inputUri);
FileUtils.copyInputStreamToFile(inputStream, tempDB);

SQLiteDatabase db = SQLiteDatabase.openDatabase(tempDB.getAbsolutePath(),
Expand All @@ -99,8 +78,6 @@ public static void importBackup(Uri inputUri, Context context) throws IOExceptio
} catch (IOException | SQLiteException e) {
Log.e(TAG, Log.getStackTraceString(e));
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
Expand Up @@ -57,12 +57,10 @@ public EmbeddedImageFetcher(EmbeddedChapterImage image) {

@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super ByteBuffer> callback) {

BufferedInputStream stream = null;
try {
final File localFile = new File(image.getMedia().getLocalMediaUrl());
try (final BufferedInputStream stream = new BufferedInputStream(new FileInputStream(localFile))
) {
if (image.getMedia().localFileAvailable()) {
File localFile = new File(image.getMedia().getLocalMediaUrl());
stream = new BufferedInputStream(new FileInputStream(localFile));
IOUtils.skip(stream, image.getPosition());
byte[] imageContent = new byte[image.getLength()];
IOUtils.read(stream, imageContent, 0, image.getLength());
Expand All @@ -81,8 +79,6 @@ public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super B
}
} catch (IOException e) {
callback.onLoadFailed(e);
} finally {
IOUtils.closeQuietly(stream);
}
}

Expand Down