This upgrades Apache HttpClient

- Update to latest version of httpclient and httpcomponents
- Fixes resulting deprecations
- Switch to using try with resources

Signed-off-by: Ben Kelsey <bfkelsey@gmail.com>
master
Ben Kelsey 8 years ago
parent 33c16db802
commit c9536ff310
  1. 4
      libresonic-main/pom.xml
  2. 110
      libresonic-main/src/main/java/org/libresonic/player/ajax/CoverArtService.java
  3. 20
      libresonic-main/src/main/java/org/libresonic/player/ajax/LyricsService.java
  4. 34
      libresonic-main/src/main/java/org/libresonic/player/controller/ProxyController.java
  5. 24
      libresonic-main/src/main/java/org/libresonic/player/service/AudioScrobblerService.java
  6. 58
      libresonic-main/src/main/java/org/libresonic/player/service/NetworkService.java
  7. 157
      libresonic-main/src/main/java/org/libresonic/player/service/PodcastService.java
  8. 6
      libresonic-main/src/main/java/org/libresonic/player/service/SettingsService.java
  9. 40
      libresonic-main/src/main/java/org/libresonic/player/service/VersionService.java
  10. 20
      libresonic-main/src/main/java/org/libresonic/player/service/sonos/SonosServiceRegistration.java

@ -136,13 +136,13 @@
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId> <artifactId>httpcore</artifactId>
<version>4.2.4</version> <version>4.4.5</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.2.4</version> <version>4.5.2</version>
</dependency> </dependency>
<dependency> <dependency>

@ -25,11 +25,11 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.impl.client.HttpClients;
import org.libresonic.player.Logger; import org.libresonic.player.Logger;
import org.libresonic.player.domain.MediaFile; import org.libresonic.player.domain.MediaFile;
@ -72,69 +72,69 @@ public class CoverArtService {
private void saveCoverArt(String path, String url) throws Exception { private void saveCoverArt(String path, String url) throws Exception {
InputStream input = null; InputStream input = null;
OutputStream output = null; OutputStream output = null;
HttpClient client = new DefaultHttpClient();
try { try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpConnectionParams.setConnectionTimeout(client.getParams(), 20 * 1000); // 20 seconds RequestConfig requestConfig = RequestConfig.custom()
HttpConnectionParams.setSoTimeout(client.getParams(), 20 * 1000); // 20 seconds .setConnectTimeout(20 * 1000) // 20 seconds
.setSocketTimeout(20 * 1000) // 20 seconds
.build();
HttpGet method = new HttpGet(url); HttpGet method = new HttpGet(url);
method.setConfig(requestConfig);
try (CloseableHttpResponse response = client.execute(method)) {
input = response.getEntity().getContent();
// Attempt to resolve proper suffix.
String suffix = "jpg";
if (url.toLowerCase().endsWith(".gif")) {
suffix = "gif";
} else if (url.toLowerCase().endsWith(".png")) {
suffix = "png";
}
HttpResponse response = client.execute(method); // Check permissions.
input = response.getEntity().getContent(); File newCoverFile = new File(path, "cover." + suffix);
if (!securityService.isWriteAllowed(newCoverFile)) {
// Attempt to resolve proper suffix. throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath()));
String suffix = "jpg"; }
if (url.toLowerCase().endsWith(".gif")) {
suffix = "gif";
} else if (url.toLowerCase().endsWith(".png")) {
suffix = "png";
}
// Check permissions.
File newCoverFile = new File(path, "cover." + suffix);
if (!securityService.isWriteAllowed(newCoverFile)) {
throw new Exception("Permission denied: " + StringUtil.toHtml(newCoverFile.getPath()));
}
// If file exists, create a backup.
backup(newCoverFile, new File(path, "cover." + suffix + ".backup"));
// Write file.
output = new FileOutputStream(newCoverFile);
IOUtils.copy(input, output);
MediaFile dir = mediaFileService.getMediaFile(path);
// Refresh database.
mediaFileService.refreshMediaFile(dir);
dir = mediaFileService.getMediaFile(dir.getId());
// Rename existing cover files if new cover file is not the preferred. // If file exists, create a backup.
try { backup(newCoverFile, new File(path, "cover." + suffix + ".backup"));
while (true) {
File coverFile = mediaFileService.getCoverArt(dir); // Write file.
if (coverFile != null && !isMediaFile(coverFile) && !newCoverFile.equals(coverFile)) { output = new FileOutputStream(newCoverFile);
if (!coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old"))) { IOUtils.copy(input, output);
LOG.warn("Unable to rename old image file " + coverFile);
MediaFile dir = mediaFileService.getMediaFile(path);
// Refresh database.
mediaFileService.refreshMediaFile(dir);
dir = mediaFileService.getMediaFile(dir.getId());
// Rename existing cover files if new cover file is not the preferred.
try {
while (true) {
File coverFile = mediaFileService.getCoverArt(dir);
if (coverFile != null && !isMediaFile(coverFile) && !newCoverFile.equals(coverFile)) {
if (!coverFile.renameTo(new File(coverFile.getCanonicalPath() + ".old"))) {
LOG.warn("Unable to rename old image file " + coverFile);
break;
}
LOG.info("Renamed old image file " + coverFile);
// Must refresh again.
mediaFileService.refreshMediaFile(dir);
dir = mediaFileService.getMediaFile(dir.getId());
} else {
break; break;
} }
LOG.info("Renamed old image file " + coverFile);
// Must refresh again.
mediaFileService.refreshMediaFile(dir);
dir = mediaFileService.getMediaFile(dir.getId());
} else {
break;
} }
} catch (Exception x) {
LOG.warn("Failed to rename existing cover file.", x);
} }
} catch (Exception x) {
LOG.warn("Failed to rename existing cover file.", x);
} }
} finally { } finally {
IOUtils.closeQuietly(input); IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output); IOUtils.closeQuietly(output);
client.getConnectionManager().shutdown();
} }
} }

