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

The following examples show how to use org.eclipse.core.resources.IFile#getLocationURI() . 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
private List<String> getBuildFiles() {
    List<String> result = new ArrayList<>();
    List<IJavaProject> javaProjects = JdtUtils.listJavaProjects(ResourcesPlugin.getWorkspace().getRoot());
    for (IJavaProject javaProject : javaProjects) {
        IFile buildFile = null;
        if (ProjectUtils.isMavenProject(javaProject.getProject())) {
            buildFile = javaProject.getProject().getFile("pom.xml");
        } else if (ProjectUtils.isGradleProject(javaProject.getProject())) {
            buildFile = javaProject.getProject().getFile("build.gradle");
        }

        if (buildFile != null && buildFile.exists() && buildFile.getLocationURI() != null) {
            result.add(ResourceUtils.fixURI(buildFile.getLocationURI()));
        }
    }

    return result;
}
 
Example 2
@Override
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);

	URI location= file.getLocationURI();
	if (location == null) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_unknownLocation,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}

	IFileInfo jFile= EFS.getStore(location).fetchInfo();
	if (jFile.exists()) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_exists,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}
	return result;
}
 
Example 3
@Test
public void testIsFolder() throws Exception {
	IProject project = WorkspaceHelper.getProject(ProjectsManager.DEFAULT_PROJECT_NAME);

	// Creating test folders and file using 'java.io.*' API (from the outside of the workspace)
	File dir = new File(project.getLocation().toString(), "/src/org/eclipse/testIsFolder");
	dir.mkdirs();
	File file = new File(dir, "Test.java");
	file.createNewFile();

	// Accessing test folders and file using 'org.eclipse.core.resources.*' API (from inside of the workspace)
	IContainer iFolder = project.getFolder("/src/org/eclipse/testIsFolder");
	URI uriFolder = iFolder.getLocationURI();
	IFile iFile = project.getFile("/src/org/eclipse/testIsFolder/Test.java");
	URI uriFile = iFile.getLocationURI();
	assertTrue(JDTUtils.isFolder(uriFolder.toString()));
	assertEquals(JDTUtils.getFileOrFolder(uriFolder.toString()).getType(), IResource.FOLDER);
	assertEquals(JDTUtils.getFileOrFolder(uriFile.toString()).getType(), IResource.FILE);
	assertFalse(JDTUtils.isFolder(uriFile.toString()));
	assertNotNull(JDTUtils.findFile(uriFile.toString()));
	assertNotNull(JDTUtils.findFolder(uriFolder.toString()));
}
 
Example 4
Source Project: gef   File: DotGraphView.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private boolean updateGraph(IFile file) {
	if (file != null) {
		URI locationURI = file.getLocationURI();
		if (locationURI != null) {
			URL url = null;
			try {
				url = locationURI.toURL();
			} catch (MalformedURLException e) {
				DotActivatorEx.logError(e);
				return false;
			}
			if (url != null) {
				File dotFile = DotFileUtils.resolve(url);
				return updateGraph(dotFile);
			}
		}
	}

	return false;
}
 
Example 5
Source Project: depan   File: AbstractDocXmlPersist.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Cancels the {@code monitor} if there is an exception,
 * but reports no worked steps on the supplied {@code monitor}.
 */
public void saveDocument(
    IFile file, T docInfo,
    IProgressMonitor monitor) {
  URI location = file.getLocationURI();
  try {
    this.save(location, docInfo);
    file.refreshLocal(IResource.DEPTH_ZERO, monitor);
  } catch (Exception err) {
    if (null != monitor) {
      monitor.setCanceled(true);
    }
    String msg = buildSaveErrorMsg(location);
    logException(msg, err);
  }
}
 
Example 6
@Override
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);

	URI location= file.getLocationURI();
	if (location == null) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_unknownLocation,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}

	IFileInfo jFile= EFS.getStore(location).fetchInfo();
	if (jFile.exists()) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_exists,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}
	return result;
}
 
Example 7
ClasspathJar(IFile resource, AccessRuleSet accessRuleSet) {
	this.resource = resource;
	try {
		java.net.URI location = resource.getLocationURI();
		if (location == null) {
			this.zipFilename = ""; //$NON-NLS-1$
		} else {
			File localFile = Util.toLocalFile(location, null);
			this.zipFilename = localFile.getPath();
		}
	} catch (CoreException e) {
		// ignore
	}
	this.zipFile = null;
	this.knownPackageNames = null;
	this.accessRuleSet = accessRuleSet;
}
 
