001/**
002 * Copyright (C) 2006-2024 Talend Inc. - www.talend.com
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.talend.sdk.component.runtime.manager.reflect.parameterenricher;
017
018import static java.util.Optional.ofNullable;
019
020import java.util.Optional;
021import java.util.function.Supplier;
022
023import org.talend.sdk.component.api.service.configuration.LocalConfiguration;
024import org.talend.sdk.component.spi.parameter.ParameterExtensionEnricher;
025
026import lombok.Data;
027
028public abstract class BaseParameterEnricher implements ParameterExtensionEnricher {
029
030    private final ThreadLocal<Context> context = new ThreadLocal<>();
031
032    public <T> T withContext(final Context context, final Supplier<T> task) {
033        this.context.set(context);
034        try {
035            return task.get();
036        } finally {
037            this.context.remove();
038        }
039    }
040
041    protected Optional<Context> getContext() {
042        final Context value = context.get();
043        if (value == null) {
044            context.remove();
045        }
046        return ofNullable(value);
047    }
048
049    @Data
050    public static class Context {
051
052        private final LocalConfiguration configuration;
053    }
054}