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

The following examples show how to use org.eclipse.core.resources.IFile#createLink() . 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: ResourceHelper.java    From tlaplus with MIT License 6 votes vote down vote up
public static IFile getLinkedFileUnchecked(IContainer project, String name, boolean createNew) throws CoreException
{
    if (name == null || project == null)
    {
        return null;
    }
    IPath location = new Path(name);
    IFile file = project.getFile(new Path(location.lastSegment()));
    if (createNew)
    {
        if (!file.isLinked())
        {
                file.createLink(location, IResource.NONE, new NullProgressMonitor());
                return file;
        }
        if (file.exists())
        {
            return file;
        } else
        {
            return null;
        }
    }
    return file;
}
 
Example 2
Source File: TracePackageExportOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a linked resource in the specified folder
 *
 * @param exportFolder the folder that will contain the linked resource
 * @param res the resource to export
 * @throws CoreException when createLink fails
 * @return the created linked resource
 */
private static IResource createExportResource(IFolder exportFolder, IResource res) throws CoreException {
    IResource ret = null;
    // Note: The resources cannot be HIDDEN or else they are ignored by ArchiveFileExportOperation
    if (res instanceof IFolder) {
        IFolder folder = exportFolder.getFolder(res.getName());
        folder.createLink(res.getLocationURI(), IResource.REPLACE, null);
        ret = folder;
    } else if (res instanceof IFile) {
        IFile file = exportFolder.getFile(res.getName());
        if (!file.exists()) {
            file.createLink(res.getLocationURI(), IResource.NONE, null);
        }
        ret = file;
    }
    return ret;
}
 
Example 3
Source File: FileUtils.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
private static IFile createLinkedFile(final String path, final IFile file) {
	java.net.URI resolvedURI = null;
	final java.net.URI javaURI = URIUtil.toURI(path);// new java.io.File(path).toURI();

	try {
		resolvedURI = ROOT.getPathVariableManager().convertToRelative(javaURI, true, null);
	} catch (final CoreException e1) {
		resolvedURI = javaURI;
	}
	try {
		file.createLink(resolvedURI, IResource.NONE, null);
	} catch (final CoreException e) {
		e.printStackTrace();
		return null;
	}
	return file;
}
 
Example 4
Source File: TexProjectParser.java    From texlipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the given file from the project and returns it or null
 * if such a file wasn't found. If the file was found in a path outside
 * the project, a link to the file is created.
 * 
 * @param fileName The name of the file to look for
 * @param referringFile The file referring to this file (used for paths)
 * @param currentProject
 * @return The found file or null if it wasn't found
 */
public static IFile findIFile(String fileName, IFile referringFile, IProject currentProject) {

    // Append default ending
    if (fileName.indexOf('.') == -1
            || fileName.lastIndexOf('/') > fileName.lastIndexOf('.')) {
        fileName += TEX_FILE_ENDING;
    }
    IPath path = referringFile.getFullPath();
    path = path.removeFirstSegments(1).removeLastSegments(1).append(fileName);
    IFile file = currentProject.getFile(path);
    if (!file.exists()) {
        //Try Kpsewhich
        KpsewhichRunner filesearch = new KpsewhichRunner();
        try {
            String fName = filesearch.getFile(currentProject, fileName, "latex");
            if (fName.length() > 0) {
                //Create a link
                IPath p = new Path(fName);
                file.createLink(p, IResource.NONE, null);
            }
        } catch (CoreException e) {
            TexlipsePlugin.log("Can't run Kpathsea", e);
        }
    }
    return file.exists() ? file : null;
}
 
Example 5
Source File: AbstractProjectsManagerBasedTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected IFile linkFilesToDefaultProject(String path) throws Exception {
	IProject testProject = projectsManager.getDefaultProject();
	String fullpath = copyFiles(path, true).getAbsolutePath().replace('\\', '/');
	String fileName = fullpath.substring(fullpath.lastIndexOf("/") + 1);
	IPath filePath = new Path("src").append(fileName);
	final IFile file = testProject.getFile(filePath);
	URI uri = Paths.get(fullpath).toUri();
	JDTUtils.createFolders(file.getParent(), monitor);
	waitForBackgroundJobs();
	file.createLink(uri, IResource.REPLACE, monitor);
	waitForBackgroundJobs();
	return file;
}
 