Example 8
Source Project: uima-uimaj   File: DocumentUimaImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the content. The XCAS {@link InputStream} gets parsed.
 *
 * @param casFile the new content
 * @throws CoreException the core exception
 */
private void setContent(IFile casFile) throws CoreException {

  IPreferenceStore store = CasEditorPlugin.getDefault().getPreferenceStore();
  boolean withPartialTypesystem = store
          .getBoolean(AnnotationEditorPreferenceConstants.ANNOTATION_EDITOR_PARTIAL_TYPESYSTEM);

  URI uri = casFile.getLocationURI();
  if (casFile.isLinked()) {
    uri = casFile.getRawLocationURI();
  }
  File file = EFS.getStore(uri).toLocalFile(0, new NullProgressMonitor());
  try {
    format = CasIOUtils.load(file.toURI().toURL(), null, mCAS, withPartialTypesystem);
  } catch (IOException e) {
    throwCoreException(e);
  }

}
 
Example 9
@Test
public void testCleanupDefaultProject() throws Exception {
	projectsManager.initializeProjects(Collections.emptyList(), monitor);
	waitForJobsToComplete();
	IFile file = linkFilesToDefaultProject("singlefile/WithError.java");
	java.io.File physicalFile = new java.io.File(file.getLocationURI());
	physicalFile.delete();

	BuildWorkspaceHandler handler = new BuildWorkspaceHandler(projectsManager);
	BuildWorkspaceStatus result = handler.buildWorkspace(true, monitor);

	waitForBackgroundJobs();
	assertEquals(String.format("BuildWorkspaceStatus is: %s.", result.toString()), BuildWorkspaceStatus.SUCCEED, result);
}
 
Example 10
public URI getURI()
{
	IFile file = getFile();
	if (file == null)
	{
		return null;
	}
	return file.getLocationURI();
}
 
Example 11
protected URI getURI()
{
	// Now try and resolve the value as a URI...
	IEditorInput input = getEditorInput();
	if (input instanceof IURIEditorInput)
	{
		return ((IURIEditorInput) input).getURI();
	}
	if (input instanceof IFileEditorInput)
	{
		IFile file = ((IFileEditorInput) input).getFile();
		return file.getLocationURI();
	}
	return null;
}
 
Example 12
/**
 * Creates a new JarEntry with the passed path and contents, and writes it
 * to the current archive.
 *
 * @param	resource			the file to write
 * @param	path				the path inside the archive
 *
    * @throws	IOException			if an I/O error has occurred
 * @throws	CoreException 		if the resource can-t be accessed
 */
protected void addFile(IFile resource, IPath path) throws IOException, CoreException {
	JarEntry newEntry= new JarEntry(path.toString().replace(File.separatorChar, '/'));
	byte[] readBuffer= new byte[4096];

	if (fJarPackage.isCompressed())
		newEntry.setMethod(ZipEntry.DEFLATED);
		// Entry is filled automatically.
	else {
		newEntry.setMethod(ZipEntry.STORED);
		JarPackagerUtil.calculateCrcAndSize(newEntry, resource.getContents(false), readBuffer);
	}

	long lastModified= System.currentTimeMillis();
	URI locationURI= resource.getLocationURI();
	if (locationURI != null) {
		IFileInfo info= EFS.getStore(locationURI).fetchInfo();
		if (info.exists())
			lastModified= info.getLastModified();
	}

	// Set modification time
	newEntry.setTime(lastModified);

	InputStream contentStream = resource.getContents(false);

	addEntry(newEntry, contentStream);
}
 
Example 13
public NameEnvironmentAnswer findClass(String sourceFileWithoutExtension, String qualifiedPackageName, String qualifiedSourceFileWithoutExtension) {
	SimpleLookupTable dirTable = directoryTable(qualifiedPackageName);
	if (dirTable != null && dirTable.elementSize > 0) {
		IFile file = (IFile) dirTable.get(sourceFileWithoutExtension);
		if (file != null) {
			return new NameEnvironmentAnswer(new ResourceCompilationUnit(file, file.getLocationURI()), null /* no access restriction */);
		}
	}
	return null;
}
 
