Java Code Examples for org.eclipse.jdt.core.IJavaProject

The following examples show how to use org.eclipse.jdt.core.IJavaProject. These examples are extracted from open source projects. 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
protected IRegion regionWithBDM(final IJavaProject javaProject) throws JavaModelException {
    final IRegion newRegion = JavaCore.newRegion();
    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
    if (rawClasspath != null) {
        final IClasspathEntry repositoryDependenciesClasspathEntry = find(asIterable(rawClasspath),
                repositoryDependenciesEntry(), null);
        final IPackageFragmentRoot[] fragmentRoots = javaProject
                .findPackageFragmentRoots(repositoryDependenciesClasspathEntry);
        if (fragmentRoots != null) {
            final IPackageFragmentRoot packageFragmentRoot = find(asIterable(fragmentRoots),
                    withElementName(BDM_CLIENT_POJO_JAR_NAME), null);
            if (packageFragmentRoot != null) {
                newRegion.add(packageFragmentRoot);
            }
        }
    }
    return newRegion;
}
 
Example 2
@Test public void testFullBuildBigProjectWithSyntaxErrors() throws Exception {
	IJavaProject project = workspace.createJavaProject("foo");
	workspace.addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	int NUM_FILES = 500;
	IFile[] files = new IFile[NUM_FILES];
	StopWatch timer = new StopWatch();
	for (int i = 0; i < NUM_FILES; i++) {
		IFile file = folder.getFile("Test_" + i + "_" + F_EXT);
		files[i] = file;
		String contents = "object Foo" + i + " references Foo" + (i * 1000);
		if (i == NUM_FILES)
			contents = "object Foo" + i;
		file.create(new StringInputStream(contents), true, workspace.monitor());
	}
	logAndReset("Creating files", timer);
	workspace.build();
	logAndReset("Auto build", timer);
	IMarker[] iMarkers = folder.findMarkers(EValidator.MARKER, true, IResource.DEPTH_INFINITE);
	assertEquals(NUM_FILES-1,iMarkers.length);
}
 
Example 3
@Test
public void testOnCloseOpenRemoveProject() {
  try {
    Assert.assertEquals(0, this.getCachedPackageFragmentRootData().size());
    final IJavaProject project = JavaProjectSetupUtil.createJavaProject("testProject");
    final IJavaProject project2 = JavaProjectSetupUtil.createJavaProject("testProject2");
    final int sizeBefore = this.getCachedPackageFragmentRootData().size();
    final IFile file = this.createJar(project);
    JavaProjectSetupUtil.addJarToClasspath(project, file);
    JavaProjectSetupUtil.addJarToClasspath(project2, file);
    this.assertBothProjects(sizeBefore);
    project2.getProject().close(IResourcesSetupUtil.monitor());
    this.assertFirstProject(sizeBefore);
    project.getProject().close(IResourcesSetupUtil.monitor());
    this.assertNonProjects();
    project.getProject().open(IResourcesSetupUtil.monitor());
    this.assertFirstProject(sizeBefore);
    project2.getProject().open(IResourcesSetupUtil.monitor());
    this.assertBothProjects(sizeBefore);
    project.getProject().delete(true, IResourcesSetupUtil.monitor());
    project2.getProject().delete(true, IResourcesSetupUtil.monitor());
    this.assertNonProjects();
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 4
private boolean newTypeExtendsClientBundle() {
  IJavaProject javaProject = getJavaProject();
  if (javaProject == null) {
    return false;
  }

  for (Object superInterface : getSuperInterfaces()) {
    String interfaceTypeName = (String) superInterface;
    try {
      if (ClientBundleUtilities.isClientBundle(javaProject, interfaceTypeName)) {
        return true;
      }
    } catch (JavaModelException e) {
      GWTPluginLog.logError(e);
    }
  }
  return false;
}
 
Example 5
Source Project: gwt-eclipse-plugin   Source File: ModuleUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Scans the package fragments (including jars if includeJars is true) invoking the visitor
 * callback.
 *
 * Stops if the callback returns a non-null result, and passes that result back to the caller.
 */
private static <T> T visitFragments(IJavaProject project, boolean includeJars, IPackageFragmentVisitor<T> visitor) {
  try {
    for (IPackageFragmentRoot pckgRoot : project.getPackageFragmentRoots()) {
      if (pckgRoot.isArchive() && !includeJars) {
        continue;
      }

      for (IJavaElement elem : pckgRoot.getChildren()) {
        T result = visitor.visit((IPackageFragment) elem);
        if (result != null) {
          return result;
        }
      }
    }
  } catch (JavaModelException e) {
    GWTPluginLog.logError(e);
  }

  return null;
}
 
Example 6
private Change[] cleanUpProject(IJavaProject project, CleanUpTarget[] targets, ICleanUp[] cleanUps, IProgressMonitor monitor) throws CoreException {
	CleanUpFixpointIterator iter= new CleanUpFixpointIterator(targets, cleanUps);

	SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 2 * targets.length * cleanUps.length);
	subMonitor.beginTask("", targets.length); //$NON-NLS-1$
	subMonitor.subTask(Messages.format(FixMessages.CleanUpRefactoring_Parser_Startup_message, BasicElementLabels.getResourceName(project.getProject())));
	try {
		while (iter.hasNext()) {
			iter.next(subMonitor);
		}

		return iter.getResult();
	} finally {
		iter.dispose();
		subMonitor.done();
	}
}
 
Example 7
/**
 * Gets the current tab width.
 *
 * @param project
 *        The project where the source is used, used for project specific options or
 *        <code>null</code> if the project is unknown and the workspace default should be used
 * @return The tab width
 */
public static int getTabWidth(IJavaProject project) {
	/*
	 * If the tab-char is SPACE, FORMATTER_INDENTATION_SIZE is not used
	 * by the core formatter.
	 * We piggy back the visual tab length setting in that preference in
	 * that case.
	 */
	String key;
	if (JavaCore.SPACE.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR)))
		key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE;
	else
		key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE;

	return getCoreOption(project, key, 4);
}
 