Example 6
Source File: ResourceHelper.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * Retrieves a a resource from the project, creates a link if createNew is true and the file is not present 
 * TODO improve this, if the name is wrong
 * 
 * @param name full filename of the resource
 * @param project
 * @param createNew, a boolean flag indicating if the new link should be created if it does not exist
 */
public static IFile getLinkedFile(IContainer project, String name, boolean createNew)
{
    if (name == null || project == null)
    {
        return null;
    }
    IPath location = new Path(name);
    IFile file = project.getFile(new Path(location.lastSegment()));
    if (createNew)
    {
        if (!file.isLinked())
        {
            try
            {
                file.createLink(location, IResource.NONE, new NullProgressMonitor());
                return file;

            } catch (CoreException e)
            {
                Activator.getDefault().logError("Error creating resource link to " + name, e);
            }
        }
        if (file.exists())
        {
            return file;
        } else
        {
            return null;
        }
    }
    return file;
}
 
Example 7
Source File: WorkspaceModelsManager.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
IFile createUnclassifiedModelsProjectAndAdd(final IPath location) {
	IFile iFile = null;
	try {
		final IFolder modelFolder = createUnclassifiedModelsProject(location);
		iFile = modelFolder.getFile(location.lastSegment());
		if ( iFile.exists() ) {
			if ( iFile.isLinked() ) {
				final IPath path = iFile.getLocation();
				if ( path.equals(location) ) {
					// First case, this is a linked resource to the same location. In that case, we simply return
					// its name.
					return iFile;
				} else {
					// Second case, this resource is a link to another location. We create a filename that is
					// guaranteed not to exist and change iFile accordingly.
					iFile = createUniqueFileFrom(iFile, modelFolder);
				}
			} else {
				// Third case, this resource is local and we do not want to overwrite it. We create a filename that
				// is guaranteed not to exist and change iFile accordingly.
				iFile = createUniqueFileFrom(iFile, modelFolder);
			}
		}
		iFile.createLink(location, IResource.NONE, null);
		// RefreshHandler.run();
		return iFile;
	} catch (final CoreException e) {
		e.printStackTrace();
		MessageDialog.openInformation(Display.getDefault().getActiveShell(), "Error in creation",
			"The file " + (iFile == null ? location.lastSegment() : iFile.getFullPath().lastSegment()) +
				" cannot be created because of the following exception " + e.getMessage());
		return null;
	}
}
 
