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

The following examples show how to use org.eclipse.core.resources.IFile#refreshLocal() . 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: ProjectCacheInvalidationPluginTest.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Performs the given {@code updateOperation} on the loaded AST of the given {@code packageJsonFile} and saves it to
 * disk.
 */
private void updatePackageJsonFile(IFile packageJsonFile, Consumer<JSONObject> updateOperation)
		throws CoreException {
	final IProject project = packageJsonFile.getProject();
	final ResourceSet resourceSet = resourceSetProvider.get(project);

	// read and parse package.json contents
	final String path = packageJsonFile.getFullPath().toString();
	final URI uri = URI.createPlatformResourceURI(path, true);
	final Resource resource = resourceSet.getResource(uri, true);

	final JSONObject root = PackageJSONTestUtils.getPackageJSONRoot(resource);
	updateOperation.accept(root);

	try {
		resource.save(null);
	} catch (IOException e) {
		throw new WrappedException("Failed to save package.json resource at " + resource.getURI().toString() + ".",
				e);
	}
	packageJsonFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
}
 
Example 2
Source File: CompileCommandsJsonParser.java    From cmake4eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private static void createMarker(IFile file, String message) throws CoreException {
  IMarker marker;
  try {
    marker = file.createMarker(MARKER_ID);
  } catch (CoreException ex) {
    // resource is not (yet) known by the workbench
    try {
      file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
      marker = file.createMarker(MARKER_ID);
    } catch (CoreException ex2) {
      // resource is not known by the workbench, use project instead of file
      marker = file.getProject().createMarker(MARKER_ID);
    }
  }
  marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
  marker.setAttribute(IMarker.MESSAGE, message);
  marker.setAttribute(IMarker.LOCATION, CompileCommandsJsonParser.class.getName());
}
 
Example 3
Source File: AbstractRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void migrate(final IProgressMonitor monitor) throws CoreException, MigrationException {
    List<IFile> filesToMigrate = getChildren().stream()
            .filter(fs -> !fs.isReadOnly())
            .filter(IRepositoryFileStore::canBeShared)
            .map(IRepositoryFileStore::getResource)
            .filter(IFile.class::isInstance)
            .map(IFile.class::cast)
            .filter(IFile::exists)
            .collect(Collectors.toList());

    for (IFile file : filesToMigrate) {
        monitor.subTask(file.getName());
        InputStream newIs;
        try (final InputStream is = file.getContents()) {
            newIs = handlePreImport(file.getName(), is);
            if (!is.equals(newIs)) {
                file.setContents(newIs, IResource.FORCE, monitor);
                file.refreshLocal(IResource.DEPTH_ONE, monitor);
            }
        } catch (final IOException e) {
            throw new MigrationException("Cannot migrate resource " + file.getName() + " (not a valid file)", e);
        }
    }
}
 
Example 4
Source File: AbstractDocXmlPersist.java    From depan with 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 5
Source File: Storage2UriMapperJdtImplTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug463258_03c() throws Exception {
	IJavaProject project = createJavaProject("foo");
	IFile file = project.getProject().getFile("foo.jar");
	file.create(jarInputStream(new TextFile("foo/bar.notindexed", "//empty")), true, monitor());
	addJarToClasspath(project, file);
	
	Storage2UriMapperJavaImpl impl = getStorage2UriMapper();
	
	IPackageFragmentRoot root = JarPackageFragmentRootTestUtil.getJarPackageFragmentRoot(file, (JavaProject) project);
	IPackageFragment foo = root.getPackageFragment("foo");
	JarEntryFile fileInJar = new JarEntryFile("bar.notindexed");
	fileInJar.setParent(foo);
	
	File jarFile = file.getLocation().toFile();
	assertTrue("exists", jarFile.exists());
	assertTrue("delete", jarFile.delete());
	// simulate an automated refresh
	file.refreshLocal(IResource.DEPTH_ONE, null);
	URI uri = impl.getUri(fileInJar);
	assertNull(uri);
}
 
