sdedic commented on a change in pull request #2882: URL: https://github.com/apache/netbeans/pull/2882#discussion_r613364436
########## File path: java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/LspTemplateUI.java ########## @@ -0,0 +1,253 @@ +/* + * 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.protocol; + +import com.google.gson.JsonPrimitive; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.function.Function; +import org.eclipse.lsp4j.ExecuteCommandParams; +import org.eclipse.lsp4j.MessageParams; +import org.eclipse.lsp4j.MessageType; +import org.eclipse.lsp4j.WorkspaceFolder; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.filesystems.URLMapper; +import org.openide.loaders.DataFolder; +import org.openide.loaders.DataObject; +import org.openide.loaders.DataObjectNotFoundException; +import org.openide.nodes.Node; +import org.openide.util.Exceptions; +import org.openide.util.NbBundle; +import org.openide.util.UserCancelException; + +class LspTemplateUI { + private LspTemplateUI() { + } + + static CompletableFuture<Object> createFromTemplate(String templates, NbCodeLanguageClient client, ExecuteCommandParams params) { + final FileObject fo = FileUtil.getConfigFile(templates); + final DataFolder folder = DataFolder.findFolder(fo); + return displayUI(folder, client, params); + } + + @NbBundle.Messages({ + "CTL_TemplateUI_SelectGroup=Select Template Type", + "CTL_TemplateUI_SelectTemplate=Select Template", + "CTL_TemplateUI_SelectTarget=Where to put the object?", + "CTL_TemplateUI_SelectName=Name of the object?", + "# {0} - path", + "ERR_InvalidPath={0} isn't valid folder", + }) + private static CompletableFuture<Object> displayUI(DataFolder templates, NbCodeLanguageClient client, ExecuteCommandParams params) { + final List<QuickPickItem> categories = quickPickTemplates(templates); + final CompletionStage<List<QuickPickItem>> pickGroup = client.showQuickPick(new ShowQuickPickParams(Bundle.CTL_TemplateUI_SelectGroup(), false, categories)); + final CompletionStage<DataFolder> group = pickGroup.thenApply((selectedGroups) -> { + final String chosen = singleSelection(selectedGroups); + FileObject chosenFo = templates.getPrimaryFile().getFileObject(chosen); + return DataFolder.findFolder(chosenFo); + }); + final CompletionStage<List<QuickPickItem>> pickProject = group.thenCompose(chosenGroup -> { + List<QuickPickItem> projectTypes = quickPickTemplates(chosenGroup); + return client.showQuickPick(new ShowQuickPickParams(Bundle.CTL_TemplateUI_SelectTemplate(), false, projectTypes)); + }); + final CompletionStage<DataObject> findTemplate = pickProject.thenCombine(group, (selectedTemplates, chosenGroup) -> { + try { + final String templateName = singleSelection(selectedTemplates); + final FileObject templateFo = chosenGroup.getPrimaryFile().getFileObject(templateName); + return DataObject.find(templateFo); + } catch (DataObjectNotFoundException ex) { + throw raise(RuntimeException.class, ex); + } + }); + final CompletionStage<DataFolder> findTarget = findTemplate.thenCompose(any -> client.workspaceFolders()).thenCompose(folders -> { + boolean[] suggestionIsExact = { true }; + DataFolder suggestion = findTargetFolder(params, folders, suggestionIsExact); + if (suggestionIsExact[0]) { + return CompletableFuture.completedFuture(suggestion); + } + + class VerifyPath implements Function<String, CompletionStage<DataFolder>> { + @Override + public CompletionStage<DataFolder> apply(String path) { + if (path == null) { + throw raise(RuntimeException.class, new UserCancelException(path)); + } + FileObject fo = FileUtil.toFileObject(new File(path)); + if (fo == null || !fo.isFolder()) { + client.showMessage(new MessageParams(MessageType.Error, Bundle.ERR_InvalidPath(path))); + return client.showInputBox(new ShowInputBoxParams(Bundle.CTL_TemplateUI_SelectTarget(), suggestion.getPrimaryFile().getPath())).thenCompose(this); Review comment: Now this is a **masterpiece**. A loop in a CompletionStage... ########## File path: java/java.lsp.server/src/org/netbeans/modules/java/lsp/server/protocol/LspTemplateUI.java ########## @@ -0,0 +1,253 @@ +/* + * 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.protocol; + +import com.google.gson.JsonPrimitive; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.function.Function; +import org.eclipse.lsp4j.ExecuteCommandParams; +import org.eclipse.lsp4j.MessageParams; +import org.eclipse.lsp4j.MessageType; +import org.eclipse.lsp4j.WorkspaceFolder; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.filesystems.URLMapper; +import org.openide.loaders.DataFolder; +import org.openide.loaders.DataObject; +import org.openide.loaders.DataObjectNotFoundException; +import org.openide.nodes.Node; +import org.openide.util.Exceptions; +import org.openide.util.NbBundle; +import org.openide.util.UserCancelException; + +class LspTemplateUI { + private LspTemplateUI() { + } + + static CompletableFuture<Object> createFromTemplate(String templates, NbCodeLanguageClient client, ExecuteCommandParams params) { + final FileObject fo = FileUtil.getConfigFile(templates); + final DataFolder folder = DataFolder.findFolder(fo); + return displayUI(folder, client, params); + } + + @NbBundle.Messages({ + "CTL_TemplateUI_SelectGroup=Select Template Type", + "CTL_TemplateUI_SelectTemplate=Select Template", + "CTL_TemplateUI_SelectTarget=Where to put the object?", + "CTL_TemplateUI_SelectName=Name of the object?", + "# {0} - path", + "ERR_InvalidPath={0} isn't valid folder", + }) + private static CompletableFuture<Object> displayUI(DataFolder templates, NbCodeLanguageClient client, ExecuteCommandParams params) { + final List<QuickPickItem> categories = quickPickTemplates(templates); + final CompletionStage<List<QuickPickItem>> pickGroup = client.showQuickPick(new ShowQuickPickParams(Bundle.CTL_TemplateUI_SelectGroup(), false, categories)); + final CompletionStage<DataFolder> group = pickGroup.thenApply((selectedGroups) -> { + final String chosen = singleSelection(selectedGroups); + FileObject chosenFo = templates.getPrimaryFile().getFileObject(chosen); + return DataFolder.findFolder(chosenFo); + }); + final CompletionStage<List<QuickPickItem>> pickProject = group.thenCompose(chosenGroup -> { + List<QuickPickItem> projectTypes = quickPickTemplates(chosenGroup); + return client.showQuickPick(new ShowQuickPickParams(Bundle.CTL_TemplateUI_SelectTemplate(), false, projectTypes)); + }); + final CompletionStage<DataObject> findTemplate = pickProject.thenCombine(group, (selectedTemplates, chosenGroup) -> { + try { + final String templateName = singleSelection(selectedTemplates); + final FileObject templateFo = chosenGroup.getPrimaryFile().getFileObject(templateName); + return DataObject.find(templateFo); + } catch (DataObjectNotFoundException ex) { + throw raise(RuntimeException.class, ex); + } + }); + final CompletionStage<DataFolder> findTarget = findTemplate.thenCompose(any -> client.workspaceFolders()).thenCompose(folders -> { + boolean[] suggestionIsExact = { true }; + DataFolder suggestion = findTargetFolder(params, folders, suggestionIsExact); + if (suggestionIsExact[0]) { + return CompletableFuture.completedFuture(suggestion); + } + + class VerifyPath implements Function<String, CompletionStage<DataFolder>> { + @Override + public CompletionStage<DataFolder> apply(String path) { + if (path == null) { + throw raise(RuntimeException.class, new UserCancelException(path)); + } + FileObject fo = FileUtil.toFileObject(new File(path)); + if (fo == null || !fo.isFolder()) { + client.showMessage(new MessageParams(MessageType.Error, Bundle.ERR_InvalidPath(path))); + return client.showInputBox(new ShowInputBoxParams(Bundle.CTL_TemplateUI_SelectTarget(), suggestion.getPrimaryFile().getPath())).thenCompose(this); + } + return CompletableFuture.completedFuture(DataFolder.findFolder(fo)); + } + } + return client.showInputBox(new ShowInputBoxParams(Bundle.CTL_TemplateUI_SelectTarget(), suggestion.getPrimaryFile().getPath())).thenCompose(new VerifyPath()); + }); + CompletionStage<String> findTargetName = findTarget.thenCombine(findTemplate, (target, source) -> source).thenCompose((source) -> { + return client.showInputBox(new ShowInputBoxParams(Bundle.CTL_TemplateUI_SelectName(), source.getName())); + }).thenCombine(findTemplate, (nameWithExtension, source) -> { + String templateExtension = source.getPrimaryFile().getExt(); + return removeExtensionFromFileName(nameWithExtension, templateExtension); + }); + return findTargetName.thenCombine(findTemplate.thenCombine(findTarget, (source, target) -> new DataObject[] { source, target }), (name, sourceAndTarget) -> { + try { + DataObject source = sourceAndTarget[0]; + DataFolder target = (DataFolder) sourceAndTarget[1]; + DataObject newPrj = source.createFromTemplate(target, name); + return (Object) newPrj.getPrimaryFile().toURI().toString(); + } catch (IOException ex) { + throw raise(RuntimeException.class, ex); + } + }).exceptionally((error) -> { + if (error instanceof UserCancelException || error.getCause() instanceof UserCancelException) { + return null; + } + Exceptions.printStackTrace(error); + return null; + }).toCompletableFuture(); + } + + private static DataFolder findWorkspaceRoot(List<WorkspaceFolder> folders) { + for (WorkspaceFolder f : folders) { + try { + FileObject fo = URLMapper.findFileObject(new URL(f.getUri())); + if (fo != null && fo.isFolder()) { + return DataFolder.findFolder(fo); + } + } catch (MalformedURLException ex) { + continue; + } + } + String root = System.getProperty("user.home"); // NOI18N + return DataFolder.findFolder(FileUtil.toFileObject(new File(root))); + } + + private static String singleSelection(List<QuickPickItem> selectedGroups) { + if (selectedGroups == null || selectedGroups.size() != 1) { + throw raise(RuntimeException.class, new UserCancelException("")); + } + return selectedGroups.get(0).getUserData().toString(); + } + + private static DataFolder findTargetFolder(ExecuteCommandParams params, List<WorkspaceFolder> folders, boolean[] defaultTargetExact) { + for (Object arg : params.getArguments()) { + if (arg == null) { + continue; + } + String path; + if (arg instanceof JsonPrimitive) { + JsonPrimitive jp = (JsonPrimitive) arg; + path = jp.getAsString(); + } else { + path = arg.toString(); + } + try { + FileObject fo = URLMapper.findFileObject(new URL(path)); + for (;;) { + if (fo == null) { + break; + } + if (!fo.isFolder()) { + fo = fo.getParent(); + defaultTargetExact[0] = false; + continue; + } + return DataFolder.findFolder(fo); + } + } catch (MalformedURLException ex) { + continue; + } + } + defaultTargetExact[0] = false; + return findWorkspaceRoot(folders); + } + + private static String removeExtensionFromFileName(String nameWithExtension, String templateExtension) { + if (nameWithExtension.endsWith('.' + templateExtension)) { + return nameWithExtension.substring(0, nameWithExtension.length() - templateExtension.length() - 1); + } else { + return nameWithExtension; + } + } + + private static List<QuickPickItem> quickPickTemplates(final DataFolder folder) { + Node[] arr = folder.getNodeDelegate().getChildren().getNodes(true); + List<QuickPickItem> categories = new ArrayList<>(); + for (Node n : arr) { + FileObject fo = n.getLookup().lookup(FileObject.class); + DataObject obj = n.getLookup().lookup(DataObject.class); + + boolean display; + if (obj instanceof DataFolder) { + Object o = obj.getPrimaryFile ().getAttribute ("simple"); // NOI18N + display = o == null || Boolean.TRUE.equals (o); + } else { + display = obj.isTemplate(); + } + + if (display) { + String detail = findDetail(obj); + final String displayName = n.getDisplayName(); + String description = n.getShortDescription(); + if (description != null && description.equals(displayName)) { + description = null; + } + categories.add(new QuickPickItem( + displayName, description, detail, + false, fo.getNameExt() + )); + } + } + return categories; + } + + private static String findDetail(DataObject obj) { + URL description = org.openide.loaders.TemplateWizard.getDescription(obj); + String descriptionText = null; + if (description != null) { + try (ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = description.openStream()) { + FileUtil.copy(is, os); + descriptionText = os.toString("UTF-8"); + int bodyBegin = descriptionText.toUpperCase().indexOf("<BODY>"); + int bodyEnd = descriptionText.toUpperCase().indexOf("</BODY>"); + if (bodyBegin >= 0 && bodyEnd > bodyBegin) { + descriptionText = descriptionText.substring(bodyBegin + 6, bodyEnd); + } else { + descriptionText = null; + } + } catch (IOException ex) { + Exceptions.printStackTrace(ex); Review comment: This could raise an error message in the LSP client's UI through `DialogDisplayer.notify`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected] For further information about the NetBeans mailing lists, visit: https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists
