001: /* ServletContextLocator.java
002:
003: {{IS_NOTE
004: Purpose:
005:
006: Description:
007:
008: History:
009: Wed Jul 6 15:16:05 2005, Created by tomyeh
010: }}IS_NOTE
011:
012: Copyright (C) 2005 Potix Corporation. All Rights Reserved.
013:
014: {{IS_RIGHT
015: This program is distributed under GPL Version 2.0 in the hope that
016: it will be useful, but WITHOUT ANY WARRANTY.
017: }}IS_RIGHT
018: */
019: package org.zkoss.web.util.resource;
020:
021: import java.io.InputStream;
022: import java.net.URL;
023: import javax.servlet.ServletContext;
024:
025: import org.zkoss.lang.SystemException;
026: import org.zkoss.util.resource.Locator;
027:
028: /**
029: * Locator based on ServletContext.
030: *
031: * @author tomyeh
032: */
033: public class ServletContextLocator implements Locator {
034: private final ServletContext _ctx;
035: private final String _dir;
036:
037: public ServletContextLocator(ServletContext ctx) {
038: this (ctx, null);
039: }
040:
041: /**
042: * @param dir the directory used when relative path is specified
043: * (for {@link #getResource} and {@link #getResourceAsStream}).
044: * It must be null, empty, or starts with /.
045: */
046: public ServletContextLocator(ServletContext ctx, String dir) {
047: if (ctx == null)
048: throw new IllegalArgumentException("null");
049: if (dir != null) {
050: final int len = dir.length();
051: if (len == 0)
052: dir = null;
053: else {
054: if (dir.charAt(0) != '/')
055: throw new IllegalArgumentException(dir);
056: if (dir.charAt(len - 1) != '/')
057: dir += '/';
058: }
059: }
060:
061: _ctx = ctx;
062: _dir = dir;
063: }
064:
065: /** Returns the servlet context. */
066: public ServletContext getServletContext() {
067: return _ctx;
068: }
069:
070: private String fixName(String name) {
071: return _dir != null && name.length() > 0
072: && name.charAt(0) != '/' ? _dir + name : name;
073: }
074:
075: //-- Locator --//
076: public String getDirectory() {
077: return _dir;
078: }
079:
080: public URL getResource(String name) {
081: try {
082: return _ctx.getResource(fixName(name));
083: } catch (java.net.MalformedURLException ex) {
084: throw new SystemException(ex);
085: }
086: }
087:
088: public InputStream getResourceAsStream(String name) {
089: return _ctx.getResourceAsStream(fixName(name));
090: }
091:
092: //-- Object --//
093: public int hashCode() {
094: return _ctx.hashCode();
095: }
096:
097: public boolean equals(Object o) {
098: return o instanceof ServletContextLocator
099: && ((ServletContextLocator) o)._ctx.equals(_ctx);
100: }
101: }
|