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.nuxeo.ecm.automation.client.annotations.EntityType; 024import org.nuxeo.ecm.automation.client.jaxrs.spi.JsonMarshaller; 025 026import com.fasterxml.jackson.core.JsonGenerator; 027import com.fasterxml.jackson.core.JsonParser; 028 029/** 030 * Marshaller for the default ObjectCodec for the java Boolean class instances. Returned into entity-type primitive the 031 * content of existing {@link EntityType} annotation. 032 * 033 * @author ogrisel 034 * @since 5.7 035 */ 036public class PojoMarshaller<T> implements JsonMarshaller<T> { 037 038 final Class<T> type; 039 040 protected String entityTypeName; 041 042 public PojoMarshaller(Class<T> type) { 043 this.type = type; 044 this.entityTypeName = ""; 045 if (type.getAnnotation(EntityType.class) != null) { 046 this.entityTypeName = type.getAnnotation(EntityType.class).value(); 047 } 048 } 049 050 public static <T> PojoMarshaller<T> forClass(Class<T> type) { 051 return new PojoMarshaller<T>(type); 052 } 053 054 @Override 055 public String getType() { 056 return entityTypeName.isEmpty() ? type.getName() : entityTypeName; 057 } 058 059 @Override 060 public Class<T> getJavaType() { 061 return type; 062 } 063 064 @Override 065 public T read(JsonParser jp) throws IOException { 066 jp.nextToken(); 067 jp.nextToken(); 068 return jp.readValueAs(type); 069 } 070 071 @Override 072 public void write(JsonGenerator jg, Object value) throws IOException { 073 jg.writeStartObject(); 074 jg.writeStringField("entity-type", getType()); 075 jg.writeObjectField("value", value); 076 jg.writeEndObject(); 077 } 078 079}