Path: blob/master/src/jdk.internal.jvmstat/share/classes/sun/jvmstat/monitor/HostIdentifier.java
41159 views
/*1* Copyright (c) 2004, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.jvmstat.monitor;2627import java.net.*;2829/**30* An abstraction that identifies a target host and communications31* protocol. The HostIdentifier, or hostid, provides a convenient string32* representation of the information needed to locate and communicate with33* a target host. The string, based on a {@link URI}, may specify the34* the communications protocol, host name, and protocol specific information35* for a target host. The format for a HostIdentifier string is:36* <pre>37* [<I>protocol</I>:][[<I>//</I>]<I>hostname</I>][<I>:port</I>][<I>/servername</I>]38* </pre>39* There are actually no required components of this string, as a null string40* is interpreted to mean a local connection to the local host and is equivalent41* to the string <em>local://localhost</em>. The components of the42* HostIdentifier are:43* <ul>44* <li><p>{@code protocol} - The communications protocol. If omitted,45* and a hostname is not specified, then default local protocol,46* <em>local:</em>, is assumed. If the protocol is omitted and a47* hostname is specified then the default remote protocol,48* <em>rmi:</em> is assumed.49* </p></li>50* <li><p>{@code hostname} - The hostname. If omitted, then51* <em>localhost</em> is assumed. If the protocol is also omitted,52* then default local protocol <em>local:</em> is also assumed.53* If the hostname is not omitted but the protocol is omitted,54* then the default remote protocol, <em>rmi:</em> is assumed.55* </p></li>56* <li><p>{@code port} - The port for the communications protocol.57* Treatment of the {@code port} parameter is implementation58* (protocol) specific. It is unused by the default local protocol,59* <em>local:</em>. For the default remote protocol, <em>rmi:</em>,60* {@code port} indicates the port number of the <em>rmiregistry</em>61* on the target host and defaults to port 1099.62* </p></li>63* <li><p>{@code servername} - The treatment of the Path, Query, and64* Fragment components of the HostIdentifier are implementation65* (protocol) dependent. These components are ignored by the66* default local protocol, <em>local:</em>. For the default remote67* protocol, <em>rmi</em>, the Path component is interpreted as68* the name of the RMI remote object. The Query component may69* contain an access mode specifier <em>?mode=</em> specifying70* <em>"r"</em> or <em>"rw"</em> access (write access currently71* ignored). The Fragment part is ignored.72* </p></li>73* </ul>74* <p>75* All HostIdentifier objects are represented as absolute, hierarchical URIs.76* The constructors accept relative URIs, but these will generally be77* transformed into an absolute URI specifying a default protocol. A78* HostIdentifier differs from a URI in that certain contractions and79* illicit syntactical constructions are allowed. The following are all80* valid HostIdentifier strings:81*82* <ul>83* <li>{@code <null>} - transformed into "//localhost"</li>84* <li>localhost - transformed into "//localhost"</li>85* <li>hostname - transformed into "//hostname"</li>86* <li>hostname:port - transformed into "//hostname:port"</li>87* <li>proto:hostname - transformed into "proto://hostname"</li>88* <li>proto:hostname:port - transformed into89* "proto://hostname:port"</li>90* <li>proto://hostname:port</li>91* </ul>92*93* @see URI94* @see VmIdentifier95*96* @author Brian Doherty97* @since 1.598*/99public class HostIdentifier {100private URI uri;101102/**103* creates a canonical representation of the uriString. This method104* performs certain translations depending on the type of URI generated105* by the string.106*/107private URI canonicalize(String uriString) throws URISyntaxException {108if ((uriString == null) || (uriString.compareTo("localhost") == 0)) {109uriString = "//localhost";110return new URI(uriString);111}112113if (Character.isDigit(uriString.charAt(0))) {114// may be hostname or hostname:port since it starts with digits115uriString = "//" + uriString;116}117118URI u = new URI(uriString);119120if (u.isAbsolute()) {121if (u.isOpaque()) {122/*123* this code is here to deal with a special case. For ease of124* use, we'd like to be able to handle the case where the user125* specifies hostname:port, not requiring the scheme part.126* This introduces some subtleties.127* hostname:port - scheme = hostname128* - schemespecificpart = port129* - hostname = null130* - userinfo=null131* however, someone could also enter scheme:hostname:port and132* get into this code. the strategy is to consider this133* syntax illegal and provide some code to defend against it.134* Basically, we test that the string contains only one ":"135* and that the ssp is numeric. If we get two colons, we will136* attempt to insert the "//" after the first colon and then137* try to create a URI from the resulting string.138*/139String scheme = u.getScheme();140String ssp = u.getSchemeSpecificPart();141String frag = u.getFragment();142URI u2 = null;143144int c1index = uriString.indexOf(':');145int c2index = uriString.lastIndexOf(':');146if (c2index != c1index) {147/*148* this is the scheme:hostname:port case. Attempt to149* transform this to scheme://hostname:port. If a path150* part is part of the original strings, it will be151* included in the SchemeSpecificPart. however, the152* fragment part must be handled separately.153*/154if (frag == null) {155u2 = new URI(scheme + "://" + ssp);156} else {157u2 = new URI(scheme + "://" + ssp + "#" + frag);158}159return u2;160}161/*162* here we have the <string>:<string> case, possibly with163* optional path and fragment components. we assume that164* the part following the colon is a number. we don't check165* this condition here as it will get detected later anyway.166*/167u2 = new URI("//" + uriString);168return u2;169} else {170return u;171}172} else {173/*174* This is the case where we were given a hostname followed175* by a path part, fragment part, or both a path and fragment176* part. The key here is that no scheme part was specified.177* For this case, if the scheme specific part does not begin178* with "//", then we prefix the "//" to the given string and179* attempt to create a URI from the resulting string.180*/181String ssp = u.getSchemeSpecificPart();182if (ssp.startsWith("//")) {183return u;184} else {185return new URI("//" + uriString);186}187}188}189190/**191* Create a HostIdentifier instance from a string value.192*193* @param uriString a string representing a target host. The syntax of194* the string must conform to the rules specified in the195* class documentation.196*197* @throws URISyntaxException Thrown when the uriString or its canonical198* form is poorly formed. This exception may199* get encapsulated into a MonitorException in200* a future version.201*202*/203public HostIdentifier(String uriString) throws URISyntaxException {204uri = canonicalize(uriString);205}206207/**208* Create a HostIdentifier instance from component parts of a URI.209*210* @param scheme the {@link URI#getScheme} component of a URI.211* @param authority the {@link URI#getAuthority} component of a URI.212* @param path the {@link URI#getPath} component of a URI.213* @param query the {@link URI#getQuery} component of a URI.214* @param fragment the {@link URI#getFragment} component of a URI.215*216* @throws URISyntaxException Thrown when the uriString or its canonical217* form is poorly formed. This exception may218* get encapsulated into a MonitorException in219* a future version.220* @see URI221*/222public HostIdentifier(String scheme, String authority, String path,223String query, String fragment)224throws URISyntaxException {225uri = new URI(scheme, authority, path, query, fragment);226}227228/**229* Create a HostIdentifier instance from a VmIdentifier.230*231* The necessary components of the VmIdentifier are extracted and232* reassembled into a HostIdentifier. If a "file:" scheme (protocol)233* is specified, the returned HostIdentifier will always be234* equivalent to HostIdentifier("file://localhost").235*236* @param vmid the VmIdentifier use to construct the HostIdentifier.237*/238public HostIdentifier(VmIdentifier vmid) {239/*240* Extract all components of the VmIdentifier URI except the241* user-info part of the authority (the lvmid).242*/243StringBuilder sb = new StringBuilder();244String scheme = vmid.getScheme();245String host = vmid.getHost();246String authority = vmid.getAuthority();247248// check for 'file:' VmIdentifiers and handled as a special case.249if ((scheme != null) && (scheme.compareTo("file") == 0)) {250try {251uri = new URI("file://localhost");252} catch (URISyntaxException e) { };253return;254}255256if ((host != null) && (host.compareTo(authority) == 0)) {257/*258* this condition occurs when the VmIdentifier specifies only259* the authority (i.e. the lvmid ), and not a host name.260*/261host = null;262}263264if (scheme == null) {265if (host == null) {266scheme = "local"; // default local scheme267} else {268/*269* rmi is the default remote scheme. if the VmIdentifier270* specifies some other protocol, this default is overridden.271*/272scheme = "rmi";273}274}275276sb.append(scheme).append("://");277278if (host == null) {279sb.append("localhost"); // default host name280} else {281sb.append(host);282}283284int port = vmid.getPort();285if (port != -1) {286sb.append(":").append(port);287}288289String path = vmid.getPath();290if ((path != null) && (path.length() != 0)) {291sb.append(path);292}293294String query = vmid.getQuery();295if (query != null) {296sb.append("?").append(query);297}298299String frag = vmid.getFragment();300if (frag != null) {301sb.append("#").append(frag);302}303304try {305uri = new URI(sb.toString());306} catch (URISyntaxException e) {307// shouldn't happen, as we were passed a valid VmIdentifier308throw new RuntimeException("Internal Error", e);309}310}311312/**313* Resolve a VmIdentifier with this HostIdentifier. A VmIdentifier, such314* as <em>1234</em> or <em>1234@hostname</em> or any other string that315* omits certain components of the URI string may be valid, but is certainly316* incomplete. They are missing critical information for identifying the317* the communications protocol, target host, or other parameters. A318* VmIdentifier of this form is considered <em>unresolved</em>. This method319* uses components of the HostIdentifier to resolve the missing components320* of the VmIdentifier.321* <p>322* Specified components of the unresolved VmIdentifier take precedence323* over their HostIdentifier counterparts. For example, if the VmIdentifier324* indicates <em>1234@hostname:2099</em> and the HostIdentifier indicates325* <em>rmi://hostname:1099/</em>, then the resolved VmIdentifier will326* be <em>rmi://1234@hostname:2099</em>. Any component not explicitly327* specified or assumed by the HostIdentifier, will remain unresolved in328* resolved VmIdentifier.329* <p>330* A VmIdentifier specifying a <em>file:</em> scheme (protocol), is331* not changed in any way by this method.332*333* @param vmid the unresolved VmIdentifier.334* @return VmIdentifier - the resolved VmIdentifier. If vmid was resolved335* on entry to this method, then the returned336* VmIdentifier will be equal, but not identical, to337* vmid.338*/339public VmIdentifier resolve(VmIdentifier vmid)340throws URISyntaxException, MonitorException {341String scheme = vmid.getScheme();342String host = vmid.getHost();343String authority = vmid.getAuthority();344345if ((scheme != null) && (scheme.compareTo("file") == 0)) {346// don't attempt to resolve a file based VmIdentifier.347return vmid;348}349350if ((host != null) && (host.compareTo(authority) == 0)) {351/*352* this condition occurs when the VmIdentifier specifies only353* the authority (i.e. an lvmid), and not a host name.354*/355host = null;356}357358if (scheme == null) {359scheme = getScheme();360}361362URI nuri = null;363364StringBuilder sb = new StringBuilder();365366sb.append(scheme).append("://");367368String userInfo = vmid.getUserInfo();369if (userInfo != null) {370sb.append(userInfo);371} else {372sb.append(vmid.getAuthority());373}374375if (host == null) {376host = getHost();377}378sb.append("@").append(host);379380int port = vmid.getPort();381if (port == -1) {382port = getPort();383}384385if (port != -1) {386sb.append(":").append(port);387}388389String path = vmid.getPath();390if ((path == null) || (path.length() == 0)) {391path = getPath();392}393394if ((path != null) && (path.length() > 0)) {395sb.append(path);396}397398String query = vmid.getQuery();399if (query == null) {400query = getQuery();401}402if (query != null) {403sb.append("?").append(query);404}405406String fragment = vmid.getFragment();407if (fragment == null) {408fragment = getFragment();409}410if (fragment != null) {411sb.append("#").append(fragment);412}413414String s = sb.toString();415return new VmIdentifier(s);416}417418/**419* Return the Scheme, or protocol, portion of this HostIdentifier.420*421* @return String - the scheme for this HostIdentifier.422* @see URI#getScheme()423*/424public String getScheme() {425return uri.isAbsolute() ? uri.getScheme() : null;426}427428/**429* Return the Scheme Specific Part of this HostIdentifier.430*431* @return String - the scheme specific part for this HostIdentifier.432* @see URI#getSchemeSpecificPart()433*/434public String getSchemeSpecificPart() {435return uri.getSchemeSpecificPart();436}437438/**439* Return the User Info part of this HostIdentifier.440*441* @return String - the user info part for this HostIdentifier.442* @see URI#getUserInfo()443*/444public String getUserInfo() {445return uri.getUserInfo();446}447448/**449* Return the Host part of this HostIdentifier.450*451* @return String - the host part for this HostIdentifier, or452* "localhost" if the URI.getHost() returns null.453* @see URI#getUserInfo()454*/455public String getHost() {456return (uri.getHost() == null) ? "localhost" : uri.getHost();457}458459/**460* Return the Port for of this HostIdentifier.461*462* @return String - the port for this HostIdentifier463* @see URI#getPort()464*/465public int getPort() {466return uri.getPort();467}468469/**470* Return the Path part of this HostIdentifier.471*472* @return String - the path part for this HostIdentifier.473* @see URI#getPath()474*/475public String getPath() {476return uri.getPath();477}478479/**480* Return the Query part of this HostIdentifier.481*482* @return String - the query part for this HostIdentifier.483* @see URI#getQuery()484*/485public String getQuery() {486return uri.getQuery();487}488489/**490* Return the Fragment part of this HostIdentifier.491*492* @return String - the fragment part for this HostIdentifier.493* @see URI#getFragment()494*/495public String getFragment() {496return uri.getFragment();497}498499/**500* Return the mode indicated in this HostIdentifier.501*502* @return String - the mode string. If no mode is specified, then "r"503* is returned. otherwise, the specified mode is returned.504*/505public String getMode() {506String query = getQuery();507if (query != null) {508String[] queryArgs = query.split("\\+");509for (int i = 0; i < queryArgs.length; i++) {510if (queryArgs[i].startsWith("mode=")) {511int index = queryArgs[i].indexOf('=');512return queryArgs[i].substring(index+1);513}514}515}516return "r";517}518519/**520* Return the URI associated with the HostIdentifier.521*522* @return URI - the URI.523* @see URI524*/525public URI getURI() {526return uri;527}528529/**530* Return the hash code for this HostIdentifier. The hash code is531* identical to the hash code for the contained URI.532*533* @return int - the hashcode.534* @see URI#hashCode()535*/536public int hashCode() {537return uri.hashCode();538}539540/**541* Test for quality with other objects.542*543* @param object the object to be test for equality.544* @return boolean - returns true if the given object is of type545* HostIdentifier and its URI field is equal to this546* object's URI field. Otherwise, returns false.547*548* @see URI#equals(Object)549*/550public boolean equals(Object object) {551if (object == this) {552return true;553}554if (!(object instanceof HostIdentifier)) {555return false;556}557return uri.equals(((HostIdentifier)object).uri);558}559560561/**562* Convert to a string representation. Conversion is identical to563* calling getURI().toString(). This may change in a future release.564*565* @return String - a String representation of the HostIdentifier.566*567* @see URI#toString()568*/569public String toString() {570return uri.toString();571}572}573574575