org.eclipse.jdt.ls.core.internal.JDTUtils Java Examples
The following examples show how to use
org.eclipse.jdt.ls.core.internal.JDTUtils.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FormatterHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testDisableFormattingOnType() throws Exception { //@formatter:off String text = "package org.sample;\n" + "\n" + " public class Baz { \n" + "String name ;\n" + "}\n"; //@formatter:on ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 28), "\n"); params.setTextDocument(textDocument); params.setOptions(options); //Check it's disabled by default List<? extends TextEdit> edits = server.onTypeFormatting(params).get(); assertNotNull(edits); String newText = TextEditUtil.apply(unit, edits); assertEquals(text, newText); }
Example #2
Source File: DocumentLifeCycleHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private void assertNewProblemReported(ExpectedProblemReport... expectedReports) { List<PublishDiagnosticsParams> diags = getClientRequests("publishDiagnostics"); assertEquals(expectedReports.length, diags.size()); for (int i = 0; i < expectedReports.length; i++) { PublishDiagnosticsParams diag = diags.get(i); ExpectedProblemReport expected = expectedReports[i]; assertEquals(JDTUtils.toURI(expected.cu), diag.getUri()); if (expected.problemCount != diag.getDiagnostics().size()) { String message = ""; for (Diagnostic d : diag.getDiagnostics()) { message += d.getMessage() + ", "; } assertEquals(message, expected.problemCount, diag.getDiagnostics().size()); } } diags.clear(); }
Example #3
Source File: SyntaxDocumentLifeCycleHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Override public ICompilationUnit resolveCompilationUnit(String uri) { IFile resource = JDTUtils.findFile(uri); ICompilationUnit unit = JDTUtils.resolveCompilationUnit(resource); if (JDTUtils.isOnClassPath(unit)) { return unit; } // Open file not on the classpath. IPath filePath = ResourceUtils.canonicalFilePathFromURI(uri); Collection<IPath> rootPaths = preferenceManager.getPreferences().getRootPaths(); Optional<IPath> belongedRootPath = rootPaths.stream().filter(rootPath -> rootPath.isPrefixOf(filePath)).findFirst(); if (belongedRootPath.isPresent()) { if (tryUpdateClasspath(filePath, belongedRootPath.get())) { unit = JDTUtils.resolveCompilationUnit(uri); projectsManager.registerWatchers(true);; } } if (unit == null) { unit = JDTUtils.getFakeCompilationUnit(uri); } return unit; }
Example #4
Source File: ProjectCommand.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
/** * Checks if the input uri is a test source file or not. * * @param uri * Uri of the source file that needs to be queried. * @return <code>true</code> if the input uri is a test file in its belonging * project, otherwise returns <code>false</code>. * @throws CoreException */ public static boolean isTestFile(String uri) throws CoreException { ICompilationUnit compilationUnit = JDTUtils.resolveCompilationUnit(uri); if (compilationUnit == null) { throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to an existing Java source file.")); } IJavaProject javaProject = compilationUnit.getJavaProject(); if (javaProject == null) { throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Given URI does not belong to an existing Java project.")); } // Ignore default project if (ProjectsManager.DEFAULT_PROJECT_NAME.equals(javaProject.getProject().getName())) { return false; } final IPath compilationUnitPath = compilationUnit.getPath(); for (IPath testpath : listTestSourcePaths(javaProject)) { if (testpath.isPrefixOf(compilationUnitPath)) { return true; } } return false; }
Example #5
Source File: SyntaxProjectsManager.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Override public void fileChanged(String uriString, CHANGE_TYPE changeType) { if (uriString == null) { return; } IResource resource = JDTUtils.getFileOrFolder(uriString); if (resource == null) { return; } try { Optional<IBuildSupport> bs = getBuildSupport(resource.getProject()); if (bs.isPresent()) { IBuildSupport buildSupport = bs.get(); buildSupport.fileChanged(resource, changeType, new NullProgressMonitor()); } } catch (CoreException e) { JavaLanguageServerPlugin.logException("Problem refreshing workspace", e); } }
Example #6
Source File: NavigateToDefinitionHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static Location fixLocation(IJavaElement element, Location location, IJavaProject javaProject) { if (location == null) { return null; } if (!javaProject.equals(element.getJavaProject()) && element.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) { // see issue at: https://github.com/eclipse/eclipse.jdt.ls/issues/842 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=541573 // for jdk classes, jdt will reuse the java model by altering project to share the model between projects // so that sometimes the project for `element` is default project and the project is different from the project for `unit` // this fix is to replace the project name with non-default ones since default project should be transparent to users. if (location.getUri().contains(ProjectsManager.DEFAULT_PROJECT_NAME)) { String patched = StringUtils.replaceOnce(location.getUri(), ProjectsManager.DEFAULT_PROJECT_NAME, javaProject.getProject().getName()); try { IClassFile cf = (IClassFile) JavaCore.create(JDTUtils.toURI(patched).getQuery()); if (cf != null && cf.exists()) { location.setUri(patched); } } catch (Exception ex) { } } } return location; }
Example #7
Source File: NavigateToDefinitionHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private Location computeDefinitionNavigation(ITypeRoot unit, int line, int column, IProgressMonitor monitor) { try { IJavaElement element = JDTUtils.findElementAtSelection(unit, line, column, this.preferenceManager, monitor); if (monitor.isCanceled()) { return null; } if (element == null) { return computeBreakContinue(unit, line, column); } return computeDefinitionNavigation(element, unit.getJavaProject()); } catch (CoreException e) { JavaLanguageServerPlugin.logException("Problem computing definition for" + unit.getElementName(), e); } return null; }
Example #8
Source File: SemanticTokensCommandTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testSemanticTokens_packages() throws JavaModelException { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("import java.nio.*;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); SemanticTokensLegend legend = SemanticTokensCommand.getLegend(); SemanticTokens tokens = SemanticTokensCommand.provide(JDTUtils.toURI(cu)); Map<Integer, Map<Integer, int[]>> decodedTokens = decode(tokens); assertToken(decodedTokens, legend, 1, 7, 9, "namespace", Arrays.asList()); assertToken(decodedTokens, legend, 2, 7, 8, "namespace", Arrays.asList()); }
Example #9
Source File: NavigateToDefinitionHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static Location computeDefinitionNavigation(IJavaElement element, IJavaProject javaProject) throws JavaModelException { if (element == null) { return null; } ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE); if (compilationUnit != null || (cf != null && cf.getSourceRange() != null)) { return fixLocation(element, JDTUtils.toLocation(element), javaProject); } if (element instanceof IMember && ((IMember) element).getClassFile() != null) { return fixLocation(element, JDTUtils.toLocation(((IMember) element).getClassFile()), javaProject); } return null; }
Example #10
Source File: HoverHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testHoverThrowable() throws Exception { String uriString = ClassFileUtil.getURI(project, "java.lang.Exception"); IClassFile classFile = JDTUtils.resolveClassFile(uriString); String contents = JavaLanguageServerPlugin.getContentProviderManager().getSource(classFile, monitor); IDocument document = new Document(contents); IRegion region = new FindReplaceDocumentAdapter(document).find(0, "Throwable", true, false, false, false); int offset = region.getOffset(); int line = document.getLineOfOffset(offset); int character = offset - document.getLineOffset(line); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uriString); Position position = new Position(line, character); TextDocumentPositionParams params = new TextDocumentPositionParams(textDocument, position); Hover hover = handler.hover(params, monitor); assertNotNull(hover); assertTrue("Unexpected hover ", !hover.getContents().getLeft().isEmpty()); }
Example #11
Source File: InvisibleProjectImporter.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static IPath inferSourceDirectory(java.nio.file.Path filePath, String packageName) { String packagePath = packageName.replace(JDTUtils.PERIOD, JDTUtils.PATH_SEPARATOR); java.nio.file.Path sourcePath = filePath.getParent(); if (StringUtils.isBlank(packagePath)) { return ResourceUtils.filePathFromURI(sourcePath.toUri().toString()); } else if (sourcePath.endsWith(Paths.get(packagePath))) { // package should match ancestor folders. int packageCount = packageName.split("\\" + JDTUtils.PERIOD).length; while (packageCount > 0) { sourcePath = sourcePath.getParent(); packageCount--; } return ResourceUtils.filePathFromURI(sourcePath.toUri().toString()); } return null; }
Example #12
Source File: SemanticTokensCommandTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testSemanticTokens_variables() throws JavaModelException { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("\n"); buf.append(" public static void foo() {\n"); buf.append(" String bar1;\n"); buf.append(" final String bar2 = \"test\";\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); SemanticTokensLegend legend = SemanticTokensCommand.getLegend(); SemanticTokens tokens = SemanticTokensCommand.provide(JDTUtils.toURI(cu)); Map<Integer, Map<Integer, int[]>> decodedTokens = decode(tokens); assertToken(decodedTokens, legend, 5, 13, 4, "variable", Arrays.asList()); assertToken(decodedTokens, legend, 6, 19, 4, "variable", Arrays.asList("readonly")); }
Example #13
Source File: DocumentLifeCycleHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private void changeDocument(ICompilationUnit cu, String content, int version, Range range, int length) throws JavaModelException { DidChangeTextDocumentParams changeParms = new DidChangeTextDocumentParams(); VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(cu)); textDocument.setVersion(version); changeParms.setTextDocument(textDocument); TextDocumentContentChangeEvent event = new TextDocumentContentChangeEvent(); if (range != null) { event.setRange(range); event.setRangeLength(length); } event.setText(content); List<TextDocumentContentChangeEvent> contentChanges = new ArrayList<>(); contentChanges.add(event); changeParms.setContentChanges(contentChanges); lifeCycleHandler.didChange(changeParms); }
Example #14
Source File: FindLinksHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testNoSuperMethod() throws JavaModelException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); //@formatter:off ICompilationUnit unitA = pack1.createCompilationUnit("A.java", "package test1;\n" + "\n" + "public class A {\n" + " public void run() {\n" + " }\n" + "}", true, null); //@formatter:on String uri = JDTUtils.toURI(unitA); List<? extends Location> response = FindLinksHandler.findLinks("superImplementation", new TextDocumentPositionParams(new TextDocumentIdentifier(uri), new Position(3, 14)), new NullProgressMonitor()); assertTrue(response == null || response.isEmpty()); }
Example #15
Source File: AdvancedExtractTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testMoveFile() throws Exception { when(preferenceManager.getClientPreferences().isMoveRefactoringSupported()).thenReturn(true); IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public /*[*/class E /*]*/{\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); Range selection = getRange(cu, null); List<Either<Command, CodeAction>> codeActions = evaluateCodeActions(cu, selection); Assert.assertNotNull(codeActions); Either<Command, CodeAction> moveAction = CodeActionHandlerTest.findAction(codeActions, JavaCodeActionKind.REFACTOR_MOVE); Assert.assertNotNull(moveAction); Command moveCommand = CodeActionHandlerTest.getCommand(moveAction); Assert.assertNotNull(moveCommand); Assert.assertEquals(RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, moveCommand.getCommand()); Assert.assertNotNull(moveCommand.getArguments()); Assert.assertEquals(3, moveCommand.getArguments().size()); Assert.assertEquals(RefactorProposalUtility.MOVE_FILE_COMMAND, moveCommand.getArguments().get(0)); Assert.assertTrue(moveCommand.getArguments().get(2) instanceof RefactorProposalUtility.MoveFileInfo); Assert.assertEquals(JDTUtils.toURI(cu), ((RefactorProposalUtility.MoveFileInfo) moveCommand.getArguments().get(2)).uri); }
Example #16
Source File: CallHierarchyHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private CallHierarchyItem toCallHierarchyItem(IMember member) throws JavaModelException { Location fullLocation = getLocation(member, LocationType.FULL_RANGE); Range range = fullLocation.getRange(); String uri = fullLocation.getUri(); CallHierarchyItem item = new CallHierarchyItem(); item.setName(JDTUtils.getName(member)); item.setKind(DocumentSymbolHandler.mapKind(member)); item.setRange(range); item.setSelectionRange(getLocation(member, LocationType.NAME_RANGE).getRange()); item.setUri(uri); IType declaringType = member.getDeclaringType(); item.setDetail(declaringType == null ? null : declaringType.getFullyQualifiedName()); if (JDTUtils.isDeprecated(member)) { item.setTags(Arrays.asList(SymbolTag.Deprecated)); } return item; }
Example #17
Source File: DocumentLifeCycleHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
protected List<Either<Command, CodeAction>> getCodeActions(ICompilationUnit cu) throws JavaModelException { CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null); IProblem[] problems = astRoot.getProblems(); Range range = getRange(cu, problems); CodeActionParams parms = new CodeActionParams(); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(cu)); parms.setTextDocument(textDocument); parms.setRange(range); CodeActionContext context = new CodeActionContext(); context.setDiagnostics(DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true)); context.setOnly(Arrays.asList(CodeActionKind.QuickFix)); parms.setContext(context); return new CodeActionHandler(this.preferenceManager).getCodeActionCommands(parms, new NullProgressMonitor()); }
Example #18
Source File: SaveActionHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testWillSaveWaitUntil() throws Exception { URI srcUri = project.getFile("src/java/Foo4.java").getRawLocationURI(); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(srcUri); StringBuilder buf = new StringBuilder(); buf.append("package java;\n"); buf.append("\n"); buf.append("public class Foo4 {\n"); buf.append("}\n"); WillSaveTextDocumentParams params = new WillSaveTextDocumentParams(); TextDocumentIdentifier document = new TextDocumentIdentifier(); document.setUri(srcUri.toString()); params.setTextDocument(document); List<TextEdit> result = handler.willSaveWaitUntil(params, monitor); Document doc = new Document(); doc.set(cu.getSource()); assertEquals(TextEditUtil.apply(doc, result), buf.toString()); }
Example #19
Source File: MoveHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static PackageNode createPackageNode(IPackageFragment fragment) { if (fragment == null) { return null; } String projectName = fragment.getJavaProject().getProject().getName(); String uri = null; if (fragment.getResource() != null) { uri = JDTUtils.getFileURI(fragment.getResource()); } if (fragment.isDefaultPackage()) { return new PackageNode(DEFAULT_PACKAGE_DISPLAYNAME, uri, fragment.getPath().toPortableString(), projectName, true); } return new PackageNode(fragment.getElementName(), uri, fragment.getPath().toPortableString(), projectName, false); }
Example #20
Source File: BaseDiagnosticsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings("restriction") private static Range convertRange(IOpenable openable, IProblem problem) { try { return JDTUtils.toRange(openable, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1); } catch (CoreException e) { // In case failed to open the IOpenable's buffer, use the IProblem's information to calculate the range. Position start = new Position(); Position end = new Position(); start.setLine(problem.getSourceLineNumber() - 1);// The protocol is 0-based. end.setLine(problem.getSourceLineNumber() - 1); if (problem instanceof DefaultProblem) { DefaultProblem dProblem = (DefaultProblem) problem; start.setCharacter(dProblem.getSourceColumnNumber() - 1); int offset = 0; if (dProblem.getSourceStart() != -1 && dProblem.getSourceEnd() != -1) { offset = dProblem.getSourceEnd() - dProblem.getSourceStart() + 1; } end.setCharacter(dProblem.getSourceColumnNumber() - 1 + offset); } return new Range(start, end); } }
Example #21
Source File: SemanticHighlightingTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
protected void changeDocument(ICompilationUnit unit, String content, int version, Range range, int length) { DidChangeTextDocumentParams changeParms = new DidChangeTextDocumentParams(); VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(unit)); textDocument.setVersion(version); changeParms.setTextDocument(textDocument); TextDocumentContentChangeEvent event = new TextDocumentContentChangeEvent(); if (range != null) { event.setRange(range); event.setRangeLength(length); } event.setText(content); List<TextDocumentContentChangeEvent> contentChanges = new ArrayList<>(); contentChanges.add(event); changeParms.setContentChanges(contentChanges); lifeCycleHandler.didChange(changeParms); }
Example #22
Source File: DocumentLifeCycleHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Test public void testDidOpenNotOnClasspath() throws Exception { importProjects("eclipse/hello"); IProject project = WorkspaceHelper.getProject("hello"); URI uri = project.getFile("nopackage/Test2.java").getRawLocationURI(); ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri); String source = FileUtils.readFileToString(FileUtils.toFile(uri.toURL())); openDocument(cu, source, 1); Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor); assertEquals(project, cu.getJavaProject().getProject()); assertEquals(source, cu.getSource()); List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics"); assertEquals(1, diagnosticReports.size()); PublishDiagnosticsParams diagParam = diagnosticReports.get(0); assertEquals(2, diagParam.getDiagnostics().size()); closeDocument(cu); Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor); diagnosticReports = getClientRequests("publishDiagnostics"); assertEquals(2, diagnosticReports.size()); diagParam = diagnosticReports.get(1); assertEquals(0, diagParam.getDiagnostics().size()); }
Example #23
Source File: BaseDocumentLifeCycleHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public void didClose(DidCloseTextDocumentParams params) { ISchedulingRule rule = JDTUtils.getRule(params.getTextDocument().getUri()); try { ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { handleClosed(params); } }, rule, IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException e) { JavaLanguageServerPlugin.logException("Handle document close ", e); } }
Example #24
Source File: HoverHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public Hover hover(TextDocumentPositionParams position, IProgressMonitor monitor) { ITypeRoot unit = JDTUtils.resolveTypeRoot(position.getTextDocument().getUri()); List<Either<String, MarkedString>> content = null; if (unit != null && !monitor.isCanceled()) { content = computeHover(unit, position.getPosition().getLine(), position.getPosition().getCharacter(), monitor); } else { content = Collections.singletonList(Either.forLeft("")); } Hover $ = new Hover(); $.setContents(content); return $; }
Example #25
Source File: CodeActionHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test @Ignore public void testCodeAction_superfluousSemicolon() throws Exception{ ICompilationUnit unit = getWorkingCopy( "src/java/Foo.java", "public class Foo {\n"+ " void foo() {\n"+ ";" + " }\n"+ "}\n"); CodeActionParams params = new CodeActionParams(); params.setTextDocument(new TextDocumentIdentifier(JDTUtils.toURI(unit))); final Range range = CodeActionUtil.getRange(unit, ";"); params.setRange(range); params.setContext(new CodeActionContext(Arrays.asList(getDiagnostic(Integer.toString(IProblem.SuperfluousSemicolon), range)))); List<Either<Command, CodeAction>> codeActions = getCodeActions(params); Assert.assertNotNull(codeActions); Assert.assertEquals(1, codeActions.size()); Assert.assertEquals(codeActions.get(0), CodeActionKind.QuickFix); Command c = getCommand(codeActions.get(0)); Assert.assertEquals(CodeActionHandler.COMMAND_ID_APPLY_EDIT, c.getCommand()); Assert.assertNotNull(c.getArguments()); Assert.assertTrue(c.getArguments().get(0) instanceof WorkspaceEdit); WorkspaceEdit we = (WorkspaceEdit) c.getArguments().get(0); List<org.eclipse.lsp4j.TextEdit> edits = we.getChanges().get(JDTUtils.toURI(unit)); Assert.assertEquals(1, edits.size()); Assert.assertEquals("", edits.get(0).getNewText()); Assert.assertEquals(range, edits.get(0).getRange()); }
Example #26
Source File: FormatterHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test // typing } should format the previous block public void testFormattingOnTypeCloseBlock() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "package org.sample;\n" + "\n" + " public class Baz { \n" + "String name ;\n" + "} "//typed } here //@formatter:on ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(4, 0), "}"); params.setTextDocument(textDocument); params.setOptions(options); preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true); List<? extends TextEdit> edits = server.onTypeFormatting(params).get(); assertNotNull(edits); //@formatter:off String expectedText = "package org.sample;\n" + "\n" + "public class Baz {\n" + " String name;\n" + "}"; //@formatter:on String newText = TextEditUtil.apply(unit, edits); assertEquals(expectedText, newText); }
Example #27
Source File: DiagnosticsCommandTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testRefreshDiagnosticsWithReportAllErrors() throws Exception { IJavaProject javaProject = newDefaultProject(); IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src")); IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null); // @formatter:off String standaloneFileContent = "package java;\n"+ "public class Foo extends UnknownType {\n"+ " public void method1(){\n"+ " super.whatever()\n"+ " }\n"+ "}"; // @formatter:on ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null); openDocument(cu1, cu1.getSource(), 1); List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics"); assertEquals(1, diagnosticReports.size()); PublishDiagnosticsParams diagParam = diagnosticReports.get(0); assertEquals(2, diagParam.getDiagnostics().size()); assertEquals("Foo.java is a non-project file, only syntax errors are reported", diagParam.getDiagnostics().get(0).getMessage()); DiagnosticsCommand.refreshDiagnostics(JDTUtils.toURI(cu1), "thisFile", false); diagnosticReports = getClientRequests("publishDiagnostics"); assertEquals(2, diagnosticReports.size()); diagParam = diagnosticReports.get(1); assertEquals(4, diagParam.getDiagnostics().size()); assertEquals("Foo.java is a non-project file, only JDK classes are added to its build path", diagParam.getDiagnostics().get(0).getMessage()); assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(1).getMessage()); assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(2).getMessage()); assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(3).getMessage()); }
Example #28
Source File: FormatterHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testDocumentFormattingWithCustomOption() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "@Deprecated package org.sample;\n\n" + "public class Baz {\n"+ " /**Java doc @param a some parameter*/\n"+ "\tvoid foo(int a){;;\n"+ "}\n"+ "}\n" //@formatter:on ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(2, true); options.putNumber("org.eclipse.jdt.core.formatter.blank_lines_before_package", Integer.valueOf(2)); options.putString("org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package", "do not insert"); options.putBoolean("org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line", Boolean.TRUE); DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options); preferenceManager.getPreferences().setJavaFormatComments(false); List<? extends TextEdit> edits = server.formatting(params).get(); assertNotNull(edits); String expectedText = "\n"+ "\n"+ "@Deprecated package org.sample;\n"+ "\n"+ "public class Baz {\n"+ " /**Java doc @param a some parameter*/\n"+ " void foo(int a) {\n"+ " ;\n"+ " ;\n"+ " }\n"+ "}\n"; String newText = TextEditUtil.apply(unit, edits); preferenceManager.getPreferences().setJavaFormatComments(true); assertEquals(expectedText, newText); }
Example #29
Source File: FormatterHandlerTest.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Test public void testDocumentFormatting() throws Exception { ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", //@formatter:off "package org.sample ;\n\n" + " public class Baz { String name;}\n" //@formatter:on ); String uri = JDTUtils.toURI(unit); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri); FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options); List<? extends TextEdit> edits = server.formatting(params).get(); assertNotNull(edits); //@formatter:off String expectedText = "package org.sample;\n" + "\n" + "public class Baz {\n" + " String name;\n" + "}\n"; //@formatter:on String newText = TextEditUtil.apply(unit, edits); assertEquals(expectedText, newText); }
Example #30
Source File: JavaDebugDelegateCommandHandler.java From java-debug with Eclipse Public License 1.0 | 5 votes |
private boolean isOnClasspath(List<Object> arguments) throws DebugException { if (arguments.size() < 1) { throw new DebugException("No file uri is specified."); } String uri = (String) arguments.get(0); final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri); if (unit == null || unit.getResource() == null || !unit.getResource().exists()) { throw new DebugException("The compilation unit " + uri + " doesn't exist."); } IJavaProject javaProject = unit.getJavaProject(); return javaProject == null || javaProject.isOnClasspath(unit); }