Java Code Examples for org.eclipse.core.resources.IProject

The following are top voted examples for showing how to use org.eclipse.core.resources.IProject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pgcodekeeper   File: IPgObjectPage.java   View source code 6 votes vote down vote up
static IFolder createSchema(String name, boolean open, IProject project) throws CoreException {
    IFolder projectFolder = project.getFolder(DbObjType.SCHEMA.name());
    if (!projectFolder.exists()) {
        projectFolder.create(false, true, null);
    }
    IFolder schemaFolder = projectFolder.getFolder(name);
    if (!schemaFolder.exists()) {
        schemaFolder.create(false, true, null);
    }
    IFile file = projectFolder.getFile(name + POSTFIX);
    if (!file.exists()) {
        StringBuilder sb = new StringBuilder();
        sb.append(MessageFormat.format(PATTERN, DbObjType.SCHEMA, name));
        sb.append(MessageFormat.format(OWNER_TO, DbObjType.SCHEMA, name));
        file.create(new ByteArrayInputStream(sb.toString().getBytes()), false, null);
    }
    if (open) {
        openFileInEditor(file);
    }
    return schemaFolder;
}
 
Example 2
Project: Equella   File: JPFParentRepositoriesPage.java   View source code 6 votes vote down vote up
/**
 * @see PreferencePage#performOk
 */
@Override
public boolean performOk()
{
	if( !modified )
	{
		return true;
	}
	IPath path = Path.EMPTY;
	Object[] checked = listViewer.getCheckedElements();
	for( Object elements : checked )
	{
		path = path.append(((IProject) elements).getName());
	}
	IPreferenceStore prefs = getPreferenceStore();
	prefs.setValue(JPFClasspathPlugin.PREF_PARENT_REGISTRIES, path.toString());
	try
	{
		((IPersistentPreferenceStore) prefs).save();
	}
	catch( IOException e )
	{
		JPFClasspathLog.logError(e);
	}
	return true;
}
 
Example 3
Project: gw4e.project   File: ResourceManager.java   View source code 6 votes vote down vote up
/**
 * Test whether the project has the passed nature
 * 
 * @param receiver
 * @param nature
 * @return
 */
public static boolean hasNature(Object receiver, String nature) {
	IProject project = JDTManager.toJavaProject(receiver);
	if (project == null || !project.isOpen())
		return false;
	IProjectDescription description;
	try {
		description = project.getDescription();
	} catch (CoreException e) {
		ResourceManager.logException(e);
		return false;
	}
	String[] natures = description.getNatureIds();
	for (int i = 0; i < natures.length; i++) {
		if (nature.equalsIgnoreCase(natures[i]))
			return true;
	}
	return false;
}
 
Example 4
Project: gemoc-studio-modeldebugging   File: CreateDomainModelProjectHandler.java   View source code 6 votes vote down vote up
@Override
public Object executeForSelectedLanguage(ExecutionEvent event,
		IProject updatedGemocLanguageProject, Language language)
		throws ExecutionException {
	CreateDomainModelWizardContextAction action = new CreateDomainModelWizardContextAction(
			updatedGemocLanguageProject); 
	action.actionToExecute = CreateDomainModelAction.CREATE_NEW_EMF_PROJECT;
	action.execute();
	
	if(action.getCreatedEcoreUri() != null){
		waitForAutoBuild();
		updateMelange(event,language,action.getCreatedEcoreUri());
	}
	
	return null;
}
 
Example 5
Project: n4js   File: BuilderParticipantPluginTest.java   View source code 6 votes vote down vote up
/**
 * <ol>
 * <li>create Class1 file with having Class1.field0 -> should have no errors</li>
 * <li>create Class0 file with referencing Class1.field0 -> should have no errors as Class1 already created</li>
 * </ol>
 */
