All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.diirt.datasource.graphene.CheckedReadFunction Maven / Gradle / Ivy

There is a newer version: 3.1.7
Show newest version
/**
 * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
 * All rights reserved. Use is subject to license terms. See LICENSE.TXT
 */
package org.diirt.datasource.graphene;

import java.util.ArrayList;
import java.util.List;
import org.diirt.datasource.ReadFunction;
import org.diirt.vtype.ValueUtil;

/**
 *
 * @author carcassi
 */
public class CheckedReadFunction implements ReadFunction {
    
    private final Class clazz;
    private final Class[] classes;
    private final ReadFunction arg;
    private final String argName;

    public CheckedReadFunction(ReadFunction arg, String argName, Class clazz) {
        if (clazz == null) {
            throw new NullPointerException("Class can't be null");
        }
        this.clazz = clazz;
        this.classes = null;
        this.arg = arg;
        this.argName = argName;
    }

    @SafeVarargs
    public CheckedReadFunction(ReadFunction arg, String argName, Class... classes) {
        if (classes == null) {
            throw new NullPointerException("Classes can't be null");
        }
        this.clazz = null;
        this.classes = classes;
        this.arg = arg;
        this.argName = argName;
    }
    
    @Override
    public T readValue() {
        Object obj = arg.readValue();
        if (obj == null) {
            return null;
        }

        if (clazz != null) {
            if (clazz.isInstance(obj)) {
                return clazz.cast(obj);
            } else {
                throw new RuntimeException(argName + " must be a " + clazz.getSimpleName() + " (was " + ValueUtil.typeOf(obj).getSimpleName() + ")");
            }
        } else {
            for (Class aClass : classes) {
                if (aClass.isInstance(obj)) {
                    return aClass.cast(obj);
                }
            }
            StringBuilder sb = new StringBuilder();
            List names = new ArrayList<>();
            for (Class aClass : classes) {
                names.add(aClass.getSimpleName());
            }
            throw new RuntimeException(argName + " must be one of " + names.toString() + " (was " + ValueUtil.typeOf(obj).getSimpleName() + ")");
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy