Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

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