Java Code Examples for org.eclipse.jdt.core.IJavaProject#setRawClasspath()

The following examples show how to use org.eclipse.jdt.core.IJavaProject#setRawClasspath() . 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: FixProjectsUtils.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 6 votes vote down vote up
public static void setClasspath(IClasspathEntry[] classpath, IJavaProject javaProject, IProgressMonitor monitor) throws JavaModelException
{
	// backup .classpath
	File classPathFileBak = javaProject.getProject().getFile(".classpath.bak").getLocation().toFile();
	if (!classPathFileBak.exists())
	{
		File classPathFile = javaProject.getProject().getFile(".classpath").getLocation().toFile();
		try {
			Files.copy(Paths.get(classPathFile.getAbsolutePath()), Paths.get(classPathFileBak.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
		}
		catch (IOException e) {
			// can't back up file but we should continue anyway
			Activator.log("Failed to backup classfile [" + classPathFile.getAbsolutePath() + "]");
		}
	}
	javaProject.setRawClasspath(classpath, monitor);	
}
 
Example 2
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.17
 */
public static void addToClasspath(IJavaProject javaProject, IClasspathEntry newClassPathEntry, boolean build)
		throws JavaModelException {
	IClasspathEntry[] newClassPath;
	IClasspathEntry[] classPath = javaProject.getRawClasspath();
	for (IClasspathEntry classPathEntry : classPath) {
		if (classPathEntry.equals(newClassPathEntry)) {
			return;
		}
	}
	newClassPath = new IClasspathEntry[classPath.length + 1];
	System.arraycopy(classPath, 0, newClassPath, 1, classPath.length);
	newClassPath[0] = newClassPathEntry;
	javaProject.setRawClasspath(newClassPath, null);
	if (build) {
		waitForBuild();
	}
}
 
Example 3
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Configures the classpath of the project before refactoring.
 *
 * @param project
 *            the java project
 * @param root
 *            the package fragment root to refactor
 * @param folder
 *            the temporary source folder
 * @param monitor
 *            the progress monitor to use
 * @throws IllegalStateException
 *             if the plugin state location does not exist
 * @throws CoreException
 *             if an error occurs while configuring the class path
 */
private static void configureClasspath(final IJavaProject project, final IPackageFragmentRoot root, final IFolder folder, final IProgressMonitor monitor) throws IllegalStateException, CoreException {
	try {
		monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 200);
		final IClasspathEntry entry= root.getRawClasspathEntry();
		final IClasspathEntry[] entries= project.getRawClasspath();
		final List<IClasspathEntry> list= new ArrayList<IClasspathEntry>();
		list.addAll(Arrays.asList(entries));
		final IFileStore store= EFS.getLocalFileSystem().getStore(JavaPlugin.getDefault().getStateLocation().append(STUB_FOLDER).append(project.getElementName()));
		if (store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists())
			store.delete(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
		store.mkdir(EFS.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
		folder.createLink(store.toURI(), IResource.NONE, new SubProgressMonitor(monitor, 25, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
		addExclusionPatterns(list, folder.getFullPath());
		for (int index= 0; index < entries.length; index++) {
			if (entries[index].equals(entry))
				list.add(index, JavaCore.newSourceEntry(folder.getFullPath()));
		}
		project.setRawClasspath(list.toArray(new IClasspathEntry[list.size()]), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
	} finally {
		monitor.done();
	}
}
 
Example 4
Source File: AbstractSarlUiTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void addToClasspath(IJavaProject javaProject,
		boolean autobuild,
		Iterable<IClasspathEntry> newClassPathEntries) throws JavaModelException {
	List<IClasspathEntry> newClassPath = new ArrayList<>(Arrays.asList(javaProject.getRawClasspath()));
	for (IClasspathEntry classPathEntry : newClassPathEntries) {
		if (!newClassPath.contains(classPathEntry)) {
			newClassPath.add(classPathEntry);
		}
	}
	IClasspathEntry[] classPath = new IClasspathEntry[newClassPath.size()];
	newClassPath.toArray(classPath);
	javaProject.setRawClasspath(classPath, null);
	if (autobuild) {
		helper().awaitAutoBuild();
	}
}
 
Example 5
Source File: Bug486584Test.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNoFullBuildWhenClasspathNotReallyChanged_1() throws CoreException, IOException, InterruptedException {
	IJavaProject project = setupProject();
	IFile libaryFile = copyAndGetXtendExampleJar(project);
	IPath rawLocation = libaryFile.getRawLocation();
	IClasspathEntry libraryEntry = JavaCore.newLibraryEntry(rawLocation, null, null);
	addToClasspath(project, libraryEntry);
	build();
	assertFalse(getEvents().isEmpty());
	getEvents().clear();
	project.setRawClasspath(project.getRawClasspath(), null);
	project.getProject().getFile("src/dummy.txt").create(new StringInputStream(""), false, null);
	project.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
	build();
	assertEquals(0, getEvents().size());
}
 
Example 6
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void updateBinaries(IJavaProject javaProject, Map<Path, IPath> libraries, IProgressMonitor monitor) throws CoreException {
	if (monitor.isCanceled()) {
		return;
	}
	IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
	List<IClasspathEntry> newEntries = Arrays.stream(rawClasspath).filter(cpe -> cpe.getEntryKind() != IClasspathEntry.CPE_LIBRARY).collect(Collectors.toCollection(ArrayList::new));

	for (Map.Entry<Path, IPath> library : libraries.entrySet()) {
		if (monitor.isCanceled()) {
			return;
		}
		IPath binary = new org.eclipse.core.runtime.Path(library.getKey().toString());
		IPath source = library.getValue();
		IClasspathEntry newEntry = JavaCore.newLibraryEntry(binary, source, null);
		JavaLanguageServerPlugin.logInfo(">> Adding " + binary + " to the classpath");
		newEntries.add(newEntry);
	}
	IClasspathEntry[] newClasspath = newEntries.toArray(new IClasspathEntry[newEntries.size()]);
	if (!Arrays.equals(rawClasspath, newClasspath)) {
		javaProject.setRawClasspath(newClasspath, monitor);
	}
}
 
Example 7
Source File: Bug486584Test.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNoFullBuildIfAttachmentChangeOnly() throws CoreException, InterruptedException {
	IJavaProject project = setupProject();
	assertFalse(getEvents().isEmpty());
	getEvents().clear();
	IFile libaryFile = copyAndGetXtendExampleJar(project);
	IClasspathEntry libraryEntry = JavaCore.newLibraryEntry(libaryFile.getFullPath(), null, null);
	addToClasspath(project, libraryEntry);
	build();
	assertEquals(1, getEvents().size());
	Event singleEvent = getEvents().get(0);
	ImmutableList<Delta> deltas = singleEvent.getDeltas();
	assertEquals(1, deltas.size());
	getEvents().clear();
	IClasspathEntry[] classpath = project.getRawClasspath();
	for (int i = 0; i < classpath.length; ++i) {
		IPath entryPath = classpath[i].getPath();
		if (libraryEntry.getPath().equals(entryPath)) {
			IClasspathEntry[] newClasspath = new IClasspathEntry[classpath.length];
			System.arraycopy(classpath, 0, newClasspath, 0, classpath.length);

			classpath[i] = JavaCore.newLibraryEntry(libaryFile.getFullPath(), libaryFile.getFullPath(), null);
			project.setRawClasspath(classpath, null);

		}
	}
	build();
	assertEquals(0, getEvents().size());
}
 
Example 8
Source File: IDEOpenSampleReportAction.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private void setClasspath( IProject project ) throws JavaModelException,
		CoreException
{
	IJavaProject javaProject = JavaCore.create( project );

	IPath path = project.getFullPath( ).append( "bin" ); //$NON-NLS-1$
	javaProject.setOutputLocation( path, null );

	IClasspathEntry[] entries = getClassPathEntries( project );
	javaProject.setRawClasspath( entries, null );
}
 
Example 9
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void addToClasspath(IJavaProject jproject, IClasspathEntry cpe) throws JavaModelException {
    IClasspathEntry[] oldEntries = jproject.getRawClasspath();
    for (int i = 0; i < oldEntries.length; i++) {
        if (oldEntries[i].equals(cpe)) {
            return;
        }
    }
    int nEntries = oldEntries.length;
    IClasspathEntry[] newEntries = new IClasspathEntry[nEntries + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, nEntries);
    newEntries[nEntries] = cpe;
    jproject.setRawClasspath(newEntries, null);
}
 
Example 10
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static void removeFromClasspath(IJavaProject from, int entryKind, IPath path) throws CoreException {
	List<IClasspathEntry> classpath = Lists.newArrayList(from.getRawClasspath());
	Iterator<IClasspathEntry> iterator = classpath.iterator();
	while (iterator.hasNext()) {
		IClasspathEntry entry = iterator.next();
		if (entry.getEntryKind() == entryKind) {
			if (entry.getPath().equals(path))
				iterator.remove();
		}
	}
	from.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), monitor());
}
 
Example 11
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean addSourcePath(IPath sourcePath, IPath[] exclusionPaths, IJavaProject project) throws CoreException {
	IClasspathEntry[] existingEntries = project.getRawClasspath();
	List<IPath> parentSrcPaths = new ArrayList<>();
	List<IPath> exclusionPatterns = new ArrayList<>();
	for (IClasspathEntry entry : existingEntries) {
		if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
			if (entry.getPath().equals(sourcePath)) {
				return false;
			} else if (entry.getPath().isPrefixOf(sourcePath)) {
				parentSrcPaths.add(entry.getPath());
			} else if (sourcePath.isPrefixOf(entry.getPath())) {
				exclusionPatterns.add(entry.getPath().makeRelativeTo(sourcePath).addTrailingSeparator());
			}
		}
	}

	if (!parentSrcPaths.isEmpty()) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, Messages
				.format("Cannot add the folder ''{0}'' to the source path because it''s parent folder is already in the source path of the project ''{1}''.", new String[] { sourcePath.toOSString(), project.getProject().getName() })));
	}

	if (exclusionPaths != null) {
		for (IPath exclusion : exclusionPaths) {
			if (sourcePath.isPrefixOf(exclusion) && !sourcePath.equals(exclusion)) {
				exclusionPatterns.add(exclusion.makeRelativeTo(sourcePath).addTrailingSeparator());
			}
		}
	}

	IClasspathEntry[] newEntries = new IClasspathEntry[existingEntries.length + 1];
	System.arraycopy(existingEntries, 0, newEntries, 0, existingEntries.length);
	newEntries[newEntries.length - 1] = JavaCore.newSourceEntry(sourcePath, exclusionPatterns.toArray(new IPath[0]));
	project.setRawClasspath(newEntries, project.getOutputLocation(), null);
	return true;
}
 
