Skip to content

Commit 8ca093b

Browse files
author
Mattia Bertorello
committed
Add slf4j, optimize some code and fix reported lint problem
1 parent 6592c42 commit 8ca093b

File tree

4 files changed

+51
-61
lines changed

4 files changed

+51
-61
lines changed

Diff for: arduino-core/src/cc/arduino/utils/network/FileDownloader.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131

3232
import org.apache.commons.compress.utils.IOUtils;
3333

34+
import org.slf4j.Logger;
35+
import org.slf4j.LoggerFactory;
3436
import processing.app.BaseNoGui;
3537
import processing.app.helpers.FileUtils;
3638

@@ -44,11 +46,9 @@
4446
import java.util.Observable;
4547
import java.util.Optional;
4648
import java.util.logging.Level;
47-
import java.util.logging.Logger;
4849

4950
public class FileDownloader extends Observable {
50-
private static Logger log = Logger
51-
.getLogger(FileDownloader.class.getName());
51+
private static Logger log = LoggerFactory.getLogger(FileDownloader.class);
5252

5353
public enum Status {
5454
CONNECTING, //
@@ -163,7 +163,7 @@ private void downloadFile(boolean noResume) throws InterruptedException {
163163
return;
164164
}
165165
} catch (Exception e) {
166-
log.log(Level.WARNING,
166+
log.warn(
167167
"Cannot get the file from the cache, will be downloaded a new one ", e.getCause());
168168

169169
}
@@ -219,6 +219,7 @@ private void downloadFile(boolean noResume) throws InterruptedException {
219219
throw new Exception("Incomplete download");
220220
}
221221
// Set the cache whe it finish to download the file
222+
IOUtils.closeQuietly(randomAccessOutputFile);
222223
fileDownloaderCache.fillCache(outputFile);
223224
setStatus(Status.COMPLETE);
224225
} catch (InterruptedException e) {

Diff for: arduino-core/src/cc/arduino/utils/network/FileDownloaderCache.java

+11-15
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package cc.arduino.utils.network;
22

33
import com.sun.istack.internal.NotNull;
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
46
import processing.app.PreferencesData;
57
import processing.app.helpers.FileUtils;
68

@@ -15,24 +17,20 @@
1517
import java.nio.file.Path;
1618
import java.nio.file.Paths;
1719
import java.util.Optional;
18-
import java.util.logging.Logger;
1920

2021
public class FileDownloaderCache {
21-
private static Logger log = Logger
22-
.getLogger(FileDownloaderCache.class.getName());
23-
private final String cacheFolder;
22+
private static Logger log = LoggerFactory.getLogger(FileDownloaderCache.class);
2423
private final URL remoteURL;
2524
private final Path cacheFilePath;
2625
// Will be initialized by call the checkIfTheFileIsChanged function
2726
private String eTag;
2827

2928
// BaseNoGui.getSettingsFolder()
3029
public FileDownloaderCache(@NotNull String cacheFolder, @NotNull URL remoteURL) {
31-
this.cacheFolder = cacheFolder;
3230
this.remoteURL = remoteURL;
3331
String[] splitPath = remoteURL.getPath().split("/");
3432
if (splitPath.length > 0) {
35-
this.cacheFilePath = Paths.get(cacheFolder, splitPath[splitPath.length - 1]);
33+
this.cacheFilePath = Paths.get(cacheFolder, splitPath);
3634
} else {
3735
this.cacheFilePath = null;
3836
}
@@ -47,13 +45,14 @@ public boolean checkIfTheFileIsChanged()
4745
try {
4846
connection.setRequestMethod("HEAD");
4947
} catch (ProtocolException e) {
50-
throw new RuntimeException(e);
48+
log.error("Invalid protocol", e);
5149
}
5250
});
5351
final int responseCode = headRequest.getResponseCode();
52+
headRequest.disconnect();
5453
// Something bad is happening return a conservative true to try to download the file
5554
if (responseCode < 200 || responseCode >= 300) {
56-
log.warning("The head request return a bad response code " + responseCode);
55+
log.warn("The head request return a bad response code " + responseCode);
5756
return true;
5857
}
5958

@@ -71,10 +70,8 @@ public boolean checkIfTheFileIsChanged()
7170
}
7271

7372
public Optional<File> getFileFromCache() {
74-
if (Optional.ofNullable(cacheFilePath).isPresent()) {
75-
if (Files.exists(cacheFilePath)) {
76-
return Optional.of(new File(cacheFilePath.toUri()));
77-
}
73+
if (Optional.ofNullable(cacheFilePath).isPresent() && Files.exists(cacheFilePath)) {
74+
return Optional.of(new File(cacheFilePath.toUri()));
7875
}
7976
return Optional.empty();
8077

@@ -86,9 +83,8 @@ public void fillCache(File fileToCache) throws Exception {
8683

8784
PreferencesData.set(getPreferencesDataKey(), eTag);
8885
// If the cache directory does not exist create it
89-
final Path cachePath = Paths.get(cacheFolder);
90-
if (!Files.exists(cachePath)) {
91-
Files.createDirectory(cachePath);
86+
if (!Files.exists(cacheFilePath.getParent())) {
87+
Files.createDirectories(cacheFilePath.getParent());
9288
}
9389
FileUtils.copyFile(fileToCache, cacheFilePath.toFile());
9490
}

Diff for: arduino-core/src/cc/arduino/utils/network/HttpConnectionManager.java

+22-23
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
package cc.arduino.utils.network;
22

33
import cc.arduino.net.CustomProxySelector;
4+
import com.sun.istack.internal.NotNull;
45
import org.apache.commons.codec.binary.Base64;
6+
import org.apache.commons.httpclient.CircularRedirectException;
7+
import org.apache.commons.lang3.StringUtils;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
510
import processing.app.BaseNoGui;
611
import processing.app.PreferencesData;
712

@@ -12,12 +17,9 @@
1217
import java.net.URISyntaxException;
1318
import java.net.URL;
1419
import java.util.function.Consumer;
15-
import java.util.logging.Level;
16-
import java.util.logging.Logger;
1720

1821
public class HttpConnectionManager {
19-
private static Logger log = Logger
20-
.getLogger(HttpConnectionManager.class.getName());
22+
private static Logger log = LoggerFactory.getLogger(HttpConnectionManager.class);
2123
private final URL requestURL;
2224
private final String userAgent;
2325
private int connectTimeout;
@@ -41,38 +43,35 @@ public HttpConnectionManager(URL requestURL) {
4143
Integer.parseInt(
4244
PreferencesData.get("http.connection_timeout", "5000"));
4345
} catch (NumberFormatException e) {
44-
log.log(Level.WARNING,
46+
log.warn(
4547
"Cannot parse the http.connection_timeout configuration switch to default 5000 milliseconds", e.getCause());
4648
this.connectTimeout = 5000;
4749
}
4850

4951
}
5052

51-
public HttpURLConnection makeConnection(Consumer<HttpURLConnection> beforeConnection)
52-
throws URISyntaxException, NoSuchMethodException, IOException,
53-
ScriptException {
53+
public HttpURLConnection makeConnection(@NotNull Consumer<HttpURLConnection> beforeConnection)
54+
throws IOException, NoSuchMethodException, ScriptException, URISyntaxException {
5455
return makeConnection(this.requestURL, 0, beforeConnection);
5556
}
5657

57-
private HttpURLConnection makeConnection(URL requestURL, int movedTimes,
58-
Consumer<HttpURLConnection> beforeConnection)
59-
throws NoSuchMethodException, ScriptException, IOException,
60-
URISyntaxException {
58+
59+
public HttpURLConnection makeConnection()
60+
throws IOException, NoSuchMethodException, ScriptException, URISyntaxException {
61+
return makeConnection(this.requestURL, 0, (c) -> {});
62+
}
63+
64+
private HttpURLConnection makeConnection(@NotNull URL requestURL, int movedTimes,
65+
@NotNull Consumer<HttpURLConnection> beforeConnection) throws IOException, URISyntaxException, ScriptException, NoSuchMethodException {
6166
log.info("Prepare http request to " + requestURL);
62-
if (requestURL == null) {
63-
log.warning("Invalid request url is null");
64-
throw new RuntimeException("Invalid request url is null");
65-
}
6667
if (movedTimes > 3) {
67-
log.warning("Too many redirect " + requestURL);
68-
throw new RuntimeException("Too many redirect " + requestURL);
68+
log.warn("Too many redirect " + requestURL);
69+
throw new CircularRedirectException("Too many redirect " + requestURL);
6970
}
7071

7172
Proxy proxy = new CustomProxySelector(PreferencesData.getMap())
7273
.getProxyFor(requestURL.toURI());
73-
if ("true".equals(System.getProperty("DEBUG"))) {
74-
System.err.println("Using proxy " + proxy);
75-
}
74+
log.debug("Using proxy {}", proxy);
7675

7776
HttpURLConnection connection = (HttpURLConnection) requestURL
7877
.openConnection(proxy);
@@ -89,7 +88,7 @@ private HttpURLConnection makeConnection(URL requestURL, int movedTimes,
8988
beforeConnection.accept(connection);
9089

9190
// Connect
92-
log.info("Connect to " + requestURL);
91+
log.info("Connect to {} with method {}", requestURL, connection.getRequestMethod());
9392

9493
connection.connect();
9594
int resp = connection.getResponseCode();
@@ -102,7 +101,7 @@ private HttpURLConnection makeConnection(URL requestURL, int movedTimes,
102101

103102
return this.makeConnection(newUrl, movedTimes + 1, beforeConnection);
104103
}
105-
log.info("The response code was" + resp);
104+
log.info("The response code {}, headers {}", resp, StringUtils.join(connection.getHeaderFields()));
106105

107106
return connection;
108107
}

Diff for: arduino-core/src/processing/app/Platform.java

+13-19
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@
2323
package processing.app;
2424

2525
import cc.arduino.packages.BoardPort;
26+
import cc.arduino.utils.network.HttpConnectionManager;
27+
import com.fasterxml.jackson.databind.DeserializationFeature;
28+
import com.fasterxml.jackson.databind.ObjectMapper;
29+
import org.slf4j.Logger;
30+
import org.slf4j.LoggerFactory;
2631
import processing.app.debug.TargetBoard;
2732
import processing.app.debug.TargetPackage;
2833
import processing.app.debug.TargetPlatform;
@@ -31,19 +36,10 @@
3136
import javax.swing.*;
3237
import java.io.File;
3338
import java.io.IOException;
34-
import java.util.HashMap;
35-
import java.util.LinkedList;
36-
import java.util.List;
37-
import java.util.Map;
38-
import java.util.ArrayList;
39-
import java.util.Arrays;
40-
41-
import java.net.URL;
42-
import java.net.URLConnection;
43-
import java.net.HttpURLConnection;
44-
import com.fasterxml.jackson.databind.ObjectMapper;
45-
import com.fasterxml.jackson.databind.DeserializationFeature;
4639
import java.io.InputStream;
40+
import java.net.HttpURLConnection;
41+
import java.net.URL;
42+
import java.util.*;
4743

4844
import static processing.app.I18n.tr;
4945

@@ -64,7 +60,7 @@
6460
* know if name is proper Java package syntax.)
6561
*/
6662
public class Platform {
67-
63+
private static Logger log = LoggerFactory.getLogger(Platform.class);
6864

6965
/**
7066
* Set the default L & F. While I enjoy the bounty of the sixteen possible
@@ -207,12 +203,9 @@ public synchronized void getBoardWithMatchingVidPidFromCloud(String vid, String
207203
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
208204
try {
209205
URL jsonUrl = new URL("http", "api-builder.arduino.cc", 80, "/builder/v1/boards/0x"+vid+"/0x"+pid);
210-
URLConnection connection = jsonUrl.openConnection();
211-
String userAgent = "ArduinoIDE/" + BaseNoGui.VERSION_NAME + " Java/"
212-
+ System.getProperty("java.version");
213-
connection.setRequestProperty("User-agent", userAgent);
214-
connection.connect();
215-
HttpURLConnection httpConnection = (HttpURLConnection) connection;
206+
207+
final HttpURLConnection httpConnection = new HttpConnectionManager(jsonUrl)
208+
.makeConnection();
216209
int code = httpConnection.getResponseCode();
217210
if (code == 404) {
218211
return;
@@ -228,6 +221,7 @@ public synchronized void getBoardWithMatchingVidPidFromCloud(String vid, String
228221
} catch (Exception e) {
229222
// No connection no problem, fail silently
230223
//e.printStackTrace();
224+
231225
}
232226
}
233227

0 commit comments

Comments
 (0)