org.eclipse.jdt.core.IJavaProject Java Examples

The following examples show how to use org.eclipse.jdt.core.IJavaProject. 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: ClasspathModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #2
Source File: BusinessObjectModelRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
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 #3
Source File: CodeFormatterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #4
Source File: XbaseResourceForEditorInputFactoryTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 #5
Source File: CleanUpRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #6
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #7
Source File: NewClientBundleWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
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 #8
Source File: PackageBrowseAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #9
Source File: ModuleUtils.java    From gwt-eclipse-plugin with 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 #10
Source File: NiCadOutputParser.java    From JDeodorant with 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 #11
Source File: Storage2UriMapperJavaImplTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 #12
Source File: ProfilerAbstractBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@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 #13
Source File: GWTRuntimeTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tests that we find an {@link com.google.gdt.eclipse.core.sdk.Sdk} on the
 * gwt-user project. Note this test uses gwt-dev instead of gwt-dev-${PLAT} as
 * the dev project name.
 */
public void testFindSdkFor_GwtDevProject() throws Exception {
  GwtRuntimeTestUtilities.importGwtSourceProjects();
  try {
    IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    IJavaProject javaProject = javaModel.getJavaProject("gwt-dev");
    GwtSdk sdk = GwtSdk.findSdkFor(javaProject);
    IClasspathEntry[] entries = sdk.getClasspathEntries();
    assertEquals(new IClasspathEntry[] {JavaCore.newSourceEntry(javaModel.getJavaProject(
        "gwt-dev").getPath().append("core/src"))}, entries);
  } finally {
    GwtRuntimeTestUtilities.removeGwtSourceProjects();
  }
}
 
Example #14
Source File: GwtCompilerSettingsTab.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private IProject getProject() throws CoreException {
  IJavaProject javaProject = getJavaProject();
  if (javaProject == null || !javaProject.exists()) {
    throw new CoreException(new Status(IStatus.ERROR, GWTPlugin.PLUGIN_ID, "Could not get a valid Java project"));
  }

  return javaProject.getProject();
}
 
Example #15
Source File: GradleProjectImporter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean checkGradlePersistence(IProject project, File projectDir) {
	if (ProjectUtils.isJavaProject(project) && !project.getFile(IJavaProject.CLASSPATH_FILE_NAME).exists()) {
		return true;
	}
	boolean shouldSynchronize = true;
	PersistentModel model = CorePlugin.modelPersistence().loadModel(project);
	if (model.isPresent()) {
		File persistentFile = CorePlugin.getInstance().getStateLocation().append("project-preferences").append(project.getName()).toFile();
		if (persistentFile.exists()) {
			long modified = persistentFile.lastModified();
			if (projectDir.exists()) {
				File[] files = projectDir.listFiles(new FilenameFilter() {

					@Override
					public boolean accept(File dir, String name) {
						if (name != null && name.endsWith(GradleBuildSupport.GRADLE_SUFFIX)) {
							return new File(dir, name).lastModified() > modified;
						}
						return false;
					}
				});
				shouldSynchronize = files != null && files.length > 0;
			}
		}
	}
	return shouldSynchronize;
}
 
Example #16
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.17
 */
public static void addJreClasspathEntry(IJavaProject javaProject, boolean build) throws JavaModelException {
	// init default mappings
	makeJava7Default();
	IClasspathEntry existingJreContainerClasspathEntry = getJreContainerClasspathEntry(javaProject);
	if (existingJreContainerClasspathEntry == null) {
		addToClasspath(javaProject, JREContainerProvider.getDefaultJREContainerEntry(), build);
	}
}
 
