1
0
mirror of https://github.com/arduino/Arduino.git synced 2025-01-31 20:52:13 +01:00

Add slf4j, optimize some code and fix reported lint problem

This commit is contained in:
Mattia Bertorello 2019-06-28 13:02:50 +02:00
parent 6592c42dcf
commit 8ca093b945
No known key found for this signature in database
GPG Key ID: CE1FB2BE91770F24
4 changed files with 51 additions and 61 deletions

View File

@ -31,6 +31,8 @@ package cc.arduino.utils.network;
import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import processing.app.BaseNoGui; import processing.app.BaseNoGui;
import processing.app.helpers.FileUtils; import processing.app.helpers.FileUtils;
@ -44,11 +46,9 @@ import java.nio.file.Paths;
import java.util.Observable; import java.util.Observable;
import java.util.Optional; import java.util.Optional;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger;
public class FileDownloader extends Observable { public class FileDownloader extends Observable {
private static Logger log = Logger private static Logger log = LoggerFactory.getLogger(FileDownloader.class);
.getLogger(FileDownloader.class.getName());
public enum Status { public enum Status {
CONNECTING, // CONNECTING, //
@ -163,7 +163,7 @@ public class FileDownloader extends Observable {
return; return;
} }
} catch (Exception e) { } catch (Exception e) {
log.log(Level.WARNING, log.warn(
"Cannot get the file from the cache, will be downloaded a new one ", e.getCause()); "Cannot get the file from the cache, will be downloaded a new one ", e.getCause());
} }
@ -219,6 +219,7 @@ public class FileDownloader extends Observable {
throw new Exception("Incomplete download"); throw new Exception("Incomplete download");
} }
// Set the cache whe it finish to download the file // Set the cache whe it finish to download the file
IOUtils.closeQuietly(randomAccessOutputFile);
fileDownloaderCache.fillCache(outputFile); fileDownloaderCache.fillCache(outputFile);
setStatus(Status.COMPLETE); setStatus(Status.COMPLETE);
} catch (InterruptedException e) { } catch (InterruptedException e) {

View File

@ -1,6 +1,8 @@
package cc.arduino.utils.network; package cc.arduino.utils.network;
import com.sun.istack.internal.NotNull; import com.sun.istack.internal.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import processing.app.PreferencesData; import processing.app.PreferencesData;
import processing.app.helpers.FileUtils; import processing.app.helpers.FileUtils;
@ -15,12 +17,9 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Optional; import java.util.Optional;
import java.util.logging.Logger;
public class FileDownloaderCache { public class FileDownloaderCache {
private static Logger log = Logger private static Logger log = LoggerFactory.getLogger(FileDownloaderCache.class);
.getLogger(FileDownloaderCache.class.getName());
private final String cacheFolder;
private final URL remoteURL; private final URL remoteURL;
private final Path cacheFilePath; private final Path cacheFilePath;
// Will be initialized by call the checkIfTheFileIsChanged function // Will be initialized by call the checkIfTheFileIsChanged function
@ -28,11 +27,10 @@ public class FileDownloaderCache {
// BaseNoGui.getSettingsFolder() // BaseNoGui.getSettingsFolder()
public FileDownloaderCache(@NotNull String cacheFolder, @NotNull URL remoteURL) { public FileDownloaderCache(@NotNull String cacheFolder, @NotNull URL remoteURL) {
this.cacheFolder = cacheFolder;
this.remoteURL = remoteURL; this.remoteURL = remoteURL;
String[] splitPath = remoteURL.getPath().split("/"); String[] splitPath = remoteURL.getPath().split("/");
if (splitPath.length > 0) { if (splitPath.length > 0) {
this.cacheFilePath = Paths.get(cacheFolder, splitPath[splitPath.length - 1]); this.cacheFilePath = Paths.get(cacheFolder, splitPath);
} else { } else {
this.cacheFilePath = null; this.cacheFilePath = null;
} }
@ -47,13 +45,14 @@ public class FileDownloaderCache {
try { try {
connection.setRequestMethod("HEAD"); connection.setRequestMethod("HEAD");
} catch (ProtocolException e) { } catch (ProtocolException e) {
throw new RuntimeException(e); log.error("Invalid protocol", e);
} }
}); });
final int responseCode = headRequest.getResponseCode(); final int responseCode = headRequest.getResponseCode();
headRequest.disconnect();
// Something bad is happening return a conservative true to try to download the file // Something bad is happening return a conservative true to try to download the file
if (responseCode < 200 || responseCode >= 300) { if (responseCode < 200 || responseCode >= 300) {
log.warning("The head request return a bad response code " + responseCode); log.warn("The head request return a bad response code " + responseCode);
return true; return true;
} }
@ -71,10 +70,8 @@ public class FileDownloaderCache {
} }
public Optional<File> getFileFromCache() { public Optional<File> getFileFromCache() {
if (Optional.ofNullable(cacheFilePath).isPresent()) { if (Optional.ofNullable(cacheFilePath).isPresent() && Files.exists(cacheFilePath)) {
if (Files.exists(cacheFilePath)) { return Optional.of(new File(cacheFilePath.toUri()));
return Optional.of(new File(cacheFilePath.toUri()));
}
} }
return Optional.empty(); return Optional.empty();
@ -86,9 +83,8 @@ public class FileDownloaderCache {
PreferencesData.set(getPreferencesDataKey(), eTag); PreferencesData.set(getPreferencesDataKey(), eTag);
// If the cache directory does not exist create it // If the cache directory does not exist create it
final Path cachePath = Paths.get(cacheFolder); if (!Files.exists(cacheFilePath.getParent())) {
if (!Files.exists(cachePath)) { Files.createDirectories(cacheFilePath.getParent());
Files.createDirectory(cachePath);
} }
FileUtils.copyFile(fileToCache, cacheFilePath.toFile()); FileUtils.copyFile(fileToCache, cacheFilePath.toFile());
} }

View File

@ -1,7 +1,12 @@
package cc.arduino.utils.network; package cc.arduino.utils.network;
import cc.arduino.net.CustomProxySelector; import cc.arduino.net.CustomProxySelector;
import com.sun.istack.internal.NotNull;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.CircularRedirectException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import processing.app.BaseNoGui; import processing.app.BaseNoGui;
import processing.app.PreferencesData; import processing.app.PreferencesData;
@ -12,12 +17,9 @@ import java.net.Proxy;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HttpConnectionManager { public class HttpConnectionManager {
private static Logger log = Logger private static Logger log = LoggerFactory.getLogger(HttpConnectionManager.class);
.getLogger(HttpConnectionManager.class.getName());
private final URL requestURL; private final URL requestURL;
private final String userAgent; private final String userAgent;
private int connectTimeout; private int connectTimeout;
@ -41,38 +43,35 @@ public class HttpConnectionManager {
Integer.parseInt( Integer.parseInt(
PreferencesData.get("http.connection_timeout", "5000")); PreferencesData.get("http.connection_timeout", "5000"));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
log.log(Level.WARNING, log.warn(
"Cannot parse the http.connection_timeout configuration switch to default 5000 milliseconds", e.getCause()); "Cannot parse the http.connection_timeout configuration switch to default 5000 milliseconds", e.getCause());
this.connectTimeout = 5000; this.connectTimeout = 5000;
} }
} }
public HttpURLConnection makeConnection(Consumer<HttpURLConnection> beforeConnection) public HttpURLConnection makeConnection(@NotNull Consumer<HttpURLConnection> beforeConnection)
throws URISyntaxException, NoSuchMethodException, IOException, throws IOException, NoSuchMethodException, ScriptException, URISyntaxException {
ScriptException {
return makeConnection(this.requestURL, 0, beforeConnection); return makeConnection(this.requestURL, 0, beforeConnection);
} }
private HttpURLConnection makeConnection(URL requestURL, int movedTimes,
Consumer<HttpURLConnection> beforeConnection) public HttpURLConnection makeConnection()
throws NoSuchMethodException, ScriptException, IOException, throws IOException, NoSuchMethodException, ScriptException, URISyntaxException {
URISyntaxException { return makeConnection(this.requestURL, 0, (c) -> {});
}
private HttpURLConnection makeConnection(@NotNull URL requestURL, int movedTimes,
@NotNull Consumer<HttpURLConnection> beforeConnection) throws IOException, URISyntaxException, ScriptException, NoSuchMethodException {
log.info("Prepare http request to " + requestURL); log.info("Prepare http request to " + requestURL);
if (requestURL == null) {
log.warning("Invalid request url is null");
throw new RuntimeException("Invalid request url is null");
}
if (movedTimes > 3) { if (movedTimes > 3) {
log.warning("Too many redirect " + requestURL); log.warn("Too many redirect " + requestURL);
throw new RuntimeException("Too many redirect " + requestURL); throw new CircularRedirectException("Too many redirect " + requestURL);
} }
Proxy proxy = new CustomProxySelector(PreferencesData.getMap()) Proxy proxy = new CustomProxySelector(PreferencesData.getMap())
.getProxyFor(requestURL.toURI()); .getProxyFor(requestURL.toURI());
if ("true".equals(System.getProperty("DEBUG"))) { log.debug("Using proxy {}", proxy);
System.err.println("Using proxy " + proxy);
}
HttpURLConnection connection = (HttpURLConnection) requestURL HttpURLConnection connection = (HttpURLConnection) requestURL
.openConnection(proxy); .openConnection(proxy);
@ -89,7 +88,7 @@ public class HttpConnectionManager {
beforeConnection.accept(connection); beforeConnection.accept(connection);
// Connect // Connect
log.info("Connect to " + requestURL); log.info("Connect to {} with method {}", requestURL, connection.getRequestMethod());
connection.connect(); connection.connect();
int resp = connection.getResponseCode(); int resp = connection.getResponseCode();
@ -102,7 +101,7 @@ public class HttpConnectionManager {
return this.makeConnection(newUrl, movedTimes + 1, beforeConnection); return this.makeConnection(newUrl, movedTimes + 1, beforeConnection);
} }
log.info("The response code was" + resp); log.info("The response code {}, headers {}", resp, StringUtils.join(connection.getHeaderFields()));
return connection; return connection;
} }

View File

@ -23,6 +23,11 @@
package processing.app; package processing.app;
import cc.arduino.packages.BoardPort; import cc.arduino.packages.BoardPort;
import cc.arduino.utils.network.HttpConnectionManager;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import processing.app.debug.TargetBoard; import processing.app.debug.TargetBoard;
import processing.app.debug.TargetPackage; import processing.app.debug.TargetPackage;
import processing.app.debug.TargetPlatform; import processing.app.debug.TargetPlatform;
@ -31,19 +36,10 @@ import processing.app.legacy.PConstants;
import javax.swing.*; import javax.swing.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import static processing.app.I18n.tr; import static processing.app.I18n.tr;
@ -64,7 +60,7 @@ import static processing.app.I18n.tr;
* know if name is proper Java package syntax.) * know if name is proper Java package syntax.)
*/ */
public class Platform { public class Platform {
private static Logger log = LoggerFactory.getLogger(Platform.class);
/** /**
* Set the default L & F. While I enjoy the bounty of the sixteen possible * Set the default L & F. While I enjoy the bounty of the sixteen possible
@ -207,12 +203,9 @@ public class Platform {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try { try {
URL jsonUrl = new URL("http", "api-builder.arduino.cc", 80, "/builder/v1/boards/0x"+vid+"/0x"+pid); URL jsonUrl = new URL("http", "api-builder.arduino.cc", 80, "/builder/v1/boards/0x"+vid+"/0x"+pid);
URLConnection connection = jsonUrl.openConnection();
String userAgent = "ArduinoIDE/" + BaseNoGui.VERSION_NAME + " Java/" final HttpURLConnection httpConnection = new HttpConnectionManager(jsonUrl)
+ System.getProperty("java.version"); .makeConnection();
connection.setRequestProperty("User-agent", userAgent);
connection.connect();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode(); int code = httpConnection.getResponseCode();
if (code == 404) { if (code == 404) {
return; return;
@ -228,6 +221,7 @@ public class Platform {
} catch (Exception e) { } catch (Exception e) {
// No connection no problem, fail silently // No connection no problem, fail silently
//e.printStackTrace(); //e.printStackTrace();
} }
} }