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
|
'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as Path from "path";
import * as FS from "fs";
import { window, workspace, ExtensionContext, commands, tasks, Task, TaskExecution, ShellExecution, Uri, TaskDefinition, languages, IndentAction, Progress, ProgressLocation } from 'vscode';
import {LanguageClient, LanguageClientOptions, ServerOptions, NotificationType} from "vscode-languageclient";
// If we want to profile using VisualVM, we have to run the language server using regular java, not jlink
// This is intended to be used in the 'F5' debug-extension mode, where the extension is running against the actual source, not build.vsix
const visualVm = false;
/** Called when extension is activated */
export function activate(context: ExtensionContext) {
console.log('Activating Java');
// Options to control the language client
let clientOptions: LanguageClientOptions = {
// Register the server for java documents
documentSelector: ['java'],
synchronize: {
// Synchronize the setting section 'java' to the server
// NOTE: this currently doesn't do anything
configurationSection: 'java',
// Notify the server about file changes to 'javaconfig.json' files contain in the workspace
fileEvents: [
workspace.createFileSystemWatcher('**/javaconfig.json'),
workspace.createFileSystemWatcher('**/pom.xml'),
workspace.createFileSystemWatcher('**/WORKSPACE'),
workspace.createFileSystemWatcher('**/BUILD'),
workspace.createFileSystemWatcher('**/*.java')
]
},
outputChannelName: 'Java',
revealOutputChannelOn: 4 // never
}
let launcherRelativePath = platformSpecificLauncher();
let launcherPath = [context.extensionPath].concat(launcherRelativePath);
let launcher = Path.resolve(...launcherPath);
console.log(launcher);
// Start the child java process
let serverOptions: ServerOptions = {
command: launcher,
args: [],
options: { cwd: context.extensionPath }
}
if (visualVm) {
serverOptions = visualVmConfig(context);
}
// Copied from typescript
languages.setLanguageConfiguration('java', {
indentationRules: {
// ^(.*\*/)?\s*\}.*$
decreaseIndentPattern: /^((?!.*?\/\*).*\*\/)?\s*[\}\]\)].*$/,
// ^.*\{[^}"']*$
increaseIndentPattern: /^((?!\/\/).)*(\{[^}"'`]*|\([^)"'`]*|\[[^\]"'`]*)$/,
indentNextLinePattern: /^\s*(for|while|if|else)\b(?!.*[;{}]\s*(\/\/.*|\/[*].*[*]\/\s*)?$)/
},
onEnterRules: [
{
// e.g. /** | */
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: IndentAction.IndentOutdent, appendText: ' * ' }
}, {
// e.g. /** ...|
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: IndentAction.None, appendText: ' * ' }
}, {
// e.g. * ...|
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: IndentAction.None, appendText: '* ' }
}, {
// e.g. */|
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
},
{
// e.g. *-----*/|
beforeText: /^(\t|(\ \ ))*\ \*[^/]*\*\/\s*$/,
action: { indentAction: IndentAction.None, removeText: 1 }
}
]
})
// Create the language client and start the client.
let client = new LanguageClient('java', 'Java Language Server', serverOptions, clientOptions);
let disposable = client.start();
// Push the disposable to the context's subscriptions so that the
// client can be deactivated on extension deactivation
context.subscriptions.push(disposable);
// Register test commands
commands.registerCommand('java.command.test.run', runTest);
commands.registerCommand('java.command.findReferences', runFindReferences);
// When the language client activates, register a progress-listener
client.onReady().then(() => createProgressListeners(client));
}
// this method is called when your extension is deactivated
export function deactivate() {
}
function runFindReferences(uri: string, lineNumber: number, column: number) {
// LSP is 0-based but VSCode is 1-based
return commands.executeCommand('editor.action.findReferences', Uri.parse(uri), {lineNumber: lineNumber+1, column: column+1});
}
interface JavaTestTask extends TaskDefinition {
className: string
methodName: string
}
function runTest(sourceUri: string, className: string, methodName: string): Thenable<TaskExecution> {
let file = Uri.parse(sourceUri).fsPath;
file = Path.relative(workspace.rootPath, file);
let kind: JavaTestTask = {
type: 'java.task.test',
className: className,
methodName: methodName,
}
var shell;
let config = workspace.getConfiguration('java')
// Run method or class
if (methodName != null) {
let command = config.get('testMethod') as string[]
if (command.length == 0) {
window.showErrorMessage('Set "java.testMethod" in .vscode/settings.json')
shell = new ShellExecution('echo', ['Set "java.testMethod" in .vscode/settings.json, for example ["mvn", "test", "-Dtest=${class}#${method}"]'])
} else {
shell = templateCommand(command, file, className, methodName)
}
} else {
let command = config.get('testClass') as string[]
if (command.length == 0) {
window.showErrorMessage('Set "java.testClass" in .vscode/settings.json')
shell = new ShellExecution('echo', ['Set "java.testClass" in .vscode/settings.json, for example ["mvn", "test", "-Dtest=${class}"]'])
} else {
shell = templateCommand(command, file, className, methodName)
}
}
let workspaceFolder = workspace.getWorkspaceFolder(Uri.parse(sourceUri))
let task = new Task(kind, workspaceFolder, 'Java Test', 'Java Language Server', shell)
return tasks.executeTask(task)
}
function templateCommand(command: string[], file: string, className: string, methodName: string) {
// Replace template parameters
var replaced = []
for (var i = 0; i < command.length; i++) {
let c = command[i]
c = c.replace('${file}', file)
c = c.replace('${class}', className)
c = c.replace('${method}', methodName)
replaced[i] = c
}
// Populate env
let env = {...process.env} as {[key: string]: string};
return new ShellExecution(replaced[0], replaced.slice(1), {env})
}
interface ProgressMessage {
message: string
increment: number
}
function createProgressListeners(client: LanguageClient) {
// Create a "checking files" progress indicator
let progressListener = new class {
progress: Progress<{message: string, increment?: number}>
resolve: (nothing: {}) => void
startProgress(message: string) {
if (this.progress != null)
this.endProgress();
window.withProgress({title: message, location: ProgressLocation.Notification}, progress => new Promise((resolve, _reject) => {
this.progress = progress;
this.resolve = resolve;
}));
}
reportProgress(message: string, increment: number) {
if (increment == -1)
this.progress.report({message});
else
this.progress.report({message, increment})
}
endProgress() {
if (this.progress != null) {
this.resolve({});
this.progress = null;
this.resolve = null;
}
}
}
// Use custom notifications to drive progressListener
client.onNotification(new NotificationType('java/startProgress'), (event: ProgressMessage) => {
progressListener.startProgress(event.message);
});
client.onNotification(new NotificationType('java/reportProgress'), (event: ProgressMessage) => {
progressListener.reportProgress(event.message, event.increment);
});
client.onNotification(new NotificationType('java/endProgress'), () => {
progressListener.endProgress();
});
}
function platformSpecificLauncher(): string[] {
switch (process.platform) {
case 'win32':
return ['dist', 'windows', 'bin', 'launcher'];
case 'darwin':
return ['dist', 'mac', 'bin', 'launcher'];
}
throw `unsupported platform: ${process.platform}`;
}
// Alternative server options if you want to use visualvm
function visualVmConfig(context: ExtensionContext): ServerOptions {
let javaExecutablePath = findJavaExecutable('java');
if (javaExecutablePath == null) {
window.showErrorMessage("Couldn't locate java in $JAVA_HOME or $PATH");
throw "Gave up";
}
let classes = Path.resolve(context.extensionPath, "target", "classes");
let cpTxt = Path.resolve(context.extensionPath, "target", "cp.txt");
let cpContents = FS.readFileSync(cpTxt, "utf-8");
let args = [
'-cp', classes + ":" + cpContents,
'-Xverify:none', // helps VisualVM avoid 'error 62'
'-Xdebug',
// '-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005',
'org.javacs.Main'
];
console.log(javaExecutablePath + ' ' + args.join(' '));
// Start the child java process
return {
command: javaExecutablePath,
args: args,
options: { cwd: context.extensionPath }
}
}
function findJavaExecutable(binname: string) {
binname = correctBinname(binname);
// First search java.home setting
let userJavaHome = workspace.getConfiguration('java').get('home') as string;
if (userJavaHome != null) {
console.log('Looking for java in settings java.home ' + userJavaHome + '...');
let candidate = findJavaExecutableInJavaHome(userJavaHome, binname);
if (candidate != null)
return candidate;
}
// Then search each JAVA_HOME
let envJavaHome = process.env['JAVA_HOME'];
if (envJavaHome) {
console.log('Looking for java in environment variable JAVA_HOME ' + envJavaHome + '...');
let candidate = findJavaExecutableInJavaHome(envJavaHome, binname);
if (candidate != null)
return candidate;
}
// Then search PATH parts
if (process.env['PATH']) {
console.log('Looking for java in PATH');
let pathparts = process.env['PATH'].split(Path.delimiter);
for (let i = 0; i < pathparts.length; i++) {
let binpath = Path.join(pathparts[i], binname);
if (FS.existsSync(binpath)) {
return binpath;
}
}
}
// Else return the binary name directly (this will likely always fail downstream)
return null;
}
function correctBinname(binname: string) {
if (process.platform === 'win32')
return binname + '.exe';
else
return binname;
}
function findJavaExecutableInJavaHome(javaHome: string, binname: string) {
let workspaces = javaHome.split(Path.delimiter);
for (let i = 0; i < workspaces.length; i++) {
let binpath = Path.join(workspaces[i], 'bin', binname);
if (FS.existsSync(binpath))
return binpath;
}
return null;
}
|