JsonAttributeConverter.java 2.36 KB
package fi.codecrew.moya.model.converters;

import java.io.StringReader;
import java.sql.SQLException;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.postgresql.util.PGobject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Converter(autoApply = true)
public class JsonAttributeConverter implements AttributeConverter<JsonObject, PGobject> {
	private static final Logger log = LoggerFactory.getLogger(JsonAttributeConverter.class);

	/**
	 * JsonObject -> PGobject
	 */
	public PGobject convertToDatabaseColumn(JsonObject jsonObject) {
		//log.info("Converting JsonObject to PGobject. Original JsonObject: {}", jsonObject);

		PGobject pgObject = new PGobject();
		pgObject.setType("json");
		try {
			if (jsonObject != null) {
				pgObject.setValue(jsonObject.toString());
			} else {
				pgObject.setValue(null);
			}
		} catch (SQLException e) {
			log.warn("PGobject.setValue() threw an exception. Should not happen. Something is wrong.", e);
		}
//		log.info("Converted JsonObject to PGobject: {}", pgObject);
		return pgObject;
	}

	/**
	 * PGobject -> JsonObject
	 */
	public JsonObject convertToEntityAttribute(PGobject pgObject) {
//		log.info("Converting PGobject to JsonObject. Original PGobject: {}", pgObject);

		// Convert null values to empty object
		if (pgObject == null) {
//			log.info("PGobject was null. Retruning an empty JsonObject.");
			return Json.createObjectBuilder().build();
		}

		// Correct type of object?
		if (pgObject.getType().equals("json") == false) {
			log.error("Expected to be converting JSON column, but got PGobject whose type is not json but {}", pgObject.getType());
			throw new RuntimeException("Expected JSON object from database");
		}

		// Read the value as JSON
		String stringValue = pgObject.getValue();
		
		// We must test for "null" because pgObject.getValues() seems to return "null" for null :)
		if (stringValue != null && !stringValue.toLowerCase().equals("null")) {
			JsonReader jsonReader = Json.createReader(new StringReader(stringValue));
			JsonObject jsonObject = jsonReader.readObject();
//			log.info("Converted PGobject to JsonObject: {}", jsonObject);
			return jsonObject;
		} else {
			log.info("Null value. Returning empty JsonObject");
			return Json.createObjectBuilder().build();
		}
	}
}