001/*
002 *  Copyright 2014 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.odf.source;
017
018import java.io.IOException;
019import java.net.MalformedURLException;
020import java.util.Map;
021import java.util.regex.Matcher;
022import java.util.regex.Pattern;
023
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.avalon.framework.service.Serviceable;
027import org.apache.commons.lang.StringUtils;
028import org.apache.excalibur.source.Source;
029import org.apache.excalibur.source.SourceFactory;
030
031import org.ametys.runtime.plugin.component.AbstractLogEnabled;
032
033/**
034 * This factory looks for files in the WEB-INF/stylesheets directory and falls back to the default stylesheet .
035 * Use: odf-view://path_to_file
036 */
037public class ODFViewSourceFactory extends AbstractLogEnabled implements SourceFactory, Serviceable
038{
039    /** The regexp for a protocol */
040    protected static final Pattern __SOURCE_PATTERN = Pattern.compile("^([^:])+(:([^:]+))?://(.*)$");
041    
042    /** The ODF view selector */
043    private ODFViewSelector _odfViewSelector;
044    
045    public void service(ServiceManager manager) throws ServiceException
046    {
047        _odfViewSelector = (ODFViewSelector) manager.lookup(ODFViewSelector.ROLE);
048    }
049
050    @Override
051    public Source getSource(String location, Map parameters) throws IOException, MalformedURLException
052    {
053        Matcher m = __SOURCE_PATTERN.matcher(location);
054        if (!m.matches())
055        {
056            throw new MalformedURLException("URI must be like protocol:<name>://path/to/resource. Location was '" + location + "'");
057        }
058        
059        String pluginName = m.group(3);
060        if (StringUtils.isEmpty(pluginName))
061        {
062            pluginName = "odf"; // default plugin
063        }
064        
065        String fileLocation = m.group(4);
066        
067        return _odfViewSelector.getSource(pluginName, fileLocation);
068    }
069
070    @Override
071    public void release(Source source)
072    {
073        // empty method
074    }
075}