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

The following examples show how to use org.eclipse.core.resources.IStorage. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static IStorage getResourceBundle(IJavaProject javaProject, AccessorClassReference accessorClassReference) throws JavaModelException {
	String resourceBundle= accessorClassReference.getResourceBundleName();
	if (resourceBundle == null)
		return null;

	String resourceName= Signature.getSimpleName(resourceBundle) + NLSRefactoring.PROPERTY_FILE_EXT;
	String packName= Signature.getQualifier(resourceBundle);
	ITypeBinding accessorClass= accessorClassReference.getBinding();

	if (accessorClass.isFromSource())
		return getResourceBundle(javaProject, packName, resourceName);
	else if (accessorClass.getJavaElement() != null)
		return getResourceBundle((IPackageFragmentRoot)accessorClass.getJavaElement().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT), packName, resourceName);

	return null;
}
 
Example 2
Source Project: xtext-eclipse   Source File: BuilderParticipant.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.7
 */
protected String getCurrentSourceFolder(IBuildContext context, Delta delta) {
	Iterable<org.eclipse.xtext.util.Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(delta.getUri());
	for (org.eclipse.xtext.util.Pair<IStorage, IProject> pair : storages) {
		if (pair.getFirst() instanceof IResource) {
			final IResource resource = (IResource) pair.getFirst();
			IProject project = pair.getSecond();
			for (OutputConfiguration output : getOutputConfigurations(context).values()) {
				for (SourceMapping sourceMapping : output.getSourceMappings()) {
					IContainer folder = ResourceUtil.getContainer(project, sourceMapping.getSourceFolder());
					if (folder.contains(resource)) {
						return sourceMapping.getSourceFolder();
					}
				}
			}
		}
	}
	return null;
}
 
Example 3
Source Project: dsl-devkit   Source File: AbstractUtilTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Prepare mocks for all tests.
 */
public static void prepareMocksBase() {
  oldDesc = mock(IResourceDescription.class);
  newDesc = mock(IResourceDescription.class);
  delta = mock(Delta.class);
  resource = mock(Resource.class);
  uriCorrect = mock(URI.class);
  when(uriCorrect.isPlatformResource()).thenReturn(true);
  when(uriCorrect.isFile()).thenReturn(true);
  when(uriCorrect.toFileString()).thenReturn(DUMMY_PATH);
  when(uriCorrect.toPlatformString(true)).thenReturn(DUMMY_PATH);
  when(delta.getNew()).thenReturn(newDesc);
  when(delta.getOld()).thenReturn(oldDesc);
  when(delta.getUri()).thenReturn(uriCorrect);
  when(resource.getURI()).thenReturn(uriCorrect);
  file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uriCorrect.toPlatformString(true)));
  Iterable<Pair<IStorage, IProject>> storages = singleton(Tuples.<IStorage, IProject> create(file, file.getProject()));
  mapperCorrect = mock(Storage2UriMapperImpl.class);
  when(mapperCorrect.getStorages(uriCorrect)).thenReturn(storages);
}
 
Example 4
Source Project: xtext-eclipse   Source File: IntegrationTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testIgnoreFilesInOutputFolder() throws Exception {
	IJavaProject javaProject = createJavaProjectWithRootSrc("foo");
	createFile("foo/src/foo" + F_EXT, "object Foo ");
	createFile("foo/bar" + F_EXT, "object Bar references Foo");
	build();
	IProject project = javaProject.getProject();
	IResource resourceFromBin = project.findMember(new Path("/bin/foo" + F_EXT));
	assertNotNull(resourceFromBin);
	assertTrue(resourceFromBin instanceof IStorage);
	assertTrue(resourceFromBin.exists());
	URI fakeBinURI = URI.createPlatformResourceURI("/" + project.getName() + "/bin/foo" + F_EXT, true);
	assertFalse(serviceProvider.canHandle(fakeBinURI, (IStorage) resourceFromBin));
	assertTrue(serviceProvider.canHandle(fakeBinURI));
	IResource resourceFromRoot = project.findMember(new Path("/bar" + F_EXT));
	assertNotNull(resourceFromRoot);
	assertTrue(resourceFromRoot instanceof IStorage);
	URI fromRootURI = URI.createPlatformResourceURI("/" + project.getName() + "/bar" + F_EXT, true);
	assertFalse(serviceProvider.canHandle(fromRootURI, (IStorage) resourceFromBin));
	assertTrue(serviceProvider.canHandle(fromRootURI));
}
 
