001// Licensed under the Apache License, Version 2.0 (the "License"); 002// you may not use this file except in compliance with the License. 003// You may obtain a copy of the License at 004// 005// http://www.apache.org/licenses/LICENSE-2.0 006// 007// Unless required by applicable law or agreed to in writing, software 008// distributed under the License is distributed on an "AS IS" BASIS, 009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 010// See the License for the specific language governing permissions and 011// limitations under the License. 012 013package org.apache.tapestry5.internal.util; 014 015import java.io.ByteArrayInputStream; 016import java.io.IOException; 017import java.io.InputStream; 018import java.net.URL; 019import java.nio.charset.Charset; 020import java.util.Locale; 021 022import org.apache.tapestry5.commons.Resource; 023 024/** 025 * Base class for virtual resources: resources that are not simply mapped to stored files, but are assembled, as necessary, 026 * on the fly. This is used inside Tapestry to expose the application's localized message catalog as a module. 027 * Subclasses should implement the {@link org.apache.tapestry5.commons.Resource#openStream()} method to return a stream of 028 * the contents of the virtual resource. 029 * 030 * @see org.apache.tapestry5.services.javascript.ModuleManager 031 * @see org.apache.tapestry5.internal.services.javascript.ModuleDispatcher 032 * @since 5.4 033 */ 034public abstract class VirtualResource implements Resource 035{ 036 protected static final Charset UTF8 = Charset.forName("UTF-8"); 037 038 private <T> T unsupported(String name) 039 { 040 throw new UnsupportedOperationException(String.format("Method %s() is not supported for a VirtualResource.", name)); 041 } 042 043 public boolean exists() 044 { 045 046 return true; 047 } 048 049 public URL toURL() 050 { 051 return unsupported("toURL"); 052 } 053 054 public Resource forLocale(Locale locale) 055 { 056 return unsupported("forLocale"); 057 } 058 059 public Resource forFile(String relativePath) 060 { 061 return this; 062 } 063 064 public Resource withExtension(String extension) 065 { 066 return unsupported("withExtension"); 067 } 068 069 public String getFolder() 070 { 071 return unsupported("getFolder"); 072 } 073 074 public String getFile() 075 { 076 return unsupported("getFile"); 077 } 078 079 public String getPath() 080 { 081 return unsupported("getPath"); 082 } 083 084 protected InputStream toInputStream(String content) throws IOException 085 { 086 return toInputStream(content.getBytes(UTF8)); 087 } 088 089 protected InputStream toInputStream(byte[] content) throws IOException 090 { 091 return new ByteArrayInputStream(content); 092 } 093 094 @Override 095 public boolean isVirtual() 096 { 097 return true; 098 } 099}