Example 8
public static BuildpathDelta addExternalJars(IPath[] absolutePaths, CPJavaProject cpProject) {
  	BuildpathDelta result= new BuildpathDelta(NewWizardMessages.NewSourceContainerWorkbookPage_ToolBar_AddJarCP_tooltip);

  	IJavaProject javaProject= cpProject.getJavaProject();

  	List<CPListElement> existingEntries= cpProject.getCPListElements();
  	for (int i= 0; i < absolutePaths.length; i++) {
       CPListElement newEntry= new CPListElement(javaProject, IClasspathEntry.CPE_LIBRARY, absolutePaths[i], null);
       if (!existingEntries.contains(newEntry)) {
       	insertAtEndOfCategory(newEntry, existingEntries);
       	result.addEntry(newEntry);
       }
      }

result.setNewEntries(existingEntries.toArray(new CPListElement[existingEntries.size()]));
result.setDefaultOutputLocation(cpProject.getDefaultOutputLocation());
return result;
  }
 
Example 9
@Test
public void testValidationIsDisabled_03() throws Exception {
	IProject project = AbstractXbaseUITestCase.createPluginProject("my.plugin.project");
	IJavaProject jp = JavaCore.create(project);
	boolean wasTested = false;
	for (IPackageFragmentRoot pfr : jp.getAllPackageFragmentRoots()) {
		if (pfr.isArchive()) {
			for (Object o : pfr.getNonJavaResources()) {
				if (o instanceof IStorage) {
					assertTrue(isValidationDisabled((IStorage) o));
					wasTested = true;
				}
			}
		}
	}
	assertTrue(wasTested);
}
 
Example 10
private void format(IDocument doc, CompilationUnitContext context) throws BadLocationException {
	Map<String, String> options;
	IJavaProject project= context.getJavaProject();
	if (project != null)
		options= project.getOptions(true);
	else
		options= JavaCore.getOptions();

	String contents= doc.get();
	int[] kinds= { CodeFormatter.K_EXPRESSION, CodeFormatter.K_STATEMENTS, CodeFormatter.K_UNKNOWN};
	TextEdit edit= null;
	for (int i= 0; i < kinds.length && edit == null; i++) {
		edit= CodeFormatterUtil.format2(kinds[i], contents, fInitialIndentLevel, fLineDelimiter, options);
	}

	if (edit == null)
		throw new BadLocationException(); // fall back to indenting

	edit.apply(doc, TextEdit.UPDATE_REGIONS);
}
 
Example 11
public static Object[] createPackageListInput(ICompilationUnit cu, String elementNameMatch){
	try{
		IJavaProject project= cu.getJavaProject();
		IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
		List<IPackageFragment> result= new ArrayList<IPackageFragment>();
		HashMap<String, Object> entered =new HashMap<String, Object>();
		for (int i= 0; i < roots.length; i++){
			if (canAddPackageRoot(roots[i])){
				getValidPackages(roots[i], result, entered, elementNameMatch);
			}
		}
		return result.toArray();
	} catch (JavaModelException e){
		JavaPlugin.log(e);
		return new Object[0];
	}
}
 