Example 5
Source Project: xtext-eclipse   Source File: QueuedBuildData.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public void queueURI(URI uri) {
	Iterable<Pair<IStorage, IProject>> iterable = mapper.getStorages(uri);
	boolean associatedWithProject = false;
	for (Pair<IStorage, IProject> pair : iterable) {
		IProject project = pair.getSecond();
		if (XtextProjectHelper.hasNature(project) && XtextProjectHelper.hasBuilder(project)) {
			String projectName = project.getName();
			LinkedHashSetQueue<URI> list = projectNameToChangedResource.get(projectName);
			if (list == null) {
				list = new LinkedHashSetQueue<>();
				projectNameToChangedResource.put(projectName, list);
			}
			list.add(uri);
			associatedWithProject = true;
		}
	}
	if (!associatedWithProject) {
		this.uris.add(uri);
	}
}
 
Example 6
@Override
public boolean collectSourceFileOpeners(IEditorPart editor, IAcceptor<FileOpener> acceptor) {
	IStorage storage = getStorage(editor);
	if (storage instanceof IResource) {
		IResource resource = (IResource) storage;
		try {
			Set<URI> uris = Sets.newHashSet();
			IMarker[] markers = derivedResourceMarkers.findDerivedResourceMarkers(resource);
			for (IMarker marker : markers) {
				String source = derivedResourceMarkers.getSource(marker);
				if (source != null)
					uris.add(URI.createURI(source));
			}
			for (URI uri : uris)
				for (Pair<IStorage, IProject> destination : storage2UriMapper.getStorages(uri))
					acceptor.accept(createOpener(destination.getFirst()));
			return true;
		} catch (CoreException e) {
			LOG.error(e.getMessage(), e);
		}
	}
	return false;
}
 
Example 7
Source Project: birt   Source File: StorageDocumentProvider.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public boolean isReadOnly( Object element )
{
	IStorage storage = null;
	try
	{
		if ( element instanceof IStorageEditorInput )
		{
			storage = ( (IStorageEditorInput) element ).getStorage( );
		}
	}
	catch ( CoreException x )
	{
		ExceptionHandler.handle( x );
	}

	if ( storage != null )
	{
		return storage.isReadOnly( );
	}
	return super.isReadOnly( element );
}
 
Example 8
Source Project: xtext-eclipse   Source File: JavaSearchHelper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected void accept(IReferenceDescription referenceDescription) {
	URI sourceResourceURI = referenceDescription.getSourceEObjectUri().trimFragment();
	Iterable<Pair<IStorage, IProject>> storages = storage2UriMapper.getStorages(sourceResourceURI);
	Iterator<Pair<IStorage, IProject>> iterator = storages.iterator();
	while (iterator.hasNext()) {
		Pair<IStorage, IProject> pair = iterator.next();
		IStorage storage = pair.getFirst();
		IProject project = pair.getSecond();
		if (project != null && !project.isHidden()) {
			ResourceSet resourceSet = getResourceSet(project);
			EObject sourceEObject = resourceSet.getEObject(referenceDescription.getSourceEObjectUri(), true);
			if (sourceEObject != null) {
				ITextRegion region = getLocation(
						sourceEObject, referenceDescription.getEReference(), 
						referenceDescription.getIndexInList());
				acceptMatch(storage, region);
			} else {
				acceptMatch(referenceDescription, null);
			}
		}
	}
}
 
Example 9
Source Project: xtext-eclipse   Source File: XtextBuilder.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a visitor that is used to traverse the information that is obtained from {@link #getDelta(IProject)}. It
 * accumulates its findings in the given <code>toBeBuilt</code>.
 */
protected IResourceDeltaVisitor createDeltaVisitor(ToBeBuiltComputer toBeBuiltComputer, ToBeBuilt toBeBuilt,
		final SubMonitor progress) {
	IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
		@Override
		public boolean visit(IResourceDelta delta) throws CoreException {
			if (progress.isCanceled())
				throw new OperationCanceledException();
			if (delta.getResource() instanceof IProject) {
				return true;
			}
			if (delta.getResource() instanceof IStorage) {
				if (delta.getKind() == IResourceDelta.REMOVED) {
					return toBeBuiltComputer.removeStorage(null, toBeBuilt, (IStorage) delta.getResource());
				} else if (delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.CHANGED) {
					return toBeBuiltComputer.updateStorage(null, toBeBuilt, (IStorage) delta.getResource());
				}
			}
			return true;
		}
	};
	return visitor;
}
 