Example 6
Source File: ERFluteMultiPageEditor.java    From erflute with Apache License 2.0 6 votes vote down vote up
private void prepareDiagram() {
    try {
        final IFile file = ((IFileEditorInput) getEditorInput()).getFile();
        setPartName(file.getName());
        final Persistent persistent = Persistent.getInstance();
        if (!file.isSynchronized(IResource.DEPTH_ONE)) {
            file.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
        }
        final InputStream in = file.getContents();
        diagram = persistent.read(in);
    } catch (final Exception e) {
        Activator.showExceptionDialog(e);
    }
    if (diagram == null) {
        diagram = new ERDiagram(DBManagerFactory.getAllDBList().get(0));
        diagram.init();
    }
    diagram.setEditor(this);
}
 
Example 7
Source File: DuplicateDiagramOperation.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private void replaceIdInFile(final IFile file, final Copier copier) throws IOException, CoreException {
    final File fileToModify = file.getLocation().toFile();
    StringBuilder sb = new StringBuilder();
    String line = ""; //$NON-NLS-1$
    try (final BufferedReader reader = new BufferedReader(new FileReader(fileToModify));) {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
        }
    }
    for (final java.util.Map.Entry<EObject, EObject> entry : copier.entrySet()) {
        final String originalId = ModelHelper.getEObjectID(entry.getKey());
        final String newId = ModelHelper.getEObjectID(entry.getValue());
        final String content = sb.toString();
        if (content.contains(originalId)) {
            sb = new StringBuilder(content.replaceAll(originalId, newId));
        }
    }

    try (final FileWriter writer = new FileWriter(fileToModify.getAbsolutePath());) {
        writer.write(sb.toString());
    }
    file.refreshLocal(IResource.DEPTH_ONE, Repository.NULL_PROGRESS_MONITOR);
}
 
Example 8
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 9
Source File: TxtUMLToUML2.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Exports the txtUML model to a org.eclipse.uml2.uml.Model representation
 * 
 * @param sourceProject
 *            name of the source project, where the txtUML model can be find
 * @param packageName
 *            fully qualified name of the txtUML model
 * @param outputDirectory
 *            where the result model should be saved
 * @param folder
 *            the target folder for generated model
 */
public static Model exportModel(String sourceProject, String packageName, URI outputDirectory,
		ExportMode exportMode, String folder) throws NotFoundException, JavaModelException, IOException {

	Model model = exportModel(sourceProject, packageName, exportMode, folder);

	File file = new File(model.eResource().getURI().toFileString());
	file.getParentFile().mkdirs();
	model.eResource().save(null);

	IFile createdFile = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI())[0];
	try {
		createdFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
	} catch (CoreException e) {
		throw new RuntimeException(e);
	}

	return model;
}
 
Example 10
Source File: CodeTemplates.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static IFile createChildFile(String name, String template, IContainer parent,
    Map<String, String> values, IProgressMonitor monitor) throws CoreException {
  monitor.subTask("Creating file " + name);

  ResourceUtils.createFolders(parent, monitor);
  IFile child = parent.getFile(new Path(name));
  if (!child.exists()) {
    Templates.createFileContent(child.getLocation().toString(), template, values);
    child.refreshLocal(IResource.DEPTH_ZERO, monitor);
  }
  return child;
}
 
Example 11
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 12
Source File: BDMArtifactDescriptor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public void save(IFile descriptorPropertyFile) throws CoreException {
    Properties properties = new PropertiesWithoutComment();
    properties.setProperty(GROUP_ID_PROPERTY, getGroupId());
    try (OutputStream out = new FileOutputStream(descriptorPropertyFile.getLocation().toFile())) {
        properties.store(out, null);
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, BusinessObjectPlugin.PLUGIN_ID,
                "Failed to save BDM artifact descriptor", e));
    }
    descriptorPropertyFile.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor());
}
 
