Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding command for New Database Connection #3358

Merged
merged 8 commits into from Dec 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -81,7 +81,7 @@
<build-prerequisite/>
<compile-dependency/>
<run-dependency>
<specification-version>1.13</specification-version>
<specification-version>1.16</specification-version>
</run-dependency>
</dependency>
<dependency>
Expand Down
2 changes: 1 addition & 1 deletion java/java.lsp.server/nbcode/nbproject/platform.properties
Expand Up @@ -116,9 +116,9 @@ disabled.modules=\
org.netbeans.modules.css.model,\
org.netbeans.modules.css.prep,\
org.netbeans.modules.css.visual,\
org.netbeans.modules.db.kit,\
org.netbeans.modules.db.core,\
sdedic marked this conversation as resolved.
Show resolved Hide resolved
org.netbeans.modules.db.dataview,\
org.netbeans.modules.db.kit,\
org.netbeans.modules.db.mysql,\
org.netbeans.modules.db.sql.editor,\
org.netbeans.modules.db.sql.visualeditor,\
Expand Down
2 changes: 1 addition & 1 deletion java/java.lsp.server/nbproject/project.properties
Expand Up @@ -17,7 +17,7 @@

javac.source=1.8
javac.compilerargs=-Xlint -Xlint:-serial
spec.version.base=1.15.0
spec.version.base=1.16.0
javadoc.arch=${basedir}/arch.xml
requires.nb.javac=true
lsp.build.dir=vscode/nbcode
Expand Down
@@ -0,0 +1,183 @@
/*
* 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.
*/
package org.netbeans.modules.java.lsp.server.db;

import java.net.URL;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.eclipse.lsp4j.CodeAction;
import org.eclipse.lsp4j.CodeActionParams;
import org.eclipse.lsp4j.MessageParams;
import org.eclipse.lsp4j.MessageType;
import org.netbeans.api.db.explorer.ConnectionManager;
import org.netbeans.api.db.explorer.DatabaseConnection;
import org.netbeans.api.db.explorer.DatabaseException;
import org.netbeans.api.db.explorer.JDBCDriver;
import org.netbeans.api.db.explorer.JDBCDriverManager;
import org.netbeans.modules.java.lsp.server.protocol.CodeActionsProvider;
import org.netbeans.modules.java.lsp.server.protocol.NbCodeLanguageClient;
import org.netbeans.modules.java.lsp.server.protocol.QuickPickItem;
import org.netbeans.modules.java.lsp.server.protocol.ShowInputBoxParams;
import org.netbeans.modules.java.lsp.server.protocol.ShowQuickPickParams;
import org.netbeans.modules.parsing.api.ResultIterator;
import org.openide.awt.StatusDisplayer;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.URLMapper;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;