Example 10
private Set<IPath> getUiXmlWorkspaceRelativePaths(
    TypeDeclaration ownerTypeDecl) {
  Set<IPath> paths = new HashSet<IPath>();

  String ownerTypeName = ownerTypeDecl.resolveBinding().getQualifiedName();
  for (IType uiBinderSubtype : uiBinderToOwner.getUiBinderTypes(ownerTypeName)) {
    IPath uiXmlClasspathRelativePath = ownerToUiXml.getUiXmlPath(uiBinderSubtype);
    try {
      IStorage uiXmlFile = ClasspathResourceUtilities.resolveFile(
          uiXmlClasspathRelativePath, javaProject);

      // Verify that the ui.xml exists and is not in a JAR
      if (uiXmlFile instanceof IFile) {
        paths.add(uiXmlFile.getFullPath());
      }
    } catch (JavaModelException e) {
      GWTPluginLog.logError(e);
    }
  }
  return paths;
}
 
Example 11
/**
 * @since 2.4
 */
@Override
public Map<URI, IStorage> getAllEntries(IContainer container) {
	final Map<URI,IStorage> result = newLinkedHashMap();
	try {
		container.accept(new IResourceVisitor() {
			@Override
			public boolean visit(IResource resource) throws CoreException {
				if (resource instanceof IFile) {
					final IFile storage = (IFile) resource;
					URI uri = getUri(storage);
					if (uri != null)
						result.put(uri, storage);
				}
				if (resource instanceof IFolder) {
					return isHandled((IFolder)resource);
				}
				return true;
			}
		});
	} catch (CoreException e) {
		log.error(e.getMessage(), e);
	}
	return result;
}
 
Example 12
Source Project: xtext-xtend   Source File: XtendUIValidator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected String getExpectedPackageName(XtendFile xtendFile) {
	URI fileURI = xtendFile.eResource().getURI();
	for(Pair<IStorage, IProject> storage: storage2UriMapper.getStorages(fileURI)) {
		if(storage.getFirst() instanceof IFile) {
			IPath fileWorkspacePath = storage.getFirst().getFullPath();
			IJavaProject javaProject = JavaCore.create(storage.getSecond());
			if(javaProject != null && javaProject.exists() && javaProject.isOpen()) {
				try {
					for(IPackageFragmentRoot root: javaProject.getPackageFragmentRoots()) {
						if(!root.isArchive() && !root.isExternal()) {
							IResource resource = root.getResource();
							if(resource != null) {
								IPath sourceFolderPath = resource.getFullPath();
								if(sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
									IPath claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
									return claspathRelativePath.removeLastSegments(1).toString().replace("/", ".");
								}
							}
						}
					}
				} catch (JavaModelException e) {
					LOG.error("Error resolving expected path for XtendFile", e);
				}
			}
		}
	}
	return null;
}
 
Example 13
public static boolean isOpenableStorage(Object storage) {
	if (storage instanceof IJarEntryResource) {
		return ((IJarEntryResource) storage).isFile();
	} else {
		return storage instanceof IStorage;
	}
}
 
