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

The following examples show how to use org.eclipse.core.resources.IFile#exists() . 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: XMLPersistenceProvider.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This operation writes the specified object to the file in XML.
 *
 * @param obj
 *            The object to be written
 * @param file
 *            The file to where it should be written
 */
private void writeFile(Object obj, IFile file) {
	// Create an output stream containing the XML.
	ByteArrayOutputStream outputStream = createXMLStream(obj);
	// Convert it to an input stream so it can be pushed to file
	ByteArrayInputStream inputStream = new ByteArrayInputStream(
			outputStream.toByteArray());
	try {
		// Update the output file if it already exists
		if (file.exists()) {
			file.setContents(inputStream, IResource.FORCE, null);
		} else {
			// Or create it from scratch
			file.create(inputStream, IResource.FORCE, null);
		}
	} catch (CoreException e) {
		// Complain
		logger.error(getClass().getName() + " Exception!", e);
	}
	return;
}
 
Example 2
Source File: MavenImportUtils.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Restore the original pom file.
 *
 * @param project the project in which the pom file is located.
 * @param monitor the progress monitor.
 * @throws CoreException if the pom file cannot be changed.
 */
static void restorePom(IProject project, IProgressMonitor monitor) throws CoreException {
	final IFile pomFile = project.getFile(POM_FILE);
	final IFile savedPomFile = project.getFile(POM_BACKUP_FILE);
	pomFile.refreshLocal(IResource.DEPTH_ZERO, monitor);
	savedPomFile.refreshLocal(IResource.DEPTH_ZERO, monitor);
	monitor.worked(1);
	if (savedPomFile.exists()) {
		final SubMonitor submon = SubMonitor.convert(monitor, 3);
		if (pomFile.exists()) {
			pomFile.delete(true, false, submon);
		} else {
			submon.worked(1);
		}
		savedPomFile.copy(pomFile.getFullPath(), true, submon);
		savedPomFile.delete(true, false, monitor);
		submon.worked(1);
	} else {
		monitor.worked(1);
	}
}
 
Example 3
Source File: AbstractRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public T getChild(final String fileName, boolean force) {
    Assert.isNotNull(fileName);
    final IFile file = getResource().getFile(fileName);
    if (force && !file.isSynchronized(IResource.DEPTH_ONE) && file.isAccessible()) {
        try {
            file.refreshLocal(IResource.DEPTH_ONE, Repository.NULL_PROGRESS_MONITOR);
        } catch (final CoreException e) {
            BonitaStudioLog.error(e);
        }
    }
    if (file.exists()) {
        return createRepositoryFileStore(fileName);
    }

    return null;
}
 
Example 4
Source File: ClientBundleResourceDialog.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * If the user just changed the File field to a valid file and the other
 * fields are blank, pre-populate them based on the filename.
 */
private void fileFieldChanged() {
  IFile file = getFileFieldValue();
  if (file == null || !file.exists()) {
    return;
  }

  if (methodNameField.getText().length() == 0) {
    methodNameField.setText(ClientBundleUtilities.suggestMethodName(file));
  }

  if (resourceTypeField.getText().length() == 0) {
    resourceTypeField.setText(ClientBundleUtilities.suggestResourceTypeName(
        javaProject, file));
  }
}
 
Example 5
Source File: AbstractRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private T createEmptyFile(final String fileName, final InputStream inputStream) {
    try {
        final IFile iFile = getResource().getFile(fileName);
        final File file = iFile.getLocation().toFile();
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            getResource().refreshLocal(IResource.DEPTH_INFINITE, Repository.NULL_PROGRESS_MONITOR);
        }
        if (!iFile.exists()) {
            iFile.create(inputStream, true, Repository.NULL_PROGRESS_MONITOR);
        }
    } catch (final CoreException e) {
        BonitaStudioLog.error(e);
    }
    return null;
}
 
Example 6
Source File: Model.java    From tlaplus with MIT License 6 votes vote down vote up
private boolean isMarkerSet(String markerType, final String attributeName) {
	// marker
	final IFile resource = getFile();
	if (resource.exists()) {
		try {
			final IMarker[] foundMarkers = resource.findMarkers(markerType, false, IResource.DEPTH_ZERO);
			if (foundMarkers.length > 0) {
				boolean set = foundMarkers[0].getAttribute(attributeName, false);
				// remove trash if any
				for (int i = 1; i < foundMarkers.length; i++) {
					foundMarkers[i].delete();
				}
				return set;
			} else {
				return false;
			}
		} catch (CoreException shouldNotHappen) {
			TLCActivator.logError(shouldNotHappen.getMessage(), shouldNotHappen);
		}
	}
	return false;
}
 
