View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.commons.text.lookup;
18  
19  import java.net.InetAddress;
20  import java.net.UnknownHostException;
21  
22  /**
23   * Looks up keys related to the local host: host name, canonical host name, host address.
24   * <p>
25   * The lookup keys are:
26   * </p>
27   * <ul>
28   * <li><b>name</b>: for the local host name, for example {@code EXAMPLE}.</li>
29   * <li><b>canonical-name</b>: for the local canonical host name, for example {@code EXAMPLE.apache.org}.</li>
30   * <li><b>address</b>: for the local host address, for example {@code 192.168.56.1}.</li>
31   * </ul>
32   *
33   * @since 1.3
34   */
35  final class LocalHostStringLookup extends AbstractStringLookup {
36  
37      /**
38       * Defines the singleton for this class.
39       */
40      static final LocalHostStringLookup INSTANCE = new LocalHostStringLookup();
41  
42      /**
43       * No need to build instances for now.
44       */
45      private LocalHostStringLookup() {
46          // empty
47      }
48  
49      /**
50       * Looks up the value of a local host key.
51       *
52       * @param key the key to be looked up, may be null.
53       * @return The value of the environment variable.
54       */
55      @Override
56      public String lookup(final String key) {
57          if (key == null) {
58              return null;
59          }
60          try {
61              switch (key) {
62              case InetAddressKeys.KEY_NAME:
63                  return InetAddress.getLocalHost().getHostName();
64              case InetAddressKeys.KEY_CANONICAL_NAME:
65                  return InetAddress.getLocalHost().getCanonicalHostName();
66              case InetAddressKeys.KEY_ADDRESS:
67                  return InetAddress.getLocalHost().getHostAddress();
68              default:
69                  throw new IllegalArgumentException(key);
70              }
71          } catch (final UnknownHostException e) {
72              return null;
73          }
74      }
75  }