JWTStringConverter.java

  1. /*******************************************************************************
  2.  * Copyright 2017 The MIT Internet Trust Consortium
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  *******************************************************************************/

  16. package org.mitre.oauth2.model.convert;

  17. import java.text.ParseException;

  18. import javax.persistence.AttributeConverter;
  19. import javax.persistence.Converter;

  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;

  22. import com.nimbusds.jwt.JWT;
  23. import com.nimbusds.jwt.JWTParser;

  24. /**
  25.  * @author jricher
  26.  *
  27.  */
  28. @Converter
  29. public class JWTStringConverter implements AttributeConverter<JWT, String> {

  30.     public static Logger logger = LoggerFactory.getLogger(JWTStringConverter.class);

  31.     @Override
  32.     public String convertToDatabaseColumn(JWT attribute) {
  33.         if (attribute != null) {
  34.             return attribute.serialize();
  35.         } else {
  36.             return null;
  37.         }
  38.     }

  39.     /* (non-Javadoc)
  40.      * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object)
  41.      */
  42.     @Override
  43.     public JWT convertToEntityAttribute(String dbData) {
  44.         if (dbData != null) {
  45.             try {
  46.                 JWT jwt = JWTParser.parse(dbData);
  47.                 return jwt;
  48.             } catch (ParseException e) {
  49.                 logger.error("Unable to parse JWT", e);
  50.                 return null;
  51.             }
  52.         } else {
  53.             return null;
  54.         }
  55.     }

  56. }