-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJmbInstance.java
More file actions
350 lines (287 loc) · 9.95 KB
/
Copy pathJmbInstance.java
File metadata and controls
350 lines (287 loc) · 9.95 KB
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package com.ss.jme.plugin.jmb;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.ss.jme.plugin.JmeMessagesBundle;
import com.ss.jme.plugin.JmeModuleComponent;
import com.ss.jme.plugin.jmb.command.client.ClientCommand;
import com.ss.jme.plugin.jmb.command.client.InitClasspathClientCommand;
import com.ss.jme.plugin.jmb.command.server.EmptyServerCommand;
import com.ss.jme.plugin.util.JmePluginUtils;
import com.ss.rlib.common.concurrent.util.ConcurrentUtils;
import com.ss.rlib.common.concurrent.util.ThreadUtils;
import com.ss.rlib.common.network.NetworkConfig;
import com.ss.rlib.common.network.NetworkFactory;
import com.ss.rlib.common.network.client.ClientNetwork;
import com.ss.rlib.common.network.client.ConnectHandler;
import com.ss.rlib.common.network.client.server.Server;
import com.ss.rlib.common.network.packet.ReadablePacketRegistry;
import com.ss.rlib.common.util.FileUtils;
import com.ss.rlib.common.util.Utils;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The class to present an instance of jMB.
*
* @author JavaSaBr
*/
public class JmbInstance extends Thread {
@NotNull
private static final Logger LOG = Logger.getInstance("#com.ss.jme.plugin.jmb.JmbInstance");
@NotNull
private static final ReadablePacketRegistry PACKET_REGISTRY = ReadablePacketRegistry.of(EmptyServerCommand.class);
@NotNull
private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
@NotNull
private static final NetworkConfig NETWORK_CONFIG = new NetworkConfig() {
@Override
public int getReadBufferSize() {
return Short.MAX_VALUE * 2;
}
@Override
public int getWriteBufferSize() {
return Short.MAX_VALUE * 2;
}
};
/**
* The module.
*/
@NotNull
private final Module module;
/**
* The notificator.
*/
@NotNull
private final Object notificator;
/**
* The client network.
*/
@NotNull
private final ClientNetwork clientNetwork;
/**
* The process.
*/
@Nullable
private volatile Process process;
/**
* The server of jMB.
*/
@Nullable
@Getter(AccessLevel.PRIVATE)
@Setter(AccessLevel.PRIVATE)
private volatile Server server;
/**
* The last used path to jMB.
*/
@Nullable
@Getter(AccessLevel.PRIVATE)
@Setter(AccessLevel.PRIVATE)
private volatile Path lastJmbPath;
/**
* The flag of reading to work with jMB.
*/
private volatile boolean ready;
/**
* The flag about that last attempt was failed.
*/
private volatile boolean wasFailed;
public JmbInstance(@NotNull Module module) {
this.module = module;
this.notificator = new Object();
this.clientNetwork = NetworkFactory.newDefaultAsyncClientNetwork(
NETWORK_CONFIG, PACKET_REGISTRY, ConnectHandler.newDefault());
start();
}
@Override
public void run() {
LOG.debug("Started background checking thread.");
while (true) {
if (process == null) {
synchronized (notificator) {
if (process == null) {
LOG.debug("Waiting for a new jMB instance...");
ConcurrentUtils.waitInSynchronize(notificator);
}
}
}
LOG.debug("Taken the jMB process: ", process);
LOG.debug("Started waiting for finishing of the process: ", process);
try {
process.waitFor();
} catch (InterruptedException e) {
LOG.warn(e);
}
process = null;
ready = false;
setServer(null);
}
}
public void setServer(Server server) {
this.server = server;
}
/**
* Starts an instance of jMB.
*
* @param project the project which request starting an instance.
*/
private void startInstance(@NotNull Project project) {
if (ready) {
return;
}
String title = JmeMessagesBundle.message("jmb.instance.launch.title");
ProgressManager.getInstance().run(new Task.Modal(project, title, false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
startInstanceImpl();
}
});
}
/**
* Executes starting jMB.
*/
private synchronized void startInstanceImpl() {
if (ready) {
return;
}
Path pathToJmb = JmePluginUtils.getPathToJmb();
if (wasFailed && pathToJmb != null && pathToJmb.equals(getLastJmbPath())) {
SwingUtilities.invokeLater(() -> {
String message = JmeMessagesBundle.message("jme.instance.error.wasFailed.message");
String title = JmeMessagesBundle.message("jme.instance.error.wasFailed.title");
Messages.showWarningDialog(message, title);
});
return;
}
setLastJmbPath(pathToJmb);
if (pathToJmb == null) {
SwingUtilities.invokeLater(() -> {
String message = JmeMessagesBundle.message("jme.instance.error.noPath.message");
String title = JmeMessagesBundle.message("jme.instance.error.noPath.title");
Messages.showWarningDialog(message, title);
});
wasFailed = true;
return;
}
if (!JmePluginUtils.checkJmb(pathToJmb)) {
return;
}
LOG.debug("starting a new jMB instance...");
int freePort = Utils.getFreePort(5000);
LOG.debug("free port: ", freePort);
JmeModuleComponent moduleComponent = module.getComponent(JmeModuleComponent.class);
Path assetFolder = moduleComponent.getAssetFolder();
LOG.debug("asset folder: ", assetFolder);
ProcessBuilder builder;
if ("jar".equals(FileUtils.getExtension(pathToJmb))) {
Path folder = pathToJmb.getParent();
builder = new ProcessBuilder("java", "-jar", pathToJmb.toString());
builder.directory(folder.toFile());
} else {
builder = new ProcessBuilder(pathToJmb.toString());
}
Map<String, String> env = builder.environment();
env.put("Server.api.port", String.valueOf(freePort));
if (assetFolder != null) {
env.put("Editor.assetFolder", assetFolder.toString());
}
builder.inheritIO();
LOG.debug("commands: ", builder.command());
LOG.debug("env: ", env);
Process process;
try {
process = builder.start();
} catch (IOException e) {
LOG.warn(e);
SwingUtilities.invokeLater(() -> {
String message = JmeMessagesBundle.message("jme.instance.error.cantExecute.message", pathToJmb.toString());
String title = JmeMessagesBundle.message("jme.instance.error.cantExecute.title");
Messages.showWarningDialog(message, title);
});
wasFailed = true;
return;
}
Server server = getServer();
if (server != null) {
LOG.debug("destroy the previous server: ", server);
server.destroy();
}
ThreadUtils.sleep(2000);
LOG.debug("connecting to the launched instance...");
while (true) {
try {
LOG.debug("Trying to connect...");
server = clientNetwork.connect(new InetSocketAddress("localhost", freePort));
server.sendPacket(new InitClasspathClientCommand(moduleComponent.getCompileOutput(), moduleComponent.getLibraries()));
setServer(server);
break;
} catch (RuntimeException e) {
LOG.warn(e);
LOG.debug("Waiting for 1 sec.");
ThreadUtils.sleep(1000);
}
}
LOG.debug("Connected to the instance.");
this.process = process;
this.wasFailed = false;
this.ready = true;
LOG.debug("Notify background thread.");
ConcurrentUtils.notifyAll(notificator);
LOG.debug("jMB was started successfully.");
}
private void setLastJmbPath(Path pathToJmb) {
lastJmbPath = pathToJmb;
}
private Server getServer() {
return server;
}
private Path getLastJmbPath() {
return lastJmbPath;
}
/**
* Gets the server of jMB.
*
* @return the server of jMB.
*/
private @NotNull
Optional<Server> getServerOpt() {
return Optional.ofNullable(server);
}
/**
* Sends the command to jMB.
*
* @param command the command.
* @param project the project.
*/
public void sendCommand(@NotNull ClientCommand command, @NotNull Project project) {
EXECUTOR_SERVICE.execute(() -> {
startInstance(project);
getServerOpt().ifPresent(it -> it.sendPacket(command));
});
}
/**
* Sends the command to jMB if we already have running instance.
*
* @param command the command.
*/
public void sendCommandIfRunning(@NotNull ClientCommand command) {
if (!ready) return;
EXECUTOR_SERVICE.execute(() ->
getServerOpt().ifPresent(it -> it.sendPacket(command)));
}
}