AbstractRestViewV1.java 2.04 KB
package fi.codecrew.moya.rest.meta.v1;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;

import fi.codecrew.moya.model.EntityMeta;
import fi.codecrew.moya.utilities.JsonUtils;

public abstract class AbstractRestViewV1 {

	/**
	 * Convert List<PathSegment> to List<String>
	 * 
	 * @param path
	 *            List<PathSegment>
	 * @return List<String>
	 */
	public List<String> pathToStrings(List<PathSegment> path) {
		ArrayList<String> stringList = new ArrayList<String>(path.size());
		for (PathSegment s : path) {
			String segmentString = s.getPath();
			if (segmentString != null && !segmentString.isEmpty()) {
				stringList.add(segmentString);
			}
		}
		return stringList;
	}

	public JsonObject parseJson(String jsonString) {
		JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
		JsonObject newData = jsonReader.readObject();
		return newData;
	}

	protected void setEntityMeta(EntityMeta entity, List<PathSegment> keys, String jsonString) {
		if (entity == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}

		JsonObject meta = entity.getMeta();
		if (meta == null) {
			meta = Json.createObjectBuilder().build();
		}

		JsonObject alteredMeta = JsonUtils.alterSubObject(meta, pathToStrings(keys), parseJson(jsonString));
		if (alteredMeta != null) {
			entity.setMeta(alteredMeta);
		}
	}

	protected String getEntityMeta(EntityMeta entity, List<PathSegment> keys) {
		if (entity == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}

		JsonObject meta = entity.getMeta();
		if (meta == null) {
			meta = Json.createObjectBuilder().build();
		}

		JsonValue subValue = JsonUtils.getSubObject(meta, pathToStrings(keys));
		if (subValue == null) {
			subValue = Json.createObjectBuilder().build();
		}

		return subValue.toString() + "\n";
	}
}