Java Code Examples for org.eclipse.jdt.core.JavaCore#create()

The following examples show how to use org.eclipse.jdt.core.JavaCore#create() . 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: WorkspaceClassPathFinder.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private List getProjectPath( IProject project )
{
	List retValue = new ArrayList( );
	if ( !hasJavaNature( project ) )
	{
		return retValue;
	}

	IJavaProject fCurrJProject = JavaCore.create( project );
	IClasspathEntry[] classpathEntries = null;
	boolean projectExists = ( project.exists( ) && project.getFile( ".classpath" ).exists( ) ); //$NON-NLS-1$
	if ( projectExists )
	{
		if ( classpathEntries == null )
		{
			classpathEntries = fCurrJProject.readRawClasspath( );
		}
	}

	if ( classpathEntries != null )
	{
		retValue = getExistingEntries( classpathEntries, project );
	}
	return retValue;
}
 
Example 2
Source File: NativeLibrariesPropertyPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IJavaElement getJavaElement() {
	IAdaptable adaptable= getElement();
	IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
	if (elem == null) {

		IResource resource= (IResource) adaptable.getAdapter(IResource.class);
		//special case when the .jar is a file
		try {
			if (resource instanceof IFile && ArchiveFileFilter.isArchivePath(resource.getFullPath(), false)) {
				IProject proj= resource.getProject();
				if (proj.hasNature(JavaCore.NATURE_ID)) {
					IJavaProject jproject= JavaCore.create(proj);
					elem= jproject.getPackageFragmentRoot(resource); // create a handle
				}
			}
		} catch (CoreException e) {
			JavaPlugin.log(e);
		}
	}
	return elem;
}
 
Example 3
Source File: DocumentUimaImpl.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the project class loader.
 *
 * @param project the project
 * @return the project class loader
 * @throws CoreException the core exception
 */
public static ClassLoader getProjectClassLoader(IProject project) throws CoreException {
  IProjectNature javaNature = project.getNature(JAVA_NATURE);
  if (javaNature != null) {
    JavaProject javaProject = (JavaProject) JavaCore.create(project);
    
    String[] runtimeClassPath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
    List<URL> urls = new ArrayList<>();
    for (String cp : runtimeClassPath) {
      try {
        urls.add(Paths.get(cp).toUri().toURL());
      } catch (MalformedURLException e) {
        CasEditorPlugin.log(e);
      }
    }
    return new URLClassLoader(urls.toArray(new URL[0]));
  } 
  return null;
}
 
Example 4
Source File: RenamePackageChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void renamePackage(IPackageFragment pack, IProgressMonitor pm, IPath newPath, String newName) throws JavaModelException, CoreException {
	if (! pack.exists())
	 {
		return; // happens if empty parent with single subpackage is renamed, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=199045
	}
	pack.rename(newName, false, pm);
	if (fCompilationUnitStamps != null) {
		IPackageFragment newPack= (IPackageFragment) JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath));
		if (newPack.exists()) {
			ICompilationUnit[] units= newPack.getCompilationUnits();
			for (int i= 0; i < units.length; i++) {
				IResource resource= units[i].getResource();
				if (resource != null) {
					Long stamp= fCompilationUnitStamps.get(resource);
					if (stamp != null) {
						resource.revertModificationStamp(stamp.longValue());
					}
				}
			}
		}
	}
}
 
Example 5
Source File: JavadocConfigurationPropertyPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IJavaElement getJavaElement() {
	IAdaptable adaptable= getElement();
	IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
	if (elem == null) {

		IResource resource= (IResource) adaptable.getAdapter(IResource.class);
		//special case when the .jar is a file
		try {
			if (resource instanceof IFile && ArchiveFileFilter.isArchivePath(resource.getFullPath(), true)) {
				IProject proj= resource.getProject();
				if (proj.hasNature(JavaCore.NATURE_ID)) {
					IJavaProject jproject= JavaCore.create(proj);
					elem= jproject.getPackageFragmentRoot(resource); // create a handle
				}
			}
		} catch (CoreException e) {
			JavaPlugin.log(e);
		}
	}
	return elem;
}
 
