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

The following examples show how to use org.eclipse.jdt.core.IJavaProject#getProject() . 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: ASTReader.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<IMarker> buildProject(IJavaProject iJavaProject, IProgressMonitor pm) {
	ArrayList<IMarker> result = new ArrayList<IMarker>();
	try {
		IProject project = iJavaProject.getProject();
		project.refreshLocal(IResource.DEPTH_INFINITE, pm);	
		project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, pm);
		IMarker[] markers = null;
		markers = project.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
		for (IMarker marker: markers) {
			Integer severityType = (Integer) marker.getAttribute(IMarker.SEVERITY);
			if (severityType.intValue() == IMarker.SEVERITY_ERROR) {
				result.add(marker);
			}
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}
	return result;
}
 
Example 2
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Adds a source container to a IJavaProject.
 *
 * @param jproject
 *            The parent project
 * @param containerName
 *            The name of the new source container
 * @param inclusionFilters
 *            Inclusion filters to set
 * @param exclusionFilters
 *            Exclusion filters to set
 * @return The handle to the new source container
 * @throws CoreException
 *             Creation failed
 */
public static IPackageFragmentRoot addSourceContainer(IJavaProject jproject, String containerName, IPath[] inclusionFilters,
        IPath[] exclusionFilters) throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
        container = project;
    } else {
        IFolder folder = project.getFolder(containerName);
        if (!folder.exists()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        container = folder;
    }
    IPackageFragmentRoot root = jproject.getPackageFragmentRoot(container);

    IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath(), inclusionFilters, exclusionFilters, null);
    addToClasspath(jproject, cpe);
    return root;
}
 
Example 3
Source File: JdtRenameParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected List<? extends IRenameElementContext> createRenameElementContexts(Object element) {
	if (element instanceof IJavaElement) {
		IJavaElement javaElement = (IJavaElement) element;
		EClass expectedJvmType = getExpectedJvmType(javaElement);
		if (expectedJvmType != null) {
			IJavaProject javaProject = javaElement.getJavaProject();
			IProject project = javaProject.getProject();
			ResourceSet resourceSet = resourceSetProvider.get(project);
			EObject directJvmElement = jvmElementFinder.getCorrespondingJvmElement(javaElement, resourceSet);
			if (directJvmElement != null && expectedJvmType.isSuperTypeOf(directJvmElement.eClass())) {
				ResourceSet resourceSet2 = resourceSetProvider.get(project);
				EObject indexedJvmElement = jvmElementFinder.findJvmElementDeclarationInIndex(directJvmElement,
						project, resourceSet2);
				if (indexedJvmElement != null)
					// jvmElement is indexed, thus contained in an XtextResurce and likely inferred from some Xtext-based elements
					return getContextFactory(indexedJvmElement).createJdtParticipantXtextSourceContexts(
							this, indexedJvmElement);
				else if (directJvmElement instanceof JvmMember)
					// jvmElement could only be cross referenced by Xtext-based elements
					return createJdtRenameParticipantContext((JvmMember) directJvmElement, javaElement);
			}
		}
	}
	return null;
}
 
Example 4
Source File: ActionUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isOnBuildPath(IJavaElement element) {
       //fix for bug http://dev.eclipse.org/bugs/show_bug.cgi?id=20051
       if (element.getElementType() == IJavaElement.JAVA_PROJECT)
           return true;
	IJavaProject project= element.getJavaProject();
	try {
		if (!project.isOnClasspath(element))
			return false;
		IProject resourceProject= project.getProject();
		if (resourceProject == null)
			return false;
		IProjectNature nature= resourceProject.getNature(JavaCore.NATURE_ID);
		// We have a Java project
		if (nature != null)
			return true;
	} catch (CoreException e) {
	}
	return false;
}
 
