-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathextension.ts
More file actions
2159 lines (2005 loc) · 95.9 KB
/
extension.ts
File metadata and controls
2159 lines (2005 loc) · 95.9 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict';
import { commands, window, workspace, ExtensionContext, ProgressLocation, TextEditorDecorationType } from 'vscode';
import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
StreamInfo
} from 'vscode-languageclient/node';
import {
CloseAction,
ErrorAction,
Message,
MessageType,
LogMessageNotification,
RevealOutputChannelOn,
DocumentSelector,
ErrorHandlerResult,
CloseHandlerResult,
SymbolInformation,
TextDocumentFilter,
TelemetryEventNotification
} from 'vscode-languageclient';
import * as net from 'net';
import * as fs from 'fs';
import * as path from 'path';
import { spawnSync, ChildProcess } from 'child_process';
import * as vscode from 'vscode';
import * as ls from 'vscode-languageserver-protocol';
import * as launcher from './nbcode';
import {NbTestAdapter} from './testAdapter';
import { asRanges, StatusMessageRequest, ShowStatusMessageParams, QuickPickRequest, InputBoxRequest, MutliStepInputRequest, TestProgressNotification, DebugConnector,
TextEditorDecorationCreateRequest, TextEditorDecorationSetNotification, TextEditorDecorationDisposeNotification, HtmlPageRequest, HtmlPageParams,
ExecInHtmlPageRequest, SetTextEditorDecorationParams, ProjectActionParams, UpdateConfigurationRequest, QuickPickStep, InputBoxStep, SaveDocumentsRequest, SaveDocumentRequestParams, OutputMessage, WriteOutputRequest, ShowOutputRequest, CloseOutputRequest, ResetOutputRequest
} from './protocol';
import * as launchConfigurations from './launchConfigurations';
import { createTreeViewService, TreeViewService, TreeItemDecorator, Visualizer, CustomizableTreeDataProvider } from './explorer';
import { initializeRunConfiguration, runConfigurationProvider, runConfigurationNodeProvider, configureRunSettings, runConfigurationUpdateAll } from './runConfiguration';
import { dBConfigurationProvider, onDidTerminateSession } from './dbConfigurationProvider';
import { InputStep, MultiStepInput } from './utils';
import { PropertiesView } from './propertiesView/propertiesView';
import * as configuration from './jdk/configuration';
import * as jdk from './jdk/jdk';
import { validateJDKCompatibility } from './jdk/validation/validation';
import * as sshGuide from './panels/SshGuidePanel';
import * as runImageGuide from './panels/RunImageGuidePanel';
import { shouldHideGuideFor } from './panels/guidesUtil';
import { SSHSession } from './ssh/ssh';
import { env } from 'process';
const API_VERSION : string = "1.0";
export const COMMAND_PREFIX : string = "nbls";
const DATABASE: string = 'Database';
export const listeners = new Map<string, string[]>();
export let client: Promise<NbLanguageClient>;
export let clientRuntimeJDK : string | null = null;
export const MINIMAL_JDK_VERSION = 17;
export const TEST_PROGRESS_EVENT: string = "testProgress";
const TEST_ADAPTER_CREATED_EVENT: string = "testAdapterCreated";
let testAdapter: NbTestAdapter | undefined;
let nbProcess : ChildProcess | null = null;
let debugPort: number = -1;
let consoleLog: boolean = !!process.env['ENABLE_CONSOLE_LOG'];
let specifiedJDKWarned : string[] = [];
type DebugConsoleListener = {
callback: (output: string) => void;
}
export let debugConsoleListeners: DebugConsoleListener[] = [];
export class NbLanguageClient extends LanguageClient {
private _treeViewService: TreeViewService;
constructor (id : string, name: string, s : ServerOptions, log : vscode.OutputChannel, c : LanguageClientOptions) {
super(id, name, s, c);
this._treeViewService = createTreeViewService(log, this);
}
findTreeViewService(): TreeViewService {
return this._treeViewService;
}
stop(): Promise<void> {
// stop will be called even in case of external close & client restart, so OK.
const r: Promise<void> = super.stop();
this._treeViewService.dispose();
return r;
}
}
function handleLog(log: vscode.OutputChannel, msg: string): void {
log.appendLine(msg);
if (consoleLog) {
console.log(msg);
}
}
function handleLogNoNL(log: vscode.OutputChannel, msg: string): void {
log.append(msg);
if (consoleLog) {
process.stdout.write(msg);
}
}
export function clearDebugConsoleListeners() {
debugConsoleListeners = [];
}
export function enableConsoleLog() {
consoleLog = true;
console.log("enableConsoleLog");
}
export function findClusters(myPath : string, log: vscode.OutputChannel): string[] {
let clusters: string[] = [];
for (let e of vscode.extensions.all) {
if (e.extensionPath === myPath) {
continue;
}
const dir = path.join(e.extensionPath, 'nbcode');
searchAddCluster(dir);
}
return clusters;
function searchAddCluster(rootWithClusters: string) {
if (fs.existsSync(rootWithClusters)) {
const exists = fs.readdirSync(rootWithClusters);
for (let clusterName of exists) {
let clusterPath = path.join(rootWithClusters, clusterName);
addCluster(clusterPath);
}
}
}
function addCluster(clusterPath: string): boolean {
let clusterModules = path.join(clusterPath, 'config', 'Modules');
if (fs.existsSync(clusterModules)) {
let perm = fs.statSync(clusterModules);
if (perm.isDirectory()) {
clusters.push(clusterPath);
return true;
}
}
return false;
}
}
// for tests only !
export function awaitClient() : Promise<NbLanguageClient> {
const c : Promise<NbLanguageClient> = client;
if (c && !(c instanceof InitialPromise)) {
return c;
}
let nbcode = vscode.extensions.getExtension('asf.apache-netbeans-java');
if (!nbcode) {
return Promise.reject(new Error("Extension not installed."));
}
const t : Thenable<NbLanguageClient> = nbcode.activate().then(nc => {
if (client === undefined || client instanceof InitialPromise) {
throw new Error("Client not available");
} else {
return client;
}
});
return Promise.resolve(t);
}
function findJDK(onChange: (path : string | null) => void): void {
let nowDark : boolean = isDarkColorTheme();
let nowJavaEnabled : boolean = isJavaSupportEnabled();
function find(): string | null {
let nbJdk = workspace.getConfiguration('netbeans').get('jdkhome');
if (nbJdk) {
return nbJdk as string;
}
let javahome = workspace.getConfiguration('java').get('home');
if (javahome) {
return javahome as string;
}
let jdkHome: any = process.env.JDK_HOME;
if (jdkHome) {
return jdkHome as string;
}
let jHome: any = process.env.JAVA_HOME;
if (jHome) {
return jHome as string;
}
return null;
}
let currentJdk = find();
let projectJdk : string | undefined = getProjectJDKHome();
validateJDKCompatibility(projectJdk);
let timeout: NodeJS.Timeout | undefined = undefined;
workspace.onDidChangeConfiguration(params => {
if (timeout) {
return;
}
let interested : boolean = false;
if (params.affectsConfiguration('netbeans') || params.affectsConfiguration('java')) {
interested = true;
} else if (params.affectsConfiguration('workbench.colorTheme')) {
let d = isDarkColorTheme();
if (d != nowDark) {
interested = true;
}
}
if (!interested) {
return;
}
timeout = setTimeout(() => {
timeout = undefined;
let newJdk = find();
let newD = isDarkColorTheme();
let newJavaEnabled = isJavaSupportEnabled();
let newProjectJDK : string | undefined = getProjectJDKHome();
if (newJdk !== currentJdk || newD != nowDark || newJavaEnabled != nowJavaEnabled || newProjectJDK != projectJdk) {
nowDark = newD;
nowJavaEnabled = newJavaEnabled;
currentJdk = newJdk;
projectJdk = newProjectJDK;
onChange(currentJdk);
}
}, 0);
});
onChange(currentJdk);
}
interface VSNetBeansAPI {
version : string;
apiVersion: string;
}
function contextUri(ctx : any) : vscode.Uri | undefined {
if (ctx?.fsPath) {
return ctx as vscode.Uri;
} else if (ctx?.resourceUri) {
return ctx.resourceUri as vscode.Uri;
} else if (typeof ctx == 'string') {
try {
return vscode.Uri.parse(ctx, true);
} catch (err) {
return vscode.Uri.file(ctx);
}
}
return vscode.window.activeTextEditor?.document?.uri;
}
/**
* Executes a project action. It is possible to provide an explicit configuration to use (or undefined), display output from the action etc.
* Arguments are attempted to parse as file or editor references or Nodes; otherwise they are attempted to be passed to the action as objects.
*
* @param action ID of the project action to run
* @param configuration configuration to use or undefined - use default/active one.
* @param title Title for the progress displayed in vscode
* @param log output channel that should be revealed
* @param showOutput if true, reveals the passed output channel
* @param args additional arguments
* @returns Promise for the command's result
*/
function wrapProjectActionWithProgress(action : string, configuration : string | undefined, title : string, log? : vscode.OutputChannel, showOutput? : boolean, ...args : any[]) : Thenable<unknown> {
let items = [];
let actionParams = {
action : action,
configuration : configuration,
} as ProjectActionParams;
for (let item of args) {
let u : vscode.Uri | undefined;
if (item?.fsPath) {
items.push((item.fsPath as vscode.Uri).toString());
} else if (item?.resourceUri) {
items.push((item.resourceUri as vscode.Uri).toString());
} else {
items.push(item);
}
}
return wrapCommandWithProgress(COMMAND_PREFIX + '.project.run.action', title, log, showOutput, actionParams, ...items);
}
function wrapCommandWithProgress(lsCommand : string, title : string, log? : vscode.OutputChannel, showOutput? : boolean, ...args : any[]) : Thenable<unknown> {
return window.withProgress({ location: ProgressLocation.Window }, p => {
return new Promise(async (resolve, reject) => {
let c : LanguageClient = await client;
const docsTosave : Thenable<boolean>[]= vscode.workspace.textDocuments.
filter(d => fs.existsSync(d.uri.fsPath)).
map(d => d.save());
await Promise.all(docsTosave);
const commands = await vscode.commands.getCommands();
if (commands.includes(lsCommand)) {
p.report({ message: title });
c.outputChannel.show(true);
const start = new Date().getTime();
try {
if (log) {
handleLog(log, `starting ${lsCommand}`);
}
const res = await vscode.commands.executeCommand(lsCommand, ...args)
const elapsed = new Date().getTime() - start;
if (log) {
handleLog(log, `finished ${lsCommand} in ${elapsed} ms with result ${res}`);
}
const humanVisibleDelay = elapsed < 1000 ? 1000 : 0;
setTimeout(() => { // set a timeout so user would still see the message when build time is short
if (res) {
resolve(res);
} else {
if (log) {
handleLog(log, `Command ${lsCommand} takes too long to start`);
}
reject(res);
}
}, humanVisibleDelay);
} catch (err : any) {
if (log) {
handleLog(log, `command ${lsCommand} executed with error: ${JSON.stringify(err)}`);
}
reject(err && typeof err.message === 'string' ? err.message : "Error");
}
} else {
reject(`cannot run ${lsCommand}; client is ${c}`);
}
});
});
}
/**
* Just a simple promise subclass, so I can test for the 'initial promise' value:
* unlike all other promises, that must be fullfilled in order to e.g. properly stop the server or otherwise communicate with it,
* the initial one needs to be largely ignored in the launching/mgmt code, BUT should be available to normal commands / features.
*/
class InitialPromise extends Promise<NbLanguageClient> {
constructor(f : (resolve: (value: NbLanguageClient | PromiseLike<NbLanguageClient>) => void, reject: (reason?: any) => void) => void) {
super(f);
}
}
/**
* Determines the outcome, if there's a conflict betwee RH Java and us: disable java, enable java, ask the user.
* @returns false, if java should be disablde; true, if enabled. Undefined if no config is present, ask the user
*/
function shouldEnableConflictingJavaSupport() : boolean | undefined {
// backwards compatibility; remove in NBLS 19
if (vscode.extensions.getExtension('oracle-labs-graalvm.gcn')) {
return false;
}
let r = undefined;
for (const ext of vscode.extensions.all) {
const services = ext.packageJSON?.contributes && ext.packageJSON?.contributes['netbeans.options'];
if (!services) {
continue;
}
if (services['javaSupport.conflict'] !== undefined) {
const v = !!services['javaSupport.conflict'];
if (!v) {
// request to disable wins.
return false;
}
r = v;
}
}
return r;
}
function getValueAfterPrefix(input: string | undefined, prefix: string): string {
if (input === undefined) {
return "";
}
const parts = input.split(' ');
for (let i = 0; i < parts.length; i++) {
if (parts[i].startsWith(prefix)) {
return parts[i].substring(prefix.length);
}
}
return '';
}
class LineBufferingPseudoterminal implements vscode.Pseudoterminal {
private static instances = new Map<string, LineBufferingPseudoterminal>();
private writeEmitter = new vscode.EventEmitter<string>();
onDidWrite: vscode.Event<string> = this.writeEmitter.event;
private closeEmitter = new vscode.EventEmitter<void>();
onDidClose?: vscode.Event<void> = this.closeEmitter.event;
private buffer: string = '';
private isOpen = false;
private readonly name: string;
private terminal: vscode.Terminal | undefined;
private constructor(name: string) {
this.name = name;
}
open(): void {
this.isOpen = true;
}
close(): void {
this.isOpen = false;
this.closeEmitter.fire();
}
/**
* Accepts partial input strings and logs complete lines when they are formed.
* Also processes carriage returns (\r) to overwrite the current line.
* @param input The string input to the pseudoterminal.
*/
public acceptInput(input: string): void {
if (!this.isOpen) {
return;
}
for (const char of input) {
if (char === '\n') {
// Process a newline: log the current buffer and reset it
this.logLine(this.buffer.trim());
this.buffer = '';
} else if (char === '\r') {
// Process a carriage return: log the current buffer on the same line
this.logInline(this.buffer.trim());
this.buffer = '';
} else {
// Append characters to the buffer
this.buffer += char;
}
}
}
private logLine(line: string): void {
console.log('[Gradle Debug]', line.toString());
this.writeEmitter.fire(`${line}\r\n`);
}
private logInline(line: string): void {
// Clear the current line and move the cursor to the start
this.writeEmitter.fire(`\x1b[2K\x1b[1G${line}`);
}
public flushBuffer(): void {
if (this.buffer.trim().length > 0) {
this.logLine(this.buffer.trim());
this.buffer = '';
}
}
public clear(): void {
this.writeEmitter.fire('\x1b[2J\x1b[3J\x1b[H'); // Clear screen and move cursor to top-left
}
public show(): void {
if (!this.terminal) {
this.terminal = vscode.window.createTerminal({
name: this.name,
pty: this,
});
// Listen for terminal close events
vscode.window.onDidCloseTerminal((closedTerminal) => {
if (closedTerminal === this.terminal) {
this.terminal = undefined; // Clear the terminal reference
}
});
}
// Prevent 'stealing' of the focus when running tests in parallel
if (!testAdapter?.testInParallelProfileExist()) {
this.terminal.show(true);
}
}
/**
* Gets an existing instance or creates a new one by the terminal name.
* The terminal is also created and managed internally.
* @param name The name of the pseudoterminal.
* @returns The instance of the pseudoterminal.
*/
public static getInstance(name: string): LineBufferingPseudoterminal {
if (!this.instances.has(name)) {
const instance = new LineBufferingPseudoterminal(name);
this.instances.set(name, instance);
}
const instance = this.instances.get(name)!;
instance.show();
return instance;
}
}
export function activate(context: ExtensionContext): VSNetBeansAPI {
const provider = new StringContentProvider();
const scheme = 'in-memory';
const providerRegistration = vscode.workspace.registerTextDocumentContentProvider(scheme, provider);
context.subscriptions.push(vscode.commands.registerCommand('cloud.assets.policy.create', async function (viewItem) {
const POLICIES_PREVIEW = 'Open a preview of the OCI policies';
const POLICIES_UPLOAD = 'Upload the OCI Policies to OCI';
const selected: any = await window.showQuickPick([POLICIES_PREVIEW, POLICIES_UPLOAD], { placeHolder: 'Select a target for the OCI policies' });
if (selected == POLICIES_UPLOAD) {
await vscode.commands.executeCommand('nbls.cloud.assets.policy.upload');
return;
}
const content = await vscode.commands.executeCommand('nbls.cloud.assets.policy.create.local') as string;
const document = vscode.Uri.parse(`${scheme}:policies.txt?${encodeURIComponent(content)}`);
vscode.workspace.openTextDocument(document).then(doc => {
vscode.window.showTextDocument(doc, { preview: false });
});
})
);
context.subscriptions.push(vscode.commands.registerCommand('cloud.assets.config.create', async function (viewItem) {
const CONFIG_LOCAL = 'Open a preview of the config in the editor';
const CONFIG_TO_DEVOPS_CM = 'Upload the config to a ConfigMap artifact whithin an OCI DevOps Project';
const CONFIG_TO_OKE_CM = 'Upload the config to a ConfigMap artifact whithin OKE cluster';
const selected: any = await window.showQuickPick([CONFIG_LOCAL, CONFIG_TO_OKE_CM, CONFIG_TO_DEVOPS_CM], { placeHolder: 'Select a target for the config' });
if (selected == CONFIG_TO_DEVOPS_CM) {
await commands.executeCommand('nbls.cloud.assets.configmap.devops.upload');
return;
} else if (selected == CONFIG_TO_OKE_CM) {
await commands.executeCommand('nbls.cloud.assets.configmap.upload');
return;
}
const content = await vscode.commands.executeCommand('nbls.cloud.assets.config.create.local') as string;
const document = vscode.Uri.parse(`${scheme}:application.properties?${encodeURIComponent(content)}`);
vscode.workspace.openTextDocument(document).then(doc => {
vscode.window.showTextDocument(doc, { preview: false });
});
})
);
let log = vscode.window.createOutputChannel("Apache NetBeans Language Server");
var clientResolve : (x : NbLanguageClient) => void;
var clientReject : (err : any) => void;
// establish a waitable Promise, export the callbacks so they can be called after activation.
client = new InitialPromise((resolve, reject) => {
clientResolve = resolve;
clientReject = reject;
});
// we need to call refresh here as @OnStart in NBLS is called before the workspace projects are opened.
client.then(() => {
vscode.commands.executeCommand('nbls.cloud.assets.refresh');
});
function checkConflict(): void {
let conf = workspace.getConfiguration();
if (conf.get("netbeans.conflict.check")) {
if (conf.get("netbeans.javaSupport.enabled")) {
const e : boolean | undefined = shouldEnableConflictingJavaSupport();
if (!e && vscode.extensions.getExtension('redhat.java')) {
if (e === false) {
// do not ask, an extension wants us to disable on conflict
conf.update("netbeans.javaSupport.enabled", false, true);
} else {
const DISABLE_EXTENSION = `Manually disable extension`;
const DISABLE_JAVA = `Disable Java in Apache NetBeans Language Server`;
vscode.window.showInformationMessage(`Another Java support extension is already installed. It is recommended to use only one Java support per workspace.`, DISABLE_EXTENSION, DISABLE_JAVA).then((selected) => {
if (DISABLE_EXTENSION === selected) {
vscode.commands.executeCommand('workbench.extensions.action.showInstalledExtensions');
} else if (DISABLE_JAVA === selected) {
conf.update("netbeans.javaSupport.enabled", false, true);
}
});
}
}
} else if (!vscode.extensions.getExtension('redhat.java')) {
workspace.findFiles(`**/*.java`, undefined, 1).then(files => {
if (files.length) {
const ENABLE_JAVA = `Enable Java in Apache NetBeans Language Server`;
vscode.window.showInformationMessage(`Java in Apache NetBeans Language Server is disabled and no other Java support extension is currently installed.`, ENABLE_JAVA).then((selected) => {
if (ENABLE_JAVA === selected) {
conf.update("netbeans.javaSupport.enabled", true, true);
}
});
}
});
}
}
}
checkConflict();
// find acceptable JDK and launch the Java part
findJDK(async (specifiedJDK) => {
const osExeSuffix = process.platform === 'win32' ? '.exe' : '';
let jdkOK : boolean = true;
let javaExecPath : string;
if (!specifiedJDK) {
javaExecPath = 'java';
} else {
javaExecPath = path.resolve(specifiedJDK, 'bin', 'java');
jdkOK = fs.existsSync(path.resolve(specifiedJDK, 'bin', `java${osExeSuffix}`)) && fs.existsSync(path.resolve(specifiedJDK, 'bin', `javac${osExeSuffix}`));
}
if (jdkOK) {
log.appendLine(`Verifying java: ${javaExecPath}`);
// let the shell interpret PATH and .exe extension
let javaCheck = spawnSync(`"${javaExecPath}" -version`, { shell : true });
if (javaCheck.error || javaCheck.status) {
jdkOK = false;
} else {
javaCheck.stderr.toString().split('\n').find(l => {
// yes, versions like 1.8 (up to 9) will be interpreted as 1, which is OK for < comparison
let re = /.* version \"([0-9]+)\.[^"]+\".*/.exec(l);
if (re) {
let versionNumber = Number(re[1]);
if (versionNumber < MINIMAL_JDK_VERSION) {
jdkOK = false;
}
}
});
}
}
let warnedJDKs : string[] = specifiedJDKWarned;
if (!jdkOK && !warnedJDKs.includes(specifiedJDK || '')) {
const msg = specifiedJDK ?
`The current path to JDK "${specifiedJDK}" may be invalid. A valid JDK ${MINIMAL_JDK_VERSION}+ is required by Apache NetBeans Language Server to run.
You should configure a proper JDK for Apache NetBeans and/or other technologies. Do you want to run JDK configuration now?` :
`A valid JDK ${MINIMAL_JDK_VERSION}+ is required by Apache NetBeans Language Server to run, but none was found. You should configure a proper JDK for Apache NetBeans and/or other technologies. ` +
'Do you want to run JDK configuration now?';
const Y = "Yes";
const N = "No";
if (await vscode.window.showErrorMessage(msg, Y, N) == Y) {
vscode.commands.executeCommand('nbls.jdk.configuration');
return;
} else {
warnedJDKs.push(specifiedJDK || '');
}
}
let currentClusters = findClusters(context.extensionPath, log).sort();
const dsSorter = (a: TextDocumentFilter, b: TextDocumentFilter) => {
return (a.language || '').localeCompare(b.language || '')
|| (a.pattern || '').localeCompare(b.pattern || '')
|| (a.scheme || '').localeCompare(b.scheme || '');
};
let currentDocumentSelectors = collectDocumentSelectors().sort(dsSorter);
context.subscriptions.push(vscode.extensions.onDidChange(() => {
checkConflict();
const newClusters = findClusters(context.extensionPath, log).sort();
const newDocumentSelectors = collectDocumentSelectors().sort(dsSorter);
if (newClusters.length !== currentClusters.length || newDocumentSelectors.length !== currentDocumentSelectors.length
|| newClusters.find((value, index) => value !== currentClusters[index]) || newDocumentSelectors.find((value, index) => value !== currentDocumentSelectors[index])) {
currentClusters = newClusters;
currentDocumentSelectors = newDocumentSelectors;
activateWithJDK(specifiedJDK, context, log, true, clientResolve, clientReject);
}
}));
activateWithJDK(specifiedJDK, context, log, true, clientResolve, clientReject);
});
//register debugger:
let debugTrackerFactory =new NetBeansDebugAdapterTrackerFactory();
context.subscriptions.push(vscode.debug.registerDebugAdapterTrackerFactory('java+', debugTrackerFactory));
let configInitialProvider = new NetBeansConfigurationInitialProvider();
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java+', configInitialProvider, vscode.DebugConfigurationProviderTriggerKind.Initial));
let configDynamicProvider = new NetBeansConfigurationDynamicProvider(context);
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java+', configDynamicProvider, vscode.DebugConfigurationProviderTriggerKind.Dynamic));
let configResolver = new NetBeansConfigurationResolver();
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java+', configResolver));
let configNativeResolver = new NetBeansConfigurationNativeResolver();
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('nativeimage', configNativeResolver));
context.subscriptions.push(vscode.debug.onDidTerminateDebugSession(((session) => onDidTerminateSession(session))));
let debugDescriptionFactory = new NetBeansDebugAdapterDescriptionFactory();
context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory('java+', debugDescriptionFactory));
context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory('nativeimage', debugDescriptionFactory));
// initialize Run Configuration
initializeRunConfiguration().then(initialized => {
if (initialized) {
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java+', dBConfigurationProvider));
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java', dBConfigurationProvider));
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java+', runConfigurationProvider));
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('java', runConfigurationProvider));
context.subscriptions.push(vscode.window.registerTreeDataProvider('run-config', runConfigurationNodeProvider));
context.subscriptions.push(vscode.commands.registerCommand(COMMAND_PREFIX + '.workspace.configureRunSettings', (...params: any[]) => {
configureRunSettings(context, params);
}));
vscode.commands.executeCommand('setContext', 'runConfigurationInitialized', true);
}
});
// register commands
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.workspace.new', async (ctx, template) => {
let c : LanguageClient = await client;
const commands = await vscode.commands.getCommands();
if (commands.includes(COMMAND_PREFIX + '.new.from.template')) {
// first give the template (if present), then the context, and then the open-file hint in the case the context is not specific enough
const params = [];
if (typeof template === 'string') {
params.push(template);
}
params.push(contextUri(ctx)?.toString(), vscode.window.activeTextEditor?.document?.uri?.toString());
const res = await vscode.commands.executeCommand(COMMAND_PREFIX + '.new.from.template', ...params);
if (typeof res === 'string') {
let newFile = vscode.Uri.parse(res as string);
await vscode.window.showTextDocument(newFile, { preview: false });
} else if (Array.isArray(res)) {
for(let r of res) {
if (typeof r === 'string') {
let newFile = vscode.Uri.parse(r as string);
await vscode.window.showTextDocument(newFile, { preview: false });
}
}
}
} else {
throw `Client ${c} doesn't support new from template`;
}
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.workspace.newproject', async (ctx) => {
let c : LanguageClient = await client;
const commands = await vscode.commands.getCommands();
if (commands.includes(COMMAND_PREFIX + '.new.project')) {
const res = await vscode.commands.executeCommand(COMMAND_PREFIX + '.new.project', contextUri(ctx)?.toString());
if (typeof res === 'string') {
let newProject = vscode.Uri.parse(res as string);
const OPEN_IN_NEW_WINDOW = 'Open in new window';
const ADD_TO_CURRENT_WORKSPACE = 'Add to current workspace';
const value = await vscode.window.showInformationMessage('New project created', OPEN_IN_NEW_WINDOW, ADD_TO_CURRENT_WORKSPACE);
if (value === OPEN_IN_NEW_WINDOW) {
await vscode.commands.executeCommand('vscode.openFolder', newProject, true);
} else if (value === ADD_TO_CURRENT_WORKSPACE) {
vscode.workspace.updateWorkspaceFolders(vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders.length : 0, undefined, { uri: newProject });
}
}
} else {
throw `Client ${c} doesn't support new project`;
}
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.open.test', async (ctx) => {
let c: LanguageClient = await client;
const commands = await vscode.commands.getCommands();
if (commands.includes(COMMAND_PREFIX + '.go.to.test')) {
try {
const res: any = await vscode.commands.executeCommand(COMMAND_PREFIX + '.go.to.test', contextUri(ctx)?.toString());
if("errorMessage" in res){
throw new Error(res.errorMessage);
}
res?.providerErrors?.map((error: any) => {
if(error?.message){
vscode.window.showErrorMessage(error.message);
}
});
if (res?.locations?.length) {
if (res.locations.length === 1) {
const { file, offset } = res.locations[0];
const filePath = vscode.Uri.parse(file);
const editor = await vscode.window.showTextDocument(filePath, { preview: false });
if (offset != -1) {
const pos: vscode.Position = editor.document.positionAt(offset);
editor.selections = [new vscode.Selection(pos, pos)];
const range = new vscode.Range(pos, pos);
editor.revealRange(range);
}
} else {
const namePathMapping: { [key: string]: string } = {}
res.locations.forEach((fp:any) => {
const fileName = path.basename(fp.file);
namePathMapping[fileName] = fp.file
});
const selected = await window.showQuickPick(Object.keys(namePathMapping), {
title: 'Select files to open',
placeHolder: 'Test files or source files associated to each other',
canPickMany: true
});
if (selected) {
for await (const filePath of selected) {
let file = vscode.Uri.parse(filePath);
await vscode.window.showTextDocument(file, { preview: false });
}
} else {
vscode.window.showInformationMessage("No file selected");
}
}
}
} catch (err:any) {
vscode.window.showInformationMessage(err?.message || "No Test or Tested class found");
}
} else {
throw `Client ${c} doesn't support go to test`;
}
}));
const trackerFactory: vscode.DebugAdapterTrackerFactory = {
createDebugAdapterTracker(_session: vscode.DebugSession) {
return {
onDidSendMessage: (message) => {
if (message.type === "event" && message.event === "output") {
const output = message.body.output;
debugConsoleListeners.forEach((listener) => {
listener?.callback(output);
});
}
}
};
}
};
context.subscriptions.push(vscode.debug.registerDebugAdapterTrackerFactory("*", trackerFactory));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.workspace.compile', () =>
wrapCommandWithProgress(COMMAND_PREFIX + '.build.workspace', 'Compiling workspace...', log, true)
));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.workspace.clean', () =>
wrapCommandWithProgress(COMMAND_PREFIX + '.clean.workspace', 'Cleaning workspace...', log, true)
));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.project.compile', (args) => {
wrapProjectActionWithProgress('build', undefined, 'Compiling...', log, true, args);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.project.clean', (args) => {
wrapProjectActionWithProgress('clean', undefined, 'Cleaning...', log, true, args);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.project.buildPushImage', () => {
wrapCommandWithProgress(COMMAND_PREFIX + '.cloud.assets.buildPushImage', 'Building and pushing container image', log, true);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.open.type', () => {
wrapCommandWithProgress(COMMAND_PREFIX + '.quick.open', 'Opening type...', log, true).then(() => {
commands.executeCommand('workbench.action.focusActiveEditorGroup');
});
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.java.goto.super.implementation', async () => {
if (window.activeTextEditor?.document.languageId !== "java") {
return;
}
const uri = window.activeTextEditor.document.uri;
const position = window.activeTextEditor.selection.active;
const locations: any[] = await vscode.commands.executeCommand(COMMAND_PREFIX + '.java.super.implementation', uri.toString(), position) || [];
return vscode.commands.executeCommand('editor.action.goToLocations', window.activeTextEditor.document.uri, position,
locations.map(location => new vscode.Location(vscode.Uri.parse(location.uri), new vscode.Range(location.range.start.line, location.range.start.character, location.range.end.line, location.range.end.character))),
'peek', 'No super implementation found');
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.rename.element.at', async (offset) => {
const editor = window.activeTextEditor;
if (editor) {
await commands.executeCommand('editor.action.rename', [
editor.document.uri,
editor.document.positionAt(offset),
]);
}
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.surround.with', async (items) => {
const selected: any = await window.showQuickPick(items, { placeHolder: 'Surround with ...' });
if (selected) {
if (selected.userData.edit) {
const edit = await (await client).protocol2CodeConverter.asWorkspaceEdit(selected.userData.edit as ls.WorkspaceEdit);
await workspace.applyEdit(edit);
await commands.executeCommand('workbench.action.focusActiveEditorGroup');
}
await commands.executeCommand(selected.userData.command.command, ...(selected.userData.command.arguments || []));
}
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.db.add.all.connection', async () => {
const ADD_JDBC = 'Add Database Connection';
const ADD_ADB = 'Add Oracle Autonomous DB';
const selected: any = await window.showQuickPick([ADD_JDBC, ADD_ADB], { placeHolder: 'Select type...' });
if (selected == ADD_JDBC) {
await commands.executeCommand('nbls.db.add.connection');
} else if (selected == ADD_ADB) {
await commands.executeCommand('nbls:Tools:org.netbeans.modules.cloud.oracle.actions.AddADBAction');
}
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.generate.code', async (command, data) => {
const edit: any = await commands.executeCommand(command, data);
if (edit) {
const wsEdit = await (await client).protocol2CodeConverter.asWorkspaceEdit(edit as ls.WorkspaceEdit);
await workspace.applyEdit(wsEdit);
for (const entry of wsEdit.entries()) {
const file = vscode.Uri.parse(entry[0].fsPath);
await vscode.window.showTextDocument(file, { preview: false });
}
await commands.executeCommand('workbench.action.focusActiveEditorGroup');
}
}));
async function findRunConfiguration(uri : vscode.Uri) : Promise<vscode.DebugConfiguration|undefined> {
// do not invoke debug start with no (java+) configurations, as it would probably create an user prompt
let cfg = vscode.workspace.getConfiguration("launch");
let c = cfg.get('configurations');
if (!Array.isArray(c)) {
return undefined;
}
let f = c.filter((v) => v['type'] === 'java+');
if (!f.length) {
return undefined;
}
class P implements vscode.DebugConfigurationProvider {
config : vscode.DebugConfiguration | undefined;
resolveDebugConfigurationWithSubstitutedVariables(folder: vscode.WorkspaceFolder | undefined, debugConfiguration: vscode.DebugConfiguration, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration> {
this.config = debugConfiguration;
return undefined;
}
}
let provider = new P();
let d = vscode.debug.registerDebugConfigurationProvider('java+', provider);
// let vscode to select a debug config
return await vscode.commands.executeCommand('workbench.action.debug.start', { config: {
type: 'java+',
mainClass: uri.toString()
}, noDebug: true}).then((v) => {
d.dispose();
return provider.config;
}, (err) => {
d.dispose();
return undefined;
});
}
const runDebug = async (noDebug: boolean, testRun: boolean, uri: any, methodName?: string, nestedClass?: string, launchConfiguration?: string, project : boolean = false, testInParallel : boolean = false, projects: string[] | undefined = undefined) => {
const docUri = contextUri(uri);
if (docUri) {
// attempt to find the active configuration in the vsode launch settings; undefined if no config is there.
let debugConfig : vscode.DebugConfiguration = await findRunConfiguration(docUri) || {
type: "java+",
name: "Java Single Debug",
request: "launch"
};
if (methodName) {
debugConfig['methodName'] = methodName;
}
if (nestedClass) {
debugConfig['nestedClass'] = nestedClass;
}
if (launchConfiguration == '') {
if (debugConfig['launchConfiguration']) {
delete debugConfig['launchConfiguration'];
}
} else {
debugConfig['launchConfiguration'] = launchConfiguration;
}
debugConfig['noDebug'] = noDebug;
debugConfig['testRun'] = testRun;
const workspaceFolder = vscode.workspace.getWorkspaceFolder(docUri);
if (project) {
debugConfig['projectFile'] = docUri.toString();
debugConfig['project'] = true;
} else {
debugConfig['mainClass'] = docUri.toString();
}
if (testInParallel) {
debugConfig['testInParallel'] = testInParallel;
}
if (projects?.length) {
debugConfig['projects'] = projects;
}
const ret = await vscode.debug.startDebugging(workspaceFolder, debugConfig);
return ret ? new Promise((resolve) => {
const listener = vscode.debug.onDidTerminateDebugSession(() => {
listener.dispose();
resolve(true);
});
}) : ret;
}
};
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.run.test.parallel', async (projects?) => {
testAdapter?.runTestsWithParallelProfile(projects);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.run.test.parallel.createProfile', async (projects?) => {
testAdapter?.registerRunInParallelProfile(projects);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.run.test', async (uri, methodName?, launchConfiguration?, nestedClass?, testInParallel?, projects?) => {
await runDebug(true, true, uri, methodName, nestedClass, launchConfiguration, false, testInParallel, projects);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.debug.test', async (uri, methodName?, launchConfiguration?, nestedClass?) => {
await runDebug(false, true, uri, methodName, nestedClass, launchConfiguration);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.run.single', async (uri, methodName?, launchConfiguration?, nestedClass?) => {
await runDebug(true, false, uri, methodName, nestedClass, launchConfiguration);
}));
context.subscriptions.push(commands.registerCommand(COMMAND_PREFIX + '.debug.single', async (uri, methodName?, launchConfiguration?, nestedClass?) => {
await runDebug(false, false, uri, methodName, nestedClass, launchConfiguration);