Skip to content

Commit

Permalink
[JENKINS-72028] replace deprecated URL() at `core/src/main/java/hud…
Browse files Browse the repository at this point in the history
…son/` (#8565)

* missing 'alt' attribute added

* missing 'alt' attribute added

* replaced 'new URL' to 'new URI' per Java 11 target codebase

* Revert "replaced 'new URL' to 'new URI' per Java 11 target codebase"

This reverts commit aeef4c1.

* replaced deprecated URL() with URI#.toURL()

* updated code per review

* updated

* updated code

* added back file

* Update core/src/main/java/hudson/cli/InstallPluginCommand.java

Co-authored-by: James Nord <jtnord@users.noreply.github.com>

* Update core/src/main/java/hudson/TcpSlaveAgentListener.java

remove non required as per suggestion

Co-authored-by: James Nord <jtnord@users.noreply.github.com>

* Update core/src/main/java/hudson/model/UpdateSite.java

Co-authored-by: James Nord <jtnord@users.noreply.github.com>

* Update core/src/main/java/hudson/model/UpdateSite.java

* Spotless

---------

Co-authored-by: Alexander Brandes <mc.cache@web.de>
Co-authored-by: James Nord <jtnord@users.noreply.github.com>
  • Loading branch information
3 people committed Oct 11, 2023
1 parent e226ccf commit dc190ba
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 52 deletions.
9 changes: 8 additions & 1 deletion core/src/main/java/hudson/FilePath.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -3338,7 +3339,13 @@ private int findSeparator(String pattern) {
@Restricted(NoExternalUse.class)
static class UrlFactory {
public URL newURL(String location) throws MalformedURLException {
return new URL(location);
try {
return new URI(location).toURL();
} catch (URISyntaxException e) {
MalformedURLException mex = new MalformedURLException(e.getMessage());
mex.initCause(e);
throw mex;
}
}
}

Expand Down
5 changes: 2 additions & 3 deletions core/src/main/java/hudson/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,6 @@
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -1939,11 +1938,11 @@ public String getServerName() {
String url = Jenkins.get().getRootUrl();
try {
if (url != null) {
String host = new URL(url).getHost();
String host = new URI(url).toURL().getHost();
if (host != null)
return host;
}
} catch (MalformedURLException e) {
} catch (MalformedURLException | URISyntaxException e) {
// fall back to HTTP request
}
return Stapler.getCurrentRequest().getServerName();
Expand Down
13 changes: 7 additions & 6 deletions core/src/main/java/hudson/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import java.io.Writer;
import java.net.HttpRetryException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
Expand Down Expand Up @@ -99,11 +100,11 @@ public static int remotePost(String[] args) throws Exception {
if (!home.endsWith("/")) home = home + '/'; // make sure it ends with '/'

// check for authentication info
String auth = new URL(home).getUserInfo();
String auth = new URI(home).toURL().getUserInfo();
if (auth != null) auth = "Basic " + new Base64Encoder().encode(auth.getBytes(StandardCharsets.UTF_8));

{ // check if the home is set correctly
HttpURLConnection con = open(new URL(home));
HttpURLConnection con = open(new URI(home).toURL());
if (auth != null) con.setRequestProperty("Authorization", auth);
con.connect();
if (con.getResponseCode() != 200
Expand All @@ -113,7 +114,7 @@ public static int remotePost(String[] args) throws Exception {
}
}

URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");
URL jobURL = new URI(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/").toURL();

{ // check if the job name is correct
HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
Expand All @@ -128,8 +129,8 @@ public static int remotePost(String[] args) throws Exception {
// get a crumb to pass the csrf check
String crumbField = null, crumbValue = null;
try {
HttpURLConnection con = open(new URL(home +
"crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
HttpURLConnection con = open(new URI(home +
"crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'").toURL());
if (auth != null) con.setRequestProperty("Authorization", auth);
String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
String[] components = line.split(":");
Expand Down Expand Up @@ -193,7 +194,7 @@ public static int remotePost(String[] args) throws Exception {
} catch (HttpRetryException e) {
if (e.getLocation() != null) {
// retry with the new location
location = new URL(e.getLocation());
location = new URI(e.getLocation()).toURL();
continue;
}
// otherwise failed for reasons beyond us.
Expand Down
6 changes: 3 additions & 3 deletions core/src/main/java/hudson/PluginManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,7 @@ static class UrlPluginCopier implements PluginCopier {

@Override
public void copy(File target) throws Exception {
try (InputStream input = ProxyConfiguration.getInputStream(new URL(url))) {
try (InputStream input = ProxyConfiguration.getInputStream(new URI(url).toURL())) {
Files.copy(input, target.toPath());
}
}
Expand Down Expand Up @@ -1945,15 +1945,15 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl
@RequirePOST public FormValidation doCheckPluginUrl(StaplerRequest request, @QueryParameter String value) throws IOException {
if (StringUtils.isNotBlank(value)) {
try {
URL url = new URL(value);
URL url = new URI(value).toURL();
if (!url.getProtocol().startsWith("http")) {
return FormValidation.error(Messages.PluginManager_invalidUrl());
}

if (!url.getProtocol().equals("https")) {
return FormValidation.warning(Messages.PluginManager_insecureUrl());
}
} catch (MalformedURLException e) {
} catch (MalformedURLException | URISyntaxException e) {
return FormValidation.error(e.getMessage());
}
}
Expand Down
27 changes: 15 additions & 12 deletions core/src/main/java/hudson/TcpSlaveAgentListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@
import java.io.SequenceInputStream;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.StandardCharsets;
import java.security.interfaces.RSAPublicKey;
Expand Down Expand Up @@ -85,8 +85,7 @@ public final class TcpSlaveAgentListener extends Thread {
public final int configuredPort;

/**
* @param port
* Use 0 to choose a random port.
* @param port Use 0 to choose a random port.
*/
public TcpSlaveAgentListener(int port) throws IOException {
super("TCP agent listener port=" + port);
Expand Down Expand Up @@ -120,6 +119,7 @@ public int getPort() {

/**
* Gets the TCP port number in which we are advertising.
*
* @since 1.656
*/
public int getAdvertisedPort() {
Expand All @@ -128,21 +128,23 @@ public int getAdvertisedPort() {

/**
* Gets the host name that we advertise protocol clients to connect to.
*
* @since 2.198
*/
public String getAdvertisedHost() {
if (CLI_HOST_NAME != null) {
return CLI_HOST_NAME;
return CLI_HOST_NAME;
}
try {
return new URL(Jenkins.get().getRootUrl()).getHost();
} catch (MalformedURLException e) {
return new URI(Jenkins.get().getRootUrl()).getHost();
} catch (URISyntaxException e) {
throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e);
}
}

/**
* Gets the Base64 encoded public key that forms part of this instance's identity keypair.
*
* @return the Base64 encoded public key
* @since 2.16
*/
Expand All @@ -165,6 +167,7 @@ public String getAgentProtocolNames() {

/**
* Gets Remoting minimum supported version to prevent unsupported agents from connecting
*
* @since 2.171
*/
public VersionNumber getRemotingMinimumVersion() {
Expand Down Expand Up @@ -228,9 +231,9 @@ public void shutdown() {

private final class ConnectionHandler extends Thread {
private static final String DEFAULT_RESPONSE_404 = "HTTP/1.0 404 Not Found\r\n" +
"Content-Type: text/plain;charset=UTF-8\r\n" +
"\r\n" +
"Not Found\r\n";
"Content-Type: text/plain;charset=UTF-8\r\n" +
"\r\n" +
"Not Found\r\n";
private final Socket s;
/**
* Unique number to identify this connection. Used in the log.
Expand Down Expand Up @@ -407,8 +410,8 @@ public boolean connect(Socket socket) throws IOException {
socket.getRemoteSocketAddress(),
new String(ping, StandardCharsets.UTF_8),
responseLength > 0 && responseLength <= response.length ?
new String(response, 0, responseLength, StandardCharsets.UTF_8) :
"bad response length " + responseLength,
new String(response, 0, responseLength, StandardCharsets.UTF_8) :
"bad response length " + responseLength,
});
return false;
}
Expand Down
6 changes: 4 additions & 2 deletions core/src/main/java/hudson/cli/InstallPluginCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
import hudson.util.VersionNumber;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
Expand Down Expand Up @@ -104,7 +106,7 @@ protected int run() throws Exception {

// is this an URL?
try {
URL u = new URL(source);
URL u = new URI(source).toURL();
stdout.println(Messages.InstallPluginCommand_InstallingPluginFromUrl(u));
File f = getTmpFile();
FileUtils.copyURLToFile(u, f); // TODO JENKINS-58248 proxy
Expand All @@ -113,7 +115,7 @@ protected int run() throws Exception {
pm.dynamicLoad(f);
}
continue;
} catch (MalformedURLException e) {
} catch (MalformedURLException | URISyntaxException e) {
// not an URL
}

Expand Down
32 changes: 17 additions & 15 deletions core/src/main/java/hudson/model/DownloadService.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
Expand Down Expand Up @@ -79,6 +80,7 @@ public class DownloadService {
* the prefix for the signature validator name
*/
private static final String signatureValidatorPrefix = "downloadable";

/**
* Builds up an HTML fragment that starts all the download jobs.
*
Expand Down Expand Up @@ -108,6 +110,7 @@ public Downloadable getById(String id) {
* Confusingly, the JSONP files are given the {@code *.json} file extension, when they are really JavaScript and should be {@code *.js}.
* This method extracts the JSON from a JSONP URL, since that is what we actually want when we download from the server.
* (Currently the true JSON is not published separately, and extracting from the {@code *.json.html} is more work.)
*
* @param src a URL to a JSONP file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
Expand All @@ -133,6 +136,7 @@ public static String loadJSON(URL src) throws IOException {

/**
* Loads JSON from a JSON-with-{@code postMessage} URL.
*
* @param src a URL to a JSON HTML file (typically including {@code id} and {@code version} query parameters)
* @return the embedded JSON text
* @throws IOException if either downloading or processing failed
Expand Down Expand Up @@ -215,14 +219,13 @@ public static class Downloadable implements ExtensionPoint {
/**
* Creates a new downloadable.
*
* @param id The ID to use.
* @param url
* URL relative to {@link UpdateCenter#getDefaultBaseUrl()}.
* So if this string is "foo.json", the ultimate URL will be
* something like "http://updates.jenkins-ci.org/updates/foo.json"
*
* For security and privacy reasons, we don't allow the retrieval
* from random locations.
* @param id The ID to use.
* @param url URL relative to {@link UpdateCenter#getDefaultBaseUrl()}.
* So if this string is "foo.json", the ultimate URL will be
* something like "http://updates.jenkins-ci.org/updates/foo.json"
* <p>
* For security and privacy reasons, we don't allow the retrieval
* from random locations.
* @param interval The interval, in milliseconds, between attempts to update this downloadable's data.
*/
public Downloadable(@NonNull String id, @NonNull String url, long interval) {
Expand Down Expand Up @@ -286,7 +289,6 @@ public String getId() {
*
* @param clazz The class to use to generate an ID.
* @return The ID generated based on the specified class.
*
* @since 2.244
*/
@NonNull
Expand Down Expand Up @@ -322,8 +324,7 @@ public List<String> getUrls() {
/**
* How often do we retrieve the new image?
*
* @return
* number of milliseconds between retrieval.
* @return number of milliseconds between retrieval.
*/
public long getInterval() {
return interval;
Expand Down Expand Up @@ -388,7 +389,7 @@ public FormValidation updateNow() throws IOException {
}
String jsonString;
try {
jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)));
jsonString = loadJSONHTML(new URI(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)).toURL());
toolInstallerMetadataExists = true;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Could not load json from " + site, e);
Expand Down Expand Up @@ -416,6 +417,7 @@ public FormValidation updateNow() throws IOException {

/**
* Function that takes multiple JSONObjects and returns a single one.
*
* @param jsonList to be processed
* @return a single JSONObject
*/
Expand All @@ -425,9 +427,10 @@ public JSONObject reduce(List<JSONObject> jsonList) {

/**
* check if the list of update center entries has duplicates
*
* @param genericList list of entries coming from multiple update centers
* @param comparator the unique ID of an entry
* @param <T> the generic class
* @param comparator the unique ID of an entry
* @param <T> the generic class
* @return true if the list has duplicates, false otherwise
*/
public static <T> boolean hasDuplicates(List<T> genericList, String comparator) {
Expand Down Expand Up @@ -470,7 +473,6 @@ public static ExtensionList<Downloadable> all() {
* {@link #idFor(Class)}).
*
* @param clazz The class to use to determine the downloadable's ID.
*
* @since 2.244
*/
@CheckForNull
Expand Down

0 comments on commit dc190ba

Please sign in to comment.