001// Copyright 2023 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.transform;
016
017import java.util.HashMap;
018import java.util.HashSet;
019import java.util.Map;
020import java.util.Set;
021
022import org.apache.tapestry5.ioc.services.PerThreadValue;
023import org.apache.tapestry5.ioc.services.PerthreadManager;
024import org.apache.tapestry5.model.MutableComponentModel;
025import org.apache.tapestry5.plastic.PlasticClass;
026import org.apache.tapestry5.plastic.PlasticUtils;
027import org.apache.tapestry5.plastic.PlasticUtils.FieldInfo;
028import org.apache.tapestry5.plastic.PropertyValueProvider;
029import org.apache.tapestry5.services.transform.ComponentClassTransformWorker2;
030import org.apache.tapestry5.services.transform.TransformationSupport;
031
032/**
033 * Worker used to gather {@linkplain FieldInfo} instances and implement
034 * {@linkplain PropertyValueProvider} for any class that has them.
035 * 
036 */
037public final class PropertyValueProviderWorker implements ComponentClassTransformWorker2
038{
039    private final PerThreadValue<Map<PlasticClass, Set<FieldInfo>>> perThreadMap;
040    
041    public PropertyValueProviderWorker(PerthreadManager perThreadManager)
042    {
043        perThreadMap = perThreadManager.createValue();
044    }
045    
046    public void add(PlasticClass plasticClass, Set<FieldInfo> fieldInfos)
047    {
048        final Map<PlasticClass, Set<FieldInfo>> map = perThreadMap.computeIfAbsent(HashMap::new);
049        if (!map.containsKey(plasticClass))
050        {
051            map.put(plasticClass, new HashSet<>(5));
052        }
053        map.get(plasticClass).addAll(fieldInfos);
054    }
055
056    public void transform(PlasticClass plasticClass, TransformationSupport support, MutableComponentModel model)
057    {
058        if (perThreadMap.exists())
059        {
060            final Set<FieldInfo> fieldInfos = perThreadMap.get().get(plasticClass);
061            if (fieldInfos != null && !fieldInfos.isEmpty())
062            {
063                PlasticUtils.implementPropertyValueProvider(plasticClass, fieldInfos);
064            }
065        }
066    }
067
068}