Example 12
Source Project: JDeodorant   Source File: NiCadOutputParser.java    License: MIT License 6 votes vote down vote up
public NiCadOutputParser(IJavaProject iJavaProject, String cloneOutputFilePath) throws InvalidInputFileException {
	super(iJavaProject, cloneOutputFilePath);
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setIgnoringElementContentWhitespace(true);
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		File file = new File(this.getToolOutputFilePath());
		this.document  = builder.parse(file);
		NodeList classInfoNodeList = document.getElementsByTagName("classinfo");
		try {
			this.setCloneGroupCount(Integer.parseInt(classInfoNodeList.item(0).getAttributes().getNamedItem("nclasses").getNodeValue()));
		} catch (Exception nfe) {
			this.document = null;
			throw new InvalidInputFileException();
		}
	} catch (IOException ioex) {
		ioex.printStackTrace();
	} catch (SAXException saxe) {
		saxe.printStackTrace();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
	}
}
 
Example 13
/**
 * Handles the deletion of the element underlying the given class file editor input.
 * @param input the editor input
 */
protected void handleDeleted(IClassFileEditorInput input) {
	if (input == null) {
		fireElementDeleted(input);
		return;
	}

	if (input.exists())
		return;

	IClassFile cf= input.getClassFile();
	try {
		/*
		 * Let's try to find the class file - maybe the JAR changed
		 */
		IType type= cf.getType();
		IJavaProject project= cf.getJavaProject();
		if (project != null) {
			type= project.findType(type.getFullyQualifiedName());
			if (type != null) {
				IEditorInput editorInput= EditorUtility.getEditorInput(type.getParent());
				if (editorInput instanceof IClassFileEditorInput) {
					fireInputChanged((IClassFileEditorInput)editorInput);
					return;
				}
			}
		}
	} catch (JavaModelException x) {
		// Don't log and fall through: element deleted
	}

	fireElementDeleted(input);

}
 
Example 14
/**
 * Indents a single line using the java heuristic scanner. Javadoc and multiline comments are
 * indented as specified by the <code>JavaDocAutoIndentStrategy</code>.
 *
 * @param document the document
 * @param line the line to be indented
 * @param caret the caret position
 * @param indenter the java indenter
 * @param scanner the heuristic scanner
 * @param multiLine <code>true</code> if more than one line is being indented
 * @return <code>true</code> if <code>document</code> was modified, <code>false</code> otherwise
 * @throws BadLocationException if the document got changed concurrently
 */
private boolean indentLine(IDocument document, int line, int caret, JavaIndenter indenter, JavaHeuristicScanner scanner, boolean multiLine) throws BadLocationException {
	IJavaProject project= getJavaProject();
	ReplaceData data= computeReplaceData(document, line, indenter, scanner, multiLine, fIsTabAction, project);

	String indent= data.indent;
	int end= data.end;
	int offset= data.offset;

	int length= end - offset;
	String currentIndent= document.get(offset, length);

	// if we are right before the text start / line end, and already after the insertion point
	// then just insert a tab.
	if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent, project) >= whiteSpaceLength(indent, project)) {
		String tab= getTabEquivalent(project);
		document.replace(caret, 0, tab);
		fCaretOffset= caret + tab.length();
		return true;
	}

	// set the caret offset so it can be used when setting the selection
	if (caret >= offset && caret <= end)
		fCaretOffset= offset + indent.length();
	else
		fCaretOffset= -1;

	// only change the document if it is a real change
	if (!indent.equals(currentIndent)) {
		document.replace(offset, length, indent);
		return true;
	} else
		return false;
}
 
Example 15
@Override
protected boolean canHandle(IStructuredSelection selection) {
   	if (selection.size() != 1)
   		return false;

   	if (!(selection.getFirstElement() instanceof IJavaProject))
   		return false;

   	return true;
   }
 
Example 16
@Override
public void cleanStarting(IJavaProject project) {
  // Cancel the current validation job.
  synchronized (this) {
    Job buildJob = validationJobs.get(project.getProject());
    if (buildJob != null) {
      buildJob.cancel();
    }
  }

  cleanBuildArtifacts(project.getProject());
}
 
Example 17
public Object[] getChildren(Object element) {
	if (!exists(element))
		return NO_CHILDREN;

	try {
		if (element instanceof IJavaModel)
			return getJavaProjects((IJavaModel)element);

		if (element instanceof IJavaProject)
			return getPackageFragmentRoots((IJavaProject)element);

		if (element instanceof IPackageFragmentRoot)
			return getPackageFragmentRootContent((IPackageFragmentRoot)element);

		if (element instanceof IPackageFragment)
			return getPackageContent((IPackageFragment)element);

		if (element instanceof IFolder)
			return getFolderContent((IFolder)element);

		if (element instanceof IJarEntryResource) {
			return ((IJarEntryResource) element).getChildren();
		}

		if (getProvideMembers() && element instanceof ISourceReference && element instanceof IParent) {
			return ((IParent)element).getChildren();
		}
	} catch (CoreException e) {
		return NO_CHILDREN;
	}
	return NO_CHILDREN;
}
 