Example 5
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates and adds a class folder to the class path.
 *
 * @param jproject
 *            The parent project
 * @param containerName
 * @param sourceAttachPath
 *            The source attachment path
 * @param sourceAttachRoot
 *            The source attachment root path
 * @return The handle of the created root
 * @throws CoreException
 */
public static IPackageFragmentRoot addClassFolder(IJavaProject jproject, String containerName, IPath sourceAttachPath,
        IPath sourceAttachRoot) throws CoreException {
    IProject project = jproject.getProject();
    IContainer container = null;
    if (containerName == null || containerName.length() == 0) {
        container = project;
    } else {
        IFolder folder = project.getFolder(containerName);
        if (!folder.exists()) {
            CoreUtility.createFolder(folder, false, true, null);
        }
        container = folder;
    }
    IClasspathEntry cpe = JavaCore.newLibraryEntry(container.getFullPath(), sourceAttachPath, sourceAttachRoot);
    addToClasspath(jproject, cpe);
    return jproject.getPackageFragmentRoot(container);
}
 
Example 6
Source File: NoServerArgumentProcessor.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void update(ILaunchConfigurationWorkingCopy launchConfig, IJavaProject javaProject,
    List<String> programArgs, List<String> vmArgs) throws CoreException {
  // No compiler arg processing
  if (GwtLaunchConfigurationProcessorUtilities.isCompiler(launchConfig)) {
    return;
  }

  IProject project = javaProject.getProject();
  int noServerArgIndex = programArgs.indexOf(ARG_NO_SERVER);

  int insertionIndex =
      LaunchConfigurationProcessorUtilities.removeArgsAndReturnInsertionIndex(programArgs,
          noServerArgIndex, false);
  if (!WebAppLaunchConfiguration.getRunServer(launchConfig) && GWTNature.isGWTProject(project)) {
    programArgs.add(insertionIndex, ARG_NO_SERVER);
  }
}
 
Example 7
Source File: JdtClasspathUriResolverTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testClasspathUriForFileInWorkspaceInOtherProjectRoot() throws Exception {
	_javaProject = JavaProjectSetupUtil.createJavaProject(TEST_PROJECT_NAME);
	IJavaProject otherProject = JavaProjectSetupUtil.createJavaProject(TEST_PROJECT_NAME + "2");
	try {
		JavaProjectSetupUtil.addProjectReference(_javaProject, otherProject);
		_project = otherProject.getProject();
		_project.getFolder("model").create(true, true, null);
		PluginUtil.copyFileToWorkspace(TestsActivator.getInstance(), "/testfiles/" + MODEL_FILE, _project, "model/"
				+ MODEL_FILE);
		URI classpathUri = URI.createURI("classpath:/model/" + MODEL_FILE + "#/");
		String expectedUri = "platform:/resource/" + TEST_PROJECT_NAME + "2/model/" + MODEL_FILE + "#/";
		URI normalizedUri = _resolver.resolve(_javaProject, classpathUri);
		assertResourceLoadable(classpathUri, normalizedUri, expectedUri);
	} finally {
		otherProject.getProject().delete(true, null);
	}
}
 
Example 8
Source File: OpenFileRunnable.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private List<IFile> findMatchingFilesInProjects(String pathString,
		Collection<IJavaProject> javaProjects) {
	List<IFile> files = new ArrayList<IFile>();
	for (IJavaProject javaProject : javaProjects) {
		IProject project = javaProject.getProject();
		if (!project.isOpen()) {
			continue;
		}

		try {
			IPath path = findPathFromFolder(pathString, project);
			if (path != null) {
				IFile file = project.getFile(path);
				files.add(file);
			}
		}
		catch (CoreException e) {
			EclipseMessageUtils.error("Unexpected exception accessing project members", e);
		}
	}
	return files;
}
 
