All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hibernate.search.elasticsearch.gson.impl.AbstractExtraPropertiesJsonAdapter Maven / Gradle / Ivy

There is a newer version: 5.11.12.Final
Show newest version
/*
 * Hibernate Search, full-text search for your domain model
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later
 * See the lgpl.txt file in the root directory or .
 */
package org.hibernate.search.elasticsearch.gson.impl;

import java.io.IOException;
import java.util.Map;

import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

/**
 * @author Yoann Rodiere
 */
public abstract class AbstractExtraPropertiesJsonAdapter extends TypeAdapter {

	interface FieldAdapter {
		void read(JsonReader in, T instance) throws IOException;

		void write(JsonWriter out, T instance) throws IOException;

		boolean serialized();
	}

	interface ExtraPropertyAdapter {
		void readOne(JsonReader in, String name, T instance) throws IOException;

		void writeAll(JsonWriter out, T instance) throws IOException;
	}

	private final Map> fieldAdapters;
	private final ExtraPropertyAdapter extraPropertyAdapter;

	public AbstractExtraPropertiesJsonAdapter(Map> fieldAdapters,
			ExtraPropertyAdapter extraPropertyAdapter) {
		super();
		this.fieldAdapters = fieldAdapters;
		this.extraPropertyAdapter = extraPropertyAdapter;
	}

	@Override
	public T read(JsonReader in) throws IOException {
		if ( in.peek() == JsonToken.NULL ) {
			in.nextNull();
			return null;
		}

		T instance = createInstance();
		try {
			in.beginObject();
			while ( in.hasNext() ) {
				String name = in.nextName();
				FieldAdapter fieldAdapter = fieldAdapters.get( name );
				if ( fieldAdapter == null ) {
					extraPropertyAdapter.readOne( in, name, instance );
				}
				else {
					fieldAdapter.read( in, instance );
				}
			}
			in.endObject();
		}
		catch (IllegalStateException e) {
			throw new JsonSyntaxException( e );
		}

		return instance;
	}

	@Override
	public void write(JsonWriter out, T instance) throws IOException {
		if ( instance == null ) {
			out.nullValue();
		}
		out.beginObject();
		for ( Map.Entry> entry : fieldAdapters.entrySet() ) {
			FieldAdapter fieldAdapter = entry.getValue();
			if ( fieldAdapter.serialized() ) {
				out.name( entry.getKey() );
				entry.getValue().write( out, instance );
			}
		}
		extraPropertyAdapter.writeAll( out, instance );
		out.endObject();
	}

	protected abstract T createInstance();

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy