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.text.ParseException;
020
021import javax.persistence.AttributeConverter;
022import javax.persistence.Converter;
023
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027import com.nimbusds.jwt.JWT;
028import com.nimbusds.jwt.JWTParser;
029
030/**
031 * @author jricher
032 *
033 */
034@Converter
035public class JWTStringConverter implements AttributeConverter<JWT, String> {
036
037        public static Logger logger = LoggerFactory.getLogger(JWTStringConverter.class);
038
039        @Override
040        public String convertToDatabaseColumn(JWT attribute) {
041                if (attribute != null) {
042                        return attribute.serialize();
043                } else {
044                        return null;
045                }
046        }
047
048        /* (non-Javadoc)
049         * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object)
050         */
051        @Override
052        public JWT convertToEntityAttribute(String dbData) {
053                if (dbData != null) {
054                        try {
055                                JWT jwt = JWTParser.parse(dbData);
056                                return jwt;
057                        } catch (ParseException e) {
058                                logger.error("Unable to parse JWT", e);
059                                return null;
060                        }
061                } else {
062                        return null;
063                }
064        }
065
066}