001/* 002 * Copyright 2013 Anyware Services 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 */ 016package org.ametys.core.util; 017 018import java.io.IOException; 019 020import org.apache.avalon.framework.component.Component; 021import org.apache.avalon.framework.logger.LogEnabled; 022import org.apache.avalon.framework.logger.Logger; 023import org.apache.avalon.framework.service.ServiceException; 024import org.apache.avalon.framework.service.ServiceManager; 025import org.apache.avalon.framework.service.Serviceable; 026 027import org.ametys.runtime.i18n.I18nizableText; 028 029import com.fasterxml.jackson.core.JsonGenerationException; 030import com.fasterxml.jackson.core.JsonGenerator; 031import com.fasterxml.jackson.databind.SerializerProvider; 032import com.fasterxml.jackson.databind.ser.std.StdSerializer; 033 034/** 035 * Serializer for {@link I18nizableText} objects. 036 * Returns the translated message for JSON value. 037 */ 038public class I18nizableTextSerializer extends StdSerializer<I18nizableText> implements Component, Serviceable, LogEnabled 039{ 040 /** The Avalon Role */ 041 public static final String ROLE = I18nizableTextSerializer.class.getName(); 042 043 private I18nUtils _i18nUtils; 044 private Logger _logger; 045 046 /** 047 * Constructor 048 */ 049 public I18nizableTextSerializer() 050 { 051 super(I18nizableText.class); 052 } 053 054 @Override 055 public void service(ServiceManager manager) throws ServiceException 056 { 057 _i18nUtils = (I18nUtils) manager.lookup(I18nUtils.ROLE); 058 } 059 060 @Override 061 public void enableLogging(Logger logger) 062 { 063 _logger = logger; 064 } 065 066 @Override 067 public void serialize(I18nizableText value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException 068 { 069 if (value.isI18n()) 070 { 071 String msg = _i18nUtils.translate(value); 072 if (msg == null) 073 { 074 if (_logger.isWarnEnabled()) 075 { 076 _logger.warn("Translation not found for key " + value.getKey() + " in catalogue " + value.getCatalogue()); 077 } 078 079 jgen.writeString(value.getCatalogue() + ':' + value.getKey()); 080 } 081 else 082 { 083 jgen.writeString(msg); 084 } 085 } 086 else 087 { 088 jgen.writeString(value.getLabel()); 089 } 090 } 091}