Example 14
/**
 * Create an ICompilationUnit info from the given compilation unit on disk.
 */
protected ICompilationUnit createCompilationUnitFromPath(Openable handle, IFile file) {
	final char[] elementName = handle.getElementName().toCharArray();
	return new ResourceCompilationUnit(file, file.getLocationURI()) {
		public char[] getFileName() {
			return elementName;
		}
	};
}
 
Example 15
Source Project: ice   File: MOOSEFileHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This realization of IWriter.write() gets a valid TreeComposite from the
 * provided Form and writes it to the given file reference as a valid MOOSE
 * *.i input file. It throws an uncaught IllegalArgumentException if the
 * Form is not valid.
 * 
 * @param formToWrite
 *            The Form containing a valid TreeComposite to be written to the
 *            MOOSE input format.
 * @param file
 *            Reference to the file we are writing to.
 */
@Override
public void write(Form formToWrite, IFile file) {

	// Make sure we have a good Form.
	if (formToWrite == null) {
		throw new IllegalArgumentException("Error: MOOSEFileHandler.write() - the provided Form was null.");
	}

	TreeComposite mooseTree = (TreeComposite) formToWrite.getComponent(MOOSEModel.mooseTreeCompositeId);
	ArrayList<TreeComposite> children = new ArrayList<TreeComposite>();

	// We may very well not have a valid TreeComposite in this Form
	// Make sure we do
	if (mooseTree != null) {
		for (int i = 0; i < mooseTree.getNumberOfChildren(); i++) {
			children.add(mooseTree.getChildAtIndex(i));
		}
		URI uri = file.getLocationURI();
		dumpInputFile(uri.getPath(), children);
	} else {
		throw new IllegalArgumentException("Error: MOOSEFileHandler.write() expects a Form with a "
				+ "MOOSE TreeComposite at ID = " + MOOSEModel.mooseTreeCompositeId + ". Write failed.");
	}

	return;

}
 
Example 16
/**
 * Moves a file to the output directory with a new name.
 * 
 * @param project the current project
 * @param sourceFile output file to be moved
 * @param destDir the destination directory of the file
 * @param destName the new name of the file
 * @param monitor progress monitor
 * @throws CoreException if an error occurs
 * @return file in the new location
 */
private static IFile moveFile(IProject project, IFile sourceFile,
		IContainer destContainer, String destName,
		IProgressMonitor monitor) throws CoreException {
	if (sourceFile != null && sourceFile.exists() && destName != null) {
	    final IPath destRelPath = new Path(destName);
        final IFile dest = destContainer.getFile(destRelPath);

        if (dest.exists()) {
            File outFile = new File(sourceFile.getLocationURI());
            File destFile = new File(dest.getLocationURI());
            try {
                // Try to move the content instead of deleting the old file
                // and replace it by the new one. This is better for some
                // viewers like Sumatrapdf
                FileOutputStream out = new FileOutputStream(destFile);
                out.getChannel().tryLock();
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(outFile));

                byte[] buf = new byte[4096];
                int l;
                while ((l = in.read(buf)) != -1) {
                    out.write(buf, 0, l);
                }
                in.close();
                out.close();
                sourceFile.delete(true, monitor);
            } catch (IOException e) {
                // try to delete and move the file
                dest.delete(true, monitor);
                sourceFile.move(dest.getFullPath(), true, monitor);
            }
        }
        else {
            // move the file
            sourceFile.move(dest.getFullPath(), true, monitor);
        }
        monitor.worked(1);
        return dest;
    }
	else {
	    return null;
	}
}
 
