MarshalledSimpleCollection.java

/***************************************************************************
   Copyright 2014 Emily Estes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
***************************************************************************/
package net.metanotion.contentstore;


import java.util.ArrayList;
import java.util.Map;

import net.metanotion.json.JsonMagic;
import net.metanotion.json.JsonObject;

import net.metanotion.util.Pair;

/** This SimpleCollection implementation will marshall objects from a generic simple collection instance into
one that deals in JSON objects.
	@param <O> The objects stored in the collection backing this one.
*/
public final class MarshalledSimpleCollection<O> implements SimpleCollection<JsonObject> {
	private final JsonMagic<O> json;
	private final SimpleCollection<O> collection;

	/** Create a simple collection backed by generic simple collection.
		@param klazz The type of objects in the backing collection.
		@param collection The backing collection.
	*/
	public MarshalledSimpleCollection(final Class<O> klazz, final SimpleCollection<O> collection) {
		this.json = new JsonMagic<>(klazz);
		this.collection = collection;
	}

	@Override public Iterable<Map.Entry<String, JsonObject>> list(final int maxPageSize, final int offset) {
		final ArrayList<Map.Entry<String,JsonObject>> list = new ArrayList<>();
		for(final Map.Entry<String,O> ix: collection.list(maxPageSize, offset)) {
			list.add(new Pair<String,JsonObject>(ix.getKey(), json.toJSON(ix.getValue())));
		}
		return list;
	}

	@Override public JsonObject get(final String index) { return json.toJSON(collection.get(index)); }

	@Override public String create(final JsonObject o) { return collection.create(json.toStruct(o)); }

	@Override public Map.Entry<String,JsonObject> update(final String index, final JsonObject o) {
		final Map.Entry<String,O> ix = collection.update(index, json.toStruct(o));
		return new Pair<String,JsonObject>(ix.getKey(), json.toJSON(ix.getValue()));
	}

	@Override public boolean remove(final String index) { return collection.remove(index); }
}