Example 6
Source File: JarPackageReader.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IPackageFragment[] getPackages(NodeList list) throws IOException {
	if (list.getLength() > 1)
		throw new IOException(Messages.format(JarPackagerMessages.JarPackageReader_error_duplicateTag, list.item(0).getNodeName()));
	if (list.getLength() == 0)
		return null; // optional entry is not present
	NodeList packageNodes= list.item(0).getChildNodes();
	List<IJavaElement> packages= new ArrayList<IJavaElement>(packageNodes.getLength());
	for (int i= 0; i < packageNodes.getLength(); i++) {
		Node packageNode= packageNodes.item(i);
		if (packageNode.getNodeType() == Node.ELEMENT_NODE && packageNode.getNodeName().equals("package")) { //$NON-NLS-1$
			String handleId= ((Element)packageNode).getAttribute("handleIdentifier"); //$NON-NLS-1$
			if (handleId.equals("")) //$NON-NLS-1$
				throw new IOException(JarPackagerMessages.JarPackageReader_error_tagHandleIdentifierNotFoundOrEmpty);
			IJavaElement je= JavaCore.create(handleId);
			if (je != null && je.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
				packages.add(je);
			else
				addWarning(JarPackagerMessages.JarPackageReader_warning_javaElementDoesNotExist, null);
		}
	}
	return packages.toArray(new IPackageFragment[packages.size()]);
}
 
Example 7
Source File: NewSarlFileWizardPage.java    From sarl with Apache License 2.0 6 votes vote down vote up
private static IPath determinePackageName(IPath path) {
	if (path != null) {
		final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
		try {
			if (project != null && project.hasNature(JavaCore.NATURE_ID)) {
				final IJavaProject javaProject = JavaCore.create(project);
				for (final IClasspathEntry entry : javaProject.getRawClasspath()) {
					if (entry.getPath().isPrefixOf(path)) {
						return path.removeFirstSegments(entry.getPath().segmentCount());
					}
				}
			}
		} catch (Exception e) {
			// Ignore the exceptions since they are not useful (hopefully)
		}
	}
	return null;
}
 
Example 8
Source File: Utils.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
public static IResource findClassByName(final String className, final IProject currentProject) throws ClassNotFoundException {
	try {
		for (final IPackageFragment l : JavaCore.create(currentProject).getPackageFragments()) {
			for (final ICompilationUnit cu : l.getCompilationUnits()) {
				final IJavaElement cuResource = JavaCore.create(cu.getCorrespondingResource());
				for (IJavaElement a : (ArrayList<IJavaElement>)((CompilationUnit) cuResource).getChildrenOfType(7)) {
					String name = cuResource.getParent().getElementName() + "." + a.getElementName();

					if (name.startsWith(".")) {
						name = name.substring(1);
					}
					if (name.startsWith(className)) {
						return cu.getCorrespondingResource();
					}
				}
			}
		}
	}
	catch (final JavaModelException e) {
		throw new ClassNotFoundException("Class " + className + " not found.", e);
	}
	throw new ClassNotFoundException("Class " + className + " not found.");
}
 
Example 9
Source File: WebappProjectPropertyPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void addEntry() {
  BuildpathJarSelectionDialog dialog = new BuildpathJarSelectionDialog(getShell(), JavaCore.create(getProject()),
      excludedJarsField.getElements());
  if (dialog.open() == Window.OK) {
    excludedJarsField.addElements(dialog.getJars());
  }
}
 
Example 10
Source File: CorrectionMarkerResolutionGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ICompilationUnit getCompilationUnit(IMarker marker) {
	IResource res= marker.getResource();
	if (res instanceof IFile && res.isAccessible()) {
		IJavaElement element= JavaCore.create((IFile) res);
		if (element instanceof ICompilationUnit)
			return (ICompilationUnit) element;
	}
	return null;
}
 
Example 11
Source File: SARLProjectConfigurator.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("checkstyle:magicnumber")
public void configure(ProjectConfigurationRequest request,
		IProgressMonitor monitor) throws CoreException {
	final IMavenProjectFacade facade = request.getMavenProjectFacade();

	// --- ECLIPSE PLUGIN ---------------------------------------------------------------
	// Special case of tycho plugins, for which the {@link #configureRawClasspath}
	// and {@link #configureClasspath} were not invoked.
	// ----------------------------------------------------------------------------------
	final boolean isEclipsePlugin = isEclipsePluginPackaging(facade);

	final SubMonitor subMonitor;
	subMonitor = SubMonitor.convert(monitor, 3);

	final IProject project = request.getProject();

	final SARLConfiguration config = readConfiguration(request, subMonitor.newChild(1));
	subMonitor.worked(1);
	forceMavenCompilerConfiguration(facade, config);
	subMonitor.worked(1);

	// --- ECLIPSE PLUGIN ---------------------------------------------------------------
	if (isEclipsePlugin) {
		// In the case of Eclipse bundle, the face to the Java project must be created by hand.
		final IJavaProject javaProject = JavaCore.create(project);
		final IClasspathDescriptor classpath = new ClasspathDescriptor(javaProject);
		configureSarlProject(facade, config, classpath, false, subMonitor.newChild(1));
		subMonitor.worked(1);
	}
	// ----------------------------------------------------------------------------------

	io.sarl.eclipse.natures.SARLProjectConfigurator.addSarlNatures(
			project,
			subMonitor.newChild(1));
	subMonitor.worked(1);
}
 
Example 12
Source File: XtendUIValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected String getExpectedPackageName(XtendFile xtendFile) {
	URI fileURI = xtendFile.eResource().getURI();
	for(Pair<IStorage, IProject> storage: storage2UriMapper.getStorages(fileURI)) {
		if(storage.getFirst() instanceof IFile) {
			IPath fileWorkspacePath = storage.getFirst().getFullPath();
			IJavaProject javaProject = JavaCore.create(storage.getSecond());
			if(javaProject != null && javaProject.exists() && javaProject.isOpen()) {
				try {
					for(IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
						if(!root.isArchive() && !root.isExternal()) {
							IResource resource = root.getResource();
							if(resource != null) {
								IPath sourceFolderPath = resource.getFullPath();
								if(sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
									IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
									return claspathRelativePath.removeLastSegments(1).toString().replace("/", ".");
								}
							}
						}
					}
				} catch (JavaModelException e) {
					LOG.error("Error resolving expected path for XtendFile", e);
				}
			}
		}
	}
	return null;
}
 
Example 13
Source File: ReorgUtils.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean containsElementOrParent(Set<IAdaptable> elements, IResource element) {
	IResource curr= element;
	do {
		if (elements.contains(curr))
			return true;
		IJavaElement jElement= JavaCore.create(curr);
		if (jElement != null && jElement.exists()) {
			return containsElementOrParent(elements, jElement);
		}
		curr= curr.getParent();
	} while (curr != null);
	return false;
}
 
Example 14
Source File: FindBugsWorker.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public FindBugsWorker(IResource resource, IProgressMonitor monitor) throws CoreException {
    super();
    this.resource = resource;
    this.project = resource.getProject();
    this.javaProject = JavaCore.create(project);
    if (javaProject == null || !javaProject.exists() || !javaProject.getProject().isOpen()) {
        throw new CoreException(FindbugsPlugin.createErrorStatus("Java project is not open or does not exist: " + project,
                null));
    }
    this.monitor = monitor;
    // clone is required because we rewrite project relative references to absolute
    this.userPrefs = FindbugsPlugin.getUserPreferences(project).clone();
}
 
Example 15
Source File: JavaBreakPointProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private String getHandleId(final IJavaStratumLineBreakpoint breakpoint) throws CoreException {
	IClassFile classFile = getClassFile(breakpoint);
	if (classFile != null)
		return classFile.getType().getHandleIdentifier();
	ILocationInEclipseResource javaLocation = getJavaLocation(breakpoint);
	if (javaLocation == null)
		return null;
	IStorage javaResource = javaLocation.getPlatformResource();
	if (!(javaResource instanceof IFile))
		return null;
	ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create((IFile) javaResource);
	IJavaElement element = compilationUnit.getElementAt(javaLocation.getTextRegion().getOffset());
	return element == null ? null : element.getHandleIdentifier();
}
 
Example 16
Source File: PackageFragmentRootReorgChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected int getUpdateModelFlags(boolean isCopy) throws JavaModelException{
	final int destination= IPackageFragmentRoot.DESTINATION_PROJECT_CLASSPATH;
	final int replace= IPackageFragmentRoot.REPLACE;
	final int originating;
	final int otherProjects;
	if (isCopy){
		originating= 0; //ORIGINATING_PROJECT_CLASSPATH does not apply to copy
		otherProjects= 0;//OTHER_REFERRING_PROJECTS_CLASSPATH does not apply to copy
	} else{
		originating= IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH;
		otherProjects= IPackageFragmentRoot.OTHER_REFERRING_PROJECTS_CLASSPATH;
	}

	IJavaElement javaElement= JavaCore.create(getDestination());
	if (javaElement == null || !javaElement.exists()) {
		return replace | originating;
	}

	if (fUpdateClasspathQuery == null) {
		return replace | originating | destination;
	}

	IJavaProject[] referencingProjects= JavaElementUtil.getReferencingProjects(getRoot());
	if (referencingProjects.length <= 1) {
		return replace | originating | destination;
	}

	boolean updateOtherProjectsToo= fUpdateClasspathQuery.confirmManipulation(getRoot(), referencingProjects);
	if (updateOtherProjectsToo) {
		return replace | originating | destination | otherProjects;
	} else {
		return replace | originating | destination;
	}
}
 
Example 17
Source File: CreateJavaTypeQuickfixes.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IJavaProject getJavaProject(URI uri){
	IProject project = projectUtil.getProject(uri);
	if(project == null){
		return null;
	}
	return JavaCore.create(project);
}
 
Example 18
Source File: ProjectUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static Map<String, String> getJavaOptions(IProject project) {
	if (!isJavaProject(project)) {
		return null;
	}
	IJavaProject javaProject = JavaCore.create(project);
	return javaProject.getOptions(true);
}
 
Example 19
Source File: MoreActiveAnnotationsTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testBug461761_01() {
  try {
    final IJavaProject macroProject = JavaCore.create(WorkbenchTestHelper.createPluginProject("macroProject"));
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package annotation");
    _builder.newLine();
    _builder.newLine();
    _builder.append("import org.eclipse.xtend.lib.macro.AbstractClassProcessor");
    _builder.newLine();
    _builder.append("import org.eclipse.xtend.lib.macro.Active");
    _builder.newLine();
    _builder.append("import org.eclipse.xtend.lib.macro.RegisterGlobalsContext");
    _builder.newLine();
    _builder.append("import org.eclipse.xtend.lib.macro.declaration.ClassDeclaration");
    _builder.newLine();
    _builder.newLine();
    _builder.append("@Active(DItemMiniProcessor)");
    _builder.newLine();
    _builder.append("annotation DItemMini {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("String value");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    _builder.newLine();
    _builder.append("class DItemMiniProcessor extends AbstractClassProcessor {");
    _builder.newLine();
    _builder.newLine();
    _builder.append("\t");
    _builder.append("override doRegisterGlobals(ClassDeclaration annotatedClass, extension RegisterGlobalsContext context) {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("val suffix = annotatedClass.annotations.head.getValue(\"value\")");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("registerClass(annotatedClass.qualifiedName + suffix)");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    this.newSource(macroProject, "annotation/DItemMini.xtend", _builder.toString());
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("package annotation");
    _builder_1.newLine();
    _builder_1.newLine();
    _builder_1.append("class StaticFeatures {");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("public static final String BAR = \"Bar\"");
    _builder_1.newLine();
    _builder_1.append("\t");
    _builder_1.append("public static final String FOOBAR = \"Foo\" + BAR ");
    _builder_1.newLine();
    _builder_1.append("}");
    _builder_1.newLine();
    this.newSource(macroProject, "annotation/StaticFeatures.xtend", _builder_1.toString());
    boolean _addExportedPackages = WorkbenchTestHelper.addExportedPackages(macroProject.getProject(), "annotation");
    if (_addExportedPackages) {
      IResourcesSetupUtil.waitForBuild();
    }
    final IJavaProject userProject = JavaCore.create(
      WorkbenchTestHelper.createPluginProject("userProject", "com.google.inject", "org.eclipse.xtend.lib", 
        "org.eclipse.xtext.xbase.lib", "org.eclipse.xtend.ide.tests.data", "org.junit", "macroProject"));
    StringConcatenation _builder_2 = new StringConcatenation();
    _builder_2.append("package client");
    _builder_2.newLine();
    _builder_2.newLine();
    _builder_2.append("import static annotation.StaticFeatures.FOOBAR");
    _builder_2.newLine();
    _builder_2.newLine();
    _builder_2.append("@annotation.DItemMini(FOOBAR)");
    _builder_2.newLine();
    _builder_2.append("class UserCode{");
    _builder_2.newLine();
    _builder_2.append("\t");
    _builder_2.append("UserCodeFooBar item");
    _builder_2.newLine();
    _builder_2.append("}");
    _builder_2.newLine();
    this.newSource(userProject, "client/UserCode.xtend", _builder_2.toString());
    IResourcesSetupUtil.waitForBuild();
    IResourcesSetupUtil.assertNoErrorsInWorkspace();
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 20
Source File: PackageFragmentRootReorgChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public IPackageFragmentRoot getRoot() {
	return (IPackageFragmentRoot)JavaCore.create(fRootHandle);
}