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.InputStream;
25  import java.net.URL;
26  
27  import org.osgi.framework.Bundle;
28  import org.slf4j.Logger;
29  import org.slf4j.LoggerFactory;
30  
31  /**
32   * Reader for service model files.
33   */
34  public final class ServiceModelReader {
35  
36    /**
37     * Classpath prefix where HAL documentation files are stored.
38     */
39    public static final String DOCS_CLASSPATH_PREFIX = "HAL-DOCS-INF";
40  
41    /**
42     * Filename with serialized model information for HAL documentation.
43     */
44    public static final String SERVICE_DOC_FILE = "serviceDoc.json";
45  
46    private static final Logger log = LoggerFactory.getLogger(ServiceModelReader.class);
47  
48    private ServiceModelReader() {
49      // static methods only
50    }
51  
52    /**
53     * Reads service model from bundle classpath.
54     * @param bundle Bundle
55     * @return Service model or null if not found or not parseable.
56     */
57    public static Service read(Bundle bundle) {
58      String resourcePath = DOCS_CLASSPATH_PREFIX + "/" + SERVICE_DOC_FILE;
59      URL bundleResource = bundle.getResource(resourcePath);
60      if (bundleResource == null) {
61        return null;
62      }
63      try (InputStream is = bundleResource.openStream()) {
64        return new ServiceJson().read(is);
65      }
66      catch (Throwable ex) {
67        log.error("Unable to parse JSON file " + resourcePath + " from bundle " + bundle.getSymbolicName());
68        return null;
69      }
70    }
71  
72  }