Example 12
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static void addToClasspath(IJavaProject javaProject, IClasspathEntry newClassPathEntry)
		throws JavaModelException {
	IClasspathEntry[] newClassPath;
	IClasspathEntry[] classPath = javaProject.getRawClasspath();
	for (IClasspathEntry classPathEntry : classPath) {
		if (classPathEntry.equals(newClassPathEntry)) {
			return;
		}
	}
	newClassPath = new IClasspathEntry[classPath.length + 1];
	System.arraycopy(classPath, 0, newClassPath, 1, classPath.length);
	newClassPath[0] = newClassPathEntry;
	javaProject.setRawClasspath(newClassPath, null);
	reallyWaitForAutoBuild();
}
 
Example 13
Source File: SourceAttachmentCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void updateProjectClasspath(IJavaProject javaProject, IClasspathEntry newEntry, IProgressMonitor monitor) throws JavaModelException {
	List<IClasspathEntry> newEntries = updateElements(javaProject.getRawClasspath(), newEntry, (entry) -> {
		return entry.getEntryKind() == newEntry.getEntryKind() && entry.getPath().equals(newEntry.getPath());
	});
	JavaLanguageServerPlugin.logInfo("Update source attachment " + (newEntry.getSourceAttachmentPath() == null ? null : newEntry.getSourceAttachmentPath().toOSString()) + " to the file " + newEntry.getPath().toOSString());
	javaProject.setRawClasspath(newEntries.toArray(new IClasspathEntry[0]), monitor);
}
 
