View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2017 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.sling.commons.caservice.impl;
21  
22  import java.io.PrintWriter;
23  import java.util.Map;
24  import java.util.concurrent.ConcurrentMap;
25  
26  import org.apache.commons.lang3.StringUtils;
27  import org.apache.felix.inventory.Format;
28  import org.apache.felix.inventory.InventoryPrinter;
29  import org.osgi.service.component.annotations.Component;
30  import org.osgi.service.component.annotations.Reference;
31  
32  import io.wcm.sling.commons.caservice.ContextAwareService;
33  import io.wcm.sling.commons.caservice.ContextAwareServiceResolver;
34  
35  /**
36   * Inventory printer for context-aware services.
37   */
38  @Component(service = InventoryPrinter.class, property = {
39      InventoryPrinter.NAME + "=wcmio-caservice",
40      InventoryPrinter.TITLE + "=wcm.io Context-Aware Services",
41      InventoryPrinter.FORMAT + "=TEXT"
42  })
43  public class ContextAwareServiceInventoryPrinter implements InventoryPrinter {
44  
45    @Reference
46    private ContextAwareServiceResolver contextAwareServiceResolver;
47  
48    @Override
49    public void print(PrintWriter pw, Format format, boolean isZip) {
50      if (format != Format.TEXT) {
51        return;
52      }
53      if (!(contextAwareServiceResolver instanceof ContextAwareServiceResolverImpl)) {
54        return;
55      }
56  
57      ConcurrentMap<String, ContextAwareServiceTracker<ContextAwareService>> map = ((ContextAwareServiceResolverImpl)contextAwareServiceResolver)
58          .getContextAwareServiceTrackerMap();
59      if (map.isEmpty()) {
60        pw.println();
61        pw.println("No context-aware services found.");
62        pw.println("The services are registered lazily on first access of the service interface or class.");
63        return;
64      }
65      for (Map.Entry<String, ContextAwareServiceTracker<ContextAwareService>> entry : map.entrySet()) {
66        pw.println();
67        pw.println(entry.getKey());
68        pw.println(StringUtils.repeat('-', entry.getKey().length()));
69        for (ServiceInfo<ContextAwareService> serviceInfo : entry.getValue().getServiceInfos()) {
70          pw.print("- ");
71          pw.println(serviceInfo.toString());
72        }
73      }
74    }
75  
76  }