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

The following are top voted examples for showing how to use org.eclipse.core.resources.IResource. 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: eclipse-batch-editor   File: BatchEditor.java   View source code 6 votes vote down vote up
private int getSeverity() {
	IEditorInput editorInput = getEditorInput();
	if (editorInput == null) {
		return IMarker.SEVERITY_INFO;
	}
	try {
		final IResource resource = ResourceUtil.getResource(editorInput);
		if (resource == null) {
			return IMarker.SEVERITY_INFO;
		}
		int severity = resource.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
		return severity;
	} catch (CoreException e) {
		// Might be a project that is not open
	}
	return IMarker.SEVERITY_INFO;
}
 
Example 2
Project: eclipse-commons   File: TestToIResourcePositive.java   View source code 6 votes vote down vote up
@Test
public void fileNested() throws Exception {
	waitForWorkspaceChanges(() -> {
		project.getFolder("/folder").create(true, true, null);
		project.getFolder("/folder/deep/").create(true, true, null);
		IFile file = project.getFile("/folder/deep/myFile.ext");
		file.create(new NullInputStream(0), true, null);
	});

	URI uri = URI.createPlatformResourceURI("/myProject/folder/deep/myFile.ext", true);
	IResource iResource = UriUtils.toIResource(uri);

	assertTrue(iResource instanceof IFile);
	assertTrue(iResource.exists());
	assertEquals("/myProject/folder/deep/myFile.ext", iResource.getFullPath().toString());
}
 
Example 3
Project: gw4e.project   File: BuildPoliciesCache.java   View source code 6 votes vote down vote up
/**
 * @param projectName
 * @param container
 * @param monitor
 */
private static void deleteCache(String cachename, IContainer container, IProgressMonitor monitor) {
	try {
		IResource[] members = container.members();
		for (IResource member : members) {
			if (member instanceof IContainer) {
				deleteCache(cachename, (IContainer) member, monitor);
			} else if (member instanceof IFile) {
				IFile file = (IFile) member;
				if (cachename.equals(file.getName())) {
					file.delete(true, monitor);
				}
			}
		}
	} catch (CoreException e) {
		ResourceManager.logException(e);
	}
}
 
Example 4
Project: Hydrograph   File: FilterOperationClassUtility.java   View source code 6 votes vote down vote up
/**
 * @param filterExtension
 * @param fileName
 * Open the dialog to browse .xml file for expression, operation or outputfields
 */
private void browseXMLSelectionDialog(String filterExtension, Text fileName) {
	String externalSchemaTextBoxValue = "";
	ExternalSchemaFileSelectionDialog dialog = new ExternalSchemaFileSelectionDialog("Project",
			"Select Input File (.xml)",  new String[]{filterExtension,Extensions.XML.toString()}, this);
	if (dialog.open() == IDialogConstants.OK_ID) {
		String file = fileNameTextBoxValue;
		IResource resource = (IResource) dialog.getFirstResult();
		String path[] = resource.getFullPath().toString().split("/");
		if (file.isEmpty()) {
			for (int i = 1; i < path.length; i++) {
				externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/";
			}
		} else {
			for (int i = 1; i < path.length; i++) {
				if (!path[i].endsWith(".xml")) {
					externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/";
				}
			}
			externalSchemaTextBoxValue = externalSchemaTextBoxValue + file;
		}
		fileName.setText(externalSchemaTextBoxValue);
	}
}
 
Example 5
Project: visuflow-plugin   File: WizardPageHandler.java   View source code 6 votes vote down vote up
/**
 * This method ensures user select Target project and permissions
 */
