1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.metricshub.wbem.sblim.slp.internal.ua;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 import java.io.IOException;
45 import java.io.OutputStream;
46 import java.net.InetAddress;
47 import java.net.Socket;
48 import org.metricshub.wbem.sblim.slp.ServiceLocationException;
49 import org.metricshub.wbem.sblim.slp.internal.SLPConfig;
50 import org.metricshub.wbem.sblim.slp.internal.TRC;
51 import org.metricshub.wbem.sblim.slp.internal.msg.MsgFactory;
52 import org.metricshub.wbem.sblim.slp.internal.msg.ReplyMessage;
53 import org.metricshub.wbem.sblim.slp.internal.msg.RequestMessage;
54
55
56
57
58
59 public class TCPRequester implements Runnable {
60 private InetAddress iDestination;
61
62 private Thread iThread;
63
64 private ResultTable iResTable;
65
66 private RequestMessage iReqMsg;
67
68 private byte[] iRequestBytes;
69
70 private int iPort = SLPConfig.getGlobalCfg().getPort();
71
72 private final int iTCPTimeOut = SLPConfig.getGlobalCfg().getTCPTimeout();
73
74
75
76
77
78
79
80
81
82
83 public TCPRequester(ResultTable pResTable, InetAddress pDestination, RequestMessage pReqMsg, boolean pAsThread)
84 throws ServiceLocationException {
85 this.iResTable = pResTable;
86 this.iDestination = pDestination;
87 this.iReqMsg = pReqMsg;
88 this.iRequestBytes = pReqMsg.serializeWithoutResponders(false, false, true);
89
90 if (pAsThread) {
91 this.iThread = new Thread(this);
92 this.iThread.start();
93 } else {
94 this.iThread = null;
95 run();
96 }
97 }
98
99
100
101
102 public void waitFor() {
103 if (this.iThread == null) return;
104 try {
105 this.iThread.join();
106 } catch (InterruptedException e) {
107 TRC.error(e);
108 }
109 }
110
111 public void run() {
112 Socket socket = null;
113 try {
114 socket = new Socket(this.iDestination, this.iPort);
115 socket.setSoTimeout(this.iTCPTimeOut);
116 OutputStream os = socket.getOutputStream();
117 TRC.debug("sendTCP");
118 os.write(this.iRequestBytes);
119 os.flush();
120 handleResponse(socket);
121 TRC.debug("recievedOnTCP");
122 } catch (Exception e) {
123 TRC.error(e.getMessage());
124 } finally {
125 if (socket != null) {
126 try {
127 socket.close();
128 } catch (IOException e) {
129 TRC.error(e);
130 }
131 }
132 }
133 }
134
135 private void handleResponse(Socket pSocket) {
136 ReplyMessage replyMsg;
137 try {
138 replyMsg = (ReplyMessage) MsgFactory.parse(pSocket);
139 } catch (Exception e) {
140 this.iResTable.addException(e);
141 return;
142 }
143 if (
144 this.iReqMsg.getXID() == replyMsg.getXID() && this.iReqMsg.isAllowedResponseType(replyMsg)
145 ) this.iResTable.addResults(replyMsg);
146 }
147 }