<commit_before>// Copyright 2006-2013 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.internal.services;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.internal.AssetConstants;
import org.apache.tapestry5.internal.TapestryInternalUtils;
import org.apache.tapestry5.internal.services.assets.ResourceChangeTracker;
import org.apache.tapestry5.ioc.Invokable;
import org.apache.tapestry5.ioc.OperationTracker;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.ioc.internal.util.LockSupport;
import org.apache.tapestry5.ioc.services.SymbolSource;
import org.apache.tapestry5.ioc.services.ThreadLocale;
import org.apache.tapestry5.ioc.util.StrategyRegistry;
import org.apache.tapestry5.services.AssetFactory;
import org.apache.tapestry5.services.AssetSource;
import org.slf4j.Logger;

import java.lang.ref.SoftReference;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

@SuppressWarnings("all")
public class AssetSourceImpl extends LockSupport implements AssetSource
{
    private final StrategyRegistry<AssetFactory> registry;

    private final ThreadLocale threadLocale;

    private final Map<String, Resource> prefixToRootResource = CollectionFactory.newMap();

    private final Map<Resource, SoftReference<Asset>> cache = new WeakHashMap<Resource, SoftReference<Asset>>();

    private final SymbolSource symbolSource;

    private final Logger logger;

    private final AtomicBoolean firstWarning = new AtomicBoolean(true);

    private final OperationTracker tracker;

    public AssetSourceImpl(ThreadLocale threadLocale,

                           Map<String, AssetFactory> configuration, SymbolSource symbolSource, Logger logger, OperationTracker tracker)
    {
        this.threadLocale = threadLocale;
        this.symbolSource = symbolSource;
        this.logger = logger;
        this.tracker = tracker;

        Map<Class, AssetFactory> byResourceClass = CollectionFactory.newMap();

        for (Map.Entry<String, AssetFactory> e : configuration.entrySet())
        {
            String prefix = e.getKey();
            AssetFactory factory = e.getValue();

            Resource rootResource = factory.getRootResource();

            byResourceClass.put(rootResource.getClass(), factory);

            prefixToRootResource.put(prefix, rootResource);
        }

        registry = StrategyRegistry.newInstance(AssetFactory.class, byResourceClass);
    }

    @PostInjection
    public void clearCacheWhenResourcesChange(ResourceChangeTracker tracker)
    {
        tracker.clearOnInvalidation(cache);
    }

    public Asset getClasspathAsset(String path)
    {
        return getClasspathAsset(path, null);
    }

    public Asset getClasspathAsset(String path, Locale locale)
    {
        return getAsset(null, path, locale);
    }

    public Asset getContextAsset(String path, Locale locale)
    {
        return getAsset(prefixToRootResource.get(AssetConstants.CONTEXT), path, locale);
    }

    public Asset getAsset(Resource baseResource, String path, Locale locale)
    {
        return getAssetInLocale(baseResource, path, defaulted(locale));
    }

    public Resource resourceForPath(String path)
    {
        return findResource(null, path);
    }

    public Asset getExpandedAsset(String path)
    {
        return getUnlocalizedAsset(symbolSource.expandSymbols(path));
    }

