Search in sources :

Example 11 with TextDocument

use of org.springframework.ide.vscode.commons.util.text.TextDocument in project sts4 by spring-projects.

the class ValuePropertyReferencesProvider method findReferencesInYMLFile.

private List<Location> findReferencesInYMLFile(String filePath, String propertyKey) {
    List<Location> foundLocations = new ArrayList<>();
    try {
        String fileContent = FileUtils.readFileToString(new File(filePath));
        Yaml yaml = new Yaml();
        YamlASTProvider parser = new YamlParser(yaml);
        URI docURI = Paths.get(filePath).toUri();
        TextDocument doc = new TextDocument(docURI.toString(), null);
        doc.setText(fileContent);
        YamlFileAST ast = parser.getAST(doc);
        List<Node> nodes = ast.getNodes();
        if (nodes != null && !nodes.isEmpty()) {
            for (Node node : nodes) {
                Node foundNode = findNode(node, "", propertyKey);
                if (foundNode != null) {
                    Position start = new Position();
                    start.setLine(foundNode.getStartMark().getLine());
                    start.setCharacter(foundNode.getStartMark().getColumn());
                    Position end = new Position();
                    end.setLine(foundNode.getEndMark().getLine());
                    end.setCharacter(foundNode.getEndMark().getColumn());
                    Range range = new Range();
                    range.setStart(start);
                    range.setEnd(end);
                    Location location = new Location(docURI.toString(), range);
                    foundLocations.add(location);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return foundLocations;
}
Also used : YamlParser(org.springframework.ide.vscode.commons.yaml.ast.YamlParser) TextDocument(org.springframework.ide.vscode.commons.util.text.TextDocument) YamlFileAST(org.springframework.ide.vscode.commons.yaml.ast.YamlFileAST) Position(org.eclipse.lsp4j.Position) MappingNode(org.yaml.snakeyaml.nodes.MappingNode) Node(org.yaml.snakeyaml.nodes.Node) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) YamlASTProvider(org.springframework.ide.vscode.commons.yaml.ast.YamlASTProvider) Range(org.eclipse.lsp4j.Range) URI(java.net.URI) Yaml(org.yaml.snakeyaml.Yaml) BadLocationException(org.springframework.ide.vscode.commons.util.BadLocationException) File(java.io.File) Location(org.eclipse.lsp4j.Location)

Example 12 with TextDocument

use of org.springframework.ide.vscode.commons.util.text.TextDocument in project sts4 by spring-projects.

the class BootPropertiesLanguageServerComponents method getCompletionEngine.

@Override
public ICompletionEngine getCompletionEngine() {
    ICompletionEngine propertiesCompletions = new SpringPropertiesCompletionEngine(indexProvider, typeUtilProvider, javaProjectFinder);
    ICompletionEngine yamlCompletions = new YamlCompletionEngine(yamlStructureProvider, yamlAssistContextProvider, COMPLETION_OPTIONS);
    return (TextDocument document, int offset) -> {
        String uri = document.getUri();
        if (uri != null) {
            if (uri.endsWith(PROPERTIES)) {
                return propertiesCompletions.getCompletions(document, offset);
            } else if (uri.endsWith(YML)) {
                return yamlCompletions.getCompletions(document, offset);
            }
        }
        return ImmutableList.of();
    };
}
Also used : ICompletionEngine(org.springframework.ide.vscode.commons.languageserver.completion.ICompletionEngine) TextDocument(org.springframework.ide.vscode.commons.util.text.TextDocument) SpringPropertiesCompletionEngine(org.springframework.ide.vscode.boot.properties.completions.SpringPropertiesCompletionEngine) YamlCompletionEngine(org.springframework.ide.vscode.commons.yaml.completion.YamlCompletionEngine)

Example 13 with TextDocument

use of org.springframework.ide.vscode.commons.util.text.TextDocument in project sts4 by spring-projects.

the class CompilationUnitCache method getClasspathEntries.

private static String[] getClasspathEntries(TextDocument document, IJavaProject project) throws Exception {
    if (project == null) {
        return new String[0];
    } else {
        IClasspath classpath = project.getClasspath();
        Stream<Path> classpathEntries = classpath.getClasspathEntries().stream();
        return classpathEntries.filter(path -> path.toFile().exists()).map(path -> path.toAbsolutePath().toString()).toArray(String[]::new);
    }
}
Also used : Path(java.nio.file.Path) SimpleTextDocumentService(org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) WriteLock(java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock) JavaProjectFinder(org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder) Log(org.springframework.ide.vscode.commons.util.Log) IJavaProject(org.springframework.ide.vscode.commons.java.IJavaProject) JavaCore(org.eclipse.jdt.core.JavaCore) ProjectObserver(org.springframework.ide.vscode.commons.languageserver.java.ProjectObserver) Set(java.util.Set) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadLock(java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock) Function(java.util.function.Function) TextDocument(org.springframework.ide.vscode.commons.util.text.TextDocument) HashSet(java.util.HashSet) Stream(java.util.stream.Stream) ASTParser(org.eclipse.jdt.core.dom.ASTParser) Map(java.util.Map) AST(org.eclipse.jdt.core.dom.AST) URI(java.net.URI) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) Path(java.nio.file.Path) IClasspath(org.springframework.ide.vscode.commons.java.IClasspath) IClasspath(org.springframework.ide.vscode.commons.java.IClasspath)

Example 14 with TextDocument

use of org.springframework.ide.vscode.commons.util.text.TextDocument in project sts4 by spring-projects.

the class SimpleLanguageServer method validateWith.

/**
 * Convenience method. Subclasses can call this to use a {@link IReconcileEngine} ported
 * from old STS codebase to validate a given {@link TextDocument} and publish Diagnostics.
 */
public void validateWith(TextDocumentIdentifier docId, IReconcileEngine engine) {
    CompletableFuture<Void> reconcileSession = this.busyReconcile = new CompletableFuture<Void>();
    // Log.debug("Reconciling BUSY");
    SimpleTextDocumentService documents = getTextDocumentService();
    int requestedVersion = documents.getDocument(docId.getUri()).getVersion();
    // Avoid running in the same thread as lsp4j as it can result
    // in long "hangs" for slow reconcile providers
    Mono.fromRunnable(() -> {
        TextDocument doc = documents.getDocument(docId.getUri()).copy();
        if (requestedVersion != doc.getVersion()) {
            // Do not bother reconciling if document contents is already stale.
            return;
        }
        if (testListener != null) {
            testListener.reconcileStarted(docId.getUri(), doc.getVersion());
        }
        IProblemCollector problems = new IProblemCollector() {

            private LinkedHashSet<Diagnostic> diagnostics = new LinkedHashSet<>();

            private List<Quickfix> quickfixes = new ArrayList<>();

            @Override
            public void endCollecting() {
                documents.setQuickfixes(docId, quickfixes);
                documents.publishDiagnostics(docId, diagnostics);
            }

            @Override
            public void beginCollecting() {
                diagnostics.clear();
            }

            @Override
            public void checkPointCollecting() {
                // publish what has been collected so far
                documents.publishDiagnostics(docId, diagnostics);
            }

            @Override
            public void accept(ReconcileProblem problem) {
                try {
                    DiagnosticSeverity severity = getDiagnosticSeverity(problem);
                    if (severity != null) {
                        Diagnostic d = new Diagnostic();
                        d.setCode(problem.getCode());
                        d.setMessage(problem.getMessage());
                        Range rng = doc.toRange(problem.getOffset(), problem.getLength());
                        d.setRange(rng);
                        d.setSeverity(severity);
                        List<QuickfixData<?>> fixes = problem.getQuickfixes();
                        if (CollectionUtil.hasElements(fixes)) {
                            for (QuickfixData<?> fix : fixes) {
                                quickfixes.add(new Quickfix<>(CODE_ACTION_COMMAND_ID, d, fix));
                            }
                        }
                        diagnostics.add(d);
                    }
                } catch (BadLocationException e) {
                    Log.warn("Invalid reconcile problem ignored", e);
                }
            }
        };
        // try {
        // Thread.sleep(2000);
        // } catch (InterruptedException e) {
        // }
        engine.reconcile(doc, problems);
    }).onErrorResume(error -> {
        Log.log(error);
        return Mono.empty();
    }).doFinally(ignore -> {
        reconcileSession.complete(null);
    // Log.debug("Reconciler DONE : "+this.busyReconcile.isDone());
    }).subscribeOn(RECONCILER_SCHEDULER).subscribe();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) QuickfixData(org.springframework.ide.vscode.commons.languageserver.quickfix.Quickfix.QuickfixData) JsonObject(com.google.gson.JsonObject) CodeLensOptions(org.eclipse.lsp4j.CodeLensOptions) LanguageClient(org.eclipse.lsp4j.services.LanguageClient) Sts4LanguageServer(org.springframework.ide.vscode.commons.languageserver.Sts4LanguageServer) QuickfixData(org.springframework.ide.vscode.commons.languageserver.quickfix.Quickfix.QuickfixData) LoggerFactory(org.slf4j.LoggerFactory) DiagnosticService(org.springframework.ide.vscode.commons.languageserver.DiagnosticService) MessageType(org.eclipse.lsp4j.MessageType) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) VscodeCompletionEngineAdapter(org.springframework.ide.vscode.commons.languageserver.completion.VscodeCompletionEngineAdapter) Map(java.util.Map) IProblemCollector(org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector) URI(java.net.URI) QuickfixRegistry(org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixRegistry) ProgressService(org.springframework.ide.vscode.commons.languageserver.ProgressService) DiagnosticSeverity(org.eclipse.lsp4j.DiagnosticSeverity) BadLocationException(org.springframework.ide.vscode.commons.util.BadLocationException) Collection(java.util.Collection) UUID(java.util.UUID) ClasspathListenerManager(org.springframework.ide.vscode.commons.languageserver.jdt.ls.ClasspathListenerManager) Assert(org.springframework.ide.vscode.commons.util.Assert) ServerCapabilities(org.eclipse.lsp4j.ServerCapabilities) Quickfix(org.springframework.ide.vscode.commons.languageserver.quickfix.Quickfix) List(java.util.List) ExecuteCommandOptions(org.eclipse.lsp4j.ExecuteCommandOptions) JsonArray(com.google.gson.JsonArray) ClasspathListener(org.springframework.ide.vscode.commons.languageserver.jdt.ls.ClasspathListener) WorkspaceFolder(org.eclipse.lsp4j.WorkspaceFolder) InitializeParams(org.eclipse.lsp4j.InitializeParams) WorkspaceFoldersOptions(org.eclipse.lsp4j.WorkspaceFoldersOptions) LanguageClientAware(org.eclipse.lsp4j.services.LanguageClientAware) Disposable(reactor.core.Disposable) ApplyWorkspaceEditParams(org.eclipse.lsp4j.ApplyWorkspaceEditParams) AsyncRunner(org.springframework.ide.vscode.commons.languageserver.util.AsyncRunner) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) QuickfixResolveParams(org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixResolveParams) Scheduler(reactor.core.scheduler.Scheduler) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) LazyCompletionResolver(org.springframework.ide.vscode.commons.languageserver.completion.VscodeCompletionEngineAdapter.LazyCompletionResolver) ImmutableList(com.google.common.collect.ImmutableList) ExecuteCommandParams(org.eclipse.lsp4j.ExecuteCommandParams) MessageParams(org.eclipse.lsp4j.MessageParams) Schedulers(reactor.core.scheduler.Schedulers) Registration(org.eclipse.lsp4j.Registration) LinkedHashSet(java.util.LinkedHashSet) TextDocumentSyncKind(org.eclipse.lsp4j.TextDocumentSyncKind) InitializeResult(org.eclipse.lsp4j.InitializeResult) RegistrationParams(org.eclipse.lsp4j.RegistrationParams) QuickfixEdit(org.springframework.ide.vscode.commons.languageserver.quickfix.QuickfixEdit) Logger(org.slf4j.Logger) Log(org.springframework.ide.vscode.commons.util.Log) ProgressParams(org.springframework.ide.vscode.commons.languageserver.ProgressParams) ICompletionEngine(org.springframework.ide.vscode.commons.languageserver.completion.ICompletionEngine) Mono(reactor.core.publisher.Mono) TextDocument(org.springframework.ide.vscode.commons.util.text.TextDocument) Consumer(java.util.function.Consumer) CollectionUtil(org.springframework.ide.vscode.commons.util.CollectionUtil) STS4LanguageClient(org.springframework.ide.vscode.commons.languageserver.STS4LanguageClient) Paths(java.nio.file.Paths) ProblemSeverity(org.springframework.ide.vscode.commons.languageserver.reconcile.ProblemSeverity) CompletionOptions(org.eclipse.lsp4j.CompletionOptions) WorkspaceServerCapabilities(org.eclipse.lsp4j.WorkspaceServerCapabilities) IReconcileEngine(org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine) ReconcileProblem(org.springframework.ide.vscode.commons.languageserver.reconcile.ReconcileProblem) Collections(java.util.Collections) ApplyWorkspaceEditResponse(org.eclipse.lsp4j.ApplyWorkspaceEditResponse) IProblemCollector(org.springframework.ide.vscode.commons.languageserver.reconcile.IProblemCollector) TextDocument(org.springframework.ide.vscode.commons.util.text.TextDocument) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) ReconcileProblem(org.springframework.ide.vscode.commons.languageserver.reconcile.ReconcileProblem) DiagnosticSeverity(org.eclipse.lsp4j.DiagnosticSeverity) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) BadLocationException(org.springframework.ide.vscode.commons.util.BadLocationException)

