001/* 002 * Copyright 2020 Global Biodiversity Information Facility (GBIF) 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 */ 016package org.gbif.api; 017 018import java.io.IOException; 019 020import com.fasterxml.jackson.annotation.JsonInclude; 021import com.fasterxml.jackson.databind.DeserializationFeature; 022import com.fasterxml.jackson.databind.ObjectMapper; 023import com.fasterxml.jackson.databind.SerializationFeature; 024 025import static org.junit.jupiter.api.Assertions.assertEquals; 026 027public class SerdeTestUtils { 028 029 private static final ObjectMapper MAPPER = new ObjectMapper(); 030 031 static { 032 // copied from common-ws JacksonJsonContextResolver to provide the same mapper configs 033 MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); 034 MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 035 MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 036 // extra for better debugging 037 MAPPER.enable(SerializationFeature.INDENT_OUTPUT); 038 } 039 040 /** 041 * Does a roundtrip from object to JSON and back to another object and then compares the 2 instances 042 * and their hashcodes. 043 * 044 * @return JSON string of the serialized object 045 */ 046 public static <T> String testSerDe(T obj, Class<T> objClass) throws IOException { 047 String json = MAPPER.writeValueAsString(obj); 048 T obj2 = MAPPER.readValue(json, objClass); 049 assertEquals(obj2, obj); 050 assertEquals(obj.hashCode(), obj2.hashCode()); 051 return json; 052 } 053 054 public static String serialize(Object obj) throws IOException { 055 return MAPPER.writeValueAsString(obj); 056 } 057 058 public static <T> T deserialize(String json, Class<T> objClass) throws IOException { 059 return MAPPER.readValue(json, objClass); 060 } 061 062 private SerdeTestUtils() { 063 throw new UnsupportedOperationException("Can't initialize class"); 064 } 065 066}