//@formatter:on
@Test
public void testNoErrorMarkersWhenReferencedFileIsCreatedBeforeReferencingFile() throws Exception {
	// create project and test files
	final IProject project = createJSProject("testNoErrorMarkersWhenReferencedFileIsCreatedBeforeReferencingFile");
	IFolder folder = configureProjectWithXtext(project);
	IFolder moduleFolder = createFolder(folder, TestFiles.moduleFolder());

	IFile file2 = createTestFile(moduleFolder, "Class1", TestFiles.class1());
	assertMarkers("File2 should have no errors", file2, 0);

	IFile file1 = createTestFile(moduleFolder, "Class0", TestFiles.class0());

	// The value of the local variable dummy is not used
	assertMarkers("File1 should have no errors", file1, 1);
}
 
Example 6
Project: gw4e.project   File: ResourceManager.java   View source code 6 votes vote down vote up
/**
 * Return a path relative to its package fragment root
 * 
 * @param project
 * @param path
 * @return
 * @throws JavaModelException
 */
public static IPath getPathWithinPackageFragment(IResource ifile) throws JavaModelException {
	IProject project = ifile.getProject();
	IPath path = ifile.getFullPath();
	String[] segments = path.segments();
	IJavaProject jproject = JavaCore.create(project);
	IPackageFragment[] pkgs = jproject.getPackageFragments();
	IPath p = new Path("/");
	for (int i = 0; i < segments.length; i++) {
		for (int j = 0; j < pkgs.length; j++) {
			if (pkgs[j].getPath().equals(p)) {
				IPath ret = path.makeRelativeTo(pkgs[j].getPath());
				return ret;
			}
		}
		p = p.append(segments[i]);
	}
	return null;
}
 
Example 7
Project: Equella   File: WorkspacePluginModelManager.java   View source code 6 votes vote down vote up
@Override
protected void createModel(IProject project, boolean notify)
{
	IPluginModel model = null;
	if( isPluginProject(project) )
	{
		model = new ProjectPluginModelImpl(this, project);
	}
	if( model != null )
	{
		fModels.put(project, model);
		if( notify )
		{
			addChange(model, IModelProviderEvent.MODELS_ADDED);
		}
	}
}
 
Example 8
Project: VerveineC-Cpp   File: FileUtil.java   View source code 6 votes vote down vote up
private static void mkdirs(IFolder destPath) {
	IContainer parent = destPath.getParent(); 
	if (! parent.exists()) {
		if (parent instanceof IFolder) {
			mkdirs((IFolder) parent);
		}
		else if (parent instanceof IProject) {
			mkdirs( ((IProject)parent).getFolder(".") );
		}
	}
	try {
		destPath.create(/*force*/true, /*local*/true, Constants.NULL_PROGRESS_MONITOR);
	} catch (CoreException e) {
		e.printStackTrace();
	}
}
 
Example 9
Project: ContentAssist   File: WorkspaceUtilities.java   View source code 6 votes vote down vote up
/**
 * Collects all compilation units within the project.
 * @return the collection of the compilation units
 */