/**
*
* @author Jan Horvath
*/
@NbBundle.Messages({
"MSG_EnterDbUrl=Enter DB URL",
"MSG_EnterUsername=Enter Username",
"MSG_EnterPassword=Enter Password",
"MSG_SelectDriver=Select db driver",
"MSG_DriverNotFound=Driver not found",
"MSG_ConnectionAdded=Connection added",
"MSG_ConnectionFailed=Connection failed",
"MSG_SelectSchema=Select Database Schema"
})
@ServiceProvider(service = CodeActionsProvider.class)
public class DBAddConnection extends CodeActionsProvider {
public static final String DB_ADD_CONNECTION = "db.add.connection"; // NOI18N

@Override
public CompletableFuture<Object> processCommand(NbCodeLanguageClient client, String command, List<Object> arguments) {
if (!DB_ADD_CONNECTION.equals(command)) {
return null;
}
JDBCDriver[] drivers = JDBCDriverManager.getDefault().getDrivers();
List<QuickPickItem> items = new ArrayList<>();
for (int i = 0; i < drivers.length; i++) {
URL[] jars = drivers[i].getURLs();
if (jars != null && jars.length > 0) {
FileObject jarFO = URLMapper.findFileObject(jars[0]);
if (jarFO != null && jarFO.isValid()) {
items.add(
new QuickPickItem(drivers[i].getName(), null, drivers[i].getDisplayName() + " (" + drivers[i].getClassName() + ")", false, i) // NOI18N
);
}
}
}

return client.showQuickPick(new ShowQuickPickParams(Bundle.MSG_SelectDriver(), false, items))
.thenApply(selectedItems -> {
if (selectedItems == null) {
return null;
}
if (!selectedItems.isEmpty()) {
int i = ((Double) selectedItems.get(0).getUserData()).intValue();
JDBCDriver driver = drivers[i];
client.showInputBox(new ShowInputBoxParams(
Bundle.MSG_EnterDbUrl(), "")).thenAccept((u) -> {
if (u == null) {
return;
}
client.showInputBox(new ShowInputBoxParams(
Bundle.MSG_EnterUsername(), "")).thenAccept((username) -> { //NOI18N
if (username == null) {
return;
}
client.showInputBox(new ShowInputBoxParams(
Bundle.MSG_EnterPassword(), "", true)).thenAccept((password) -> { //NOI18N
if (password == null) {
return;
}
DatabaseConnection dbconn = DatabaseConnection.create(driver, u, username, null, password, true);
try {
ConnectionManager.getDefault().addConnection(dbconn);
List<String> schemas = getSchemas(dbconn);
if (schemas.isEmpty()) {
client.showMessage(new MessageParams(MessageType.Info, Bundle.MSG_ConnectionAdded()));
} else {
List<QuickPickItem> schemaItems = schemas.stream().map(schema -> new QuickPickItem(schema)).collect(Collectors.toList());
client.showQuickPick(new ShowQuickPickParams(Bundle.MSG_SelectSchema(), schemaItems)).thenAccept((s) -> {
if (s == null) {
try {
// Command was interrupted, we don't want the connection to be added
ConnectionManager.getDefault().removeConnection(dbconn);
} catch (DatabaseException ex) {
StatusDisplayer.getDefault().setStatusText(ex.getMessage());
}
return;
}
String schema = s.get(0).getLabel();
DatabaseConnection dbconn1 = DatabaseConnection.create(driver, u, username, schema, password, true);
try {
ConnectionManager.getDefault().removeConnection(dbconn);
ConnectionManager.getDefault().addConnection(dbconn1);
} catch (DatabaseException ex) {
client.showMessage(new MessageParams(MessageType.Error, ex.getMessage()));
return;
}
client.showMessage(new MessageParams(MessageType.Info, Bundle.MSG_ConnectionAdded()));
});
}
} catch (SQLException | DatabaseException ex) {
client.showMessage(new MessageParams(MessageType.Error, ex.getMessage()));
}
});
});

});

} else {
client.showMessage(new MessageParams(MessageType.Error, Bundle.MSG_DriverNotFound()));
}
return null;
});
}

private static List<String> getSchemas(DatabaseConnection dbconn) throws SQLException, DatabaseException {
List<String> schemas = new ArrayList<>();
if (ConnectionManager.getDefault().connect(dbconn)) {
DatabaseMetaData dbMetaData = dbconn.getJDBCConnection().getMetaData();
if (dbMetaData.supportsSchemasInTableDefinitions()) {
ResultSet rs = dbMetaData.getSchemas();
if (rs != null) {
while (rs.next()) {
schemas.add(rs.getString(1).trim());
}
}
}
}
return schemas;
}

@Override
public Set<String> getCommands() {
return Collections.singleton(DB_ADD_CONNECTION);
}

@Override
public List<CodeAction> getCodeActions(ResultIterator resultIterator, CodeActionParams params) throws Exception {
return Collections.emptyList();
}

}
Expand Up @@ -42,14 +42,24 @@ public class ShowInputBoxParams {
*/
@NonNull
private String value;

/**
* Controls if a password input is shown. Password input hides the typed text.
*/
private boolean password = false;
sdedic marked this conversation as resolved.
Show resolved Hide resolved

public ShowInputBoxParams() {
this("", "");
}

public ShowInputBoxParams(@NonNull final String prompt, @NonNull final String value) {
this(prompt, value, false);
}

public ShowInputBoxParams(@NonNull final String prompt, @NonNull final String value, final boolean password) {
this.prompt = Preconditions.checkNotNull(prompt, "prompt");
this.value = Preconditions.checkNotNull(value, "value");
this.password = password;
}

/**
Expand Down Expand Up @@ -83,6 +93,26 @@ public String getValue() {
public void setValue(@NonNull final String value) {
this.value = Preconditions.checkNotNull(value, "value");
}

/**
* Controls if a password input is shown. Password input hides the typed text.
*
* @since 1.16
*/
@Pure
@NonNull
public boolean isPassword() {
return password;
}

/**
* Controls if a password input is shown. Password input hides the typed text.
*
* @since 1.16
*/
public void setPassword(boolean password) {
this.password = password;
JaroslavTulach marked this conversation as resolved.
Show resolved Hide resolved
}

@Override
@Pure
Expand Down
Expand Up @@ -98,6 +98,7 @@
import org.netbeans.modules.gsf.testrunner.ui.api.TestMethodFinder;
import org.netbeans.modules.java.lsp.server.LspServerState;
import org.netbeans.modules.java.lsp.server.Utils;
import org.netbeans.modules.java.lsp.server.db.DBAddConnection;
import org.netbeans.modules.java.lsp.server.debugging.attach.AttachConfigurations;
import org.netbeans.modules.java.lsp.server.debugging.attach.AttachNativeConfigurations;
import org.netbeans.modules.java.source.ElementHandleAccessor;
Expand Down Expand Up @@ -516,7 +517,7 @@ public CompletableFuture<Object> executeCommand(ExecuteCommandParams params) {
}
throw new UnsupportedOperationException("Command not supported: " + params.getCommand());
}