Example #17
Source File: OptionsConfigurationBlock.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IClasspathEntry getSourceFolderIgnoringOptionalProblems() {
	if (fProject == null) {
		return null;
	}
	IJavaProject javaProject= JavaCore.create(fProject);
	if (javaProject == null) {
		return null;
	}
	try {
		IClasspathEntry[] classpathEntries= javaProject.getRawClasspath();
		for (int i= 0; i < classpathEntries.length; i++) {
			IClasspathEntry entry= classpathEntries[i];
			if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
				IClasspathAttribute[] extraAttributes= entry.getExtraAttributes();
				for (int j= 0; j < extraAttributes.length; j++) {
					IClasspathAttribute attrib= extraAttributes[j];
					if (IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS.equals(attrib.getName())) {
						if ("true".equals(attrib.getValue())) { //$NON-NLS-1$
							return entry;
						} else {
							break;
						}
					}
				}
			}
		}
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
	return null;
}
 
Example #18
Source File: EditFilterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IPath getOutputLocation(IJavaProject javaProject) {
	try {
		return javaProject.getOutputLocation();
	} catch (CoreException e) {
		IProject project= javaProject.getProject();
		IPath projPath= project.getFullPath();
		return projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
	}
}
 
Example #19
Source File: IntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testTwoJars() throws Exception {
	IJavaProject project = createJavaProject("foo");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/Bar" + F_EXT, "object Foo")), true, monitor());
	IFile file2 = project.getProject().getFile("bar.jar");
	file2.create(
			jarInputStream(new TextFile("foo/Bar" + F_EXT, "object Foo"), new TextFile("foo/Bar2" + F_EXT,
					"object Bar references Foo")), true, monitor());

	addJarToClasspath(project, file);
	addJarToClasspath(project, file2);
	assertEquals(3, countResourcesInIndex());
}
 
Example #20
Source File: RecentSettingsStore.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getDefaultAntPath(IJavaProject project) {
	if (project != null) {
		// The Javadoc.xml file can only be stored locally. So if
		// the project isn't local then we can't provide a good
		// default location.
		IPath path= project.getProject().getLocation();
		if (path != null)
			return path.append("javadoc.xml").toOSString(); //$NON-NLS-1$
	}

	return ""; //$NON-NLS-1$
}
 
Example #21
Source File: AddFolderToBuildpathAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean canHandle(IStructuredSelection elements) {
	if (elements.size() == 0)
		return false;
	try {
		for (Iterator<?> iter= elements.iterator(); iter.hasNext();) {
			Object element= iter.next();
			if (element instanceof IJavaProject) {
				if (ClasspathModifier.isSourceFolder((IJavaProject)element))
					return false;
			} else if (element instanceof IPackageFragment) {
				IPackageFragment fragment= (IPackageFragment)element;
				if (ClasspathModifier.isDefaultFragment(fragment))
                    return false;

				if (ClasspathModifier.isInExternalOrArchive(fragment))
                    return false;
				IResource res;
				if ((res= fragment.getResource()) != null && res.isVirtual())
					return false;
			} else if (element instanceof IFolder) {
				IProject project= ((IFolder)element).getProject();
				IJavaProject javaProject= JavaCore.create(project);
				if (javaProject == null || !javaProject.exists() || ((IFolder)element).isVirtual())
					return false;
			} else {
				return false;
			}
		}
		return true;
	} catch (CoreException e) {
	}
	return false;
}
 
Example #22
Source File: ClientBundleResource.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private String getSourceAnnotationValue(IType clientBundle) throws JavaModelException {
  IJavaProject javaProject = clientBundle.getJavaProject();
  assert (javaProject.isOnClasspath(file));

  IPackageFragment resourcePckg = javaProject.findPackageFragment(file.getParent().getFullPath());

  // If the resource is not in the same package as our ClientBundle, we need
  // an @Source with the full classpath-relative path to the resource.
  if (!clientBundle.getPackageFragment().equals(resourcePckg)) {
    return ResourceUtils.getClasspathRelativePath(resourcePckg, file.getName()).toString();
  }

  // If the resource has a different name than the method, we need an @Source,
  // although in this case we don't need the full path.
  String fileNameWithoutExt = ResourceUtils.filenameWithoutExtension(file);
  if (!ResourceUtils.areFilenamesEqual(fileNameWithoutExt, methodName)) {
    return file.getName();
  }

  // If resource doesn't have one of the default extensions, we need @Source.
  IType resourceType = JavaModelSearch.findType(javaProject, resourceTypeName);
  if (!hasDefaultExtension(file, resourceType)) {
    return file.getName();
  }

  // If the resource is in ClientBundle package and its name (without file
  // extension) matches the method name, no need for @Source
  return null;
}
 
