1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.eclipse.aether.util.connector.transport;
20
21 import java.net.URI;
22
23 /**
24 * A utility class for transporters.
25 *
26 * @since 2.0.25
27 */
28 public final class TransporterUtils {
29 private TransporterUtils() {}
30
31 /**
32 * Checks whether two URIs have the same origin (scheme, host and effective port).
33 *
34 * @param origin the repository origin
35 * @param target the URI to compare with the origin
36 * @return {@code true} when both URIs have the same origin
37 * @since 2.0.25
38 */
39 public static boolean isSameOrigin(URI origin, URI target) {
40 return isSameEndpoint(origin, target, true, false);
41 }
42
43 /**
44 * Checks whether two URIs have the same authority (user, host and port).
45 *
46 * @param origin the URI to compare
47 * @param target the URI to compare with the origin
48 * @return {@code true} when both URIs have the same authority
49 * @since 2.0.25
50 */
51 public static boolean isSameAuthority(URI origin, URI target) {
52 return isSameEndpoint(origin, target, false, true);
53 }
54
55 private static boolean isSameEndpoint(
56 URI origin, URI target, boolean requireSameScheme, boolean requireSameUserInfo) {
57 if (origin.getHost() == null || target.getHost() == null) {
58 return false;
59 }
60 if (requireSameScheme && !equalsIgnoreCase(origin.getScheme(), target.getScheme())) {
61 return false;
62 }
63 if (requireSameUserInfo && !equalsIgnoreCase(origin.getUserInfo(), target.getUserInfo())) {
64 return false;
65 }
66 return origin.getHost().equalsIgnoreCase(target.getHost()) && effectivePort(origin) == effectivePort(target);
67 }
68
69 private static boolean equalsIgnoreCase(String left, String right) {
70 return left != null ? left.equalsIgnoreCase(right) : right == null;
71 }
72
73 private static int effectivePort(URI uri) {
74 if (uri.getPort() >= 0) {
75 return uri.getPort();
76 }
77 if ("https".equalsIgnoreCase(uri.getScheme())) {
78 return 443;
79 }
80 return "http".equalsIgnoreCase(uri.getScheme()) ? 80 : -1;
81 }
82 }