Example 18
Source Project: xtext-xtend   Source File: XtendQuickfixProvider.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH)
public void putXtendOnClasspath(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Add Xtend libs to classpath", "Add Xtend libs to classpath", "fix_indent.gif", new ISemanticModification() {
		@Override
		public void apply(EObject element, IModificationContext context) throws Exception {
			ResourceSet resourceSet = element.eResource().getResourceSet();
			IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
			xtendLibAdder.addLibsToClasspath(javaProject, new NullProgressMonitor());
		}
	});
}
 
Example 19
@Override
protected boolean isValidationDisabled(URI uri, IStorage storage) {
	if (storage instanceof IFile) {
		IFile file = (IFile) storage;
		IJavaProject javaProject = JavaCore.create(file.getProject());
		if (javaProject == null || !javaProject.exists() || !javaProject.isOpen()) {
			return true;
		}
		if (!canBuild(uri, storage)) {
			return true;
		}
	}
	return super.isValidationDisabled(uri, storage);
}
 
Example 20
@Test
public void testInitialize_ifSourceArtifactJarPathInvalidContainerResolvedFromScratch()
    throws CoreException, IOException {
  File artifactFile = temporaryFolder.newFile();
  assertFalse(new File(NON_EXISTENT_FILE).exists());

  IClasspathEntry entry = mock(IClasspathEntry.class);
  when(entry.getPath()).thenReturn(new Path(artifactFile.getAbsolutePath()));
  when(entry.getSourceAttachmentPath()).thenReturn(new Path(NON_EXISTENT_FILE));
  IClasspathEntry[] entries = new IClasspathEntry[]{ entry };
  LibraryClasspathContainer container = mock(LibraryClasspathContainer.class);
  when(container.getClasspathEntries()).thenReturn(entries);
  when(serializer.loadContainer(any(IJavaProject.class), any(IPath.class))).thenReturn(container);

  boolean[] called = new boolean[] {false};
  LibraryClasspathContainerInitializer containerInitializer =
      new LibraryClasspathContainerInitializer(TEST_CONTAINER_PATH, serializer, resolverService) {

        @Override
        public void requestClasspathContainerUpdate(
            IPath containerPath, IJavaProject project, IClasspathContainer containerSuggestion)
            throws CoreException {
          called[0] = true;
        }
      };
  assertFalse(called[0]);
  containerInitializer.initialize(new Path(TEST_LIBRARY_PATH), testProject.getJavaProject());
  assertTrue(called[0]);
  verifyResolveServiceResolveContainerNotCalled();
}
 
Example 21
@Override
protected boolean canHandle(IStructuredSelection elements) {
	try {
        for (Iterator<?> iterator= elements.iterator(); iterator.hasNext();) {
            Object element= iterator.next();
            if (element instanceof IJavaProject) {
            	IJavaProject project= (IJavaProject)element;
            	if (!project.isOnClasspath(project))
            		return false;

            	IClasspathEntry entry= ClasspathModifier.getClasspathEntryFor(project.getPath(), project, IClasspathEntry.CPE_SOURCE);
                if (entry.getInclusionPatterns().length == 0 && entry.getExclusionPatterns().length == 0)
                    return false;

        		return true;
            } else if (element instanceof IPackageFragmentRoot) {
            	if (ClasspathModifier.filtersSet((IPackageFragmentRoot)element))
            		return true;
            } else if (element instanceof CPListElementAttribute) {
            	if (!ClasspathModifier.isDefaultOutputFolder((CPListElementAttribute)element))
            		return true;
            } else {
            	return false;
            }
        }
       } catch (JavaModelException e) {
        return false;
       }
	return false;
}
 
Example 22
private HashMap<IJavaProject, ArrayList<IJavaElement>> getJavaElementsPerProject(IJavaElement[] elements) {
	HashMap<IJavaProject, ArrayList<IJavaElement>> result= new HashMap<IJavaProject, ArrayList<IJavaElement>>();
	for (int i= 0; i < elements.length; i++) {
		IJavaElement element= elements[i];
		IJavaProject javaProject= element.getJavaProject();
		ArrayList<IJavaElement> javaElements= result.get(javaProject);
		if (javaElements == null) {
			javaElements= new ArrayList<IJavaElement>();
			result.put(javaProject, javaElements);
		}
		javaElements.add(element);
	}
	return result;
}
 