private void dialogChanged() {
	IResource container = ResourcesPlugin.getWorkspace().getRoot()
			.findMember(new Path(getContainerName().get("TargetPath")));
	

	if (getContainerName().get("TargetPath").length() == 0) {
		updateStatus("File container must be specified");
		return;
	}
	if (container == null
			|| (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
		updateStatus("File container must exist");
		return;
	}
	if (!container.isAccessible()) {
		updateStatus("Project must be writable");
		return;
	}
	updateStatus(null);
}
 
Example 6
Project: n4js   File: ProjectSelectionDialog.java   View source code 6 votes vote down vote up
@Override
public Object[] getElements(Object inputElement) {
	if (inputElement instanceof IContainer) {
		try {
			List<IResource> projects = Arrays.asList(((IContainer) inputElement).members()).stream()
					.filter(member -> member instanceof IProject)
					.filter(project -> isN4JSProject((IProject) project))
					.sorted(new ResourceComparator())
					.collect(Collectors.toList());

			return projects.toArray(new IResource[projects.size()]);

		} catch (CoreException e) {
			e.printStackTrace();
			return null;
		}
	}
	return null;
}
 
Example 7
Project: gw4e.project   File: ResourceManager.java   View source code 6 votes vote down vote up
/**
 * Process recursively the containers until we found a resource with the
 * specified path
 * 
 * @param container
 * @param path
 * @return
 * @throws CoreException
 */
private static boolean resourceExistsIn(IContainer container, IPath path) throws CoreException {
	boolean found = false;
	IResource[] members = container.members();
	for (IResource member : members) {
		if (member instanceof IContainer) {

			found = resourceExistsIn((IContainer) member, path);
			if (found)
				break;
		} else if (member instanceof IFile) {
			IFile file = (IFile) member;

			if (path.equals(file.getFullPath()))
				return true;
		}
	}
	return found;
}
 
Example 8
Project: solidity-ide   File: SolidityCompilerBase.java   View source code 6 votes vote down vote up
@Override
public void compile(List<URI> uris, IProgressMonitor progress) {
	Set<IResource> filesToCompile = getFilesToCompile(uris);
	if (filesToCompile.isEmpty() || progress.isCanceled()) {
		return;
	}
	progress.beginTask("compiling ...", filesToCompile.size());
	try {
		Process process = new ProcessBuilder(getCompilerPath(), "--standard-json").start();
		sendInput(process.getOutputStream(), filesToCompile);
		handler.handleOutput(process.getInputStream(), filesToCompile);
		if (process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() != 0) {
			throw new Exception("Solidity compiler invocation failed with exit code " + process.exitValue() + ".");
		}
		progress.done();

	} catch (Exception e) {
		e.printStackTrace();
		progress.done();
	}

}
 
Example 9
Project: Equella   File: JPFManifestBuilder.java   View source code 6 votes vote down vote up
@Override
public boolean visit(IResourceDelta delta) throws CoreException
{
	IResource resource = delta.getResource();
	if( resource.isDerived() )
	{
		return false;
	}
	if( resource.getType() == IResource.FILE )
	{
		IFile file = (IFile) resource;
		IProject project = resource.getProject();
		if( file.equals(JPFProject.getManifest(project)) )
		{
			manifestChanged = true;
			return false;
		}
	}
	return true;
}
 
Example 10
Project: gemoc-studio-modeldebugging   File: SiriusEditorUtils.java   View source code 6 votes vote down vote up
/**
 * Show the given {@link EObject instruction}.
 * 
 * @param editorPart
 *            the opened {@link DialectEditor}
 * @param instruction
 *            the {@link EObject instruction} to show
 */
public static void showInstruction(DialectEditor editorPart, EObject instruction) {
	final URI resourceURI = instruction.eResource().getURI();
	if (resourceURI.isPlatformResource()) {
		final String resourcePath = resourceURI.toPlatformString(true);
		final IResource resource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(
				resourcePath));
		try {
			final IMarker marker = resource.createMarker(EValidator.MARKER);
			marker.setAttribute(EValidator.URI_ATTRIBUTE, EcoreUtil.getURI(instruction).toString());
			final TraceabilityMarkerNavigationProvider navigationProvider = new TraceabilityMarkerNavigationProvider(
					(DialectEditor)editorPart);
			navigationProvider.gotoMarker(marker);
			marker.delete();
		} catch (CoreException e) {
			DebugSiriusIdeUiPlugin.INSTANCE.log(e);
		}
	}
}
 
