public void testEditOutputFolder04RemoveProjectAndExcludeOutput() throws Exception { fJavaProject = createProject(null); // Use the old behavior in order to test the fallback code. Set to ERROR since 3.8. fJavaProject.setOption( JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.IGNORE); JavaProjectHelper.addSourceContainer( fJavaProject, null, new IPath[] {new Path("src1/"), new Path("src2/")}); IPackageFragmentRoot src1 = JavaProjectHelper.addSourceContainer(fJavaProject, "src1"); IPackageFragmentRoot src2 = JavaProjectHelper.addSourceContainer(fJavaProject, "src2"); IPath projectPath = fJavaProject.getProject().getFullPath(); IPath outputPath = projectPath.append("src2").append(DEFAULT_OUTPUT_FOLDER_NAME); CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); CPListElement element = cpProject.getCPElement( CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status = ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); assertTrue(status.getMessage(), status.getSeverity() == IStatus.INFO); BuildpathDelta delta = ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder( delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)); assertDeltaRemovedEntries(delta, new IPath[] {fJavaProject.getPath()}); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); assertTrue( "Default output folder was not set to bin", fJavaProject .getOutputLocation() .equals(fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME))); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 3); IClasspathEntry entry = classpathEntries[1]; assertTrue(src1.getRawClasspathEntry() == entry); IPath location = entry.getOutputLocation(); assertTrue( "Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); entry = classpathEntries[2]; assertTrue(src2.getRawClasspathEntry() == entry); IPath[] exclusionPatterns = entry.getExclusionPatterns(); assertTrue(exclusionPatterns.length == 1); assertTrue(exclusionPatterns[0].toString().equals("bin/")); }
public void testRemoveFromBuildpathBug153299Lib() throws Exception { fJavaProject = createProject(null); IPackageFragmentRoot p01 = JavaProjectHelper.addSourceContainer(fJavaProject, null, new IPath[] {new Path("src1/")}); CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); IPath[] jarPaths = new IPath[] {JavaProjectHelper.MYLIB.makeAbsolute()}; ClasspathModifier.addExternalJars(jarPaths, cpProject); ClasspathModifier.commitClassPath(cpProject, null); cpProject = CPJavaProject.createFromExisting(fJavaProject); BuildpathDelta delta = ClasspathModifier.removeFromBuildpath( new CPListElement[] { CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject) }, cpProject); assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder(delta, fJavaProject.getPath()); assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()}); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 2); }
public void testRemoveFromBuildpathBug153299Src() throws Exception { fJavaProject = createProject(null); // Use the old behavior in order to test the fallback code. Set to ERROR since 3.8. fJavaProject.setOption( JavaCore.CORE_OUTPUT_LOCATION_OVERLAPPING_ANOTHER_SOURCE, JavaCore.IGNORE); IPackageFragmentRoot p01 = JavaProjectHelper.addSourceContainer(fJavaProject, null, new IPath[] {new Path("src1/")}); JavaProjectHelper.addSourceContainer(fJavaProject, "src1"); CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); BuildpathDelta delta = ClasspathModifier.removeFromBuildpath( new CPListElement[] { CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject) }, cpProject); assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder( delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)); assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()}); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 2); }
public void testRemoveFromBuildpath01RemoveLibs() throws Exception { fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME); IPath[] jarPaths = new IPath[] { JavaProjectHelper.MYLIB.makeAbsolute(), JavaProjectHelper.JUNIT_SRC_381.makeAbsolute() }; CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); BuildpathDelta delta = ClasspathModifier.addExternalJars(jarPaths, cpProject); ClasspathModifier.commitClassPath(cpProject, null); CPListElement[] toRemove = {delta.getAddedEntries().get(0), delta.getAddedEntries().get(1)}; delta = ClasspathModifier.removeFromBuildpath(toRemove, cpProject); assertDeltaResources(delta, new IPath[0], new IPath[0], new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder( delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)); assertDeltaRemovedEntries(delta, new IPath[] {toRemove[0].getPath(), toRemove[1].getPath()}); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 1); }
public void testRemoveFromBuildpath01() throws Exception { fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME); IPackageFragmentRoot src1 = JavaProjectHelper.addSourceContainer(fJavaProject, "src1"); IPackageFragmentRoot src2 = JavaProjectHelper.addSourceContainer(fJavaProject, "src2"); CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); CPListElement[] toRemove = new CPListElement[2]; toRemove[0] = CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject); toRemove[1] = CPListElement.createFromExisting(src2.getRawClasspathEntry(), fJavaProject); BuildpathDelta delta = ClasspathModifier.removeFromBuildpath(toRemove, cpProject); assertDeltaResources( delta, new IPath[0], new IPath[] {src1.getPath(), src2.getPath()}, new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder( delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)); assertDeltaRemovedEntries(delta, new IPath[] {src1.getPath(), src2.getPath()}); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 1); }
/* * (non-Javadoc) * @see org.eclipse.jdt.core.ClasspathContainerInitializer#getComparisonID(org.eclipse.core.runtime.IPath, org.eclipse.jdt.core.IJavaProject) */ @Override public Object getComparisonID(final IPath containerPath, final IJavaProject project) { if (containerPath == null || project == null) { return null; } return containerPath.segment(0) + "/" + project.getPath().segment(0); // $NON-NLS-1$ }
private IClasspathEntry[] createClasspathEntries(IJavaProject javaProject) { IPath srcPath1 = javaProject.getPath().append("src/main/java"); IPath srcPath2 = javaProject.getPath().append("src/main/resources"); IPath srcPath3 = javaProject.getPath().append("src/test/java"); IPath srcPath4 = javaProject.getPath().append("src/test/resources"); IPath[] javaPath = new IPath[] {new Path("**/*.java")}; IPath testOutputLocation = javaProject.getPath().append("target/test-classes"); IClasspathEntry[] entries = { JavaCore.newSourceEntry(srcPath1, javaPath, null, null), JavaCore.newSourceEntry(srcPath2, javaPath), JavaCore.newSourceEntry(srcPath3, javaPath, null, testOutputLocation), JavaCore.newSourceEntry(srcPath4, javaPath, testOutputLocation), JavaRuntime.getDefaultJREContainerEntry() }; return entries; }
@Override public void replay() throws Exception { IJavaProject javaProject = JavaProjectsUpkeeper.findOrCreateJavaProject(projectName); // First, remove all references from other projects to this project for (IJavaProject someJavaProject : JavaProjectsUpkeeper.getAllJavaProjects()) { JavaProjectHelper.removeFromClasspath(someJavaProject, javaProject.getPath()); } // Next, add this project to projects that are currently referencing it for (String referencingProjectName : referencingProjectNames) { IJavaProject referencingProject = JavaProjectsUpkeeper.findOrCreateJavaProject(referencingProjectName); JavaProjectHelper.addRequiredProject(referencingProject, javaProject); } }
public void testEditOutputFolderBug154044() throws Exception { fJavaProject = createProject(DEFAULT_OUTPUT_FOLDER_NAME); IPackageFragmentRoot src1 = JavaProjectHelper.addSourceContainer(fJavaProject, "src1"); IPath projectPath = fJavaProject.getProject().getFullPath(); IPath oldOutputPath = projectPath.append("src1").append("sub").append(DEFAULT_OUTPUT_FOLDER_NAME); CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); CPListElement element = cpProject.getCPElement( CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); ClasspathModifier.setOutputLocation(element, oldOutputPath, false, cpProject); ClasspathModifier.commitClassPath(cpProject, null); IPath outputPath = projectPath.append("src1").append("sub").append("newBin"); cpProject = CPJavaProject.createFromExisting(fJavaProject); element = cpProject.getCPElement( CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status = ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); assertTrue(status.getMessage(), status.isOK()); BuildpathDelta delta = ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources( delta, new IPath[] {outputPath}, new IPath[] {oldOutputPath}, new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder( delta, fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)); assertDeltaRemovedEntries(delta, new IPath[0]); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 2); IClasspathEntry entry = classpathEntries[1]; assertTrue(src1.getRawClasspathEntry() == entry); IPath location = entry.getOutputLocation(); assertTrue( "Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); IPath[] exclusionPatterns = entry.getExclusionPatterns(); assertTrue(exclusionPatterns.length == 1); assertTrue( exclusionPatterns[0].toString(), exclusionPatterns[0].toString().equals("sub/newBin/")); }
/** * Tests if the used type is contained in the project containing the type use. * * @param tbinding the type binding of the type use * @return <code>true</code> if the used type is contained in the project, otherwise <code>false * </code> */ private boolean isInProject(ITypeBinding tbinding) { IJavaProject project = jproject.getJavaProject(); if (project == null) { return true; } try { IType type = project.findType(tbinding.getQualifiedName()); if (type != null) { String pdir = project.getPath().toString(); String tname = type.getPath().toString(); return pdir != null && tname != null && tname.startsWith(pdir); } } catch (JavaModelException e) { return false; } return false; }
@Test public void shouldConfigureSimpleProject() throws JavaModelException, IOException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); File workspaceRoot = root.getFullPath().toFile(); File projectRoot = new File(workspaceRoot, "myProject"); projectRoot.mkdir(); File sourceFolder = new File(projectRoot, "src"); sourceFolder.mkdir(); File testFolder = new File(projectRoot, "test"); testFolder.mkdir(); File outputFolder = new File(projectRoot, "bin"); outputFolder.mkdir(); IJavaProject project = mock(IJavaProject.class); Properties sonarProperties = new Properties(); when(project.getOption(JavaCore.COMPILER_SOURCE, true)).thenReturn("1.6"); when(project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)).thenReturn("1.6"); when(project.getPath()).thenReturn(new Path(projectRoot.getAbsolutePath())); IClasspathEntry[] cpes = new IClasspathEntry[] { createCPE(IClasspathEntry.CPE_SOURCE, sourceFolder), createCPE(IClasspathEntry.CPE_SOURCE, testFolder) }; when(project.getResolvedClasspath(true)).thenReturn(cpes); when(project.getOutputLocation()).thenReturn(new Path(outputFolder.getAbsolutePath())); configurator.configureJavaProject(project, sonarProperties); // TODO Find a way to mock a project inside Eclipse // assertTrue(sonarProperties.containsKey("sonar.sources")); // assertThat(sonarProperties.getProperty("sonar.sources"), is(sourceFolder.getPath())); // assertTrue(sonarProperties.containsKey("sonar.tests")); // assertThat(sonarProperties.getProperty("sonar.tests"), is(testFolder.getPath())); // assertTrue(sonarProperties.containsKey("sonar.binaries")); // assertThat(sonarProperties.getProperty("sonar.binaries"), is(outputFolder.getPath())); }
public void testRemoveFromBuildpath01RemoveProject() throws Exception { fJavaProject = createProject(null); IPackageFragmentRoot p01 = JavaProjectHelper.addSourceContainer(fJavaProject, null); CPJavaProject cpProject = CPJavaProject.createFromExisting(fJavaProject); BuildpathDelta delta = ClasspathModifier.removeFromBuildpath( new CPListElement[] { CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject) }, cpProject); assertDeltaResources(delta, new IPath[0], new IPath[] {}, new IPath[0], new IPath[0]); assertDeltaDefaultOutputFolder(delta, fJavaProject.getPath()); assertDeltaRemovedEntries(delta, new IPath[] {p01.getPath()}); assertDeltaAddedEntries(delta, new IPath[0]); ClasspathModifier.commitClassPath(cpProject, null); IClasspathEntry[] classpathEntries = fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 1); }
static final void updateClasspathEntries( Map<IPath, String> oldLocationMap, IProgressMonitor monitor) throws JavaModelException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IJavaProject[] javaProjects = JavaCore.create(root).getJavaProjects(); try { monitor.beginTask(CorextMessages.JavaDocLocations_migrate_operation, javaProjects.length); for (int i = 0; i < javaProjects.length; i++) { IJavaProject project = javaProjects[i]; String projectJavadoc = oldLocationMap.get(project.getPath()); if (projectJavadoc != null) { try { setProjectJavadocLocation(project, projectJavadoc); } catch (CoreException e) { // ignore } } IClasspathEntry[] rawClasspath = project.getRawClasspath(); boolean hasChange = false; for (int k = 0; k < rawClasspath.length; k++) { IClasspathEntry updated = getConvertedEntry(rawClasspath[k], project, oldLocationMap); if (updated != null) { rawClasspath[k] = updated; hasChange = true; } } if (hasChange) { project.setRawClasspath(rawClasspath, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } } } finally { monitor.done(); } }
public void testASTRewriteExample() throws Exception { // create a new project IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("Test"); project.create(null); project.open(null); try { // set the Java nature and Java build path IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] {JavaCore.NATURE_ID}); project.setDescription(description, null); IJavaProject javaProject = JavaCore.create(project); // build path is: project as source folder and JRE container IClasspathEntry[] cpentry = new IClasspathEntry[] { JavaCore.newSourceEntry(javaProject.getPath()), JavaRuntime.getDefaultJREContainerEntry() }; javaProject.setRawClasspath(cpentry, javaProject.getPath(), null); Map<String, String> options = new HashMap<>(); options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); javaProject.setOptions(options); // create a test file IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(project); IPackageFragment pack1 = root.createPackageFragment("test1", false, null); StringBuffer buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" while (--i > 0) {\n"); buf.append(" System.beep();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); // create an AST ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(cu); parser.setResolveBindings(false); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); AST ast = astRoot.getAST(); // create the descriptive ast rewriter ASTRewrite rewrite = ASTRewrite.create(ast); // get the block node that contains the statements in the method body TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0); MethodDeclaration methodDecl = typeDecl.getMethods()[0]; Block block = methodDecl.getBody(); // create new statements to insert MethodInvocation newInv1 = ast.newMethodInvocation(); newInv1.setName(ast.newSimpleName("bar1")); Statement newStatement1 = ast.newExpressionStatement(newInv1); MethodInvocation newInv2 = ast.newMethodInvocation(); newInv2.setName(ast.newSimpleName("bar2")); Statement newStatement2 = ast.newExpressionStatement(newInv2); // describe that the first node is inserted as first statement in block, the other one as last // statement // note: AST is not modified by this ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); listRewrite.insertFirst(newStatement1, null); listRewrite.insertLast(newStatement2, null); // evaluate the text edits corresponding to the described changes. AST and CU still // unmodified. TextEdit res = rewrite.rewriteAST(); // apply the text edits to the compilation unit Document document = new Document(cu.getSource()); res.apply(document); cu.getBuffer().setContents(document.get()); // test result String preview = cu.getSource(); buf = new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" bar1();\n"); buf.append(" while (--i > 0) {\n"); buf.append(" System.beep();\n"); buf.append(" }\n"); buf.append(" bar2();\n"); buf.append(" }\n"); buf.append("}\n"); assertEquals(preview, buf.toString()); } finally { project.delete(true, null); } }
private void createOutputLocation(IJavaProject javaProject) throws JavaModelException { IPath targetPath = javaProject.getPath().append("target/classes"); javaProject.setOutputLocation(targetPath, null); }
private void collectProposals( IJavaProject project, String name, Collection<DefaultClasspathFixProposal> proposals) throws CoreException { int idx = name.lastIndexOf('.'); char[] packageName = idx != -1 ? name.substring(0, idx).toCharArray() : null; // no package provided char[] typeName = name.substring(idx + 1).toCharArray(); if (typeName.length == 1 && typeName[0] == '*') { typeName = null; } IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); ArrayList<TypeNameMatch> res = new ArrayList<TypeNameMatch>(); TypeNameMatchCollector requestor = new TypeNameMatchCollector(res); int matchMode = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; new SearchEngine() .searchAllTypeNames( packageName, matchMode, typeName, matchMode, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); if (res.isEmpty()) { return; } HashSet<Object> addedClaspaths = new HashSet<Object>(); for (int i = 0; i < res.size(); i++) { TypeNameMatch curr = res.get(i); IType type = curr.getType(); if (type != null) { IPackageFragmentRoot root = (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); try { IClasspathEntry entry = root.getRawClasspathEntry(); if (entry == null) { continue; } IJavaProject other = root.getJavaProject(); int entryKind = entry.getEntryKind(); if ((entry.isExported() || entryKind == IClasspathEntry.CPE_SOURCE) && addedClaspaths.add(other)) { IClasspathEntry newEntry = JavaCore.newProjectEntry(other.getPath()); Change change = ClasspathFixProposal.newAddClasspathChange(project, newEntry); if (change != null) { String[] args = { BasicElementLabels.getResourceName(other.getElementName()), BasicElementLabels.getResourceName(project.getElementName()) }; String label = Messages.format( CorrectionMessages.ReorgCorrectionsSubProcessor_addcp_project_description, args); String desc = label; DefaultClasspathFixProposal proposal = new DefaultClasspathFixProposal( label, change, desc, IProposalRelevance.ADD_PROJECT_TO_BUILDPATH); proposals.add(proposal); } } if (entryKind == IClasspathEntry.CPE_CONTAINER) { IPath entryPath = entry.getPath(); if (isNonProjectSpecificContainer(entryPath)) { addLibraryProposal(project, root, entry, addedClaspaths, proposals); } else { try { IClasspathContainer classpathContainer = JavaCore.getClasspathContainer(entryPath, root.getJavaProject()); if (classpathContainer != null) { IClasspathEntry entryInContainer = JavaModelUtil.findEntryInContainer(classpathContainer, root.getPath()); if (entryInContainer != null) { addLibraryProposal(project, root, entryInContainer, addedClaspaths, proposals); } } } catch (CoreException e) { // ignore } } } else if ((entryKind == IClasspathEntry.CPE_LIBRARY || entryKind == IClasspathEntry.CPE_VARIABLE)) { addLibraryProposal(project, root, entry, addedClaspaths, proposals); } } catch (JavaModelException e) { // ignore } } } }