Example 7
Source File: WebProjectUtil.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/**
 * Create a file in the appropriate location for the project's {@code WEB-INF}. This
 * implementation respects the order and tags on the WTP virtual component model, creating the
 * file in the {@code <wb-resource>} with the {@code defaultRootSource} tag when present. This
 * method is typically used after ensuring the file does not exist with {@link
 * #findInWebInf(IProject, IPath)}.
 *
 * <p>See <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=448544">Eclipse bug 448544</a>
 * for details of the {@code defaultRootSource} tag.
 *
 * @param project the hosting project
 * @param filePath the path of the file within the project's {@code WEB-INF}
 * @param contents the content for the file
 * @param overwrite if {@code true} then overwrite the file if it exists
 * @see #findInWebInf(IProject, IPath)
 */
public static IFile createFileInWebInf(
    IProject project,
    IPath filePath,
    InputStream contents,
    boolean overwrite,
    IProgressMonitor monitor)
    throws CoreException {
  IFolder webInfDir = findWebInfForNewResource(project);
  IFile file = webInfDir.getFile(filePath);
  SubMonitor progress = SubMonitor.convert(monitor, 2);
  if (!file.exists()) {
    ResourceUtils.createFolders(file.getParent(), progress.newChild(1));
    file.create(contents, true, progress.newChild(1));
  } else if (overwrite) {
    file.setContents(contents, IResource.FORCE | IResource.KEEP_HISTORY, progress.newChild(2));
  }
  return file;
}
 
Example 8
Source File: Model.java    From tlaplus with MIT License 6 votes vote down vote up
public List<IFile> getSavedTLAFiles() {
	try {
		final List<IFile> res = new ArrayList<>();
		final IFolder targetDirectory = getTargetDirectory();
		if (targetDirectory == null) {
			// Model has not been run yet.
			return res;
		}
		final List<IResource> asList = Arrays.asList(targetDirectory.members());
		for (final IResource iResource : asList) {
			if (iResource instanceof IFile) {
				final IFile f = (IFile) iResource;
				if (f.exists() && "tla".equalsIgnoreCase(f.getFileExtension())) {
					res.add(f);
				}
			}
		}
		return res;
	} catch (CoreException e) {
		return new ArrayList<>();
	}
}
 
Example 9
Source File: ModelHelper.java    From tlaplus with MIT License 6 votes vote down vote up
public static void copyModuleFiles(IFile specRootFile, IPath targetFolderPath, IProgressMonitor monitor,
        int STEP, IProject project, Collection<String> extendedModules, final Predicate<String> p) throws CoreException
{

    // iterate and copy modules that are needed for the spec
    IFile moduleFile = null;
    
    final Iterator<String> iterator = extendedModules.iterator();
    while (iterator.hasNext()) {
    	String module = iterator.next();
        // only take care of user modules
        if (p.test(module))
        {
            moduleFile = ResourceHelper.getLinkedFile(project, module, false);
            if (moduleFile != null && moduleFile.exists())
            {
                moduleFile.copy(targetFolderPath.append(moduleFile.getProjectRelativePath()), IResource.DERIVED
                        | IResource.FORCE, new SubProgressMonitor(monitor, STEP / extendedModules.size()));
            }

            // TODO check the existence of copied files
        }
    }
}
 
Example 10
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Record a shared persistent property onto a project.
 * Note that it is orthogonal to IResource persistent properties, and client code has to decide
 * which form of storage to use appropriately. Shared properties produce real resource files which
 * can be shared through a VCM onto a server. Persistent properties are not shareable.
 * <p>
 * Shared properties end up in resource files, and thus cannot be modified during
 * delta notifications (a CoreException would then be thrown).
 *
 * @param key String
 * @param value String
 * @see JavaProject#getSharedProperty(String key)
 * @throws CoreException
 */
