View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2015 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.caravan.hal.docs.impl.reader;
21  
22  import io.wcm.caravan.hal.docs.impl.model.Service;
23  
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.OutputStream;
27  
28  import com.fasterxml.jackson.annotation.JsonAutoDetect;
29  import com.fasterxml.jackson.annotation.JsonInclude.Include;
30  import com.fasterxml.jackson.databind.ObjectMapper;
31  
32  /**
33   * Manages serialization and deserialization of service JSON files.
34   */
35  public final class ServiceJson {
36  
37    private final ObjectMapper objectMapper = new ObjectMapper()
38        .setSerializationInclusion(Include.NON_EMPTY);
39  
40    /**
41     * Constructor
42     */
43    public ServiceJson() {
44      // ensure only field serialization is used for jackson
45      objectMapper.setVisibilityChecker(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
46          .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
47          .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
48          .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
49          .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
50    }
51  
52    /**
53     * Write model to stream.
54     * @param model Model
55     * @param os Stream
56     * @throws IOException
57     */
58    public void write(Service model, OutputStream os) throws IOException {
59      objectMapper.writerWithDefaultPrettyPrinter().writeValue(os, model);
60    }
61  
62    /**
63     * Read model from stream
64     * @param is stream
65     * @return Model
66     * @throws IOException
67     */
68    public Service read(InputStream is) throws IOException {
69      return objectMapper.readValue(is, Service.class);
70    }
71  
72  }