Example 17
private Map<String, ArrayList<IResource>> buildJavaToClassMap(IContainer container, IProgressMonitor monitor) throws CoreException {
	if (container == null || !container.isAccessible())
		return new HashMap<String, ArrayList<IResource>>(0);
	/*
	 * XXX: Bug 6584: Need a way to get class files for a java file (or CU)
	 */
	IClassFileReader cfReader= null;
	IResource[] members= container.members();
	Map<String, ArrayList<IResource>> map= new HashMap<String, ArrayList<IResource>>(members.length);
	for (int i= 0;  i < members.length; i++) {
		if (isClassFile(members[i])) {
			IFile classFile= (IFile)members[i];
			URI location= classFile.getLocationURI();
			if (location != null) {
				InputStream contents= null;
				try {
					contents= EFS.getStore(location).openInputStream(EFS.NONE, monitor);
					cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.CLASSFILE_ATTRIBUTES);
				} finally {
					try {
						if (contents != null)
							contents.close();
					} catch (IOException e) {
						throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
							Messages.format(JarPackagerMessages.JarFileExportOperation_errorCannotCloseConnection, BasicElementLabels.getURLPart(Resources.getLocationString(classFile))),
							e));
					}
				}
				if (cfReader != null) {
					ISourceAttribute sourceAttribute= cfReader.getSourceFileAttribute();
					if (sourceAttribute == null) {
						/*
						 * Can't fully build the map because one or more
						 * class file does not contain the name of its
						 * source file.
						 */
						addWarning(Messages.format(
							JarPackagerMessages.JarFileExportOperation_classFileWithoutSourceFileAttribute,
							BasicElementLabels.getURLPart(Resources.getLocationString(classFile))), null);
						return null;
					}
					String javaName= new String(sourceAttribute.getSourceFileName());
					ArrayList<IResource> classFiles= map.get(javaName);
					if (classFiles == null) {
						classFiles= new ArrayList<IResource>(3);
						map.put(javaName, classFiles);
					}
					classFiles.add(classFile);
				}
			}
		}
	}
	return map;
}
 
Example 18
public URI read(IFile input) {
    return input.getLocationURI();
}
 
Example 19
Source Project: ice   File: MOOSEFileHandler.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This realization of IReader.read() takes the given file reference, gets
 * its file extension, and calls the appropriate routines to either load a
 * MOOSE input file or a MOOSE YAML specification.
 * 
 * @param file
 *            Reference to the file to be read.
 */
@Override
public Form read(IFile file) {

	// Local declarations
	String fileExt = "";
	Form returnForm = new Form();

	// Make sure we have a valid file reference
	if (file != null && file.exists()) {

		// Local declarations
		File mooseFile = new File(file.getLocationURI());
		ArrayList<TreeComposite> blocks = null;
		TreeComposite rootNode = new TreeComposite();

		String[] splitPath = mooseFile.getAbsolutePath().split("\\.(?=[^\\.]+$)");
		if (splitPath.length > 1) {
			fileExt = splitPath[1];
		} else {
			logger.info("MOOSEFileHandler Message:" + "File did not have file extension: "
					+ mooseFile.getAbsolutePath());
			return null;
		}

		try {
			// Parse the extension to see if we are loading
			// YAML or input files.
			if (fileExt.toLowerCase().equals("yaml")) {
				blocks = loadYAML(mooseFile.getAbsolutePath());
			} else if (fileExt.toLowerCase().equals("i")) {
				blocks = loadFromGetPot(mooseFile.getAbsolutePath());
			}

			// If we got a valid file, then construct
			// a Root TreeComposite to return
			if (blocks != null) {
				for (TreeComposite block : blocks) {
					// Clone the block
					TreeComposite blockClone = (TreeComposite) block.clone();

					// Don't want to do this if the file is a YAML file.
					if (!fileExt.toLowerCase().equals("yaml")) {
						// Set the parent and sibling references correctly
						blockClone.setActive(true);
						blockClone.setParent(rootNode);
					}
					rootNode.setNextChild(blockClone);
				}

				// Don't want to do this if the file is a YAML file.
				if (!fileExt.toLowerCase().equals("yaml")) {
					// Set the active data nodes
					setActiveDataNodes(rootNode);

					// Set the variable entries in the tree to
					// be discrete based on the available Variables and
					// AuxVariables
					setupVariables(rootNode);
					setupAuxVariables(rootNode);
				}

				// Set the Identifiable data on the TreeComposite
				rootNode.setId(MOOSEModel.mooseTreeCompositeId);
				rootNode.setDescription("The tree of input data for this problem.");
				rootNode.setName("Input Data");

				// Add it to the return Form
				returnForm.addComponent(rootNode);

				// Return the tree
				return returnForm;
			}

		} catch (IOException e) {
			logger.error(getClass().getName() + " Exception!", e);
			return null;
		}
	}

	return null;
}