View Javadoc
1   /*
2    * Copyright (C) 2013 4th Line GmbH, Switzerland
3    *
4    * The contents of this file are subject to the terms of either the GNU
5    * Lesser General Public License Version 2 or later ("LGPL") or the
6    * Common Development and Distribution License Version 1 or later
7    * ("CDDL") (collectively, the "License"). You may not use this file
8    * except in compliance with the License. See LICENSE.txt for more
9    * information.
10   *
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14   */
15  
16  package org.fourthline.cling.protocol;
17  
18  import org.fourthline.cling.UpnpService;
19  import org.fourthline.cling.transport.RouterException;
20  import org.seamless.util.Exceptions;
21  
22  import java.util.logging.Level;
23  import java.util.logging.Logger;
24  
25  /**
26   * Supertype for all synchronously executing protocols, sending UPnP messages.
27   * <p>
28   * After instantiation by the {@link ProtocolFactory}, this protocol <code>run()</code>s and
29   * calls its {@link #execute()} method.
30   * </p>
31   * <p>
32   * A {@link RouterException} during execution will be wrapped in a fatal <code>RuntimeException</code>,
33   * unless its cause is an <code>InterruptedException</code>, in which case an INFO message will be logged.
34   * </p>
35   *
36   * @author Christian Bauer
37   */
38  public abstract class SendingAsync implements Runnable {
39  
40      final private static Logger log = Logger.getLogger(UpnpService.class.getName());
41  
42      private final UpnpService upnpService;
43  
44      protected SendingAsync(UpnpService upnpService) {
45          this.upnpService = upnpService;
46      }
47  
48      public UpnpService getUpnpService() {
49          return upnpService;
50      }
51  
52      public void run() {
53          try {
54              execute();
55          } catch (Exception ex) {
56              Throwable cause = Exceptions.unwrap(ex);
57              if (cause instanceof InterruptedException) {
58                  log.log(Level.INFO, "Interrupted protocol '" + getClass().getSimpleName() + "': " + ex, cause);
59              } else {
60                  throw new RuntimeException(
61                      "Fatal error while executing protocol '" + getClass().getSimpleName() + "': " + ex, ex
62                  );
63              }
64          }
65      }
66  
67      protected abstract void execute() throws RouterException;
68  
69      @Override
70      public String toString() {
71          return "(" + getClass().getSimpleName() + ")";
72      }
73  
74  }