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