    public Asset getComponentAsset(final ComponentResources resources, final String path)
    {
        assert resources != null;

        assert InternalUtils.isNonBlank(path);

        return tracker.invoke(String.format("Resolving '%s' for component %s", path, resources.getCompleteId()
        ),
                new Invokable<Asset>()
                {
                    public Asset invoke()
                    {
                        // First, expand symbols:

                        String expanded = symbolSource.expandSymbols(path);

                        int dotx = expanded.indexOf(':');

                        // We special case the hell out of 'classpath:' so that we can provide warnings today (5.4) and
                        // blow up in a useful fashion tomorrow (5.5).

                        if (dotx > 0 && !expanded.substring(0, dotx).equalsIgnoreCase(AssetConstants.CLASSPATH))
                        {
                            return getAssetInLocale(resources.getBaseResource(), expanded, resources.getLocale());
                        }

                        // No prefix, so implicitly classpath:, or explicitly classpath:

                        String restOfPath = expanded.substring(dotx + 1);

                        // This is tricky, because a relative path (including "../") is ok in 5.3, since its just somewhere
                        // else on the classpath (though you can "stray" out of the "safe" zone).  In 5.4, under /META-INF/assets/
                        // it's possible to "stray" out beyond the safe zone more easily, into parts of the classpath that can't be
                        // represented in the URL.

                        // Ends with trailing slash:
                        String metaRoot = "META-INF/assets/" + toPathPrefix(resources.getComponentModel().getLibraryName());

                        String metaPath = metaRoot + (restOfPath.startsWith("/")
                                ? restOfPath.substring(1)
                                : restOfPath);

                        // Based on the path, metaResource is where it should exist in a 5.4 and beyond world ... unless the expanded
                        // path was a bit too full of ../ sequences, in which case the expanded path is not valid and we adjust the
                        // error we write.

                        Resource metaResource = findLocalizedResource(null, metaPath, resources.getLocale());

                        Asset result = getComponentAsset(resources, expanded, metaResource);

                        // This is the best way to tell if the result is an asset for a Classpath resource.

                        Resource resultResource = result.getResource();

                        if (!resultResource.equals(metaResource))
                        {
                            if (firstWarning.getAndSet(false))
                            {
                                logger.error("Packaging of classpath assets has changed in release 5.4; " +
                                        "Assets should no longer be on the main classpath, " +
                                        "but should be moved to 'META-INF/assets/' or a sub-folder. Future releases of Tapestry may " +
                                        "no longer support assets on the main classpath.");
                            }

                            if (metaResource.getFolder().startsWith(metaRoot))
                            {
                                logger.error(String.format("Classpath asset '/%s' should be moved to folder '/%s/'.",
                                        resultResource.getPath(),
                                        metaResource.getFolder()));
                            } else
                            {
                                logger.error(String.format("Classpath asset '/%s' should be moved under folder '/%s', and the relative path adjusted.",
                                        resultResource.getPath(),<commit_msg>TAP5-2167: Asset location warnings are actually coded as errors<commit_after>// Copyright 2006-2013 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.internal.services;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.internal.AssetConstants;
import org.apache.tapestry5.internal.TapestryInternalUtils;
import org.apache.tapestry5.internal.services.assets.ResourceChangeTracker;
import org.apache.tapestry5.ioc.Invokable;
import org.apache.tapestry5.ioc.OperationTracker;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.ioc.internal.util.LockSupport;
import org.apache.tapestry5.ioc.services.SymbolSource;
import org.apache.tapestry5.ioc.services.ThreadLocale;
import org.apache.tapestry5.ioc.util.StrategyRegistry;
import org.apache.tapestry5.services.AssetFactory;
import org.apache.tapestry5.services.AssetSource;
import org.slf4j.Logger;

import java.lang.ref.SoftReference;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

@SuppressWarnings("all")
public class AssetSourceImpl extends LockSupport implements AssetSource
{
    private final StrategyRegistry<AssetFactory> registry;

    private final ThreadLocale threadLocale;

    private final Map<String, Resource> prefixToRootResource = CollectionFactory.newMap();

    private final Map<Resource, SoftReference<Asset>> cache = new WeakHashMap<Resource, SoftReference<Asset>>();

    private final SymbolSource symbolSource;

    private final Logger logger;

    private final AtomicBoolean firstWarning = new AtomicBoolean(true);

    private final OperationTracker tracker;

    public AssetSourceImpl(ThreadLocale threadLocale,

                           Map<String, AssetFactory> configuration, SymbolSource symbolSource, Logger logger, OperationTracker tracker)
    {
        this.threadLocale = threadLocale;
        this.symbolSource = symbolSource;
        this.logger = logger;
        this.tracker = tracker;

        Map<Class, AssetFactory> byResourceClass = CollectionFactory.newMap();

        for (Map.Entry<String, AssetFactory> e : configuration.entrySet())
        {
            String prefix = e.getKey();
            AssetFactory factory = e.getValue();

            Resource rootResource = factory.getRootResource();

            byResourceClass.put(rootResource.getClass(), factory);

            prefixToRootResource.put(prefix, rootResource);
        }

        registry = StrategyRegistry.newInstance(AssetFactory.class, byResourceClass);
    }

    @PostInjection
    public void clearCacheWhenResourcesChange(ResourceChangeTracker tracker)
    {
        tracker.clearOnInvalidation(cache);
    }

    public Asset getClasspathAsset(String path)
    {
        return getClasspathAsset(path, null);
    }

    public Asset getClasspathAsset(String path, Locale locale)
    {
        return getAsset(null, path, locale);
    }

    public Asset getContextAsset(String path, Locale locale)
    {
        return getAsset(prefixToRootResource.get(AssetConstants.CONTEXT), path, locale);
    }

    public Asset getAsset(Resource baseResource, String path, Locale locale)
    {
        return getAssetInLocale(baseResource, path, defaulted(locale));
    }

    public Resource resourceForPath(String path)
    {
        return findResource(null, path);
    }

    public Asset getExpandedAsset(String path)
    {
        return getUnlocalizedAsset(symbolSource.expandSymbols(path));
    }

    public Asset getComponentAsset(final ComponentResources resources, final String path)
    {
        assert resources != null;

        assert InternalUtils.isNonBlank(path);

        return tracker.invoke(String.format("Resolving '%s' for component %s", path, resources.getCompleteId()
        ),
                new Invokable<Asset>()
                {
                    public Asset invoke()
                    {
                        // First, expand symbols:

                        String expanded = symbolSource.expandSymbols(path);

                        int dotx = expanded.indexOf(':');

                        // We special case the hell out of 'classpath:' so that we can provide warnings today (5.4) and
                        // blow up in a useful fashion tomorrow (5.5).

                        if (dotx > 0 && !expanded.substring(0, dotx).equalsIgnoreCase(AssetConstants.CLASSPATH))
                        {
                            return getAssetInLocale(resources.getBaseResource(), expanded, resources.getLocale());
                        }

                        // No prefix, so implicitly classpath:, or explicitly classpath:

                        String restOfPath = expanded.substring(dotx + 1);

                        // This is tricky, because a relative path (including "../") is ok in 5.3, since its just somewhere
                        // else on the classpath (though you can "stray" out of the "safe" zone).  In 5.4, under /META-INF/assets/
                        // it's possible to "stray" out beyond the safe zone more easily, into parts of the classpath that can't be
                        // represented in the URL.

                        // Ends with trailing slash:
                        String metaRoot = "META-INF/assets/" + toPathPrefix(resources.getComponentModel().getLibraryName());

                        String metaPath = metaRoot + (restOfPath.startsWith("/")
                                ? restOfPath.substring(1)
                                : restOfPath);

                        // Based on the path, metaResource is where it should exist in a 5.4 and beyond world ... unless the expanded
                        // path was a bit too full of ../ sequences, in which case the expanded path is not valid and we adjust the
                        // error we write.

                        Resource metaResource = findLocalizedResource(null, metaPath, resources.getLocale());

                        Asset result = getComponentAsset(resources, expanded, metaResource);

                        // This is the best way to tell if the result is an asset for a Classpath resource.

                        Resource resultResource = result.getResource();

                        if (!resultResource.equals(metaResource))
                        {
                            if (firstWarning.getAndSet(false))
                            {
                                logger.error("Packaging of classpath assets has changed in release 5.4; " +
                                        "Assets should no longer be on the main classpath, " +
                                        "but should be moved to 'META-INF/assets/' or a sub-folder. Future releases of Tapestry may " +
                                        "no longer support assets on the main classpath.");
                            }

                            if (metaResource.getFolder().startsWith(metaRoot))
                            {
                                logger.warn(String.format("Classpath asset '/%s' should be moved to folder '/%s/'.",
                                        resultResource.getPath(),
                                        metaResource.getFolder()));
                            } else
                            {
                                logger.warn(String.format("Classpath asset '/%s' should be moved under folder '/%s', and the relative path adjusted.",
                                        resultResource.getPath(),
{'fraction_non_alphanumeric': 0.08206796818510484, 'fraction_numerical': 0.00596529284164859, 'mean_word_length': 2.090689013035382, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5567525', 'n_tokens_mistral': 4077, 'n_tokens_neox': 3826, 'n_words': 1169}