public void setSharedProperty(String key, String value) throws CoreException {

	IFile rscFile = this.project.getFile(key);
	byte[] bytes = null;
	try {
		bytes = value.getBytes(org.eclipse.jdt.internal.compiler.util.Util.UTF_8); // .classpath always encoded with UTF-8
	} catch (UnsupportedEncodingException e) {
		Util.log(e, "Could not write .classpath with UTF-8 encoding "); //$NON-NLS-1$
		// fallback to default
		bytes = value.getBytes();
	}
	InputStream inputStream = new ByteArrayInputStream(bytes);
	// update the resource content
	if (rscFile.exists()) {
		if (rscFile.isReadOnly()) {
			// provide opportunity to checkout read-only .classpath file (23984)
			ResourcesPlugin.getWorkspace().validateEdit(new IFile[]{rscFile}, IWorkspace.VALIDATE_PROMPT);
		}
		rscFile.setContents(inputStream, IResource.FORCE, null);
	} else {
		rscFile.create(inputStream, IResource.FORCE, null);
	}
}
 
Example 11
Source File: Model.java    From tlaplus with MIT License 6 votes vote down vote up
/**
    * Tries to recover model after an abnormal TLC termination
    * It deletes all temporary files on disk and restores the state to unlocked.
    */
public void recover() {
	final IFile resource = getFile();
	if (resource.exists()) {
		try {
			// remove any crashed markers
			IMarker[] foundMarkers = resource.findMarkers(TLC_CRASHED_MARKER, false, IResource.DEPTH_ZERO);
			if (foundMarkers.length == 0) {
				return;
			}
			
			for (int i = 0; i < foundMarkers.length; i++) {
				foundMarkers[i].delete();
			}
			
			foundMarkers = resource.findMarkers(TLC_MODEL_IN_USE_MARKER, false, IResource.DEPTH_ZERO);
			for (int i = 0; i < foundMarkers.length; i++) {
				foundMarkers[i].delete();
			}
		} catch (CoreException shouldNotHappen) {
			TLCActivator.logError(shouldNotHappen.getMessage(), shouldNotHappen);
		}
	}
}
 
Example 12
Source File: TraceForStorageProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IFile asFile(AbsoluteURI absoluteURI, IProjectConfig project) {
	URI uri = absoluteURI.getURI();
	if (uri.isPlatformResource()) {
		IFile result = workspace.getRoot().getFile(new Path(uri.toPlatformString(true)));
		if (result.exists()) {
			return result;
		}
	}
	return null;
}
 
Example 13
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IEditorPart openDeclaration(IJavaElement element) throws PartInitException, JavaModelException {
	if (!(element instanceof IPackageFragment)) {
		return JavaUI.openInEditor(element);
	}
	
	IPackageFragment packageFragment= (IPackageFragment) element;
	ITypeRoot typeRoot;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		typeRoot= packageFragment.getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	} else {
		typeRoot= packageFragment.getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	}

	// open the package-info file in editor if one exists
	if (typeRoot.exists())
		return JavaUI.openInEditor(typeRoot);

	// open the package.html file in editor if one exists
	Object[] nonJavaResources= packageFragment.getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return EditorUtility.openInEditor(file, true);
			}
		}
	}

	// select the package in the Package Explorer if there is no associated package Javadoc file
	PackageExplorerPart view= (PackageExplorerPart) JavaPlugin.getActivePage().showView(JavaUI.ID_PACKAGES);
	view.tryToReveal(packageFragment);
	return null;
}
 
Example 14
Source File: StandardFacetInstallDelegate.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/** Creates an App Engine configuration file in the appropriate folder, if it doesn't exist. */
private void createAppEngineConfigurationFile(
    IProject project,
    String filename,
    String templateName,
    Map<String, String> templateParameters,
    IProgressMonitor monitor)
    throws CoreException {
  SubMonitor progress = SubMonitor.convert(monitor, 7);

  IFile targetFile =
      AppEngineConfigurationUtil.findConfigurationFile(project, new Path(filename));
  if (targetFile != null && targetFile.exists()) {
    return;
  }

  // todo Templates should provide content as an InputStream
  targetFile =
      AppEngineConfigurationUtil.createConfigurationFile(
          project,
          new Path(filename),
          new ByteArrayInputStream(new byte[0]),
          false /* overwrite */,
          progress.split(2));
  String fileLocation = targetFile.getLocation().toString();
  Templates.createFileContent(fileLocation, templateName, templateParameters);
  progress.worked(4);
  targetFile.refreshLocal(IFile.DEPTH_ZERO, progress.split(1));
}
 
