View Javadoc

1   /**
2    * Copyright 2005-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.core.api.util;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.rice.core.api.config.property.ConfigContext;
20  import org.springframework.core.io.DefaultResourceLoader;
21  import org.springframework.core.io.FileSystemResource;
22  import org.springframework.core.io.FileSystemResourceLoader;
23  import org.springframework.core.io.Resource;
24  
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.net.InetAddress;
28  import java.net.MalformedURLException;
29  import java.net.NetworkInterface;
30  import java.net.SocketException;
31  import java.net.UnknownHostException;
32  import java.util.Enumeration;
33  
34  /**
35   *
36   * @author Kuali Rice Team (rice.collab@kuali.org)
37   */
38  public final class RiceUtilities {
39      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(RiceUtilities.class);
40  
41  	private static String instanceIpAddress;
42  	private static String instanceHostName;
43  	
44  	private RiceUtilities() {
45  		throw new UnsupportedOperationException("do not call");
46  	}
47  
48      public static synchronized String getIpNumber() {
49          if ( instanceIpAddress == null ) {
50              // protect from running upon startup
51              if ( ConfigContext.getCurrentContextConfig() != null ) {
52                  // attempt to load from environment
53                  String ip = System.getProperty("host.ip");
54                  if ( StringUtils.isBlank(ip) ) {
55                      ip = ConfigContext.getCurrentContextConfig().getProperty("host.ip");
56                  }
57                  // if not set at all just return
58                  if ( StringUtils.isBlank(ip) ) {                    
59                      return getCurrentEnvironmentNetworkIp();
60                  } else { 
61                      // ok - it was set in configuration or by this method, set it permanently for this instance
62                      instanceIpAddress = ip;
63                  }
64              } else {
65                  // prior to startup, just return it
66                  return getCurrentEnvironmentNetworkIp();
67              }
68          }
69          return instanceIpAddress;
70      }
71  
72      /** * @return the current environment's IP address, taking into account the Internet connection to any of the available
73  	 *         machine's Network interfaces. Examples of the outputs can be in octatos or in IPV6 format.
74  	 *
75  	 *         fec0:0:0:9:213:e8ff:fef1:b717%4 siteLocal: true isLoopback: false isIPV6: true
76  	 *         ============================================ 130.212.150.216 <<<<<<<<<<<------------- This is the one we
77  	 *         want to grab so that we can. siteLocal: false address the DSP on the network. isLoopback: false isIPV6:
78  	 *         false ==> lo ============================================ 0:0:0:0:0:0:0:1%1 siteLocal: false isLoopback:
79  	 *         true isIPV6: true ============================================ 127.0.0.1 siteLocal: false isLoopback:
80  	 *         true isIPV6: false
81  	 */
82  	private static String getCurrentEnvironmentNetworkIp() {
83  	     Enumeration<NetworkInterface> netInterfaces = null;
84  	     try {
85  	          netInterfaces = NetworkInterface.getNetworkInterfaces();
86  	     } catch (SocketException e) {
87  	          LOG.error("Somehow we have a socket error...",e);
88  	          return "127.0.0.1";
89  	     }
90  
91  	     while (netInterfaces.hasMoreElements()) {
92  	          NetworkInterface ni = netInterfaces.nextElement();
93  	          Enumeration<InetAddress> address = ni.getInetAddresses();
94  	          while (address.hasMoreElements()) {
95  	               InetAddress addr = address.nextElement();
96  	               if (!addr.isLoopbackAddress() && !addr.isSiteLocalAddress()
97  	                         && !(addr.getHostAddress().indexOf(":") > -1)) {
98  	                    return addr.getHostAddress();
99  	               }
100 	          }
101 	     }
102 	     try {
103 	          return InetAddress.getLocalHost().getHostAddress();
104 	     } catch (UnknownHostException e) {
105 	          return "127.0.0.1";
106 	     }
107 	}
108 	
109 	
110 	public static synchronized String getHostName() {
111         if ( instanceHostName == null ) {
112             try {
113                 // protect from running upon startup
114                 if ( ConfigContext.getCurrentContextConfig() != null ) {
115                     String host = System.getProperty("host.name");
116                     if ( StringUtils.isBlank(host) ) {
117                         host = ConfigContext.getCurrentContextConfig().getProperty("host.name");
118                     }
119                     // if not set at all just return
120                     if ( StringUtils.isBlank(host) ) {
121                         return InetAddress.getByName( getCurrentEnvironmentNetworkIp() ).getHostName();
122                     } else { 
123                         // ok - it was set in configuration or by this method, set it permanently for this instance
124                         instanceHostName = host;
125                     }
126                 } else {
127                     // prior to startup, just return it
128                     return InetAddress.getByName( getCurrentEnvironmentNetworkIp() ).getHostName();
129                 }
130             } catch ( Exception ex ) {
131                 return "localhost";
132             }
133         }
134         return instanceHostName;
135 	}
136 
137 	/**
138 	 * The standard Spring FileSystemResourceLoader does not support normal absolute file paths
139 	 * for historical backwards-compatibility reasons.  This class simply circumvents that behavior
140 	 * to allow proper interpretation of absolute paths (i.e. not stripping a leading slash)  
141 	 */
142 	private static class AbsoluteFileSystemResourceLoader extends FileSystemResourceLoader {
143         @Override
144         protected Resource getResourceByPath(String path) {
145             return new FileSystemResource(path);
146         }
147 	}
148 
149 	/**
150 	 * Attempts to retrieve the resource stream.
151 	 * 
152 	 * @param resourceLoc resource location; syntax supported by {@link DefaultResourceLoader} 
153 	 * @return the resource stream or null if the resource could not be obtained
154 	 * @throws MalformedURLException
155 	 * @throws IOException
156 	 * @see DefaultResourceLoader
157 	 */
158 	public static InputStream getResourceAsStream(String resourceLoc) throws MalformedURLException, IOException {
159 	    Resource resource = getResource(resourceLoc);
160 	    if (resource.exists()) {
161 	        return resource.getInputStream();
162 	    }
163 	    return null;
164     }
165 	
166 	/**
167 	 * Returns a handle to the requested Resource.
168 	 * 
169 	 * @param resourceLoc resource location; syntax supported by {@link DefaultResourceLoader}
170 	 * @return a handle to the Resource
171 	 */
172 	private static Resource getResource(String resourceLoc) {
173 		AbsoluteFileSystemResourceLoader resourceLoader = new AbsoluteFileSystemResourceLoader();
174 		resourceLoader.setClassLoader(ClassLoaderUtils.getDefaultClassLoader());
175 	    return resourceLoader.getResource(resourceLoc);
176 	}
177 
178 	/**
179      * This method searches for an exception of the specified type in the stack trace of the given
180      * exception.
181      * @param topLevelException the exception whose stack to traverse
182      * @param exceptionClass the exception class to look for
183      * @return the first instance of an exception of the specified class if found, or null otherwise
184      */
185     public static <T extends Throwable> T findExceptionInStack(Throwable topLevelException, Class<T> exceptionClass) {
186         Throwable t = topLevelException;
187         while (t != null) {
188             if (exceptionClass.isAssignableFrom(t.getClass())) return (T) t;
189             t = t.getCause();
190         }
191         return null;
192     }
193     
194     /**
195      * Converts a given file size in bytes to a unit of bytes, kilobyte,
196      * megabyte, or gigabyte
197      * 
198      * @param fileSize
199      *            - size in bytes
200      * @return String with format 'size units'
201      */
202     public static String getFileSizeUnits(Long fileSize) {
203         Long newFileSize = fileSize;
204         String fileSizeUnits = "bytes";
205 
206         if (fileSize > 1024) {
207             Long kiloSize = fileSize / 1024;
208 
209             if (kiloSize < 1024) {
210                 newFileSize = kiloSize;
211                 fileSizeUnits = "KB";
212             } else {
213                 Long megaSize = kiloSize / 1024;
214 
215                 if (megaSize < 1024) {
216                     newFileSize = megaSize;
217                     fileSizeUnits = "MB";
218                 } else {
219                     Long gigaSize = megaSize / 1024;
220 
221                     newFileSize = gigaSize;
222                     fileSizeUnits = "GB";
223                 }
224             }
225         }
226 
227         return newFileSize + fileSizeUnits;
228     }
229 }