001/*
002 *  Copyright 2018 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.core.minimize.js;
017
018import java.io.ByteArrayOutputStream;
019import java.io.IOException;
020import java.io.InputStream;
021import java.nio.charset.StandardCharsets;
022import java.util.Locale;
023import java.util.Map;
024import java.util.regex.Matcher;
025import java.util.regex.Pattern;
026
027import org.apache.avalon.framework.context.Context;
028import org.apache.avalon.framework.context.ContextException;
029import org.apache.avalon.framework.context.Contextualizable;
030import org.apache.avalon.framework.service.ServiceException;
031import org.apache.avalon.framework.service.ServiceManager;
032import org.apache.cocoon.ProcessingException;
033import org.apache.cocoon.components.ContextHelper;
034import org.apache.cocoon.environment.ObjectModelHelper;
035import org.apache.commons.io.IOUtils;
036import org.apache.commons.lang3.StringUtils;
037import org.apache.excalibur.source.Source;
038
039import org.ametys.core.minimize.AbstractSourceMapResourceHandler;
040
041/**
042 * Resource handler for source map files
043 */
044public class JSSourceMapResourceHandler extends AbstractSourceMapResourceHandler implements Contextualizable
045{
046    private static final Pattern __LOCALE_PATTERN = Pattern.compile("^(.*resources/.*)\\.([^/.]+)\\.js$");
047    
048    /** JS minimize manager */
049    protected MinimizeJSManager _jSMinimizeManager;
050    
051    private Context _context;
052    
053    public void contextualize(Context context) throws ContextException
054    {
055        _context = context;
056    }
057
058    @Override
059    public void service(ServiceManager manager) throws ServiceException
060    {
061        super.service(manager);
062        _jSMinimizeManager = (MinimizeJSManager) manager.lookup(MinimizeJSManager.ROLE);
063    }
064    
065    @Override
066    protected Source _getAlternateSource(String location, Map objectModel) throws ProcessingException, IOException
067    {
068        Source source = null;
069        // 1. Check if the source map exist with and without the .min
070        if (location.endsWith(".min.js.map"))
071        {
072            source = _getExistingSource(location.substring(0, location.length() - ".min.js.map".length()) + ".js.map");
073        }
074        else
075        {
076            source = _getExistingSource(location.substring(0, location.length() - ".js.map".length()) + ".min.js.map");
077        }
078        
079        if (source == null)
080        {
081            // 2. check if the source map is in cache
082            String localizedLocation = _getLocalizedLocation(location);
083            source = _sourceMapCache.get(localizedLocation);
084
085            if (source == null)
086            {
087                // 3. generate the source map and store it in cache
088                source = _generateJSSourceMap(objectModel, localizedLocation);
089            }
090        }
091        
092        return source;
093    }
094    
095    private String _getLocalizedLocation(String location)
096    {
097        Matcher matcher = __LOCALE_PATTERN.matcher(location);
098        String locale = matcher.matches() ? matcher.group(2) : null;
099        
100        if (locale == null)
101        {
102            // Default locale
103            Map objectModel = ContextHelper.getObjectModel(_context);
104            locale = org.apache.cocoon.i18n.I18nUtils.findLocale(objectModel, "locale", null, Locale.getDefault(), true).getLanguage();
105        }
106        
107        return location + (locale != null ? "#" + locale : "");
108    }
109    
110
111    private Source _generateJSSourceMap(Map objectModel, String localizedLocation) throws ProcessingException, IOException
112    {
113        String originalUri = "cocoon:/" + StringUtils.removeEnd(ObjectModelHelper.getRequest(objectModel).getSitemapURI(), ".map");
114        
115        Source sourceResolved = _resolver.resolveURI(originalUri);
116        if (sourceResolved != null && sourceResolved.exists())
117        {
118            try (InputStream inputStream = sourceResolved.getInputStream())
119            {
120                ByteArrayOutputStream baos = new ByteArrayOutputStream();
121                IOUtils.copy(inputStream, baos);
122                
123                // Stores the source of the sourceMap in the cache
124                _jSMinimizeManager.generateJSSourceMap(baos.toString(StandardCharsets.UTF_8.toString()), originalUri, localizedLocation, sourceResolved.getLastModified());
125                
126                return _sourceMapCache.get(localizedLocation);
127            }
128        }
129        else
130        {
131            _resolver.release(sourceResolved);
132        }
133        
134        return null;
135    }
136}