Example 15 with TextDocument

use of org.springframework.ide.vscode.commons.util.text.TextDocument in project sts4 by spring-projects.

the class SimpleTextDocumentService method didSave.

@Override
public void didSave(DidSaveTextDocumentParams params) {
    // Workaround for PT 147263283, where error markers in STS are lost on document save.
    // STS 3.9.0 does not use the LSP4E editor for edit manifest.yml, which correctly retains error markers after save.
    // Instead, because the LSP4E editor is missing support for hovers and completions, STS 3.9.0 uses its own manifest editor
    // which extends the YEdit editor. This YEdit editor has a problem, where on save, all error markers are deleted.
    // When STS uses the LSP4E editor and no longer needs its own YEdit-based editor, the issue with error markers disappearing
    // on save should not be a problem anymore, and the workaround below will no longer be needed.
    async.execute(() -> {
        if (documentSaveListener != null) {
            TextDocumentIdentifier docId = params.getTextDocument();
            String url = docId.getUri();
            Log.debug("didSave: " + url);
            if (url != null) {
                TextDocument doc = getDocument(url);
                documentSaveListener.accept(new TextDocumentSaveChange(doc));
            }
        }
    });
}
Also used : TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) TextDocument(org.springframework.ide.vscode.commons.util.text.TextDocument)

Aggregations

TextDocument (org.springframework.ide.vscode.commons.util.text.TextDocument)43 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)12 URI (java.net.URI)11 File (java.io.File)10 Location (org.eclipse.lsp4j.Location)8 Test (org.junit.Test)8 Path (java.nio.file.Path)7 ArrayList (java.util.ArrayList)7 SymbolInformation (org.eclipse.lsp4j.SymbolInformation)7 IClasspath (org.springframework.ide.vscode.commons.java.IClasspath)7 IJavaProject (org.springframework.ide.vscode.commons.java.IJavaProject)7 ImmutableList (com.google.common.collect.ImmutableList)6 List (java.util.List)6 Range (org.eclipse.lsp4j.Range)6 Collection (java.util.Collection)5 Map (java.util.Map)5 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 Stream (java.util.stream.Stream)5 ASTParser (org.eclipse.jdt.core.dom.ASTParser)5 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)5