Example 14
Source File: JDTAwareEclipseResourceFileSystemAccess2.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void addClasspathEntry(IContainer folder, IJavaProject project) throws JavaModelException {
	IClasspathEntry srcFolderClasspathEntry = JavaCore.newSourceEntry(folder.getFullPath());
	IClasspathEntry[] classPath = project.getRawClasspath();
	IClasspathEntry[] newClassPath = new IClasspathEntry[classPath.length + 1];
	System.arraycopy(classPath, 0, newClassPath, 0, classPath.length);
	newClassPath[newClassPath.length - 1] = srcFolderClasspathEntry;
	project.setRawClasspath(newClassPath, getMonitor());
}
 
Example 15
Source File: BuildPathSupport.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void updateProjectClasspath(Shell shell, IJavaProject jproject, IClasspathEntry newEntry, String[] changedAttributes, IProgressMonitor monitor) throws JavaModelException {
	IClasspathEntry[] oldClasspath= jproject.getRawClasspath();
	int nEntries= oldClasspath.length;
	ArrayList<IClasspathEntry> newEntries= new ArrayList<IClasspathEntry>(nEntries + 1);
	int entryKind= newEntry.getEntryKind();
	IPath jarPath= newEntry.getPath();
	boolean found= false;
	for (int i= 0; i < nEntries; i++) {
		IClasspathEntry curr= oldClasspath[i];
		if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) {
			// add modified entry
			newEntries.add(getUpdatedEntry(curr, newEntry, changedAttributes, jproject));
			found= true;
		} else {
			newEntries.add(curr);
		}
	}
	if (!found) {
		if (!putJarOnClasspathDialog(shell)) {
			return;
		}
		// add new
		newEntries.add(newEntry);
	}
	IClasspathEntry[] newClasspath= newEntries.toArray(new IClasspathEntry[newEntries.size()]);
	jproject.setRawClasspath(newClasspath, monitor);
}
 