Example 13
Source File: CrossflowDocumentProvider.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
/**
* @generated
*/
protected void handleElementChanged(ResourceSetInfo info, Resource changedResource, IProgressMonitor monitor) {
	IFile file = WorkspaceSynchronizer.getFile(changedResource);
	if (file != null) {
		try {
			file.refreshLocal(IResource.DEPTH_INFINITE, monitor);
		} catch (CoreException ex) {
			CrossflowDiagramEditorPlugin.getInstance()
					.logError(Messages.CrossflowDocumentProvider_handleElementContentChanged, ex);
			// Error message to log was initially taken from org.eclipse.gmf.runtime.diagram.ui.resources.editor.ide.internal.l10n.EditorMessages.FileDocumentProvider_handleElementContentChanged
		}
	}
	changedResource.unload();

	fireElementContentAboutToBeReplaced(info.getEditorInput());
	removeUnchangedElementListeners(info.getEditorInput(), info);
	info.fStatus = null;
	try {
		setDocumentContent(info.fDocument, info.getEditorInput());
	} catch (CoreException e) {
		info.fStatus = e.getStatus();
	}
	if (!info.fCanBeSaved) {
		info.setModificationStamp(computeModificationStamp(info));
	}
	addUnchangedElementListeners(info.getEditorInput(), info);
	fireElementContentReplaced(info.getEditorInput());
}
 
Example 14
Source File: ImportedResourceCache.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Refresh local file to avoid deadlock with scheduling rule XtextBuilder ->
 * Editing Domain runexclusive
 */
