View Javadoc

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