Example 9
Source File: IntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testIgnoreFilesInOutputFolder() throws Exception {
	IJavaProject javaProject = createJavaProjectWithRootSrc("foo");
	createFile("foo/src/foo" + F_EXT, "object Foo ");
	createFile("foo/bar" + F_EXT, "object Bar references Foo");
	build();
	IProject project = javaProject.getProject();
	IResource resourceFromBin = project.findMember(new Path("/bin/foo" + F_EXT));
	assertNotNull(resourceFromBin);
	assertTrue(resourceFromBin instanceof IStorage);
	assertTrue(resourceFromBin.exists());
	URI fakeBinURI = URI.createPlatformResourceURI("/" + project.getName() + "/bin/foo" + F_EXT, true);
	assertFalse(serviceProvider.canHandle(fakeBinURI, (IStorage) resourceFromBin));
	assertTrue(serviceProvider.canHandle(fakeBinURI));
	IResource resourceFromRoot = project.findMember(new Path("/bar" + F_EXT));
	assertNotNull(resourceFromRoot);
	assertTrue(resourceFromRoot instanceof IStorage);
	URI fromRootURI = URI.createPlatformResourceURI("/" + project.getName() + "/bar" + F_EXT, true);
	assertFalse(serviceProvider.canHandle(fromRootURI, (IStorage) resourceFromBin));
	assertTrue(serviceProvider.canHandle(fromRootURI));
}
 
Example 10
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Change createChange(IPackageFragmentRoot root, IJavaProject destination, NewNameProposer nameProposer, INewNameQueries copyQueries) {
	IResource res= root.getResource();
	IProject destinationProject= destination.getProject();
	String newName= nameProposer.createNewName(res, destinationProject);
	INewNameQuery nameQuery;
	if (newName == null) {
		nameQuery= copyQueries.createNullQuery();
	} else {
		nameQuery= copyQueries.createNewPackageFragmentRootNameQuery(root, newName);
	}
	// TODO fix the query problem
	return new CopyPackageFragmentRootChange(root, destinationProject, nameQuery, null);
}
 
Example 11
Source File: MainTypeProcessor.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static String computeMainTypeName(ILaunchConfigurationWorkingCopy config, IJavaProject javaProject,
    ClassFinder classFinder) throws CoreException {

  IProject project = javaProject.getProject();

  ExtensionQuery<MainTypeProcessor.MainTypeFinder> extQuery = new ExtensionQuery<MainTypeProcessor.MainTypeFinder>(
      GdtPlugin.PLUGIN_ID, "mainTypeFinder", "class");
  List<ExtensionQuery.Data<MainTypeProcessor.MainTypeFinder>> mainTypeFinders = extQuery.getData();
  for (ExtensionQuery.Data<MainTypeProcessor.MainTypeFinder> mainTypeFinder : mainTypeFinders) {
    String mainTypeFromExtension = mainTypeFinder.getExtensionPointData().findMainType(javaProject);
    if (mainTypeFromExtension != null) {
      return mainTypeFromExtension;
    }
  }

  if (GWTNature.isGWTProject(project)) {
    ClassLoader classLoader = LaunchConfigurationProcessorUtilities.getClassLoaderFor(config);
    if (classFinder.exists(classLoader, MainType.GWT_DEV_MODE.mainTypeName)) {
      return MainType.GWT_DEV_MODE.mainTypeName;
    }

    return MainType.GWT_DEV_MODE.mainTypeName;
  } else {
    // TODO would this work?
    return MainType.GWT_DEV_MODE.mainTypeName;
  }
}
 
Example 12
Source File: JdtClasspathUriResolver.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private URI findResourceInProjectRoot(IJavaProject javaProject, String path, Set<String> visited) throws CoreException {
	boolean includeAll = visited.isEmpty();
	if (visited.add(javaProject.getElementName())) {
		IProject project = javaProject.getProject();
		IResource resourceFromProjectRoot = project.findMember(path);
		if (resourceFromProjectRoot != null && resourceFromProjectRoot.exists()) {
			return createPlatformResourceURI(resourceFromProjectRoot);
		}
		for(IClasspathEntry entry: javaProject.getResolvedClasspath(true)) {
			if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
				if (includeAll || entry.isExported()) {
					IResource referencedProject = project.getWorkspace().getRoot().findMember(entry.getPath());
					if (referencedProject != null && referencedProject.getType() == IResource.PROJECT) {
						IJavaProject referencedJavaProject = JavaCore.create((IProject) referencedProject);
						if (referencedJavaProject.exists()) {
							URI result = findResourceInProjectRoot(referencedJavaProject, path, visited);
							if (result != null) {
								return result;
							}
						}
					}
					break;
				}
			}
		}
	}
	return null;
}
 
