View Javadoc
1   /*
2    * Copyright (c) 2001-2017, Zoltan Farkas All Rights Reserved.
3    *
4    * This library is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Lesser General Public
6    * License as published by the Free Software Foundation; either
7    * version 2.1 of the License, or (at your option) any later version.
8    *
9    * This library is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU Lesser General Public
15   * License along with this program; if not, write to the Free Software
16   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17   *
18   * Additionally licensed with:
19   *
20   * Licensed under the Apache License, Version 2.0 (the "License");
21   * you may not use this file except in compliance with the License.
22   * You may obtain a copy of the License at
23   *
24   *      http://www.apache.org/licenses/LICENSE-2.0
25   *
26   * Unless required by applicable law or agreed to in writing, software
27   * distributed under the License is distributed on an "AS IS" BASIS,
28   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29   * See the License for the specific language governing permissions and
30   * limitations under the License.
31   */
32  package org.spf4j.base;
33  
34  import com.fasterxml.jackson.core.JsonFactory;
35  import com.fasterxml.jackson.core.JsonGenerator;
36  import com.fasterxml.jackson.core.JsonParser;
37  import com.fasterxml.jackson.databind.JsonSerializer;
38  import com.fasterxml.jackson.databind.Module;
39  import com.fasterxml.jackson.databind.ObjectMapper;
40  import com.fasterxml.jackson.databind.SerializationFeature;
41  import com.fasterxml.jackson.databind.SerializerProvider;
42  import com.fasterxml.jackson.databind.module.SimpleModule;
43  import java.io.IOException;
44  import java.util.ServiceLoader;
45  
46  /**
47   * @author Zoltan Farkas
48   */
49  public final class Json {
50  
51    public static final JsonFactory FACTORY = new JsonFactory();
52  
53    public static final ObjectMapper MAPPER = new ObjectMapper(FACTORY);
54  
55    private Json() { }
56  
57    static {
58      FACTORY.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
59      SimpleModule module = new SimpleModule("spf4j");
60      loadServices(module);
61      module.addSerializer(JsonWriteable.class, jsonWritableSerializer());
62      MAPPER.registerModule(module);
63      ServiceLoader<Module> loader = ServiceLoader.load(Module.class);
64      for (Module mod : loader) {
65        MAPPER.registerModule(mod);
66      }
67      MAPPER.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
68      FACTORY.setCodec(MAPPER);
69    }
70  
71    private static void loadServices(final SimpleModule module) {
72      ServiceLoader<JsonSerializer> loader = ServiceLoader.load(JsonSerializer.class);
73      for (JsonSerializer ser : loader) {
74        module.addSerializer(ser);
75      }
76    }
77  
78    public static JsonSerializer<JsonWriteable> jsonWritableSerializer() {
79      return new JsonSerializer<JsonWriteable>() {
80        @Override
81        public void serialize(final JsonWriteable value, final JsonGenerator jgen, final SerializerProvider provider)
82                throws IOException {
83          Object outputTarget = jgen.getOutputTarget();
84          if (outputTarget instanceof Appendable) {
85            jgen.flush();
86            if (jgen.getOutputContext().getCurrentName() != null) {
87              ((Appendable) outputTarget).append(':');
88            }
89            value.writeJsonTo((Appendable) outputTarget);
90            return;
91          }
92          StringBuilder json = new StringBuilder(32);
93          value.writeJsonTo(json);
94          jgen.writeRawValue(json.toString());
95        }
96      };
97    }
98  
99    public static JsonSerializer<Object> toStringJsonWritableSerializer() {
100     return new JsonSerializer<Object>() {
101       @Override
102       public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider)
103               throws IOException {
104         jgen.writeString(value.toString());
105       }
106     };
107   }
108 
109 
110 }