001/*
002 * Copyright (C) 2023 The Prometheus jmx_exporter Authors
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 */
016
017package io.prometheus.jmx.common.configuration;
018
019import io.prometheus.jmx.common.util.Precondition;
020import io.prometheus.jmx.common.yaml.YamlMapAccessor;
021
022import java.util.Map;
023import java.util.function.Function;
024import java.util.function.Supplier;
025
026/**
027 * Class to convert an Object to a Map, throwing a RuntimeException
028 * from the Supplier if there is a ClassCastException
029 */
030@SuppressWarnings("unchecked")
031public class ConvertToMapAccessor implements Function<Object, YamlMapAccessor> {
032
033    private Supplier<? extends RuntimeException> supplier;
034
035    /**
036     * Constructor
037     *
038     * @param supplier supplier
039     */
040    public ConvertToMapAccessor(Supplier<? extends RuntimeException> supplier) {
041        Precondition.notNull(supplier);
042        this.supplier = supplier;
043    }
044
045    /**
046     * Method to apply a function
047     *
048     * @param value value
049     * @return the return value
050     */
051    @Override
052    public YamlMapAccessor apply(Object value) {
053        try {
054            return new YamlMapAccessor((Map<Object, Object>) value);
055        } catch (ClassCastException e) {
056            throw supplier.get();
057        }
058    }
059}