Example 11
Project: Hydrograph   File: JobDeleteParticipant.java   View source code 6 votes vote down vote up
private void setJobFileAndXmlFile(IFolder jobsFolder) {
	try {
		IResource[] members = jobsFolder.members();
		if (members != null) {
			for (IResource jobFolderMember : members) {
				if ((IFolder.class).isAssignableFrom(jobFolderMember.getClass())) {
					setJobFileAndXmlFile((IFolder) jobFolderMember);
				} else if ((IFile.class).isAssignableFrom(jobFolderMember.getClass())) {
					String file = jobFolderMember.getFullPath().lastSegment();
					if (StringUtils.equalsIgnoreCase(modifiedResource.getName().replace(Constants.PROPERTIES_EXTENSION,
							Constants.JOB_EXTENSION), file)) {
						jobIFile = jobsFolder.getFile(modifiedResource.getName()
								.replace(Constants.PROPERTIES_EXTENSION, Constants.JOB_EXTENSION));
					} else if (StringUtils.equalsIgnoreCase(modifiedResource.getName().replace(Constants.PROPERTIES_EXTENSION,
							Constants.XML_EXTENSION), file)) {
						xmlIFile = jobsFolder.getFile(modifiedResource.getName()
								.replace(Constants.PROPERTIES_EXTENSION, Constants.XML_EXTENSION));
					}
				}
			}
		}
	} catch (CoreException coreException) {
		LOGGER.error("Error while setting job file and xml file for dependent deletion", coreException);
	}
}
 
Example 12
Project: gw4e.project   File: GW4EBuilder.java   View source code 6 votes vote down vote up
/**
 * @param project
 * @param file
 */
public static void removeMarkerForAbstractContextUsed (IFile file) {
	try {
		IMarker[] markers = file.findMarkers(GW4EBuilder.MARKER_TYPE, true, IResource.DEPTH_INFINITE);
		for (int i = 0; i < markers.length; i++) {
			IMarker m = markers[i];
			Integer pbId = (Integer)m.getAttribute(IJavaModelMarker.ID);
			if (pbId!=null) {
				if (GW4EParser.ABSTRACT_CONTEXT_USED==pbId.intValue()) {
					m.delete();
				}
			}
		}
	} catch (CoreException ce) {
	}
}
 
Example 13
Project: n4js   File: CleanInstruction.java   View source code 6 votes vote down vote up
private void cleanOutput(IProject aProject, OutputConfiguration config, IProgressMonitor monitor)
		throws CoreException {
	IContainer container = getContainer(aProject, config.getOutputDirectory());
	if (!container.exists()) {
		return;
	}
	if (config.isCanClearOutputDirectory()) {
		for (IResource resource : container.members()) {
			resource.delete(IResource.KEEP_HISTORY, monitor);
		}
	} else if (config.isCleanUpDerivedResources()) {
		List<IFile> resources = derivedResourceMarkers.findDerivedResources(container, null);
		for (IFile iFile : resources) {
			iFile.delete(IResource.KEEP_HISTORY, monitor);
		}
	}
}
 
Example 14
Project: Tarski   File: CountMarkersInResourceHandler.java   View source code 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
  ISelection selection = MarkerFactory.getSelection();
  if (selection instanceof ITreeSelection) {
    ITreeSelection treeSelection = (ITreeSelection) selection;
    if (treeSelection.getFirstElement() instanceof IOpenable
        || treeSelection.getFirstElement() instanceof IFile) {
      IResource resource =
          ((IAdaptable) treeSelection.getFirstElement()).getAdapter(IResource.class);
      List<IMarker> markers = MarkerFactory.findMarkers(resource);
      MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(), "Marker Count", null,
          markers.size() + " marker(s)", MessageDialog.INFORMATION, new String[] {"OK"}, 0);
      dialog.open();
    }
  }
  return null;
}
 
Example 15
Project: gw4e.project   File: JDTManager.java   View source code 6 votes vote down vote up
public static ICompilationUnit[] getOrCreateGeneratedTestInterfaces(IProject project)
		throws CoreException, FileNotFoundException {
	
	project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
	IPath folderForMain = project.getFullPath()
			.append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), true));
	IPath folderForTest = project.getFullPath()
			.append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), false));
	if (ResourceManager.getResource(folderForMain.toString()) == null
			&& ResourceManager.getResource(folderForTest.toString()) == null) {
		throw new IllegalStateException(
				"No target/generated-sources or target/generated-test-sources folders found");
	}

 
 
	// In main resource folder
	ICompilationUnit[] inMain = getExistingGeneratedTestInterfaces(project, true);
	// In test resource folder
	ICompilationUnit[] inTest = getExistingGeneratedTestInterfaces(project, false);
	ICompilationUnit[] ret = new ICompilationUnit[inMain.length+inTest.length];
	System.arraycopy(inMain, 0, ret, 0, inMain.length);
	System.arraycopy(inTest, 0, ret, inMain.length, inTest.length);
	return ret;
}
 