public static List<ICompilationUnit> collectAllCompilationUnits() {
    List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();
    
    try {
        IProject[] projects =  getWorkspace().getRoot().getProjects();
        for (int i = 0; i < projects.length; i++) {
            IJavaProject project = (IJavaProject)JavaCore.create((IProject)projects[i]);
            
            IPackageFragment[] packages = project.getPackageFragments();
            for (int j = 0; j < packages.length; j++) {
                
                ICompilationUnit[] cus = packages[j].getCompilationUnits();
                for (int k = 0; k < cus.length; k++) {
                    IResource res = cus[k].getResource();
                    if (res.getType() == IResource.FILE) {
                        String name = cus[k].getPath().toString();
                        if (name.endsWith(".java")) { 
                            units.add(cus[k]);
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    
    return units;
}
 
Example 10
Project: convertigo-eclipse   File: StepTreeObject.java   View source code 6 votes vote down vote up
public void openXMLTransactionStepEditor(IProject project)
{
	TransactionStep transactionStep = (TransactionStep)this.getObject();
	
	IFile	file = project.getFile("_private/"+transactionStep.getName()+".xml");
	
	
	IWorkbenchPage activePage = PlatformUI
									.getWorkbench()
									.getActiveWorkbenchWindow()
									.getActivePage();
	if (activePage != null) {
		try {
			activePage.openEditor(new XMLTransactionStepEditorInput(file,transactionStep),
									"com.twinsoft.convertigo.eclipse.editors.xml.XMLTransactionStepEditor");
		}
		catch(PartInitException e) {
			ConvertigoPlugin.logException(e, "Error while loading the step editor '" + transactionStep.getName() + "'");
		} 
	}
}
 
Example 11
Project: org.xtext.dsl.restaurante   File: RestauranteProjectCreator.java   View source code 6 votes vote down vote up
protected IFileSystemAccess2 getFileSystemAccess(final IProject project, final IProgressMonitor monitor) {
	EclipseResourceFileSystemAccess2 access = fileSystemAccessProvider.get();
	access.setContext(project);
	access.setMonitor(monitor);
	OutputConfiguration defaultOutput = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT);
	defaultOutput.setDescription("Output Folder");
	defaultOutput.setOutputDirectory("./");
	defaultOutput.setOverrideExistingResources(true);
	defaultOutput.setCreateOutputDirectory(true);
	defaultOutput.setCleanUpDerivedResources(false);
	defaultOutput.setSetDerivedProperty(false);
	defaultOutput.setKeepLocalHistory(false);
	HashMap<String, OutputConfiguration> outputConfigurations = new HashMap<String, OutputConfiguration>();
	outputConfigurations.put(IFileSystemAccess.DEFAULT_OUTPUT, defaultOutput);
	access.setOutputConfigurations(outputConfigurations);
	return access;
}
 
Example 12
Project: n4js   File: GHOLD_45_CheckIgnoreAnnotationAtClassLevel_PluginUITest.java   View source code 6 votes vote down vote up
/**
 * Runs a test module with one single class that has method with {@code Ignore} annotation.
 */
@Ignore("IDE-2270")
@Test
public void testModuleWithIgnoredMethod() {
	final IProject project = getProjectByName(PROJECT_NAME);
	assertTrue("Project is not accessible.", project.isAccessible());
	final IFile module = project.getFile("test/X1.n4js");
	assertTrue("Module is not accessible.", module.isAccessible());

	runTestWaitResult(module);

	final String[] expected = { "X1#x12Test" };
	final String[] actual = getConsoleContentLines();

	assertArrayEquals(expected, actual);
}
 
Example 13
Project: n4js   File: GHOLD_45_CheckIgnoreAnnotationAtClassLevel_PluginUITest.java   View source code 6 votes vote down vote up
/**
 * Runs a test module with one single class that has neither super class nor {@code @Ignore} annotation.
 */
@Ignore("IDE-2270")
@Test
public void testModuleWithoutSuperClass() {
	final IProject project = getProjectByName(PROJECT_NAME);
	assertTrue("Project is not accessible.", project.isAccessible());
	final IFile module = project.getFile("test/A.n4js");
	assertTrue("Module is not accessible.", module.isAccessible());

	runTestWaitResult(module);

	final String[] expected = { "A#aTest" };
	final String[] actual = getConsoleContentLines();

	assertArrayEquals(expected, actual);
}
 
Example 14
Project: n4js   File: ProjectTypeAwareWorkingSetManager.java   View source code 6 votes vote down vote up
@Override
public IAdaptable[] getElements() {
	final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
	final IProject[] elements = new IProject[projects.length];
	int elementCount = 0;
	for (int i = 0, size = projects.length; i < size; i++) {
		final IProject project = projects[i];
		final IN4JSProject n4Project = core.findProject(toUri(project)).orNull();
		if (type == null) { // Other Projects
			if (n4Project == null || !n4Project.exists()) {
				elements[elementCount++] = project;
			}
		} else {
			if (n4Project != null && n4Project.exists() && type.equals(n4Project.getProjectType())) {
				elements[elementCount++] = project;
			}
		}
	}
	return Arrays.copyOfRange(elements, 0, elementCount);
}
 
Example 15
Project: n4js   File: NfarStorageMapper.java   View source code 6 votes vote down vote up
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
	if (uri.isArchive()) {
		URIBasedStorage storage = new URIBasedStorage(uri);
		String authority = uri.authority();
		URI archiveFileURI = URI.createURI(authority.substring(0, authority.length() - 1));
		Optional<? extends IN4JSEclipseProject> optionalProject = eclipseCore.findProject(archiveFileURI);
		if (optionalProject.isPresent()) {
			return Collections.singletonList(Tuples.<IStorage, IProject> create(storage, optionalProject.get()
					.getProject()));
		} else {
			return Collections.singletonList(Tuples.create(storage, null));
		}
	} else {
		return Collections.emptyList();
	}
}
 
Example 16
Project: convertigo-eclipse   File: TemplateTreeObject.java   View source code 6 votes vote down vote up
public void launchEditor(String editorType) {
	// Retrieve the workspace project
	try {
		String projectName = ((DatabaseObject) parent.getObject()).getProject().getName();
		
		// Refresh project resource
		IProject project = ConvertigoPlugin.getDefault().getProjectPluginResource(projectName);

		Sheet sheet = (Sheet) parent.getObject();
		//String parentStyleSheet = sheet.getUrl();

		// Gets the xsl file to be edited
		IFile file = project.getFile(new Path(xslPath));

		// Launch the XslStyleSheet Editor
		PlatformUI
				.getWorkbench()
				.getActiveWorkbenchWindow()
				.getActivePage()
				.openEditor(new XslFileEditorInput(file, projectName, sheet),
						"com.twinsoft.convertigo.eclipse.editors.xsl.XslRuleEditor");
	} catch (Exception pei) {
       	ConvertigoPlugin.logException(pei, "Unexpceted exception");
	}
}
 
Example 17
Project: neoscada   File: ProjectBuilder.java   View source code 6 votes vote down vote up
protected void validateAll ( final IProject project, final ComposedAdapterFactory adapterFactory, final Set<String> extensions, final IProgressMonitor monitor )
{
    logger.debug ( "Validating all resources of {}", project );

    try
    {
        project.accept ( new IResourceVisitor () {

            @Override
            public boolean visit ( final IResource resource ) throws CoreException
            {
                return handleResource ( null, resource, adapterFactory, extensions, monitor );
            }
        } );
    }
    catch ( final CoreException e )
    {
        StatusManager.getManager ().handle ( e.getStatus () );
    }
}
 
Example 18
Project: n4js   File: WorkspaceRepositoriesProvider.java   View source code 6 votes vote down vote up
/**
 * Handles the given resource delta.
 *
 * Fires workspace repository changed event if a project was opened/closed or a project was added/removed.
 */
private boolean handleResourceDelta(IResourceDelta delta) {
	IResource affectedResource = delta.getResource();

	if (affectedResource instanceof IProject) {
		// check if kind is CHANGED
		if ((delta.getKind() & IResourceDelta.CHANGED) == IResourceDelta.CHANGED) {
			// if project was opened/closed
			if ((delta.getFlags() & IResourceDelta.OPEN) == IResourceDelta.OPEN) {
				fireWorkspaceRepositoriesChanged();
				return false;
			}
		}
		// check if kind is ADDED or REMOVED
		else if ((delta.getKind() & IResourceDelta.ADDED | IResourceDelta.REMOVED) != 0) {
			fireWorkspaceRepositoriesChanged();
			return false;
		}
	}
	return true;
}
 
Example 19
Project: convertigo-eclipse   File: StatementTreeObject.java   View source code 6 votes vote down vote up
public void launchEditor(String editorType) {
	// Retrieve the project name
	String projectName = getObject().getProject().getName();
	try {
		// Refresh project resource
		IProject project = ConvertigoPlugin.getDefault().getProjectPluginResource(projectName);

		// Get editor type
		if (editorType == null) {
			editorType = "UnknownEditor";
			if (getObject() instanceof SimpleStatement)
				editorType = "JscriptStatementEditor";
		}
			
		// Open editor
		if (editorType.equals("JscriptStatementEditor"))
			openJscriptStatementEditor(project);
		
	} catch (CoreException e) {
		ConvertigoPlugin.logException(e, "Unable to open project named '" + projectName + "'!");
	}
}
 
Example 20
Project: gemoc-studio-modeldebugging   File: CreateXtextEditorProjectHandler.java   View source code 6 votes vote down vote up
@Override
public Object executeForSelectedLanguage(ExecutionEvent event,
		IProject updatedGemocLanguageProject, Language language)
		throws ExecutionException {
	CreateEditorProjectWizardContextAction action = new CreateEditorProjectWizardContextAction(
			updatedGemocLanguageProject);
	action.actionToExecute = CreateEditorProjectAction.CREATE_NEW_XTEXT_PROJECT;
	action.execute();
	
	if(action.getSiriusPath() != null){
		waitForAutoBuild();
		updateMelange(event,language,action.getXtextPath());
	}
	
	return null;
}
 
Example 21
Project: Hydrograph   File: DebugLocalJobLauncher.java   View source code 6 votes vote down vote up
/**
 * Execute command.
 *
 * @param job the job
 * @param project the project
 * @param gradleCommand the gradle command
 * @param gefCanvas the gef canvas
 */
private void executeCommand(Job job, IProject project, String gradleCommand, DefaultGEFCanvas gefCanvas) {
	ProcessBuilder processBuilder = JobScpAndProcessUtility.INSTANCE.getProcess(project, gradleCommand);
	try {
		Process process = processBuilder.start();

		job.setLocalJobProcess(process);
		JobLogger joblogger = initJobLogger(gefCanvas,job.getUniqueJobId());

		JobManager.INSTANCE.addJob(job);
		logProcessLogsAsynchronously(joblogger, process, job);

	} catch (IOException e) {
		logger.debug("Unable to execute the job", e);
	}
}
 
Example 22
Project: Hydrograph   File: PasteHandler.java   View source code 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	List<IFile> jobFiles = new ArrayList<>();
	List<IFile> pastedFileList = new ArrayList<>();
	IWorkbenchPart part = HandlerUtil.getActivePart(event);
	if(part instanceof CommonNavigator){
		PasteAction action = new PasteAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getSite());
		action.run();
		IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();
		IProject project = workSpaceRoot.getProject(JobCopyParticipant.getCopyToPath().split("/")[1]);
		IFolder jobFolder = project.getFolder(
				JobCopyParticipant.getCopyToPath().substring(JobCopyParticipant.getCopyToPath().indexOf('/', 2)));
		IFolder paramFolder = project.getFolder(PARAMETER_FOLDER_NAME);
		try {
			createCurrentJobFileList(jobFolder, jobFiles);
			pastedFileList=getPastedFileList(jobFiles);
			generateUniqueJobIdForPastedFiles(pastedFileList);
			createXmlFilesForPastedJobFiles(pastedFileList);
			List<String> copiedPropertiesList = getCopiedPropertiesList();
			createPropertiesFilesForPastedFiles(paramFolder, pastedFileList, copiedPropertiesList);
			JobCopyParticipant.cleanUpStaticResourcesAfterPasteOperation();

		} catch (CoreException  coreException) {
			logger.warn("Error while copy paste jobFiles",coreException.getMessage() );
		}
		
	}
	
	else if(part instanceof ELTGraphicalEditor){
		IEditorPart editor = HandlerUtil.getActiveEditor(event);
		((ELTGraphicalEditor)editor).pasteSelection();
	}
	
	return null;
}
 
Example 23
Project: n4js   File: N4JSEclipseModel.java   View source code 5 votes vote down vote up
public Iterable<IN4JSProject> findAllProjects() {

		final Map<String, IProject> workspaceProjectMapping = newLinkedHashMap();
		for (final IProject workspaceProject : from(asList(workspace.getProjects())).filter(p -> p.isOpen())) {
			workspaceProjectMapping.put(workspaceProject.getName(), workspaceProject);
		}

		for (final IProject project : externalLibraryWorkspace.getProjects()) {
			if (!workspaceProjectMapping.containsKey(project.getName())) {
				workspaceProjectMapping.put(project.getName(), project);
			}
		}

		return from(workspaceProjectMapping.values()).transform(p -> getN4JSProject(p));
	}
 
Example 24
Project: SimQRI   File: WorkspaceManager.java   View source code 5 votes vote down vote up
/**
 * 
 * @return the list of all simqri modeling projects name available in the user's workspace
 */
public static List<String> getModelingProjects() { // ONLY the open ones !
	List<String> projectsNameList = new ArrayList<String>();
	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for(int i=0 ; i<projects.length; i++) {
		if(projects[i].getFile("representations.aird").exists()) {
			projectsNameList.add(projects[i].getName());
		}
	}
	return projectsNameList;
}
 
Example 25
Project: vertigo-chroma-kspplugin   File: JdtUtils.java   View source code 5 votes vote down vote up
/**
 * Obtient le type JDT pour un nom complet qualifié dans un projet donné.
 * 
 * @param fullyQualifiedName Nom complet qualifié.
 * @param project Projet.
 * @return Le type JDT, <code>null</code> sinon.
 */
public static IType getJavaType(String fullyQualifiedName, IProject project) {
	IJavaProject javaProject = JavaCore.create(project);
	try {
		return javaProject.findType(fullyQualifiedName);
	} catch (Exception e) {
		ErrorUtils.handle(e);
	}
	return null;
}
 
Example 26
Project: Hydrograph   File: RenameJobParticipant.java   View source code 5 votes vote down vote up
@Override
protected boolean initialize(Object element) {
	this.modifiedResource = (IFile) element;
	if (modifiedResource.getParent() != null && modifiedResource.getParent().getParent() instanceof IProject) {
		if (StringUtils.equalsIgnoreCase(Messages.PROPERTIES_EXT, modifiedResource.getFileExtension())) {
			if (!StringUtils.equalsIgnoreCase(modifiedResource.getParent().getName(), Messages.PARAM)) {
				return false;
			}
		}
	}
	return true;
}
 
Example 27
Project: gw4e.project   File: Helper.java   View source code 5 votes vote down vote up
public static IPath buildModelAnnotationValue (IFile in) {
	IPath ret = null;
	if (!PreferenceManager.isGraphModelFile(in)) return null;
	IProject project = in.getProject();
	String[] folders = PreferenceManager.getAuthorizedFolderForGraphDefinition();
	for (int i = 0; i < folders.length; i++) {
		IPath base = project.getFullPath().append(folders[i]);
		if (base.isPrefixOf(in.getFullPath())) {
			ret = in.getFullPath().makeRelativeTo(base);
			break;
		}
	}
	return ret;
}
 
Example 28
Project: gemoc-studio-modeldebugging   File: CreateDomainModelWizardContextAction.java   View source code 5 votes vote down vote up
protected void selectExistingEMFProject() {
	// launch the appropriate wizard
	SelectEMFIProjectDialog dialog = new SelectEMFIProjectDialog(PlatformUI
			.getWorkbench().getActiveWorkbenchWindow().getShell());
	int res = dialog.open();
	if (res == WizardDialog.OK) {
		// update the project model
		addEMFProjectToConf(((IProject) dialog.getResult()[0]));
	}
}
 
Example 29
Project: neoscada   File: ProjectBuilder.java   View source code 5 votes vote down vote up
private boolean isInterestingProject ( final IProject project )
{
    try
    {
        final boolean result = project.hasNature ( Constants.PROJECT_NATURE_CONFIGURATION );
        logger.debug ( "Checking project - project: {}, result: {}", project, result );
        return result;
    }
    catch ( final CoreException e )
    {
        StatusManager.getManager ().handle ( e.getStatus () );
        return false;
    }

}
 
Example 30
Project: gw4e.project   File: GW4EBuilder.java   View source code 5 votes vote down vote up
/**
 * Implement a full build 
 * @param monitor
 * @throws CoreException
 */
protected void fullBuild(final IProgressMonitor monitor) throws CoreException {
	try {
		 
		IProject project = getProject();
		deleteMarkers(project);
		if (!PreferenceManager.isBuildEnabled(project.getName())) return;
		getProject().accept(new GW4EResourceVisitor());
	} catch (CoreException e) {
		ResourceManager.logException(e);
	}
}
 
Example 31
Project: eclipse-commons   File: TestToIResourcePositive.java   View source code 5 votes vote down vote up
@Test
public void projectSlash() throws Exception {
	URI uri = URI.createPlatformResourceURI("/myProject/", true);
	IResource iResource = UriUtils.toIResource(uri);

	assertTrue(iResource instanceof IProject);
	assertTrue(iResource.exists());
	assertEquals("/myProject", iResource.getFullPath().toString());
}
 
Example 32
Project: visuflow-plugin   File: ProjectListener.java   View source code 5 votes vote down vote up
@Override
public void resourceChanged(IResourceChangeEvent event) {
	IResourceDelta delta = event.getDelta();
	if (delta.getResource().getType() == IResource.ROOT) {
		List<IProject> projects = getProjects(event.getDelta());
		// do something with new projects
		for (IProject project : projects) {
			try {
				triggerBuild(project);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}
}
 
Example 33
Project: convertigo-eclipse   File: SheetTreeObject.java   View source code 5 votes vote down vote up
public void launchEditor(String editorType) {
	// Retrieve the project name
	String projectName = getObject().getProject().getName();
	try {
		// Refresh project resource
		IProject project = ConvertigoPlugin.getDefault().getProjectPluginResource(projectName);

		// Open editor
		openXslEditor(project);
		
	} catch (CoreException e) {
		ConvertigoPlugin.logException(e, "Unable to open project named '" + projectName + "'!");
	}
}
 
Example 34
Project: gemoc-studio   File: ClasspathHelper.java   View source code 5 votes vote down vote up
/**
 * Add a new entry to the existing java project
 * 	you can use JavaCore factory to create the entry itself
 * 	ex : JavaCore.newProjectEntry(ecoreIFile.getProject().getFullPath())
 * If the entry is already there, the method will do nothing.
 */
public static void addEntry(IProject project, IClasspathEntry newEntry, IProgressMonitor monitor) throws CoreException{
	IJavaProject javaProject = (IJavaProject)project.getNature(JavaCore.NATURE_ID);
	ArrayList<IClasspathEntry> newClassPathArrayList = new ArrayList<IClasspathEntry>();
	IClasspathEntry[] previousentries = javaProject.getRawClasspath();
	for(IClasspathEntry previousentry : previousentries){
		newClassPathArrayList.add(previousentry);
	}
	if(!newClassPathArrayList.contains(newEntry)){
		newClassPathArrayList.add(newEntry);
		IClasspathEntry[] newClassPath = new IClasspathEntry[newClassPathArrayList.size()];
		javaProject.setRawClasspath(newClassPathArrayList.toArray(newClassPath), monitor);
	}
}
 
Example 35
Project: eclipse-commons   File: TestToIResourcePositive.java   View source code 5 votes vote down vote up
@Test
public void project() throws Exception {
	URI uri = URI.createPlatformResourceURI("/myProject", true);
	IResource iResource = UriUtils.toIResource(uri);

	assertTrue(iResource instanceof IProject);
	assertTrue(iResource.exists());
	assertEquals("/myProject", iResource.getFullPath().toString());
}
 
Example 36
Project: n4js   File: NpmManager.java   View source code 5 votes vote down vote up
private Pair<Collection<String>, Iterable<java.net.URI>> getChangedDependencies(final IProgressMonitor monitor,
		Set<String> oldNPMs) {

	logger.logInfo(LINE_SINGLE);
	logger.logInfo("Calculating dependency changes... [step 2 of 4]");
	monitor.setTaskName("Calculating dependency changes... [step 2 of 4]");

	externalLibraryWorkspace.updateState();
	URI targetPlatformNodeModulesLocation = locationProvider.getTargetPlatformNodeModulesLocation();

	Map<String, String> afterDependencies = locationProvider.getTargetPlatformContent().dependencies;
	if (null == afterDependencies) {
		afterDependencies = newHashMap();
	}
	final Set<String> newDependencies = new HashSet<>(afterDependencies.keySet());

	Set<String> newNpmProjectNames = new HashSet<>();
	Iterable<IProject> newNPMs = externalLibraryWorkspace.getProjects(targetPlatformNodeModulesLocation);
	for (IProject newNPM : newNPMs) {
		newNpmProjectNames.add(newNPM.getName());
	}

	Set<String> overwrittenShippedLibNames = getOverwrittenShippedLibs(newNpmProjectNames);
	newDependencies.addAll(overwrittenShippedLibNames);

	final Collection<String> addedDependencies = difference(newDependencies, oldNPMs);
	final Collection<String> deletedDependencies = difference(oldNPMs, newDependencies);
	final File nodeModulesFolder = new File(targetPlatformNodeModulesLocation);
	final Iterable<java.net.URI> toBeDeleted = from(deletedDependencies)
			.transform(name -> new File(nodeModulesFolder, name).toURI());
	monitor.worked(1);
	logger.logInfo("Dependency changes have been successfully calculated.");

	Pair<Collection<String>, Iterable<java.net.URI>> changedDeps = Tuples.pair(addedDependencies, toBeDeleted);

	return changedDeps;
}
 
Example 37
Project: pgcodekeeper   File: AddBuilder.java   View source code 5 votes vote down vote up
public static IProject getProject(final ExecutionEvent event) {
    final ISelection selection = HandlerUtil.getCurrentSelection(event);
    if (selection instanceof IStructuredSelection) {
        final Object element = ((IStructuredSelection) selection)
                .getFirstElement();

        return Platform.getAdapterManager().getAdapter(element,
                IProject.class);
    }

    return null;
}
 
Example 38
Project: n4js   File: WorkingSetManagerStartup.java   View source code 5 votes vote down vote up
@Override
public void earlyStartup() {
	// This will automatically register the proper listeners to keep the different working set managers in sync.
	workingSetManagerBroker.getWorkingSetManagers();

	// Listener to refresh navigator on project creation or on open/close event.
	getWorkspace().addResourceChangeListener(event -> {
		if (event != null && event.getDelta() != null) {
			try {
				event.getDelta().accept(delta -> {
					final IResource resource = delta.getResource();
					if (resource instanceof IWorkspaceRoot) {
						return true;
					} else if (resource instanceof IProject) {
						if (ADDED == delta.getKind()
								|| (CHANGED == delta.getKind() && (delta.getFlags() & OPEN) != 0)) {
							workingSetManagerBroker.refreshNavigator();
						}
					}
					return false;
				});
			} catch (final CoreException e) {
				LOGGER.error("Error occurred while visiting resource delta.", e);
			}
		}
	});
}
 
Example 39
Project: gemoc-studio-modeldebugging   File: CreateDSAWizardContextBase.java   View source code 5 votes vote down vote up
protected void addDSAProjectToConf(String projectName,IProject gemocLanguageIProject) {
	ManifestChanger manifestChanger = new ManifestChanger(gemocLanguageIProject);
	try {
		manifestChanger.addPluginDependency(projectName);
		manifestChanger.commit();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 40
Project: gw4e.project   File: ProjectHelper.java   View source code 5 votes vote down vote up
public static IJavaProject createProject(String name) throws CoreException {

		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IProject project = root.getProject(name);
		if (!project.exists()) {
			project.create(new NullProgressMonitor());
		} else {
			project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		}

		if (!project.isOpen()) {
			project.open(new NullProgressMonitor());
		}

		IFolder binFolder = project.getFolder("bin");
		if (!binFolder.exists()) {
			createFolder(binFolder, false, true, new NullProgressMonitor());
		}
		IPath outputLocation = binFolder.getFullPath();

		addNatureToProject(project, JavaCore.NATURE_ID, new NullProgressMonitor());

		IJavaProject jproject = JavaCore.create(project);
		jproject.setOutputLocation(outputLocation, new NullProgressMonitor());

		IClasspathEntry[] entries = PreferenceConstants.getDefaultJRELibrary();

		jproject.setRawClasspath(entries, new NullProgressMonitor());

		return jproject;
	}