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.log4j.net;
18  
19  import javax.jmdns.JmDNS;
20  
21  /***
22   * This singleton holds the single instance of the JmDNS instance that is used to broadcast
23   * Appender related information via ZeroConf.  Once referenced, a single JmDNS instance is created
24   * and held.  To ensure your JVM exits cleanly you should ensure that you call the {@link #shutdown() } method
25   * to broadcast the disappearance of your devices, and cleanup sockets.  (alternatively you can call the close() 
26   * method on the JmDNS instead, totally up to you...)
27   * 
28   * See http://jmdns.sf.net for more information about JmDNS and ZeroConf.
29   * 
30   * @author psmith
31   *
32   */
33  public class Zeroconf4log4j {
34  
35      private static final JmDNS instance;
36  
37      static {
38          try {
39              instance = new JmDNS();
40          } catch (Exception e) {
41              e.printStackTrace();
42              throw new RuntimeException("Failed to initialize JmDNS");
43          }
44      }
45  
46      /***
47       * Returns the current instance of the JmDNS being used by log4j.
48       * 
49       * @throws IllegalStateException if JmDNS was not correctly initialized.
50       * 
51       * @return
52       */
53      public static JmDNS getInstance() {
54          checkState();
55          return instance;
56      }
57  
58      private static void checkState() {
59          if (instance == null) {
60              throw new IllegalStateException(
61                      "JmDNS did not initialize correctly");
62          }
63      }
64      
65      /***
66       * Ensures JmDNS cleanly broadcasts 'goodbye' and closes any sockets, and (more imporantly)
67       * ensures some Threads exit so your JVM can exit.
68       *
69       */
70      public static void shutdown() {
71          checkState();
72          instance.close();
73      }
74  }