Example 16
Project: dsp4e   File: DSPDebugTarget.java   View source code 6 votes vote down vote up
private void addBreakpointToMap(IBreakpoint breakpoint) throws CoreException {
	Assert.isTrue(supportsBreakpoint(breakpoint) && breakpoint instanceof ILineBreakpoint);
	if (breakpoint instanceof ILineBreakpoint) {
		ILineBreakpoint lineBreakpoint = (ILineBreakpoint) breakpoint;
		IResource resource = lineBreakpoint.getMarker().getResource();
		IPath location = resource.getLocation();
		String path = location.toOSString();
		String name = location.lastSegment();
		int lineNumber = lineBreakpoint.getLineNumber();

		Source source = new Source().setName(name).setPath(path);

		List<SourceBreakpoint> sourceBreakpoints = targetBreakpoints.computeIfAbsent(source,
				s -> new ArrayList<>());
		sourceBreakpoints.add(new SourceBreakpoint().setLine(lineNumber));
	}
}
 
Example 17
Project: EclipseMinifyBuilder   File: PrefsAccess.java   View source code 6 votes vote down vote up
/**
 * Remove a resource (i.e. all its properties) from the builder's preferences.
 * 
 * @param prefs the preferences
 * @param resource the resource
 * @throws BackingStoreException
 */
public static void removeResource(Preferences prefs, IResource resource) 
		throws CoreException {
	try {
		String[] keys = prefs.keys();
		for (String key: keys) {
			if (key.endsWith("//" + resource.getProjectRelativePath().toPortableString())) {
				prefs.remove(key);
			}
		}
		prefs.flush();
	} catch (BackingStoreException e) {
		throw new CoreException(new Status(
				IStatus.ERROR, MinifyBuilder.BUILDER_ID, e.getMessage(), e));
	}
}
 
Example 18
Project: ec4e   File: EditorConfigSearchQuery.java   View source code 6 votes vote down vote up
@Override
public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {
	startTime = System.currentTimeMillis();
	AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult();
	textResult.removeAll();

	try {

		IContainer dir = configFile.getParent();
		dir.accept(new AbstractSectionPatternVisitor(section) {

			@Override
			protected void collect(IResourceProxy proxy) {
				Match match = new FileMatch((IFile) proxy.requestResource());
				result.addMatch(match);
			}
		}, IResource.NONE);

		return Status.OK_STATUS;
	} catch (Exception ex) {
		return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex);
	}
}
 
Example 19
Project: gw4e.project   File: PreferenceManager.java   View source code 6 votes vote down vote up
/**
 * Return the allowed folder where test can be generated in depending on the
 * user selection if the selected graph is in src/main/resource then
 * src/main/java if the selected graph is in src/test/resource then
 * src/test/java
 * 
 * @return
 */
public static IPath getTargetFolderForGeneratedTests(IResource selectedGraphFile) {

	IProject project = selectedGraphFile.getProject();

	IPath pathResourceTestFolder = project.getFullPath().append(getTestResourceFolder());
	if (ResourceManager.isInFolder(pathResourceTestFolder,
			selectedGraphFile.getParent().getFullPath()))
		return project.getFullPath().append(getTestSourceFolder());

	IPath pathResourceMainFolder = project.getFullPath().append(getMainResourceFolder());
	if (ResourceManager.isInFolder(pathResourceMainFolder,
			selectedGraphFile.getParent().getFullPath()))
		return project.getFullPath().append(getMainSourceFolder());
	return null;
}
 
