1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.fourthline.cling.protocol;
17
18 import org.fourthline.cling.UpnpService;
19 import org.fourthline.cling.model.message.UpnpMessage;
20 import org.fourthline.cling.model.message.header.UpnpHeader;
21 import org.fourthline.cling.transport.RouterException;
22 import org.seamless.util.Exceptions;
23
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26
27
28
29
30
31
32
33
34
35
36
37
38
39 public abstract class ReceivingAsync<M extends UpnpMessage> implements Runnable {
40
41 final private static Logger log = Logger.getLogger(UpnpService.class.getName());
42
43 private final UpnpService upnpService;
44
45 private M inputMessage;
46
47 protected ReceivingAsync(UpnpService upnpService, M inputMessage) {
48 this.upnpService = upnpService;
49 this.inputMessage = inputMessage;
50 }
51
52 public UpnpService getUpnpService() {
53 return upnpService;
54 }
55
56 public M getInputMessage() {
57 return inputMessage;
58 }
59
60 public void run() {
61 boolean proceed;
62 try {
63 proceed = waitBeforeExecution();
64 } catch (InterruptedException ex) {
65 log.info("Protocol wait before execution interrupted (on shutdown?): " + getClass().getSimpleName());
66 proceed = false;
67 }
68
69 if (proceed) {
70 try {
71 execute();
72 } catch (Exception ex) {
73 Throwable cause = Exceptions.unwrap(ex);
74 if (cause instanceof InterruptedException) {
75 log.log(Level.INFO, "Interrupted protocol '" + getClass().getSimpleName() + "': " + ex, cause);
76 } else {
77 throw new RuntimeException(
78 "Fatal error while executing protocol '" + getClass().getSimpleName() + "': " + ex, ex
79 );
80 }
81 }
82 }
83 }
84
85
86
87
88
89
90
91
92 protected boolean waitBeforeExecution() throws InterruptedException {
93
94 return true;
95 }
96
97 protected abstract void execute() throws RouterException;
98
99 protected <H extends UpnpHeader> H getFirstHeader(UpnpHeader.Type headerType, Class<H> subtype) {
100 return getInputMessage().getHeaders().getFirstHeader(headerType, subtype);
101 }
102
103 @Override
104 public String toString() {
105 return "(" + getClass().getSimpleName() + ")";
106 }
107
108 }