Example 23
Source Project: eclipse.jdt.ls   Source File: JavaDocLocations.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static URL getProjectJavadocLocation(IJavaProject project) {
	if (!project.getProject().isAccessible()) {
		return null;
	}
	try {
		String prop = project.getProject().getPersistentProperty(PROJECT_JAVADOC);
		if (prop == null) {
			return null;
		}
		return parseURL(prop);
	} catch (CoreException e) {
		//JavaPlugin.log(e);
	}
	return null;
}
 
Example 24
Source Project: java-debug   Source File: ProjectSettingsChecker.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check whether the project settings are all matched as the expected.
 * @param params - The checker parameters
 * @return true if all settings is matched
 */
public static boolean check(ProjectSettingsCheckerParams params) {
    Map<String, String> options = new HashMap<>();
    IJavaProject javaProject = null;
    if (StringUtils.isNotBlank(params.projectName)) {
        javaProject = JdtUtils.getJavaProject(params.projectName);
    } else if (StringUtils.isNotBlank(params.className)) {
        try {
            List<IJavaProject> projects = ResolveClasspathsHandler.getJavaProjectFromType(params.className);
            if (!projects.isEmpty()) {
                javaProject = projects.get(0);
            }
        } catch (CoreException e) {
            // do nothing
        }
    }

    if (javaProject != null) {
        options = javaProject.getOptions(params.inheritedOptions);
    }

    for (Entry<String, String> expected : params.expectedOptions.entrySet()) {
        if (!Objects.equals(options.get(expected.getKey()), expected.getValue())) {
            return false;
        }
    }

    return true;
}
 
Example 25
/**
 * @return the Java project, or null
 */
public static IJavaProject getJavaProject(
    ILaunchConfiguration launchConfiguration) {
  try {
    return JavaRuntime.getJavaProject(launchConfiguration);
  } catch (CoreException e) {
    // When the attribute holding the Java project had an issue, assume no
    // Java project
    return null;
  }
}
 
Example 26
@Test
public void testRemoveGpeClasspathEntries() throws JavaModelException {
  IJavaProject javaProject = JavaCore.create(gpeProject);

  assertTrue(containsLibrary(javaProject, "com.google.appengine.eclipse.core.GAE_CONTAINER"));
  assertTrue(containsLibrary(javaProject, "com.google.gwt.eclipse.core.GWT_CONTAINER"));

  assertTrue(GpeMigrator.removeGpeClasspathEntries(gpeProject, monitor));
  assertFalse(containsLibrary(javaProject, "com.google.appengine.eclipse.core.GAE_CONTAINER"));
  assertFalse(containsLibrary(javaProject, "com.google.gwt.eclipse.core.GWT_CONTAINER"));

  assertFalse(GpeMigrator.removeGpeClasspathEntries(gpeProject, monitor));
}
 
Example 27
public IJavaSearchScope createJavaProjectSearchScope(IEditorInput editorInput, int includeMask) {
	IJavaElement elem= JavaUI.getEditorInputJavaElement(editorInput);
	if (elem != null) {
		IJavaProject project= elem.getJavaProject();
		if (project != null) {
			return createJavaProjectSearchScope(project, includeMask);
		}
	}
	return EMPTY_SCOPE;
}
 
Example 28
public AnonymousTypeCompletionProposal(IJavaProject jproject, ICompilationUnit cu, JavaContentAssistInvocationContext invocationContext, int start, int length, String constructorCompletion, StyledString displayName, String declarationSignature, IType superType, int relevance) {
	super(constructorCompletion, cu, start, length, null, displayName, relevance, null, invocationContext);
	Assert.isNotNull(declarationSignature);
	Assert.isNotNull(jproject);
	Assert.isNotNull(cu);
	Assert.isNotNull(superType);

	fDeclarationSignature= declarationSignature;
	fSuperType= superType;

	setImage(getImageForType(fSuperType));
	setCursorPosition(constructorCompletion.indexOf('(') + 1);
}
 
Example 29
private static IJavaProject[] getRelatedProjects(IJavaProject focus) throws CoreException {
	final Set<IJavaProject> projects= new HashSet<IJavaProject>();

	addRelatedReferencing(focus, projects);
	addRelatedReferenced(focus, projects);

	projects.add(focus);
	return projects.toArray(new IJavaProject[projects.size()]);
}
 
Example 30
Source Project: junion   Source File: CompPlugin.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void buildFinished(IJavaProject project) {
	super.buildFinished(project);
	log("Finished");
	doFinish(project);
	
	current = null;
}