protected void refreshFile(final URI uri) {
	String platformString = uri.toPlatformString(true);
	if (platformString == null)
		return;
	IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(platformString));
	if (file.isAccessible() && !file.isSynchronized(IResource.DEPTH_INFINITE)) {
		try {
			file.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
 
Example 15
Source File: ParallelResourceLoader.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Make sure that all files that are about to be loaded are synchronized with the file system
 */
private void synchronizeResources(Collection<URI> toLoad) {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	for(URI uri : toLoad) {
		if (uri.isPlatformResource()) {
			Path path = new Path(uri.toPlatformString(true));
			IFile file = root.getFile(path);
			try {
				file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
			} catch (CoreException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
 
Example 16
Source File: AbstractDeleteChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected static void saveFileIfNeeded(IFile file, IProgressMonitor pm) throws CoreException {
	ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
	if (buffer != null && buffer.isDirty() &&  buffer.isStateValidated() && buffer.isSynchronized()) {
		pm.beginTask("", 2); //$NON-NLS-1$
		buffer.commit(new SubProgressMonitor(pm, 1), false);
		file.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(pm, 1));
	}
	pm.done();
}
 
Example 17
Source File: ProjectManifestFactory.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected void writeNewManifestFile(final IProject project, final IProgressMonitor monitor, final IFile projectManifest)
        throws CoreException {
    try (PrintWriter writer = new PrintWriter(projectManifest.getLocation().toFile())) {
        ManifestUtils.writeManifest(createManifestHeaders(project.getName()), writer);
        projectManifest.refreshLocal(IResource.DEPTH_ONE, monitor);
    } catch (final IOException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, CommonRepositoryPlugin.PLUGIN_ID, "Failed to create MANIFEST.MF", e));
    }
}
 
Example 18
Source File: ProjectConfigurationWorkingCopy.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Store the audit configurations to the persistent state storage.
 */
private void storeToPersistence(ProjectConfigurationWorkingCopy config)
        throws CheckstylePluginException {

  try {

    Document docu = writeProjectConfig(config);
    byte[] data = XMLUtil.toByteArray(docu);
    InputStream pipeIn = new ByteArrayInputStream(data);

    // create or overwrite the .checkstyle file
    IProject project = config.getProject();
    IFile file = project.getFile(ProjectConfigurationFactory.PROJECT_CONFIGURATION_FILE);
    if (!file.exists()) {
      file.create(pipeIn, true, null);
      file.refreshLocal(IResource.DEPTH_INFINITE, null);
    } else {

      if (file.isReadOnly()) {
        ResourceAttributes attrs = ResourceAttributes.fromFile(file.getFullPath().toFile());
        attrs.setReadOnly(true);
        file.setResourceAttributes(attrs);
      }

      file.setContents(pipeIn, true, true, null);
    }

    config.getLocalCheckConfigWorkingSet().store();
  } catch (Exception e) {
    CheckstylePluginException.rethrow(e,
            NLS.bind(Messages.errorWritingCheckConfigurations, e.getLocalizedMessage()));
  }
}
 
Example 19
Source File: DerivedSourceView.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected String computeInput(IWorkbenchPartSelection workbenchPartSelection) {
	openEditorAction.setInputFile(null);
	openEditorAction.setSelectedRegion(null);
	IEclipseTrace trace = traceInformation.getTraceToTarget(getEditorResource(workbenchPartSelection));
	if (trace != null) {
		if (workbenchPartSelection instanceof DerivedSourceSelection) {
			DerivedSourceSelection derivedSourceSelection = (DerivedSourceSelection) workbenchPartSelection;
			selectedSource = derivedSourceSelection.getStorage();
		} else {
			derivedSources = Sets.newHashSet();
			TextRegion localRegion = mapTextRegion(workbenchPartSelection);
			Iterable<IStorage> transform = Iterables.filter(transform(trace.getAllAssociatedLocations(localRegion),
					new Function<ILocationInEclipseResource, IStorage>() {
						@Override
						public IStorage apply(ILocationInEclipseResource input) {
							return input.getPlatformResource();
						}
					}), Predicates.notNull());
			addAll(derivedSources, transform);
			ILocationInEclipseResource bestAssociatedLocation = trace.getBestAssociatedLocation(localRegion);
			if (bestAssociatedLocation != null) {
				selectedSource = bestAssociatedLocation.getPlatformResource();
			} else if (!derivedSources.isEmpty()) {
				selectedSource = derivedSources.iterator().next();
			}
		}
	}
	IFile file = getSelectedFile();
	if (file != null) {
		try {
			file.refreshLocal(1, new NullProgressMonitor());
			if (file.exists()) {
				openEditorAction.setInputFile(file);
				return Files.readStreamIntoString(file.getContents());
			}
		} catch (CoreException e) {
			throw new WrappedRuntimeException(e);
		}
	}
	return null;
}
 
Example 20
Source File: DriverProcessor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void process ( final String phase, final IFolder baseDir, final IProgressMonitor monitor, final Map<String, String> properties ) throws Exception
{
    if ( phase != null && !"process".equals ( phase ) )
    {
        return;
    }

    final String name = makeName ();

    final IFolder output = baseDir.getFolder ( new Path ( name ) );
    output.create ( true, true, null );

    final IFile exporterFile = output.getFile ( "exporter.xml" ); //$NON-NLS-1$
    final IFile propFile = output.getFile ( "application.properties" ); //$NON-NLS-1$

    final DocumentRoot root = ExporterFactory.eINSTANCE.createDocumentRoot ();

    final ConfigurationType cfg = ExporterFactory.eINSTANCE.createConfigurationType ();
    root.setConfiguration ( cfg );

    final HiveType hive = ExporterFactory.eINSTANCE.createHiveType ();
    cfg.getHive ().add ( hive );
    hive.setRef ( getHiveId () );

    final HiveConfigurationType hiveCfg = ExporterFactory.eINSTANCE.createHiveConfigurationType ();
    hive.setConfiguration ( hiveCfg );

    addConfiguration ( hiveCfg );

    for ( final Endpoint ep : this.driver.getEndpoints () )
    {
        addEndpoint ( hive, ep );
    }

    // write exporter file
    new ModelWriter ( root ).store ( URI.createPlatformResourceURI ( exporterFile.getFullPath ().toString (), true ) );
    exporterFile.refreshLocal ( 1, monitor );

    // write application properties
    if ( propFile.exists () )
    {
        propFile.delete ( true, monitor );
    }
    final Properties p = new Properties ();
    fillProperties ( p );
    if ( !p.isEmpty () )
    {
        try (FileOutputStream fos = new FileOutputStream ( propFile.getRawLocation ().toOSString () ))
        {
            p.store ( fos, "Created by the Eclipse SCADA world generator" );
        }
        propFile.refreshLocal ( 1, monitor );
    }
}