Example 20
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 21
Project: pgcodekeeper   File: PgDecorator.java   View source code 6 votes vote down vote up
@Override
public void decorate(Object element, IDecoration decoration) {
    if (element instanceof IResource) {
        IResource res = (IResource) element;
        IProject proj = res.getProject();
        try {
            if (proj != null && proj.isAccessible() && proj.hasNature(NATURE.ID)) {
                IMarker[] markers = res.findMarkers(MARKER.ERROR, false,
                        IResource.DEPTH_INFINITE);
                if (markers.length > 0) {
                    decoration.addOverlay(PlatformUI.getWorkbench().getSharedImages()
                            .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR));
                }
            }
        } catch (CoreException e) {
            Log.log(e);
        }
    }
}
 
Example 22
Project: SimQRI   File: WorkspaceManager.java   View source code 6 votes vote down vote up
/**
 * 
 * @param modelingProject the name of the selected modeling project
 * @return the list of all the report templates name that are available in the selected modeling project
 */
public static List<String> getTemplates(String modelingProject) { // For the SimulationManagementWindow (names)
	List<String> templatesName = new ArrayList<String>();
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(modelingProject);
	IFolder templatesFolder = project.getFolder("Report Templates");
	try {
		IResource[] folderContent = templatesFolder.members();
		for(IResource resource : folderContent) {
			if(resource.getType() == IFile.FILE && resource.getFileExtension().equals("rptdesign")) {
				templatesName.add(resource.getName());
			}
		}
	} catch (CoreException e) {
		e.printStackTrace();
		JOptionPane.showMessageDialog(null, "Error: " + e.getMessage() + "", "Error", JOptionPane.ERROR_MESSAGE);
	}
	return templatesName;
}
 
Example 23
Project: Tarski   File: MarkerFactory.java   View source code 6 votes vote down vote up
/**
 * Finds a marker for given selection on the tree
 *
 * @param treeSelection
 * @param resource
 * @return
 */
public static IMarker findMarkerByTreeSelection(final ITreeSelection treeSelection,
    final IResource resource) {
  final Object o = treeSelection.getFirstElement();
  if (o != null && o instanceof EObject) {
    final String uri = EcoreUtil.getURI((EObject) o).toString();

    final List<IMarker> markers = MarkerFactory.findMarkers(resource);

    for (final IMarker iMarker : markers) {
      if (uri.equals(MarkUtilities.getUri(iMarker))) {
        return iMarker;
      }
    }
  }
  return null;
}
 
Example 24
Project: solidity-ide   File: SolidityMarkerCreator.java   View source code 6 votes vote down vote up
private SolcIssue createSolcIssue(CompileError error, Set<IResource> filesToCompile) {
	String[] parts = error.getFormattedMessage().split(":");
	String fileName = partAtIndex(parts, 0);
	IFile errorFile = findFileForName(filesToCompile, fileName);
	int lineNumber = extractNumber(partAtIndex(parts, 1));
	int columnNumber = extractNumber(partAtIndex(parts, 2));
	Map<Integer, String> fileContent = getFileContent(errorFile);
	int offset = calculateOffset(fileContent, columnNumber, lineNumber);
	int length = calculateIssueLength(fileContent.get(lineNumber), partAtIndex(parts, 4));

	Severity severity = calculateSeverity(error.getSeverity());
	String message = error.getMessage();
	SolcIssue solcIssue = new SolcIssue();
	solcIssue.setIFile(errorFile);
	solcIssue.setLineNumber(lineNumber);
	solcIssue.setColumnNumber(columnNumber);
	solcIssue.setSeverity(severity);
	solcIssue.setMessage(message);
	solcIssue.setOffset(offset);
	solcIssue.setLength(length);
	solcIssue.setErrorCode(createErrorCodeFromMessage(severity, message));
	EObject element = getEObject(errorFile, offset);
	solcIssue.setUriToProblem(EcoreUtil.getURI(element));
	return solcIssue;
}
 
Example 25
Project: eclipse-batch-editor   File: BatchEditor.java   View source code 6 votes vote down vote up
private boolean isMarkerChangeForThisEditor(IResourceChangeEvent event) {
	IResource resource = ResourceUtil.getResource(getEditorInput());
	if (resource == null) {
		return false;
	}
	IPath path = resource.getFullPath();
	if (path == null) {
		return false;
	}
	IResourceDelta eventDelta = event.getDelta();
	if (eventDelta == null) {
		return false;
	}
	IResourceDelta delta = eventDelta.findMember(path);
	if (delta == null) {
		return false;
	}
	boolean isMarkerChangeForThisResource = (delta.getFlags() & IResourceDelta.MARKERS) != 0;
	return isMarkerChangeForThisResource;
}
 
