From f66ba70e54dc1dd5d2f55d88e5194184030ac208 Mon Sep 17 00:00:00 2001 From: abhishekmaity Date: Sun, 17 Sep 2023 19:45:14 +0530 Subject: [PATCH 01/11] missing 'alt' attribute added --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 755a417ea158..7b92885f66f7 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ - + Jenkins logo # About From 2afcdebbd7cde09d31df66c22f98a4f5c57aca26 Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Sun, 17 Sep 2023 19:55:29 +0530 Subject: [PATCH 02/11] missing 'alt' attribute added --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b92885f66f7..99a8177cec24 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ - Jenkins logo + Jenkins logo # About From aeef4c1e4bb57a4832dbe368920aa0716a3f68e7 Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Tue, 19 Sep 2023 00:16:07 +0530 Subject: [PATCH 03/11] replaced 'new URL' to 'new URI' per Java 11 target codebase --- cli/src/main/java/hudson/cli/CLI.java | 4 +- .../java/hudson/cli/FullDuplexHttpStream.java | 2 +- cli/src/main/java/hudson/cli/SSHCLI.java | 2 +- .../java/hudson/ClassicPluginStrategy.java | 4 +- core/src/main/java/hudson/FilePath.java | 4 +- core/src/main/java/hudson/Functions.java | 2 +- core/src/main/java/hudson/Main.java | 14 ++-- core/src/main/java/hudson/Plugin.java | 2 +- core/src/main/java/hudson/PluginManager.java | 8 +- core/src/main/java/hudson/PluginWrapper.java | 2 +- .../main/java/hudson/ProxyConfiguration.java | 2 +- .../java/hudson/TcpSlaveAgentListener.java | 2 +- core/src/main/java/hudson/WebAppMain.java | 2 +- .../java/hudson/cli/InstallPluginCommand.java | 2 +- .../java/hudson/console/UrlAnnotator.java | 2 +- .../java/hudson/model/DownloadService.java | 2 +- .../main/java/hudson/model/UpdateCenter.java | 14 ++-- .../main/java/hudson/model/UpdateSite.java | 2 +- .../java/hudson/scm/RepositoryBrowser.java | 2 +- .../tools/DownloadFromUrlInstaller.java | 2 +- .../hudson/tools/ZipExtractionInstaller.java | 2 +- .../java/hudson/util/FormFieldValidator.java | 2 +- .../java/jenkins/install/SetupWizard.java | 2 +- .../validator/routines/UrlValidator.java | 6 +- .../security/ResourceDomainConfiguration.java | 10 +-- core/src/test/java/hudson/FilePathTest.java | 4 +- .../test/java/hudson/PluginManagerTest.java | 2 +- .../test/java/hudson/PluginWrapperTest.java | 2 +- .../java/hudson/console/UrlAnnotatorTest.java | 2 +- .../jenkins/model/JenkinsGetRootUrlTest.java | 2 +- .../routines/DomainValidatorTest.java | 2 +- .../validator/routines/UrlValidatorTest.java | 78 +++++++++---------- .../test/java/jenkins/util/UrlHelperTest.java | 2 +- .../test/java/hudson/PluginManagerTest.java | 2 +- .../hudson/TcpSlaveAgentListenerTest.java | 4 +- .../bugs/JnlpAccessWithSecuredHudsonTest.java | 2 +- .../hudson/console/ConsoleAnnotatorTest.java | 2 +- .../java/hudson/console/UrlAnnotatorTest.java | 2 +- .../HudsonHomeDiskUsageMonitorTest.java | 6 +- .../ReverseProxySetupMonitorTest.java | 26 +++---- .../test/java/hudson/jobs/CreateItemTest.java | 8 +- .../hudson/markup/MarkupFormatterTest.java | 2 +- .../hudson/model/AbstractProjectTest.java | 12 +-- .../model/BuildAuthorizationTokenTest.java | 12 +-- .../model/DirectlyModifiableViewTest.java | 2 +- .../model/DirectoryBrowserSupportTest.java | 4 +- .../java/hudson/model/FingerprintTest.java | 12 +-- .../test/java/hudson/model/HudsonTest.java | 2 +- .../src/test/java/hudson/model/ItemsTest.java | 8 +- .../test/java/hudson/model/ProjectTest.java | 2 +- .../src/test/java/hudson/model/QueueTest.java | 2 +- .../src/test/java/hudson/model/SlaveTest.java | 2 +- .../java/hudson/model/UpdateCenterTest.java | 2 +- .../java/hudson/model/UpdateSiteTest.java | 12 +-- .../java/hudson/model/UserRestartTest.java | 4 +- .../HudsonPrivateSecurityRealmTest.java | 2 +- .../security/csrf/CrumbExclusionTest.java | 4 +- .../security/csrf/DefaultCrumbIssuerTest.java | 2 +- .../tools/ZipExtractionInstallerTest.java | 2 +- .../util/RobustReflectionConverterTest.java | 4 +- .../java/jenkins/install/SetupWizardTest.java | 6 +- .../java/jenkins/model/AssetManagerTest.java | 2 +- .../test/java/jenkins/model/JenkinsTest.java | 8 +- .../model/ParameterizedJobMixInTest.java | 4 +- .../security/ApiCrumbExclusionTest.java | 2 +- .../security/ApiTokenPropertyTest.java | 10 +-- .../BasicHeaderApiTokenAuthenticatorTest.java | 12 +-- .../security/BasicHeaderProcessorTest.java | 2 +- .../jenkins/security/ResourceDomainTest.java | 4 +- .../jenkins/security/Security177Test.java | 6 +- .../jenkins/security/Security2278Test.java | 4 +- .../jenkins/security/Security2761Test.java | 2 +- .../jenkins/security/Security637Test.java | 28 +++---- .../security/SuspiciousRequestFilterTest.java | 2 +- .../apitoken/ApiTokenStatsRestartTest.java | 4 +- .../security/apitoken/ApiTokenStatsTest.java | 4 +- .../seed/UserSeedChangeListenerTest.java | 2 +- .../seed/UserSeedPropertyRestartTest.java | 2 +- .../security/seed/UserSeedPropertyTest.java | 2 +- .../security/stapler/DoActionFilterTest.java | 18 ++--- .../security/stapler/Security400Test.java | 16 ++-- .../security/stapler/Security914Test.java | 4 +- .../security/stapler/StaplerAbstractTest.java | 6 +- war/src/main/java/executable/Main.java | 2 +- 84 files changed, 244 insertions(+), 244 deletions(-) diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 9aee43f6f9a0..9e5d9cabdf7f 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -306,7 +306,7 @@ public boolean verify(String s, SSLSession sslSession) { } CLIConnectionFactory factory = new CLIConnectionFactory(); - String userInfo = new URL(url).getUserInfo(); + String userInfo = new URI(url).getUserInfo(); if (userInfo != null) { factory = factory.basicAuth(userInfo); } else if (auth != null) { @@ -388,7 +388,7 @@ public void close() throws IOException { private static int plainHttpConnection(String url, List args, CLIConnectionFactory factory) throws IOException, InterruptedException { LOGGER.log(FINE, "Trying to connect to {0} via plain protocol over HTTP", url); - FullDuplexHttpStream streams = new FullDuplexHttpStream(new URL(url), "cli?remoting=false", factory.authorization); + FullDuplexHttpStream streams = new FullDuplexHttpStream(new URI(url), "cli?remoting=false", factory.authorization); try (ClientSideImpl connection = new ClientSideImpl(new PlainCLIProtocol.FramedOutput(streams.getOutputStream()))) { connection.start(args); InputStream is = streams.getInputStream(); diff --git a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java index 3b4b4d25342f..509bc1ce4952 100644 --- a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java +++ b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java @@ -55,7 +55,7 @@ public FullDuplexHttpStream(URL base, String relativeTarget, String authorizatio this.base = tryToResolveRedirects(base, authorization); - URL target = new URL(this.base, relativeTarget); + URL target = new URI(this.base, relativeTarget); UUID uuid = UUID.randomUUID(); // so that the server can correlate those two connections diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 3d6ea7c42530..01455dfc33a5 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -62,7 +62,7 @@ class SSHCLI { static int sshConnection(String jenkinsUrl, String user, List args, PrivateKeyProvider provider, final boolean strictHostKey) throws IOException { Logger.getLogger(SecurityUtils.class.getName()).setLevel(Level.WARNING); // suppress: BouncyCastle not registered, using the default JCE provider - URL url = new URL(jenkinsUrl + "login"); + URL url = new URI(jenkinsUrl + "login"); URLConnection conn = openConnection(url); CLI.verifyJenkinsConnection(conn); String endpointDescription = conn.getHeaderField("X-SSH-Endpoint"); diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index c16fc93e1aa9..ffeb0e2c8203 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -294,9 +294,9 @@ protected ClassLoader createClassLoader(List paths, ClassLoader parent, At } URLClassLoader2 classLoader; if (usePluginFirstClassLoader) { - classLoader = new PluginFirstClassLoader2(urls.toArray(new URL[0]), parent); + classLoader = new PluginFirstClassLoader2(urls.toArray(new URI[0]), parent); } else { - classLoader = new URLClassLoader2(urls.toArray(new URL[0]), parent); + classLoader = new URIClassLoader2(urls.toArray(new URI[0]), parent); } return classLoader; } diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index cdc057ef9c54..15fc757d4f6c 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -3333,12 +3333,12 @@ private int findSeparator(String pattern) { } } - private static final UrlFactory DEFAULT_URL_FACTORY = new UrlFactory(); + private static final UrlFactory DEFAULT_URL_FACTORY = new URIFactory(); @Restricted(NoExternalUse.class) static class UrlFactory { public URL newURL(String location) throws MalformedURLException { - return new URL(location); + return new URI(location); } } diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 7f3411406780..3ac59d306ab1 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1939,7 +1939,7 @@ public String getServerName() { String url = Jenkins.get().getRootUrl(); try { if (url != null) { - String host = new URL(url).getHost(); + String host = new URI(url).getHost(); if (host != null) return host; } diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java index 625fef0c52ee..68f65d948377 100644 --- a/core/src/main/java/hudson/Main.java +++ b/core/src/main/java/hudson/Main.java @@ -99,11 +99,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).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)); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if (con.getResponseCode() != 200 @@ -113,10 +113,10 @@ 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/") + "/"); { // check if the job name is correct - HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult")); + HttpURLConnection con = open(new URI(jobURL, "acceptBuildResult")); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if (con.getResponseCode() != 200) { @@ -128,7 +128,7 @@ 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 + + HttpURLConnection con = open(new URI(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'")); if (auth != null) con.setRequestProperty("Authorization", auth); String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8"); @@ -165,7 +165,7 @@ public static int remotePost(String[] args) throws Exception { throw new IOException(e); } - URL location = new URL(jobURL, "postBuildResult"); + URL location = new URI(jobURL, "postBuildResult"); while (true) { try { // start a remote connection @@ -193,7 +193,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()); continue; } // otherwise failed for reasons beyond us. diff --git a/core/src/main/java/hudson/Plugin.java b/core/src/main/java/hudson/Plugin.java index 41eafeabf545..6fd540ed7966 100644 --- a/core/src/main/java/hudson/Plugin.java +++ b/core/src/main/java/hudson/Plugin.java @@ -251,7 +251,7 @@ public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOExceptio long expires = staticLink ? TimeUnit.DAYS.toMillis(365) : -1; // use serveLocalizedFile to support automatic locale selection - rsp.serveLocalizedFile(req, new URL(wrapper.baseResourceURL, '.' + path), expires); + rsp.serveLocalizedFile(req, new URI(wrapper.baseResourceURL, '.' + path), expires); } // diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index 5d64485cfa1b..e2a456a08b8d 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -1097,7 +1097,7 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { } /*package*/ static @CheckForNull Manifest parsePluginManifest(URL bundledJpi) { - try (URLClassLoader cl = new URLClassLoader(new URL[]{bundledJpi})) { + try (URLClassLoader cl = new URIClassLoader(new URI[]{bundledJpi})) { InputStream in = null; try { URL res = cl.findResource(PluginWrapper.MANIFEST_FILENAME); @@ -1848,7 +1848,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))) { Files.copy(input, target.toPath()); } } @@ -1875,7 +1875,7 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl if (StringUtils.isNotBlank(items.get(1).getString())) { // this is a URL deployment fileName = items.get(1).getString(); - copier = new UrlPluginCopier(fileName); + copier = new URIPluginCopier(fileName); } else { // this is a file upload FileItem fileItem = items.get(0); @@ -1962,7 +1962,7 @@ 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); if (!url.getProtocol().startsWith("http")) { return FormValidation.error(Messages.PluginManager_invalidUrl()); } diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java index 2161e501089f..058ac74f6ead 100644 --- a/core/src/main/java/hudson/PluginWrapper.java +++ b/core/src/main/java/hudson/PluginWrapper.java @@ -911,7 +911,7 @@ public String getPluginClass() { public boolean hasLicensesXml() { try { - new URL(baseResourceURL, "WEB-INF/licenses.xml").openStream().close(); + new URI(baseResourceURL, "WEB-INF/licenses.xml").openStream().close(); return true; } catch (IOException e) { return false; diff --git a/core/src/main/java/hudson/ProxyConfiguration.java b/core/src/main/java/hudson/ProxyConfiguration.java index a165fa6e3151..7ed7c1819f36 100644 --- a/core/src/main/java/hudson/ProxyConfiguration.java +++ b/core/src/main/java/hudson/ProxyConfiguration.java @@ -458,7 +458,7 @@ private void jenkins48775workaround(Proxy proxy, URL url) { HttpURLConnection preAuth = null; try { // We do not care if there is anything at this URL, all we care is that it is using the proxy - preAuth = (HttpURLConnection) new URL("http", url.getHost(), -1, "/").openConnection(proxy); + preAuth = (HttpURLConnection) new URI("http", url.getHost(), -1, "/").openConnection(proxy); preAuth.setRequestMethod("HEAD"); preAuth.connect(); } catch (IOException e) { diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index 3936071de2ef..d07398c7af1f 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -135,7 +135,7 @@ public String getAdvertisedHost() { return CLI_HOST_NAME; } try { - return new URL(Jenkins.get().getRootUrl()).getHost(); + return new URI(Jenkins.get().getRootUrl()).getHost(); } catch (MalformedURLException e) { throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e); } diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java index 99603ac1e411..ffecc8e7ef6a 100644 --- a/core/src/main/java/hudson/WebAppMain.java +++ b/core/src/main/java/hudson/WebAppMain.java @@ -170,7 +170,7 @@ public Locale get() { JVM jvm; try { jvm = new JVM(); - new URLClassLoader(new URL[0], getClass().getClassLoader()); + new URIClassLoader(new URI[0], getClass().getClassLoader()); } catch (SecurityException e) { throw new InsufficientPermissionDetected(e); } diff --git a/core/src/main/java/hudson/cli/InstallPluginCommand.java b/core/src/main/java/hudson/cli/InstallPluginCommand.java index cc9d3b59f91d..b7a41974ff18 100644 --- a/core/src/main/java/hudson/cli/InstallPluginCommand.java +++ b/core/src/main/java/hudson/cli/InstallPluginCommand.java @@ -104,7 +104,7 @@ protected int run() throws Exception { // is this an URL? try { - URL u = new URL(source); + URL u = new URI(source); stdout.println(Messages.InstallPluginCommand_InstallingPluginFromUrl(u)); File f = getTmpFile(); FileUtils.copyURLToFile(u, f); // TODO JENKINS-58248 proxy diff --git a/core/src/main/java/hudson/console/UrlAnnotator.java b/core/src/main/java/hudson/console/UrlAnnotator.java index 191c65544456..f9c31915c9ac 100644 --- a/core/src/main/java/hudson/console/UrlAnnotator.java +++ b/core/src/main/java/hudson/console/UrlAnnotator.java @@ -16,7 +16,7 @@ public class UrlAnnotator extends ConsoleAnnotatorFactory { @Override public ConsoleAnnotator newInstance(Object context) { - return new UrlConsoleAnnotator(); + return new URIConsoleAnnotator(); } private static class UrlConsoleAnnotator extends ConsoleAnnotator { diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index b9a5610c4e35..2010e0d11cbb 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -388,7 +388,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))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e); diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 7ea06f20191e..871ea99400df 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -1207,7 +1207,7 @@ public UpdateCenterConfiguration() { * @throws IOException if a connection can't be established */ public void checkConnection(ConnectionCheckJob job, String connectionCheckUrl) throws IOException { - testConnection(new URL(connectionCheckUrl)); + testConnection(new URI(connectionCheckUrl)); } /** @@ -1230,9 +1230,9 @@ public void checkUpdateCenter(ConnectionCheckJob job, String updateCenterUrl) th static URL toUpdateCenterCheckUrl(String updateCenterUrl) throws MalformedURLException { URL url; if (updateCenterUrl.startsWith("http://") || updateCenterUrl.startsWith("https://")) { - url = new URL(updateCenterUrl + (updateCenterUrl.indexOf('?') == -1 ? "?uctest" : "&uctest")); + url = new URI(updateCenterUrl + (updateCenterUrl.indexOf('?') == -1 ? "?uctest" : "&uctest")); } else { - url = new URL(updateCenterUrl); + url = new URI(updateCenterUrl); } return url; } @@ -2193,7 +2193,7 @@ public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth, bool @Override protected URL getURL() throws MalformedURLException { - return new URL(plugin.url); + return new URI(plugin.url); } @Override @@ -2422,7 +2422,7 @@ public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) { @Override protected URL getURL() throws MalformedURLException { - return new URL(plugin.url); + return new URI(plugin.url); } @Override @@ -2517,7 +2517,7 @@ protected URL getURL() throws MalformedURLException { if (site == null) { throw new MalformedURLException("no update site defined"); } - return new URL(site.getData().core.url); + return new URI(site.getData().core.url); } @Override @@ -2564,7 +2564,7 @@ protected URL getURL() throws MalformedURLException { if (site == null) { throw new MalformedURLException("no update site defined"); } - return new URL(site.getData().core.url); + return new URI(site.getData().core.url); } @Override diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index 1b5b734c7be6..acddfa8f2a91 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -215,7 +215,7 @@ public long getDataTimestamp() { @Restricted(NoExternalUse.class) public @NonNull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException { - return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck); + return updateData(DownloadService.loadJSON(new URI(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck); } private FormValidation updateData(String json, boolean signatureCheck) diff --git a/core/src/main/java/hudson/scm/RepositoryBrowser.java b/core/src/main/java/hudson/scm/RepositoryBrowser.java index 05b095b02bce..7844792ad207 100644 --- a/core/src/main/java/hudson/scm/RepositoryBrowser.java +++ b/core/src/main/java/hudson/scm/RepositoryBrowser.java @@ -88,7 +88,7 @@ protected static URL normalizeToEndWithSlash(URL url) { String q = url.getQuery(); q = q != null ? '?' + q : ""; try { - return new URL(url, url.getPath() + '/' + q); + return new URI(url, url.getPath() + '/' + q); } catch (MalformedURLException e) { // impossible throw new Error(e); diff --git a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java index 5d7f4c0c024f..264c7e0c0fea 100644 --- a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java +++ b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java @@ -74,7 +74,7 @@ public FilePath performInstallation(ToolInstallation tool, Node node, TaskListen if (isUpToDate(expected, inst)) return expected; - if (expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { + if (expected.installIfNecessaryFrom(new URI(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { expected.child(".timestamp").delete(); // we don't use the timestamp FilePath base = findPullUpDirectory(expected); if (base != null && base != expected) diff --git a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java index 1e1c171f6a95..39c54b3d90f8 100644 --- a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java +++ b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java @@ -83,7 +83,7 @@ public String getSubdir() { @Override public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath dir = preferredLocation(tool, node); - if (dir.installIfNecessaryFrom(new URL(url), log, "Unpacking " + url + " to " + dir + " on " + node.getDisplayName())) { + if (dir.installIfNecessaryFrom(new URI(url), log, "Unpacking " + url + " to " + dir + " on " + node.getDisplayName())) { dir.act(new ChmodRecAPlusX()); } if (subdir == null) { diff --git a/core/src/main/java/hudson/util/FormFieldValidator.java b/core/src/main/java/hudson/util/FormFieldValidator.java index 9bf1287b9e01..edec7e5882e1 100644 --- a/core/src/main/java/hudson/util/FormFieldValidator.java +++ b/core/src/main/java/hudson/util/FormFieldValidator.java @@ -335,7 +335,7 @@ protected void check() throws IOException, ServletException { if (!value.endsWith("/")) value += '/'; try { - URL url = new URL(value); + URL url = new URI(value); HttpURLConnection con = openConnection(url); con.connect(); if (con.getResponseCode() != 200 diff --git a/core/src/main/java/jenkins/install/SetupWizard.java b/core/src/main/java/jenkins/install/SetupWizard.java index 126aaf0d11bb..789d006d4020 100644 --- a/core/src/main/java/jenkins/install/SetupWizard.java +++ b/core/src/main/java/jenkins/install/SetupWizard.java @@ -561,7 +561,7 @@ public JSONArray getPlatformPluginUpdates() { suggestedPluginUrl = suggestedPluginUrl + (suggestedPluginUrl.contains("?") ? "&" : "?") + "version=" + version; } try { - URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl)); + URLConnection connection = ProxyConfiguration.open(new URI(suggestedPluginUrl)); try { String initialPluginJson = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8); diff --git a/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java b/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java index 40c0eae1d13f..2f2e50e1dd16 100644 --- a/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java +++ b/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java @@ -50,7 +50,7 @@ * Construct a UrlValidator with valid schemes of "http", and "https". * * String[] schemes = {"http","https"}. - * UrlValidator urlValidator = new UrlValidator(schemes); + * UrlValidator urlValidator = new URIValidator(schemes); * if (urlValidator.isValid("ftp://foo.bar.com/")) { * System.out.println("url is valid"); * } else { @@ -60,7 +60,7 @@ * prints "url is invalid" * If instead the default constructor is used. * - * UrlValidator urlValidator = new UrlValidator(); + * UrlValidator urlValidator = new URIValidator(); * if (urlValidator.isValid("ftp://foo.bar.com/")) { * System.out.println("url is valid"); * } else { @@ -179,7 +179,7 @@ public class UrlValidator implements Serializable { /** * Singleton instance of this class with default schemes and options. */ - private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator(); + private static final UrlValidator DEFAULT_URL_VALIDATOR = new URIValidator(); /** * Returns the singleton instance of this class with default schemes and options. diff --git a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java index f5465ca4b61e..96b1bbd4764b 100644 --- a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java +++ b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java @@ -112,14 +112,14 @@ private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlin URL resourceRootUrl; try { - resourceRootUrl = new URL(resourceRootUrlString); + resourceRootUrl = new URI(resourceRootUrlString); } catch (MalformedURLException ex) { return FormValidation.error(Messages.ResourceDomainConfiguration_Invalid()); } String resourceRootUrlHost = resourceRootUrl.getHost(); try { - String jenkinsRootUrlHost = new URL(jenkinsRootUrlString).getHost(); + String jenkinsRootUrlHost = new URI(jenkinsRootUrlString).getHost(); if (jenkinsRootUrlHost.equals(resourceRootUrlHost)) { // We do not allow the same host for Jenkins and resource root URLs even if there's some other difference. // This is a conservative choice and prohibits same host/different proto/different port/different path: @@ -147,7 +147,7 @@ private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlin // Send a request to /instance-identity/ at the resource root URL and check whether it is this Jenkins try { - URLConnection urlConnection = new URL(resourceRootUrlString + "instance-identity/").openConnection(); + URLConnection urlConnection = new URI(resourceRootUrlString + "instance-identity/").openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; int responseCode = httpURLConnection.getResponseCode(); @@ -222,7 +222,7 @@ public static boolean isResourceRequest(HttpServletRequest req) { } String resourceRootUrl = get().getUrl(); try { - URL url = new URL(resourceRootUrl); + URL url = new URI(resourceRootUrl); String resourceRootHost = url.getHost(); if (!resourceRootHost.equalsIgnoreCase(req.getServerName())) { @@ -241,7 +241,7 @@ public static boolean isResourceRequest(HttpServletRequest req) { return false; } } catch (MalformedURLException ex) { - // the URL here cannot be so broken that we cannot call `new URL(String)` on it... + // the URL here cannot be so broken that we cannot call `new URI(String)` on it... return false; } return true; diff --git a/core/src/test/java/hudson/FilePathTest.java b/core/src/test/java/hudson/FilePathTest.java index fe152a25ba49..10be262595e6 100644 --- a/core/src/test/java/hudson/FilePathTest.java +++ b/core/src/test/java/hudson/FilePathTest.java @@ -672,13 +672,13 @@ private static void assertValidateAntFileMask(String expected, FilePath d, Strin private URL someUrlToZipFile(final URLConnection con) throws IOException { - final URLStreamHandler urlHandler = new URLStreamHandler() { + final URLStreamHandler urlHandler = new URIStreamHandler() { @Override protected URLConnection openConnection(URL u) { return con; } }; - return new URL("http", "some-host", 0, "/some-path.zip", urlHandler); + return new URI("http", "some-host", 0, "/some-path.zip", urlHandler); } private InputStream someZippedContent() throws IOException { diff --git a/core/src/test/java/hudson/PluginManagerTest.java b/core/src/test/java/hudson/PluginManagerTest.java index 580808c8d56d..8d10f5f0ea24 100644 --- a/core/src/test/java/hudson/PluginManagerTest.java +++ b/core/src/test/java/hudson/PluginManagerTest.java @@ -206,7 +206,7 @@ private File createHpiWithManifest() throws IOException { private URL toManifestUrl(File jarFile) throws MalformedURLException { final String manifestPath = "META-INF/MANIFEST.MF"; - return new URL("jar:" + jarFile.toURI().toURL() + "!/" + manifestPath); + return new URI("jar:" + jarFile.toURI().toURL() + "!/" + manifestPath); } private static class FormValidationMatcher extends TypeSafeDiagnosingMatcher { diff --git a/core/src/test/java/hudson/PluginWrapperTest.java b/core/src/test/java/hudson/PluginWrapperTest.java index f12a8af7bdc3..45f758d8965a 100644 --- a/core/src/test/java/hudson/PluginWrapperTest.java +++ b/core/src/test/java/hudson/PluginWrapperTest.java @@ -105,7 +105,7 @@ public void dependencyFailedToLoad() { @Issue("JENKINS-66563") @Test public void insertJarsIntoClassPath() throws Exception { - try (URLClassLoader2 cl = new URLClassLoader2(new URL[0])) { + try (URLClassLoader2 cl = new URIClassLoader2(new URI[0])) { assertInjectingJarsWorks(cl); } } diff --git a/core/src/test/java/hudson/console/UrlAnnotatorTest.java b/core/src/test/java/hudson/console/UrlAnnotatorTest.java index d05080ff899e..8788dc3b1f8b 100644 --- a/core/src/test/java/hudson/console/UrlAnnotatorTest.java +++ b/core/src/test/java/hudson/console/UrlAnnotatorTest.java @@ -35,7 +35,7 @@ */ public class UrlAnnotatorTest { - private ConsoleAnnotator ca = new UrlAnnotator().newInstance(null); + private ConsoleAnnotator ca = new URIAnnotator().newInstance(null); @Test public void testAnnotate() { diff --git a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java index 620616a15081..1acccd5206ed 100644 --- a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java +++ b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java @@ -247,7 +247,7 @@ private URL getUrl(final String realUrl) { try { - return new URL(realUrl); + return new URI(realUrl); } catch (Exception ex) { throw new RuntimeException(ex); diff --git a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java index 3e1631692c6d..17f1ff2a7e62 100644 --- a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java +++ b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java @@ -502,7 +502,7 @@ private static long download(File f, String tldurl, long timestamp) throws IOExc } else { modTime = 0; } - HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection(); + HttpURLConnection hc = (HttpURLConnection) new URI(tldurl).openConnection(); if (modTime > 0) { SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); //Sun, 06 Nov 1994 08:49:37 GMT String since = sdf.format(new Date(modTime)); diff --git a/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java b/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java index 97cb3f7c54e4..c0945ff42dbe 100644 --- a/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java +++ b/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java @@ -63,8 +63,8 @@ public void testIsValidScheme() { if (printStatus) { System.out.print("\n testIsValidScheme() "); } - //UrlValidator urlVal = new UrlValidator(schemes,false,false,false); - UrlValidator urlVal = new UrlValidator(schemes, 0); + //UrlValidator urlVal = new URIValidator(schemes,false,false,false); + UrlValidator urlVal = new URIValidator(schemes, 0); for (ResultPair testPair : testScheme) { boolean result = urlVal.isValidScheme(testPair.item); assertEquals(testPair.item, testPair.valid, result); @@ -89,7 +89,7 @@ public void testIsValidScheme() { * @param testObjects Used to create a url. */ public void testIsValid(Object[] testObjects, long options) { - UrlValidator urlVal = new UrlValidator(null, null, options); + UrlValidator urlVal = new URIValidator(null, null, options); assertTrue(urlVal.isValid("http://www.google.com")); assertTrue(urlVal.isValid("http://www.google.com/")); int statusPerLine = 60; @@ -134,20 +134,20 @@ public void testIsValid(Object[] testObjects, long options) { @Test public void testValidator202() { String[] schemes = {"http", "https"}; - UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); + UrlValidator urlValidator = new URIValidator(schemes, UrlValidator.NO_FRAGMENTS); assertTrue(urlValidator.isValid("http://l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.org")); } @Test public void testValidator204() { String[] schemes = {"http", "https"}; - UrlValidator urlValidator = new UrlValidator(schemes); + UrlValidator urlValidator = new URIValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); } @Test public void testValidator218() { - UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); + UrlValidator validator = new URIValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue("parentheses should be valid in URLs", validator.isValid("http://somewhere.com/pathxyz/file(1).html")); } @@ -159,7 +159,7 @@ public void testValidator235() { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("http://xn--d1abbgf6aiiy.xn--p1ai")); assertTrue("президент.рф should validate", validator.isValid("http://президент.рф")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("http://www.b\u00fccher.ch")); @@ -171,7 +171,7 @@ public void testValidator235() { @Test public void testValidator248() { RegexValidator regex = new RegexValidator(new String[] {"localhost", ".*\\.my-testing"}); - UrlValidator validator = new UrlValidator(regex, 0); + UrlValidator validator = new URIValidator(regex, 0); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); @@ -187,7 +187,7 @@ public void testValidator248() { validator.isValid("http://www.apache.org/test/index.html")); // Now check using options - validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); + validator = new URIValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); @@ -201,7 +201,7 @@ public void testValidator248() { @Test public void testValidator288() { - UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); + UrlValidator validator = new URIValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("hostname should validate", validator.isValid("http://hostname")); @@ -222,7 +222,7 @@ public void testValidator288() { validator.isValid("http://www.apache.org/test/index.html")); // Turn it off, and check - validator = new UrlValidator(0); + validator = new URIValidator(0); assertFalse("hostname should no longer validate", validator.isValid("http://hostname")); @@ -237,7 +237,7 @@ public void testValidator288() { @Test public void testValidator276() { // file:// isn't allowed by default - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); @@ -259,7 +259,7 @@ public void testValidator276() { // Turn it on, and check // Note - we need to enable local urls when working with file: - validator = new UrlValidator(new String[] {"http", "file"}, UrlValidator.ALLOW_LOCAL_URLS); + validator = new URIValidator(new String[] {"http", "file"}, UrlValidator.ALLOW_LOCAL_URLS); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); @@ -290,24 +290,24 @@ public void testValidator276() { @Test public void testValidator391OK() { String[] schemes = {"file"}; - UrlValidator urlValidator = new UrlValidator(schemes); + UrlValidator urlValidator = new URIValidator(schemes); assertTrue(urlValidator.isValid("file:///C:/path/to/dir/")); } @Test public void testValidator391FAILS() { String[] schemes = {"file"}; - UrlValidator urlValidator = new UrlValidator(schemes); + UrlValidator urlValidator = new URIValidator(schemes); assertTrue(urlValidator.isValid("file:/C:/path/to/dir/")); } @Test public void testValidator309() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); - urlValidator = new UrlValidator(new String[] {"HTTP", "HTTPS"}); + urlValidator = new URIValidator(new String[] {"HTTP", "HTTPS"}); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); @@ -315,7 +315,7 @@ public void testValidator309() { @Test public void testValidator339() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://www.cnn.com./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://www.cnn.com../")); // doubly dotty @@ -325,7 +325,7 @@ public void testValidator339() { @Test public void testValidator339IDN() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://президент.рф./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://президент.рф..../")); // very dotty @@ -335,14 +335,14 @@ public void testValidator339IDN() { @Test public void testValidator342() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://example.rocks/")); assertTrue(urlValidator.isValid("http://example.rocks")); } @Test public void testValidator411() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://example.rocks:/")); assertTrue(urlValidator.isValid("http://example.rocks:0/")); assertTrue(urlValidator.isValid("http://example.rocks:65535/")); @@ -353,32 +353,32 @@ public void testValidator411() { @Test public void testValidator464() { String[] schemes = {"file"}; - UrlValidator urlValidator = new UrlValidator(schemes); + UrlValidator urlValidator = new URIValidator(schemes); String fileNAK = "file://bad ^ domain.com/label/test"; assertFalse(fileNAK, urlValidator.isValid(fileNAK)); } @Test public void testValidator452() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html")); } @Test(expected = IllegalArgumentException.class) public void testValidator473_1() { // reject null DomainValidator - new UrlValidator(new String[]{}, null, 0L, null); + new URIValidator(new String[]{}, null, 0L, null); } @Test(expected = IllegalArgumentException.class) public void testValidator473_2() { // reject null DomainValidator with mismatched allowLocal List items = new ArrayList<>(); - new UrlValidator(new String[]{}, null, 0L, DomainValidator.getInstance(true, items)); + new URIValidator(new String[]{}, null, 0L, DomainValidator.getInstance(true, items)); } @Test(expected = IllegalArgumentException.class) public void testValidator473_3() { // reject null DomainValidator with mismatched allowLocal List items = new ArrayList<>(); - new UrlValidator(new String[]{}, null, UrlValidator.ALLOW_LOCAL_URLS, DomainValidator.getInstance(false, items)); + new URIValidator(new String[]{}, null, UrlValidator.ALLOW_LOCAL_URLS, DomainValidator.getInstance(false, items)); } static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) { @@ -425,7 +425,7 @@ public void testValidateUrl() { @Test public void testValidator290() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue(validator.isValid("http://xn--h1acbxfam.idn.icann.org/")); // assertTrue(validator.isValid("http://xn--e1afmkfd.xn--80akhbyknj4f")); // Internationalized country code top-level domains @@ -484,13 +484,13 @@ public void testValidator290() { @Test public void testValidator361() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue(validator.isValid("http://hello.tokyo/")); } @Test public void testValidator363() { - UrlValidator urlValidator = new UrlValidator(); + UrlValidator urlValidator = new URIValidator(); assertTrue(urlValidator.isValid("http://www.example.org/a/b/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/a/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/hello.world/")); @@ -511,7 +511,7 @@ public void testValidator363() { @Test public void testValidator375() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://[::1]:80/index.html"; @@ -523,7 +523,7 @@ public void testValidator375() { @Test public void testValidator353() { // userinfo - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://user:pass@www.apache.org:80/path")); assertTrue(validator.isValid("http://user:@www.apache.org:80/path")); @@ -537,13 +537,13 @@ public void testValidator353() { // userinfo @Test public void testValidator382() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue(validator.isValid("ftp://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose")); } @Test public void testValidator380() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://www.apache.org:8/path")); assertTrue(validator.isValid("http://www.apache.org:/path")); @@ -551,7 +551,7 @@ public void testValidator380() { @Test public void testValidator420() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main%20Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main+Avenue")); @@ -559,7 +559,7 @@ public void testValidator420() { @Test public void testValidator467() { - UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); + UrlValidator validator = new URIValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue(validator.isValid("https://example.com/some_path/path/")); assertTrue(validator.isValid("https://example.com//somepath/path/")); assertTrue(validator.isValid("https://example.com//some_path/path/")); @@ -568,7 +568,7 @@ public void testValidator467() { @Test public void testValidator283() { - UrlValidator validator = new UrlValidator(); + UrlValidator validator = new URIValidator(); assertFalse(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%fr")); assertTrue(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%22")); } @@ -576,9 +576,9 @@ public void testValidator283() { @Test public void testFragments() { String[] schemes = {"http", "https"}; - UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); + UrlValidator urlValidator = new URIValidator(schemes, UrlValidator.NO_FRAGMENTS); assertFalse(urlValidator.isValid("http://apache.org/a/b/c#frag")); - urlValidator = new UrlValidator(schemes); + urlValidator = new URIValidator(schemes); assertTrue(urlValidator.isValid("http://apache.org/a/b/c#frag")); } @@ -689,7 +689,7 @@ public void testFragments() { * @param args - URLs to validate */ public static void main(String[] args) { - UrlValidator uv = new UrlValidator(); + UrlValidator uv = new URIValidator(); for (String arg : args) { try { URI uri = new URI(arg); diff --git a/core/src/test/java/jenkins/util/UrlHelperTest.java b/core/src/test/java/jenkins/util/UrlHelperTest.java index 31f400a86474..7734d83558a9 100644 --- a/core/src/test/java/jenkins/util/UrlHelperTest.java +++ b/core/src/test/java/jenkins/util/UrlHelperTest.java @@ -43,7 +43,7 @@ public void regularCases() { // spaces are forbidden assertFalse(UrlHelper.isValidRootUrl("http:// ")); - // examples not passing with a simple `new URL(url).toURI()` check + // examples not passing with a simple `new URI(url).toURI()` check assertFalse(UrlHelper.isValidRootUrl("http://jenkins//context")); assertFalse(UrlHelper.isValidRootUrl("http:/jenkins")); assertFalse(UrlHelper.isValidRootUrl("http://.com")); diff --git a/test/src/test/java/hudson/PluginManagerTest.java b/test/src/test/java/hudson/PluginManagerTest.java index bd761d21d4bd..296bf4edebea 100644 --- a/test/src/test/java/hudson/PluginManagerTest.java +++ b/test/src/test/java/hudson/PluginManagerTest.java @@ -241,7 +241,7 @@ public void startPlugin(PluginWrapper plugin) throws Exception { @Test public void uberClassLoaderDoesntUseContextClassLoader() throws Exception { Thread t = Thread.currentThread(); - URLClassLoader ucl = new URLClassLoader(new URL[0], r.jenkins.pluginManager.uberClassLoader); + URLClassLoader ucl = new URIClassLoader(new URI[0], r.jenkins.pluginManager.uberClassLoader); ClassLoader old = t.getContextClassLoader(); t.setContextClassLoader(ucl); diff --git a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java index 8d6f13d9807a..4a9df76058a1 100644 --- a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java +++ b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java @@ -40,12 +40,12 @@ public void diagnostics() throws Exception { int p = r.jenkins.getTcpSlaveAgentListener().getPort(); WebClient wc = r.createWebClient(); - TextPage text = wc.getPage(new URL("http://localhost:" + p + "/")); + TextPage text = wc.getPage(new URI("http://localhost:" + p + "/")); String c = text.getContent(); assertThat(c, containsString(Jenkins.VERSION)); wc.setThrowExceptionOnFailingStatusCode(false); - Page page = wc.getPage(new URL("http://localhost:" + p + "/xxx")); + Page page = wc.getPage(new URI("http://localhost:" + p + "/xxx")); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, page.getWebResponse().getStatusCode()); } } diff --git a/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java b/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java index a6544fd36150..a26815c072c8 100644 --- a/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java +++ b/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java @@ -78,7 +78,7 @@ public void anonymousCanAlwaysLoadJARs() throws Exception { URL baseUrl = jnlp.getUrl(); Document dom = new DOMReader().read(jnlp.getXmlDocument()); for (Object jar : dom.selectNodes("//jar")) { - URL url = new URL(baseUrl, ((Element) jar).attributeValue("href")); + URL url = new URI(baseUrl, ((Element) jar).attributeValue("href")); System.out.println(url); // now make sure that these URLs are unprotected diff --git a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java index 60b08b0936de..b58c57e644b4 100644 --- a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java +++ b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java @@ -149,7 +149,7 @@ class ProgressiveLogClient { } String next() throws IOException { - WebRequest req = new WebRequest(new URL(r.getURL() + run.getUrl() + "/logText/progressiveHtml" + (start != null ? "?start=" + start : ""))); + WebRequest req = new WebRequest(new URI(r.getURL() + run.getUrl() + "/logText/progressiveHtml" + (start != null ? "?start=" + start : ""))); req.setEncodingType(null); Map headers = new HashMap(); if (consoleAnnotator != null) diff --git a/test/src/test/java/hudson/console/UrlAnnotatorTest.java b/test/src/test/java/hudson/console/UrlAnnotatorTest.java index 23c3ddb275b7..5f9c51c69ccb 100644 --- a/test/src/test/java/hudson/console/UrlAnnotatorTest.java +++ b/test/src/test/java/hudson/console/UrlAnnotatorTest.java @@ -49,7 +49,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen @Test public void test2() { MarkupText m = new MarkupText("{abc='http://url/',def='ghi'}"); - new UrlAnnotator().newInstance(null).annotate(null, m); + new URIAnnotator().newInstance(null).annotate(null, m); String html = m.toString(false); assertTrue(html.contains("http://url/")); System.out.println(html); diff --git a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java index f21f5088128d..5d9fee742e7f 100644 --- a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java @@ -71,7 +71,7 @@ public void noAccessForNonAdmin() throws Exception { User bob = User.getById("bob", true); User administrator = User.getById("administrator", true); - WebRequest request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); NameValuePair param = new NameValuePair("no", "true"); request.setRequestParameters(List.of(param)); @@ -83,12 +83,12 @@ public void noAccessForNonAdmin() throws Exception { assertTrue(mon.isEnabled()); - WebRequest requestReadOnly = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET); + WebRequest requestReadOnly = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET); p = wc.getPage(requestReadOnly); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, p.getWebResponse().getStatusCode()); wc.withBasicApiToken(administrator); - request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); + request = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); request.setRequestParameters(List.of(param)); p = wc.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java b/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java index a9bb7278a849..447d1c460125 100644 --- a/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java @@ -66,7 +66,7 @@ public void localhost_correct() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); wc.getPage(request); } @@ -80,7 +80,7 @@ public void localhost_testingForContext() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); // As the context was already set inside the referer, adding another one will fail @@ -97,7 +97,7 @@ public void localhost_withoutReferer() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); // no referer assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); } @@ -111,7 +111,7 @@ public void localhost_withRefererNotComingFromManage() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); // wrong referer request.setAdditionalHeader("Referer", j.getURL() + "configure"); assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); @@ -131,7 +131,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(rootUrlWithoutContext); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); // As the rootURL is missing the context, a regular test will fail @@ -156,7 +156,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(rootUrlWithoutContext); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); @@ -176,7 +176,7 @@ public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); wc.getPage(request); @@ -195,7 +195,7 @@ public void usingIp_butRefererUsingRootUrl() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); wc.getPage(request); } @@ -209,7 +209,7 @@ public void usingIp_withoutReferer() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // no referer assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); } @@ -223,7 +223,7 @@ public void usingIp_withRefererIp() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // referer using IP request.setAdditionalHeader("Referer", getRootUrlWithIp(j) + "manage"); @@ -243,7 +243,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(getRootUrlWithIp(j).toString()); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // referer using IP request.setAdditionalHeader("Referer", getRootUrlWithIp(j) + "manage"); @@ -264,7 +264,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(rootUrlWithoutContext); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // referer using IP request.setAdditionalHeader("Referer", getRootUrlWithIp(j) + "manage"); @@ -283,6 +283,6 @@ private String getAdminMonitorTestUrl(JenkinsRule j) { } private URL getRootUrlWithIp(JenkinsRule j) throws Exception { - return new URL(j.getURL().toString().replace("localhost", "127.0.0.1")); + return new URI(j.getURL().toString().replace("localhost", "127.0.0.1")); } } diff --git a/test/src/test/java/hudson/jobs/CreateItemTest.java b/test/src/test/java/hudson/jobs/CreateItemTest.java index c8d511ce168d..9cb94d572c69 100644 --- a/test/src/test/java/hudson/jobs/CreateItemTest.java +++ b/test/src/test/java/hudson/jobs/CreateItemTest.java @@ -71,7 +71,7 @@ public void testCreateItemFromCopy() throws Exception { rule.createFreeStyleProject(sourceJobName); String newJobName = "newJob"; - URL apiURL = new URL(MessageFormat.format( + URL apiURL = new URI(MessageFormat.format( "{0}createItem?mode=copy&from={1}&name={2}", rule.getURL().toString(), sourceJobName, newJobName)); @@ -95,7 +95,7 @@ public void vetoCreateItemFromCopy() throws Exception { rule.createFreeStyleProject(sourceJobName); String newJobName = "newJob"; - URL apiURL = new URL(MessageFormat.format( + URL apiURL = new URI(MessageFormat.format( "{0}createItem?mode=copy&from={1}&name={2}", rule.getURL().toString(), sourceJobName, newJobName)); @@ -124,10 +124,10 @@ public void createWithFolderPaths() throws Exception { JenkinsRule.WebClient wc = rule.createWebClient(); - wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST)); + wc.getPage(new WebRequest(new URI(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST)); assertNotNull(d2.getItem("p2")); - wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST)); + wc.getPage(new WebRequest(new URI(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST)); assertNotNull(d2.getItem("p3")); } diff --git a/test/src/test/java/hudson/markup/MarkupFormatterTest.java b/test/src/test/java/hudson/markup/MarkupFormatterTest.java index f5e0e05095e5..eac9f8869883 100644 --- a/test/src/test/java/hudson/markup/MarkupFormatterTest.java +++ b/test/src/test/java/hudson/markup/MarkupFormatterTest.java @@ -104,7 +104,7 @@ public void security2153RequiresPOST() throws Exception { @Issue("SECURITY-2153") public void security2153SetsCSP() throws Exception { final JenkinsRule.WebClient wc = j.createWebClient(); - final Page htmlPage = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.jenkins.getRootUrl() + "/markupFormatter/previewDescription?text=lolwut"), HttpMethod.POST))); + final Page htmlPage = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.jenkins.getRootUrl() + "/markupFormatter/previewDescription?text=lolwut"), HttpMethod.POST))); final WebResponse response = htmlPage.getWebResponse(); assertEquals(200, response.getStatusCode()); assertThat(response.getContentAsString(), containsString("lolwut")); diff --git a/test/src/test/java/hudson/model/AbstractProjectTest.java b/test/src/test/java/hudson/model/AbstractProjectTest.java index 2da8fc430448..144b130797ff 100644 --- a/test/src/test/java/hudson/model/AbstractProjectTest.java +++ b/test/src/test/java/hudson/model/AbstractProjectTest.java @@ -140,7 +140,7 @@ public void wipeWorkspaceProtected() throws Exception { // make sure that the action link is protected JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - Page page = wc.getPage(new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST)); + Page page = wc.getPage(new WebRequest(new URI(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST)); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode()); } @@ -323,7 +323,7 @@ public void deleteRedirect() throws Exception { private String deleteRedirectTarget(String job) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); String base = wc.getContextPath(); - String loc = wc.getPage(wc.addCrumb(new WebRequest(new URL(base + job + "/doDelete"), HttpMethod.POST))).getUrl().toString(); + String loc = wc.getPage(wc.addCrumb(new WebRequest(new URI(base + job + "/doDelete"), HttpMethod.POST))).getUrl().toString(); assert loc.startsWith(base) : loc; return loc.substring(base.length()); } @@ -357,13 +357,13 @@ public void queueSuccessBehaviorOverHTTP() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebResponse rsp = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.getURL(), p.getUrl() + + WebResponse rsp = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.getURL(), p.getUrl() + "build?delay=0"), HttpMethod.POST))).getWebResponse(); assertEquals(HttpURLConnection.HTTP_CREATED, rsp.getStatusCode()); assertNotNull(rsp.getResponseHeaderValue("Location")); - WebResponse rsp2 = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.getURL(), p.getUrl() + + WebResponse rsp2 = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.getURL(), p.getUrl() + "build?delay=0"), HttpMethod.POST))).getWebResponse(); assertEquals(HttpURLConnection.HTTP_CREATED, rsp2.getStatusCode()); @@ -371,7 +371,7 @@ public void queueSuccessBehaviorOverHTTP() throws Exception { p.makeDisabled(true); - WebResponse rsp3 = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.getURL(), p.getUrl() + + WebResponse rsp3 = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.getURL(), p.getUrl() + "build?delay=0"), HttpMethod.POST))).getWebResponse(); assertEquals(HttpURLConnection.HTTP_CONFLICT, rsp3.getStatusCode()); @@ -450,7 +450,7 @@ public void configDotXmlSubmissionToDifferentType() throws Exception { } private HttpURLConnection postConfigDotXml(FreeStyleProject p, String xml) throws Exception { - HttpURLConnection con = (HttpURLConnection) new URL(j.getURL(), "job/" + p.getName() + "/config.xml").openConnection(); + HttpURLConnection con = (HttpURLConnection) new URI(j.getURL(), "job/" + p.getName() + "/config.xml").openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml; charset=utf-8"); con.setDoOutput(true); diff --git a/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java b/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java index 1f8de8ff5b9d..0546ee206e09 100644 --- a/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java +++ b/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java @@ -42,7 +42,7 @@ public void triggerJobWithoutSecurityRealm_ShouldSucceed_WithPost() throws Excep jr.jenkins.setAuthorizationStrategy(null); FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); - wc.getPage(wc.addCrumb(new WebRequest(new URL(jr.getURL(), project.getUrl() + + wc.getPage(wc.addCrumb(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST))); jr.waitUntilNoActivity(); @@ -59,7 +59,7 @@ public void triggerJobWithoutSecurityRealm_ShouldFail_WithGet() throws Exception FailingHttpStatusCodeException fex = assertThrows( "should not reach here since only POST request can", FailingHttpStatusCodeException.class, - () -> wc.getPage(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.GET))); + () -> wc.getPage(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.GET))); assertThat("Should fail with method not allowed", fex.getStatusCode(), is(405)); } @@ -70,7 +70,7 @@ public void triggerJobWithoutSecurityRealm_ButWithToken_ShouldSucceed_WithGet() jr.jenkins.setAuthorizationStrategy(null); FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); - wc.getPage(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), + wc.getPage(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), HttpMethod.GET)); jr.waitUntilNoActivity(); assertThat("the project should have been built", project.getBuilds(), hasSize(1)); @@ -81,7 +81,7 @@ public void triggerJobWithTokenShouldSucceedWithPost() throws Exception { FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); HtmlPage page = wc.getPage(wc.addCrumb(new WebRequest( - new URL(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), + new URI(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), HttpMethod.POST))); jr.waitUntilNoActivity(); assertThat("the project should have been built", project.getBuilds(), hasSize(1)); @@ -92,7 +92,7 @@ public void triggerJobWithTokenShouldSucceedWithGet() throws Exception { FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); HtmlPage page = wc.getPage(new WebRequest( - new URL(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), + new URI(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), HttpMethod.GET)); jr.waitUntilNoActivity(); assertThat("the project should have been built", project.getBuilds(), hasSize(1)); @@ -106,7 +106,7 @@ public void triggerJobsWithoutTokenShouldFail() throws Exception { FailingHttpStatusCodeException fex = assertThrows( "should not reach here as anonymous does not have Item.BUILD and token is not set", FailingHttpStatusCodeException.class, - () -> wc.getPage(wc.addCrumb(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); + () -> wc.getPage(wc.addCrumb(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); assertThat("Should fail with access denied", fex.getStatusCode(), is(403)); } diff --git a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java index aab9da2cfe65..2cbe77d747b2 100644 --- a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java +++ b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java @@ -188,7 +188,7 @@ private Page doPost(View view, String path) throws Exception { WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); WebRequest req = new WebRequest( - new URL(j.jenkins.getRootUrl() + view.getUrl() + path), + new URI(j.jenkins.getRootUrl() + view.getUrl() + path), HttpMethod.POST ); diff --git a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java index 7b1bbdb7c9bd..e964f8de6646 100644 --- a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java +++ b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java @@ -482,7 +482,7 @@ public InputStream open() throws IOException { @Override public URL toExternalURL() throws IOException { - return new URL(Jenkins.get().getRootUrl() + "files/" + hash); + return new URI(Jenkins.get().getRootUrl() + "files/" + hash); } }; return new VirtualFile() { // the root @@ -1454,7 +1454,7 @@ public InputStream open() throws IOException { @Override public URL toExternalURL() throws IOException { - return new URL(Jenkins.get().getRootUrl() + "files/" + hash); + return new URI(Jenkins.get().getRootUrl() + "files/" + hash); } }; return new VirtualFile() { // the root diff --git a/test/src/test/java/hudson/model/FingerprintTest.java b/test/src/test/java/hudson/model/FingerprintTest.java index 452df423d8a6..16f99c57a3de 100644 --- a/test/src/test/java/hudson/model/FingerprintTest.java +++ b/test/src/test/java/hudson/model/FingerprintTest.java @@ -400,11 +400,11 @@ public void checkNormalFingerprintWithWebClient() throws Exception { Fingerprint fp = getFingerprint(build, "test.txt"); - Page page = rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "fingerprint/" + fp.getHashString() + "/"))); + Page page = rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "fingerprint/" + fp.getHashString() + "/"))); assertEquals(200, page.getWebResponse().getStatusCode()); // could also be reached using static// - Page page2 = rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + fp.getHashString() + "/"))); + Page page2 = rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + fp.getHashString() + "/"))); assertEquals(200, page2.getWebResponse().getStatusCode()); } @@ -468,7 +468,7 @@ public void checkArbitraryEmptyFileExistenceWithWebClient() throws Exception { targetFile.deleteOnExit(); String first = fp.getHashString().substring(0, 2); String second = fp.getHashString().substring(2, 4); - rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf2/"))); + rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf2/"))); assertTrue(targetFile.exists()); } @@ -517,7 +517,7 @@ public void checkArbitraryFileExistenceWithWebClient() throws Exception { String first = fp.getHashString().substring(0, 2); String second = fp.getHashString().substring(2, 4); - rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf4/"))); + rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf4/"))); assertTrue(targetFile.exists()); } @@ -552,7 +552,7 @@ public void checkArbitraryFileNonexistenceWithWebClient() throws Exception { Fingerprint fp = getFingerprint(build, "test.txt"); String first = fp.getHashString().substring(0, 2); String second = fp.getHashString().substring(2, 4); - rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf6/"))); + rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf6/"))); } @Test @@ -577,7 +577,7 @@ public void checkArbitraryFingerprintConfigFileExistenceWithWebClient() throws E try { // that file exists, so we need to ensure if it's returned, the content is not the expected one from the test data. String partialUrl = "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf7/"; - page = rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), partialUrl))); + page = rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), partialUrl))); } catch (FailingHttpStatusCodeException e) { // expected refusal after the correction assertEquals(500, e.getStatusCode()); diff --git a/test/src/test/java/hudson/model/HudsonTest.java b/test/src/test/java/hudson/model/HudsonTest.java index a4fff0108458..f2ec7e69ee9c 100644 --- a/test/src/test/java/hudson/model/HudsonTest.java +++ b/test/src/test/java/hudson/model/HudsonTest.java @@ -177,7 +177,7 @@ public void deleteHudsonComputer() throws Exception { wc.setThrowExceptionOnFailingStatusCode(false); // try to delete it by hitting the final URL directly - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "computer/(built-in)/doDelete"), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "computer/(built-in)/doDelete"), HttpMethod.POST); page = wc.getPage(wc.addCrumb(req)); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/model/ItemsTest.java b/test/src/test/java/hudson/model/ItemsTest.java index 37c0befc3081..577a91eb5f39 100644 --- a/test/src/test/java/hudson/model/ItemsTest.java +++ b/test/src/test/java/hudson/model/ItemsTest.java @@ -228,7 +228,7 @@ private enum OverwriteTactic { // redirect perversely counts as a failure .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { throw new FailingHttpStatusCodeException(webResponse); } @@ -241,7 +241,7 @@ private enum OverwriteTactic { JenkinsRule.WebClient wc = wc(r) .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse(); r.jenkins.getItem("dupe").delete(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { throw new FailingHttpStatusCodeException(webResponse); @@ -252,7 +252,7 @@ private enum OverwriteTactic { REST_CREATE { @Override void run(JenkinsRule r, String target) throws Exception { JenkinsRule.WebClient wc = wc(r); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/xml"); req.setRequestBody(""); wc.getPage(req); @@ -265,7 +265,7 @@ private enum OverwriteTactic { JenkinsRule.WebClient wc = wc(r) .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { r.jenkins.getItem("dupe").delete(); throw new FailingHttpStatusCodeException(webResponse); diff --git a/test/src/test/java/hudson/model/ProjectTest.java b/test/src/test/java/hudson/model/ProjectTest.java index 8d2f5e6bc7cc..d6a5fb21e3f6 100644 --- a/test/src/test/java/hudson/model/ProjectTest.java +++ b/test/src/test/java/hudson/model/ProjectTest.java @@ -618,7 +618,7 @@ public void testDoDoWipeOutWorkspace() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.withBasicCredentials(user.getId(), "password"); - WebRequest request = new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST); HtmlPage p = wc.getPage(request); assertEquals(200, p.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index e31e2acdd1c9..1376bbac92d8 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -1199,7 +1199,7 @@ private void checkCancelOperationUsingUrl(Function urlProvid Queue.Item currentOne = items[0]; assertFalse(currentOne.getFuture().isCancelled()); - WebRequest request = new WebRequest(new URL(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST); { // user without right cannot cancel JenkinsRule.WebClient wc = r.createWebClient() diff --git a/test/src/test/java/hudson/model/SlaveTest.java b/test/src/test/java/hudson/model/SlaveTest.java index b66130bfc4ea..58909a8c8017 100644 --- a/test/src/test/java/hudson/model/SlaveTest.java +++ b/test/src/test/java/hudson/model/SlaveTest.java @@ -107,7 +107,7 @@ public void slaveConfigDotXml() throws Exception { } private void post(String url, String xml) throws Exception { - HttpURLConnection con = (HttpURLConnection) new URL(j.getURL(), url).openConnection(); + HttpURLConnection con = (HttpURLConnection) new URI(j.getURL(), url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml;charset=UTF-8"); con.setRequestProperty(CrumbIssuer.DEFAULT_CRUMB_NAME, "test"); diff --git a/test/src/test/java/hudson/model/UpdateCenterTest.java b/test/src/test/java/hudson/model/UpdateCenterTest.java index 998e9badd67e..9866a5883344 100644 --- a/test/src/test/java/hudson/model/UpdateCenterTest.java +++ b/test/src/test/java/hudson/model/UpdateCenterTest.java @@ -58,7 +58,7 @@ public class UpdateCenterTest { } private void doData(String location) throws Exception { - URL url = new URL(location); + URL url = new URI(location); String jsonp = DownloadService.loadJSON(url); JSONObject json = JSONObject.fromObject(jsonp); diff --git a/test/src/test/java/hudson/model/UpdateSiteTest.java b/test/src/test/java/hudson/model/UpdateSiteTest.java index e355aec53399..34508bc1e0cd 100644 --- a/test/src/test/java/hudson/model/UpdateSiteTest.java +++ b/test/src/test/java/hudson/model/UpdateSiteTest.java @@ -130,7 +130,7 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques } }); server.start(); - baseUrl = new URL("http", "localhost", connector.getLocalPort(), RELATIVE_BASE); + baseUrl = new URI("http", "localhost", connector.getLocalPort(), RELATIVE_BASE); } @After @@ -139,15 +139,15 @@ public void shutdownWebserver() throws Exception { } @Test public void relativeURLs() throws Exception { - URL url = new URL(baseUrl, "/plugins/htmlpublisher-update-center.json"); + URL url = new URI(baseUrl, "/plugins/htmlpublisher-update-center.json"); UpdateSite site = new UpdateSite(UpdateCenter.ID_DEFAULT, url.toString()); overrideUpdateSite(site); assertEquals(FormValidation.ok(), site.updateDirectly(false).get()); Data data = site.getData(); assertNotNull(data); - assertEquals(new URL(url, "jenkins.war").toString(), data.core.url); + assertEquals(new URI(url, "jenkins.war").toString(), data.core.url); assertEquals(new HashSet<>(Arrays.asList("htmlpublisher", "dummy")), data.plugins.keySet()); - assertEquals(new URL(url, "htmlpublisher.jpi").toString(), data.plugins.get("htmlpublisher").url); + assertEquals(new URI(url, "htmlpublisher.jpi").toString(), data.plugins.get("htmlpublisher").url); assertEquals("http://nowhere.net/dummy.hpi", data.plugins.get("dummy").url); UpdateSite.Plugin htmlPublisherPlugin = data.plugins.get("htmlpublisher"); @@ -177,7 +177,7 @@ public void shutdownWebserver() throws Exception { } @Test public void updateDirectlyWithJson() throws Exception { - UpdateSite us = new UpdateSite("default", new URL(baseUrl, "update-center.json").toExternalForm()); + UpdateSite us = new UpdateSite("default", new URI(baseUrl, "update-center.json").toExternalForm()); assertNull(us.getPlugin("AdaptivePlugin")); assertEquals(FormValidation.ok(), us.updateDirectly(/* TODO the certificate is now expired, and downloading a fresh copy did not seem to help */false).get()); assertNotNull(us.getPlugin("AdaptivePlugin")); @@ -241,7 +241,7 @@ private UpdateSite getUpdateSite(String path) throws Exception { } private UpdateSite getUpdateSite(String path, String id) throws Exception { - URL url = new URL(baseUrl, path); + URL url = new URI(baseUrl, path); UpdateSite site = new UpdateSite(id, url.toString()); assertEquals(FormValidation.ok(), site.updateDirectly(false).get()); return site; diff --git a/test/src/test/java/hudson/model/UserRestartTest.java b/test/src/test/java/hudson/model/UserRestartTest.java index 95641933beed..74aead70531d 100644 --- a/test/src/test/java/hudson/model/UserRestartTest.java +++ b/test/src/test/java/hudson/model/UserRestartTest.java @@ -115,7 +115,7 @@ public void legacyConfigMoveCannotEscapeUserFolder() throws Throwable { JenkinsRule.WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(r.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(r.jenkins.getRootUrl() + "whoAmI/api/xml")); request.setAdditionalHeader("Authorization", base64("..", "any-password")); wc.getPage(request); } @@ -123,7 +123,7 @@ public void legacyConfigMoveCannotEscapeUserFolder() throws Throwable { JenkinsRule.WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(r.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(r.jenkins.getRootUrl() + "whoAmI/api/xml")); request.setAdditionalHeader("Authorization", base64("../users/..", "any-password")); wc.getPage(request); } diff --git a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java index 9883b0680843..ece9e3882719 100644 --- a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java +++ b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java @@ -344,7 +344,7 @@ private void createFirstAccount(String login) throws Exception { info.password2 = login; info.fullname = StringUtils.capitalize(login); - WebRequest request = new WebRequest(new URL(wc.getContextPath() + "securityRealm/createFirstAccount"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(wc.getContextPath() + "securityRealm/createFirstAccount"), HttpMethod.POST); request.setRequestParameters(Arrays.asList( new NameValuePair("username", login), new NameValuePair("password1", login), diff --git a/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java b/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java index adb2184ff239..9e1bbd375430 100644 --- a/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java +++ b/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java @@ -62,7 +62,7 @@ public void pathInfo() throws Exception { r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to("admin")); for (String path : new String[] {/* control */ "scriptText", /* test */ "scriptText/..;/cli"}) { try { - fail(path + " should have been rejected: " + r.createWebClient().login("admin").getPage(new WebRequest(new URL(r.getURL(), path + "?script=11*11"), HttpMethod.POST)).getWebResponse().getContentAsString()); + fail(path + " should have been rejected: " + r.createWebClient().login("admin").getPage(new WebRequest(new URI(r.getURL(), path + "?script=11*11"), HttpMethod.POST)).getWebResponse().getContentAsString()); } catch (FailingHttpStatusCodeException x) { switch (x.getStatusCode()) { case 403: @@ -80,7 +80,7 @@ public void pathInfo() throws Exception { @Test public void regular() throws Exception { - r.createWebClient().getPage(new WebRequest(new URL(r.getURL(), "root/"), HttpMethod.POST)); + r.createWebClient().getPage(new WebRequest(new URI(r.getURL(), "root/"), HttpMethod.POST)); Assert.assertTrue(ExtensionList.lookupSingleton(RootActionImpl.class).posted); } diff --git a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java index b6b417f8dc6f..c67d1d4687fb 100644 --- a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java +++ b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java @@ -303,7 +303,7 @@ public void twoRequestsWithoutSessionGetDifferentCrumbs() throws Exception { } private WebRequest createRequestForJobCreation(String jobName) throws Exception { - WebRequest req = new WebRequest(new URL(r.getURL() + "createItem?name=" + jobName), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(r.getURL() + "createItem?name=" + jobName), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/xml"); req.setRequestBody(""); return req; diff --git a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java index 72210eec3362..6f273ad39e24 100644 --- a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java +++ b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java @@ -65,7 +65,7 @@ public void onlyAdminCanReachTheDoCheck() throws Exception { User.getById(ADMIN, true); User.getById(USER, true); - WebRequest request = new WebRequest(new URL(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl"), HttpMethod.POST); request.setRequestBody(URLEncoder.encode("value=https://www.google.com", StandardCharsets.UTF_8)); JenkinsRule.WebClient adminWc = j.createWebClient(); diff --git a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java index da667a80d802..f29845715903 100644 --- a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java +++ b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java @@ -206,7 +206,7 @@ public void testRestInterfaceFailure() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); WebClient wc = r.createWebClient(); wc.withBasicApiToken("test"); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD)); wc.getPage(req); @@ -237,7 +237,7 @@ public void testRestInterfaceFailure() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); wc.withBasicApiToken("test"); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue")); diff --git a/test/src/test/java/jenkins/install/SetupWizardTest.java b/test/src/test/java/jenkins/install/SetupWizardTest.java index 7168f93d93af..42b828eb7f10 100644 --- a/test/src/test/java/jenkins/install/SetupWizardTest.java +++ b/test/src/test/java/jenkins/install/SetupWizardTest.java @@ -221,7 +221,7 @@ public void testRemoteUpdateSiteFailingValidation() throws Exception { server.setHandler(new RemoteUpdateSiteHandler(serverContext, true)); try { server.start(); - baseUrl = new URL("http", "localhost", connector.getLocalPort(), serverContext); + baseUrl = new URI("http", "localhost", connector.getLocalPort(), serverContext); // Init the update site CustomRemoteUpdateSite us = new CustomRemoteUpdateSite(baseUrl.toString(), false); @@ -255,7 +255,7 @@ public void testRemoteUpdateSiteSkippingValidation() throws Exception { try { server.start(); DownloadService.signatureCheck = false; - baseUrl = new URL("http", "localhost", connector.getLocalPort(), serverContext); + baseUrl = new URI("http", "localhost", connector.getLocalPort(), serverContext); // Init the update site CustomRemoteUpdateSite us = new CustomRemoteUpdateSite(baseUrl.toString(), false); @@ -292,7 +292,7 @@ public void testRemoteUpdateSitePerformingValidation() throws Exception { server.setHandler(new RemoteUpdateSiteHandler(serverContext, true)); try { server.start(); - baseUrl = new URL("http", "localhost", connector.getLocalPort(), serverContext); + baseUrl = new URI("http", "localhost", connector.getLocalPort(), serverContext); // Init the update site CustomRemoteUpdateSite us = new CustomRemoteUpdateSite(baseUrl.toString(), true); diff --git a/test/src/test/java/jenkins/model/AssetManagerTest.java b/test/src/test/java/jenkins/model/AssetManagerTest.java index d00541d4a554..4994d264a1a4 100644 --- a/test/src/test/java/jenkins/model/AssetManagerTest.java +++ b/test/src/test/java/jenkins/model/AssetManagerTest.java @@ -41,7 +41,7 @@ public class AssetManagerTest { @Test @Issue("JENKINS-58736") public void emptyAssetDoesNotThrowError() throws Exception { - URL url = new URL(j.getURL() + "assets"); + URL url = new URI(j.getURL() + "assets"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpCon.getResponseCode()); } diff --git a/test/src/test/java/jenkins/model/JenkinsTest.java b/test/src/test/java/jenkins/model/JenkinsTest.java index 5c0c9acedbb2..33959cc8a69b 100644 --- a/test/src/test/java/jenkins/model/JenkinsTest.java +++ b/test/src/test/java/jenkins/model/JenkinsTest.java @@ -326,11 +326,11 @@ public void testDoScript() throws Exception { wc.goTo("script"); wc.assertFails("script?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD); assertNull(System.getProperty("hack")); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST); wc.getPage(req); assertEquals("me", System.getProperty("hack")); wc.assertFails("scriptText?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD); - req = new WebRequest(new URL(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST); + req = new WebRequest(new URI(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST); wc.getPage(req); assertEquals("you", System.getProperty("huck")); @@ -380,7 +380,7 @@ public void testDoEval() throws Exception { } private Page eval(WebClient wc) throws Exception { - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "eval"), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "eval"), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody("${1+2}"); return wc.getPage(req); @@ -486,7 +486,7 @@ public void runScriptOnOfflineComputer() throws Exception { DumbSlave slave = j.createSlave(true); j.disconnectSlave(slave); - URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)"); + URL url = new URI(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)"); WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); diff --git a/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java b/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java index f4b11cb2eaee..2368b5bfb284 100644 --- a/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java +++ b/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java @@ -74,7 +74,7 @@ public void doBuildWithParameters_shouldFailWhenInvokingDisabledProject() throws FailingHttpStatusCodeException fex = assertThrows( "should fail when invoking disabled project", FailingHttpStatusCodeException.class, - () -> webClient.getPage(webClient.addCrumb(new WebRequest(new URL(j.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); + () -> webClient.getPage(webClient.addCrumb(new WebRequest(new URI(j.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); assertThat("Should fail with conflict", fex.getStatusCode(), is(409)); } @@ -87,7 +87,7 @@ public void doBuildQuietPeriodInSeconds() throws Exception { project.setQuietPeriod(projectQuietPeriodInSeconds); final JenkinsRule.WebClient webClient = j.createWebClient(); - webClient.getPage(webClient.addCrumb(new WebRequest(new URL(j.getURL(), project.getUrl() + "build"), HttpMethod.POST))); + webClient.getPage(webClient.addCrumb(new WebRequest(new URI(j.getURL(), project.getUrl() + "build"), HttpMethod.POST))); long triggerTime = System.currentTimeMillis(); Queue.Item item = Jenkins.get().getQueue().getItem(1); diff --git a/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java b/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java index 59f89e8f4977..533d9b5bed3f 100644 --- a/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java +++ b/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java @@ -95,7 +95,7 @@ public void callUsingApiTokenDoesNotRequireCSRFToken() throws Exception { } private void makeRequestAndVerify(String expected) throws IOException { - WebRequest req = new WebRequest(new URL(j.getURL(), "test-post")); + WebRequest req = new WebRequest(new URI(j.getURL(), "test-post")); req.setHttpMethod(HttpMethod.POST); req.setEncodingType(null); Page p = wc.getPage(req); diff --git a/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java b/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java index 4f9080b4ac9e..07c87f186fc5 100644 --- a/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java +++ b/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java @@ -151,7 +151,7 @@ public void adminsShouldBeUnableToChangeTokensByDefault() throws Exception { requirePOST.getWebResponse().getStatusCode()); wc.setThrowExceptionOnFailingStatusCode(true); - WebRequest request = new WebRequest(new URL(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl() + "/changeToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl() + "/changeToken"), HttpMethod.POST); HtmlPage res = wc.getPage(request); // TODO This nicer alternative requires https://github.com/jenkinsci/jenkins/pull/2268 or similar to work @@ -167,7 +167,7 @@ public void postWithUsernameAndTokenInBasicAuthHeader() throws Exception { User.getById("foo", true); WebClient wc = createClientForUser("foo"); - WebRequest wr = new WebRequest(new URL(j.getURL(), "job/bar/build"), HttpMethod.POST); + WebRequest wr = new WebRequest(new URI(j.getURL(), "job/bar/build"), HttpMethod.POST); assertEquals(HttpURLConnection.HTTP_CREATED, wc.getPage(wr).getWebResponse().getStatusCode()); @@ -417,7 +417,7 @@ private void revokeAllTokenUsingFilter(WebClient wc, User user, Predicate alerted.set(true)); - HtmlPage page = wc.getPage(new URL(wc.getContextPath() + ACTION_URL)); + HtmlPage page = wc.getPage(new URI(wc.getContextPath() + ACTION_URL)); String responseContent = page.getWebResponse().getContentAsString(); wc.waitForBackgroundJavaScript(5000); diff --git a/test/src/test/java/jenkins/security/Security637Test.java b/test/src/test/java/jenkins/security/Security637Test.java index 824a06d56001..3622bf53decd 100644 --- a/test/src/test/java/jenkins/security/Security637Test.java +++ b/test/src/test/java/jenkins/security/Security637Test.java @@ -64,10 +64,10 @@ public class Security637Test { public void urlSafeDeserialization_handler_inSameJVMRemotingContext() throws Throwable { sessions.then(j -> { DumbSlave slave = j.createOnlineSlave(null, new EnvVars("JAVA_TOOL_OPTIONS", "--add-opens=java.base/java.net=ALL-UNNAMED")); - String unsafeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("https://www.google.com/"))); + String unsafeHandlerClassName = slave.getChannel().call(new URIHandlerCallable(new URI("https://www.google.com/"))); assertThat(unsafeHandlerClassName, containsString("SafeURLStreamHandler")); - String safeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("file", null, -1, "", null))); + String safeHandlerClassName = slave.getChannel().call(new URIHandlerCallable(new URI("file", null, -1, "", null))); assertThat(safeHandlerClassName, not(containsString("SafeURLStreamHandler"))); }); } @@ -95,8 +95,8 @@ public void urlDnsEquivalence() throws Throwable { sessions.then(j -> { // due to the DNS resolution they are equal assertEquals( - new URL("https://jenkins.io"), - new URL("https://www.jenkins.io") + new URI("https://jenkins.io"), + new URI("https://www.jenkins.io") ); }); } @@ -110,9 +110,9 @@ public void urlSafeDeserialization_urlBuiltInAgent_inSameJVMRemotingContext() th // we bypass the standard equals method that resolve the hostname assertThat( - slave.getChannel().call(new URLBuilderCallable("https://jenkins.io")), + slave.getChannel().call(new URIBuilderCallable("https://jenkins.io")), not(equalTo( - slave.getChannel().call(new URLBuilderCallable("https://www.jenkins.io")) + slave.getChannel().call(new URIBuilderCallable("https://www.jenkins.io")) )) ); }); @@ -127,7 +127,7 @@ private static class URLBuilderCallable extends MasterToSlaveCallable { FreeStyleProject project = j.createFreeStyleProject("project-with-url"); - URLJobProperty URLJobProperty = new URLJobProperty( + URLJobProperty URLJobProperty = new URIJobProperty( // url to be wrapped - new URL("https://www.google.com/"), + new URI("https://www.google.com/"), // safe url, not required to be wrapped - new URL("https", null, -1, "", null) + new URI("https", null, -1, "", null) ); project.addProperty(URLJobProperty); diff --git a/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java b/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java index c0f6e95f0e57..6ca49a408150 100644 --- a/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java +++ b/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java @@ -30,7 +30,7 @@ public class SuspiciousRequestFilterTest { private WebResponse get(String path) throws Exception { return j.createWebClient() .withThrowExceptionOnFailingStatusCode(false) - .getPage(new WebRequest(new URL(j.getURL(), path))) + .getPage(new WebRequest(new URI(j.getURL(), path))) .getWebResponse(); } diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java index 4f0d8a4510a2..9f0e22cbc667 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java @@ -85,7 +85,7 @@ public void roundtripWithRestart() throws Throwable { WebClient wc = j.createWebClient().withBasicCredentials(u.getId()); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); request.setRequestParameters(List.of(new NameValuePair("newTokenName", TOKEN_NAME))); Page page = wc.getPage(request); @@ -165,7 +165,7 @@ private static void checkUserIsNotConnected(WebClient wc) throws Exception { private static void revokeToken(JenkinsRule j, WebClient wc, String login, String tokenUuid) throws Exception { WebRequest request = new WebRequest( - new URL(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), + new URI(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), HttpMethod.POST ); Page p = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java index 76bd3ffecfec..dbf51574c67d 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java @@ -73,7 +73,7 @@ public void roundtrip() throws Exception { final String TOKEN_NAME = "New Token Name"; - WebRequest request = new WebRequest(new URL(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); request.setRequestParameters(List.of(new NameValuePair("newTokenName", TOKEN_NAME))); Page page = wc.getPage(request); @@ -132,7 +132,7 @@ private void checkUserIsNotConnected(WebClient wc) throws Exception { private void revokeToken(WebClient wc, String login, String tokenUuid) throws Exception { WebRequest request = new WebRequest( - new URL(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), + new URI(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), HttpMethod.POST ); Page p = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java b/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java index d2a32423c18d..8e73e009e000 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java @@ -71,7 +71,7 @@ public void onWebCallUserSeedChange_listenerTriggered() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); WebRequest webRequest = new WebRequest( - new URL(j.getURL() + alice.getUrl() + "/" + userSeed.getDescriptor().getDescriptorUrl() + "/renewSessionSeed"), + new URI(j.getURL() + alice.getUrl() + "/" + userSeed.getDescriptor().getDescriptorUrl() + "/renewSessionSeed"), HttpMethod.POST ); diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java index e41158cbc8ba..c5f5fd44614f 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java @@ -95,7 +95,7 @@ public void renewSeedSavesTheChange() throws Throwable { private static void requestRenewSeedForUser(User user, JenkinsRule j) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); wc.getPage(request); } } diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java index 1c87791f193c..a885fb6fcb8e 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java @@ -300,7 +300,7 @@ private void assertUserNotConnected(JenkinsRule.WebClient wc, String notExpected private void requestRenewSeedForUser(User user) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); wc.getPage(request); } } diff --git a/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java b/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java index 042462ca75d6..0d24afc53635 100644 --- a/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java +++ b/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java @@ -295,7 +295,7 @@ public void testAnnotatedMethodOk_annotatedGet() throws Exception { @Test public void testAnnotatedMethodOk_annotatedPost() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedPost/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedPost/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(""); assertReachableWithSettings(settings); @@ -303,7 +303,7 @@ public void testAnnotatedMethodOk_annotatedPost() throws Exception { @Test public void testAnnotatedMethodOk_annotatedPut() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedPut/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedPut/")); settings.setHttpMethod(HttpMethod.PUT); settings.setRequestBody(""); assertReachableWithSettings(settings); @@ -316,7 +316,7 @@ public void testAnnotatedMethodOk_annotatedDelete() throws Exception { @Test public void testAnnotatedMethodOk_annotatedRequirePost() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedRequirePost/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedRequirePost/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(""); assertReachableWithSettings(settings); @@ -337,7 +337,7 @@ public void validateCrumb(StaplerRequest request, String submittedCrumb) { }); - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedJavaScriptScriptMethod/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedJavaScriptScriptMethod/")); settings.setAdditionalHeader("Content-Type", "application/x-stapler-method-invocation"); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(JSONArray.fromObject(Collections.emptyList()).toString()); @@ -351,7 +351,7 @@ public void testAnnotatedMethodOk_annotatedResponseSuccess() throws Exception { @Test public void testAnnotatedMethodOk_annotatedJsonResponse() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedJsonResponse/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedJsonResponse/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(JSONObject.fromObject(Collections.emptyMap()).toString()); Page page = wc.getPage(settings); @@ -360,7 +360,7 @@ public void testAnnotatedMethodOk_annotatedJsonResponse() throws Exception { @Test public void testAnnotatedMethodOk_annotatedLimitedTo() { - FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(new URL(j.getURL(), "testNewRulesOk/annotatedLimitedTo/"))); + FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(new URI(j.getURL(), "testNewRulesOk/annotatedLimitedTo/"))); assertEquals(500, e.getStatusCode()); assertTrue(e.getResponse().getContentAsString().contains("Needs to be in role")); } @@ -379,14 +379,14 @@ public void testAnnotatedParameterOk_annotatedParamAncestorInPath() throws Excep @Test public void testAnnotatedParameterOk_annotatedParamHeader() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamHeader/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedParamHeader/")); settings.setAdditionalHeader("test-header", "TestBrowser"); assertReachableWithSettings(settings); } @Test public void testAnnotatedParameterOk_annotatedParamJsonBody() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamJsonBody/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedParamJsonBody/")); // WebClient forces us to use POST to have the possibility to send requestBody settings.setHttpMethod(HttpMethod.POST); settings.setAdditionalHeader("Content-Type", "application/json"); @@ -396,7 +396,7 @@ public void testAnnotatedParameterOk_annotatedParamJsonBody() throws Exception { @Test public void testAnnotatedParameterOk_annotatedParamSubmittedForm() throws Exception { - WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamSubmittedForm/")); + WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedParamSubmittedForm/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestParameters(List.of( diff --git a/test/src/test/java/jenkins/security/stapler/Security400Test.java b/test/src/test/java/jenkins/security/stapler/Security400Test.java index e48faf5dbd8f..c80075191635 100644 --- a/test/src/test/java/jenkins/security/stapler/Security400Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security400Test.java @@ -231,7 +231,7 @@ public void ensureDoStopStillReachable() throws Exception { j.jenkins.setNumExecutors(1); { // preliminary test, calling the stop method without any executor results in 404 - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -256,7 +256,7 @@ public void ensureDoStopStillReachable() throws Exception { // we need to wait until the SemaphoreBuilder is running (blocked) otherwise the job is ABORTED not FAILURE j.waitForMessage(SemaphoredBuilder.START_MESSAGE, build); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -290,7 +290,7 @@ public void ensureDoStopBuildWorks() throws Exception { j.jenkins.setNumExecutors(1); { // preliminary test, calling stopBuild without any executor results in 404 - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -319,7 +319,7 @@ public void ensureDoStopBuildWorks() throws Exception { QueueTaskFuture futureBuild = p.scheduleBuild2(0); futureBuild.waitForStart(); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -340,7 +340,7 @@ public void ensureDoStopBuildWorks() throws Exception { FreeStyleBuild build = futureBuild.waitForStart(); String runExtId = URLEncoder.encode(build.getExternalizableId(), StandardCharsets.UTF_8); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -360,7 +360,7 @@ public void ensureDoStopBuildWorks() throws Exception { QueueTaskFuture futureBuild = p.scheduleBuild2(0); futureBuild.waitForStart(); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=whatever"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=whatever"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -564,7 +564,7 @@ public void ensureLogRecordManagerAccessibleOnlyByAdmin() throws Exception { assertEquals(404, wc.goTo("log/" + logNameForAdmin + "/autoCompleteLoggerName/?value=a", null).getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); - WebRequest request = new WebRequest(new URL(j.getURL() + "log/newLogRecorder/?name=" + logNameForAdmin), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "log/newLogRecorder/?name=" + logNameForAdmin), HttpMethod.POST); wc.getOptions().setRedirectEnabled(false); Page page = wc.getPage(request); @@ -588,7 +588,7 @@ public void ensureLogRecordManagerAccessibleOnlyByAdmin() throws Exception { assertEquals(403, wc.goTo("log/" + logNameForUser + "/autoCompleteLoggerName/?value=a", null).getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); - WebRequest request = new WebRequest(new URL(j.getURL() + "log/newLogRecorder/?name=" + logNameForUser), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "log/newLogRecorder/?name=" + logNameForUser), HttpMethod.POST); wc.getOptions().setRedirectEnabled(false); Page page = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/stapler/Security914Test.java b/test/src/test/java/jenkins/security/stapler/Security914Test.java index 5ade00a7678f..17851e68eb06 100644 --- a/test/src/test/java/jenkins/security/stapler/Security914Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security914Test.java @@ -54,7 +54,7 @@ public void cannotUseInvalidLocale_toTraverseFolder() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.xml")); + WebRequest request = new WebRequest(new URI(j.getURL() + "plugin/credentials/.xml")); // plugin deployed in: test\target\jenkins7375296945862059919tmp // rootDir is in : test\target\jenkinsTests.tmp\jenkins1274934531848159942test // j.jenkins.getRootDir().getName() = jenkins1274934531848159942test @@ -74,7 +74,7 @@ public void cannotUseInvalidLocale_toAnyFileInSystem() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.ini")); + WebRequest request = new WebRequest(new URI(j.getURL() + "plugin/credentials/.ini")); // ../ can be multiply to infinity, no impact, we just need to have enough to reach the root request.setAdditionalHeader("Accept-Language", "../../../../../../../../../../../../windows/win"); diff --git a/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java b/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java index 4c3f5d28b6a2..4d9e1bb5fd04 100644 --- a/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java +++ b/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java @@ -177,7 +177,7 @@ protected void assertFieldRequestWasNotBlocked() { protected void assertReachable(String url, HttpMethod method) throws IOException { try { - Page page = wc.getPage(new WebRequest(new URL(j.getURL(), url), method)); + Page page = wc.getPage(new WebRequest(new URI(j.getURL(), url), method)); assertEquals(200, page.getWebResponse().getStatusCode()); assertThat(page.getWebResponse().getContentAsString(), startsWith("ok")); @@ -202,7 +202,7 @@ protected void assertReachableWithSettings(WebRequest request) throws IOExceptio protected void assertReachableWithoutOk(String url) throws IOException { try { - Page page = wc.getPage(new URL(j.getURL(), url)); + Page page = wc.getPage(new URI(j.getURL(), url)); assertEquals(200, page.getWebResponse().getStatusCode()); } catch (FailingHttpStatusCodeException e) { throw new AssertionError("Url " + url + " should be reachable, received " + e.getMessage() + " (" + e.getStatusCode() + ") instead.", e); @@ -210,7 +210,7 @@ protected void assertReachableWithoutOk(String url) throws IOException { } protected void assertNotReachable(String url) throws IOException { - FailingHttpStatusCodeException e = assertThrows("Url " + url + " is reachable but should not be, a not-found error is expected", FailingHttpStatusCodeException.class, () -> wc.getPage(new URL(j.getURL(), url))); + FailingHttpStatusCodeException e = assertThrows("Url " + url + " is reachable but should not be, a not-found error is expected", FailingHttpStatusCodeException.class, () -> wc.getPage(new URI(j.getURL(), url))); assertEquals("Url " + url + " returns an error different from 404", 404, e.getResponse().getStatusCode()); } } diff --git a/war/src/main/java/executable/Main.java b/war/src/main/java/executable/Main.java index 1a537e46825e..3ae4c52d5bfe 100644 --- a/war/src/main/java/executable/Main.java +++ b/war/src/main/java/executable/Main.java @@ -278,7 +278,7 @@ public static void main(String[] args) throws IllegalAccessException { // locate the Winstone launcher ClassLoader cl; try { - cl = new URLClassLoader(new URL[] {tmpJar.toURI().toURL()}); + cl = new URIClassLoader(new URI[] {tmpJar.toURI().toURL()}); } catch (MalformedURLException e) { throw new UncheckedIOException(e); } From ddc5115da2550262655147b36f6a673b19a81e63 Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Tue, 19 Sep 2023 01:09:51 +0530 Subject: [PATCH 04/11] Revert "replaced 'new URL' to 'new URI' per Java 11 target codebase" This reverts commit aeef4c1e4bb57a4832dbe368920aa0716a3f68e7. --- cli/src/main/java/hudson/cli/CLI.java | 4 +- .../java/hudson/cli/FullDuplexHttpStream.java | 2 +- cli/src/main/java/hudson/cli/SSHCLI.java | 2 +- .../java/hudson/ClassicPluginStrategy.java | 4 +- core/src/main/java/hudson/FilePath.java | 4 +- core/src/main/java/hudson/Functions.java | 2 +- core/src/main/java/hudson/Main.java | 14 ++-- core/src/main/java/hudson/Plugin.java | 2 +- core/src/main/java/hudson/PluginManager.java | 8 +- core/src/main/java/hudson/PluginWrapper.java | 2 +- .../main/java/hudson/ProxyConfiguration.java | 2 +- .../java/hudson/TcpSlaveAgentListener.java | 2 +- core/src/main/java/hudson/WebAppMain.java | 2 +- .../java/hudson/cli/InstallPluginCommand.java | 2 +- .../java/hudson/console/UrlAnnotator.java | 2 +- .../java/hudson/model/DownloadService.java | 2 +- .../main/java/hudson/model/UpdateCenter.java | 14 ++-- .../main/java/hudson/model/UpdateSite.java | 2 +- .../java/hudson/scm/RepositoryBrowser.java | 2 +- .../tools/DownloadFromUrlInstaller.java | 2 +- .../hudson/tools/ZipExtractionInstaller.java | 2 +- .../java/hudson/util/FormFieldValidator.java | 2 +- .../java/jenkins/install/SetupWizard.java | 2 +- .../validator/routines/UrlValidator.java | 6 +- .../security/ResourceDomainConfiguration.java | 10 +-- core/src/test/java/hudson/FilePathTest.java | 4 +- .../test/java/hudson/PluginManagerTest.java | 2 +- .../test/java/hudson/PluginWrapperTest.java | 2 +- .../java/hudson/console/UrlAnnotatorTest.java | 2 +- .../jenkins/model/JenkinsGetRootUrlTest.java | 2 +- .../routines/DomainValidatorTest.java | 2 +- .../validator/routines/UrlValidatorTest.java | 78 +++++++++---------- .../test/java/jenkins/util/UrlHelperTest.java | 2 +- .../test/java/hudson/PluginManagerTest.java | 2 +- .../hudson/TcpSlaveAgentListenerTest.java | 4 +- .../bugs/JnlpAccessWithSecuredHudsonTest.java | 2 +- .../hudson/console/ConsoleAnnotatorTest.java | 2 +- .../java/hudson/console/UrlAnnotatorTest.java | 2 +- .../HudsonHomeDiskUsageMonitorTest.java | 6 +- .../ReverseProxySetupMonitorTest.java | 26 +++---- .../test/java/hudson/jobs/CreateItemTest.java | 8 +- .../hudson/markup/MarkupFormatterTest.java | 2 +- .../hudson/model/AbstractProjectTest.java | 12 +-- .../model/BuildAuthorizationTokenTest.java | 12 +-- .../model/DirectlyModifiableViewTest.java | 2 +- .../model/DirectoryBrowserSupportTest.java | 4 +- .../java/hudson/model/FingerprintTest.java | 12 +-- .../test/java/hudson/model/HudsonTest.java | 2 +- .../src/test/java/hudson/model/ItemsTest.java | 8 +- .../test/java/hudson/model/ProjectTest.java | 2 +- .../src/test/java/hudson/model/QueueTest.java | 2 +- .../src/test/java/hudson/model/SlaveTest.java | 2 +- .../java/hudson/model/UpdateCenterTest.java | 2 +- .../java/hudson/model/UpdateSiteTest.java | 12 +-- .../java/hudson/model/UserRestartTest.java | 4 +- .../HudsonPrivateSecurityRealmTest.java | 2 +- .../security/csrf/CrumbExclusionTest.java | 4 +- .../security/csrf/DefaultCrumbIssuerTest.java | 2 +- .../tools/ZipExtractionInstallerTest.java | 2 +- .../util/RobustReflectionConverterTest.java | 4 +- .../java/jenkins/install/SetupWizardTest.java | 6 +- .../java/jenkins/model/AssetManagerTest.java | 2 +- .../test/java/jenkins/model/JenkinsTest.java | 8 +- .../model/ParameterizedJobMixInTest.java | 4 +- .../security/ApiCrumbExclusionTest.java | 2 +- .../security/ApiTokenPropertyTest.java | 10 +-- .../BasicHeaderApiTokenAuthenticatorTest.java | 12 +-- .../security/BasicHeaderProcessorTest.java | 2 +- .../jenkins/security/ResourceDomainTest.java | 4 +- .../jenkins/security/Security177Test.java | 6 +- .../jenkins/security/Security2278Test.java | 4 +- .../jenkins/security/Security2761Test.java | 2 +- .../jenkins/security/Security637Test.java | 28 +++---- .../security/SuspiciousRequestFilterTest.java | 2 +- .../apitoken/ApiTokenStatsRestartTest.java | 4 +- .../security/apitoken/ApiTokenStatsTest.java | 4 +- .../seed/UserSeedChangeListenerTest.java | 2 +- .../seed/UserSeedPropertyRestartTest.java | 2 +- .../security/seed/UserSeedPropertyTest.java | 2 +- .../security/stapler/DoActionFilterTest.java | 18 ++--- .../security/stapler/Security400Test.java | 16 ++-- .../security/stapler/Security914Test.java | 4 +- .../security/stapler/StaplerAbstractTest.java | 6 +- war/src/main/java/executable/Main.java | 2 +- 84 files changed, 244 insertions(+), 244 deletions(-) diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 9e5d9cabdf7f..9aee43f6f9a0 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -306,7 +306,7 @@ public boolean verify(String s, SSLSession sslSession) { } CLIConnectionFactory factory = new CLIConnectionFactory(); - String userInfo = new URI(url).getUserInfo(); + String userInfo = new URL(url).getUserInfo(); if (userInfo != null) { factory = factory.basicAuth(userInfo); } else if (auth != null) { @@ -388,7 +388,7 @@ public void close() throws IOException { private static int plainHttpConnection(String url, List args, CLIConnectionFactory factory) throws IOException, InterruptedException { LOGGER.log(FINE, "Trying to connect to {0} via plain protocol over HTTP", url); - FullDuplexHttpStream streams = new FullDuplexHttpStream(new URI(url), "cli?remoting=false", factory.authorization); + FullDuplexHttpStream streams = new FullDuplexHttpStream(new URL(url), "cli?remoting=false", factory.authorization); try (ClientSideImpl connection = new ClientSideImpl(new PlainCLIProtocol.FramedOutput(streams.getOutputStream()))) { connection.start(args); InputStream is = streams.getInputStream(); diff --git a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java index 509bc1ce4952..3b4b4d25342f 100644 --- a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java +++ b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java @@ -55,7 +55,7 @@ public FullDuplexHttpStream(URL base, String relativeTarget, String authorizatio this.base = tryToResolveRedirects(base, authorization); - URL target = new URI(this.base, relativeTarget); + URL target = new URL(this.base, relativeTarget); UUID uuid = UUID.randomUUID(); // so that the server can correlate those two connections diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 01455dfc33a5..3d6ea7c42530 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -62,7 +62,7 @@ class SSHCLI { static int sshConnection(String jenkinsUrl, String user, List args, PrivateKeyProvider provider, final boolean strictHostKey) throws IOException { Logger.getLogger(SecurityUtils.class.getName()).setLevel(Level.WARNING); // suppress: BouncyCastle not registered, using the default JCE provider - URL url = new URI(jenkinsUrl + "login"); + URL url = new URL(jenkinsUrl + "login"); URLConnection conn = openConnection(url); CLI.verifyJenkinsConnection(conn); String endpointDescription = conn.getHeaderField("X-SSH-Endpoint"); diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index ffeb0e2c8203..c16fc93e1aa9 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -294,9 +294,9 @@ protected ClassLoader createClassLoader(List paths, ClassLoader parent, At } URLClassLoader2 classLoader; if (usePluginFirstClassLoader) { - classLoader = new PluginFirstClassLoader2(urls.toArray(new URI[0]), parent); + classLoader = new PluginFirstClassLoader2(urls.toArray(new URL[0]), parent); } else { - classLoader = new URIClassLoader2(urls.toArray(new URI[0]), parent); + classLoader = new URLClassLoader2(urls.toArray(new URL[0]), parent); } return classLoader; } diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index 15fc757d4f6c..cdc057ef9c54 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -3333,12 +3333,12 @@ private int findSeparator(String pattern) { } } - private static final UrlFactory DEFAULT_URL_FACTORY = new URIFactory(); + private static final UrlFactory DEFAULT_URL_FACTORY = new UrlFactory(); @Restricted(NoExternalUse.class) static class UrlFactory { public URL newURL(String location) throws MalformedURLException { - return new URI(location); + return new URL(location); } } diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 3ac59d306ab1..7f3411406780 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1939,7 +1939,7 @@ public String getServerName() { String url = Jenkins.get().getRootUrl(); try { if (url != null) { - String host = new URI(url).getHost(); + String host = new URL(url).getHost(); if (host != null) return host; } diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java index 68f65d948377..625fef0c52ee 100644 --- a/core/src/main/java/hudson/Main.java +++ b/core/src/main/java/hudson/Main.java @@ -99,11 +99,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 URI(home).getUserInfo(); + String auth = new URL(home).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 URI(home)); + HttpURLConnection con = open(new URL(home)); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if (con.getResponseCode() != 200 @@ -113,10 +113,10 @@ public static int remotePost(String[] args) throws Exception { } } - URL jobURL = new URI(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/"); + URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/"); { // check if the job name is correct - HttpURLConnection con = open(new URI(jobURL, "acceptBuildResult")); + HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult")); if (auth != null) con.setRequestProperty("Authorization", auth); con.connect(); if (con.getResponseCode() != 200) { @@ -128,7 +128,7 @@ 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 URI(home + + HttpURLConnection con = open(new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'")); if (auth != null) con.setRequestProperty("Authorization", auth); String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8"); @@ -165,7 +165,7 @@ public static int remotePost(String[] args) throws Exception { throw new IOException(e); } - URL location = new URI(jobURL, "postBuildResult"); + URL location = new URL(jobURL, "postBuildResult"); while (true) { try { // start a remote connection @@ -193,7 +193,7 @@ public static int remotePost(String[] args) throws Exception { } catch (HttpRetryException e) { if (e.getLocation() != null) { // retry with the new location - location = new URI(e.getLocation()); + location = new URL(e.getLocation()); continue; } // otherwise failed for reasons beyond us. diff --git a/core/src/main/java/hudson/Plugin.java b/core/src/main/java/hudson/Plugin.java index 6fd540ed7966..41eafeabf545 100644 --- a/core/src/main/java/hudson/Plugin.java +++ b/core/src/main/java/hudson/Plugin.java @@ -251,7 +251,7 @@ public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOExceptio long expires = staticLink ? TimeUnit.DAYS.toMillis(365) : -1; // use serveLocalizedFile to support automatic locale selection - rsp.serveLocalizedFile(req, new URI(wrapper.baseResourceURL, '.' + path), expires); + rsp.serveLocalizedFile(req, new URL(wrapper.baseResourceURL, '.' + path), expires); } // diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index e2a456a08b8d..5d64485cfa1b 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -1097,7 +1097,7 @@ protected void copyBundledPlugin(URL src, String fileName) throws IOException { } /*package*/ static @CheckForNull Manifest parsePluginManifest(URL bundledJpi) { - try (URLClassLoader cl = new URIClassLoader(new URI[]{bundledJpi})) { + try (URLClassLoader cl = new URLClassLoader(new URL[]{bundledJpi})) { InputStream in = null; try { URL res = cl.findResource(PluginWrapper.MANIFEST_FILENAME); @@ -1848,7 +1848,7 @@ static class UrlPluginCopier implements PluginCopier { @Override public void copy(File target) throws Exception { - try (InputStream input = ProxyConfiguration.getInputStream(new URI(url))) { + try (InputStream input = ProxyConfiguration.getInputStream(new URL(url))) { Files.copy(input, target.toPath()); } } @@ -1875,7 +1875,7 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl if (StringUtils.isNotBlank(items.get(1).getString())) { // this is a URL deployment fileName = items.get(1).getString(); - copier = new URIPluginCopier(fileName); + copier = new UrlPluginCopier(fileName); } else { // this is a file upload FileItem fileItem = items.get(0); @@ -1962,7 +1962,7 @@ 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 URI(value); + URL url = new URL(value); if (!url.getProtocol().startsWith("http")) { return FormValidation.error(Messages.PluginManager_invalidUrl()); } diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java index 058ac74f6ead..2161e501089f 100644 --- a/core/src/main/java/hudson/PluginWrapper.java +++ b/core/src/main/java/hudson/PluginWrapper.java @@ -911,7 +911,7 @@ public String getPluginClass() { public boolean hasLicensesXml() { try { - new URI(baseResourceURL, "WEB-INF/licenses.xml").openStream().close(); + new URL(baseResourceURL, "WEB-INF/licenses.xml").openStream().close(); return true; } catch (IOException e) { return false; diff --git a/core/src/main/java/hudson/ProxyConfiguration.java b/core/src/main/java/hudson/ProxyConfiguration.java index 7ed7c1819f36..a165fa6e3151 100644 --- a/core/src/main/java/hudson/ProxyConfiguration.java +++ b/core/src/main/java/hudson/ProxyConfiguration.java @@ -458,7 +458,7 @@ private void jenkins48775workaround(Proxy proxy, URL url) { HttpURLConnection preAuth = null; try { // We do not care if there is anything at this URL, all we care is that it is using the proxy - preAuth = (HttpURLConnection) new URI("http", url.getHost(), -1, "/").openConnection(proxy); + preAuth = (HttpURLConnection) new URL("http", url.getHost(), -1, "/").openConnection(proxy); preAuth.setRequestMethod("HEAD"); preAuth.connect(); } catch (IOException e) { diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index d07398c7af1f..3936071de2ef 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -135,7 +135,7 @@ public String getAdvertisedHost() { return CLI_HOST_NAME; } try { - return new URI(Jenkins.get().getRootUrl()).getHost(); + return new URL(Jenkins.get().getRootUrl()).getHost(); } catch (MalformedURLException e) { throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e); } diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java index ffecc8e7ef6a..99603ac1e411 100644 --- a/core/src/main/java/hudson/WebAppMain.java +++ b/core/src/main/java/hudson/WebAppMain.java @@ -170,7 +170,7 @@ public Locale get() { JVM jvm; try { jvm = new JVM(); - new URIClassLoader(new URI[0], getClass().getClassLoader()); + new URLClassLoader(new URL[0], getClass().getClassLoader()); } catch (SecurityException e) { throw new InsufficientPermissionDetected(e); } diff --git a/core/src/main/java/hudson/cli/InstallPluginCommand.java b/core/src/main/java/hudson/cli/InstallPluginCommand.java index b7a41974ff18..cc9d3b59f91d 100644 --- a/core/src/main/java/hudson/cli/InstallPluginCommand.java +++ b/core/src/main/java/hudson/cli/InstallPluginCommand.java @@ -104,7 +104,7 @@ protected int run() throws Exception { // is this an URL? try { - URL u = new URI(source); + URL u = new URL(source); stdout.println(Messages.InstallPluginCommand_InstallingPluginFromUrl(u)); File f = getTmpFile(); FileUtils.copyURLToFile(u, f); // TODO JENKINS-58248 proxy diff --git a/core/src/main/java/hudson/console/UrlAnnotator.java b/core/src/main/java/hudson/console/UrlAnnotator.java index f9c31915c9ac..191c65544456 100644 --- a/core/src/main/java/hudson/console/UrlAnnotator.java +++ b/core/src/main/java/hudson/console/UrlAnnotator.java @@ -16,7 +16,7 @@ public class UrlAnnotator extends ConsoleAnnotatorFactory { @Override public ConsoleAnnotator newInstance(Object context) { - return new URIConsoleAnnotator(); + return new UrlConsoleAnnotator(); } private static class UrlConsoleAnnotator extends ConsoleAnnotator { diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index 2010e0d11cbb..b9a5610c4e35 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -388,7 +388,7 @@ public FormValidation updateNow() throws IOException { } String jsonString; try { - jsonString = loadJSONHTML(new URI(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))); + jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e); diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 871ea99400df..7ea06f20191e 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -1207,7 +1207,7 @@ public UpdateCenterConfiguration() { * @throws IOException if a connection can't be established */ public void checkConnection(ConnectionCheckJob job, String connectionCheckUrl) throws IOException { - testConnection(new URI(connectionCheckUrl)); + testConnection(new URL(connectionCheckUrl)); } /** @@ -1230,9 +1230,9 @@ public void checkUpdateCenter(ConnectionCheckJob job, String updateCenterUrl) th static URL toUpdateCenterCheckUrl(String updateCenterUrl) throws MalformedURLException { URL url; if (updateCenterUrl.startsWith("http://") || updateCenterUrl.startsWith("https://")) { - url = new URI(updateCenterUrl + (updateCenterUrl.indexOf('?') == -1 ? "?uctest" : "&uctest")); + url = new URL(updateCenterUrl + (updateCenterUrl.indexOf('?') == -1 ? "?uctest" : "&uctest")); } else { - url = new URI(updateCenterUrl); + url = new URL(updateCenterUrl); } return url; } @@ -2193,7 +2193,7 @@ public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth, bool @Override protected URL getURL() throws MalformedURLException { - return new URI(plugin.url); + return new URL(plugin.url); } @Override @@ -2422,7 +2422,7 @@ public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) { @Override protected URL getURL() throws MalformedURLException { - return new URI(plugin.url); + return new URL(plugin.url); } @Override @@ -2517,7 +2517,7 @@ protected URL getURL() throws MalformedURLException { if (site == null) { throw new MalformedURLException("no update site defined"); } - return new URI(site.getData().core.url); + return new URL(site.getData().core.url); } @Override @@ -2564,7 +2564,7 @@ protected URL getURL() throws MalformedURLException { if (site == null) { throw new MalformedURLException("no update site defined"); } - return new URI(site.getData().core.url); + return new URL(site.getData().core.url); } @Override diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index acddfa8f2a91..1b5b734c7be6 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -215,7 +215,7 @@ public long getDataTimestamp() { @Restricted(NoExternalUse.class) public @NonNull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException { - return updateData(DownloadService.loadJSON(new URI(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck); + return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck); } private FormValidation updateData(String json, boolean signatureCheck) diff --git a/core/src/main/java/hudson/scm/RepositoryBrowser.java b/core/src/main/java/hudson/scm/RepositoryBrowser.java index 7844792ad207..05b095b02bce 100644 --- a/core/src/main/java/hudson/scm/RepositoryBrowser.java +++ b/core/src/main/java/hudson/scm/RepositoryBrowser.java @@ -88,7 +88,7 @@ protected static URL normalizeToEndWithSlash(URL url) { String q = url.getQuery(); q = q != null ? '?' + q : ""; try { - return new URI(url, url.getPath() + '/' + q); + return new URL(url, url.getPath() + '/' + q); } catch (MalformedURLException e) { // impossible throw new Error(e); diff --git a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java index 264c7e0c0fea..5d7f4c0c024f 100644 --- a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java +++ b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java @@ -74,7 +74,7 @@ public FilePath performInstallation(ToolInstallation tool, Node node, TaskListen if (isUpToDate(expected, inst)) return expected; - if (expected.installIfNecessaryFrom(new URI(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { + if (expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { expected.child(".timestamp").delete(); // we don't use the timestamp FilePath base = findPullUpDirectory(expected); if (base != null && base != expected) diff --git a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java index 39c54b3d90f8..1e1c171f6a95 100644 --- a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java +++ b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java @@ -83,7 +83,7 @@ public String getSubdir() { @Override public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath dir = preferredLocation(tool, node); - if (dir.installIfNecessaryFrom(new URI(url), log, "Unpacking " + url + " to " + dir + " on " + node.getDisplayName())) { + if (dir.installIfNecessaryFrom(new URL(url), log, "Unpacking " + url + " to " + dir + " on " + node.getDisplayName())) { dir.act(new ChmodRecAPlusX()); } if (subdir == null) { diff --git a/core/src/main/java/hudson/util/FormFieldValidator.java b/core/src/main/java/hudson/util/FormFieldValidator.java index edec7e5882e1..9bf1287b9e01 100644 --- a/core/src/main/java/hudson/util/FormFieldValidator.java +++ b/core/src/main/java/hudson/util/FormFieldValidator.java @@ -335,7 +335,7 @@ protected void check() throws IOException, ServletException { if (!value.endsWith("/")) value += '/'; try { - URL url = new URI(value); + URL url = new URL(value); HttpURLConnection con = openConnection(url); con.connect(); if (con.getResponseCode() != 200 diff --git a/core/src/main/java/jenkins/install/SetupWizard.java b/core/src/main/java/jenkins/install/SetupWizard.java index 789d006d4020..126aaf0d11bb 100644 --- a/core/src/main/java/jenkins/install/SetupWizard.java +++ b/core/src/main/java/jenkins/install/SetupWizard.java @@ -561,7 +561,7 @@ public JSONArray getPlatformPluginUpdates() { suggestedPluginUrl = suggestedPluginUrl + (suggestedPluginUrl.contains("?") ? "&" : "?") + "version=" + version; } try { - URLConnection connection = ProxyConfiguration.open(new URI(suggestedPluginUrl)); + URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl)); try { String initialPluginJson = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8); diff --git a/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java b/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java index 2f2e50e1dd16..40c0eae1d13f 100644 --- a/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java +++ b/core/src/main/java/jenkins/org/apache/commons/validator/routines/UrlValidator.java @@ -50,7 +50,7 @@ * Construct a UrlValidator with valid schemes of "http", and "https". * * String[] schemes = {"http","https"}. - * UrlValidator urlValidator = new URIValidator(schemes); + * UrlValidator urlValidator = new UrlValidator(schemes); * if (urlValidator.isValid("ftp://foo.bar.com/")) { * System.out.println("url is valid"); * } else { @@ -60,7 +60,7 @@ * prints "url is invalid" * If instead the default constructor is used. * - * UrlValidator urlValidator = new URIValidator(); + * UrlValidator urlValidator = new UrlValidator(); * if (urlValidator.isValid("ftp://foo.bar.com/")) { * System.out.println("url is valid"); * } else { @@ -179,7 +179,7 @@ public class UrlValidator implements Serializable { /** * Singleton instance of this class with default schemes and options. */ - private static final UrlValidator DEFAULT_URL_VALIDATOR = new URIValidator(); + private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator(); /** * Returns the singleton instance of this class with default schemes and options. diff --git a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java index 96b1bbd4764b..f5465ca4b61e 100644 --- a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java +++ b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java @@ -112,14 +112,14 @@ private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlin URL resourceRootUrl; try { - resourceRootUrl = new URI(resourceRootUrlString); + resourceRootUrl = new URL(resourceRootUrlString); } catch (MalformedURLException ex) { return FormValidation.error(Messages.ResourceDomainConfiguration_Invalid()); } String resourceRootUrlHost = resourceRootUrl.getHost(); try { - String jenkinsRootUrlHost = new URI(jenkinsRootUrlString).getHost(); + String jenkinsRootUrlHost = new URL(jenkinsRootUrlString).getHost(); if (jenkinsRootUrlHost.equals(resourceRootUrlHost)) { // We do not allow the same host for Jenkins and resource root URLs even if there's some other difference. // This is a conservative choice and prohibits same host/different proto/different port/different path: @@ -147,7 +147,7 @@ private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlin // Send a request to /instance-identity/ at the resource root URL and check whether it is this Jenkins try { - URLConnection urlConnection = new URI(resourceRootUrlString + "instance-identity/").openConnection(); + URLConnection urlConnection = new URL(resourceRootUrlString + "instance-identity/").openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; int responseCode = httpURLConnection.getResponseCode(); @@ -222,7 +222,7 @@ public static boolean isResourceRequest(HttpServletRequest req) { } String resourceRootUrl = get().getUrl(); try { - URL url = new URI(resourceRootUrl); + URL url = new URL(resourceRootUrl); String resourceRootHost = url.getHost(); if (!resourceRootHost.equalsIgnoreCase(req.getServerName())) { @@ -241,7 +241,7 @@ public static boolean isResourceRequest(HttpServletRequest req) { return false; } } catch (MalformedURLException ex) { - // the URL here cannot be so broken that we cannot call `new URI(String)` on it... + // the URL here cannot be so broken that we cannot call `new URL(String)` on it... return false; } return true; diff --git a/core/src/test/java/hudson/FilePathTest.java b/core/src/test/java/hudson/FilePathTest.java index 10be262595e6..fe152a25ba49 100644 --- a/core/src/test/java/hudson/FilePathTest.java +++ b/core/src/test/java/hudson/FilePathTest.java @@ -672,13 +672,13 @@ private static void assertValidateAntFileMask(String expected, FilePath d, Strin private URL someUrlToZipFile(final URLConnection con) throws IOException { - final URLStreamHandler urlHandler = new URIStreamHandler() { + final URLStreamHandler urlHandler = new URLStreamHandler() { @Override protected URLConnection openConnection(URL u) { return con; } }; - return new URI("http", "some-host", 0, "/some-path.zip", urlHandler); + return new URL("http", "some-host", 0, "/some-path.zip", urlHandler); } private InputStream someZippedContent() throws IOException { diff --git a/core/src/test/java/hudson/PluginManagerTest.java b/core/src/test/java/hudson/PluginManagerTest.java index 8d10f5f0ea24..580808c8d56d 100644 --- a/core/src/test/java/hudson/PluginManagerTest.java +++ b/core/src/test/java/hudson/PluginManagerTest.java @@ -206,7 +206,7 @@ private File createHpiWithManifest() throws IOException { private URL toManifestUrl(File jarFile) throws MalformedURLException { final String manifestPath = "META-INF/MANIFEST.MF"; - return new URI("jar:" + jarFile.toURI().toURL() + "!/" + manifestPath); + return new URL("jar:" + jarFile.toURI().toURL() + "!/" + manifestPath); } private static class FormValidationMatcher extends TypeSafeDiagnosingMatcher { diff --git a/core/src/test/java/hudson/PluginWrapperTest.java b/core/src/test/java/hudson/PluginWrapperTest.java index 45f758d8965a..f12a8af7bdc3 100644 --- a/core/src/test/java/hudson/PluginWrapperTest.java +++ b/core/src/test/java/hudson/PluginWrapperTest.java @@ -105,7 +105,7 @@ public void dependencyFailedToLoad() { @Issue("JENKINS-66563") @Test public void insertJarsIntoClassPath() throws Exception { - try (URLClassLoader2 cl = new URIClassLoader2(new URI[0])) { + try (URLClassLoader2 cl = new URLClassLoader2(new URL[0])) { assertInjectingJarsWorks(cl); } } diff --git a/core/src/test/java/hudson/console/UrlAnnotatorTest.java b/core/src/test/java/hudson/console/UrlAnnotatorTest.java index 8788dc3b1f8b..d05080ff899e 100644 --- a/core/src/test/java/hudson/console/UrlAnnotatorTest.java +++ b/core/src/test/java/hudson/console/UrlAnnotatorTest.java @@ -35,7 +35,7 @@ */ public class UrlAnnotatorTest { - private ConsoleAnnotator ca = new URIAnnotator().newInstance(null); + private ConsoleAnnotator ca = new UrlAnnotator().newInstance(null); @Test public void testAnnotate() { diff --git a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java index 1acccd5206ed..620616a15081 100644 --- a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java +++ b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java @@ -247,7 +247,7 @@ private URL getUrl(final String realUrl) { try { - return new URI(realUrl); + return new URL(realUrl); } catch (Exception ex) { throw new RuntimeException(ex); diff --git a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java index 17f1ff2a7e62..3e1631692c6d 100644 --- a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java +++ b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java @@ -502,7 +502,7 @@ private static long download(File f, String tldurl, long timestamp) throws IOExc } else { modTime = 0; } - HttpURLConnection hc = (HttpURLConnection) new URI(tldurl).openConnection(); + HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection(); if (modTime > 0) { SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); //Sun, 06 Nov 1994 08:49:37 GMT String since = sdf.format(new Date(modTime)); diff --git a/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java b/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java index c0945ff42dbe..97cb3f7c54e4 100644 --- a/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java +++ b/core/src/test/java/jenkins/org/apache/commons/validator/routines/UrlValidatorTest.java @@ -63,8 +63,8 @@ public void testIsValidScheme() { if (printStatus) { System.out.print("\n testIsValidScheme() "); } - //UrlValidator urlVal = new URIValidator(schemes,false,false,false); - UrlValidator urlVal = new URIValidator(schemes, 0); + //UrlValidator urlVal = new UrlValidator(schemes,false,false,false); + UrlValidator urlVal = new UrlValidator(schemes, 0); for (ResultPair testPair : testScheme) { boolean result = urlVal.isValidScheme(testPair.item); assertEquals(testPair.item, testPair.valid, result); @@ -89,7 +89,7 @@ public void testIsValidScheme() { * @param testObjects Used to create a url. */ public void testIsValid(Object[] testObjects, long options) { - UrlValidator urlVal = new URIValidator(null, null, options); + UrlValidator urlVal = new UrlValidator(null, null, options); assertTrue(urlVal.isValid("http://www.google.com")); assertTrue(urlVal.isValid("http://www.google.com/")); int statusPerLine = 60; @@ -134,20 +134,20 @@ public void testIsValid(Object[] testObjects, long options) { @Test public void testValidator202() { String[] schemes = {"http", "https"}; - UrlValidator urlValidator = new URIValidator(schemes, UrlValidator.NO_FRAGMENTS); + UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertTrue(urlValidator.isValid("http://l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.org")); } @Test public void testValidator204() { String[] schemes = {"http", "https"}; - UrlValidator urlValidator = new URIValidator(schemes); + UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); } @Test public void testValidator218() { - UrlValidator validator = new URIValidator(UrlValidator.ALLOW_2_SLASHES); + UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue("parentheses should be valid in URLs", validator.isValid("http://somewhere.com/pathxyz/file(1).html")); } @@ -159,7 +159,7 @@ public void testValidator235() { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("http://xn--d1abbgf6aiiy.xn--p1ai")); assertTrue("президент.рф should validate", validator.isValid("http://президент.рф")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("http://www.b\u00fccher.ch")); @@ -171,7 +171,7 @@ public void testValidator235() { @Test public void testValidator248() { RegexValidator regex = new RegexValidator(new String[] {"localhost", ".*\\.my-testing"}); - UrlValidator validator = new URIValidator(regex, 0); + UrlValidator validator = new UrlValidator(regex, 0); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); @@ -187,7 +187,7 @@ public void testValidator248() { validator.isValid("http://www.apache.org/test/index.html")); // Now check using options - validator = new URIValidator(UrlValidator.ALLOW_LOCAL_URLS); + validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); @@ -201,7 +201,7 @@ public void testValidator248() { @Test public void testValidator288() { - UrlValidator validator = new URIValidator(UrlValidator.ALLOW_LOCAL_URLS); + UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("hostname should validate", validator.isValid("http://hostname")); @@ -222,7 +222,7 @@ public void testValidator288() { validator.isValid("http://www.apache.org/test/index.html")); // Turn it off, and check - validator = new URIValidator(0); + validator = new UrlValidator(0); assertFalse("hostname should no longer validate", validator.isValid("http://hostname")); @@ -237,7 +237,7 @@ public void testValidator288() { @Test public void testValidator276() { // file:// isn't allowed by default - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); @@ -259,7 +259,7 @@ public void testValidator276() { // Turn it on, and check // Note - we need to enable local urls when working with file: - validator = new URIValidator(new String[] {"http", "file"}, UrlValidator.ALLOW_LOCAL_URLS); + validator = new UrlValidator(new String[] {"http", "file"}, UrlValidator.ALLOW_LOCAL_URLS); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); @@ -290,24 +290,24 @@ public void testValidator276() { @Test public void testValidator391OK() { String[] schemes = {"file"}; - UrlValidator urlValidator = new URIValidator(schemes); + UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("file:///C:/path/to/dir/")); } @Test public void testValidator391FAILS() { String[] schemes = {"file"}; - UrlValidator urlValidator = new URIValidator(schemes); + UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("file:/C:/path/to/dir/")); } @Test public void testValidator309() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); - urlValidator = new URIValidator(new String[] {"HTTP", "HTTPS"}); + urlValidator = new UrlValidator(new String[] {"HTTP", "HTTPS"}); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); @@ -315,7 +315,7 @@ public void testValidator309() { @Test public void testValidator339() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://www.cnn.com./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://www.cnn.com../")); // doubly dotty @@ -325,7 +325,7 @@ public void testValidator339() { @Test public void testValidator339IDN() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://президент.рф./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://президент.рф..../")); // very dotty @@ -335,14 +335,14 @@ public void testValidator339IDN() { @Test public void testValidator342() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks/")); assertTrue(urlValidator.isValid("http://example.rocks")); } @Test public void testValidator411() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks:/")); assertTrue(urlValidator.isValid("http://example.rocks:0/")); assertTrue(urlValidator.isValid("http://example.rocks:65535/")); @@ -353,32 +353,32 @@ public void testValidator411() { @Test public void testValidator464() { String[] schemes = {"file"}; - UrlValidator urlValidator = new URIValidator(schemes); + UrlValidator urlValidator = new UrlValidator(schemes); String fileNAK = "file://bad ^ domain.com/label/test"; assertFalse(fileNAK, urlValidator.isValid(fileNAK)); } @Test public void testValidator452() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html")); } @Test(expected = IllegalArgumentException.class) public void testValidator473_1() { // reject null DomainValidator - new URIValidator(new String[]{}, null, 0L, null); + new UrlValidator(new String[]{}, null, 0L, null); } @Test(expected = IllegalArgumentException.class) public void testValidator473_2() { // reject null DomainValidator with mismatched allowLocal List items = new ArrayList<>(); - new URIValidator(new String[]{}, null, 0L, DomainValidator.getInstance(true, items)); + new UrlValidator(new String[]{}, null, 0L, DomainValidator.getInstance(true, items)); } @Test(expected = IllegalArgumentException.class) public void testValidator473_3() { // reject null DomainValidator with mismatched allowLocal List items = new ArrayList<>(); - new URIValidator(new String[]{}, null, UrlValidator.ALLOW_LOCAL_URLS, DomainValidator.getInstance(false, items)); + new UrlValidator(new String[]{}, null, UrlValidator.ALLOW_LOCAL_URLS, DomainValidator.getInstance(false, items)); } static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) { @@ -425,7 +425,7 @@ public void testValidateUrl() { @Test public void testValidator290() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://xn--h1acbxfam.idn.icann.org/")); // assertTrue(validator.isValid("http://xn--e1afmkfd.xn--80akhbyknj4f")); // Internationalized country code top-level domains @@ -484,13 +484,13 @@ public void testValidator290() { @Test public void testValidator361() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://hello.tokyo/")); } @Test public void testValidator363() { - UrlValidator urlValidator = new URIValidator(); + UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.example.org/a/b/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/a/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/hello.world/")); @@ -511,7 +511,7 @@ public void testValidator363() { @Test public void testValidator375() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://[::1]:80/index.html"; @@ -523,7 +523,7 @@ public void testValidator375() { @Test public void testValidator353() { // userinfo - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://user:pass@www.apache.org:80/path")); assertTrue(validator.isValid("http://user:@www.apache.org:80/path")); @@ -537,13 +537,13 @@ public void testValidator353() { // userinfo @Test public void testValidator382() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("ftp://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose")); } @Test public void testValidator380() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://www.apache.org:8/path")); assertTrue(validator.isValid("http://www.apache.org:/path")); @@ -551,7 +551,7 @@ public void testValidator380() { @Test public void testValidator420() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main%20Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main+Avenue")); @@ -559,7 +559,7 @@ public void testValidator420() { @Test public void testValidator467() { - UrlValidator validator = new URIValidator(UrlValidator.ALLOW_2_SLASHES); + UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue(validator.isValid("https://example.com/some_path/path/")); assertTrue(validator.isValid("https://example.com//somepath/path/")); assertTrue(validator.isValid("https://example.com//some_path/path/")); @@ -568,7 +568,7 @@ public void testValidator467() { @Test public void testValidator283() { - UrlValidator validator = new URIValidator(); + UrlValidator validator = new UrlValidator(); assertFalse(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%fr")); assertTrue(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%22")); } @@ -576,9 +576,9 @@ public void testValidator283() { @Test public void testFragments() { String[] schemes = {"http", "https"}; - UrlValidator urlValidator = new URIValidator(schemes, UrlValidator.NO_FRAGMENTS); + UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertFalse(urlValidator.isValid("http://apache.org/a/b/c#frag")); - urlValidator = new URIValidator(schemes); + urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://apache.org/a/b/c#frag")); } @@ -689,7 +689,7 @@ public void testFragments() { * @param args - URLs to validate */ public static void main(String[] args) { - UrlValidator uv = new URIValidator(); + UrlValidator uv = new UrlValidator(); for (String arg : args) { try { URI uri = new URI(arg); diff --git a/core/src/test/java/jenkins/util/UrlHelperTest.java b/core/src/test/java/jenkins/util/UrlHelperTest.java index 7734d83558a9..31f400a86474 100644 --- a/core/src/test/java/jenkins/util/UrlHelperTest.java +++ b/core/src/test/java/jenkins/util/UrlHelperTest.java @@ -43,7 +43,7 @@ public void regularCases() { // spaces are forbidden assertFalse(UrlHelper.isValidRootUrl("http:// ")); - // examples not passing with a simple `new URI(url).toURI()` check + // examples not passing with a simple `new URL(url).toURI()` check assertFalse(UrlHelper.isValidRootUrl("http://jenkins//context")); assertFalse(UrlHelper.isValidRootUrl("http:/jenkins")); assertFalse(UrlHelper.isValidRootUrl("http://.com")); diff --git a/test/src/test/java/hudson/PluginManagerTest.java b/test/src/test/java/hudson/PluginManagerTest.java index 296bf4edebea..bd761d21d4bd 100644 --- a/test/src/test/java/hudson/PluginManagerTest.java +++ b/test/src/test/java/hudson/PluginManagerTest.java @@ -241,7 +241,7 @@ public void startPlugin(PluginWrapper plugin) throws Exception { @Test public void uberClassLoaderDoesntUseContextClassLoader() throws Exception { Thread t = Thread.currentThread(); - URLClassLoader ucl = new URIClassLoader(new URI[0], r.jenkins.pluginManager.uberClassLoader); + URLClassLoader ucl = new URLClassLoader(new URL[0], r.jenkins.pluginManager.uberClassLoader); ClassLoader old = t.getContextClassLoader(); t.setContextClassLoader(ucl); diff --git a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java index 4a9df76058a1..8d6f13d9807a 100644 --- a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java +++ b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java @@ -40,12 +40,12 @@ public void diagnostics() throws Exception { int p = r.jenkins.getTcpSlaveAgentListener().getPort(); WebClient wc = r.createWebClient(); - TextPage text = wc.getPage(new URI("http://localhost:" + p + "/")); + TextPage text = wc.getPage(new URL("http://localhost:" + p + "/")); String c = text.getContent(); assertThat(c, containsString(Jenkins.VERSION)); wc.setThrowExceptionOnFailingStatusCode(false); - Page page = wc.getPage(new URI("http://localhost:" + p + "/xxx")); + Page page = wc.getPage(new URL("http://localhost:" + p + "/xxx")); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, page.getWebResponse().getStatusCode()); } } diff --git a/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java b/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java index a26815c072c8..a6544fd36150 100644 --- a/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java +++ b/test/src/test/java/hudson/bugs/JnlpAccessWithSecuredHudsonTest.java @@ -78,7 +78,7 @@ public void anonymousCanAlwaysLoadJARs() throws Exception { URL baseUrl = jnlp.getUrl(); Document dom = new DOMReader().read(jnlp.getXmlDocument()); for (Object jar : dom.selectNodes("//jar")) { - URL url = new URI(baseUrl, ((Element) jar).attributeValue("href")); + URL url = new URL(baseUrl, ((Element) jar).attributeValue("href")); System.out.println(url); // now make sure that these URLs are unprotected diff --git a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java index b58c57e644b4..60b08b0936de 100644 --- a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java +++ b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java @@ -149,7 +149,7 @@ class ProgressiveLogClient { } String next() throws IOException { - WebRequest req = new WebRequest(new URI(r.getURL() + run.getUrl() + "/logText/progressiveHtml" + (start != null ? "?start=" + start : ""))); + WebRequest req = new WebRequest(new URL(r.getURL() + run.getUrl() + "/logText/progressiveHtml" + (start != null ? "?start=" + start : ""))); req.setEncodingType(null); Map headers = new HashMap(); if (consoleAnnotator != null) diff --git a/test/src/test/java/hudson/console/UrlAnnotatorTest.java b/test/src/test/java/hudson/console/UrlAnnotatorTest.java index 5f9c51c69ccb..23c3ddb275b7 100644 --- a/test/src/test/java/hudson/console/UrlAnnotatorTest.java +++ b/test/src/test/java/hudson/console/UrlAnnotatorTest.java @@ -49,7 +49,7 @@ public boolean perform(AbstractBuild build, Launcher launcher, BuildListen @Test public void test2() { MarkupText m = new MarkupText("{abc='http://url/',def='ghi'}"); - new URIAnnotator().newInstance(null).annotate(null, m); + new UrlAnnotator().newInstance(null).annotate(null, m); String html = m.toString(false); assertTrue(html.contains("http://url/")); System.out.println(html); diff --git a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java index 5d9fee742e7f..f21f5088128d 100644 --- a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java @@ -71,7 +71,7 @@ public void noAccessForNonAdmin() throws Exception { User bob = User.getById("bob", true); User administrator = User.getById("administrator", true); - WebRequest request = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); NameValuePair param = new NameValuePair("no", "true"); request.setRequestParameters(List.of(param)); @@ -83,12 +83,12 @@ public void noAccessForNonAdmin() throws Exception { assertTrue(mon.isEnabled()); - WebRequest requestReadOnly = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET); + WebRequest requestReadOnly = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET); p = wc.getPage(requestReadOnly); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, p.getWebResponse().getStatusCode()); wc.withBasicApiToken(administrator); - request = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); + request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); request.setRequestParameters(List.of(param)); p = wc.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java b/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java index 447d1c460125..a9bb7278a849 100644 --- a/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/ReverseProxySetupMonitorTest.java @@ -66,7 +66,7 @@ public void localhost_correct() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); wc.getPage(request); } @@ -80,7 +80,7 @@ public void localhost_testingForContext() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); // As the context was already set inside the referer, adding another one will fail @@ -97,7 +97,7 @@ public void localhost_withoutReferer() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); // no referer assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); } @@ -111,7 +111,7 @@ public void localhost_withRefererNotComingFromManage() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); // wrong referer request.setAdditionalHeader("Referer", j.getURL() + "configure"); assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); @@ -131,7 +131,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(rootUrlWithoutContext); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); // As the rootURL is missing the context, a regular test will fail @@ -156,7 +156,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(rootUrlWithoutContext); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); @@ -176,7 +176,7 @@ public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.getURL(), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(j.getURL(), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); wc.getPage(request); @@ -195,7 +195,7 @@ public void usingIp_butRefererUsingRootUrl() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); request.setAdditionalHeader("Referer", j.getURL() + "manage"); wc.getPage(request); } @@ -209,7 +209,7 @@ public void usingIp_withoutReferer() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // no referer assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(request)); } @@ -223,7 +223,7 @@ public void usingIp_withRefererIp() { public void evaluate() throws Throwable { JenkinsRule j = rr.j; JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // referer using IP request.setAdditionalHeader("Referer", getRootUrlWithIp(j) + "manage"); @@ -243,7 +243,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(getRootUrlWithIp(j).toString()); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // referer using IP request.setAdditionalHeader("Referer", getRootUrlWithIp(j) + "manage"); @@ -264,7 +264,7 @@ public void evaluate() throws Throwable { JenkinsLocationConfiguration.get().setUrl(rootUrlWithoutContext); JenkinsRule.WebClient wc = rr.j.createWebClient(); - WebRequest request = new WebRequest(new URI(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); + WebRequest request = new WebRequest(new URL(getRootUrlWithIp(j), getAdminMonitorTestUrl(j))); // referer using IP request.setAdditionalHeader("Referer", getRootUrlWithIp(j) + "manage"); @@ -283,6 +283,6 @@ private String getAdminMonitorTestUrl(JenkinsRule j) { } private URL getRootUrlWithIp(JenkinsRule j) throws Exception { - return new URI(j.getURL().toString().replace("localhost", "127.0.0.1")); + return new URL(j.getURL().toString().replace("localhost", "127.0.0.1")); } } diff --git a/test/src/test/java/hudson/jobs/CreateItemTest.java b/test/src/test/java/hudson/jobs/CreateItemTest.java index 9cb94d572c69..c8d511ce168d 100644 --- a/test/src/test/java/hudson/jobs/CreateItemTest.java +++ b/test/src/test/java/hudson/jobs/CreateItemTest.java @@ -71,7 +71,7 @@ public void testCreateItemFromCopy() throws Exception { rule.createFreeStyleProject(sourceJobName); String newJobName = "newJob"; - URL apiURL = new URI(MessageFormat.format( + URL apiURL = new URL(MessageFormat.format( "{0}createItem?mode=copy&from={1}&name={2}", rule.getURL().toString(), sourceJobName, newJobName)); @@ -95,7 +95,7 @@ public void vetoCreateItemFromCopy() throws Exception { rule.createFreeStyleProject(sourceJobName); String newJobName = "newJob"; - URL apiURL = new URI(MessageFormat.format( + URL apiURL = new URL(MessageFormat.format( "{0}createItem?mode=copy&from={1}&name={2}", rule.getURL().toString(), sourceJobName, newJobName)); @@ -124,10 +124,10 @@ public void createWithFolderPaths() throws Exception { JenkinsRule.WebClient wc = rule.createWebClient(); - wc.getPage(new WebRequest(new URI(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST)); + wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST)); assertNotNull(d2.getItem("p2")); - wc.getPage(new WebRequest(new URI(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST)); + wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST)); assertNotNull(d2.getItem("p3")); } diff --git a/test/src/test/java/hudson/markup/MarkupFormatterTest.java b/test/src/test/java/hudson/markup/MarkupFormatterTest.java index eac9f8869883..f5e0e05095e5 100644 --- a/test/src/test/java/hudson/markup/MarkupFormatterTest.java +++ b/test/src/test/java/hudson/markup/MarkupFormatterTest.java @@ -104,7 +104,7 @@ public void security2153RequiresPOST() throws Exception { @Issue("SECURITY-2153") public void security2153SetsCSP() throws Exception { final JenkinsRule.WebClient wc = j.createWebClient(); - final Page htmlPage = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.jenkins.getRootUrl() + "/markupFormatter/previewDescription?text=lolwut"), HttpMethod.POST))); + final Page htmlPage = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.jenkins.getRootUrl() + "/markupFormatter/previewDescription?text=lolwut"), HttpMethod.POST))); final WebResponse response = htmlPage.getWebResponse(); assertEquals(200, response.getStatusCode()); assertThat(response.getContentAsString(), containsString("lolwut")); diff --git a/test/src/test/java/hudson/model/AbstractProjectTest.java b/test/src/test/java/hudson/model/AbstractProjectTest.java index 144b130797ff..2da8fc430448 100644 --- a/test/src/test/java/hudson/model/AbstractProjectTest.java +++ b/test/src/test/java/hudson/model/AbstractProjectTest.java @@ -140,7 +140,7 @@ public void wipeWorkspaceProtected() throws Exception { // make sure that the action link is protected JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - Page page = wc.getPage(new WebRequest(new URI(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST)); + Page page = wc.getPage(new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST)); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode()); } @@ -323,7 +323,7 @@ public void deleteRedirect() throws Exception { private String deleteRedirectTarget(String job) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); String base = wc.getContextPath(); - String loc = wc.getPage(wc.addCrumb(new WebRequest(new URI(base + job + "/doDelete"), HttpMethod.POST))).getUrl().toString(); + String loc = wc.getPage(wc.addCrumb(new WebRequest(new URL(base + job + "/doDelete"), HttpMethod.POST))).getUrl().toString(); assert loc.startsWith(base) : loc; return loc.substring(base.length()); } @@ -357,13 +357,13 @@ public void queueSuccessBehaviorOverHTTP() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebResponse rsp = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.getURL(), p.getUrl() + + WebResponse rsp = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.getURL(), p.getUrl() + "build?delay=0"), HttpMethod.POST))).getWebResponse(); assertEquals(HttpURLConnection.HTTP_CREATED, rsp.getStatusCode()); assertNotNull(rsp.getResponseHeaderValue("Location")); - WebResponse rsp2 = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.getURL(), p.getUrl() + + WebResponse rsp2 = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.getURL(), p.getUrl() + "build?delay=0"), HttpMethod.POST))).getWebResponse(); assertEquals(HttpURLConnection.HTTP_CREATED, rsp2.getStatusCode()); @@ -371,7 +371,7 @@ public void queueSuccessBehaviorOverHTTP() throws Exception { p.makeDisabled(true); - WebResponse rsp3 = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.getURL(), p.getUrl() + + WebResponse rsp3 = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.getURL(), p.getUrl() + "build?delay=0"), HttpMethod.POST))).getWebResponse(); assertEquals(HttpURLConnection.HTTP_CONFLICT, rsp3.getStatusCode()); @@ -450,7 +450,7 @@ public void configDotXmlSubmissionToDifferentType() throws Exception { } private HttpURLConnection postConfigDotXml(FreeStyleProject p, String xml) throws Exception { - HttpURLConnection con = (HttpURLConnection) new URI(j.getURL(), "job/" + p.getName() + "/config.xml").openConnection(); + HttpURLConnection con = (HttpURLConnection) new URL(j.getURL(), "job/" + p.getName() + "/config.xml").openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml; charset=utf-8"); con.setDoOutput(true); diff --git a/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java b/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java index 0546ee206e09..1f8de8ff5b9d 100644 --- a/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java +++ b/test/src/test/java/hudson/model/BuildAuthorizationTokenTest.java @@ -42,7 +42,7 @@ public void triggerJobWithoutSecurityRealm_ShouldSucceed_WithPost() throws Excep jr.jenkins.setAuthorizationStrategy(null); FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); - wc.getPage(wc.addCrumb(new WebRequest(new URI(jr.getURL(), project.getUrl() + + wc.getPage(wc.addCrumb(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST))); jr.waitUntilNoActivity(); @@ -59,7 +59,7 @@ public void triggerJobWithoutSecurityRealm_ShouldFail_WithGet() throws Exception FailingHttpStatusCodeException fex = assertThrows( "should not reach here since only POST request can", FailingHttpStatusCodeException.class, - () -> wc.getPage(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.GET))); + () -> wc.getPage(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.GET))); assertThat("Should fail with method not allowed", fex.getStatusCode(), is(405)); } @@ -70,7 +70,7 @@ public void triggerJobWithoutSecurityRealm_ButWithToken_ShouldSucceed_WithGet() jr.jenkins.setAuthorizationStrategy(null); FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); - wc.getPage(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), + wc.getPage(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), HttpMethod.GET)); jr.waitUntilNoActivity(); assertThat("the project should have been built", project.getBuilds(), hasSize(1)); @@ -81,7 +81,7 @@ public void triggerJobWithTokenShouldSucceedWithPost() throws Exception { FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); HtmlPage page = wc.getPage(wc.addCrumb(new WebRequest( - new URI(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), + new URL(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), HttpMethod.POST))); jr.waitUntilNoActivity(); assertThat("the project should have been built", project.getBuilds(), hasSize(1)); @@ -92,7 +92,7 @@ public void triggerJobWithTokenShouldSucceedWithGet() throws Exception { FreeStyleProject project = createFreestyleProjectWithToken(); JenkinsRule.WebClient wc = jr.createWebClient(); HtmlPage page = wc.getPage(new WebRequest( - new URI(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), + new URL(jr.getURL(), project.getUrl() + "build?delay=0&token=" + token), HttpMethod.GET)); jr.waitUntilNoActivity(); assertThat("the project should have been built", project.getBuilds(), hasSize(1)); @@ -106,7 +106,7 @@ public void triggerJobsWithoutTokenShouldFail() throws Exception { FailingHttpStatusCodeException fex = assertThrows( "should not reach here as anonymous does not have Item.BUILD and token is not set", FailingHttpStatusCodeException.class, - () -> wc.getPage(wc.addCrumb(new WebRequest(new URI(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); + () -> wc.getPage(wc.addCrumb(new WebRequest(new URL(jr.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); assertThat("Should fail with access denied", fex.getStatusCode(), is(403)); } diff --git a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java index 2cbe77d747b2..aab9da2cfe65 100644 --- a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java +++ b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java @@ -188,7 +188,7 @@ private Page doPost(View view, String path) throws Exception { WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); WebRequest req = new WebRequest( - new URI(j.jenkins.getRootUrl() + view.getUrl() + path), + new URL(j.jenkins.getRootUrl() + view.getUrl() + path), HttpMethod.POST ); diff --git a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java index e964f8de6646..7b1bbdb7c9bd 100644 --- a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java +++ b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java @@ -482,7 +482,7 @@ public InputStream open() throws IOException { @Override public URL toExternalURL() throws IOException { - return new URI(Jenkins.get().getRootUrl() + "files/" + hash); + return new URL(Jenkins.get().getRootUrl() + "files/" + hash); } }; return new VirtualFile() { // the root @@ -1454,7 +1454,7 @@ public InputStream open() throws IOException { @Override public URL toExternalURL() throws IOException { - return new URI(Jenkins.get().getRootUrl() + "files/" + hash); + return new URL(Jenkins.get().getRootUrl() + "files/" + hash); } }; return new VirtualFile() { // the root diff --git a/test/src/test/java/hudson/model/FingerprintTest.java b/test/src/test/java/hudson/model/FingerprintTest.java index 16f99c57a3de..452df423d8a6 100644 --- a/test/src/test/java/hudson/model/FingerprintTest.java +++ b/test/src/test/java/hudson/model/FingerprintTest.java @@ -400,11 +400,11 @@ public void checkNormalFingerprintWithWebClient() throws Exception { Fingerprint fp = getFingerprint(build, "test.txt"); - Page page = rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "fingerprint/" + fp.getHashString() + "/"))); + Page page = rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "fingerprint/" + fp.getHashString() + "/"))); assertEquals(200, page.getWebResponse().getStatusCode()); // could also be reached using static// - Page page2 = rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + fp.getHashString() + "/"))); + Page page2 = rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + fp.getHashString() + "/"))); assertEquals(200, page2.getWebResponse().getStatusCode()); } @@ -468,7 +468,7 @@ public void checkArbitraryEmptyFileExistenceWithWebClient() throws Exception { targetFile.deleteOnExit(); String first = fp.getHashString().substring(0, 2); String second = fp.getHashString().substring(2, 4); - rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf2/"))); + rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf2/"))); assertTrue(targetFile.exists()); } @@ -517,7 +517,7 @@ public void checkArbitraryFileExistenceWithWebClient() throws Exception { String first = fp.getHashString().substring(0, 2); String second = fp.getHashString().substring(2, 4); - rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf4/"))); + rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf4/"))); assertTrue(targetFile.exists()); } @@ -552,7 +552,7 @@ public void checkArbitraryFileNonexistenceWithWebClient() throws Exception { Fingerprint fp = getFingerprint(build, "test.txt"); String first = fp.getHashString().substring(0, 2); String second = fp.getHashString().substring(2, 4); - rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf6/"))); + rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf6/"))); } @Test @@ -577,7 +577,7 @@ public void checkArbitraryFingerprintConfigFileExistenceWithWebClient() throws E try { // that file exists, so we need to ensure if it's returned, the content is not the expected one from the test data. String partialUrl = "static/abc/fingerprint/" + first + second + "%2f..%2f..%2f" + first + "%2f" + second + "%2f..%2f..%2f..%2f..%2fcf7/"; - page = rule.createWebClient().getPage(new WebRequest(new URI(rule.getURL(), partialUrl))); + page = rule.createWebClient().getPage(new WebRequest(new URL(rule.getURL(), partialUrl))); } catch (FailingHttpStatusCodeException e) { // expected refusal after the correction assertEquals(500, e.getStatusCode()); diff --git a/test/src/test/java/hudson/model/HudsonTest.java b/test/src/test/java/hudson/model/HudsonTest.java index f2ec7e69ee9c..a4fff0108458 100644 --- a/test/src/test/java/hudson/model/HudsonTest.java +++ b/test/src/test/java/hudson/model/HudsonTest.java @@ -177,7 +177,7 @@ public void deleteHudsonComputer() throws Exception { wc.setThrowExceptionOnFailingStatusCode(false); // try to delete it by hitting the final URL directly - WebRequest req = new WebRequest(new URI(wc.getContextPath() + "computer/(built-in)/doDelete"), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(wc.getContextPath() + "computer/(built-in)/doDelete"), HttpMethod.POST); page = wc.getPage(wc.addCrumb(req)); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/model/ItemsTest.java b/test/src/test/java/hudson/model/ItemsTest.java index 577a91eb5f39..37c0befc3081 100644 --- a/test/src/test/java/hudson/model/ItemsTest.java +++ b/test/src/test/java/hudson/model/ItemsTest.java @@ -228,7 +228,7 @@ private enum OverwriteTactic { // redirect perversely counts as a failure .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { throw new FailingHttpStatusCodeException(webResponse); } @@ -241,7 +241,7 @@ private enum OverwriteTactic { JenkinsRule.WebClient wc = wc(r) .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse(); r.jenkins.getItem("dupe").delete(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { throw new FailingHttpStatusCodeException(webResponse); @@ -252,7 +252,7 @@ private enum OverwriteTactic { REST_CREATE { @Override void run(JenkinsRule r, String target) throws Exception { JenkinsRule.WebClient wc = wc(r); - WebRequest req = new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/xml"); req.setRequestBody(""); wc.getPage(req); @@ -265,7 +265,7 @@ private enum OverwriteTactic { JenkinsRule.WebClient wc = wc(r) .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { r.jenkins.getItem("dupe").delete(); throw new FailingHttpStatusCodeException(webResponse); diff --git a/test/src/test/java/hudson/model/ProjectTest.java b/test/src/test/java/hudson/model/ProjectTest.java index d6a5fb21e3f6..8d2f5e6bc7cc 100644 --- a/test/src/test/java/hudson/model/ProjectTest.java +++ b/test/src/test/java/hudson/model/ProjectTest.java @@ -618,7 +618,7 @@ public void testDoDoWipeOutWorkspace() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.withBasicCredentials(user.getId(), "password"); - WebRequest request = new WebRequest(new URI(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST); HtmlPage p = wc.getPage(request); assertEquals(200, p.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index 1376bbac92d8..e31e2acdd1c9 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -1199,7 +1199,7 @@ private void checkCancelOperationUsingUrl(Function urlProvid Queue.Item currentOne = items[0]; assertFalse(currentOne.getFuture().isCancelled()); - WebRequest request = new WebRequest(new URI(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST); { // user without right cannot cancel JenkinsRule.WebClient wc = r.createWebClient() diff --git a/test/src/test/java/hudson/model/SlaveTest.java b/test/src/test/java/hudson/model/SlaveTest.java index 58909a8c8017..b66130bfc4ea 100644 --- a/test/src/test/java/hudson/model/SlaveTest.java +++ b/test/src/test/java/hudson/model/SlaveTest.java @@ -107,7 +107,7 @@ public void slaveConfigDotXml() throws Exception { } private void post(String url, String xml) throws Exception { - HttpURLConnection con = (HttpURLConnection) new URI(j.getURL(), url).openConnection(); + HttpURLConnection con = (HttpURLConnection) new URL(j.getURL(), url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml;charset=UTF-8"); con.setRequestProperty(CrumbIssuer.DEFAULT_CRUMB_NAME, "test"); diff --git a/test/src/test/java/hudson/model/UpdateCenterTest.java b/test/src/test/java/hudson/model/UpdateCenterTest.java index 9866a5883344..998e9badd67e 100644 --- a/test/src/test/java/hudson/model/UpdateCenterTest.java +++ b/test/src/test/java/hudson/model/UpdateCenterTest.java @@ -58,7 +58,7 @@ public class UpdateCenterTest { } private void doData(String location) throws Exception { - URL url = new URI(location); + URL url = new URL(location); String jsonp = DownloadService.loadJSON(url); JSONObject json = JSONObject.fromObject(jsonp); diff --git a/test/src/test/java/hudson/model/UpdateSiteTest.java b/test/src/test/java/hudson/model/UpdateSiteTest.java index 34508bc1e0cd..e355aec53399 100644 --- a/test/src/test/java/hudson/model/UpdateSiteTest.java +++ b/test/src/test/java/hudson/model/UpdateSiteTest.java @@ -130,7 +130,7 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques } }); server.start(); - baseUrl = new URI("http", "localhost", connector.getLocalPort(), RELATIVE_BASE); + baseUrl = new URL("http", "localhost", connector.getLocalPort(), RELATIVE_BASE); } @After @@ -139,15 +139,15 @@ public void shutdownWebserver() throws Exception { } @Test public void relativeURLs() throws Exception { - URL url = new URI(baseUrl, "/plugins/htmlpublisher-update-center.json"); + URL url = new URL(baseUrl, "/plugins/htmlpublisher-update-center.json"); UpdateSite site = new UpdateSite(UpdateCenter.ID_DEFAULT, url.toString()); overrideUpdateSite(site); assertEquals(FormValidation.ok(), site.updateDirectly(false).get()); Data data = site.getData(); assertNotNull(data); - assertEquals(new URI(url, "jenkins.war").toString(), data.core.url); + assertEquals(new URL(url, "jenkins.war").toString(), data.core.url); assertEquals(new HashSet<>(Arrays.asList("htmlpublisher", "dummy")), data.plugins.keySet()); - assertEquals(new URI(url, "htmlpublisher.jpi").toString(), data.plugins.get("htmlpublisher").url); + assertEquals(new URL(url, "htmlpublisher.jpi").toString(), data.plugins.get("htmlpublisher").url); assertEquals("http://nowhere.net/dummy.hpi", data.plugins.get("dummy").url); UpdateSite.Plugin htmlPublisherPlugin = data.plugins.get("htmlpublisher"); @@ -177,7 +177,7 @@ public void shutdownWebserver() throws Exception { } @Test public void updateDirectlyWithJson() throws Exception { - UpdateSite us = new UpdateSite("default", new URI(baseUrl, "update-center.json").toExternalForm()); + UpdateSite us = new UpdateSite("default", new URL(baseUrl, "update-center.json").toExternalForm()); assertNull(us.getPlugin("AdaptivePlugin")); assertEquals(FormValidation.ok(), us.updateDirectly(/* TODO the certificate is now expired, and downloading a fresh copy did not seem to help */false).get()); assertNotNull(us.getPlugin("AdaptivePlugin")); @@ -241,7 +241,7 @@ private UpdateSite getUpdateSite(String path) throws Exception { } private UpdateSite getUpdateSite(String path, String id) throws Exception { - URL url = new URI(baseUrl, path); + URL url = new URL(baseUrl, path); UpdateSite site = new UpdateSite(id, url.toString()); assertEquals(FormValidation.ok(), site.updateDirectly(false).get()); return site; diff --git a/test/src/test/java/hudson/model/UserRestartTest.java b/test/src/test/java/hudson/model/UserRestartTest.java index 74aead70531d..95641933beed 100644 --- a/test/src/test/java/hudson/model/UserRestartTest.java +++ b/test/src/test/java/hudson/model/UserRestartTest.java @@ -115,7 +115,7 @@ public void legacyConfigMoveCannotEscapeUserFolder() throws Throwable { JenkinsRule.WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URI(r.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URL(r.jenkins.getRootUrl() + "whoAmI/api/xml")); request.setAdditionalHeader("Authorization", base64("..", "any-password")); wc.getPage(request); } @@ -123,7 +123,7 @@ public void legacyConfigMoveCannotEscapeUserFolder() throws Throwable { JenkinsRule.WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URI(r.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URL(r.jenkins.getRootUrl() + "whoAmI/api/xml")); request.setAdditionalHeader("Authorization", base64("../users/..", "any-password")); wc.getPage(request); } diff --git a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java index ece9e3882719..9883b0680843 100644 --- a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java +++ b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java @@ -344,7 +344,7 @@ private void createFirstAccount(String login) throws Exception { info.password2 = login; info.fullname = StringUtils.capitalize(login); - WebRequest request = new WebRequest(new URI(wc.getContextPath() + "securityRealm/createFirstAccount"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(wc.getContextPath() + "securityRealm/createFirstAccount"), HttpMethod.POST); request.setRequestParameters(Arrays.asList( new NameValuePair("username", login), new NameValuePair("password1", login), diff --git a/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java b/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java index 9e1bbd375430..adb2184ff239 100644 --- a/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java +++ b/test/src/test/java/hudson/security/csrf/CrumbExclusionTest.java @@ -62,7 +62,7 @@ public void pathInfo() throws Exception { r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to("admin")); for (String path : new String[] {/* control */ "scriptText", /* test */ "scriptText/..;/cli"}) { try { - fail(path + " should have been rejected: " + r.createWebClient().login("admin").getPage(new WebRequest(new URI(r.getURL(), path + "?script=11*11"), HttpMethod.POST)).getWebResponse().getContentAsString()); + fail(path + " should have been rejected: " + r.createWebClient().login("admin").getPage(new WebRequest(new URL(r.getURL(), path + "?script=11*11"), HttpMethod.POST)).getWebResponse().getContentAsString()); } catch (FailingHttpStatusCodeException x) { switch (x.getStatusCode()) { case 403: @@ -80,7 +80,7 @@ public void pathInfo() throws Exception { @Test public void regular() throws Exception { - r.createWebClient().getPage(new WebRequest(new URI(r.getURL(), "root/"), HttpMethod.POST)); + r.createWebClient().getPage(new WebRequest(new URL(r.getURL(), "root/"), HttpMethod.POST)); Assert.assertTrue(ExtensionList.lookupSingleton(RootActionImpl.class).posted); } diff --git a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java index c67d1d4687fb..b6b417f8dc6f 100644 --- a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java +++ b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java @@ -303,7 +303,7 @@ public void twoRequestsWithoutSessionGetDifferentCrumbs() throws Exception { } private WebRequest createRequestForJobCreation(String jobName) throws Exception { - WebRequest req = new WebRequest(new URI(r.getURL() + "createItem?name=" + jobName), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(r.getURL() + "createItem?name=" + jobName), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/xml"); req.setRequestBody(""); return req; diff --git a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java index 6f273ad39e24..72210eec3362 100644 --- a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java +++ b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java @@ -65,7 +65,7 @@ public void onlyAdminCanReachTheDoCheck() throws Exception { User.getById(ADMIN, true); User.getById(USER, true); - WebRequest request = new WebRequest(new URI(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl"), HttpMethod.POST); request.setRequestBody(URLEncoder.encode("value=https://www.google.com", StandardCharsets.UTF_8)); JenkinsRule.WebClient adminWc = j.createWebClient(); diff --git a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java index f29845715903..da667a80d802 100644 --- a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java +++ b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java @@ -206,7 +206,7 @@ public void testRestInterfaceFailure() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); WebClient wc = r.createWebClient(); wc.withBasicApiToken("test"); - WebRequest req = new WebRequest(new URI(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD)); wc.getPage(req); @@ -237,7 +237,7 @@ public void testRestInterfaceFailure() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); wc.withBasicApiToken("test"); - WebRequest req = new WebRequest(new URI(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue")); diff --git a/test/src/test/java/jenkins/install/SetupWizardTest.java b/test/src/test/java/jenkins/install/SetupWizardTest.java index 42b828eb7f10..7168f93d93af 100644 --- a/test/src/test/java/jenkins/install/SetupWizardTest.java +++ b/test/src/test/java/jenkins/install/SetupWizardTest.java @@ -221,7 +221,7 @@ public void testRemoteUpdateSiteFailingValidation() throws Exception { server.setHandler(new RemoteUpdateSiteHandler(serverContext, true)); try { server.start(); - baseUrl = new URI("http", "localhost", connector.getLocalPort(), serverContext); + baseUrl = new URL("http", "localhost", connector.getLocalPort(), serverContext); // Init the update site CustomRemoteUpdateSite us = new CustomRemoteUpdateSite(baseUrl.toString(), false); @@ -255,7 +255,7 @@ public void testRemoteUpdateSiteSkippingValidation() throws Exception { try { server.start(); DownloadService.signatureCheck = false; - baseUrl = new URI("http", "localhost", connector.getLocalPort(), serverContext); + baseUrl = new URL("http", "localhost", connector.getLocalPort(), serverContext); // Init the update site CustomRemoteUpdateSite us = new CustomRemoteUpdateSite(baseUrl.toString(), false); @@ -292,7 +292,7 @@ public void testRemoteUpdateSitePerformingValidation() throws Exception { server.setHandler(new RemoteUpdateSiteHandler(serverContext, true)); try { server.start(); - baseUrl = new URI("http", "localhost", connector.getLocalPort(), serverContext); + baseUrl = new URL("http", "localhost", connector.getLocalPort(), serverContext); // Init the update site CustomRemoteUpdateSite us = new CustomRemoteUpdateSite(baseUrl.toString(), true); diff --git a/test/src/test/java/jenkins/model/AssetManagerTest.java b/test/src/test/java/jenkins/model/AssetManagerTest.java index 4994d264a1a4..d00541d4a554 100644 --- a/test/src/test/java/jenkins/model/AssetManagerTest.java +++ b/test/src/test/java/jenkins/model/AssetManagerTest.java @@ -41,7 +41,7 @@ public class AssetManagerTest { @Test @Issue("JENKINS-58736") public void emptyAssetDoesNotThrowError() throws Exception { - URL url = new URI(j.getURL() + "assets"); + URL url = new URL(j.getURL() + "assets"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpCon.getResponseCode()); } diff --git a/test/src/test/java/jenkins/model/JenkinsTest.java b/test/src/test/java/jenkins/model/JenkinsTest.java index 33959cc8a69b..5c0c9acedbb2 100644 --- a/test/src/test/java/jenkins/model/JenkinsTest.java +++ b/test/src/test/java/jenkins/model/JenkinsTest.java @@ -326,11 +326,11 @@ public void testDoScript() throws Exception { wc.goTo("script"); wc.assertFails("script?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD); assertNull(System.getProperty("hack")); - WebRequest req = new WebRequest(new URI(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST); wc.getPage(req); assertEquals("me", System.getProperty("hack")); wc.assertFails("scriptText?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD); - req = new WebRequest(new URI(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST); + req = new WebRequest(new URL(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST); wc.getPage(req); assertEquals("you", System.getProperty("huck")); @@ -380,7 +380,7 @@ public void testDoEval() throws Exception { } private Page eval(WebClient wc) throws Exception { - WebRequest req = new WebRequest(new URI(wc.getContextPath() + "eval"), HttpMethod.POST); + WebRequest req = new WebRequest(new URL(wc.getContextPath() + "eval"), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody("${1+2}"); return wc.getPage(req); @@ -486,7 +486,7 @@ public void runScriptOnOfflineComputer() throws Exception { DumbSlave slave = j.createSlave(true); j.disconnectSlave(slave); - URL url = new URI(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)"); + URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)"); WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); diff --git a/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java b/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java index 2368b5bfb284..f4b11cb2eaee 100644 --- a/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java +++ b/test/src/test/java/jenkins/model/ParameterizedJobMixInTest.java @@ -74,7 +74,7 @@ public void doBuildWithParameters_shouldFailWhenInvokingDisabledProject() throws FailingHttpStatusCodeException fex = assertThrows( "should fail when invoking disabled project", FailingHttpStatusCodeException.class, - () -> webClient.getPage(webClient.addCrumb(new WebRequest(new URI(j.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); + () -> webClient.getPage(webClient.addCrumb(new WebRequest(new URL(j.getURL(), project.getUrl() + "build?delay=0"), HttpMethod.POST)))); assertThat("Should fail with conflict", fex.getStatusCode(), is(409)); } @@ -87,7 +87,7 @@ public void doBuildQuietPeriodInSeconds() throws Exception { project.setQuietPeriod(projectQuietPeriodInSeconds); final JenkinsRule.WebClient webClient = j.createWebClient(); - webClient.getPage(webClient.addCrumb(new WebRequest(new URI(j.getURL(), project.getUrl() + "build"), HttpMethod.POST))); + webClient.getPage(webClient.addCrumb(new WebRequest(new URL(j.getURL(), project.getUrl() + "build"), HttpMethod.POST))); long triggerTime = System.currentTimeMillis(); Queue.Item item = Jenkins.get().getQueue().getItem(1); diff --git a/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java b/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java index 533d9b5bed3f..59f89e8f4977 100644 --- a/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java +++ b/test/src/test/java/jenkins/security/ApiCrumbExclusionTest.java @@ -95,7 +95,7 @@ public void callUsingApiTokenDoesNotRequireCSRFToken() throws Exception { } private void makeRequestAndVerify(String expected) throws IOException { - WebRequest req = new WebRequest(new URI(j.getURL(), "test-post")); + WebRequest req = new WebRequest(new URL(j.getURL(), "test-post")); req.setHttpMethod(HttpMethod.POST); req.setEncodingType(null); Page p = wc.getPage(req); diff --git a/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java b/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java index 07c87f186fc5..4f9080b4ac9e 100644 --- a/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java +++ b/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java @@ -151,7 +151,7 @@ public void adminsShouldBeUnableToChangeTokensByDefault() throws Exception { requirePOST.getWebResponse().getStatusCode()); wc.setThrowExceptionOnFailingStatusCode(true); - WebRequest request = new WebRequest(new URI(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl() + "/changeToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl() + "/changeToken"), HttpMethod.POST); HtmlPage res = wc.getPage(request); // TODO This nicer alternative requires https://github.com/jenkinsci/jenkins/pull/2268 or similar to work @@ -167,7 +167,7 @@ public void postWithUsernameAndTokenInBasicAuthHeader() throws Exception { User.getById("foo", true); WebClient wc = createClientForUser("foo"); - WebRequest wr = new WebRequest(new URI(j.getURL(), "job/bar/build"), HttpMethod.POST); + WebRequest wr = new WebRequest(new URL(j.getURL(), "job/bar/build"), HttpMethod.POST); assertEquals(HttpURLConnection.HTTP_CREATED, wc.getPage(wr).getWebResponse().getStatusCode()); @@ -417,7 +417,7 @@ private void revokeAllTokenUsingFilter(WebClient wc, User user, Predicate alerted.set(true)); - HtmlPage page = wc.getPage(new URI(wc.getContextPath() + ACTION_URL)); + HtmlPage page = wc.getPage(new URL(wc.getContextPath() + ACTION_URL)); String responseContent = page.getWebResponse().getContentAsString(); wc.waitForBackgroundJavaScript(5000); diff --git a/test/src/test/java/jenkins/security/Security637Test.java b/test/src/test/java/jenkins/security/Security637Test.java index 3622bf53decd..824a06d56001 100644 --- a/test/src/test/java/jenkins/security/Security637Test.java +++ b/test/src/test/java/jenkins/security/Security637Test.java @@ -64,10 +64,10 @@ public class Security637Test { public void urlSafeDeserialization_handler_inSameJVMRemotingContext() throws Throwable { sessions.then(j -> { DumbSlave slave = j.createOnlineSlave(null, new EnvVars("JAVA_TOOL_OPTIONS", "--add-opens=java.base/java.net=ALL-UNNAMED")); - String unsafeHandlerClassName = slave.getChannel().call(new URIHandlerCallable(new URI("https://www.google.com/"))); + String unsafeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("https://www.google.com/"))); assertThat(unsafeHandlerClassName, containsString("SafeURLStreamHandler")); - String safeHandlerClassName = slave.getChannel().call(new URIHandlerCallable(new URI("file", null, -1, "", null))); + String safeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("file", null, -1, "", null))); assertThat(safeHandlerClassName, not(containsString("SafeURLStreamHandler"))); }); } @@ -95,8 +95,8 @@ public void urlDnsEquivalence() throws Throwable { sessions.then(j -> { // due to the DNS resolution they are equal assertEquals( - new URI("https://jenkins.io"), - new URI("https://www.jenkins.io") + new URL("https://jenkins.io"), + new URL("https://www.jenkins.io") ); }); } @@ -110,9 +110,9 @@ public void urlSafeDeserialization_urlBuiltInAgent_inSameJVMRemotingContext() th // we bypass the standard equals method that resolve the hostname assertThat( - slave.getChannel().call(new URIBuilderCallable("https://jenkins.io")), + slave.getChannel().call(new URLBuilderCallable("https://jenkins.io")), not(equalTo( - slave.getChannel().call(new URIBuilderCallable("https://www.jenkins.io")) + slave.getChannel().call(new URLBuilderCallable("https://www.jenkins.io")) )) ); }); @@ -127,7 +127,7 @@ private static class URLBuilderCallable extends MasterToSlaveCallable { FreeStyleProject project = j.createFreeStyleProject("project-with-url"); - URLJobProperty URLJobProperty = new URIJobProperty( + URLJobProperty URLJobProperty = new URLJobProperty( // url to be wrapped - new URI("https://www.google.com/"), + new URL("https://www.google.com/"), // safe url, not required to be wrapped - new URI("https", null, -1, "", null) + new URL("https", null, -1, "", null) ); project.addProperty(URLJobProperty); diff --git a/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java b/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java index 6ca49a408150..c0f6e95f0e57 100644 --- a/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java +++ b/test/src/test/java/jenkins/security/SuspiciousRequestFilterTest.java @@ -30,7 +30,7 @@ public class SuspiciousRequestFilterTest { private WebResponse get(String path) throws Exception { return j.createWebClient() .withThrowExceptionOnFailingStatusCode(false) - .getPage(new WebRequest(new URI(j.getURL(), path))) + .getPage(new WebRequest(new URL(j.getURL(), path))) .getWebResponse(); } diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java index 9f0e22cbc667..4f0d8a4510a2 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsRestartTest.java @@ -85,7 +85,7 @@ public void roundtripWithRestart() throws Throwable { WebClient wc = j.createWebClient().withBasicCredentials(u.getId()); wc.getOptions().setThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URI(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); request.setRequestParameters(List.of(new NameValuePair("newTokenName", TOKEN_NAME))); Page page = wc.getPage(request); @@ -165,7 +165,7 @@ private static void checkUserIsNotConnected(WebClient wc) throws Exception { private static void revokeToken(JenkinsRule j, WebClient wc, String login, String tokenUuid) throws Exception { WebRequest request = new WebRequest( - new URI(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), + new URL(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), HttpMethod.POST ); Page p = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java index dbf51574c67d..76bd3ffecfec 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java @@ -73,7 +73,7 @@ public void roundtrip() throws Exception { final String TOKEN_NAME = "New Token Name"; - WebRequest request = new WebRequest(new URI(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "user/" + u.getId() + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/generateNewToken"), HttpMethod.POST); request.setRequestParameters(List.of(new NameValuePair("newTokenName", TOKEN_NAME))); Page page = wc.getPage(request); @@ -132,7 +132,7 @@ private void checkUserIsNotConnected(WebClient wc) throws Exception { private void revokeToken(WebClient wc, String login, String tokenUuid) throws Exception { WebRequest request = new WebRequest( - new URI(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), + new URL(j.getURL(), "user/" + login + "/descriptorByName/" + ApiTokenProperty.class.getName() + "/revoke/?tokenUuid=" + tokenUuid), HttpMethod.POST ); Page p = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java b/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java index 8e73e009e000..d2a32423c18d 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java @@ -71,7 +71,7 @@ public void onWebCallUserSeedChange_listenerTriggered() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); WebRequest webRequest = new WebRequest( - new URI(j.getURL() + alice.getUrl() + "/" + userSeed.getDescriptor().getDescriptorUrl() + "/renewSessionSeed"), + new URL(j.getURL() + alice.getUrl() + "/" + userSeed.getDescriptor().getDescriptorUrl() + "/renewSessionSeed"), HttpMethod.POST ); diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java index c5f5fd44614f..e41158cbc8ba 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java @@ -95,7 +95,7 @@ public void renewSeedSavesTheChange() throws Throwable { private static void requestRenewSeedForUser(User user, JenkinsRule j) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); wc.getPage(request); } } diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java index a885fb6fcb8e..1c87791f193c 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java @@ -300,7 +300,7 @@ private void assertUserNotConnected(JenkinsRule.WebClient wc, String notExpected private void requestRenewSeedForUser(User user) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); - WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + user.getUrl() + "/descriptorByName/" + UserSeedProperty.class.getName() + "/renewSessionSeed/"), HttpMethod.POST); wc.getPage(request); } } diff --git a/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java b/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java index 0d24afc53635..042462ca75d6 100644 --- a/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java +++ b/test/src/test/java/jenkins/security/stapler/DoActionFilterTest.java @@ -295,7 +295,7 @@ public void testAnnotatedMethodOk_annotatedGet() throws Exception { @Test public void testAnnotatedMethodOk_annotatedPost() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedPost/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedPost/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(""); assertReachableWithSettings(settings); @@ -303,7 +303,7 @@ public void testAnnotatedMethodOk_annotatedPost() throws Exception { @Test public void testAnnotatedMethodOk_annotatedPut() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedPut/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedPut/")); settings.setHttpMethod(HttpMethod.PUT); settings.setRequestBody(""); assertReachableWithSettings(settings); @@ -316,7 +316,7 @@ public void testAnnotatedMethodOk_annotatedDelete() throws Exception { @Test public void testAnnotatedMethodOk_annotatedRequirePost() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedRequirePost/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedRequirePost/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(""); assertReachableWithSettings(settings); @@ -337,7 +337,7 @@ public void validateCrumb(StaplerRequest request, String submittedCrumb) { }); - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedJavaScriptScriptMethod/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedJavaScriptScriptMethod/")); settings.setAdditionalHeader("Content-Type", "application/x-stapler-method-invocation"); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(JSONArray.fromObject(Collections.emptyList()).toString()); @@ -351,7 +351,7 @@ public void testAnnotatedMethodOk_annotatedResponseSuccess() throws Exception { @Test public void testAnnotatedMethodOk_annotatedJsonResponse() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedJsonResponse/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedJsonResponse/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestBody(JSONObject.fromObject(Collections.emptyMap()).toString()); Page page = wc.getPage(settings); @@ -360,7 +360,7 @@ public void testAnnotatedMethodOk_annotatedJsonResponse() throws Exception { @Test public void testAnnotatedMethodOk_annotatedLimitedTo() { - FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(new URI(j.getURL(), "testNewRulesOk/annotatedLimitedTo/"))); + FailingHttpStatusCodeException e = assertThrows(FailingHttpStatusCodeException.class, () -> wc.getPage(new URL(j.getURL(), "testNewRulesOk/annotatedLimitedTo/"))); assertEquals(500, e.getStatusCode()); assertTrue(e.getResponse().getContentAsString().contains("Needs to be in role")); } @@ -379,14 +379,14 @@ public void testAnnotatedParameterOk_annotatedParamAncestorInPath() throws Excep @Test public void testAnnotatedParameterOk_annotatedParamHeader() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedParamHeader/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamHeader/")); settings.setAdditionalHeader("test-header", "TestBrowser"); assertReachableWithSettings(settings); } @Test public void testAnnotatedParameterOk_annotatedParamJsonBody() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedParamJsonBody/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamJsonBody/")); // WebClient forces us to use POST to have the possibility to send requestBody settings.setHttpMethod(HttpMethod.POST); settings.setAdditionalHeader("Content-Type", "application/json"); @@ -396,7 +396,7 @@ public void testAnnotatedParameterOk_annotatedParamJsonBody() throws Exception { @Test public void testAnnotatedParameterOk_annotatedParamSubmittedForm() throws Exception { - WebRequest settings = new WebRequest(new URI(j.getURL(), "testNewRulesOk/annotatedParamSubmittedForm/")); + WebRequest settings = new WebRequest(new URL(j.getURL(), "testNewRulesOk/annotatedParamSubmittedForm/")); settings.setHttpMethod(HttpMethod.POST); settings.setRequestParameters(List.of( diff --git a/test/src/test/java/jenkins/security/stapler/Security400Test.java b/test/src/test/java/jenkins/security/stapler/Security400Test.java index c80075191635..e48faf5dbd8f 100644 --- a/test/src/test/java/jenkins/security/stapler/Security400Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security400Test.java @@ -231,7 +231,7 @@ public void ensureDoStopStillReachable() throws Exception { j.jenkins.setNumExecutors(1); { // preliminary test, calling the stop method without any executor results in 404 - WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -256,7 +256,7 @@ public void ensureDoStopStillReachable() throws Exception { // we need to wait until the SemaphoreBuilder is running (blocked) otherwise the job is ABORTED not FAILURE j.waitForMessage(SemaphoredBuilder.START_MESSAGE, build); - WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stop"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -290,7 +290,7 @@ public void ensureDoStopBuildWorks() throws Exception { j.jenkins.setNumExecutors(1); { // preliminary test, calling stopBuild without any executor results in 404 - WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -319,7 +319,7 @@ public void ensureDoStopBuildWorks() throws Exception { QueueTaskFuture futureBuild = p.scheduleBuild2(0); futureBuild.waitForStart(); - WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -340,7 +340,7 @@ public void ensureDoStopBuildWorks() throws Exception { FreeStyleBuild build = futureBuild.waitForStart(); String runExtId = URLEncoder.encode(build.getExternalizableId(), StandardCharsets.UTF_8); - WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -360,7 +360,7 @@ public void ensureDoStopBuildWorks() throws Exception { QueueTaskFuture futureBuild = p.scheduleBuild2(0); futureBuild.waitForStart(); - WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=whatever"), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=whatever"), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -564,7 +564,7 @@ public void ensureLogRecordManagerAccessibleOnlyByAdmin() throws Exception { assertEquals(404, wc.goTo("log/" + logNameForAdmin + "/autoCompleteLoggerName/?value=a", null).getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); - WebRequest request = new WebRequest(new URI(j.getURL() + "log/newLogRecorder/?name=" + logNameForAdmin), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "log/newLogRecorder/?name=" + logNameForAdmin), HttpMethod.POST); wc.getOptions().setRedirectEnabled(false); Page page = wc.getPage(request); @@ -588,7 +588,7 @@ public void ensureLogRecordManagerAccessibleOnlyByAdmin() throws Exception { assertEquals(403, wc.goTo("log/" + logNameForUser + "/autoCompleteLoggerName/?value=a", null).getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); - WebRequest request = new WebRequest(new URI(j.getURL() + "log/newLogRecorder/?name=" + logNameForUser), HttpMethod.POST); + WebRequest request = new WebRequest(new URL(j.getURL() + "log/newLogRecorder/?name=" + logNameForUser), HttpMethod.POST); wc.getOptions().setRedirectEnabled(false); Page page = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/stapler/Security914Test.java b/test/src/test/java/jenkins/security/stapler/Security914Test.java index 17851e68eb06..5ade00a7678f 100644 --- a/test/src/test/java/jenkins/security/stapler/Security914Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security914Test.java @@ -54,7 +54,7 @@ public void cannotUseInvalidLocale_toTraverseFolder() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URI(j.getURL() + "plugin/credentials/.xml")); + WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.xml")); // plugin deployed in: test\target\jenkins7375296945862059919tmp // rootDir is in : test\target\jenkinsTests.tmp\jenkins1274934531848159942test // j.jenkins.getRootDir().getName() = jenkins1274934531848159942test @@ -74,7 +74,7 @@ public void cannotUseInvalidLocale_toAnyFileInSystem() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URI(j.getURL() + "plugin/credentials/.ini")); + WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.ini")); // ../ can be multiply to infinity, no impact, we just need to have enough to reach the root request.setAdditionalHeader("Accept-Language", "../../../../../../../../../../../../windows/win"); diff --git a/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java b/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java index 4d9e1bb5fd04..4c3f5d28b6a2 100644 --- a/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java +++ b/test/src/test/java/jenkins/security/stapler/StaplerAbstractTest.java @@ -177,7 +177,7 @@ protected void assertFieldRequestWasNotBlocked() { protected void assertReachable(String url, HttpMethod method) throws IOException { try { - Page page = wc.getPage(new WebRequest(new URI(j.getURL(), url), method)); + Page page = wc.getPage(new WebRequest(new URL(j.getURL(), url), method)); assertEquals(200, page.getWebResponse().getStatusCode()); assertThat(page.getWebResponse().getContentAsString(), startsWith("ok")); @@ -202,7 +202,7 @@ protected void assertReachableWithSettings(WebRequest request) throws IOExceptio protected void assertReachableWithoutOk(String url) throws IOException { try { - Page page = wc.getPage(new URI(j.getURL(), url)); + Page page = wc.getPage(new URL(j.getURL(), url)); assertEquals(200, page.getWebResponse().getStatusCode()); } catch (FailingHttpStatusCodeException e) { throw new AssertionError("Url " + url + " should be reachable, received " + e.getMessage() + " (" + e.getStatusCode() + ") instead.", e); @@ -210,7 +210,7 @@ protected void assertReachableWithoutOk(String url) throws IOException { } protected void assertNotReachable(String url) throws IOException { - FailingHttpStatusCodeException e = assertThrows("Url " + url + " is reachable but should not be, a not-found error is expected", FailingHttpStatusCodeException.class, () -> wc.getPage(new URI(j.getURL(), url))); + FailingHttpStatusCodeException e = assertThrows("Url " + url + " is reachable but should not be, a not-found error is expected", FailingHttpStatusCodeException.class, () -> wc.getPage(new URL(j.getURL(), url))); assertEquals("Url " + url + " returns an error different from 404", 404, e.getResponse().getStatusCode()); } } diff --git a/war/src/main/java/executable/Main.java b/war/src/main/java/executable/Main.java index 3ae4c52d5bfe..1a537e46825e 100644 --- a/war/src/main/java/executable/Main.java +++ b/war/src/main/java/executable/Main.java @@ -278,7 +278,7 @@ public static void main(String[] args) throws IllegalAccessException { // locate the Winstone launcher ClassLoader cl; try { - cl = new URIClassLoader(new URI[] {tmpJar.toURI().toURL()}); + cl = new URLClassLoader(new URL[] {tmpJar.toURI().toURL()}); } catch (MalformedURLException e) { throw new UncheckedIOException(e); } From d20efb70326669c50221e7c14a71d53d1737ad4a Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Thu, 21 Sep 2023 22:52:03 +0530 Subject: [PATCH 05/11] JENKINS-72028; deprecated URL instantiation applied --- cli/src/main/java/hudson/cli/CLI.java | 7 ++-- cli/src/main/java/hudson/cli/SSHCLI.java | 21 +++++----- core/src/main/java/hudson/FilePath.java | 7 +++- core/src/main/java/hudson/Functions.java | 4 +- core/src/main/java/hudson/Main.java | 9 +++-- core/src/main/java/hudson/PluginManager.java | 6 ++- .../java/hudson/TcpSlaveAgentListener.java | 7 +++- .../java/hudson/cli/InstallPluginCommand.java | 3 +- .../java/hudson/model/DownloadService.java | 3 +- .../main/java/hudson/model/UpdateCenter.java | 38 ++++++++++++++----- .../main/java/hudson/model/UpdateSite.java | 7 +++- .../tools/DownloadFromUrlInstaller.java | 22 +++++++---- .../hudson/tools/ZipExtractionInstaller.java | 8 +++- .../java/hudson/util/FormFieldValidator.java | 6 ++- .../java/jenkins/install/SetupWizard.java | 3 +- .../security/ResourceDomainConfiguration.java | 10 ++++- .../test/java/hudson/PluginManagerTest.java | 8 +++- .../jenkins/model/JenkinsGetRootUrlTest.java | 3 +- .../routines/DomainValidatorTest.java | 11 ++++-- .../hudson/TcpSlaveAgentListenerTest.java | 5 ++- .../hudson/console/ConsoleAnnotatorTest.java | 9 ++++- .../HudsonHomeDiskUsageMonitorTest.java | 7 ++-- .../test/java/hudson/jobs/CreateItemTest.java | 13 ++++--- .../hudson/markup/MarkupFormatterTest.java | 3 +- .../hudson/model/AbstractProjectTest.java | 5 ++- .../model/DirectlyModifiableViewTest.java | 3 +- .../model/DirectoryBrowserSupportTest.java | 12 +++++- .../test/java/hudson/model/HudsonTest.java | 3 +- .../src/test/java/hudson/model/ItemsTest.java | 9 +++-- .../src/test/java/hudson/model/QueueTest.java | 3 +- .../java/hudson/model/UpdateCenterTest.java | 3 +- .../java/hudson/model/UserRestartTest.java | 6 ++- .../HudsonPrivateSecurityRealmTest.java | 3 +- .../security/csrf/DefaultCrumbIssuerTest.java | 3 +- .../tools/ZipExtractionInstallerTest.java | 3 +- .../util/RobustReflectionConverterTest.java | 5 ++- .../java/jenkins/model/AssetManagerTest.java | 3 +- .../test/java/jenkins/model/JenkinsTest.java | 7 ++-- .../security/ApiTokenPropertyTest.java | 3 +- .../BasicHeaderApiTokenAuthenticatorTest.java | 14 ++++--- .../jenkins/security/ResourceDomainTest.java | 6 ++- .../jenkins/security/Security2278Test.java | 6 ++- .../jenkins/security/Security2761Test.java | 4 +- .../jenkins/security/Security637Test.java | 5 ++- .../apitoken/ApiTokenStatsRestartTest.java | 3 +- .../security/apitoken/ApiTokenStatsTest.java | 4 +- .../seed/UserSeedChangeListenerTest.java | 4 +- .../seed/UserSeedPropertyRestartTest.java | 4 +- .../security/seed/UserSeedPropertyTest.java | 4 +- .../security/stapler/Security400Test.java | 17 +++++---- .../security/stapler/Security914Test.java | 5 ++- 51 files changed, 246 insertions(+), 121 deletions(-) diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 9aee43f6f9a0..466ac032aafd 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -39,6 +39,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; @@ -306,7 +307,7 @@ public boolean verify(String s, SSLSession sslSession) { } CLIConnectionFactory factory = new CLIConnectionFactory(); - String userInfo = new URL(url).getUserInfo(); + String userInfo = new URI(url).getUserInfo(); if (userInfo != null) { factory = factory.basicAuth(userInfo); } else if (auth != null) { @@ -386,9 +387,9 @@ public void close() throws IOException { } } - private static int plainHttpConnection(String url, List args, CLIConnectionFactory factory) throws IOException, InterruptedException { + private static int plainHttpConnection(String url, List args, CLIConnectionFactory factory) throws IOException, InterruptedException, URISyntaxException { LOGGER.log(FINE, "Trying to connect to {0} via plain protocol over HTTP", url); - FullDuplexHttpStream streams = new FullDuplexHttpStream(new URL(url), "cli?remoting=false", factory.authorization); + FullDuplexHttpStream streams = new FullDuplexHttpStream(new URI(url).toURL(), "cli?remoting=false", factory.authorization); try (ClientSideImpl connection = new ClientSideImpl(new PlainCLIProtocol.FramedOutput(streams.getOutputStream()))) { connection.start(args); InputStream is = streams.getInputStream(); diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 3d6ea7c42530..54a3a34733ea 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -29,8 +29,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.util.QuotedStringTokenizer; import java.io.IOException; -import java.net.SocketAddress; import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.security.KeyPair; @@ -60,9 +61,14 @@ */ class SSHCLI { - static int sshConnection(String jenkinsUrl, String user, List args, PrivateKeyProvider provider, final boolean strictHostKey) throws IOException { + static int sshConnection(String jenkinsUrl, String user, List args, PrivateKeyProvider provider, final boolean strictHostKey) throws IOException, URISyntaxException { Logger.getLogger(SecurityUtils.class.getName()).setLevel(Level.WARNING); // suppress: BouncyCastle not registered, using the default JCE provider - URL url = new URL(jenkinsUrl + "login"); + URL url = null; + try { + url = new URI(jenkinsUrl + "login").toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } URLConnection conn = openConnection(url); CLI.verifyJenkinsConnection(conn); String endpointDescription = conn.getHeaderField("X-SSH-Endpoint"); @@ -86,12 +92,9 @@ static int sshConnection(String jenkinsUrl, String user, List args, Priv try (SshClient client = SshClient.setUpDefaultClient()) { - KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier(new ServerKeyVerifier() { - @Override - public boolean verifyServerKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) { - CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString()); - return !strictHostKey; - } + KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier((clientSession, remoteAddress, serverKey) -> { + CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString()); + return !strictHostKey; }, true); client.setServerKeyVerifier(verifier); diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index cdc057ef9c54..bf5662bcf5a8 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -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; @@ -1065,6 +1066,8 @@ private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListen return true; } catch (IOException e) { throw new IOException("Failed to install " + archive + " to " + remote, e); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } } @@ -3337,8 +3340,8 @@ private int findSeparator(String pattern) { @Restricted(NoExternalUse.class) static class UrlFactory { - public URL newURL(String location) throws MalformedURLException { - return new URL(location); + public URL newURL(String location) throws MalformedURLException, URISyntaxException { + return new URI(location).toURL(); } } diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 7f3411406780..dad30b25066f 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1939,12 +1939,14 @@ 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) { // fall back to HTTP request + } catch (URISyntaxException e) { + throw new RuntimeException(e); } return Stapler.getCurrentRequest().getServerName(); } diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java index 625fef0c52ee..accae4a9f249 100644 --- a/core/src/main/java/hudson/Main.java +++ b/core/src/main/java/hudson/Main.java @@ -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; @@ -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).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 @@ -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")); @@ -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. diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index 5d64485cfa1b..5cf879746eb3 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -1848,7 +1848,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()); } } @@ -1962,7 +1962,7 @@ 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()); } @@ -1972,6 +1972,8 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl } } catch (MalformedURLException e) { return FormValidation.error(e.getMessage()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } } return FormValidation.ok(); diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index 3936071de2ef..2e190e1bacbb 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -41,7 +41,8 @@ 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; @@ -135,9 +136,11 @@ public String getAdvertisedHost() { return CLI_HOST_NAME; } try { - return new URL(Jenkins.get().getRootUrl()).getHost(); + return new URI(Jenkins.get().getRootUrl()).toURL().getHost(); } catch (MalformedURLException e) { throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } } diff --git a/core/src/main/java/hudson/cli/InstallPluginCommand.java b/core/src/main/java/hudson/cli/InstallPluginCommand.java index cc9d3b59f91d..140c02192e73 100644 --- a/core/src/main/java/hudson/cli/InstallPluginCommand.java +++ b/core/src/main/java/hudson/cli/InstallPluginCommand.java @@ -33,6 +33,7 @@ import hudson.util.VersionNumber; import java.io.File; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; @@ -104,7 +105,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 diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index b9a5610c4e35..5a5e8b0481da 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -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; @@ -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); diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 7ea06f20191e..89675616f00a 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -66,6 +66,8 @@ import java.net.HttpRetryException; 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.net.UnknownHostException; @@ -1206,8 +1208,8 @@ public UpdateCenterConfiguration() { * that is assumed to be always available. * @throws IOException if a connection can't be established */ - public void checkConnection(ConnectionCheckJob job, String connectionCheckUrl) throws IOException { - testConnection(new URL(connectionCheckUrl)); + public void checkConnection(ConnectionCheckJob job, String connectionCheckUrl) throws IOException, URISyntaxException { + testConnection(new URI(connectionCheckUrl).toURL()); } /** @@ -1217,7 +1219,7 @@ public void checkConnection(ConnectionCheckJob job, String connectionCheckUrl) t * @param updateCenterUrl A sting containing the URL of the update center host. * @throws IOException if a connection to the update center server can't be established. */ - public void checkUpdateCenter(ConnectionCheckJob job, String updateCenterUrl) throws IOException { + public void checkUpdateCenter(ConnectionCheckJob job, String updateCenterUrl) throws IOException, URISyntaxException { testConnection(toUpdateCenterCheckUrl(updateCenterUrl)); } @@ -1227,12 +1229,12 @@ public void checkUpdateCenter(ConnectionCheckJob job, String updateCenterUrl) th * @return the converted URL. * @throws MalformedURLException if the supplied URL is malformed. */ - static URL toUpdateCenterCheckUrl(String updateCenterUrl) throws MalformedURLException { + static URL toUpdateCenterCheckUrl(String updateCenterUrl) throws MalformedURLException, URISyntaxException { URL url; if (updateCenterUrl.startsWith("http://") || updateCenterUrl.startsWith("https://")) { - url = new URL(updateCenterUrl + (updateCenterUrl.indexOf('?') == -1 ? "?uctest" : "&uctest")); + url = new URI(updateCenterUrl + (updateCenterUrl.indexOf('?') == -1 ? "?uctest" : "&uctest")).toURL(); } else { - url = new URL(updateCenterUrl); + url = new URI(updateCenterUrl).toURL(); } return url; } @@ -2193,7 +2195,11 @@ public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth, bool @Override protected URL getURL() throws MalformedURLException { - return new URL(plugin.url); + try { + return new URI(plugin.url).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } @Override @@ -2422,7 +2428,11 @@ public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) { @Override protected URL getURL() throws MalformedURLException { - return new URL(plugin.url); + try { + return new URI(plugin.url).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } @Override @@ -2517,7 +2527,11 @@ protected URL getURL() throws MalformedURLException { if (site == null) { throw new MalformedURLException("no update site defined"); } - return new URL(site.getData().core.url); + try { + return new URI(site.getData().core.url).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } @Override @@ -2564,7 +2578,11 @@ protected URL getURL() throws MalformedURLException { if (site == null) { throw new MalformedURLException("no update site defined"); } - return new URL(site.getData().core.url); + try { + return new URI(site.getData().core.url).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } @Override diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index 1b5b734c7be6..e6fb6b3e525e 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -47,6 +47,7 @@ import java.io.File; import java.io.IOException; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -215,7 +216,11 @@ public long getDataTimestamp() { @Restricted(NoExternalUse.class) public @NonNull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException { - return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8))), signatureCheck); + try { + return updateData(DownloadService.loadJSON(new URI(getUrl() + "?id=" + URLEncoder.encode(getId(), StandardCharsets.UTF_8) + "&version=" + URLEncoder.encode(Jenkins.VERSION, StandardCharsets.UTF_8)).toURL()), signatureCheck); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } private FormValidation updateData(String json, boolean signatureCheck) diff --git a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java index 5d7f4c0c024f..83501fe2a3c8 100644 --- a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java +++ b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java @@ -6,6 +6,8 @@ import hudson.model.TaskListener; import hudson.slaves.NodeSpecific; import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; @@ -74,14 +76,18 @@ public FilePath performInstallation(ToolInstallation tool, Node node, TaskListen if (isUpToDate(expected, inst)) return expected; - if (expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { - expected.child(".timestamp").delete(); // we don't use the timestamp - FilePath base = findPullUpDirectory(expected); - if (base != null && base != expected) - base.moveAllChildrenTo(expected); - // leave a record for the next up-to-date check - expected.child(".installedFrom").write(inst.url, "UTF-8"); - expected.act(new ZipExtractionInstaller.ChmodRecAPlusX()); + try { + if (expected.installIfNecessaryFrom(new URI(inst.url).toURL(), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { + expected.child(".timestamp").delete(); // we don't use the timestamp + FilePath base = findPullUpDirectory(expected); + if (base != null && base != expected) + base.moveAllChildrenTo(expected); + // leave a record for the next up-to-date check + expected.child(".installedFrom").write(inst.url, "UTF-8"); + expected.act(new ZipExtractionInstaller.ChmodRecAPlusX()); + } + } catch (URISyntaxException e) { + throw new RuntimeException(e); } return expected; diff --git a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java index 1e1c171f6a95..601e26762f65 100644 --- a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java +++ b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java @@ -83,8 +83,12 @@ public String getSubdir() { @Override public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath dir = preferredLocation(tool, node); - if (dir.installIfNecessaryFrom(new URL(url), log, "Unpacking " + url + " to " + dir + " on " + node.getDisplayName())) { - dir.act(new ChmodRecAPlusX()); + try { + if (dir.installIfNecessaryFrom(new URI(url).toURL(), log, "Unpacking " + url + " to " + dir + " on " + node.getDisplayName())) { + dir.act(new ChmodRecAPlusX()); + } + } catch (URISyntaxException e) { + throw new RuntimeException(e); } if (subdir == null) { return dir; diff --git a/core/src/main/java/hudson/util/FormFieldValidator.java b/core/src/main/java/hudson/util/FormFieldValidator.java index 9bf1287b9e01..cdcb8c2c31e9 100644 --- a/core/src/main/java/hudson/util/FormFieldValidator.java +++ b/core/src/main/java/hudson/util/FormFieldValidator.java @@ -40,6 +40,8 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.Locale; @@ -335,7 +337,7 @@ protected void check() throws IOException, ServletException { if (!value.endsWith("/")) value += '/'; try { - URL url = new URL(value); + URL url = new URI(value).toURL(); HttpURLConnection con = openConnection(url); con.connect(); if (con.getResponseCode() != 200 @@ -347,6 +349,8 @@ protected void check() throws IOException, ServletException { ok(); } catch (IOException e) { handleIOException(value, e); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } } diff --git a/core/src/main/java/jenkins/install/SetupWizard.java b/core/src/main/java/jenkins/install/SetupWizard.java index 126aaf0d11bb..274b3a4ba663 100644 --- a/core/src/main/java/jenkins/install/SetupWizard.java +++ b/core/src/main/java/jenkins/install/SetupWizard.java @@ -29,6 +29,7 @@ import java.io.IOException; import java.net.HttpRetryException; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; @@ -561,7 +562,7 @@ public JSONArray getPlatformPluginUpdates() { suggestedPluginUrl = suggestedPluginUrl + (suggestedPluginUrl.contains("?") ? "&" : "?") + "version=" + version; } try { - URLConnection connection = ProxyConfiguration.open(new URL(suggestedPluginUrl)); + URLConnection connection = ProxyConfiguration.open(new URI(suggestedPluginUrl).toURL()); try { String initialPluginJson = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8); diff --git a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java index f5465ca4b61e..f51f4371df32 100644 --- a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java +++ b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java @@ -34,6 +34,8 @@ import java.io.IOException; 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.StandardCharsets; @@ -112,9 +114,11 @@ private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlin URL resourceRootUrl; try { - resourceRootUrl = new URL(resourceRootUrlString); + resourceRootUrl = new URI(resourceRootUrlString).toURL(); } catch (MalformedURLException ex) { return FormValidation.error(Messages.ResourceDomainConfiguration_Invalid()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } String resourceRootUrlHost = resourceRootUrl.getHost(); @@ -222,7 +226,7 @@ public static boolean isResourceRequest(HttpServletRequest req) { } String resourceRootUrl = get().getUrl(); try { - URL url = new URL(resourceRootUrl); + URL url = new URI(resourceRootUrl).toURL(); String resourceRootHost = url.getHost(); if (!resourceRootHost.equalsIgnoreCase(req.getServerName())) { @@ -243,6 +247,8 @@ public static boolean isResourceRequest(HttpServletRequest req) { } catch (MalformedURLException ex) { // the URL here cannot be so broken that we cannot call `new URL(String)` on it... return false; + } catch (URISyntaxException e) { + throw new RuntimeException(e); } return true; } diff --git a/core/src/test/java/hudson/PluginManagerTest.java b/core/src/test/java/hudson/PluginManagerTest.java index 580808c8d56d..f3ffe001e15a 100644 --- a/core/src/test/java/hudson/PluginManagerTest.java +++ b/core/src/test/java/hudson/PluginManagerTest.java @@ -40,6 +40,8 @@ import java.io.File; import java.io.IOException; import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -206,7 +208,11 @@ private File createHpiWithManifest() throws IOException { private URL toManifestUrl(File jarFile) throws MalformedURLException { final String manifestPath = "META-INF/MANIFEST.MF"; - return new URL("jar:" + jarFile.toURI().toURL() + "!/" + manifestPath); + try { + return new URI("jar:" + jarFile.toURI().toURL() + "!/" + manifestPath).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } private static class FormValidationMatcher extends TypeSafeDiagnosingMatcher { diff --git a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java index 620616a15081..06d9b2224c91 100644 --- a/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java +++ b/core/src/test/java/jenkins/model/JenkinsGetRootUrlTest.java @@ -31,6 +31,7 @@ import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; +import java.net.URI; import java.net.URL; import org.junit.Before; import org.junit.Test; @@ -247,7 +248,7 @@ private URL getUrl(final String realUrl) { try { - return new URL(realUrl); + return new URI(realUrl).toURL(); } catch (Exception ex) { throw new RuntimeException(ex); diff --git a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java index 3e1631692c6d..11235ee46d45 100644 --- a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java +++ b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java @@ -25,9 +25,7 @@ import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.net.HttpURLConnection; -import java.net.IDN; -import java.net.URL; +import java.net.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; @@ -502,7 +500,12 @@ private static long download(File f, String tldurl, long timestamp) throws IOExc } else { modTime = 0; } - HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection(); + HttpURLConnection hc = null; + try { + hc = (HttpURLConnection) new URI(tldurl).toURL().openConnection(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } if (modTime > 0) { SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); //Sun, 06 Nov 1994 08:49:37 GMT String since = sdf.format(new Date(modTime)); diff --git a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java index 8d6f13d9807a..38d9e537cc23 100644 --- a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java +++ b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java @@ -6,6 +6,7 @@ import static org.junit.Assert.assertEquals; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import jenkins.model.Jenkins; import org.htmlunit.Page; @@ -40,12 +41,12 @@ public void diagnostics() throws Exception { int p = r.jenkins.getTcpSlaveAgentListener().getPort(); WebClient wc = r.createWebClient(); - TextPage text = wc.getPage(new URL("http://localhost:" + p + "/")); + TextPage text = wc.getPage(new URI("http://localhost:" + p + "/").toURL()); String c = text.getContent(); assertThat(c, containsString(Jenkins.VERSION)); wc.setThrowExceptionOnFailingStatusCode(false); - Page page = wc.getPage(new URL("http://localhost:" + p + "/xxx")); + Page page = wc.getPage(new URI("http://localhost:" + p + "/xxx").toURL()); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, page.getWebResponse().getStatusCode()); } } diff --git a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java index 60b08b0936de..4df8ac3a0683 100644 --- a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java +++ b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java @@ -24,6 +24,8 @@ import hudson.triggers.SCMTrigger; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; @@ -149,7 +151,12 @@ class ProgressiveLogClient { } String next() throws IOException { - WebRequest req = new WebRequest(new URL(r.getURL() + run.getUrl() + "/logText/progressiveHtml" + (start != null ? "?start=" + start : ""))); + WebRequest req = null; + try { + req = new WebRequest(new URI(r.getURL() + run.getUrl() + "/logText/progressiveHtml" + (start != null ? "?start=" + start : "")).toURL()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } req.setEncodingType(null); Map headers = new HashMap(); if (consoleAnnotator != null) diff --git a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java index f21f5088128d..e986b02efede 100644 --- a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java @@ -9,6 +9,7 @@ import hudson.security.GlobalMatrixAuthorizationStrategy; import java.io.IOException; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.util.List; import jenkins.model.Jenkins; @@ -71,7 +72,7 @@ public void noAccessForNonAdmin() throws Exception { User bob = User.getById("bob", true); User administrator = User.getById("administrator", true); - WebRequest request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act").toURL(), HttpMethod.POST); NameValuePair param = new NameValuePair("no", "true"); request.setRequestParameters(List.of(param)); @@ -83,12 +84,12 @@ public void noAccessForNonAdmin() throws Exception { assertTrue(mon.isEnabled()); - WebRequest requestReadOnly = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET); + WebRequest requestReadOnly = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull").toURL(), HttpMethod.GET); p = wc.getPage(requestReadOnly); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, p.getWebResponse().getStatusCode()); wc.withBasicApiToken(administrator); - request = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act"), HttpMethod.POST); + request = new WebRequest(new URI(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull/act").toURL(), HttpMethod.POST); request.setRequestParameters(List.of(param)); p = wc.getPage(request); assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/jobs/CreateItemTest.java b/test/src/test/java/hudson/jobs/CreateItemTest.java index c8d511ce168d..df8c577e30dc 100644 --- a/test/src/test/java/hudson/jobs/CreateItemTest.java +++ b/test/src/test/java/hudson/jobs/CreateItemTest.java @@ -35,6 +35,7 @@ import hudson.model.ItemGroup; import hudson.model.listeners.ItemListener; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.text.MessageFormat; import org.htmlunit.HttpMethod; @@ -71,9 +72,9 @@ public void testCreateItemFromCopy() throws Exception { rule.createFreeStyleProject(sourceJobName); String newJobName = "newJob"; - URL apiURL = new URL(MessageFormat.format( + URL apiURL = new URI(MessageFormat.format( "{0}createItem?mode=copy&from={1}&name={2}", - rule.getURL().toString(), sourceJobName, newJobName)); + rule.getURL().toString(), sourceJobName, newJobName)).toURL(); WebRequest request = new WebRequest(apiURL, HttpMethod.POST); deleteContentTypeHeader(request); @@ -95,9 +96,9 @@ public void vetoCreateItemFromCopy() throws Exception { rule.createFreeStyleProject(sourceJobName); String newJobName = "newJob"; - URL apiURL = new URL(MessageFormat.format( + URL apiURL = new URI(MessageFormat.format( "{0}createItem?mode=copy&from={1}&name={2}", - rule.getURL().toString(), sourceJobName, newJobName)); + rule.getURL().toString(), sourceJobName, newJobName)).toURL(); WebRequest request = new WebRequest(apiURL, HttpMethod.POST); deleteContentTypeHeader(request); @@ -124,10 +125,10 @@ public void createWithFolderPaths() throws Exception { JenkinsRule.WebClient wc = rule.createWebClient(); - wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST)); + wc.getPage(new WebRequest(new URI(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p").toURL(), HttpMethod.POST)); assertNotNull(d2.getItem("p2")); - wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST)); + wc.getPage(new WebRequest(new URI(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p").toURL(), HttpMethod.POST)); assertNotNull(d2.getItem("p3")); } diff --git a/test/src/test/java/hudson/markup/MarkupFormatterTest.java b/test/src/test/java/hudson/markup/MarkupFormatterTest.java index f5e0e05095e5..e5dde33db4bd 100644 --- a/test/src/test/java/hudson/markup/MarkupFormatterTest.java +++ b/test/src/test/java/hudson/markup/MarkupFormatterTest.java @@ -33,6 +33,7 @@ import hudson.security.HudsonPrivateSecurityRealm; import java.io.IOException; import java.io.Writer; +import java.net.URI; import java.net.URL; import org.htmlunit.HttpMethod; import org.htmlunit.Page; @@ -104,7 +105,7 @@ public void security2153RequiresPOST() throws Exception { @Issue("SECURITY-2153") public void security2153SetsCSP() throws Exception { final JenkinsRule.WebClient wc = j.createWebClient(); - final Page htmlPage = wc.getPage(wc.addCrumb(new WebRequest(new URL(j.jenkins.getRootUrl() + "/markupFormatter/previewDescription?text=lolwut"), HttpMethod.POST))); + final Page htmlPage = wc.getPage(wc.addCrumb(new WebRequest(new URI(j.jenkins.getRootUrl() + "/markupFormatter/previewDescription?text=lolwut").toURL(), HttpMethod.POST))); final WebResponse response = htmlPage.getWebResponse(); assertEquals(200, response.getStatusCode()); assertThat(response.getContentAsString(), containsString("lolwut")); diff --git a/test/src/test/java/hudson/model/AbstractProjectTest.java b/test/src/test/java/hudson/model/AbstractProjectTest.java index 2da8fc430448..d4108e3a4c93 100644 --- a/test/src/test/java/hudson/model/AbstractProjectTest.java +++ b/test/src/test/java/hudson/model/AbstractProjectTest.java @@ -56,6 +56,7 @@ import hudson.util.StreamTaskListener; import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -140,7 +141,7 @@ public void wipeWorkspaceProtected() throws Exception { // make sure that the action link is protected JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - Page page = wc.getPage(new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST)); + Page page = wc.getPage(new WebRequest(new URI(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace").toURL(), HttpMethod.POST)); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode()); } @@ -323,7 +324,7 @@ public void deleteRedirect() throws Exception { private String deleteRedirectTarget(String job) throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); String base = wc.getContextPath(); - String loc = wc.getPage(wc.addCrumb(new WebRequest(new URL(base + job + "/doDelete"), HttpMethod.POST))).getUrl().toString(); + String loc = wc.getPage(wc.addCrumb(new WebRequest(new URI(base + job + "/doDelete").toURL(), HttpMethod.POST))).getUrl().toString(); assert loc.startsWith(base) : loc; return loc.substring(base.length()); } diff --git a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java index aab9da2cfe65..b285f81963f2 100644 --- a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java +++ b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java @@ -29,6 +29,7 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; +import java.net.URI; import java.net.URL; import org.hamcrest.Matchers; import org.htmlunit.HttpMethod; @@ -188,7 +189,7 @@ private Page doPost(View view, String path) throws Exception { WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); WebRequest req = new WebRequest( - new URL(j.jenkins.getRootUrl() + view.getUrl() + path), + new URI(j.jenkins.getRootUrl() + view.getUrl() + path).toURL(), HttpMethod.POST ); diff --git a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java index 7b1bbdb7c9bd..df22343f7a67 100644 --- a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java +++ b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java @@ -482,7 +482,11 @@ public InputStream open() throws IOException { @Override public URL toExternalURL() throws IOException { - return new URL(Jenkins.get().getRootUrl() + "files/" + hash); + try { + return new URI(Jenkins.get().getRootUrl() + "files/" + hash).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } }; return new VirtualFile() { // the root @@ -1454,7 +1458,11 @@ public InputStream open() throws IOException { @Override public URL toExternalURL() throws IOException { - return new URL(Jenkins.get().getRootUrl() + "files/" + hash); + try { + return new URI(Jenkins.get().getRootUrl() + "files/" + hash).toURL(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } } }; return new VirtualFile() { // the root diff --git a/test/src/test/java/hudson/model/HudsonTest.java b/test/src/test/java/hudson/model/HudsonTest.java index a4fff0108458..822fd28eaf04 100644 --- a/test/src/test/java/hudson/model/HudsonTest.java +++ b/test/src/test/java/hudson/model/HudsonTest.java @@ -39,6 +39,7 @@ import hudson.tasks.BuildStep; import java.lang.reflect.Field; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.util.List; import jenkins.model.Jenkins; @@ -177,7 +178,7 @@ public void deleteHudsonComputer() throws Exception { wc.setThrowExceptionOnFailingStatusCode(false); // try to delete it by hitting the final URL directly - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "computer/(built-in)/doDelete"), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "computer/(built-in)/doDelete").toURL(), HttpMethod.POST); page = wc.getPage(wc.addCrumb(req)); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode()); diff --git a/test/src/test/java/hudson/model/ItemsTest.java b/test/src/test/java/hudson/model/ItemsTest.java index 37c0befc3081..75e81101820b 100644 --- a/test/src/test/java/hudson/model/ItemsTest.java +++ b/test/src/test/java/hudson/model/ItemsTest.java @@ -41,6 +41,7 @@ import java.io.ByteArrayInputStream; import java.io.File; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -228,7 +229,7 @@ private enum OverwriteTactic { // redirect perversely counts as a failure .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject").toURL(), HttpMethod.POST)).getWebResponse(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { throw new FailingHttpStatusCodeException(webResponse); } @@ -241,7 +242,7 @@ private enum OverwriteTactic { JenkinsRule.WebClient wc = wc(r) .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe").toURL(), HttpMethod.POST)).getWebResponse(); r.jenkins.getItem("dupe").delete(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { throw new FailingHttpStatusCodeException(webResponse); @@ -252,7 +253,7 @@ private enum OverwriteTactic { REST_CREATE { @Override void run(JenkinsRule r, String target) throws Exception { JenkinsRule.WebClient wc = wc(r); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "createItem?name=" + target).toURL(), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/xml"); req.setRequestBody(""); wc.getPage(req); @@ -265,7 +266,7 @@ private enum OverwriteTactic { JenkinsRule.WebClient wc = wc(r) .withRedirectEnabled(false) .withThrowExceptionOnFailingStatusCode(false); - WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse(); + WebResponse webResponse = wc.getPage(new WebRequest(new URI(wc.getContextPath() + "job/dupe/doRename?newName=" + target).toURL(), HttpMethod.POST)).getWebResponse(); if (webResponse.getStatusCode() != HttpURLConnection.HTTP_MOVED_TEMP) { r.jenkins.getItem("dupe").delete(); throw new FailingHttpStatusCodeException(webResponse); diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index e31e2acdd1c9..facc8cb0ab1b 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -83,6 +83,7 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -1199,7 +1200,7 @@ private void checkCancelOperationUsingUrl(Function urlProvid Queue.Item currentOne = items[0]; assertFalse(currentOne.getFuture().isCancelled()); - WebRequest request = new WebRequest(new URL(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(r.getURL() + urlProvider.apply(currentOne)).toURL(), HttpMethod.POST); { // user without right cannot cancel JenkinsRule.WebClient wc = r.createWebClient() diff --git a/test/src/test/java/hudson/model/UpdateCenterTest.java b/test/src/test/java/hudson/model/UpdateCenterTest.java index 998e9badd67e..57ecf1d2d8bd 100644 --- a/test/src/test/java/hudson/model/UpdateCenterTest.java +++ b/test/src/test/java/hudson/model/UpdateCenterTest.java @@ -31,6 +31,7 @@ import static org.junit.Assume.assumeNoException; import java.io.ByteArrayInputStream; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.cert.CertificateFactory; @@ -58,7 +59,7 @@ public class UpdateCenterTest { } private void doData(String location) throws Exception { - URL url = new URL(location); + URL url = new URI(location).toURL(); String jsonp = DownloadService.loadJSON(url); JSONObject json = JSONObject.fromObject(jsonp); diff --git a/test/src/test/java/hudson/model/UserRestartTest.java b/test/src/test/java/hudson/model/UserRestartTest.java index 95641933beed..928edbc8c68d 100644 --- a/test/src/test/java/hudson/model/UserRestartTest.java +++ b/test/src/test/java/hudson/model/UserRestartTest.java @@ -33,6 +33,8 @@ import hudson.FilePath; import hudson.tasks.Mailer; + +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; @@ -115,7 +117,7 @@ public void legacyConfigMoveCannotEscapeUserFolder() throws Throwable { JenkinsRule.WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(r.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(r.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("..", "any-password")); wc.getPage(request); } @@ -123,7 +125,7 @@ public void legacyConfigMoveCannotEscapeUserFolder() throws Throwable { JenkinsRule.WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(r.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(r.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("../users/..", "any-password")); wc.getPage(request); } diff --git a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java index 9883b0680843..25d1dd18cd01 100644 --- a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java +++ b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java @@ -43,6 +43,7 @@ import hudson.model.User; import hudson.security.pages.SignupPage; import java.lang.reflect.Field; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -344,7 +345,7 @@ private void createFirstAccount(String login) throws Exception { info.password2 = login; info.fullname = StringUtils.capitalize(login); - WebRequest request = new WebRequest(new URL(wc.getContextPath() + "securityRealm/createFirstAccount"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(wc.getContextPath() + "securityRealm/createFirstAccount").toURL(), HttpMethod.POST); request.setRequestParameters(Arrays.asList( new NameValuePair("username", login), new NameValuePair("password1", login), diff --git a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java index b6b417f8dc6f..b2e9f3abf5cb 100644 --- a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java +++ b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java @@ -17,6 +17,7 @@ import hudson.model.User; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import javax.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; @@ -303,7 +304,7 @@ public void twoRequestsWithoutSessionGetDifferentCrumbs() throws Exception { } private WebRequest createRequestForJobCreation(String jobName) throws Exception { - WebRequest req = new WebRequest(new URL(r.getURL() + "createItem?name=" + jobName), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(r.getURL() + "createItem?name=" + jobName).toURL(), HttpMethod.POST); req.setAdditionalHeader("Content-Type", "application/xml"); req.setRequestBody(""); return req; diff --git a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java index 72210eec3362..a6db76638aa4 100644 --- a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java +++ b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java @@ -28,6 +28,7 @@ import hudson.model.User; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -65,7 +66,7 @@ public void onlyAdminCanReachTheDoCheck() throws Exception { User.getById(ADMIN, true); User.getById(USER, true); - WebRequest request = new WebRequest(new URL(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "descriptorByName/hudson.tools.ZipExtractionInstaller/checkUrl").toURL(), HttpMethod.POST); request.setRequestBody(URLEncoder.encode("value=https://www.google.com", StandardCharsets.UTF_8)); JenkinsRule.WebClient adminWc = j.createWebClient(); diff --git a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java index da667a80d802..8b7d1a4be9d4 100644 --- a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java +++ b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java @@ -44,6 +44,7 @@ import hudson.security.ACL; import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.util.Map; @@ -206,7 +207,7 @@ public void testRestInterfaceFailure() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); WebClient wc = r.createWebClient(); wc.withBasicApiToken("test"); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())).toURL(), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD)); wc.getPage(req); @@ -237,7 +238,7 @@ public void testRestInterfaceFailure() throws Exception { WebClient wc = r.createWebClient() .withThrowExceptionOnFailingStatusCode(false); wc.withBasicApiToken("test"); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())).toURL(), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue")); diff --git a/test/src/test/java/jenkins/model/AssetManagerTest.java b/test/src/test/java/jenkins/model/AssetManagerTest.java index d00541d4a554..9683d6479bfd 100644 --- a/test/src/test/java/jenkins/model/AssetManagerTest.java +++ b/test/src/test/java/jenkins/model/AssetManagerTest.java @@ -27,6 +27,7 @@ import static org.junit.Assert.assertEquals; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import org.junit.Rule; import org.junit.Test; @@ -41,7 +42,7 @@ public class AssetManagerTest { @Test @Issue("JENKINS-58736") public void emptyAssetDoesNotThrowError() throws Exception { - URL url = new URL(j.getURL() + "assets"); + URL url = new URI(j.getURL() + "assets").toURL(); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpCon.getResponseCode()); } diff --git a/test/src/test/java/jenkins/model/JenkinsTest.java b/test/src/test/java/jenkins/model/JenkinsTest.java index 5c0c9acedbb2..5c79f994b0c1 100644 --- a/test/src/test/java/jenkins/model/JenkinsTest.java +++ b/test/src/test/java/jenkins/model/JenkinsTest.java @@ -70,6 +70,7 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.Socket; +import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collections; @@ -326,11 +327,11 @@ public void testDoScript() throws Exception { wc.goTo("script"); wc.assertFails("script?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD); assertNull(System.getProperty("hack")); - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "script?script=System.setProperty('hack','me')"), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "script?script=System.setProperty('hack','me')").toURL(), HttpMethod.POST); wc.getPage(req); assertEquals("me", System.getProperty("hack")); wc.assertFails("scriptText?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD); - req = new WebRequest(new URL(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')"), HttpMethod.POST); + req = new WebRequest(new URI(wc.getContextPath() + "scriptText?script=System.setProperty('huck','you')").toURL(), HttpMethod.POST); wc.getPage(req); assertEquals("you", System.getProperty("huck")); @@ -380,7 +381,7 @@ public void testDoEval() throws Exception { } private Page eval(WebClient wc) throws Exception { - WebRequest req = new WebRequest(new URL(wc.getContextPath() + "eval"), HttpMethod.POST); + WebRequest req = new WebRequest(new URI(wc.getContextPath() + "eval").toURL(), HttpMethod.POST); req.setEncodingType(null); req.setRequestBody("${1+2}"); return wc.getPage(req); diff --git a/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java b/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java index 4f9080b4ac9e..30361ed8658c 100644 --- a/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java +++ b/test/src/test/java/jenkins/security/ApiTokenPropertyTest.java @@ -22,6 +22,7 @@ import hudson.security.ACL; import hudson.security.ACLContext; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import java.util.Collection; import java.util.List; @@ -151,7 +152,7 @@ public void adminsShouldBeUnableToChangeTokensByDefault() throws Exception { requirePOST.getWebResponse().getStatusCode()); wc.setThrowExceptionOnFailingStatusCode(true); - WebRequest request = new WebRequest(new URL(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl() + "/changeToken"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl() + "/changeToken").toURL(), HttpMethod.POST); HtmlPage res = wc.getPage(request); // TODO This nicer alternative requires https://github.com/jenkinsci/jenkins/pull/2268 or similar to work diff --git a/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java b/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java index 9ca39bb05f7f..893d8b6ee492 100644 --- a/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java +++ b/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java @@ -33,6 +33,8 @@ import hudson.ExtensionComponent; import hudson.model.User; + +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; @@ -83,12 +85,12 @@ public void legacyToken_regularCase() throws Throwable { wc.getOptions().setThrowExceptionOnFailingStatusCode(false); { // for invalid token, no effect - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("user1", "invalid-token")); assertThat(wc.getPage(request).getWebResponse().getStatusCode(), equalTo(401)); } { // for invalid user, no effect - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("user-not-valid", token.get())); assertThat(wc.getPage(request).getWebResponse().getStatusCode(), equalTo(401)); } @@ -96,7 +98,7 @@ public void legacyToken_regularCase() throws Throwable { assertNull(User.getById("user-not-valid", false)); { // valid user with valid token, ok - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("user1", token.get())); XmlPage xmlPage = wc.getPage(request); assertThat(xmlPage, hasXPath("//name", is("user1"))); @@ -131,12 +133,12 @@ public void legacyToken_withoutLastGrantedAuthorities() throws Throwable { wc.getOptions().setThrowExceptionOnFailingStatusCode(false); { // for invalid token, no effect - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("user1", "invalid-token")); assertThat(wc.getPage(request).getWebResponse().getStatusCode(), equalTo(401)); } { // for invalid user, no effect - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("user-not-valid", token.get())); assertThat(wc.getPage(request).getWebResponse().getStatusCode(), equalTo(401)); } @@ -145,7 +147,7 @@ public void legacyToken_withoutLastGrantedAuthorities() throws Throwable { assertNull(User.getById("user-not-valid", false)); { // valid user with valid token, ok - WebRequest request = new WebRequest(new URL(j.jenkins.getRootUrl() + "whoAmI/api/xml")); + WebRequest request = new WebRequest(new URI(j.jenkins.getRootUrl() + "whoAmI/api/xml").toURL()); request.setAdditionalHeader("Authorization", base64("user1", token.get())); XmlPage xmlPage = wc.getPage(request); assertThat(xmlPage, hasXPath("//name", is("user1"))); diff --git a/test/src/test/java/jenkins/security/ResourceDomainTest.java b/test/src/test/java/jenkins/security/ResourceDomainTest.java index 9a6f88a2a035..648a7193caae 100644 --- a/test/src/test/java/jenkins/security/ResourceDomainTest.java +++ b/test/src/test/java/jenkins/security/ResourceDomainTest.java @@ -12,6 +12,8 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.UnprotectedRootAction; + +import java.net.URI; import java.net.URL; import java.time.Instant; import java.util.UUID; @@ -352,13 +354,13 @@ public void testMoreUrlEncoding() throws Exception { URL url = page.getUrl(); Assert.assertTrue("page is served by resource domain", url.toString().contains("/static-files/")); - URL dirUrl = new URL(url.toString().replace("%20100%25%20evil%20content%20.html", "")); + URL dirUrl = new URI(url.toString().replace("%20100%25%20evil%20content%20.html", "")).toURL(); Page dirPage = webClient.getPage(dirUrl); Assert.assertEquals("page is found", 200, dirPage.getWebResponse().getStatusCode()); Assert.assertTrue("page content is HTML", dirPage.getWebResponse().getContentAsString().contains("href")); Assert.assertTrue("page content references file", dirPage.getWebResponse().getContentAsString().contains("evil content")); - URL topDirUrl = new URL(url.toString().replace("%20100%25%20evil%20dir%20name%20%20%20/%20100%25%20evil%20content%20.html", "")); + URL topDirUrl = new URI(url.toString().replace("%20100%25%20evil%20dir%20name%20%20%20/%20100%25%20evil%20content%20.html", "")).toURL(); Page topDirPage = webClient.getPage(topDirUrl); Assert.assertEquals("page is found", 200, topDirPage.getWebResponse().getStatusCode()); Assert.assertTrue("page content is HTML", topDirPage.getWebResponse().getContentAsString().contains("href")); diff --git a/test/src/test/java/jenkins/security/Security2278Test.java b/test/src/test/java/jenkins/security/Security2278Test.java index c556d5d079bf..da20edcf15f2 100644 --- a/test/src/test/java/jenkins/security/Security2278Test.java +++ b/test/src/test/java/jenkins/security/Security2278Test.java @@ -15,6 +15,8 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.Queue; + +import java.net.URI; import java.net.URL; import java.util.List; import java.util.Objects; @@ -94,7 +96,7 @@ public void testQueueCancelWithoutPermission() throws Exception { webClient.setThrowExceptionOnFailingStatusCode(false); webClient.setRedirectEnabled(false); - final Page stopResponse = webClient.getPage(addReferer(webClient.addCrumb(new WebRequest(new URL(j.jenkins.getRootUrl() + "/queue/cancelItem?id=" + id), HttpMethod.POST)), j.jenkins.getRootUrl())); + final Page stopResponse = webClient.getPage(addReferer(webClient.addCrumb(new WebRequest(new URI(j.jenkins.getRootUrl() + "/queue/cancelItem?id=" + id).toURL(), HttpMethod.POST)), j.jenkins.getRootUrl())); assertEquals(404, stopResponse.getWebResponse().getStatusCode()); Assert.assertEquals(1, j.jenkins.getQueue().getItems().length); } @@ -119,7 +121,7 @@ public void testWebMethodWithoutPermission() throws Exception { if (found < 0) { throw new IllegalStateException("didn't find executor"); } - final Page stopResponse = webClient.getPage(addReferer(webClient.addCrumb(new WebRequest(new URL(j.jenkins.getRootUrl() + "/computer/(master)/executors/" + found + "/stop/"), HttpMethod.POST)), j.jenkins.getRootUrl())); + final Page stopResponse = webClient.getPage(addReferer(webClient.addCrumb(new WebRequest(new URI(j.jenkins.getRootUrl() + "/computer/(master)/executors/" + found + "/stop/").toURL(), HttpMethod.POST)), j.jenkins.getRootUrl())); assertEquals(302, stopResponse.getWebResponse().getStatusCode()); final FreeStyleBuild build = project.getBuildByNumber(1); diff --git a/test/src/test/java/jenkins/security/Security2761Test.java b/test/src/test/java/jenkins/security/Security2761Test.java index f1c75d9e7647..855d9cc004dc 100644 --- a/test/src/test/java/jenkins/security/Security2761Test.java +++ b/test/src/test/java/jenkins/security/Security2761Test.java @@ -7,6 +7,8 @@ import hudson.model.InvisibleAction; import hudson.model.UnprotectedRootAction; + +import java.net.URI; import java.net.URL; import java.util.concurrent.atomic.AtomicBoolean; import org.htmlunit.html.HtmlPage; @@ -29,7 +31,7 @@ public void symbolIconAltIsEscaped() throws Exception { JenkinsRule.WebClient wc = j.createWebClient(); wc.setAlertHandler((page, s) -> alerted.set(true)); - HtmlPage page = wc.getPage(new URL(wc.getContextPath() + ACTION_URL)); + HtmlPage page = wc.getPage(new URI(wc.getContextPath() + ACTION_URL).toURL()); String responseContent = page.getWebResponse().getContentAsString(); wc.waitForBackgroundJavaScript(5000); diff --git a/test/src/test/java/jenkins/security/Security637Test.java b/test/src/test/java/jenkins/security/Security637Test.java index 824a06d56001..a691db743411 100644 --- a/test/src/test/java/jenkins/security/Security637Test.java +++ b/test/src/test/java/jenkins/security/Security637Test.java @@ -42,6 +42,7 @@ import hudson.slaves.DumbSlave; import java.io.IOException; import java.lang.reflect.Field; +import java.net.URI; import java.net.URL; import java.net.URLStreamHandler; import java.util.Collections; @@ -127,7 +128,7 @@ private static class URLBuilderCallable extends MasterToSlaveCallable futureBuild = p.scheduleBuild2(0); futureBuild.waitForStart(); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild").toURL(), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -340,7 +341,7 @@ public void ensureDoStopBuildWorks() throws Exception { FreeStyleBuild build = futureBuild.waitForStart(); String runExtId = URLEncoder.encode(build.getExternalizableId(), StandardCharsets.UTF_8); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=" + runExtId).toURL(), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -360,7 +361,7 @@ public void ensureDoStopBuildWorks() throws Exception { QueueTaskFuture futureBuild = p.scheduleBuild2(0); futureBuild.waitForStart(); - WebRequest request = new WebRequest(new URL(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=whatever"), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "computers/0/executors/0/stopBuild?runExtId=whatever").toURL(), HttpMethod.POST); Page page = wc.getPage(request); assertEquals(404, page.getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); @@ -564,7 +565,7 @@ public void ensureLogRecordManagerAccessibleOnlyByAdmin() throws Exception { assertEquals(404, wc.goTo("log/" + logNameForAdmin + "/autoCompleteLoggerName/?value=a", null).getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); - WebRequest request = new WebRequest(new URL(j.getURL() + "log/newLogRecorder/?name=" + logNameForAdmin), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "log/newLogRecorder/?name=" + logNameForAdmin).toURL(), HttpMethod.POST); wc.getOptions().setRedirectEnabled(false); Page page = wc.getPage(request); @@ -588,7 +589,7 @@ public void ensureLogRecordManagerAccessibleOnlyByAdmin() throws Exception { assertEquals(403, wc.goTo("log/" + logNameForUser + "/autoCompleteLoggerName/?value=a", null).getWebResponse().getStatusCode()); assertRequestWasNotBlocked(); - WebRequest request = new WebRequest(new URL(j.getURL() + "log/newLogRecorder/?name=" + logNameForUser), HttpMethod.POST); + WebRequest request = new WebRequest(new URI(j.getURL() + "log/newLogRecorder/?name=" + logNameForUser).toURL(), HttpMethod.POST); wc.getOptions().setRedirectEnabled(false); Page page = wc.getPage(request); diff --git a/test/src/test/java/jenkins/security/stapler/Security914Test.java b/test/src/test/java/jenkins/security/stapler/Security914Test.java index 5ade00a7678f..b01a66a2aab1 100644 --- a/test/src/test/java/jenkins/security/stapler/Security914Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security914Test.java @@ -31,6 +31,7 @@ import hudson.Functions; import java.net.HttpURLConnection; +import java.net.URI; import java.net.URL; import org.htmlunit.Page; import org.htmlunit.WebRequest; @@ -54,7 +55,7 @@ public void cannotUseInvalidLocale_toTraverseFolder() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.xml")); + WebRequest request = new WebRequest(new URI(j.getURL() + "plugin/credentials/.xml").toURL()); // plugin deployed in: test\target\jenkins7375296945862059919tmp // rootDir is in : test\target\jenkinsTests.tmp\jenkins1274934531848159942test // j.jenkins.getRootDir().getName() = jenkins1274934531848159942test @@ -74,7 +75,7 @@ public void cannotUseInvalidLocale_toAnyFileInSystem() throws Exception { JenkinsRule.WebClient wc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); - WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.ini")); + WebRequest request = new WebRequest(new URI(j.getURL() + "plugin/credentials/.ini").toURL()); // ../ can be multiply to infinity, no impact, we just need to have enough to reach the root request.setAdditionalHeader("Accept-Language", "../../../../../../../../../../../../windows/win"); From c92687421b7e69cb67b352b51933d8095f03d2df Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Thu, 21 Sep 2023 22:54:12 +0530 Subject: [PATCH 06/11] JENKINS-72028; mvn spotless applied --- cli/src/main/java/hudson/cli/CLI.java | 1 - cli/src/main/java/hudson/cli/SSHCLI.java | 2 -- core/src/main/java/hudson/Functions.java | 1 - core/src/main/java/hudson/model/UpdateSite.java | 1 - core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java | 1 - core/src/main/java/hudson/tools/ZipExtractionInstaller.java | 1 - test/src/test/java/hudson/TcpSlaveAgentListenerTest.java | 1 - test/src/test/java/hudson/console/ConsoleAnnotatorTest.java | 1 - .../java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java | 1 - test/src/test/java/hudson/markup/MarkupFormatterTest.java | 1 - test/src/test/java/hudson/model/DirectlyModifiableViewTest.java | 1 - test/src/test/java/hudson/model/ItemsTest.java | 1 - test/src/test/java/hudson/model/QueueTest.java | 1 - test/src/test/java/hudson/model/UserRestartTest.java | 2 -- .../java/hudson/security/HudsonPrivateSecurityRealmTest.java | 1 - .../test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java | 1 - test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java | 1 - .../test/java/hudson/util/RobustReflectionConverterTest.java | 1 - .../jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java | 2 -- test/src/test/java/jenkins/security/ResourceDomainTest.java | 1 - test/src/test/java/jenkins/security/Security2278Test.java | 2 -- test/src/test/java/jenkins/security/Security2761Test.java | 2 -- .../test/java/jenkins/security/apitoken/ApiTokenStatsTest.java | 1 - .../java/jenkins/security/seed/UserSeedChangeListenerTest.java | 2 -- .../java/jenkins/security/seed/UserSeedPropertyRestartTest.java | 2 -- .../test/java/jenkins/security/seed/UserSeedPropertyTest.java | 2 -- .../src/test/java/jenkins/security/stapler/Security400Test.java | 1 - .../src/test/java/jenkins/security/stapler/Security914Test.java | 1 - 28 files changed, 36 deletions(-) diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java index 466ac032aafd..e4d7df6b8da7 100644 --- a/cli/src/main/java/hudson/cli/CLI.java +++ b/cli/src/main/java/hudson/cli/CLI.java @@ -40,7 +40,6 @@ import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.nio.charset.Charset; diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 54a3a34733ea..5be733ef3d29 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -35,7 +35,6 @@ import java.net.URL; import java.net.URLConnection; import java.security.KeyPair; -import java.security.PublicKey; import java.util.List; import java.util.Set; import java.util.logging.Level; @@ -46,7 +45,6 @@ import org.apache.sshd.client.future.ConnectFuture; import org.apache.sshd.client.keyverifier.DefaultKnownHostsServerKeyVerifier; import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier; -import org.apache.sshd.client.keyverifier.ServerKeyVerifier; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.future.WaitableFuture; import org.apache.sshd.common.util.io.input.NoCloseInputStream; diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index dad30b25066f..707de6972b04 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -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; diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index e6fb6b3e525e..07e97a946200 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -48,7 +48,6 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.Instant; diff --git a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java index 83501fe2a3c8..d50cef554c5c 100644 --- a/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java +++ b/core/src/main/java/hudson/tools/DownloadFromUrlInstaller.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; diff --git a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java index 601e26762f65..ff853573d13b 100644 --- a/core/src/main/java/hudson/tools/ZipExtractionInstaller.java +++ b/core/src/main/java/hudson/tools/ZipExtractionInstaller.java @@ -39,7 +39,6 @@ import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; diff --git a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java index 38d9e537cc23..c589b1a46d55 100644 --- a/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java +++ b/test/src/test/java/hudson/TcpSlaveAgentListenerTest.java @@ -7,7 +7,6 @@ import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import jenkins.model.Jenkins; import org.htmlunit.Page; import org.htmlunit.TextPage; diff --git a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java index 4df8ac3a0683..5aa4a3cdac32 100644 --- a/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java +++ b/test/src/test/java/hudson/console/ConsoleAnnotatorTest.java @@ -26,7 +26,6 @@ import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; diff --git a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java index e986b02efede..0e57e336b49f 100644 --- a/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java +++ b/test/src/test/java/hudson/diagnosis/HudsonHomeDiskUsageMonitorTest.java @@ -10,7 +10,6 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import java.util.List; import jenkins.model.Jenkins; import org.htmlunit.ElementNotFoundException; diff --git a/test/src/test/java/hudson/markup/MarkupFormatterTest.java b/test/src/test/java/hudson/markup/MarkupFormatterTest.java index e5dde33db4bd..a9e1283fb53e 100644 --- a/test/src/test/java/hudson/markup/MarkupFormatterTest.java +++ b/test/src/test/java/hudson/markup/MarkupFormatterTest.java @@ -34,7 +34,6 @@ import java.io.IOException; import java.io.Writer; import java.net.URI; -import java.net.URL; import org.htmlunit.HttpMethod; import org.htmlunit.Page; import org.htmlunit.WebRequest; diff --git a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java index b285f81963f2..52f46ca8f57e 100644 --- a/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java +++ b/test/src/test/java/hudson/model/DirectlyModifiableViewTest.java @@ -30,7 +30,6 @@ import java.io.IOException; import java.net.URI; -import java.net.URL; import org.hamcrest.Matchers; import org.htmlunit.HttpMethod; import org.htmlunit.Page; diff --git a/test/src/test/java/hudson/model/ItemsTest.java b/test/src/test/java/hudson/model/ItemsTest.java index 75e81101820b..b41e9d48bdcd 100644 --- a/test/src/test/java/hudson/model/ItemsTest.java +++ b/test/src/test/java/hudson/model/ItemsTest.java @@ -42,7 +42,6 @@ import java.io.File; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; import jenkins.model.Jenkins; diff --git a/test/src/test/java/hudson/model/QueueTest.java b/test/src/test/java/hudson/model/QueueTest.java index facc8cb0ab1b..bdacb2f72a63 100644 --- a/test/src/test/java/hudson/model/QueueTest.java +++ b/test/src/test/java/hudson/model/QueueTest.java @@ -84,7 +84,6 @@ import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; diff --git a/test/src/test/java/hudson/model/UserRestartTest.java b/test/src/test/java/hudson/model/UserRestartTest.java index 928edbc8c68d..d5b84b352029 100644 --- a/test/src/test/java/hudson/model/UserRestartTest.java +++ b/test/src/test/java/hudson/model/UserRestartTest.java @@ -33,9 +33,7 @@ import hudson.FilePath; import hudson.tasks.Mailer; - import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import org.htmlunit.WebRequest; diff --git a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java index 25d1dd18cd01..845201f8b9fa 100644 --- a/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java +++ b/test/src/test/java/hudson/security/HudsonPrivateSecurityRealmTest.java @@ -44,7 +44,6 @@ import hudson.security.pages.SignupPage; import java.lang.reflect.Field; import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; diff --git a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java index b2e9f3abf5cb..2904af69fc4d 100644 --- a/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java +++ b/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java @@ -18,7 +18,6 @@ import hudson.model.User; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import javax.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; import net.sf.json.JSONObject; diff --git a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java index a6db76638aa4..920cd9fe5f9b 100644 --- a/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java +++ b/test/src/test/java/hudson/tools/ZipExtractionInstallerTest.java @@ -29,7 +29,6 @@ import hudson.model.User; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import jenkins.model.Jenkins; diff --git a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java index 8b7d1a4be9d4..ff0b255114e1 100644 --- a/test/src/test/java/hudson/util/RobustReflectionConverterTest.java +++ b/test/src/test/java/hudson/util/RobustReflectionConverterTest.java @@ -45,7 +45,6 @@ import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import java.nio.charset.Charset; import java.util.Map; import java.util.Set; diff --git a/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java b/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java index 893d8b6ee492..873194dfb089 100644 --- a/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java +++ b/test/src/test/java/jenkins/security/BasicHeaderApiTokenAuthenticatorTest.java @@ -33,9 +33,7 @@ import hudson.ExtensionComponent; import hudson.model.User; - import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.concurrent.atomic.AtomicReference; diff --git a/test/src/test/java/jenkins/security/ResourceDomainTest.java b/test/src/test/java/jenkins/security/ResourceDomainTest.java index 648a7193caae..feeed98b5f68 100644 --- a/test/src/test/java/jenkins/security/ResourceDomainTest.java +++ b/test/src/test/java/jenkins/security/ResourceDomainTest.java @@ -12,7 +12,6 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.UnprotectedRootAction; - import java.net.URI; import java.net.URL; import java.time.Instant; diff --git a/test/src/test/java/jenkins/security/Security2278Test.java b/test/src/test/java/jenkins/security/Security2278Test.java index da20edcf15f2..161b67932c24 100644 --- a/test/src/test/java/jenkins/security/Security2278Test.java +++ b/test/src/test/java/jenkins/security/Security2278Test.java @@ -15,9 +15,7 @@ import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.Queue; - import java.net.URI; -import java.net.URL; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; diff --git a/test/src/test/java/jenkins/security/Security2761Test.java b/test/src/test/java/jenkins/security/Security2761Test.java index 855d9cc004dc..87f51fa2f517 100644 --- a/test/src/test/java/jenkins/security/Security2761Test.java +++ b/test/src/test/java/jenkins/security/Security2761Test.java @@ -7,9 +7,7 @@ import hudson.model.InvisibleAction; import hudson.model.UnprotectedRootAction; - import java.net.URI; -import java.net.URL; import java.util.concurrent.atomic.AtomicBoolean; import org.htmlunit.html.HtmlPage; import org.junit.Rule; diff --git a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java index b85d8149e6fb..68185e6efac3 100644 --- a/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java +++ b/test/src/test/java/jenkins/security/apitoken/ApiTokenStatsTest.java @@ -34,7 +34,6 @@ import static org.junit.Assert.assertThrows; import hudson.model.User; - import java.net.URI; import java.net.URL; import java.util.List; diff --git a/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java b/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java index c523e21a6826..c2c787f1187d 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedChangeListenerTest.java @@ -30,9 +30,7 @@ import edu.umd.cs.findbugs.annotations.NonNull; import hudson.model.User; - import java.net.URI; -import java.net.URL; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; import org.junit.Rule; diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java index 09d6a8e336b0..0d44074d67a1 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyRestartTest.java @@ -29,9 +29,7 @@ import static org.junit.Assert.assertNotNull; import hudson.model.User; - import java.net.URI; -import java.net.URL; import java.util.concurrent.atomic.AtomicReference; import org.htmlunit.HttpMethod; import org.htmlunit.WebRequest; diff --git a/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java b/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java index 223f11e2a772..d87761ad391c 100644 --- a/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java +++ b/test/src/test/java/jenkins/security/seed/UserSeedPropertyTest.java @@ -35,9 +35,7 @@ import static org.junit.Assert.assertThrows; import hudson.model.User; - import java.net.URI; -import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.List; diff --git a/test/src/test/java/jenkins/security/stapler/Security400Test.java b/test/src/test/java/jenkins/security/stapler/Security400Test.java index f9cbd0b840f3..2a26ceda1fdb 100644 --- a/test/src/test/java/jenkins/security/stapler/Security400Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security400Test.java @@ -49,7 +49,6 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.concurrent.Semaphore; diff --git a/test/src/test/java/jenkins/security/stapler/Security914Test.java b/test/src/test/java/jenkins/security/stapler/Security914Test.java index b01a66a2aab1..8a722c0109ac 100644 --- a/test/src/test/java/jenkins/security/stapler/Security914Test.java +++ b/test/src/test/java/jenkins/security/stapler/Security914Test.java @@ -32,7 +32,6 @@ import hudson.Functions; import java.net.HttpURLConnection; import java.net.URI; -import java.net.URL; import org.htmlunit.Page; import org.htmlunit.WebRequest; import org.junit.Rule; From 7ac67c05256674b79d30f2e047e67de94ab44046 Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Fri, 22 Sep 2023 06:23:20 +0530 Subject: [PATCH 07/11] resolve checkstyle --- .../commons/validator/routines/DomainValidatorTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java index 11235ee46d45..0e3a92afe224 100644 --- a/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java +++ b/core/src/test/java/jenkins/org/apache/commons/validator/routines/DomainValidatorTest.java @@ -25,7 +25,10 @@ import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.net.*; +import java.net.HttpURLConnection; +import java.net.IDN; +import java.net.URI; +import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.text.SimpleDateFormat; From 0ca8a73c6741bb02df2b342edc556c9f1a932fe7 Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Tue, 26 Sep 2023 00:13:25 +0530 Subject: [PATCH 08/11] updated exception handling from generic to specific --- core/src/main/java/hudson/Functions.java | 5 +++-- core/src/main/java/hudson/PluginManager.java | 4 ++-- core/src/main/java/hudson/TcpSlaveAgentListener.java | 4 ++-- core/src/main/java/hudson/model/UpdateCenter.java | 2 +- .../jenkins/security/ResourceDomainConfiguration.java | 8 ++++---- .../test/java/jenkins/security/ResourceDomainTest.java | 3 ++- 6 files changed, 14 insertions(+), 12 deletions(-) diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 707de6972b04..5e946fff0ff9 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1932,7 +1932,7 @@ public static String toEmailSafeString(String projectName) { * @deprecated use {@link JNLPLauncher#getInboundAgentUrl} */ @Deprecated - public String getServerName() { + public String getServerName() throws URISyntaxException, MalformedURLException { // Try to infer this from the configured root URL. // This makes it work correctly when Hudson runs behind a reverse proxy. String url = Jenkins.get().getRootUrl(); @@ -1944,8 +1944,9 @@ public String getServerName() { } } catch (MalformedURLException e) { // fall back to HTTP request + throw new MalformedURLException(); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new URISyntaxException(e.getReason(), e.getInput()); } return Stapler.getCurrentRequest().getServerName(); } diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index a73240a4e29d..a42da386ca7b 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -1942,7 +1942,7 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl } @Restricted(NoExternalUse.class) - @RequirePOST public FormValidation doCheckPluginUrl(StaplerRequest request, @QueryParameter String value) throws IOException { + @RequirePOST public FormValidation doCheckPluginUrl(StaplerRequest request, @QueryParameter String value) throws IOException, URISyntaxException { if (StringUtils.isNotBlank(value)) { try { URL url = new URI(value).toURL(); @@ -1956,7 +1956,7 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl } catch (MalformedURLException e) { return FormValidation.error(e.getMessage()); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new URISyntaxException(e.getReason(), e.getInput()); } } return FormValidation.ok(); diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index 2e190e1bacbb..5d9dae19653d 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -131,7 +131,7 @@ public int getAdvertisedPort() { * Gets the host name that we advertise protocol clients to connect to. * @since 2.198 */ - public String getAdvertisedHost() { + public String getAdvertisedHost() throws URISyntaxException { if (CLI_HOST_NAME != null) { return CLI_HOST_NAME; } @@ -140,7 +140,7 @@ public String getAdvertisedHost() { } catch (MalformedURLException e) { throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new URISyntaxException(e.getReason(), e.getInput()); } } diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 89675616f00a..19c32198fc9e 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -2430,7 +2430,7 @@ public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) { protected URL getURL() throws MalformedURLException { try { return new URI(plugin.url).toURL(); - } catch (URISyntaxException e) { + } catch (MalformedURLException| URISyntaxException e) { throw new RuntimeException(e); } } diff --git a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java index f51f4371df32..d1574bc52d77 100644 --- a/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java +++ b/core/src/main/java/jenkins/security/ResourceDomainConfiguration.java @@ -85,13 +85,13 @@ public ResourceDomainConfiguration() { @Restricted(NoExternalUse.class) @POST - public FormValidation doCheckUrl(@QueryParameter("url") String resourceRootUrlString) { + public FormValidation doCheckUrl(@QueryParameter("url") String resourceRootUrlString) throws URISyntaxException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); return checkUrl(resourceRootUrlString, true); } - private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlineIdentityCheck) { + private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlineIdentityCheck) throws URISyntaxException { String jenkinsRootUrlString = JenkinsLocationConfiguration.get().getUrl(); if (ExtensionList.lookupSingleton(RootUrlNotSetMonitor.class).isActivated() || jenkinsRootUrlString == null) { // This is needed to round-trip expired resource URLs through regular URLs to refresh them, @@ -118,7 +118,7 @@ private FormValidation checkUrl(String resourceRootUrlString, boolean allowOnlin } catch (MalformedURLException ex) { return FormValidation.error(Messages.ResourceDomainConfiguration_Invalid()); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new URISyntaxException(e.getReason(), e.getInput()); } String resourceRootUrlHost = resourceRootUrl.getHost(); @@ -198,7 +198,7 @@ public String getUrl() { return url; } - public void setUrl(@CheckForNull String url) { + public void setUrl(@CheckForNull String url) throws URISyntaxException { if (checkUrl(url, false).kind == FormValidation.Kind.OK) { // only accept valid configurations, both with and without URL, but allow for networking issues url = Util.fixEmpty(url); diff --git a/test/src/test/java/jenkins/security/ResourceDomainTest.java b/test/src/test/java/jenkins/security/ResourceDomainTest.java index feeed98b5f68..6aed432351f1 100644 --- a/test/src/test/java/jenkins/security/ResourceDomainTest.java +++ b/test/src/test/java/jenkins/security/ResourceDomainTest.java @@ -13,6 +13,7 @@ import hudson.model.Item; import hudson.model.UnprotectedRootAction; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.time.Instant; import java.util.UUID; @@ -277,7 +278,7 @@ public void indexFileIsUsedIfDefined() { } @Test - public void adminMonitorShowsUpWithOverriddenCSP() { + public void adminMonitorShowsUpWithOverriddenCSP() throws URISyntaxException { ResourceDomainRecommendation monitor = ExtensionList.lookupSingleton(ResourceDomainRecommendation.class); Assert.assertFalse(monitor.isActivated()); System.setProperty(DirectoryBrowserSupport.class.getName() + ".CSP", ""); From 2145fedaf4fc564d539123b25401c96eb5557b3b Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Tue, 26 Sep 2023 07:38:07 +0530 Subject: [PATCH 09/11] fix whitespace in response to checkstyle --- core/src/main/java/hudson/model/UpdateCenter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 19c32198fc9e..0165d88f9c85 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -2430,7 +2430,7 @@ public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) { protected URL getURL() throws MalformedURLException { try { return new URI(plugin.url).toURL(); - } catch (MalformedURLException| URISyntaxException e) { + } catch (MalformedURLException | URISyntaxException e) { throw new RuntimeException(e); } } From 34d09f2264ea25127181e9082484e899fa2e536b Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Wed, 4 Oct 2023 00:29:58 +0530 Subject: [PATCH 10/11] fix issues as per code review --- cli/src/main/java/hudson/cli/SSHCLI.java | 19 ++++++++++--------- core/src/main/java/hudson/FilePath.java | 6 +++--- core/src/main/java/hudson/Functions.java | 7 ++----- core/src/main/java/hudson/PluginManager.java | 4 +--- .../java/hudson/TcpSlaveAgentListener.java | 6 ++---- .../main/java/hudson/model/UpdateCenter.java | 6 +++--- 6 files changed, 21 insertions(+), 27 deletions(-) diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 5be733ef3d29..3ab1dc5021e7 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -29,12 +29,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.util.QuotedStringTokenizer; import java.io.IOException; -import java.net.SocketTimeoutException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; +import java.net.*; import java.security.KeyPair; +import java.security.PublicKey; import java.util.List; import java.util.Set; import java.util.logging.Level; @@ -45,6 +42,7 @@ import org.apache.sshd.client.future.ConnectFuture; import org.apache.sshd.client.keyverifier.DefaultKnownHostsServerKeyVerifier; import org.apache.sshd.client.keyverifier.KnownHostsServerKeyVerifier; +import org.apache.sshd.client.keyverifier.ServerKeyVerifier; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.future.WaitableFuture; import org.apache.sshd.common.util.io.input.NoCloseInputStream; @@ -65,7 +63,7 @@ static int sshConnection(String jenkinsUrl, String user, List args, Priv try { url = new URI(jenkinsUrl + "login").toURL(); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new URISyntaxException(e.getInput(),e.getReason()); } URLConnection conn = openConnection(url); CLI.verifyJenkinsConnection(conn); @@ -90,9 +88,12 @@ static int sshConnection(String jenkinsUrl, String user, List args, Priv try (SshClient client = SshClient.setUpDefaultClient()) { - KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier((clientSession, remoteAddress, serverKey) -> { - CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString()); - return !strictHostKey; + KnownHostsServerKeyVerifier verifier = new DefaultKnownHostsServerKeyVerifier(new ServerKeyVerifier() { + @Override + public boolean verifyServerKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) { + CLI.LOGGER.log(Level.WARNING, "Unknown host key for {0}", remoteAddress.toString()); + return !strictHostKey; + } }, true); client.setServerKeyVerifier(verifier); diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index bf5662bcf5a8..40a00e47fbb3 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -974,14 +974,14 @@ public Void invoke(File dir, VirtualChannel channel) throws IOException { * was considered up to date. * @since 1.299 */ - public boolean installIfNecessaryFrom(@NonNull URL archive, @CheckForNull TaskListener listener, @NonNull String message) throws IOException, InterruptedException { + public boolean installIfNecessaryFrom(@NonNull URL archive, @CheckForNull TaskListener listener, @NonNull String message) throws IOException, InterruptedException, URISyntaxException { if (listener == null) { listener = TaskListener.NULL; } return installIfNecessaryFrom(archive, listener, message, MAX_REDIRECTS); } - private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListener listener, @NonNull String message, int maxRedirects) throws InterruptedException, IOException { + private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListener listener, @NonNull String message, int maxRedirects) throws InterruptedException, IOException, URISyntaxException { try { FilePath timestamp = this.child(".timestamp"); long lastModified = timestamp.lastModified(); @@ -1067,7 +1067,7 @@ private boolean installIfNecessaryFrom(@NonNull URL archive, @NonNull TaskListen } catch (IOException e) { throw new IOException("Failed to install " + archive + " to " + remote, e); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new URISyntaxException(e.getInput(), e.getReason()); } } diff --git a/core/src/main/java/hudson/Functions.java b/core/src/main/java/hudson/Functions.java index 5e946fff0ff9..5438423c6d7e 100644 --- a/core/src/main/java/hudson/Functions.java +++ b/core/src/main/java/hudson/Functions.java @@ -1932,7 +1932,7 @@ public static String toEmailSafeString(String projectName) { * @deprecated use {@link JNLPLauncher#getInboundAgentUrl} */ @Deprecated - public String getServerName() throws URISyntaxException, MalformedURLException { + public String getServerName() { // Try to infer this from the configured root URL. // This makes it work correctly when Hudson runs behind a reverse proxy. String url = Jenkins.get().getRootUrl(); @@ -1942,11 +1942,8 @@ public String getServerName() throws URISyntaxException, MalformedURLException { if (host != null) return host; } - } catch (MalformedURLException e) { + } catch (MalformedURLException | URISyntaxException e) { // fall back to HTTP request - throw new MalformedURLException(); - } catch (URISyntaxException e) { - throw new URISyntaxException(e.getReason(), e.getInput()); } return Stapler.getCurrentRequest().getServerName(); } diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index a42da386ca7b..0ec7bd29470c 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -1953,10 +1953,8 @@ public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, Servl if (!url.getProtocol().equals("https")) { return FormValidation.warning(Messages.PluginManager_insecureUrl()); } - } catch (MalformedURLException e) { + } catch (MalformedURLException |URISyntaxException e) { return FormValidation.error(e.getMessage()); - } catch (URISyntaxException e) { - throw new URISyntaxException(e.getReason(), e.getInput()); } } return FormValidation.ok(); diff --git a/core/src/main/java/hudson/TcpSlaveAgentListener.java b/core/src/main/java/hudson/TcpSlaveAgentListener.java index 5d9dae19653d..442df7675c5a 100644 --- a/core/src/main/java/hudson/TcpSlaveAgentListener.java +++ b/core/src/main/java/hudson/TcpSlaveAgentListener.java @@ -131,16 +131,14 @@ public int getAdvertisedPort() { * Gets the host name that we advertise protocol clients to connect to. * @since 2.198 */ - public String getAdvertisedHost() throws URISyntaxException { + public String getAdvertisedHost() { if (CLI_HOST_NAME != null) { return CLI_HOST_NAME; } try { return new URI(Jenkins.get().getRootUrl()).toURL().getHost(); - } catch (MalformedURLException e) { + } catch (MalformedURLException | URISyntaxException e) { throw new IllegalStateException("Could not get TcpSlaveAgentListener host name", e); - } catch (URISyntaxException e) { - throw new URISyntaxException(e.getReason(), e.getInput()); } } diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index 0165d88f9c85..f970cd99ef49 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -2198,7 +2198,7 @@ protected URL getURL() throws MalformedURLException { try { return new URI(plugin.url).toURL(); } catch (URISyntaxException e) { - throw new RuntimeException(e); + throw new MalformedURLException("Not a valid URL"); } } @@ -2430,8 +2430,8 @@ public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) { protected URL getURL() throws MalformedURLException { try { return new URI(plugin.url).toURL(); - } catch (MalformedURLException | URISyntaxException e) { - throw new RuntimeException(e); + } catch (URISyntaxException e) { + throw new MalformedURLException("Not a valid URL"); } } From 5c6a96ec50e0f12f0033d2a39b0a457a936d5c2a Mon Sep 17 00:00:00 2001 From: Abhishek Maity Date: Wed, 4 Oct 2023 06:40:11 +0530 Subject: [PATCH 11/11] fix checkstyle issues --- cli/src/main/java/hudson/cli/SSHCLI.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cli/src/main/java/hudson/cli/SSHCLI.java b/cli/src/main/java/hudson/cli/SSHCLI.java index 3ab1dc5021e7..dedd027f5635 100644 --- a/cli/src/main/java/hudson/cli/SSHCLI.java +++ b/cli/src/main/java/hudson/cli/SSHCLI.java @@ -29,7 +29,12 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.util.QuotedStringTokenizer; import java.io.IOException; -import java.net.*; +import java.net.SocketAddress; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; import java.security.KeyPair; import java.security.PublicKey; import java.util.List; @@ -63,7 +68,7 @@ static int sshConnection(String jenkinsUrl, String user, List args, Priv try { url = new URI(jenkinsUrl + "login").toURL(); } catch (URISyntaxException e) { - throw new URISyntaxException(e.getInput(),e.getReason()); + throw new URISyntaxException(e.getInput(), e.getReason()); } URLConnection conn = openConnection(url); CLI.verifyJenkinsConnection(conn);