PageRenderTime 69ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/Examples/D2W/ERModernMoviesDemo/Sources/er/modern/movies/demo/JarResourceRequestHandler.java

https://bitbucket.org/molequedeideias/wonder
Java | 275 lines | 208 code | 59 blank | 8 comment | 58 complexity | 600d64e9dc8a84fb7b72923c51cdfd53 MD5 | raw file
  1. package er.modern.movies.demo;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.net.MalformedURLException;
  7. import java.net.URL;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.apache.log4j.Logger;
  10. import com.webobjects.appserver.WOApplication;
  11. import com.webobjects.appserver.WORequest;
  12. import com.webobjects.appserver.WORequestHandler;
  13. import com.webobjects.appserver.WOResourceManager;
  14. import com.webobjects.appserver.WOResponse;
  15. import com.webobjects.appserver._private.WOResourceRequestHandler;
  16. import com.webobjects.appserver._private.WOShared;
  17. import com.webobjects.appserver._private.WOURLValuedElementData;
  18. import com.webobjects.foundation.NSBundle;
  19. import com.webobjects.foundation.NSDictionary;
  20. import com.webobjects.foundation.NSLog;
  21. import com.webobjects.foundation.NSNotificationCenter;
  22. import com.webobjects.foundation.NSPathUtilities;
  23. import er.extensions.foundation.ERXDictionaryUtilities;
  24. import er.extensions.foundation.ERXProperties;
  25. /**
  26. * @author <a href="mailto:hprange@gmail.com.br">Henrique Prange</a>
  27. */
  28. public class JarResourceRequestHandler extends WOResourceRequestHandler {
  29. private static final Logger LOGGER = Logger.getLogger(JarResourceRequestHandler.class);
  30. private final WOApplication _app;
  31. private String _documentRoot;
  32. public JarResourceRequestHandler() {
  33. _app = WOApplication.application();
  34. _documentRoot = null;
  35. }
  36. @SuppressWarnings("all")
  37. protected WOResponse _generateResponseForInputStream(InputStream is, long length, String type) {
  38. WOResponse response = _app.createResponseInContext(null);
  39. if (is != null) {
  40. if (length != 0) {
  41. response.setContentStream(is, 50 * 1024, length);
  42. }
  43. } else {
  44. response.setStatus(404);
  45. }
  46. if (type != null) {
  47. response.setHeader(type, "content-type");
  48. }
  49. if (length != 0) {
  50. response.setHeader("" + length, "content-length");
  51. }
  52. return response;
  53. }
  54. private String documentRoot() {
  55. if (_documentRoot == null) {
  56. _documentRoot = ERXProperties.stringForKey("WODocumentRoot");
  57. if (_documentRoot == null) {
  58. NSBundle bundle = NSBundle.bundleForName("JavaWebObjects");
  59. NSDictionary dict = ERXDictionaryUtilities.dictionaryFromPropertyList("WebServerConfig", bundle);
  60. _documentRoot = (String) dict.objectForKey("DocumentRoot");
  61. }
  62. }
  63. return _documentRoot;
  64. }
  65. protected WOResponse generateResponseForInputStream(InputStream is, long aContentLength, String aContentType) {
  66. WOResponse aResponse = _app.createResponseInContext(null);
  67. if (aContentType != null) {
  68. aResponse.setHeader(aContentType, "content-type");
  69. }
  70. if (is != null && aContentLength != 0L) {
  71. aResponse.setHeader(Long.toString(aContentLength), "content-length");
  72. aResponse.setContentStream(is, 131072, aContentLength);
  73. } else {
  74. LOGGER.warn("The resource was not found. Turn log DEBUG on for more details.");
  75. aResponse.setStatus(404);
  76. aResponse.setHeader(WOShared.unsignedIntString(0), "content-length");
  77. }
  78. return aResponse;
  79. }
  80. @Override
  81. public WOResponse handleRequest(WORequest request) {
  82. WOResponse response = null;
  83. FileInputStream is = null;
  84. int length = 0;
  85. String contentType = null;
  86. String uri = request.uri();
  87. if (uri.charAt(0) == '/') {
  88. WOResourceManager rm = _app.resourceManager();
  89. String documentRoot = documentRoot();
  90. File file = null;
  91. StringBuffer sb = new StringBuffer(documentRoot.length() + uri.length());
  92. String wodataKey = request.stringFormValueForKey("wodata");
  93. if (uri.startsWith("/cgi-bin") && wodataKey != null) {
  94. uri = wodataKey;
  95. if (uri.startsWith("file:")) {
  96. // remove file:/
  97. uri = uri.substring(5);
  98. }
  99. } else {
  100. int index = uri.indexOf("/wodata=");
  101. if (index >= 0) {
  102. uri = uri.substring(index + "/wodata=".length());
  103. } else {
  104. sb.append(documentRoot);
  105. }
  106. }
  107. sb.append(uri);
  108. String path = sb.toString();
  109. try {
  110. path = path.replace('+', ' ');
  111. path = path.replaceAll("\\?.*", "");
  112. file = new File(path);
  113. length = (int) file.length();
  114. is = new FileInputStream(file);
  115. contentType = rm.contentTypeForResourceNamed(path);
  116. LOGGER.debug("Reading file '" + file + "' for uri: " + uri);
  117. } catch (IOException ex) {
  118. if (!uri.toLowerCase().endsWith("/favicon.ico")) {
  119. LOGGER.debug("Unable to get contents of file '" + file + "' for uri: " + uri);
  120. return handleRequestWithResourceInsideJar(request);
  121. }
  122. }
  123. } else {
  124. LOGGER.error("Can't fetch relative path: " + uri);
  125. }
  126. response = _generateResponseForInputStream(is, length, contentType);
  127. NSNotificationCenter.defaultCenter().postNotification(WORequestHandler.DidHandleRequestNotification, response);
  128. response._finalizeInContext(null);
  129. return response;
  130. }
  131. public WOResponse handleRequestWithResourceInsideJar(WORequest request) {
  132. LOGGER.debug("Handling the request for (entire URI) " + request.uri());
  133. boolean requestHandlerContainsPath = false;
  134. String requestHandlerPath = request.requestHandlerPath();
  135. String resourceDataKey = request.stringFormValueForKey("wodata");
  136. if (requestHandlerPath != null
  137. && (requestHandlerPath.endsWith(".class") || requestHandlerPath.endsWith(".jar") || requestHandlerPath.endsWith(".zip") || requestHandlerPath
  138. .endsWith(".table")) && requestHandlerPath.indexOf("..") == requestHandlerPath.indexOf('~')) {
  139. requestHandlerContainsPath = true;
  140. }
  141. WOResponse response = null;
  142. if (requestHandlerContainsPath && _app.isDirectConnectEnabled()) {
  143. LOGGER.debug("The path to resources is (based on request handler path) " + requestHandlerPath);
  144. response = responseForJavaClassAtPath(requestHandlerPath);
  145. } else if (StringUtils.isNotBlank(requestHandlerPath) && resourceDataKey == null) {
  146. // A classe ERXResourceManager altera a URL de forma errada. Ao
  147. // invés de ?wodata=, o Anjo mudou para /wodata=. Isso faz com
  148. // que seja necessário tratarmos aqui essa key.
  149. requestHandlerPath = StringUtils.replace(requestHandlerPath, "wodata=", "");
  150. // Tosca modificacao para carregar recursos no WO541 e Wonder 4 em Windows
  151. requestHandlerPath = StringUtils.replace(requestHandlerPath, "%3A", ":");
  152. LOGGER.debug("The path to resources is (based on a corrected path) " + requestHandlerPath);
  153. URL resourcesUrl = null;
  154. try {
  155. resourcesUrl = new URL("file", "", requestHandlerPath);
  156. response = responseForDataAtURL(resourcesUrl);
  157. } catch (MalformedURLException exception) {
  158. LOGGER.error("An error occurred while trying to handle the resource", exception);
  159. }
  160. } else if (resourceDataKey != null) {
  161. LOGGER.debug("The path to resources is (based on wodata key) " + resourceDataKey);
  162. response = responseForDataCachedWithKey(resourceDataKey);
  163. }
  164. if (response == null) {
  165. LOGGER.warn("THE REQUEST CANNOT BE CORRECTLY HANDLED. GENERATING AN EMPTY RESPONSE.");
  166. String contentType = request.headerForKey("content-type");
  167. if (contentType == null) {
  168. contentType = "text/plain";
  169. }
  170. response = generateResponseForInputStream(null, 0L, contentType);
  171. }
  172. NSNotificationCenter.defaultCenter().postNotification(WORequestHandler.DidHandleRequestNotification, response);
  173. response._finalizeInContext(null);
  174. return response;
  175. }
  176. protected WOResponse responseForDataAtURL(URL anURL) {
  177. InputStream is = null;
  178. long fileLength = 0L;
  179. String aResourcePath = anURL.toString();
  180. String aContentType = _app.resourceManager().contentTypeForResourceNamed(aResourcePath);
  181. try {
  182. fileLength = NSPathUtilities._contentLengthForPathURL(anURL);
  183. is = anURL.openStream();
  184. } catch (IOException ioe) {
  185. NSLog.err.appendln((new StringBuilder()).append("<").append(getClass().getName()).append("> Unable to get contents of file for path '").append(
  186. aResourcePath).append("': ").append(ioe).toString());
  187. if (NSLog.debugLoggingAllowedForLevelAndGroups(2, 36L)) {
  188. NSLog.debug.appendln(ioe);
  189. }
  190. }
  191. WOResponse aResponse = generateResponseForInputStream(is, fileLength, aContentType);
  192. return aResponse;
  193. }
  194. protected WOResponse responseForDataCachedWithKey(String aResourceKey) {
  195. WOResponse response = _app.createResponseInContext(null);
  196. WOResourceManager resourceManager = _app.resourceManager();
  197. WOURLValuedElementData aResourceDataObject = resourceManager._cachedDataForKey(aResourceKey);
  198. if (aResourceDataObject == null) {
  199. LOGGER.warn("The resource was not found in cache. Turn log DEBUG on for more details.");
  200. return response;
  201. }
  202. aResourceDataObject.appendToResponse(response, null);
  203. if (aResourceDataObject.isTemporary()) {
  204. resourceManager.removeDataForKey(aResourceKey, null);
  205. }
  206. return response;
  207. }
  208. protected WOResponse responseForJavaClassAtPath(String aPath) {
  209. WOResponse aResponse = null;
  210. URL anURL = _app.resourceManager()._pathURLForJavaClass(aPath);
  211. if (anURL != null) {
  212. aResponse = responseForDataAtURL(anURL);
  213. }
  214. return aResponse;
  215. }
  216. }