001/*******************************************************************************
002 * Copyright 2017 The MIT Internet Trust Consortium
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 org.mitre.oauth2.model.convert;
018
019import java.io.Serializable;
020import java.util.Date;
021
022import javax.persistence.AttributeConverter;
023import javax.persistence.Converter;
024
025import org.slf4j.Logger;
026import org.slf4j.LoggerFactory;
027
028/**
029 * Translates a Serializable object of certain primitive types
030 * into a String for storage in the database, for use with the
031 * OAuth2Request extensions map.
032 *
033 * This class does allow some extension data to be lost.
034 *
035 * @author jricher
036 *
037 */
038@Converter
039public class SerializableStringConverter implements AttributeConverter<Serializable, String> {
040
041        private static Logger logger = LoggerFactory.getLogger(SerializableStringConverter.class);
042
043        @Override
044        public String convertToDatabaseColumn(Serializable attribute) {
045                if (attribute == null) {
046                        return null;
047                } else if (attribute instanceof String) {
048                        return (String) attribute;
049                } else if (attribute instanceof Long) {
050                        return attribute.toString();
051                } else if (attribute instanceof Date) {
052                        return Long.toString(((Date)attribute).getTime());
053                } else {
054                        logger.warn("Dropping data from request: " + attribute + " :: " + attribute.getClass());
055                        return null;
056                }
057        }
058
059        @Override
060        public Serializable convertToEntityAttribute(String dbData) {
061                return dbData;
062        }
063
064}