Example 26
Project: eclipse-jenkins-editor   File: JenkinsEditorUtil.java   View source code 6 votes vote down vote up
public static void addLinterError(IEditorPart editor, JenkinsLinterError error) {
	if (editor == null) {
		return;
	}
	if (error == null) {
		return;
	}

	IEditorInput input = editor.getEditorInput();
	if (input == null) {
		return;
	}
	IResource editorResource = input.getAdapter(IResource.class);
	if (editorResource == null) {
		return;
	}
	try {
		linterMarkerHelper.createErrorMarker(editorResource, error.getMessage(), error.getLine());
	} catch (CoreException e) {
		logError("Was not able to add error markers", e);
	}

}
 
Example 27
Project: pgcodekeeper   File: ProjectEditorDiffer.java   View source code 5 votes vote down vote up
private IEditorInput createProjectScriptFile(String content, String filename) throws CoreException, IOException {
    Log.log(Log.LOG_INFO, "Creating file " + filename); //$NON-NLS-1$
    IProject iProject = proj.getProject();
    IFolder folder = iProject.getFolder(PROJ_PATH.MIGRATION_DIR);
    if (!folder.exists()){
        folder.create(IResource.NONE, true, null);
    }
    IFile file = folder.getFile(filename + ".sql"); //$NON-NLS-1$
    InputStream source = new ByteArrayInputStream(content.getBytes(proj.getProjectCharset()));
    file.create(source, IResource.NONE, null);
    return new FileEditorInput(iProject.getFile(file.getProjectRelativePath()));
}
 
Example 28
Project: OCCI-Studio   File: DesignerGeneratorAction.java   View source code 5 votes vote down vote up
private IProject generateDesignProject(String occieLocation, String designName, String designProjectName,
		final IProgressMonitor monitor) throws CoreException, IOException {

	// Load the ecore file.
	String ecoreLocation = occieLocation.replace(".occie", ".ecore");
	URI ecoreURI = URI.createFileURI(ecoreLocation);
	// Create a new resource set.
	ResourceSet resourceSet = new ResourceSetImpl();
	// Load the OCCI resource.
	org.eclipse.emf.ecore.resource.Resource resource = resourceSet.getResource(ecoreURI, true);
	// Return the first element.
	EPackage ePackage = (EPackage) resource.getContents().get(0);

	String extensionScheme = Occi2Ecore.convertEcoreNamespace2OcciScheme(ePackage.getNsURI());

	// Register the ePackage to avoid an error when trying to open the generated
	// .odesign file,
	EPackage.Registry.INSTANCE.put(ePackage.getNsURI(), ePackage);

	
	URI occieURI = URI.createFileURI(occieLocation);
	
	/*
	 * Create design project
	 */
	IProject project = DesignerGeneratorUtils.genDesignProject(designProjectName, designName, extensionScheme,
			new ProgressMonitorDialog(shell));

	/*
	 * Create design model
	 */
	org.eclipse.cmf.occi.core.gen.design.extended.main.Generate generator = new org.eclipse.cmf.occi.core.gen.design.extended.main.Generate(
			occieURI, project.getFolder("description").getLocation().toFile(), new ArrayList<String>());
	generator.doGenerate(BasicMonitor.toMonitor(monitor));
	project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
	return project;
}
 
Example 29
Project: java-debug   File: JavaHotCodeReplaceProvider.java   View source code 5 votes vote down vote up
private void redefineTypesJDK(List<IResource> resources, List<String> qualifiedNames) throws DebugException {
    Map<ReferenceType, byte[]> typesToBytes = getTypesToBytes(resources, qualifiedNames);
    try {
        currentDebugSession.getVM().redefineClasses(typesToBytes);
    } catch (UnsupportedOperationException | NoClassDefFoundError | VerifyError | ClassFormatError
            | ClassCircularityError e) {
        publishEvent(HotCodeReplaceEvent.EventType.ERROR, e.getMessage());
        throw new DebugException("Failed to redefine classes: " + e.getMessage());
    }
}
 
