forked from Petersoj/IQFeed4j
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIQConnectExecutable.java
268 lines (229 loc) · 9.87 KB
/
IQConnectExecutable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package net.jacobpeterson.iqfeed4j.executable;
import net.jacobpeterson.iqfeed4j.properties.IQFeed4jProperties;
import net.jacobpeterson.iqfeed4j.util.split.SplitUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* {@link IQConnectExecutable} provides a convenient way to start/stop the <code>IQConnect.exe</code> program.
*/
public class IQConnectExecutable {
private static final Logger LOGGER = LoggerFactory.getLogger(IQConnectExecutable.class);
private final String iqConnectCommand;
private final String productID;
private final String applicationVersion;
private final String login;
private final String password;
private final Boolean autoconnect;
private final Boolean saveLoginInfo;
private final Object startStopLock;
private boolean disableInternalProcessLogging;
private Process iqConnectProcess;
/**
* Instantiates a new {@link IQConnectExecutable} with properties defined in {@link
* IQFeed4jProperties#PROPERTIES_FILE}.
*/
public IQConnectExecutable() {
this(IQFeed4jProperties.IQCONNECT_COMMAND,
IQFeed4jProperties.PRODUCT_ID,
IQFeed4jProperties.APPLICATION_VERSION,
IQFeed4jProperties.LOGIN,
IQFeed4jProperties.PASSWORD,
IQFeed4jProperties.AUTOCONNECT,
IQFeed4jProperties.SAVE_LOGIN_INFO);
}
/**
* Instantiates a new {@link IQConnectExecutable}.
*
* @param iqConnectCommand the <code>IQConnect.exe</code> command (optional)
* @param productID the product ID (optional)
* @param applicationVersion the application version (optional)
* @param login the login (optional)
* @param password the password (optional)
* @param autoconnect the autoconnect (optional)
* @param saveLoginInfo the save login info (optional)
*/
public IQConnectExecutable(String iqConnectCommand, String productID, String applicationVersion, String login,
String password, Boolean autoconnect, Boolean saveLoginInfo) {
checkNotNull(iqConnectCommand);
this.iqConnectCommand = iqConnectCommand;
this.productID = productID;
this.applicationVersion = applicationVersion;
this.login = login;
this.password = password;
this.autoconnect = autoconnect;
this.saveLoginInfo = saveLoginInfo;
startStopLock = new Object();
disableInternalProcessLogging = false;
LOGGER.trace("{}", this);
}
/**
* Starts the <code>IQConnect.exe</code> executable with the given parameters asynchronously. Does nothing if it's
* already started. This method is synchronized with {@link #stop()}.
*
* @throws IOException thrown for {@link IOException}s
*/
public void start() throws IOException {
synchronized (startStopLock) {
if (iqConnectProcess == null || !iqConnectProcess.isAlive()) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.redirectErrorStream(true);
List<String> command = new ArrayList<>();
command.addAll(SplitUtil.splitQuoteEscapedSpaces(iqConnectCommand));
if (productID != null) {
command.add("‑product");
command.add(productID);
}
if (applicationVersion != null) {
command.add("-version");
command.add(applicationVersion);
}
if (login != null) {
command.add("-login");
command.add(login);
}
if (password != null) {
command.add("-password");
command.add(password);
}
if (autoconnect != null && autoconnect) {
command.add("-autoconnect");
}
if (saveLoginInfo != null && saveLoginInfo) {
command.add("-savelogininfo");
}
processBuilder.command(command);
LOGGER.debug("Starting IQConnect process with the following command: {}", command);
iqConnectProcess = processBuilder.start();
if (!disableInternalProcessLogging) {
createProcessReader();
}
}
}
}
/**
* Creates a process reader for {@link #iqConnectProcess} outputting to {@link #LOGGER}. Used for debugging
* purposes. This creates a {@link Thread} that dies on its own.
*/
private void createProcessReader() {
new Thread(() -> {
BufferedReader processReader = new BufferedReader(new InputStreamReader(iqConnectProcess.getInputStream()));
while (!Thread.currentThread().isInterrupted()) {
try {
String line = processReader.readLine();
if (line == null) {
processReader.close();
return;
} else {
LOGGER.debug("IQConnect.exe process output: {}", line);
}
} catch (IOException exception) {
LOGGER.error("IQConnect.exe process output reading error!", exception);
return;
}
}
}).start();
}
/**
* Stops the <code>IQConnect.exe</code> executable. Does nothing if it's already stopped. This method is
* synchronized with {@link #start()}.
*/
public void stop() {
synchronized (startStopLock) {
if (iqConnectProcess != null && iqConnectProcess.isAlive()) {
iqConnectProcess.destroy();
LOGGER.debug("Stopped IQConnect process.");
}
}
}
/**
* Calls {@link #waitForConnection(String, int, int, long)} with {@link IQFeed4jProperties#FEED_HOSTNAME} and {@link
* IQFeed4jProperties#LOOKUP_FEED_PORT} and a <code>pollingInterval</code> of 250ms.
*
* @see #waitForConnection(String, int, int, long)
*/
public int waitForConnection(long timeoutMillis) throws TimeoutException {
return waitForConnection(IQFeed4jProperties.FEED_HOSTNAME, IQFeed4jProperties.LOOKUP_FEED_PORT,
250, timeoutMillis);
}
/**
* This method is used to block the current thread until <code>IQConnect.exe</code> has successfully started up. It
* will used the passed in <code>hostname</code> and <code>port</code> to continuously attempt connections to
* <code>IQConnect.exe</code> until <code>timoutMillis</code> have elapsed or a successful connection was made.
*
* @param hostname the hostname
* @param port the port
* @param pollingInterval the time to wait between connection attempts
* @param timoutMillis the timeout time in milliseconds
*
* @return the number of attempts it took to connect, or <code>-1</code> if waiting for connection was interrupted
*
* @throws TimeoutException thrown when <code>timoutMillis</code> have elapsed without a successful connection
*/
public int waitForConnection(String hostname, int port, int pollingInterval, long timoutMillis)
throws TimeoutException {
checkNotNull(hostname);
checkArgument(port > 0);
checkArgument(timoutMillis > 0);
ExecutablePollingFeed executablePollingFeed = new ExecutablePollingFeed(hostname, port);
int attempts = 0;
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < timoutMillis) {
try {
Thread.sleep(pollingInterval);
attempts++;
executablePollingFeed.start();
executablePollingFeed.stop(); // This will execute upon successful 'start()'
Thread.sleep(500); // Sleep for a bit longer to ensure that IQConnect ready
return attempts;
} catch (InterruptedException interruptedException) {
return -1;
} catch (IOException ignored) {}
}
throw new TimeoutException(String.format("Could not establish connection after %d attempts!", attempts));
}
/**
* Returns true if {@link #iqConnectProcess} is not <code>null</code> and is {@link Process#isAlive() alive}.
*
* @return a boolean
*/
public boolean isIQConnectRunning() {
return iqConnectProcess != null && iqConnectProcess.isAlive();
}
/**
* Sets whether to disable internal logging of the {@link #iqConnectProcess} or not. Must be called before {@link
* #start()}.
*
* @param disableInternalProcessLogging a boolean
*/
public void disableInternalProcessLogging(boolean disableInternalProcessLogging) {
this.disableInternalProcessLogging = disableInternalProcessLogging;
}
/**
* Gets {@link #iqConnectProcess}.
*
* @return a {@link Process}
*/
public Process getIQConnectProcess() {
return iqConnectProcess;
}
@Override
public String toString() {
return "IQConnectExecutable{" +
"iqConnectCommand='" + iqConnectCommand + '\'' +
", productID='" + productID + '\'' +
", applicationVersion='" + applicationVersion + '\'' +
", login='" + login + '\'' +
", password='" + password + '\'' +
", autoconnect=" + autoconnect +
", saveLoginInfo=" + saveLoginInfo +
'}';
}
}