Example 13
Source File: GWTCompileRunner.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param processReceiver optional, receives the process after it is started
 */
public static void compile(IJavaProject javaProject, IPath warLocation,
    GWTCompileSettings settings, OutputStream consoleOutputStream,
    IProcessReceiver processReceiver) throws IOException,
    InterruptedException, CoreException, OperationCanceledException {
  IProject project = javaProject.getProject();

  if (settings.getEntryPointModules().isEmpty()) {
    // Nothing to compile, so just return.
    return;
  }

  int processStatus = ProcessUtilities.launchProcessAndWaitFor(
      computeCompilerCommandLine(javaProject, warLocation, settings),
      project.getLocation().toFile(), consoleOutputStream, processReceiver);

  /*
   * Do a refresh on the war folder if it's in the workspace. This ensures
   * that Eclipse sees the generated artifacts from the GWT compile, and
   * doesn't complain about stale resources during subsequent file searches.
   */
  if (warLocation != null) {
     for (IContainer warFolder : ResourcesPlugin.getWorkspace().getRoot()
        .findContainersForLocationURI(URIUtil.toURI(warLocation))) {
      warFolder.refreshLocal(IResource.DEPTH_INFINITE, null);
    }
  }

  if (processStatus != 0) {
    if (processReceiver != null && processReceiver.hasDestroyedProcess()) {
      PrintWriter printWriter = new PrintWriter(consoleOutputStream);
      printWriter.println("GWT compilation terminated by the user.");
      printWriter.flush();
      throw new OperationCanceledException();
    } else {
      throw new CoreException(new Status(IStatus.ERROR, GWTPlugin.PLUGIN_ID,
          "GWT compilation failed"));
    }
  }
}
 
Example 14
Source File: BuildPath.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/** Return the libraries whose definitions are matched by the project's pom's dependencies. */
public static Collection<Library> loadMavenLibraries(IJavaProject javaProject,
    Collection<Library> availableLibraries, IProgressMonitor monitor)
    throws CoreException {
  IProject project = javaProject.getProject();
  IFile pomFile = project.getFile("pom.xml"); //$NON-NLS-1$

  try {
    Pom pom = Pom.parse(pomFile);
    return pom.resolveLibraries(availableLibraries);
  } catch (SAXException | IOException ex) {
    IStatus status = StatusUtil.error(BuildPath.class, ex.getMessage(), ex);
    throw new CoreException(status);
  }
}
 
Example 15
Source File: WebAppLaunchDelegate.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Publish any {@link IModule}s that the project has if it is not using a managed war directory and it is running a
 * server.
 */
public static void maybePublishModulesToWarDirectory(ILaunchConfiguration configuration, IProgressMonitor monitor,
    IJavaProject javaProject, boolean forceFullPublish) throws CoreException {

  if (javaProject == null) {
    // No Java Project
    return;
  }

  IProject project = javaProject.getProject();

  List<String> args = LaunchConfigurationProcessorUtilities.parseProgramArgs(configuration);
  if (WebAppUtilities.hasManagedWarOut(project) || NoServerArgumentProcessor.hasNoServerArg(args)) {
    // Project has a managed war directory or it is running in noserver
    // mode
    return;
  }

  WarParser parser = WarArgumentProcessor.WarParser.parse(args, javaProject);
  if (parser.resolvedUnverifiedWarDir == null) {
    // Invalid war directory
    return;
  }

  IModule[] modules = ServerUtil.getModules(project);
  if (modules.length > 0) {
    Path unmanagedWarPath = new Path(parser.resolvedUnverifiedWarDir);
    WtpPublisher.publishModulesToWarDirectory(project, modules, unmanagedWarPath, forceFullPublish, monitor);
  }
}
 
