|
| 1 | +package com.acme.modres; |
| 2 | + |
| 3 | +import com.acme.modres.db.ModResortsCustomerInformation; |
| 4 | +import com.acme.modres.exception.ExceptionHandler; |
| 5 | +import com.acme.modres.mbean.AppInfo; |
| 6 | + |
| 7 | +import java.io.BufferedReader; |
| 8 | + |
| 9 | +import java.io.IOException; |
| 10 | +import java.io.InputStreamReader; |
| 11 | +import java.io.Serializable; |
| 12 | +import java.lang.management.ManagementFactory; |
| 13 | +import java.net.HttpURLConnection; |
| 14 | +import java.net.MalformedURLException; |
| 15 | +import java.net.ProtocolException; |
| 16 | +import java.net.URI; |
| 17 | +import java.net.URL; |
| 18 | +import java.util.Hashtable; |
| 19 | +import java.util.logging.Level; |
| 20 | +import java.util.logging.Logger; |
| 21 | + |
| 22 | +import javax.servlet.ServletException; |
| 23 | +import javax.servlet.ServletOutputStream; |
| 24 | +import javax.servlet.http.HttpServlet; |
| 25 | +import javax.servlet.http.HttpServletRequest; |
| 26 | +import javax.servlet.http.HttpServletResponse; |
| 27 | + |
| 28 | +import javax.inject.Inject; |
| 29 | +import javax.management.InstanceAlreadyExistsException; |
| 30 | +import javax.management.InstanceNotFoundException; |
| 31 | +import javax.management.IntrospectionException; |
| 32 | +import javax.management.MBeanInfo; |
| 33 | +import javax.management.MBeanRegistrationException; |
| 34 | +import javax.management.MBeanServer; |
| 35 | +import javax.management.MalformedObjectNameException; |
| 36 | +import javax.management.NotCompliantMBeanException; |
| 37 | +import javax.management.ObjectInstance; |
| 38 | +import javax.management.ObjectName; |
| 39 | +import javax.management.ReflectionException; |
| 40 | +import javax.naming.InitialContext; |
| 41 | +import javax.naming.NamingException; |
| 42 | +import javax.servlet.annotation.WebServlet; |
| 43 | + |
| 44 | +// changed annotation |
| 45 | +@WebServlet( |
| 46 | + name={"weather"}, |
| 47 | + urlPatterns={"/resorts/weather"} |
| 48 | +) |
| 49 | +public class WeatherServlet extends HttpServlet implements Serializable { // changed declaration |
| 50 | + private static final long serialVersionUID = 1L; // added comment |
| 51 | + |
| 52 | + @Inject |
| 53 | + private ModResortsCustomerInformation customerInfo; // mod |
| 54 | + |
| 55 | + private int newField; // added field |
| 56 | + |
| 57 | + // local OS environment variable key name. The key value should provide an API |
| 58 | + // key that will be used to |
| 59 | + // get weather information from site: http://www.wunderground.com |
| 60 | + private static final String WEATHER_API_KEY = "WEATHER_API_KEY"; |
| 61 | + |
| 62 | + private static final Logger logger = Logger.getLogger(WeatherServlet.class.getName()); |
| 63 | + |
| 64 | + private static InitialContext context; |
| 65 | + |
| 66 | + MBeanServer server; |
| 67 | + ObjectName weatherON; |
| 68 | + ObjectInstance mbean; |
| 69 | + |
| 70 | + @Override |
| 71 | + public void init() { |
| 72 | + server = ManagementFactory.getPlatformMBeanServer(); |
| 73 | + try { |
| 74 | + weatherON = new ObjectName("com.acme.modres.mbean:name=appInfo"); |
| 75 | + } catch (MalformedObjectNameException e) { |
| 76 | + // TODO Auto-generated catch block |
| 77 | + e.printStackTrace(); |
| 78 | + } |
| 79 | + try { |
| 80 | + if (weatherON != null) { |
| 81 | + mbean = server.registerMBean(new AppInfo(), weatherON); |
| 82 | + } |
| 83 | + } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { |
| 84 | + e.printStackTrace(); |
| 85 | + } |
| 86 | + context = setInitialContextProps(); |
| 87 | + } |
| 88 | + |
| 89 | + @Override |
| 90 | + public void destroy() { |
| 91 | + if (mbean != null) { |
| 92 | + try { |
| 93 | + server.unregisterMBean(weatherON); |
| 94 | + } catch (MBeanRegistrationException | InstanceNotFoundException e) { |
| 95 | + // TODO Auto-generated catch block |
| 96 | + System.out.println(e.getMessage()); |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + @Override |
| 102 | + protected void doGet(HttpServletRequest request, |
| 103 | + HttpServletResponse response) throws IOException, ServletException { |
| 104 | + |
| 105 | + String methodName = "doGet"; |
| 106 | + logger.entering(WeatherServlet.class.getName(), methodName); |
| 107 | + |
| 108 | + try { |
| 109 | + MBeanInfo weatherConfig = server.getMBeanInfo(weatherON); |
| 110 | + } catch (IntrospectionException | InstanceNotFoundException | ReflectionException e) { |
| 111 | + e.printStackTrace(); |
| 112 | + } |
| 113 | + |
| 114 | + String city = request.getParameter("selectedCity"); |
| 115 | + logger.log(Level.FINE, "requested city is " + city); |
| 116 | + |
| 117 | + String weatherAPIKey = System.getenv(WEATHER_API_KEY); |
| 118 | + String mockedKey = mockKey(weatherAPIKey); |
| 119 | + logger.log(Level.FINE, "weatherAPIKey is " + mockedKey); |
| 120 | + |
| 121 | + if (weatherAPIKey != null && weatherAPIKey.trim().length() > 0) { |
| 122 | + logger.info("weatherAPIKey is found, system will provide the real time weather data for the city " + city); |
| 123 | + getRealTimeWeatherData(city, weatherAPIKey, response); |
| 124 | + } else { |
| 125 | + logger.info( |
| 126 | + "weatherAPIKey is not found, will provide the weather data dated August 10th, 2018 for the city " + city); |
| 127 | + getDefaultWeatherData(city, response); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private void getRealTimeWeatherData(String city, String apiKey, HttpServletResponse response) |
| 132 | + throws ServletException, IOException { |
| 133 | + String resturl = null; |
| 134 | + String resturlbase = Constants.WUNDERGROUND_API_PREFIX + apiKey + Constants.WUNDERGROUND_API_PART; |
| 135 | + |
| 136 | + if (Constants.PARIS.equals(city)) { |
| 137 | + resturl = resturlbase + "France/Paris.json"; |
| 138 | + } else if (Constants.LAS_VEGAS.equals(city)) { |
| 139 | + resturl = resturlbase + "NV/Las_Vegas.json"; |
| 140 | + } else if (Constants.SAN_FRANCISCO.equals(city)) { |
| 141 | + resturl = resturlbase + "/CA/San_Francisco.json"; |
| 142 | + } else if (Constants.MIAMI.equals(city)) { |
| 143 | + resturl = resturlbase + "FL/Miami.json"; |
| 144 | + } else if (Constants.CORK.equals(city)) { |
| 145 | + resturl = resturlbase + "ireland/cork.json"; |
| 146 | + } else if (Constants.BARCELONA.equals(city)) { |
| 147 | + resturl = resturlbase + "Spain/Barcelona.json"; |
| 148 | + } else { |
| 149 | + String errorMsg = "Sorry, the weather information for your selected city: " + city + |
| 150 | + " is not available. Valid selections are: " + Constants.SUPPORTED_CITIES; |
| 151 | + ExceptionHandler.handleException(null, errorMsg, logger); |
| 152 | + } |
| 153 | + |
| 154 | + URL obj = null; |
| 155 | + HttpURLConnection con = null; |
| 156 | + try { |
| 157 | + obj = URI.create(resturl).toURL(); |
| 158 | + con = (HttpURLConnection) obj.openConnection(); |
| 159 | + con.setRequestMethod("GET"); |
| 160 | + } catch (MalformedURLException e1) { |
| 161 | + String errorMsg = "Caught MalformedURLException. Please make sure the url is correct."; |
| 162 | + ExceptionHandler.handleException(e1, errorMsg, logger); |
| 163 | + } catch (ProtocolException e2) { |
| 164 | + String errorMsg = "Caught ProtocolException: " + e2.getMessage() |
| 165 | + + ". Not able to set request method to http connection."; |
| 166 | + ExceptionHandler.handleException(e2, errorMsg, logger); |
| 167 | + } catch (IOException e3) { |
| 168 | + String errorMsg = "Caught IOException: " + e3.getMessage() + ". Not able to open connection."; |
| 169 | + ExceptionHandler.handleException(e3, errorMsg, logger); |
| 170 | + } |
| 171 | + |
| 172 | + int responseCode = con.getResponseCode(); |
| 173 | + logger.log(Level.FINEST, "Response Code: " + responseCode); |
| 174 | + |
| 175 | + if (responseCode >= 200 && responseCode < 300) { |
| 176 | + |
| 177 | + BufferedReader in = null; |
| 178 | + ServletOutputStream out = null; |
| 179 | + |
| 180 | + try { |
| 181 | + in = new BufferedReader(new InputStreamReader(con.getInputStream())); |
| 182 | + String inputLine = null; |
| 183 | + StringBuffer responseStr = new StringBuffer(); |
| 184 | + |
| 185 | + while ((inputLine = in.readLine()) != null) { |
| 186 | + responseStr.append(inputLine); |
| 187 | + } |
| 188 | + |
| 189 | + response.setContentType("application/json"); |
| 190 | + out = response.getOutputStream(); |
| 191 | + out.print(responseStr.toString()); |
| 192 | + logger.log(Level.FINE, "responseStr: " + responseStr); |
| 193 | + } catch (Exception e) { |
| 194 | + String errorMsg = "Problem occured when processing the weather server response."; |
| 195 | + ExceptionHandler.handleException(e, errorMsg, logger); |
| 196 | + } finally { |
| 197 | + if (in != null) { |
| 198 | + in.close(); |
| 199 | + } |
| 200 | + if (out != null) { |
| 201 | + out.close(); |
| 202 | + } |
| 203 | + in = null; |
| 204 | + out = null; |
| 205 | + } |
| 206 | + } else { |
| 207 | + String errorMsg = "REST API call " + resturl + " returns an error response: " + responseCode; |
| 208 | + ExceptionHandler.handleException(null, errorMsg, logger); |
| 209 | + } |
| 210 | + } |
| 211 | + |
| 212 | + private void getDefaultWeatherData(String city, HttpServletResponse response) |
| 213 | + throws ServletException, IOException { |
| 214 | + DefaultWeatherData defaultWeatherData = null; |
| 215 | + |
| 216 | + try { |
| 217 | + defaultWeatherData = new DefaultWeatherData(city); |
| 218 | + } catch (UnsupportedOperationException e) { |
| 219 | + ExceptionHandler.handleException(e, e.getMessage(), logger); |
| 220 | + } |
| 221 | + |
| 222 | + ServletOutputStream out = null; |
| 223 | + |
| 224 | + try { |
| 225 | + String responseStr = defaultWeatherData.getDefaultWeatherData(); |
| 226 | + response.setContentType("application/json"); |
| 227 | + out = response.getOutputStream(); |
| 228 | + out.print(responseStr.toString()); |
| 229 | + logger.log(Level.FINEST, "responseStr: " + responseStr); |
| 230 | + } catch (Exception e) { |
| 231 | + String errorMsg = "Problem occured when getting the default weather data."; |
| 232 | + ExceptionHandler.handleException(e, errorMsg, logger); |
| 233 | + } finally { |
| 234 | + |
| 235 | + if (out != null) { |
| 236 | + out.close(); |
| 237 | + } |
| 238 | + |
| 239 | + out = null; |
| 240 | + } |
| 241 | + } |
| 242 | + |
| 243 | + /** |
| 244 | + * Returns the weather information for a given city |
| 245 | + */ |
| 246 | + protected void doPost(HttpServletRequest request, HttpServletResponse response) |
| 247 | + throws ServletException, IOException { |
| 248 | + |
| 249 | + doGet(request, response); |
| 250 | + } |
| 251 | + |
| 252 | + private static String mockKey(String toBeMocked) { |
| 253 | + if (toBeMocked == null) { |
| 254 | + return null; |
| 255 | + } |
| 256 | + String lastToKeep = toBeMocked.substring(toBeMocked.length() - 3); |
| 257 | + return "*********" + lastToKeep; |
| 258 | + } |
| 259 | + |
| 260 | + private String configureEnvDiscovery() { |
| 261 | + |
| 262 | + String serverEnv = ""; |
| 263 | + |
| 264 | + serverEnv += System.getProperty("wlp.server.name"); |
| 265 | + serverEnv += System.getProperty("wlp.server.name"); |
| 266 | + |
| 267 | + return serverEnv; |
| 268 | + } |
| 269 | + |
| 270 | + private InitialContext setInitialContextProps() { |
| 271 | + |
| 272 | + Hashtable ht = new Hashtable(); |
| 273 | + |
| 274 | + InitialContext ctx = null; |
| 275 | + try { |
| 276 | + ctx = new InitialContext(ht); |
| 277 | + } catch (NamingException e) { |
| 278 | + e.printStackTrace(); |
| 279 | + } |
| 280 | + |
| 281 | + return ctx; |
| 282 | + } |
| 283 | +} |
0 commit comments