Example 16
Source File: AbstractSarlUiTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public void addToClasspath(IJavaProject javaProject, IClasspathEntry newClassPathEntry) throws JavaModelException {
	IClasspathEntry[] newClassPath;
	IClasspathEntry[] classPath = javaProject.getRawClasspath();
	for (IClasspathEntry classPathEntry : classPath) {
		if (classPathEntry.equals(newClassPathEntry)) {
			return;
		}
	}
	newClassPath = new IClasspathEntry[classPath.length + 1];
	System.arraycopy(classPath, 0, newClassPath, 1, classPath.length);
	newClassPath[0] = newClassPathEntry;
	javaProject.setRawClasspath(newClassPath, null);
	helper().awaitAutoBuild();
}
 
Example 17
Source File: LoggedCreateTargetQueries.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void createPackageFragmentRoot(IPackageFragmentRoot root) throws CoreException {
	final IJavaProject project= root.getJavaProject();
	if (!project.exists()) {
		//				createJavaProject(project.getProject());
	}
	final IFolder folder= project.getProject().getFolder(root.getElementName());
	if (!folder.exists()) {
		ResourceUtil.createFolder(folder, true, true, new NullProgressMonitor());
	}
	final List<IClasspathEntry> list= Arrays.asList(project.getRawClasspath());
	list.add(JavaCore.newSourceEntry(folder.getFullPath()));
	project.setRawClasspath(list.toArray(new IClasspathEntry[list.size()]), new NullProgressMonitor());
}
 
