001/* 002 * Copyright (c) 2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * Nuxeo 011 */ 012package org.nuxeo.ecm.automation.client.jaxrs.spi.marshallers; 013 014import java.io.IOException; 015 016import org.codehaus.jackson.JsonGenerator; 017import org.codehaus.jackson.JsonParser; 018import org.nuxeo.ecm.automation.client.annotations.EntityType; 019import org.nuxeo.ecm.automation.client.jaxrs.spi.JsonMarshaller; 020 021/** 022 * Marshaller for the default ObjectCodec for the java Boolean class instances. Returned into entity-type primitive the 023 * content of existing {@link EntityType} annotation. 024 * 025 * @author ogrisel 026 * @since 5.7 027 */ 028public class PojoMarshaller<T> implements JsonMarshaller<T> { 029 030 final Class<T> type; 031 032 protected String entityTypeName; 033 034 public PojoMarshaller(Class<T> type) { 035 this.type = type; 036 this.entityTypeName = ""; 037 if (type.getAnnotation(EntityType.class) != null) { 038 this.entityTypeName = type.getAnnotation(EntityType.class).value(); 039 } 040 } 041 042 public static <T> PojoMarshaller<T> forClass(Class<T> type) { 043 return new PojoMarshaller<T>(type); 044 } 045 046 @Override 047 public String getType() { 048 return entityTypeName.isEmpty() ? type.getName() : entityTypeName; 049 } 050 051 @Override 052 public Class<T> getJavaType() { 053 return type; 054 } 055 056 @Override 057 public T read(JsonParser jp) throws IOException { 058 jp.nextToken(); 059 jp.nextToken(); 060 return jp.readValueAs(type); 061 } 062 063 @Override 064 public void write(JsonGenerator jg, Object value) throws IOException { 065 jg.writeStartObject(); 066 jg.writeStringField("entity-type", getType()); 067 jg.writeObjectField("value", value); 068 jg.writeEndObject(); 069 } 070 071}