Example 30
Project: gw4e.project   File: ResourceManagerTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateFileDeleteIfExistsStringStringStringIProgressMonitor() throws Exception {
	IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true, true);
	IFile impl = (IFile) ResourceManager
			.getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString());
	int[] count = new int[1];

	count[0] = 0;
	IResourceVisitor visitor = new IResourceVisitor() {
		@Override
		public boolean visit(IResource resource) throws CoreException {
			if (resource.getFileExtension() != null && resource.getFileExtension().equalsIgnoreCase("java")) {
				count[0] = count[0] + 1;
			}
			return true;
		}
	};
	impl.getParent().accept(visitor);
	assertTrue(count[0] == 1);

	ResourceManager.createFileDeleteIfExists(impl.getParent().getFullPath().toString(), "SimpleImpl.java", "",
			new NullProgressMonitor());
	String s = IOHelper.getContent(impl);
	assertTrue(s.length() == 0);

	count[0] = 0;
	impl.getParent().accept(visitor);
	assertTrue(count[0] == 2);
}
 
Example 31
Project: n4js   File: AbstractBuilderParticipantTest.java   View source code 5 votes vote down vote up
/***/
protected void replaceFileContentAndWaitForRefresh(IFolder folder, IFile file, String newContent)
		throws IOException, CoreException {
	File fileInFilesystem = file.getLocation().toFile();
	FileWriter fileWriter = new FileWriter(fileInFilesystem);
	fileWriter.write(newContent);
	fileWriter.close();
	folder.refreshLocal(IResource.DEPTH_INFINITE, monitor());
	waitForAutoBuild();
}
 
Example 32
Project: pgcodekeeper   File: SQLEditor.java   View source code 5 votes vote down vote up
@Override
public void doSave(IProgressMonitor progressMonitor) {
    super.doSave(progressMonitor);
    IResource res = ResourceUtil.getResource(getEditorInput());
    try {
        if (res == null || !PgUIDumpLoader.isInProject(res)) {
            refreshParser(getParser(), res, progressMonitor);
        }
    } catch (Exception ex) {
        Log.log(ex);
    }
}
 
Example 33
Project: neoscada   File: RecipeHelper.java   View source code 5 votes vote down vote up
public static void processFile ( final IResource file, final IProgressMonitor monitor ) throws Exception
{
    final ModelLoader<Definition> loader = new ModelLoader<Definition> ( Definition.class );

    final Definition def = loader.load ( file.getLocationURI () );

    processFile ( file.getParent (), def, null, monitor );
}
 
Example 34
Project: Open_Source_ECOA_Toolset_AS5   File: PluginUtil.java   View source code 5 votes vote down vote up
public ArrayList<String> getResourcesWithExtension(String ext, String containerName) {
	ArrayList<String> ret = new ArrayList<String>();
	if (containerName != null) {
		String[] names = StringUtils.split(containerName, "/");
		IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = wsRoot.findMember(new Path("/" + names[0]));
		IPath loc = resource.getLocation();
		File prjLoc = new File(loc.toString());
		Collection<File> res = FileUtils.listFiles(prjLoc, FileFilterUtils.suffixFileFilter(ext, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE);
		for (File file : res)
			ret.add(file.getAbsolutePath());
	}
	return ret;
}
 
Example 35
Project: vertigo-chroma-kspplugin   File: ResourceStore.java   View source code 5 votes vote down vote up
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
	IResource resource = delta.getResource();

	/* Dossier target : on n'explore pas. */
	if (ResourceUtils.isTargetFolder(resource)) {
		return false;
	}

	/* Filtre sur les fichiers. */
	if (!(resource instanceof IFile)) {
		/* Dossier : on continue la visite. */
		return true;
	}

	/* La ressource est un fichier. */
	IFile file = (IFile) resource;

	/* Vérifie que le magasin est concerné par ce fichier. */
	boolean isCandidate = implementor.isCandidate(file);
	if (!isCandidate) {
		return false;
	}

	switch (delta.getKind()) {
	case IResourceDelta.REMOVED:
	case IResourceDelta.REMOVED_PHANTOM:
		/* Cas d'une suppression de fichier. */
		handleDeletion(file);
		break;
	default:
		/* Cas d'un ajout ou d'un changement : on traite le fichier. */
		handleChange(file);
		break;
	}

	/* Fin de la visite. */
	return false;
}
 