Example 18
Source File: ClasspathUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Use this method to set the raw classpath of an IJavaProject. This method
 * should be used in favor of IJavaProject.setRawClasspath(IJavaProject,
 * IClasspathEntry [], IProgressMonitor) due to an odd interaction with
 * certain source control systems, such as Perforce. See the following URL for
 * more information: <a
 * href="http://bugs.eclipse.org/bugs/show_bug.cgi?id=243692"
 * >http://bugs.eclipse.org/bugs/show_bug.cgi?id=243692</a>
 *
 * <p>
 * Note that this method is asynchronous, so the caller will regain control
 * immediately, and the raw classpath will be set at some future time. Right
 * now, there is no way to tell the caller when the operation has completed.
 * If this becomes a concern in the future, a callback parameter can be
 * introduced.
 * </p>
 *
 * <p>
 * This method does not accept an IProgressMonitor, unlike the equivalent
 * method in IJavaProject, because there is an implicit progress monitor
 * provided when running the setRawClasspath operation as a task. In the
 * future, this method could be modified to accept a user-specified progress
 * monitor.
 * </p>
 *
 * NOTE: If you are already running in a job, you probably don't want to call
 * this method.
 */
public static void setRawClasspath(final IJavaProject javaProject,
    final IClasspathEntry[] newClasspathEntries) {

  IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
    @Override
    public void run(IProgressMonitor monitor) throws CoreException,
        OperationCanceledException {
      javaProject.setRawClasspath(newClasspathEntries, monitor);
    }
  };

  WorkbenchRunnableAdapter op = new WorkbenchRunnableAdapter(runnable);
  op.runAsUserJob("Updating classpath of Java project '"
      + javaProject.getProject().getName() + "'", null);
}
 
Example 19
Source File: PerformanceTestProjectSetup.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public static IJavaProject createJavaProject(
			final String projectName, 
			String[] projectNatures) {

		IProject project = null;
		IJavaProject javaProject = null;
		try {
			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			project = workspace.getRoot().getProject(projectName);
			deleteProject(project);

			javaProject = JavaCore.create(project);
			IProjectDescription projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(
					projectName);
			project.create(projectDescription, null);
			List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
			projectDescription.setNatureIds(projectNatures);

			final ICommand java = projectDescription.newCommand();
			java.setBuilderName(JavaCore.BUILDER_ID);

			final ICommand manifest = projectDescription.newCommand();
			manifest.setBuilderName("org.eclipse.pde.ManifestBuilder");

			final ICommand schema = projectDescription.newCommand();
			schema.setBuilderName("org.eclipse.pde.SchemaBuilder");

			projectDescription.setBuildSpec(new ICommand[] { java, manifest, schema });

			project.open(null);
			project.setDescription(projectDescription, null);

			classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5")));
			classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins")));

			javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]),
					null);
			
			makeJava8Compliant(javaProject);

			javaProject.setOutputLocation(new Path("/" + projectName + "/bin"), null);
			createManifest(projectName, project);
//			project.build(IncrementalProjectBuilder.FULL_BUILD, null);
			refreshExternalArchives(javaProject);
			refresh(javaProject);
		}
		catch (final Exception exception) {
			throw new RuntimeException(exception);
		}
		return javaProject ;
	}
 
Example 20
Source File: InternalImpl.java    From saros with GNU General Public License v2.0 3 votes vote down vote up
@Override
public void createJavaProject(String projectName) throws RemoteException {

  log.trace("creating java project: " + projectName);

  IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);

  try {

    project.create(null);
    project.open(null);

    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] {JavaCore.NATURE_ID});
    project.setDescription(description, null);

    IJavaProject javaProject = JavaCore.create(project);

    Set<IClasspathEntry> entries = new HashSet<IClasspathEntry>();

    entries.add(JavaCore.newSourceEntry(javaProject.getPath().append("src"), new IPath[0]));

    IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();

    LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);

    for (LibraryLocation element : locations) {
      entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
    }

    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

  } catch (CoreException e) {
    log.error("unable to create java project '" + projectName + "' :" + e.getMessage(), e);
    throw new RemoteException(e.getMessage(), e.getCause());
  }
}