View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.catalog.api.dao;
18  
19  import java.time.LocalDateTime;
20  
21  import com.fasterxml.jackson.core.JsonFactory;
22  import com.fasterxml.jackson.core.JsonParser;
23  import com.fasterxml.jackson.core.JsonProcessingException;
24  import com.fasterxml.jackson.databind.ObjectMapper;
25  import org.apache.logging.log4j.LogManager;
26  import org.apache.logging.log4j.Logger;
27  import org.apache.logging.log4j.catalog.api.Attribute;
28  import org.apache.logging.log4j.catalog.api.CatalogReader;
29  
30  /**
31   * Provides access to the JSON version of the catalog. This version is not modifiable.
32   */
33  //@Component
34  public class JsonCatalogReader extends AbstractCatalogReader {
35  
36      private static final Logger LOGGER = LogManager.getLogger(JsonCatalogReader.class);
37  
38      //@Autowired
39      CatalogReader catalogReader;
40  
41      public CatalogReader getCatalogReader() {
42          return catalogReader;
43      }
44  
45      public void setCatalogReader(CatalogReader catalogReader) {
46          this.catalogReader = catalogReader;
47      }
48  
49      //@PostConstruct
50      public void init() {
51          catalogData = catalogReader.read();
52          for (Attribute attribute : catalogData.getAttributes()) {
53              attributes.put(attribute.getName(), attribute);
54          }
55      }
56  
57      @Override
58      public String readCatalog() {
59          JsonFactory factory = new JsonFactory();
60          factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
61          ObjectMapper mapper = new ObjectMapper(factory);
62          try {
63              return mapper.writeValueAsString(catalogData);
64          } catch (JsonProcessingException ex) {
65              LOGGER.error("Unable to serialze Catalog", ex);
66              return null;
67          }
68      }
69  
70      @Override
71      public LocalDateTime getLastUpdated() {
72          return catalogReader.getLastUpdated();
73      }
74  }