Example 36
Project: eclipse-commons   File: TestToIResourcePositive.java   View source code 5 votes vote down vote up
@Test
public void workspaceRoot() throws Exception {
	URI uri = URI.createPlatformResourceURI("", true);
	IResource iResource = UriUtils.toIResource(uri);

	assertTrue(iResource instanceof IWorkspaceRoot);
	assertTrue(iResource.exists());
	assertEquals("/", iResource.getFullPath().toString());
}
 
Example 37
Project: n4js   File: LaunchConfigurationMainTab.java   View source code 5 votes vote down vote up
/***
 * Open a resource chooser to select a file
 **/
protected void browseFiles() {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	ResourceListSelectionDialog dialog = new ResourceListSelectionDialog(getShell(), root, IResource.FILE);
	dialog.setTitle("Search File");
	if (dialog.open() == Window.OK) {
		Object[] files = dialog.getResult();
		IFile file = (IFile) files[0];
		fileText.setText(file.getFullPath().toString());
	}

}
 
Example 38
Project: Tarski   File: CreatingAtomWizardContentProvider.java   View source code 5 votes vote down vote up
@Override
public boolean hasChildren(Object element) {
  if (element instanceof IResource) {
    return true;
  } else {
    return false;
  }
}
 
Example 39
Project: n4js   File: ModuleSpecifierSelectionDialog.java   View source code 5 votes vote down vote up
@Override
protected void computeResult() {

	Object selection = treeViewer.getStructuredSelection().getFirstElement();

	if (selection == null) {
		return;
	}

	String moduleName = elementNameInput.getText();
	String moduleFileExtension = elementNameInput.getSuffix();

	// For selected files where the element name input equals the selected file
	if (selection instanceof IFile
			&& ((IFile) selection).getFullPath().removeFileExtension().lastSegment().equals(moduleName)) {
		// Use the selected file's path as result
		IPath fileSpec = sourceFolderRelativePath((IResource) selection);
		this.setResult(Arrays.asList(fileSpec.toString()));
		return;
	} else if (selection instanceof IResource) {
		// For files with different element name input value, use their container as basepath
		if (selection instanceof IFile) {
			selection = ((IFile) selection).getParent();
		}

		IFile moduleFile = ((IContainer) selection).getFile(new Path(moduleName + moduleFileExtension));
		this.setResult(
				Arrays.asList(moduleFile.getFullPath().makeRelativeTo(sourceFolder.getFullPath()).toString()));

		return;
	} else {
		updateError("Invalid selection type.");
	}
}
 
Example 40
Project: gemoc-studio-modeldebugging   File: AbstractCreateNewGemocLanguageProject.java   View source code 5 votes vote down vote up
@Override
public boolean performFinish() {
	
	try {
		createdProject = _askProjectNamePage.getProjectHandle();
		final String languageName = _askLanguageNamePage.getLanguageName();

		IWorkspace workspace = ResourcesPlugin.getWorkspace(); 
		final IProjectDescription description = workspace.newProjectDescription(createdProject.getName());
		if (!_askProjectNamePage.getLocationPath().equals(workspace.getRoot().getLocation()))
			description.setLocation(_askProjectNamePage.getLocationPath());
		//description.setLocationURI(_askProjectNamePage.getLocationURI());
		
		IWorkspaceRunnable operation = new IWorkspaceRunnable() {
			 public void run(IProgressMonitor monitor) throws CoreException {
				 createdProject.create(description, monitor);
				 createdProject.open(monitor);
				 initializeProject(createdProject, languageName);
				 createdProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
				 createdProject.touch(new NullProgressMonitor()); // [FT] One touch to force eclipse to serialize the project properties that will update accordingly the gemoc actions in the menu.
				 //createdProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
			 }
		};
		ResourcesPlugin.getWorkspace().run(operation, null);
	} catch (CoreException exception) {
		Activator.error(exception.getMessage(), exception);
		return false;
	}
	return true;
}