private final AtomicReference<BiConsumer<FileObject, Collection<TestMethodController.TestMethod>>> testMethodsListener = new AtomicReference<>();
private final AtomicReference<PropertyChangeListener> openProjectsListener = new AtomicReference<>();

Expand Down
5 changes: 5 additions & 0 deletions java/java.lsp.server/vscode/package.json
Expand Up @@ -405,6 +405,11 @@
"command": "foundProjects.deleteEntry",
"title": "Delete"
},
{
"command": "db.add.connection",
"title": "Add Database Connection",
"category": "Database"
JaroslavTulach marked this conversation as resolved.
Show resolved Hide resolved
},
{
"command": "nbls:Database:netbeans.db.explorer.action.Connect",
"title": "Connect to Database"
Expand Down
2 changes: 1 addition & 1 deletion java/java.lsp.server/vscode/src/extension.ts
Expand Up @@ -756,7 +756,7 @@ function doActivateWithJDK(specifiedJDK: string | null, context: ExtensionContex
return selected ? Array.isArray(selected) ? selected : [selected] : undefined;
});
c.onRequest(InputBoxRequest.type, async param => {
return await window.showInputBox({ prompt: param.prompt, value: param.value });
return await window.showInputBox({ prompt: param.prompt, value: param.value, password: param.password });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bump required spec version in nbcode/integration module.

});
c.onNotification(TestProgressNotification.type, param => {
if (testAdapter) {
Expand Down
4 changes: 3 additions & 1 deletion java/java.lsp.server/vscode/src/nbcode.ts
Expand Up @@ -97,7 +97,9 @@ if (typeof process === 'object' && process.argv0 === 'node') {
let clusters = fs.readdirSync(nbcode).filter(c => c !== 'bin' && c !== 'etc').map(c => path.join(nbcode, c));
let args = process.argv.slice(2);
let json = JSON.parse("" + fs.readFileSync(path.join(extension, 'package.json')));
let globalStorage = path.join(os.homedir(), '.config', 'Code', 'User', 'globalStorage', json.publisher + '.' + json.name);
let globalStorage = os.platform() === 'darwin' ?
path.join(os.homedir(), 'Library', 'Application Support', 'Code', 'User', 'globalStorage', json.publisher + '.' + json.name) :
JaroslavTulach marked this conversation as resolved.
Show resolved Hide resolved
path.join(os.homedir(), '.config', 'Code', 'User', 'globalStorage', json.publisher + '.' + json.name);
let info = {
clusters : clusters,
extensionPath: extension,
Expand Down
4 changes: 4 additions & 0 deletions java/java.lsp.server/vscode/src/protocol.ts
Expand Up @@ -79,6 +79,10 @@ export interface ShowInputBoxParams {
* The value to prefill in the input box.
*/
value: string;
/**
* Controls if a password input is shown. Password input hides the typed text.
*/
password?: boolean;
}

export namespace InputBoxRequest {
Expand Down