Example 15
Source File: LibraryClasspathContainerSerializer.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public void removeContainerStateFile(IJavaProject javaProject, String id) throws CoreException {
  IFile stateFile = getFile(javaProject, id, false);
  Verify.verifyNotNull(stateFile);
  if (stateFile.exists()) {
    stateFile.delete(true, new NullProgressMonitor());
  }
}
 
Example 16
Source File: CheckExtensionGenerator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the given plugin file is valid.
 *
 * @param file
 *          plugin.xml file to check, must not be {@code null}
 * @return {@code true} if the file is valid
 */
private boolean validPluginFile(final IFile file) {
  if (file == null || !file.exists()) {
    return false;
  }
  try {
    SAXParserFactory.newInstance().newSAXParser().parse(new BufferedInputStream(file.getContents(true)), new PluginHandler(false));
    return true;
  } catch (SAXException | IOException | ParserConfigurationException | CoreException e) {
    return false;
  }
}
 
Example 17
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 18
Source File: WizardSaveAsPage.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get the saving path
 * 
 * @return the saving path
 */
public IPath getResult( )
{

	IPath path = resourceGroup.getContainerFullPath( )
			.append( resourceGroup.getResource( ) );

	// If the user does not supply a file extension and if the save
	// as dialog was provided a default file name append the extension
	// of the default filename to the new name
	if ( path.getFileExtension( ) == null )
	{
		if ( originalFile != null
				&& originalFile.getFileExtension( ) != null )
			path = path.addFileExtension( originalFile.getFileExtension( ) );
		else if ( originalName != null )
		{
			int pos = originalName.lastIndexOf( '.' );
			if ( ++pos > 0 && pos < originalName.length( ) )
				path = path.addFileExtension( originalName.substring( pos ) );
		}
	}

	// If the path already exists then confirm overwrite.
	IFile file = ResourcesPlugin.getWorkspace( ).getRoot( ).getFile( path );

	if ( file.exists( ) )
	{
		String[] buttons = new String[]{
				IDialogConstants.YES_LABEL,
				IDialogConstants.NO_LABEL,
				IDialogConstants.CANCEL_LABEL
		};
		String question = Messages.getFormattedString( "WizardSaveAsPage.OverwriteQuestion", //$NON-NLS-1$
				new Object[]{
					path.toOSString( )
				} );
		MessageDialog d = new MessageDialog( getShell( ),
				Messages.getString( "WizardSaveAsPage.Question" ), //$NON-NLS-1$
				null,
				question,
				MessageDialog.QUESTION,
				buttons,
				0 );
		int overwrite = d.open( );
		switch ( overwrite )
		{
			case 0 : // Yes
				break;
			case 1 : // No
				return null;
			case 2 : // Cancel
			default :
				return Path.EMPTY;
		}
	}

	return path;
}
 
Example 19
Source File: IDEMultiPageReportEditor.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void partActivated( IWorkbenchPart part )
{
	super.partActivated( part );
	if ( part != this )

		return;
	if ( isWorkspaceResource )
	{
		final IFile file = ( (IFileEditorInput) getEditorInput( ) ).getFile( );
		if ( !file.exists( ) )
		{

			Shell shell = getSite( ).getShell( );

			String title = DLG_SAVE_TITLE;

			String message = DLG_SAVE_CONFIRM_DELETE;

			String[] buttons = {
					DLG_SAVE_BUTTON_SAVE, DLG_SAVE_BUTTON_CLOSE
			};

			if ( closedStatus.contains( file ) )
			{
				return;
			}

			MessageDialog dialog = new MessageDialog( shell,
					title,
					null,
					message,
					MessageDialog.QUESTION,
					buttons,
					0 );

			closedStatus.add( file );

			int result = dialog.open( );

			if ( result == 0 )
			{
				doSaveAs( );
				partActivated( part );
			}
			else
			{
				closeEditor( false );
			}
			Display.getDefault( ).asyncExec( new Runnable( ) {

				public void run( )
				{
					closedStatus.remove( file );
				}
			} );
		}
	}
}
 
Example 20
Source File: ResourceUtil.java    From APICloud-Studio with GNU General Public License v3.0 2 votes vote down vote up
/**
 * If the file is null, doesn't exist, is derived or is team private this returns true. Used to skip files for
 * build/reconcile.
 * 
 * @param file
 * @return
 */
public static boolean shouldIgnore(IFile file)
{
	return file == null || !file.exists() || file.isTeamPrivateMember(IResource.CHECK_ANCESTORS)
			|| file.isDerived(IResource.CHECK_ANCESTORS);
}