com.formkiq.core.form.bean.UUIDConverter.java Source code

Java tutorial

Introduction

Here is the source code for com.formkiq.core.form.bean.UUIDConverter.java

Source

/*
 * Copyright (C) 2017 FormKiQ Inc.
 *
 * 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 com.formkiq.core.form.bean;

import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.converters.AbstractConverter;

/**
 * {@link BeanUtils} converter for {@link UUID}.
 *
 */
public class UUIDConverter extends AbstractConverter {

    @SuppressWarnings("unchecked")
    @Override
    public <T> T convert(final Class<T> type, final Object value) {

        // We have to support Object, too, because this class is sometimes
        // used for a standard to Object conversion
        if (UUID.class.equals(type) || Object.class.equals(type)) {

            if (value != null) {
                return (T) UUID.fromString(value.toString());
            }
        }

        return null;
    }

    /**
     * Return the default type this <code>Converter</code> handles.
     *
     * @return The default type this <code>Converter</code> handles.
     */
    @Override
    protected Class<?> getDefaultType() {
        return UUID.class;
    }

    /**
     * Convert the specified input object into an output object of the
     * specified type.
     *
     * @param <T> Target type of the conversion.
     * @param type Data type to which this value should be converted.
     * @param value The input value to be converted.
     * @return The converted value.
     * @throws Throwable if an error occurs converting to the specified type
     */
    @Override
    protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {
        // We have to support Object, too, because this class is sometimes
        // used for a standard to Object conversion
        if (UUID.class.equals(type) || Object.class.equals(type)) {
            return type.cast(value.toString());
        }
        throw conversionException(type, value);
    }
}