Java Code Examples for org.eclipse.core.resources.IResource#getLocationURI()

The following examples show how to use org.eclipse.core.resources.IResource#getLocationURI() . 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: ResourceUtil.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Delete a broken symbolic link. Has no effect if the resource is not a
 * symbolic link or if the target of the symbolic link exists.
 *
 * @param resource
 *            the resource in the workspace.
 * @throws CoreException
 *             if an error occurs
 */
public static void deleteIfBrokenSymbolicLink(@Nullable IResource resource) throws CoreException {
    if (resource == null) {
        return;
    }
    if (resource.isLinked()) {
        IPath location = resource.getLocation();
        if (location == null || !location.toFile().exists()) {
            resource.delete(true, null);
        }
    } else {
        URI uri = resource.getLocationURI();
        if (uri != null) {
            Path linkPath = Paths.get(uri);
            if (Files.isSymbolicLink(linkPath) && !resource.exists()) {
                try {
                    Files.delete(linkPath);
                } catch (Exception e) {
                    // Do nothing.
                }
            }
        }
    }
}
 
Example 2
Source File: MSyncWizardFilePage.java    From slr-toolkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This methods searches for all Bib-Files.
 * For each Bib-File a WorkspaceBibTexEntry will be created/updated.
 * In order to do that the content of each Bib-File will be parsed
 * with the JBibTeX Library and put into the WorkspaceBibTexEntry
 */
private void createWorkspaceContent(){
	IWorkspace workspace = ResourcesPlugin.getWorkspace();

	for(IProject project : workspace.getRoot().getProjects()){
		try {
			for(IResource resource :project.members()){
				if(resource.getFileExtension().equals("bib")){
					URI uri = resource.getLocationURI();
					WorkspaceBibTexEntry entry = new WorkspaceBibTexEntry(uri, project);
					wm.updateFileBibTex(entry);
				}
			}
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
 
Example 3
Source File: JdtSourceLookUpProvider.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
private static String getFileURI(IResource resource) {
    URI uri = resource.getLocationURI();
    if (uri != null) {
        // If the file path contains non ASCII characters, encode the result.
        String uriString = uri.toASCIIString();
        // Fix uris by adding missing // to single file:/ prefix.
        return uriString.replaceFirst("file:/([^/])", "file:///$1");
    }
    return null;
}
 
Example 4
Source File: ReorgUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean areEqualInWorkspaceOrOnDisk(IResource r1, IResource r2){
	if (r1 == null || r2 == null) {
		return false;
	}
	if (r1.equals(r2)) {
		return true;
	}
	URI r1Location= r1.getLocationURI();
	URI r2Location= r2.getLocationURI();
	if (r1Location == null || r2Location == null) {
		return false;
	}
	return r1Location.equals(r2Location);
}
 
Example 5
Source File: ResourceUtil.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the location URI of the given resource. If the resource is file
 * system symbolic link then it will return the link target location.
 *
 * @param resource
 *            the resource to check
 * @return the URI of the resource or null
 */
public static @Nullable URI getLocationURI(@Nullable IResource resource) {
    if (resource != null) {
        if (isFileSystemSymbolicLink(resource)) {
            try {
                return Files.readSymbolicLink(Paths.get(resource.getLocationURI())).toUri();
            } catch (IOException e) {
                // Do nothing... return null below
            }
        } else {
            return resource.getLocationURI();
        }
    }
    return null;
}
 
Example 6
Source File: ReorgUtils.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean areEqualInWorkspaceOrOnDisk(IResource r1, IResource r2){
	if (r1 == null || r2 == null)
		return false;
	if (r1.equals(r2))
		return true;
	URI r1Location= r1.getLocationURI();
	URI r2Location= r2.getLocationURI();
	if (r1Location == null || r2Location == null)
		return false;
	return r1Location.equals(r2Location);
}
 
Example 7
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the resources with the given names exist.
 *
 * @param resources
 *            IResources to checl
 * @return Multi status with one error message for each missing file.
 */
IStatus checkExist(IResource[] resources) {
    MultiStatus multiStatus = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, getProblemsMessage(), null);

    for (int i = 0; i < resources.length; i++) {
        IResource resource = resources[i];
        if (resource != null) {
            URI location = resource.getLocationURI();
            String message = null;
            if (location != null) {
                IFileInfo info = IDEResourceInfoUtils.getFileInfo(location);
                if (info == null || info.exists() == false) {
                    if (resource.isLinked()) {
                        message = NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_missingLinkTarget,
                                resource.getName());
                    } else {
                        message = NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_resourceDeleted,
                                resource.getName());
                    }
                }
            }
            if (message != null) {
                IStatus status = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.OK, message, null);
                multiStatus.add(status);
            }
        }
    }
    return multiStatus;
}
 