Example 8
Source File: Importer.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 4 votes vote down vote up
private void fixMissingProjectResources(IProgressMonitor monitor, File platformHome) throws CoreException
{
	Set<IProject> projects = FixProjectsUtils.getAllHybrisProjects();
	IProject config = null;
	IProject platform = null;
	for(IProject proj: projects) {
		if( "config".equals(proj.getName()) ) {
			config = proj;
		}
		if( "platform".equals(proj.getName()) ) {
			platform = proj;
		}
	}
	if( config != null && platform != null ) {
		IFile activeRoleEnvPropertyFile = platform.getFile("active-role-env.properties");
		IFile instancePropertiesLink = config.getFile("instance.properties");
		
		if( instancePropertiesLink.exists() ) {
			// Remove the instance.properties link if existing
			instancePropertiesLink.delete(IResource.NEVER_DELETE_PROJECT_CONTENT, monitor);
		}
		if( activeRoleEnvPropertyFile.exists() ) {
			// extract currently enabled role & instance from active-role-env.properties
			// https://wiki.hybris.com/display/RD/hybris+server+roles)
			Properties prop = new Properties();
			try (InputStream input = new FileInputStream(activeRoleEnvPropertyFile.getLocation().toFile())) {
				prop.load(input);
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
			String activeRole = prop.getProperty("ACTIVE_ROLE").replace("${platformhome}", platformHome.toString());
			String activeInstance = prop.getProperty("ACTIVE_ROLE_INSTANCE").replace("${platformhome}", platformHome.toString());

			// Create the instance.properties link
			File hybrisRootDir = platform.getLocation().toFile().getParentFile().getParentFile();
		    File instanceConfigDir = new File(new File(new File(new File(hybrisRootDir, "roles"), activeRole), activeInstance), "config");
		    File instancePropertiesFile = new File(instanceConfigDir, "instance.properties");
		    
		   IPath location = new Path(instancePropertiesFile.toString());
		   if (DEBUG) {
			   Activator.log("location = "+location.toString());
			   Activator.log("instancePropertiesLink = "+instancePropertiesLink.toString());
		   }
		   
		   instancePropertiesLink.createLink(location, IResource.NONE, null);
		}
	}
}
 
Example 9
Source File: ProjectExplorerTraceActionsTest.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Test the backward compatibility
 */
@Test
public void testExperimentLinkBackwardCompatibility() {
    /*
     * close the editor for the trace to avoid name conflicts with the one for the
     * experiment
     */
    fBot.closeAllEditors();

    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    final IProject project = root.getProject(TRACE_PROJECT_NAME);
    assertTrue(project.exists());
    TmfProjectElement projectElement = TmfProjectRegistry.getProject(project);

    // Get the experiment folder
    TmfExperimentFolder experimentsFolder = projectElement.getExperimentsFolder();
    assertNotNull("Experiment folder should exist", experimentsFolder);
    IFolder experimentsFolderResource = experimentsFolder.getResource();
    String experimentName = "exp";
    IFolder expFolder = experimentsFolderResource.getFolder(experimentName);
    assertFalse(expFolder.exists());

    // Create the experiment
    try {
        expFolder.create(true, true, null);
        IFile file = expFolder.getFile(TRACE_NAME);
        file.createLink(Path.fromOSString(fTestFile.getAbsolutePath()), IResource.REPLACE, new NullProgressMonitor());
    } catch (CoreException e) {
        fail("Failed to create the experiment");
    }

    fBot.viewByTitle(PROJECT_EXPLORER_VIEW_NAME).setFocus();
    SWTBotTreeItem experimentsItem = SWTBotUtils.getTraceProjectItem(fBot, SWTBotUtils.selectProject(fBot, TRACE_PROJECT_NAME), "Experiments");

    SWTBotTreeItem expItem = SWTBotUtils.getTraceProjectItem(fBot, experimentsItem, "exp");

    // find the trace under the experiment
    expItem.expand();
    expItem.getNode(TRACE_NAME);

    // Open the experiment
    expItem.contextMenu().menu("Open").click();
    fBot.waitUntil(new ConditionHelpers.ActiveEventsEditor(fBot, experimentName));
}
 
Example 10
Source File: TmfCommonProjectElement.java    From tracecompass with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Actually returns the bookmark file or creates it in the project element's
 * folder
 *
 * @param bookmarksFolder
 *            Folder where to put the bookmark file
 * @param editorInputType
 *            The editor input type to set (trace or experiment)
 * @param monitor
 *            The progress monitor
 * @return The bookmark file
 * @throws CoreException
 *             if the bookmarks file cannot be created
 * @throws OperationCanceledException
 *             if the operation was canceled
 * @since 4.0
 */
protected IFile createBookmarksFile(IFolder bookmarksFolder, String editorInputType, IProgressMonitor monitor) throws CoreException, OperationCanceledException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, 2);
    IFile file = getBookmarksFile();
    if (!file.exists()) {
        final IFile bookmarksFile = bookmarksFolder.getFile(BOOKMARKS_HIDDEN_FILE);
        if (!bookmarksFile.exists()) {
            final InputStream source = new ByteArrayInputStream(new byte[0]);
            bookmarksFile.create(source, IResource.FORCE | IResource.HIDDEN, subMonitor.split(1));
        }
        file.createLink(bookmarksFile.getLocation(), IResource.REPLACE | IResource.HIDDEN, subMonitor.split(1));
    }
    file.setPersistentProperty(TmfCommonConstants.TRACETYPE, editorInputType);
    return file;
}