Example #23
Source File: JdtBasedProcessorProvider.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ClassLoader getClassLoader(final EObject ctx) {
  ResourceSet _resourceSet = ctx.eResource().getResourceSet();
  final XtextResourceSet rs = ((XtextResourceSet) _resourceSet);
  final boolean isBuilder = ResourceSetContext.get(rs).isBuilder();
  final boolean isEditor = ResourceSetContext.get(rs).isEditor();
  if (isBuilder) {
    final ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter adapter = IterableExtensions.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>head(Iterables.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>filter(rs.eAdapters(), ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter.class));
    if ((adapter != null)) {
      return adapter.getClassLoader();
    }
  }
  if (isEditor) {
    final ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter adapter_1 = IterableExtensions.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>head(Iterables.<ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter>filter(this.getEditorResource(ctx).eAdapters(), ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter.class));
    if ((adapter_1 != null)) {
      ClassLoader _classLoader = adapter_1.getClassLoader();
      boolean _tripleEquals = (_classLoader == null);
      if (_tripleEquals) {
        this.getEditorResource(ctx).eAdapters().remove(adapter_1);
      } else {
        return adapter_1.getClassLoader();
      }
    }
  }
  Object _classpathURIContext = rs.getClasspathURIContext();
  final IJavaProject project = ((IJavaProject) _classpathURIContext);
  final URLClassLoader classloader = this.createClassLoaderForJavaProject(project);
  if (isBuilder) {
    EList<Adapter> _eAdapters = rs.eAdapters();
    ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter _processorClassloaderAdapter = new ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter(classloader);
    _eAdapters.add(_processorClassloaderAdapter);
  }
  if (isEditor) {
    EList<Adapter> _eAdapters_1 = this.getEditorResource(ctx).eAdapters();
    ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter _processorClassloaderAdapter_1 = new ProcessorInstanceForJvmTypeProvider.ProcessorClassloaderAdapter(classloader);
    _eAdapters_1.add(_processorClassloaderAdapter_1);
  }
  return classloader;
}
 
Example #24
Source File: UiFieldProposalComputer.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
UiFieldProposalComputer(Set<IType> ownerTypes, String widgetTypeName,
    IJavaProject javaProject, String enteredText, int replaceOffset,
    int replaceLength) {
  super(javaProject, enteredText, replaceOffset, replaceLength);

  this.uiBinderTypes = ownerTypes;
  this.widgetTypeName = widgetTypeName;
}
 
Example #25
Source File: JavaProjectHelper.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a IJavaProject.
 *
 * @param projectName
 *            The name of the project
 * @param binFolderName
 *            Name of the output folder
 * @return Returns the Java project handle
 * @throws CoreException
 *             Project creation failed
 */
public static IJavaProject createJavaProject(String projectName, String binFolderName) throws CoreException {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(projectName);
    if (!project.exists()) {
        project.create(null);
    } else {
        project.refreshLocal(IResource.DEPTH_INFINITE, null);
    }

    if (!project.isOpen()) {
        project.open(null);
    }

    IPath outputLocation;
    if (binFolderName != null && binFolderName.length() > 0) {
        IFolder binFolder = project.getFolder(binFolderName);
        if (!binFolder.exists()) {
            CoreUtility.createFolder(binFolder, false, true, null);
        }
        outputLocation = binFolder.getFullPath();
    } else {
        outputLocation = project.getFullPath();
    }

    if (!project.hasNature(JavaCore.NATURE_ID)) {
        addNatureToProject(project, JavaCore.NATURE_ID, null);
    }

    IJavaProject jproject = JavaCore.create(project);

    jproject.setOutputLocation(outputLocation, null);
    jproject.setRawClasspath(new IClasspathEntry[0], null);

    return jproject;
}
 