Example 8
Source File: ResourceUtils.java    From goclipse with Eclipse Public License 1.0 5 votes vote down vote up
public static Location getLocation(IResource resource) throws CommonException {
	IPath location = resource.getLocation();
	if(location == null) {
		throw new CommonException("Invalid resource location: " + resource.getLocationURI());
	}
	return Location.create(location.toFile().toPath());
}
 
Example 9
Source File: JdtBasedProcessorProvider.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void collectClasspathURLs(final IJavaProject projectToUse, final LinkedHashSet<URL> result, final boolean includeOutputFolder, final Set<IJavaProject> visited) throws JavaModelException {
  try {
    if (((!projectToUse.getProject().isAccessible()) || (!visited.add(projectToUse)))) {
      return;
    }
    if (includeOutputFolder) {
      IPath path = projectToUse.getOutputLocation().addTrailingSeparator();
      String _string = URI.createPlatformResourceURI(path.toString(), true).toString();
      URL url = new URL(_string);
      result.add(url);
    }
    final IClasspathEntry[] resolvedClasspath = projectToUse.getResolvedClasspath(true);
    for (final IClasspathEntry entry : resolvedClasspath) {
      {
        URL url_1 = null;
        int _entryKind = entry.getEntryKind();
        switch (_entryKind) {
          case IClasspathEntry.CPE_SOURCE:
            if (includeOutputFolder) {
              final IPath path_1 = entry.getOutputLocation();
              if ((path_1 != null)) {
                String _string_1 = URI.createPlatformResourceURI(path_1.addTrailingSeparator().toString(), true).toString();
                URL _uRL = new URL(_string_1);
                url_1 = _uRL;
              }
            }
            break;
          case IClasspathEntry.CPE_PROJECT:
            IPath path_2 = entry.getPath();
            final IResource project = this.getWorkspaceRoot(projectToUse).findMember(path_2);
            final IJavaProject referencedProject = JavaCore.create(project.getProject());
            this.collectClasspathURLs(referencedProject, result, true, visited);
            break;
          case IClasspathEntry.CPE_LIBRARY:
            IPath path_3 = entry.getPath();
            final IResource library = this.getWorkspaceRoot(projectToUse).findMember(path_3);
            URL _xifexpression = null;
            if ((library != null)) {
              URL _xblockexpression = null;
              {
                final java.net.URI locationUri = library.getLocationURI();
                URL _xifexpression_1 = null;
                String _scheme = null;
                if (locationUri!=null) {
                  _scheme=locationUri.getScheme();
                }
                boolean _equals = Objects.equal(EFS.SCHEME_FILE, _scheme);
                if (_equals) {
                  java.net.URI _rawLocationURI = library.getRawLocationURI();
                  URL _uRL_1 = null;
                  if (_rawLocationURI!=null) {
                    _uRL_1=_rawLocationURI.toURL();
                  }
                  _xifexpression_1 = _uRL_1;
                } else {
                  _xifexpression_1 = null;
                }
                _xblockexpression = _xifexpression_1;
              }
              _xifexpression = _xblockexpression;
            } else {
              _xifexpression = path_3.toFile().toURI().toURL();
            }
            url_1 = _xifexpression;
            break;
          default:
            {
              IPath path_4 = entry.getPath();
              url_1 = path_4.toFile().toURI().toURL();
            }
            break;
        }
        if ((url_1 != null)) {
          result.add(url_1);
        }
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 10
Source File: ResourceUtil.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean isFileSystemSymbolicLink(IResource resource) {
    URI uri = resource.getLocationURI();
    return (uri == null ? false : Files.isSymbolicLink(Paths.get(uri)));
}
 
Example 11
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 12
Source File: SharedCorePlugin.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Given a resource get the string in the filesystem for it.
 */
public static String getIResourceOSString(IResource f) {
    URI locationURI = f.getLocationURI();
    if (locationURI != null) {
        try {
            //RTC source control not return a valid uri
            return FileUtils.getFileAbsolutePath(new File(locationURI));
        } catch (IllegalArgumentException e) {
        }
    }

    IPath rawLocation = f.getRawLocation();
    if (rawLocation == null) {
        return null; //yes, we could have a resource that was deleted but we still have it's representation...
    }
    String fullPath = rawLocation.toOSString();
    //now, we have to make sure it is canonical...
    File file = new File(fullPath);
    if (file.exists()) {
        return FileUtils.getFileAbsolutePath(file);
    } else {
        //it does not exist, so, we have to check its project to validate the part that we can
        IProject project = f.getProject();
        IPath location = project.getLocation();
        File projectFile = location.toFile();
        if (projectFile.exists()) {
            String projectFilePath = FileUtils.getFileAbsolutePath(projectFile);

            if (fullPath.startsWith(projectFilePath)) {
                //the case is all ok
                return fullPath;
            } else {
                //the case appears to be different, so, let's check if this is it...
                if (fullPath.toLowerCase().startsWith(projectFilePath.toLowerCase())) {
                    String relativePart = fullPath.substring(projectFilePath.length());

                    //at least the first part was correct
                    return projectFilePath + relativePart;
                }
            }
        }
    }

    //it may not be correct, but it was the best we could do...
    return fullPath;
}
 
Example 13
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Checks whether the destination is valid for copying the source resources.
 * <p>
 * Note this method is for internal use only. It is not API.
 * </p>
 *
 * @param destination
 *            the destination container
 * @param sourceResources
 *            the source resources
 * @return an error message, or <code>null</code> if the path is valid
 */
public String validateDestination(IContainer destination, IResource[] sourceResources) {
    if (!isAccessible(destination)) {
        return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_destinationAccessError;
    }
    IContainer firstParent = null;
    URI destinationLocation = destination.getLocationURI();
    for (int i = 0; i < sourceResources.length; i++) {
        IResource sourceResource = sourceResources[i];
        if (firstParent == null) {
            firstParent = sourceResource.getParent();
        } else if (firstParent.equals(sourceResource.getParent()) == false) {
            // Resources must have common parent. Fixes bug 33398.
            return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_parentNotEqual;
        }

        URI sourceLocation = sourceResource.getLocationURI();
        if (sourceLocation == null) {
            if (sourceResource.isLinked()) {
                // Don't allow copying linked resources with undefined path
                // variables. See bug 28754.
                return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_missingPathVariable,
                        sourceResource.getName());
            }
            return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_resourceDeleted,
                    sourceResource.getName());

        }
        if (sourceLocation.equals(destinationLocation)) {
            return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_sameSourceAndDest,
                    sourceResource.getName());
        }
        // is the source a parent of the destination?
        if (new Path(sourceLocation.toString()).isPrefixOf(new Path(destinationLocation.toString()))) {
            return IDEWorkbenchMessages.CopyFilesAndFoldersOperation_destinationDescendentError;
        }

        String linkedResourceMessage = validateLinkedResource(destination, sourceResource);
        if (linkedResourceMessage != null) {
            return linkedResourceMessage;
        }
    }
    return null;
}
 
Example 14
Source File: Resources.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the location of the given resource. For local
 * resources this is the OS path in the local file system. For
 * remote resource this is the URI.
 *
 * @param resource the resource
 * @return the location string or <code>null</code> if the
 *  location URI of the resource is <code>null</code>
 */
public static String getLocationString(IResource resource) {
	URI uri= resource.getLocationURI();
	if (uri == null)
		return null;
	return EFS.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())
		? new File(uri).getAbsolutePath()
		: uri.toString();
}