001: package org.jicengine.io;
002:
003: import java.io.InputStream;
004: import java.io.IOException;
005: import java.io.FileNotFoundException;
006: import java.util.StringTokenizer;
007:
008: /**
009: * Resource of some Class. The resource is read by calling
010: * [resource-owner-class].getResourceAsStream([resource-name])
011: *
012: *
013: * <p>
014: * Copyright (C) 2004 Timo Laitinen
015: * </p>
016: *
017: * @author Timo Laitinen
018: * @created 2004-09-20
019: * @since JICE-0.10
020: * @version 1.0
021: * @see java.lang.Class
022: * @see java.lang.ClassLoader
023: * @see java.lang.Class#getResourceAsStream
024: * @see java.lang.Class#getResource
025: */
026:
027: public class ClassResource extends AbstractResource implements
028: UrlReadable {
029:
030: private Class resourceOwnerClass;
031: private String resourceName;
032:
033: /**
034: * @param resourceOwnerClass the Class that own the resource. specifies the
035: * location of the actual file.
036: * @param resourceName The name of the resource, given for method
037: * <code>Class.getResourceAsStream()</code>.
038: *
039: * @see java.lang.Class#getResourceAsStream
040: * @see java.lang.Class#getResource
041: */
042: public ClassResource(Class resourceOwnerClass, String resourceName) {
043: super ("class://" + resourceOwnerClass.getName() + "/"
044: + resourceName);
045: this .resourceName = resourceName;
046: this .resourceOwnerClass = resourceOwnerClass;
047: }
048:
049: public Class getResourceOwnerClass() {
050: return this .resourceOwnerClass;
051: }
052:
053: /**
054: * not same as the getIdentifier(), which is prefixed with the
055: * name of the owner class..
056: */
057: public String getResourceName() {
058: return this .resourceName;
059: }
060:
061: public java.net.URL getUrl() throws IOException {
062: java.net.URL url = getResourceOwnerClass().getResource(
063: getResourceName());
064: if (url != null) {
065: return url;
066: } else {
067: throw new java.io.FileNotFoundException("Resource '"
068: + getResourceName() + "' of class '"
069: + getResourceOwnerClass().getName()
070: + "' not available.");
071: }
072: }
073:
074: public boolean isAvailable() {
075: if (getResourceOwnerClass().getResource(getResourceName()) != null) {
076: return true;
077: } else {
078: return false;
079: }
080: }
081:
082: public InputStream getInputStream() throws java.io.IOException {
083: InputStream stream = this .resourceOwnerClass
084: .getResourceAsStream(getResourceName());
085: if (stream != null) {
086: return stream;
087: } else {
088: throw new java.io.FileNotFoundException("Resource '"
089: + getResourceName() + "' of class '"
090: + getResourceOwnerClass().getName()
091: + "' not available.");
092: }
093: }
094:
095: public Resource getResource(String relativePath)
096: throws java.io.IOException {
097: return new ClassResource(getResourceOwnerClass(), PathResolver
098: .getRealPath(getResourceName(), relativePath));
099: }
100:
101: }
|