001/* 002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo 018 */ 019package org.nuxeo.ecm.automation.client.jaxrs.spi.marshallers; 020 021import java.io.IOException; 022 023import org.codehaus.jackson.JsonGenerator; 024import org.codehaus.jackson.JsonParser; 025import org.nuxeo.ecm.automation.client.annotations.EntityType; 026import org.nuxeo.ecm.automation.client.jaxrs.spi.JsonMarshaller; 027 028/** 029 * Marshaller for the default ObjectCodec for the java Boolean class instances. Returned into entity-type primitive the 030 * content of existing {@link EntityType} annotation. 031 * 032 * @author ogrisel 033 * @since 5.7 034 */ 035public class PojoMarshaller<T> implements JsonMarshaller<T> { 036 037 final Class<T> type; 038 039 protected String entityTypeName; 040 041 public PojoMarshaller(Class<T> type) { 042 this.type = type; 043 this.entityTypeName = ""; 044 if (type.getAnnotation(EntityType.class) != null) { 045 this.entityTypeName = type.getAnnotation(EntityType.class).value(); 046 } 047 } 048 049 public static <T> PojoMarshaller<T> forClass(Class<T> type) { 050 return new PojoMarshaller<T>(type); 051 } 052 053 @Override 054 public String getType() { 055 return entityTypeName.isEmpty() ? type.getName() : entityTypeName; 056 } 057 058 @Override 059 public Class<T> getJavaType() { 060 return type; 061 } 062 063 @Override 064 public T read(JsonParser jp) throws IOException { 065 jp.nextToken(); 066 jp.nextToken(); 067 return jp.readValueAs(type); 068 } 069 070 @Override 071 public void write(JsonGenerator jg, Object value) throws IOException { 072 jg.writeStartObject(); 073 jg.writeStringField("entity-type", getType()); 074 jg.writeObjectField("value", value); 075 jg.writeEndObject(); 076 } 077 078}