1/*
2 * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.jvmstat.monitor;
27
28import java.net.*;
29
30/**
31 * An abstraction that identifies a target host and communications
32 * protocol. The HostIdentifier, or hostid, provides a convenient string
33 * representation of the information needed to locate and communicate with
34 * a target host. The string, based on a {@link URI}, may specify the
35 * the communications protocol, host name, and protocol specific information
36 * for a target host. The format for a HostIdentifier string is:
37 * <pre>
38 *       [<I>protocol</I>:][[<I>//</I>]<I>hostname</I>][<I>:port</I>][<I>/servername</I>]
39 * </pre>
40 * There are actually no required components of this string, as a null string
41 * is interpreted to mean a local connection to the local host and is equivalent
42 * to the string <em>local://localhost</em>. The components of the
43 * HostIdentifier are:
44 * <ul>
45 *   <li><p>{@code protocol} - The communications protocol. If omitted,
46 *          and a hostname is not specified, then default local protocol,
47 *          <em>local:</em>, is assumed. If the protocol is omitted and a
48 *          hostname is specified then the default remote protocol,
49 *          <em>rmi:</em> is assumed.
50 *       </p></li>
51 *   <li><p>{@code hostname} - The hostname. If omitted, then
52 *          <em>localhost</em> is assumed. If the protocol is also omitted,
53 *          then default local protocol <em>local:</em> is also assumed.
54 *          If the hostname is not omitted but the protocol is omitted,
55 *          then the default remote protocol, <em>rmi:</em> is assumed.
56 *       </p></li>
57 *   <li><p>{@code port} - The port for the communications protocol.
58 *          Treatment of the {@code port} parameter is implementation
59 *          (protocol) specific. It is unused by the default local protocol,
60 *          <em>local:</em>. For the default remote protocol, <em>rmi:</em>,
61 *          {@code port} indicates the port number of the <em>rmiregistry</em>
62 *          on the target host and defaults to port 1099.
63 *       </p></li>
64 *   <li><p>{@code servername} - The treatment of the Path, Query, and
65 *          Fragment components of the HostIdentifier are implementation
66 *          (protocol) dependent. These components are ignored by the
67 *          default local protocol, <em>local:</em>. For the default remote
68 *          protocol, <em>rmi</em>, the Path component is interpreted as
69 *          the name of the RMI remote object. The Query component may
70 *          contain an access mode specifier <em>?mode=</em> specifying
71 *          <em>"r"</em> or <em>"rw"</em> access (write access currently
72 *          ignored). The Fragment part is ignored.
73 *       </p></li>
74 * </ul>
75 * <p>
76 * All HostIdentifier objects are represented as absolute, hierarchical URIs.
77 * The constructors accept relative URIs, but these will generally be
78 * transformed into an absolute URI specifying a default protocol. A
79 * HostIdentifier differs from a URI in that certain contractions and
80 * illicit syntactical constructions are allowed. The following are all
81 * valid HostIdentifier strings:
82 *
83 * <ul>
84 *   <li>{@code <null>} - transformed into "//localhost"</li>
85 *   <li>localhost - transformed into "//localhost"</li>
86 *   <li>hostname - transformed into "//hostname"</li>
87 *   <li>hostname:port - transformed into "//hostname:port"</li>
88 *   <li>proto:hostname - transformed into "proto://hostname"</li>
89 *   <li>proto:hostname:port - transformed into
90 *          "proto://hostname:port"</li>
91 *   <li>proto://hostname:port</li>
92 * </ul>
93 *
94 * @see URI
95 * @see VmIdentifier
96 *
97 * @author Brian Doherty
98 * @since 1.5
99 */
100public class HostIdentifier {
101    private URI uri;
102
103    /**
104     * creates a canonical representation of the uriString. This method
105     * performs certain translations depending on the type of URI generated
106     * by the string.
107     */
108    private URI canonicalize(String uriString) throws URISyntaxException {
109        if ((uriString == null) || (uriString.compareTo("localhost") == 0)) {
110            uriString = "//localhost";
111            return new URI(uriString);
112        }
113
114        URI u = new URI(uriString);
115
116        if (u.isAbsolute()) {
117            if (u.isOpaque()) {
118                /*
119                 * this code is here to deal with a special case. For ease of
120                 * use, we'd like to be able to handle the case where the user
121                 * specifies hostname:port, not requiring the scheme part.
122                 * This introduces some subtleties.
123                 *     hostname:port - scheme = hostname
124                 *                   - schemespecificpart = port
125                 *                   - hostname = null
126                 *                   - userinfo=null
127                 * however, someone could also enter scheme:hostname:port and
128                 * get into this code. the strategy is to consider this
129                 * syntax illegal and provide some code to defend against it.
130                 * Basically, we test that the string contains only one ":"
131                 * and that the ssp is numeric. If we get two colons, we will
132                 * attempt to insert the "//" after the first colon and then
133                 * try to create a URI from the resulting string.
134                 */
135                String scheme = u.getScheme();
136                String ssp = u.getSchemeSpecificPart();
137                String frag = u.getFragment();
138                URI u2 = null;
139
140                int c1index = uriString.indexOf(':');
141                int c2index = uriString.lastIndexOf(':');
142                if (c2index != c1index) {
143                    /*
144                     * this is the scheme:hostname:port case. Attempt to
145                     * transform this to scheme://hostname:port. If a path
146                     * part is part of the original strings, it will be
147                     * included in the SchemeSpecificPart. however, the
148                     * fragment part must be handled separately.
149                     */
150                    if (frag == null) {
151                        u2 = new URI(scheme + "://" + ssp);
152                    } else {
153                        u2 = new URI(scheme + "://" + ssp + "#" + frag);
154                    }
155                    return u2;
156                }
157                /*
158                 * here we have the <string>:<string> case, possibly with
159                 * optional path and fragment components. we assume that
160                 * the part following the colon is a number. we don't check
161                 * this condition here as it will get detected later anyway.
162                 */
163                u2 = new URI("//" + uriString);
164                return u2;
165            } else {
166                return u;
167            }
168        } else {
169            /*
170             * This is the case where we were given a hostname followed
171             * by a path part, fragment part, or both a path and fragment
172             * part. The key here is that no scheme part was specified.
173             * For this case, if the scheme specific part does not begin
174             * with "//", then we prefix the "//" to the given string and
175             * attempt to create a URI from the resulting string.
176             */
177            String ssp = u.getSchemeSpecificPart();
178            if (ssp.startsWith("//")) {
179                return u;
180            } else {
181                return new URI("//" + uriString);
182            }
183        }
184    }
185
186    /**
187     * Create a HostIdentifier instance from a string value.
188     *
189     * @param uriString a string representing a target host. The syntax of
190     *                  the string must conform to the rules specified in the
191     *                  class documentation.
192     *
193     * @throws URISyntaxException Thrown when the uriString or its canonical
194     *                            form is poorly formed. This exception may
195     *                            get encapsulated into a MonitorException in
196     *                            a future version.
197     *
198     */
199    public HostIdentifier(String uriString) throws URISyntaxException {
200        uri = canonicalize(uriString);
201    }
202
203    /**
204     * Create a HostIdentifier instance from component parts of a URI.
205     *
206     * @param scheme the {@link URI#getScheme} component of a URI.
207     * @param authority the {@link URI#getAuthority} component of a URI.
208     * @param path the {@link URI#getPath} component of a URI.
209     * @param query the {@link URI#getQuery} component of a URI.
210     * @param fragment the {@link URI#getFragment} component of a URI.
211     *
212     * @throws URISyntaxException Thrown when the uriString or its canonical
213     *                            form is poorly formed. This exception may
214     *                            get encapsulated into a MonitorException in
215     *                            a future version.
216     * @see URI
217     */
218    public HostIdentifier(String scheme, String authority, String path,
219                          String query, String fragment)
220           throws URISyntaxException {
221        uri = new URI(scheme, authority, path, query, fragment);
222    }
223
224    /**
225     * Create a HostIdentifier instance from a VmIdentifier.
226     *
227     * The necessary components of the VmIdentifier are extracted and
228     * reassembled into a HostIdentifier. If a "file:" scheme (protocol)
229     * is specified, the returned HostIdentifier will always be
230     * equivalent to HostIdentifier("file://localhost").
231     *
232     * @param vmid the VmIdentifier use to construct the HostIdentifier.
233     */
234    public HostIdentifier(VmIdentifier vmid) {
235        /*
236         * Extract all components of the VmIdentifier URI except the
237         * user-info part of the authority (the lvmid).
238         */
239        StringBuilder sb = new StringBuilder();
240        String scheme = vmid.getScheme();
241        String host = vmid.getHost();
242        String authority = vmid.getAuthority();
243
244        // check for 'file:' VmIdentifiers and handled as a special case.
245        if ((scheme != null) && (scheme.compareTo("file") == 0)) {
246            try {
247                uri = new URI("file://localhost");
248            } catch (URISyntaxException e) { };
249            return;
250        }
251
252        if ((host != null) && (host.compareTo(authority) == 0)) {
253            /*
254             * this condition occurs when the VmIdentifier specifies only
255             * the authority (i.e. the lvmid ), and not a host name.
256             */
257            host = null;
258        }
259
260        if (scheme == null) {
261            if (host == null) {
262                scheme = "local";            // default local scheme
263            } else {
264                /*
265                 * rmi is the default remote scheme. if the VmIdentifier
266                 * specifies some other protocol, this default is overridden.
267                 */
268                scheme = "rmi";
269            }
270        }
271
272        sb.append(scheme).append("://");
273
274        if (host == null) {
275            sb.append("localhost");          // default host name
276        } else {
277            sb.append(host);
278        }
279
280        int port = vmid.getPort();
281        if (port != -1) {
282            sb.append(":").append(port);
283        }
284
285        String path = vmid.getPath();
286        if ((path != null) && (path.length() != 0)) {
287            sb.append(path);
288        }
289
290        String query = vmid.getQuery();
291        if (query != null) {
292            sb.append("?").append(query);
293        }
294
295        String frag = vmid.getFragment();
296        if (frag != null) {
297            sb.append("#").append(frag);
298        }
299
300        try {
301           uri = new URI(sb.toString());
302        } catch (URISyntaxException e) {
303           // shouldn't happen, as we were passed a valid VmIdentifier
304           throw new RuntimeException("Internal Error", e);
305        }
306    }
307
308    /**
309     * Resolve a VmIdentifier with this HostIdentifier. A VmIdentifier, such
310     * as <em>1234</em> or <em>1234@hostname</em> or any other string that
311     * omits certain components of the URI string may be valid, but is certainly
312     * incomplete. They are missing critical information for identifying the
313     * the communications protocol, target host, or other parameters. A
314     * VmIdentifier of this form is considered <em>unresolved</em>. This method
315     * uses components of the HostIdentifier to resolve the missing components
316     * of the VmIdentifier.
317     * <p>
318     * Specified components of the unresolved VmIdentifier take precedence
319     * over their HostIdentifier counterparts. For example, if the VmIdentifier
320     * indicates <em>1234@hostname:2099</em> and the HostIdentifier indicates
321     * <em>rmi://hostname:1099/</em>, then the resolved VmIdentifier will
322     * be <em>rmi://1234@hostname:2099</em>. Any component not explicitly
323     * specified or assumed by the HostIdentifier, will remain unresolved in
324     * resolved VmIdentifier.
325     *  <p>
326     * A VmIdentifier specifying a <em>file:</em> scheme (protocol), is
327     * not changed in any way by this method.
328     *
329     * @param vmid the unresolved VmIdentifier.
330     * @return VmIdentifier - the resolved VmIdentifier. If vmid was resolved
331     *                        on entry to this method, then the returned
332     *                        VmIdentifier will be equal, but not identical, to
333     *                        vmid.
334     */
335    public VmIdentifier resolve(VmIdentifier vmid)
336           throws URISyntaxException, MonitorException {
337        String scheme = vmid.getScheme();
338        String host = vmid.getHost();
339        String authority = vmid.getAuthority();
340
341        if ((scheme != null) && (scheme.compareTo("file") == 0)) {
342            // don't attempt to resolve a file based VmIdentifier.
343            return vmid;
344        }
345
346        if ((host != null) && (host.compareTo(authority) == 0)) {
347            /*
348             * this condition occurs when the VmIdentifier specifies only
349             * the authority (i.e. an lvmid), and not a host name.
350             */
351            host = null;
352        }
353
354        if (scheme == null) {
355            scheme = getScheme();
356        }
357
358        URI nuri = null;
359
360        StringBuilder sb = new StringBuilder();
361
362        sb.append(scheme).append("://");
363
364        String userInfo = vmid.getUserInfo();
365        if (userInfo != null) {
366            sb.append(userInfo);
367        } else {
368            sb.append(vmid.getAuthority());
369        }
370
371        if (host == null) {
372            host = getHost();
373        }
374        sb.append("@").append(host);
375
376        int port = vmid.getPort();
377        if (port == -1) {
378            port = getPort();
379        }
380
381        if (port != -1) {
382            sb.append(":").append(port);
383        }
384
385        String path = vmid.getPath();
386        if ((path == null) || (path.length() == 0)) {
387            path = getPath();
388        }
389
390        if ((path != null) && (path.length() > 0)) {
391            sb.append(path);
392        }
393
394        String query = vmid.getQuery();
395        if (query == null) {
396            query = getQuery();
397        }
398        if (query != null) {
399            sb.append("?").append(query);
400        }
401
402        String fragment = vmid.getFragment();
403        if (fragment == null) {
404            fragment = getFragment();
405        }
406        if (fragment != null) {
407            sb.append("#").append(fragment);
408        }
409
410        String s = sb.toString();
411        return new VmIdentifier(s);
412    }
413
414    /**
415     * Return the Scheme, or protocol, portion of this HostIdentifier.
416     *
417     * @return String - the scheme for this HostIdentifier.
418     * @see URI#getScheme()
419     */
420    public String getScheme() {
421        return uri.isAbsolute() ? uri.getScheme() : null;
422    }
423
424    /**
425     * Return the Scheme Specific Part of this HostIdentifier.
426     *
427     * @return String - the scheme specific part for this HostIdentifier.
428     * @see URI#getSchemeSpecificPart()
429     */
430    public String getSchemeSpecificPart() {
431        return  uri.getSchemeSpecificPart();
432    }
433
434    /**
435     * Return the User Info part of this HostIdentifier.
436     *
437     * @return String - the user info part for this HostIdentifier.
438     * @see URI#getUserInfo()
439     */
440    public String getUserInfo() {
441        return uri.getUserInfo();
442    }
443
444    /**
445     * Return the Host part of this HostIdentifier.
446     *
447     * @return String - the host part for this HostIdentifier, or
448     *                  "localhost" if the URI.getHost() returns null.
449     * @see URI#getUserInfo()
450     */
451    public String getHost() {
452        return (uri.getHost() == null) ? "localhost" : uri.getHost();
453    }
454
455    /**
456     * Return the Port for of this HostIdentifier.
457     *
458     * @return String - the port for this HostIdentifier
459     * @see URI#getPort()
460     */
461    public int getPort() {
462        return uri.getPort();
463    }
464
465    /**
466     * Return the Path part of this HostIdentifier.
467     *
468     * @return String - the path part for this HostIdentifier.
469     * @see URI#getPath()
470     */
471    public String getPath() {
472        return uri.getPath();
473    }
474
475    /**
476     * Return the Query part of this HostIdentifier.
477     *
478     * @return String - the query part for this HostIdentifier.
479     * @see URI#getQuery()
480     */
481    public String getQuery() {
482        return uri.getQuery();
483    }
484
485    /**
486     * Return the Fragment part of this HostIdentifier.
487     *
488     * @return String - the fragment part for this HostIdentifier.
489     * @see URI#getFragment()
490     */
491    public String getFragment() {
492        return uri.getFragment();
493    }
494
495    /**
496     * Return the mode indicated in this HostIdentifier.
497     *
498     * @return String - the mode string. If no mode is specified, then "r"
499     *                  is returned. otherwise, the specified mode is returned.
500     */
501    public String getMode() {
502        String query = getQuery();
503        if (query != null) {
504            String[] queryArgs = query.split("\\+");
505            for (int i = 0; i < queryArgs.length; i++) {
506                if (queryArgs[i].startsWith("mode=")) {
507                    int index = queryArgs[i].indexOf('=');
508                    return queryArgs[i].substring(index+1);
509                }
510            }
511        }
512        return "r";
513    }
514
515    /**
516     * Return the URI associated with the HostIdentifier.
517     *
518     * @return URI - the URI.
519     * @see URI
520     */
521    public URI getURI() {
522        return uri;
523    }
524
525    /**
526     * Return the hash code for this HostIdentifier. The hash code is
527     * identical to the hash code for the contained URI.
528     *
529     * @return int - the hashcode.
530     * @see URI#hashCode()
531     */
532    public int hashCode() {
533        return uri.hashCode();
534    }
535
536    /**
537     * Test for quality with other objects.
538     *
539     * @param object the object to be test for equality.
540     * @return boolean - returns true if the given object is of type
541     *                   HostIdentifier and its URI field is equal to this
542     *                   object's URI field. Otherwise, returns false.
543     *
544     * @see URI#equals(Object)
545     */
546    public boolean equals(Object object) {
547        if (object == this) {
548            return true;
549        }
550        if (!(object instanceof HostIdentifier)) {
551            return false;
552        }
553        return uri.equals(((HostIdentifier)object).uri);
554    }
555
556
557    /**
558     * Convert to a string representation. Conversion is identical to
559     * calling getURI().toString(). This may change in a future release.
560     *
561     * @return String - a String representation of the HostIdentifier.
562     *
563     * @see URI#toString()
564     */
565    public String toString() {
566        return uri.toString();
567    }
568}
569