Example 14
Source Project: n4js   Source File: N4JSStorage2UriMapper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * GH-1190: disable a new behavior of Xtext, which adds pairs <code>FileStoreStorage -> null</code> for file URIs
 * (see private method <code>#getStorages(URI, IFile)</code> of super class), because these pairs will lead to a
 * NullPointerException in Xtext's {@code ToBeBuiltComputer#doRemoveProject(IProject, IProgressMonitor)} when
 * applied to a project located in the external library workspace.
 */
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(URI uri) {
	Iterable<Pair<IStorage, IProject>> storages = super.getStorages(uri);
	if (!uri.isPlatformResource() && uri.isFile()) {
		storages = super.getContribution().getStorages(uri);
	} else {
		storages = super.getStorages(uri);
	}
	return Iterables.filter(storages,
			pair -> !(pair != null && pair.getFirst() instanceof FileStoreStorage));
}
 
Example 15
/**
 * @since 2.1
 */
protected boolean isJavaTargetFolder(IStorage storage) {
	if (storage instanceof IResource) {
		return jdtHelper.isFromOutputPath((IResource) storage);
	}
	return false;
}
 
Example 16
@Override
public Iterable<Pair<IStorage, IProject>> getStorages(final URI uri) {
	final IN4JSEclipseProject project = eclipseCore.findProject(uri).orNull();
	if (null != project && project.exists()) {
		final IProject resourceProject = project.getProject();
		return singleton(Tuples.create(new URIBasedStorage(uri), resourceProject));
	}
	return emptyList();
}
 
Example 17
Source Project: xtext-eclipse   Source File: XbaseBreakpointUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public SourceRelativeURI getBreakpointURI(IEditorInput input) {
	IResource resource = Adapters.adapt(input, IResource.class);
	if (resource != null)
		return null;
	if (input instanceof IStorageEditorInput) {
		IStorage storage;
		try {
			storage = ((IStorageEditorInput) input).getStorage();
			if (storage instanceof IResource)
				return null;
			if (storage instanceof IJarEntryResource) {
				IJarEntryResource jarEntryResource = (IJarEntryResource) storage;
				if (!jarEntryResource.getPackageFragmentRoot().isArchive())
					return null;
				Object parent = jarEntryResource.getParent();
				if (parent instanceof IPackageFragment) {
					String path = ((IPackageFragment) parent).getElementName().replace('.', '/');
					return new SourceRelativeURI(path + "/" + storage.getName());
				} else if (parent instanceof IPackageFragmentRoot) {
					return new SourceRelativeURI(storage.getName());
				}
			}
		} catch (CoreException e) {
			logger.error("Error finding breakpoint URI", e);
			return null;
		}
	} else {
		IClassFile classFile = Adapters.adapt(input, IClassFile.class);
		if (classFile != null) {
			ITrace traceToSource = traceForTypeRootProvider.getTraceToSource(classFile);
			if (traceToSource == null)
				return null;
			for (ILocationInResource loc : traceToSource.getAllAssociatedLocations())
				return loc.getSrcRelativeResourceURI();
			return null;
		}
	}
	return null;
}
 
Example 18
/**
 * @since 2.3
 */
/* @Nullable */
protected IFile getTraceFile(IFile file) {
	IStorage traceFile = fileBasedTraceInformation.getTraceFile(file);
	if (traceFile instanceof IFile) {
		IFile result = (IFile) traceFile;
		syncIfNecessary(result);
		return result;
	}
	return null;
}
 
Example 19
/**
 * The worker method...
 */
private void doFinish(File scanDir, IProgressMonitor monitor) throws CoreException {
	
	monitor.beginTask("Creating analysis file", 3);
	monitor.worked(1);
	
	try {
		runTSVAnalysis(scanDir);
		monitor.worked(1);
		
		monitor.setTaskName("Opening results file...");
		getShell().getDisplay().asyncExec(new Runnable() {
			public void run() {
				
				IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				
				try {
					IStorage storage = new TSVResultsStorage(getResultsString(), new Path("garbage"));
					IStorageEditorInput input = new TSVResultsInput(storage, "TSV Analysis");
					IDE.openEditor(page, input, "com.hybris.hyeclipse.tsv.editors.TSVEditor", true);
				}
				catch (PartInitException e) {
					e.printStackTrace();
				}
			}
		});
		monitor.worked(1);
	}
	catch (RuntimeException re) {
		System.out.println(re.getMessage());
	}
	
}
 
Example 20
Source Project: xtext-eclipse   Source File: ToBeBuiltComputer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean removeStorage(ToBeBuilt toBeBuilt, IStorage storage, IProgressMonitor monitor) {
	for (int i = 0; i < contributions.size(); i++) {
		if (contributions.get(i).removeStorage(toBeBuilt, storage, monitor)) {
			return true;
		}
	}
	return false;
}
 
Example 21
Source Project: xtext-eclipse   Source File: TraceEditor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected IStorage getLocalStorage(IResourceServiceProvider serviceProvider, URI traceURI) {
	TraceFileNameProvider fileNameProvider = serviceProvider.get(TraceFileNameProvider.class);
	IStorage2UriMapper storage2UriMapper = serviceProvider.get(IStorage2UriMapper.class);
	String generatedName = fileNameProvider.getJavaFromTrace(traceURI.lastSegment());
	URI generatedURI = traceURI.trimSegments(1).appendSegment(generatedName);
	for (Pair<IStorage, IProject> x : storage2UriMapper.getStorages(generatedURI))
		return x.getFirst();
	throw new IllegalStateException("Could not find IStorage for " + generatedURI);
}
 
Example 22
@Override
public Image getImage(Object element) {
	Image result= fImageLabelProvider.getImageLabel(element, fImageFlags);
	if (result != null) {
		return result;
	}

	if (element instanceof IStorage)
		return fStorageLabelProvider.getImage(element);

	return result;
}
 
Example 23
@Override
protected void openEObject(EObject state) {
	try {
		if (state instanceof JvmIdentifiableElement && state.eResource() instanceof TypeResource) {
			IJavaElement javaElement = javaElementFinder.findElementFor((JvmIdentifiableElement) state);
			if (javaElement instanceof IMember) {
				IResource resource = javaElement.getResource();
				if (resource instanceof IStorage) {
					ITrace traceToSource = traceInformation.getTraceToSource((IStorage) resource);
					if (traceToSource != null) {
						ISourceRange sourceRange = ((IMember) javaElement).getSourceRange();
						ILocationInResource sourceInformation = traceToSource.getBestAssociatedLocation(new TextRegion(sourceRange.getOffset(), sourceRange.getLength()));
						if (sourceInformation != null) {
							globalURIEditorOpener.open(sourceInformation.getAbsoluteResourceURI().getURI(), javaElement, true);
							return;
						}
					}
				}
				globalURIEditorOpener.open(null, javaElement, true);
				return;
			}
		}
	} catch (Exception exc) {
		LOG.error("Error opening java editor", exc);
	}
	super.openEObject(state);
}
 
Example 24
private void mockMarkerResource(final URI uri) throws CoreException {
  // Resource is a file and so gets processed
  when(mockMarker.getResource()).thenReturn(mockFile);
  when(mockFile.getName()).thenReturn(uri.lastSegment());
  when(mockFile.findMarkers(anyString(), anyBoolean(), anyInt())).thenReturn(new IMarker[] {});
  when(mockMarker.getAttribute(eq(Issue.URI_KEY), anyString())).thenReturn(uri.toString());
  when(mockMarker.isSubtypeOf(eq(MarkerTypes.ANY_VALIDATION))).thenReturn(true);
  when(mockStorage2UriMapper.getUri(eq(mockFile))).thenReturn(uri);
  @SuppressWarnings("unchecked")
  Iterable<Pair<IStorage, IProject>> storages = Lists.newArrayList(Tuples.create((IStorage) mockFile, mock(IProject.class)));
  when(mockStorage2UriMapper.getStorages(eq(uri))).thenReturn(storages);
  when(mockLanguageResourceHelper.isLanguageResource(eq(mockFile))).thenReturn(true);
}
 
Example 25
@Override
public IEclipseTrace getTraceToSource(IStorage derivedResource) {
	if (derivedResource instanceof IFile) {
		return getTraceToSource((IFile) derivedResource);
	}
	return null;
}
 
Example 26
@Override
public boolean isTraceFile(IStorage storage) {
	if (!(storage instanceof IFile)) {
		return false;
	}
	IFile file = (IFile) storage;
	String originLastSegment = file.getFullPath().lastSegment();
	return getTraceFileNameProvider().isTraceFileName(originLastSegment);
}
 
Example 27
public static IStorage getResourceBundle(ICompilationUnit compilationUnit) throws JavaModelException {
	IJavaProject project= compilationUnit.getJavaProject();
	if (project == null)
		return null;

	String name= getResourceBundleName(compilationUnit);
	if (name == null)
		return null;

	String packName= Signature.getQualifier(name);
	String resourceName= Signature.getSimpleName(name) + NLSRefactoring.PROPERTY_FILE_EXT;

	return getResourceBundle(project, packName, resourceName);
}
 
Example 28
@Override
public CheckGeneratorConfig get(final URI uri) {
  CheckGeneratorConfig result = new CheckGeneratorConfig();
  IProject project = null;
  if (uri != null) {
    Pair<IStorage, IProject> pair = Iterables.getFirst(storage2UriMapper.getStorages(uri), null);
    if (pair != null) {
      project = pair.getSecond();
    }
  }
  xbaseBuilderPreferenceAccess.loadBuilderPreferences(result, project);
  return result;
}
 
Example 29
@Override
protected ResourceSet getResourceSet(/* @Nullable */ IStorage storage) {
	if (storage instanceof IJarEntryResource) {
		IPackageFragmentRoot root = ((IJarEntryResource) storage).getPackageFragmentRoot();
		if (root != null) {
			IJavaProject project = root.getJavaProject();
			if (project != null)
				return getResourceSetProvider().get(project.getProject());
		}
	} 
	return super.getResourceSet(storage);
}
 
Example 30
Source Project: xds-ide   Source File: StorageEditorInput.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class adapter) {
	Object adapted = super.getAdapter(adapter);
	if (adapted == null) {
		if (IStorage.class.equals(adapter)) {
			return fStorage;
		}
	}
	return adapted;
}