Example #26
Source File: Utils.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method searches the passed project for the class that contains the main method.
 *
 * @param project Project that is searched
 * @param requestor Object that handles the search results
 */
public static void findMainMethodInCurrentProject(final IJavaProject project, final SearchRequestor requestor) {
	final SearchPattern sp = SearchPattern.createPattern("main", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

	final SearchEngine se = new SearchEngine();
	final SearchParticipant[] searchParticipants = new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
	final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {project});

	try {
		se.search(sp, searchParticipants, scope, requestor, null);
	}
	catch (final CoreException e) {
		Activator.getDefault().logError(e);
	}
}
 
Example #27
Source File: SourceAttachmentCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateSourceAttachmentFromProjectJar() throws Exception {
	IResource source = project.findMember("foo-sources.jar");
	assertNotNull(source);
	IPath sourcePath = source.getLocation();
	SourceAttachmentAttribute attributes = new SourceAttachmentAttribute(null, sourcePath.toOSString(), "UTF-8");
	SourceAttachmentRequest request = new SourceAttachmentRequest(classFileUri, attributes);
	String arguments = new Gson().toJson(request, SourceAttachmentRequest.class);
	SourceAttachmentResult updateResult = SourceAttachmentCommand.updateSourceAttachment(Arrays.asList(arguments), new NullProgressMonitor());
	assertNotNull(updateResult);
	assertNull(updateResult.errorMessage);

	// Verify the source is attached to the classfile.
	IClassFile classfile = JDTUtils.resolveClassFile(classFileUri);
	IBuffer buffer = classfile.getBuffer();
	assertNotNull(buffer);
	assertTrue(buffer.getContents().indexOf("return sum;") >= 0);

	// Verify whether project inside jar attachment is saved with project relative path.
	IJavaProject javaProject = JavaCore.create(project);
	IPath relativePath = source.getFullPath();
	IPath absolutePath = source.getLocation();
	for (IClasspathEntry entry : javaProject.getRawClasspath()) {
		if (Objects.equals("foo.jar", entry.getPath().lastSegment())) {
			assertNotNull(entry.getSourceAttachmentPath());
			assertEquals(relativePath, entry.getSourceAttachmentPath());
			assertNotEquals(absolutePath, entry.getSourceAttachmentPath());
			break;
		}
	}
}
 
Example #28
Source File: CompPlugin.java    From junion with 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;
}
 
Example #29
Source File: UpdateTriggerCompilationParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean isActive(IJavaProject project) {
  if (!project.exists()) {
    return false;
  }

  // Only run when preferences are set to ok, and it's a gwt project
  if (GdtPreferences.getCaptureAnalytics() && GWTNature.isGWTProject(project.getProject())) {
    runProcesses();
    return true;
  } else {
    return false;
  }
}
 
Example #30
Source File: JavadocWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void setAllJavadocLocations(IJavaProject[] projects, URL newURL) {
	Shell shell= getShell();
	String[] buttonlabels= new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL };

	for (int j= 0; j < projects.length; j++) {
		IJavaProject iJavaProject= projects[j];
		String message= Messages.format(JavadocExportMessages.JavadocWizard_updatejavadoclocation_message, new String[] { BasicElementLabels.getJavaElementName(iJavaProject.getElementName()), BasicElementLabels.getPathLabel(fDestination, true) });
		MessageDialog dialog= new MessageDialog(shell, JavadocExportMessages.JavadocWizard_updatejavadocdialog_label, null, message, MessageDialog.QUESTION, buttonlabels, 1);

		switch (dialog.open()) {
			case YES :
				JavaUI.setProjectJavadocLocation(iJavaProject, newURL);
				break;
			case YES_TO_ALL :
				for (int i= j; i < projects.length; i++) {
					iJavaProject= projects[i];
					JavaUI.setProjectJavadocLocation(iJavaProject, newURL);
					j++;
				}
				break;
			case NO_TO_ALL :
				j= projects.length;
				break;
			case NO :
			default :
				break;
		}
	}
}