Example 16
Source File: WorkingSetAwareContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private IProject getProject(IJavaElement element) {
	IJavaProject project= element.getJavaProject();
	if (project == null)
		return null;
	return project.getProject();
}
 
Example 17
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Change createChange(IPackageFragmentRoot root, IJavaProject destination) {
	// /XXX fix the query
	return new MovePackageFragmentRootChange(root, destination.getProject(), null);
}
 
Example 18
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public static void deleteJavaProject(IJavaProject javaProject) throws CoreException {
	IProject project = javaProject.getProject();
	deleteProject(project);
}
 
Example 19
Source File: MavenBuildSupport.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public ILaunchConfiguration getLaunchConfiguration(IJavaProject javaProject, String scope) throws CoreException {
	return new JavaApplicationLaunchConfiguration(javaProject.getProject(), scope, MavenRuntimeClasspathProvider.MAVEN_CLASSPATH_PROVIDER);
}
 
Example 20
Source File: PerformanceTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testBuildOfDownstreamProject() throws Exception {
  final IJavaProject project = PerformanceTestProjectSetup.testProject;
  final IJavaProject downStreamProject = PerformanceTestProjectSetup.createJavaProject("performance.test.project.downstream", 
    new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" });
  JavaProjectSetupUtil.addProjectReference(downStreamProject, project);
  new ToggleXtextNatureCommand().toggleNature(downStreamProject.getProject());
  final IFolder sourceFolder = JavaProjectSetupUtil.addSourceFolder(downStreamProject, "src");
  JavaProjectSetupUtil.addSourceFolder(downStreamProject, "xtend-gen");
  sourceFolder.getFolder("foo").create(true, true, null);
  final IFile sourceFile = sourceFolder.getFile("foo/MyFile.xtend");
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("package foo");
  _builder.newLine();
  _builder.newLine();
  _builder.append("import org.eclipse.xtext.xbase.formatting.BasicFormatterPreferenceKeys");
  _builder.newLine();
  _builder.append("import org.eclipse.xtext.xbase.formatting.FormattableDocument");
  _builder.newLine();
  _builder.append("import org.eclipse.xtext.xbase.formatting.HiddenLeafAccess");
  _builder.newLine();
  _builder.append("import org.eclipse.xtext.xbase.formatting.NodeModelAccess");
  _builder.newLine();
  _builder.append("import org.eclipse.xtext.xbase.formatting.XbaseFormatter2");
  _builder.newLine();
  _builder.newLine();
  _builder.append("class MyFile extends XbaseFormatter2 {");
  _builder.newLine();
  _builder.append("\t");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("def a(BasicFormatterPreferenceKeys keys) {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("BasicFormatterPreferenceKeys::indentation");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("\t");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("def b(FormattableDocument doc) {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("doc.cfg.get(BasicFormatterPreferenceKeys::indentation)");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("\t");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("def c(HiddenLeafAccess x) {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("x.getHiddenLeafsAfter(null).newLines");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("\t");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("def d(NodeModelAccess x) {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("x.nodeForEObject(null).asTreeIterable");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  StringInputStream _stringInputStream = new StringInputStream(_builder.toString());
  sourceFile.create(_stringInputStream, true, null);
  final IProject p = downStreamProject.getProject();
  p.build(IncrementalProjectBuilder.FULL_BUILD, null);
  p.build(IncrementalProjectBuilder.FULL_BUILD, null);
  Stopwatches.resetAll();
  p.build(IncrementalProjectBuilder.FULL_BUILD, null);
}