@ -24,12 +24,12 @@ import java.io.StringReader;
import java.net.SocketException; import java.net.SocketException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler; import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.impl.client.HttpClients;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
@ -92,17 +92,15 @@ public class LyricsService {
} }
private String executeGetRequest(String url) throws IOException { private String executeGetRequest(String url) throws IOException {
HttpClient client = new DefaultHttpClient(); RequestConfig requestConfig = RequestConfig.custom()
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000); .setConnectTimeout(15000)
HttpConnectionParams.setSoTimeout(client.getParams(), 15000); .setSocketTimeout(15000)
.build();
HttpGet method = new HttpGet(url); HttpGet method = new HttpGet(url);
try { method.setConfig(requestConfig);
try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler(); ResponseHandler<String> responseHandler = new BasicResponseHandler();
return client.execute(method, responseHandler); return client.execute(method, responseHandler);
} finally {
client.getConnectionManager().shutdown();
} }
} }
} }

@ -25,12 +25,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.impl.client.HttpClients;
import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.mvc.Controller;
@ -45,24 +45,26 @@ public class ProxyController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String url = ServletRequestUtils.getRequiredStringParameter(request, "url"); String url = ServletRequestUtils.getRequiredStringParameter(request, "url");
HttpClient client = new DefaultHttpClient(); RequestConfig requestConfig = RequestConfig.custom()
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000); .setConnectTimeout(15000)
HttpConnectionParams.setSoTimeout(client.getParams(), 15000); .setSocketTimeout(15000)
.build();
HttpGet method = new HttpGet(url); HttpGet method = new HttpGet(url);
method.setConfig(requestConfig);
InputStream in = null; InputStream in = null;
try { try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpResponse resp = client.execute(method); try (CloseableHttpResponse resp = client.execute(method)) {
int statusCode = resp.getStatusLine().getStatusCode(); int statusCode = resp.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_OK) {
response.sendError(statusCode); response.sendError(statusCode);
} else { } else {
in = resp.getEntity().getContent(); in = resp.getEntity().getContent();
IOUtils.copy(in, response.getOutputStream()); IOUtils.copy(in, response.getOutputStream());
}
} }
} finally { } finally {
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
client.getConnectionManager().shutdown();
} }
return null; return null;
} }

@ -29,16 +29,16 @@ import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler; import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.libresonic.player.Logger; import org.libresonic.player.Logger;
import org.libresonic.player.domain.MediaFile; import org.libresonic.player.domain.MediaFile;
@ -62,7 +62,10 @@ public class AudioScrobblerService {
private final LinkedBlockingQueue<RegistrationData> queue = new LinkedBlockingQueue<RegistrationData>(); private final LinkedBlockingQueue<RegistrationData> queue = new LinkedBlockingQueue<RegistrationData>();
private SettingsService settingsService; private SettingsService settingsService;
private final RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(15000)
.setSocketTimeout(15000)
.build();
/** /**
* Registers the given media file at www.last.fm. This method returns immediately, the actual registration is done * Registers the given media file at www.last.fm. This method returns immediately, the actual registration is done
@ -234,7 +237,9 @@ public class AudioScrobblerService {
} }
private String[] executeGetRequest(String url) throws IOException { private String[] executeGetRequest(String url) throws IOException {
return executeRequest(new HttpGet(url)); HttpGet method = new HttpGet(url);
method.setConfig(requestConfig);
return executeRequest(method);
} }
private String[] executePostRequest(String url, Map<String, String> parameters) throws IOException { private String[] executePostRequest(String url, Map<String, String> parameters) throws IOException {
@ -245,22 +250,17 @@ public class AudioScrobblerService {
HttpPost request = new HttpPost(url); HttpPost request = new HttpPost(url);
request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8)); request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
request.setConfig(requestConfig);
return executeRequest(request); return executeRequest(request);
} }
private String[] executeRequest(HttpUriRequest request) throws IOException { private String[] executeRequest(HttpUriRequest request) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
try { try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler(); ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(request, responseHandler); String response = client.execute(request, responseHandler);
return response.split("\\n"); return response.split("\\n");
} finally {
client.getConnectionManager().shutdown();
} }
} }

@ -28,19 +28,18 @@ import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.StatusLine; import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.libresonic.player.Logger; import org.libresonic.player.Logger;
@ -250,34 +249,32 @@ public class NetworkService {
params.add(new BasicNameValuePair("licenseHolder", settingsService.getLicenseEmail())); params.add(new BasicNameValuePair("licenseHolder", settingsService.getLicenseEmail()));
} }
HttpClient client = new DefaultHttpClient();
try {
try (CloseableHttpClient client = HttpClients.createDefault()) {
urlRedirectionStatus.setText(enable ? "Registering web address..." : "Unregistering web address..."); urlRedirectionStatus.setText(enable ? "Registering web address..." : "Unregistering web address...");
request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8)); request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
HttpResponse response = client.execute(request); try (CloseableHttpResponse response = client.execute(request)) {
StatusLine status = response.getStatusLine(); StatusLine status = response.getStatusLine();
switch (status.getStatusCode()) { switch (status.getStatusCode()) {
case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_BAD_REQUEST:
urlRedirectionStatus.setText(EntityUtils.toString(response.getEntity())); urlRedirectionStatus.setText(EntityUtils.toString(response.getEntity()));
testUrlRedirection = false; testUrlRedirection = false;
break; break;
case HttpStatus.SC_OK: case HttpStatus.SC_OK:
urlRedirectionStatus.setText(enable ? "Successfully registered web address." : "Web address disabled."); urlRedirectionStatus.setText(enable ? "Successfully registered web address." : "Web address disabled.");
break; break;
default: default:
testUrlRedirection = false; testUrlRedirection = false;
throw new IOException(status.getStatusCode() + " " + status.getReasonPhrase()); throw new IOException(status.getStatusCode() + " " + status.getReasonPhrase());
}
} }
} catch (Throwable x) { } catch (Throwable x) {
LOG.warn(enable ? "Failed to register web address." : "Failed to unregister web address.", x); LOG.warn(enable ? "Failed to register web address." : "Failed to unregister web address.", x);
urlRedirectionStatus.setText(enable ? ("Failed to register web address. " + x.getMessage() + urlRedirectionStatus.setText(enable ? ("Failed to register web address. " + x.getMessage() +
" (" + x.getClass().getSimpleName() + ")") : "Web address disabled."); " (" + x.getClass().getSimpleName() + ")") : "Web address disabled.");
} finally {
client.getConnectionManager().shutdown();
} }
// Test redirection, but only once. // Test redirection, but only once.
@ -305,20 +302,19 @@ public class NetworkService {
} }
HttpGet request = new HttpGet(url); HttpGet request = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpConnectionParams.setSoTimeout(client.getParams(), 30000);
try { RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(15000)
.setSocketTimeout(15000)
.build();
request.setConfig(requestConfig);
try (CloseableHttpClient client = HttpClients.createDefault()) {
urlRedirectionStatus.setText("Testing web address " + urlToTest + ". Please wait..."); urlRedirectionStatus.setText("Testing web address " + urlToTest + ". Please wait...");
String response = client.execute(request, new BasicResponseHandler()); String response = client.execute(request, new BasicResponseHandler());
urlRedirectionStatus.setText(response); urlRedirectionStatus.setText(response);
} catch (Throwable x) { } catch (Throwable x) {
LOG.warn("Failed to test web address.", x); LOG.warn("Failed to test web address.", x);
urlRedirectionStatus.setText("Failed to test web address. " + x.getMessage() + " (" + x.getClass().getSimpleName() + ")"); urlRedirectionStatus.setText("Failed to test web address. " + x.getMessage() + " (" + x.getClass().getSimpleName() + ")");
} finally {
client.getConnectionManager().shutdown();
} }
} }
} }

@ -39,25 +39,25 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.impl.client.HttpClients;
import org.jdom.Document; import org.jdom.Document;
import org.jdom.Element; import org.jdom.Element;
import org.jdom.Namespace; import org.jdom.Namespace;
import org.jdom.input.SAXBuilder; import org.jdom.input.SAXBuilder;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.libresonic.player.Logger; import org.libresonic.player.Logger;
import org.libresonic.player.dao.PodcastDao; import org.libresonic.player.dao.PodcastDao;
import org.libresonic.player.domain.MediaFile; import org.libresonic.player.domain.MediaFile;
@ -302,33 +302,34 @@ public class PodcastService {
@SuppressWarnings({"unchecked"}) @SuppressWarnings({"unchecked"})
private void doRefreshChannel(PodcastChannel channel, boolean downloadEpisodes) { private void doRefreshChannel(PodcastChannel channel, boolean downloadEpisodes) {
InputStream in = null; InputStream in = null;
HttpClient client = new DefaultHttpClient();
try { try (CloseableHttpClient client = HttpClients.createDefault()) {
channel.setStatus(PodcastStatus.DOWNLOADING); channel.setStatus(PodcastStatus.DOWNLOADING);
channel.setErrorMessage(null); channel.setErrorMessage(null);
podcastDao.updateChannel(channel); podcastDao.updateChannel(channel);
RequestConfig requestConfig = RequestConfig.custom()
HttpConnectionParams.setConnectionTimeout(client.getParams(), 2 * 60 * 1000); // 2 minutes .setConnectTimeout(2 * 60 * 1000) // 2 minutes
HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 60 * 1000); // 10 minutes .setSocketTimeout(10 * 60 * 1000) // 10 minutes
.build();
HttpGet method = new HttpGet(channel.getUrl()); HttpGet method = new HttpGet(channel.getUrl());
method.setConfig(requestConfig);
HttpResponse response = client.execute(method); try (CloseableHttpResponse response = client.execute(method)) {
in = response.getEntity().getContent(); in = response.getEntity().getContent();
Document document = new SAXBuilder().build(in);
Element channelElement = document.getRootElement().getChild("channel");
channel.setTitle(StringUtil.removeMarkup(channelElement.getChildTextTrim("title"))); Document document = new SAXBuilder().build(in);
channel.setDescription(StringUtil.removeMarkup(channelElement.getChildTextTrim("description"))); Element channelElement = document.getRootElement().getChild("channel");
channel.setImageUrl(getChannelImageUrl(channelElement));
channel.setStatus(PodcastStatus.COMPLETED);
channel.setErrorMessage(null);
podcastDao.updateChannel(channel);
downloadImage(channel); channel.setTitle(StringUtil.removeMarkup(channelElement.getChildTextTrim("title")));
refreshEpisodes(channel, channelElement.getChildren("item")); channel.setDescription(StringUtil.removeMarkup(channelElement.getChildTextTrim("description")));
channel.setImageUrl(getChannelImageUrl(channelElement));
channel.setStatus(PodcastStatus.COMPLETED);
channel.setErrorMessage(null);
podcastDao.updateChannel(channel);
downloadImage(channel);
refreshEpisodes(channel, channelElement.getChildren("item"));
}
} catch (Exception x) { } catch (Exception x) {
LOG.warn("Failed to get/parse RSS file for Podcast channel " + channel.getUrl(), x); LOG.warn("Failed to get/parse RSS file for Podcast channel " + channel.getUrl(), x);
channel.setStatus(PodcastStatus.ERROR); channel.setStatus(PodcastStatus.ERROR);
@ -336,7 +337,6 @@ public class PodcastService {
podcastDao.updateChannel(channel); podcastDao.updateChannel(channel);
} finally { } finally {
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
client.getConnectionManager().shutdown();
} }
if (downloadEpisodes) { if (downloadEpisodes) {
@ -349,10 +349,9 @@ public class PodcastService {
} }
private void downloadImage(PodcastChannel channel) { private void downloadImage(PodcastChannel channel) {
HttpClient client = new DefaultHttpClient();
InputStream in = null; InputStream in = null;
OutputStream out = null; OutputStream out = null;
try { try(CloseableHttpClient client = HttpClients.createDefault()) {
String imageUrl = channel.getImageUrl(); String imageUrl = channel.getImageUrl();
if (imageUrl == null) { if (imageUrl == null) {
return; return;
@ -367,17 +366,17 @@ public class PodcastService {
} }
HttpGet method = new HttpGet(imageUrl); HttpGet method = new HttpGet(imageUrl);
HttpResponse response = client.execute(method); try (CloseableHttpResponse response = client.execute(method)) {
in = response.getEntity().getContent(); in = response.getEntity().getContent();
out = new FileOutputStream(new File(dir, "cover." + getCoverArtSuffix(response))); out = new FileOutputStream(new File(dir, "cover." + getCoverArtSuffix(response)));
IOUtils.copy(in, out); IOUtils.copy(in, out);
mediaFileService.refreshMediaFile(channelMediaFile); mediaFileService.refreshMediaFile(channelMediaFile);
}
} catch (Exception x) { } catch (Exception x) {
LOG.warn("Failed to download cover art for podcast channel '" + channel.getTitle() + "': " + x, x); LOG.warn("Failed to download cover art for podcast channel '" + channel.getTitle() + "': " + x, x);
} finally { } finally {
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out); IOUtils.closeQuietly(out);
client.getConnectionManager().shutdown();
} }
} }
@ -534,68 +533,69 @@ public class PodcastService {
LOG.info("Starting to download Podcast from " + episode.getUrl()); LOG.info("Starting to download Podcast from " + episode.getUrl());
HttpClient client = new DefaultHttpClient(); try (CloseableHttpClient client = HttpClients.createDefault()) {
try {
if (!settingsService.getLicenseInfo().isLicenseOrTrialValid()) { if (!settingsService.getLicenseInfo().isLicenseOrTrialValid()) {
throw new Exception("Sorry, the trial period is expired."); throw new Exception("Sorry, the trial period is expired.");
} }
PodcastChannel channel = getChannel(episode.getChannelId()); PodcastChannel channel = getChannel(episode.getChannelId());
RequestConfig requestConfig = RequestConfig.custom()
HttpConnectionParams.setConnectionTimeout(client.getParams(), 2 * 60 * 1000); // 2 minutes .setConnectTimeout(2 * 60 * 1000) // 2 minutes
HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 60 * 1000); // 10 minutes .setSocketTimeout(10 * 60 * 1000) // 10 minutes
.build();
HttpGet method = new HttpGet(episode.getUrl()); HttpGet method = new HttpGet(episode.getUrl());
method.setConfig(requestConfig);
HttpResponse response = client.execute(method); try (CloseableHttpResponse response = client.execute(method)) {
in = response.getEntity().getContent(); in = response.getEntity().getContent();
File file = getFile(channel, episode); File file = getFile(channel, episode);
out = new FileOutputStream(file); out = new FileOutputStream(file);
episode.setStatus(PodcastStatus.DOWNLOADING); episode.setStatus(PodcastStatus.DOWNLOADING);
episode.setBytesDownloaded(0L); episode.setBytesDownloaded(0L);
episode.setErrorMessage(null); episode.setErrorMessage(null);
episode.setPath(file.getPath()); episode.setPath(file.getPath());
podcastDao.updateEpisode(episode); podcastDao.updateEpisode(episode);
byte[] buffer = new byte[4096]; byte[] buffer = new byte[4096];
long bytesDownloaded = 0; long bytesDownloaded = 0;
int n; int n;
long nextLogCount = 30000L; long nextLogCount = 30000L;
while ((n = in.read(buffer)) != -1) { while ((n = in.read(buffer)) != -1) {
out.write(buffer, 0, n); out.write(buffer, 0, n);
bytesDownloaded += n; bytesDownloaded += n;
if (bytesDownloaded > nextLogCount) { if (bytesDownloaded > nextLogCount) {
episode.setBytesDownloaded(bytesDownloaded); episode.setBytesDownloaded(bytesDownloaded);
nextLogCount += 30000L; nextLogCount += 30000L;
// Abort download if episode was deleted by user. // Abort download if episode was deleted by user.
if (isEpisodeDeleted(episode)) { if (isEpisodeDeleted(episode)) {
break; break;
}
podcastDao.updateEpisode(episode);
} }
podcastDao.updateEpisode(episode);
} }
}
if (isEpisodeDeleted(episode)) { if (isEpisodeDeleted(episode)) {
LOG.info("Podcast " + episode.getUrl() + " was deleted. Aborting download."); LOG.info("Podcast " + episode.getUrl() + " was deleted. Aborting download.");
IOUtils.closeQuietly(out); IOUtils.closeQuietly(out);
file.delete(); file.delete();
} else { } else {
addMediaFileIdToEpisodes(Arrays.asList(episode)); addMediaFileIdToEpisodes(Arrays.asList(episode));
episode.setBytesDownloaded(bytesDownloaded); episode.setBytesDownloaded(bytesDownloaded);
podcastDao.updateEpisode(episode); podcastDao.updateEpisode(episode);
LOG.info("Downloaded " + bytesDownloaded + " bytes from Podcast " + episode.getUrl()); LOG.info("Downloaded " + bytesDownloaded + " bytes from Podcast " + episode.getUrl());
IOUtils.closeQuietly(out); IOUtils.closeQuietly(out);
updateTags(file, episode); updateTags(file, episode);
episode.setStatus(PodcastStatus.COMPLETED); episode.setStatus(PodcastStatus.COMPLETED);
podcastDao.updateEpisode(episode); podcastDao.updateEpisode(episode);
deleteObsoleteEpisodes(channel); deleteObsoleteEpisodes(channel);
}
} }
} catch (Exception x) { } catch (Exception x) {
LOG.warn("Failed to download Podcast from " + episode.getUrl(), x); LOG.warn("Failed to download Podcast from " + episode.getUrl(), x);
episode.setStatus(PodcastStatus.ERROR); episode.setStatus(PodcastStatus.ERROR);
@ -604,7 +604,6 @@ public class PodcastService {
} finally { } finally {
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out); IOUtils.closeQuietly(out);
client.getConnectionManager().shutdown();
} }
} }

@ -43,12 +43,6 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.libresonic.player.Logger; import org.libresonic.player.Logger;
import org.libresonic.player.dao.AvatarDao; import org.libresonic.player.dao.AvatarDao;

@ -19,16 +19,6 @@
*/ */
package org.libresonic.player.service; package org.libresonic.player.service;
import org.libresonic.player.Logger;
import org.libresonic.player.domain.Version;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -40,6 +30,17 @@ import java.util.Date;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.libresonic.player.Logger;
import org.libresonic.player.domain.Version;
/** /**
* Provides version-related services, including functionality for determining whether a newer * Provides version-related services, including functionality for determining whether a newer
* version of Libresonic is available. * version of Libresonic is available.
@ -231,25 +232,22 @@ public class VersionService {
*/ */
private void readLatestVersion() throws IOException { private void readLatestVersion() throws IOException {
HttpClient client = new DefaultHttpClient(); RequestConfig requestConfig = RequestConfig.custom()
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); .setConnectTimeout(10000)
HttpConnectionParams.setSoTimeout(client.getParams(), 10000); .setSocketTimeout(10000)
.build();
HttpGet method = new HttpGet(VERSION_URL + "?v=" + getLocalVersion()); HttpGet method = new HttpGet(VERSION_URL + "?v=" + getLocalVersion());
method.setConfig(requestConfig);
String content; String content;
try { try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler(); ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(method, responseHandler); content = client.execute(method, responseHandler);
} finally {
client.getConnectionManager().shutdown();
} }
BufferedReader reader = new BufferedReader(new StringReader(content));
Pattern finalPattern = Pattern.compile("LIBRESONIC_FULL_VERSION_BEGIN(.*)LIBRESONIC_FULL_VERSION_END"); Pattern finalPattern = Pattern.compile("LIBRESONIC_FULL_VERSION_BEGIN(.*)LIBRESONIC_FULL_VERSION_END");
Pattern betaPattern = Pattern.compile("LIBRESONIC_BETA_VERSION_BEGIN(.*)LIBRESONIC_BETA_VERSION_END"); Pattern betaPattern = Pattern.compile("LIBRESONIC_BETA_VERSION_BEGIN(.*)LIBRESONIC_BETA_VERSION_END");
try { try (BufferedReader reader = new BufferedReader(new StringReader(content))) {
String line = reader.readLine(); String line = reader.readLine();
while (line != null) { while (line != null) {
Matcher finalMatcher = finalPattern.matcher(line); Matcher finalMatcher = finalPattern.matcher(line);
@ -265,8 +263,6 @@ public class VersionService {
line = reader.readLine(); line = reader.readLine();
} }
} finally {
reader.close();
} }
} }
} }

@ -24,15 +24,15 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler; import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.libresonic.player.Logger; import org.libresonic.player.Logger;
import org.libresonic.player.util.Pair; import org.libresonic.player.util.Pair;
@ -82,24 +82,24 @@ public class SonosServiceRegistration {
for (Pair<String, String> parameter : parameters) { for (Pair<String, String> parameter : parameters) {
params.add(new BasicNameValuePair(parameter.getFirst(), parameter.getSecond())); params.add(new BasicNameValuePair(parameter.getFirst(), parameter.getSecond()));
} }
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(20 * 1000) // 20 seconds
.setSocketTimeout(20 * 1000) // 20 seconds
.build();
HttpPost request = new HttpPost(url); HttpPost request = new HttpPost(url);
request.setConfig(requestConfig);
request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8)); request.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
return executeRequest(request); return executeRequest(request);
} }
private String executeRequest(HttpUriRequest request) throws IOException { private String executeRequest(HttpUriRequest request) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
try {
try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler(); ResponseHandler<String> responseHandler = new BasicResponseHandler();
return client.execute(request, responseHandler); return client.execute(request, responseHandler);
} finally {
client.getConnectionManager().shutdown();
} }
} }
} }

Loading…
Cancel
Save