Java Code Examples for org.eclipse.core.resources.IWorkspace#addResourceChangeListener()

The following examples show how to use org.eclipse.core.resources.IWorkspace#addResourceChangeListener() . 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: HierarchicalDataWorkspaceModelFactory.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the IHierarchicalDataModel. If one does not exists, this method
 * will create one and register a workspace listener.
 *
 * @return
 */
public static IHierarchicalDataModel getHierarchicalDataModel() {
	IHierarchicalDataModelGetFileModel getModel = new GetFileModelFactory();
	final HierarchicalDataModel model = new HierarchicalDataModel(getModel);

	IResourceChangeListener listener = new IResourceChangeListener() {

		@Override
		public void resourceChanged(IResourceChangeEvent event) {
			IResourceDelta delta = event.getDelta();
			if (delta != null) {
				try {
					delta.accept(new DeltaVisitor(model));
				} catch (CoreException e) {
					// our visitor does not throw CoreException
				}
			}
		}
	};
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(listener);

	return model;
}
 
Example 2
Source File: ModelRefreshTests.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
/** Record and return the set of files altered when running the provided block. */
private static Set<IFile> recordChangedFilesDuring(IWorkspace workspace, ICoreRunnable block)
    throws CoreException {
  Set<IFile> changed = new LinkedHashSet<>();
  IResourceChangeListener listener =
      event -> {
        try {
          changed.addAll(ResourceUtils.getAffectedFiles(event.getDelta()).values());
        } catch (CoreException ex) {
          throw new RuntimeException(ex);
        }
      };
  workspace.addResourceChangeListener(listener);
  try {
    block.run(new NullProgressMonitor());
  } finally {
    workspace.removeResourceChangeListener(listener);
  }
  return changed;
}
 
Example 3
Source File: DotGraphView.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
private void toggleResourceListener() {
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	ISelectionService service = getSite().getWorkbenchWindow()
			.getSelectionService();
	if (listenToDotContent) {
		IWorkbenchPart activeEditor = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage()
				.getActiveEditor();
		checkActiveEditorAndUpdateGraph(activeEditor);
		workspace.addResourceChangeListener(resourceChangeListener,
				IResourceChangeEvent.POST_BUILD
						| IResourceChangeEvent.POST_CHANGE);
		service.addSelectionListener(selectionChangeListener);
	} else {
		workspace.removeResourceChangeListener(resourceChangeListener);
		service.removeSelectionListener(selectionChangeListener);
	}
}
 
Example 4
Source File: ApplicationWorkbenchWindowAdvisor.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public void addWorkplaceListener(){
	   IWorkspace workspace = ResourcesPlugin.getWorkspace(); 
	   workspace.addResourceChangeListener(new IResourceChangeListener() {
		
		public void resourceChanged(IResourceChangeEvent event) {
			//刷新项目导航视图
			Display.getDefault().syncExec(new Runnable() {		
				public void run() {
					IViewPart findView = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
							.findView("net.heartsome.cat.common.ui.navigator.view");
					if(null == findView){
						return ;
					}
					IAction refreshActionHandler = findView.getViewSite().getActionBars()
							.getGlobalActionHandler(ActionFactory.REFRESH.getId());
					if(null == refreshActionHandler){
						return;
					}
					refreshActionHandler.run();
				}
			});
		}
	});
}
 
Example 5
Source File: DerbyServerUtils.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void startDerbyServer( IProject proj) throws CoreException {
	String args = CommonNames.START_DERBY_SERVER;
	String vmargs="";
	DerbyProperties dprop=new DerbyProperties(proj);
	//Starts the server as a Java app
	args+=" -h "+dprop.getHost()+ " -p "+dprop.getPort();
	
	//Set Derby System Home from the Derby Properties
	if((dprop.getSystemHome()!=null)&& !(dprop.getSystemHome().equals(""))){
		vmargs=CommonNames.D_SYSTEM_HOME+dprop.getSystemHome();
	}
	String procName="["+proj.getName()+"] - "+CommonNames.DERBY_SERVER+" "+CommonNames.START_DERBY_SERVER+" ("+dprop.getHost()+ ", "+dprop.getPort()+")";
	ILaunch launch = DerbyUtils.launch(proj, procName ,		
	CommonNames.DERBY_SERVER_CLASS, args, vmargs, CommonNames.START_DERBY_SERVER);
	IProcess ip=launch.getProcesses()[0];
	//set a name to be seen in the Console list
	ip.setAttribute(IProcess.ATTR_PROCESS_LABEL,procName);
	
	// saves the mapping between (server) process and project
	//servers.put(launch.getProcesses()[0], proj);
	servers.put(ip, proj);
	// register a listener to listen, when this process is finished
	DebugPlugin.getDefault().addDebugEventListener(listener);
	//Add resource listener
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	
	workspace.addResourceChangeListener(rlistener);
	setRunning(proj, Boolean.TRUE);
	Shell shell = new Shell();
	MessageDialog.openInformation(
		shell,
		CommonNames.PLUGIN_NAME,
		Messages.D_NS_ATTEMPT_STARTED+dprop.getPort()+".");

}
 
Example 6
Source File: ConfigEditor.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
ResourceChangeListener(ConfigEditor editorPart, Composite container) {
	this.editorPart = editorPart;
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(this);
	container.addDisposeListener(new DisposeListener() {
		public void widgetDisposed(DisposeEvent e) {
			workspace.removeResourceChangeListener(ResourceChangeListener.this);
		}
	});
}
 
Example 7
Source File: SarosSessionTest.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private static IWorkspace createWorkspaceMock(final List<Object> workspaceListeners) {

    final IWorkspace workspace = createMock(IWorkspace.class);

    workspace.addResourceChangeListener(isA(IResourceChangeListener.class), anyInt());

    expectLastCall()
        .andStubAnswer(
            new IAnswer<Object>() {

              @Override
              public Object answer() throws Throwable {
                workspaceListeners.add(getCurrentArguments()[0]);
                return null;
              }
            });

    workspace.removeResourceChangeListener(isA(IResourceChangeListener.class));

    expectLastCall()
        .andStubAnswer(
            new IAnswer<Object>() {

              @Override
              public Object answer() throws Throwable {
                workspaceListeners.remove(getCurrentArguments()[0]);
                return null;
              }
            });

    replay(workspace);

    PowerMock.mockStaticPartial(ResourcesPlugin.class, "getWorkspace");
    ResourcesPlugin.getWorkspace();
    expectLastCall().andReturn(workspace).anyTimes();
    PowerMock.replay(ResourcesPlugin.class);

    return workspace;
  }
 
Example 8
Source File: ProjectActionGroup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new <code>ProjectActionGroup</code>. The group requires
 * that the selection provided by the given selection provider is of type
 * {@link IStructuredSelection}.
 *
 * @param site the site that will own the action group.
 * @param selectionProvider the selection provider used instead of the
 *  page selection provider.
 *
 * @since 3.4
 */
public ProjectActionGroup(IWorkbenchSite site, ISelectionProvider selectionProvider) {
	fSelectionProvider= selectionProvider;
	ISelection selection= selectionProvider.getSelection();

	fCloseAction= new CloseResourceAction(site);
	fCloseAction.setActionDefinitionId(IWorkbenchCommandConstants.PROJECT_CLOSE_PROJECT);

	fCloseUnrelatedAction= new CloseUnrelatedProjectsAction(site);
	fCloseUnrelatedAction.setActionDefinitionId(IWorkbenchCommandConstants.PROJECT_CLOSE_UNRELATED_PROJECTS);

	fOpenAction= new OpenProjectAction(site);
	fOpenAction.setActionDefinitionId(IWorkbenchCommandConstants.PROJECT_OPEN_PROJECT);
	if (selection instanceof IStructuredSelection) {
		IStructuredSelection s= (IStructuredSelection)selection;
		fOpenAction.selectionChanged(s);
		fCloseAction.selectionChanged(s);
		fCloseUnrelatedAction.selectionChanged(s);
	}

	fSelectionChangedListener= new ISelectionChangedListener() {
		public void selectionChanged(SelectionChangedEvent event) {
			ISelection s= event.getSelection();
			if (s instanceof IStructuredSelection) {
				performSelectionChanged((IStructuredSelection) s);
			}
		}
	};
	selectionProvider.addSelectionChangedListener(fSelectionChangedListener);

	IWorkspace workspace= ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(fOpenAction);
	workspace.addResourceChangeListener(fCloseAction);
	workspace.addResourceChangeListener(fCloseUnrelatedAction);
}
 
Example 9
Source File: BibtexEntryView.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The constructor.
 */
public BibtexEntryView() {
	super();
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(markerChangeListener);
	workspace.addResourceChangeListener(projectChangeListener);
	initializeEditingDomain();
}
 
Example 10
Source File: MarkerManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private MarkerManager()
{
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(new IResourceChangeListener()
	{
		public void resourceChanged(IResourceChangeEvent event)
		{
			handleResourceChanged();
		}
	}, IResourceChangeEvent.PRE_BUILD);
}
 
Example 11
Source File: DerbyServerUtils.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void startDerbyServer( IProject proj) throws CoreException {
	String args = CommonNames.START_DERBY_SERVER;
	String vmargs="";
	DerbyProperties dprop=new DerbyProperties(proj);
	//Starts the server as a Java app
	args+=" -h "+dprop.getHost()+ " -p "+dprop.getPort();
	
	//Set Derby System Home from the Derby Properties
	if((dprop.getSystemHome()!=null)&& !(dprop.getSystemHome().equals(""))){
		vmargs=CommonNames.D_SYSTEM_HOME+dprop.getSystemHome();
	}
	String procName="["+proj.getName()+"] - "+CommonNames.DERBY_SERVER+" "+CommonNames.START_DERBY_SERVER+" ("+dprop.getHost()+ ", "+dprop.getPort()+")";
	ILaunch launch = DerbyUtils.launch(proj, procName ,		
	CommonNames.DERBY_SERVER_CLASS, args, vmargs, CommonNames.START_DERBY_SERVER);
	IProcess ip=launch.getProcesses()[0];
	//set a name to be seen in the Console list
	ip.setAttribute(IProcess.ATTR_PROCESS_LABEL,procName);
	
	// saves the mapping between (server) process and project
	//servers.put(launch.getProcesses()[0], proj);
	servers.put(ip, proj);
	// register a listener to listen, when this process is finished
	DebugPlugin.getDefault().addDebugEventListener(listener);
	//Add resource listener
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	
	workspace.addResourceChangeListener(rlistener);
	setRunning(proj, Boolean.TRUE);
	Shell shell = new Shell();
	MessageDialog.openInformation(
		shell,
		CommonNames.PLUGIN_NAME,
		Messages.D_NS_ATTEMPT_STARTED+dprop.getPort()+".");

}
 
Example 12
Source File: ToolboxExplorerResourceListener.java    From tlaplus with MIT License 5 votes vote down vote up
public void postWorkbenchWindowOpen() {
	// We might have missed events during Toolbox startup when there was
	// a workspace but no UI yet.
	resourceChanged(null);
	
	// update CNF viewers
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(this);
}
 
Example 13
Source File: ProblemViewResourceListener.java    From tlaplus with MIT License 5 votes vote down vote up
public void postWorkbenchWindowOpen() {
	// Check if there have been any markers set already
	showOrHideProblemView();
	
	// ...and listen for new markers
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_BUILD);
}
 
Example 14
Source File: XdsResourceChangeListener.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Installs the {@link IWorkspace#addResourceChangeListener(IResourceChangeListener)}
 */
public XdsResourceChangeListener() {
	try {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		if (workspace != null) {
			workspace.addResourceChangeListener(this);
		}
	} catch (java.lang.IllegalStateException e) {
	}
}
 
Example 15
Source File: ResourceCache.java    From depan with Apache License 2.0 4 votes vote down vote up
protected void attachWorkspace(IWorkspace workspace) {
  workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
}
 
Example 16
Source File: SVNProviderPlugin.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
public void start(BundleContext ctxt) throws Exception {
	super.start(ctxt);
	
	messageHandlers = getMessageHandlers();
	
	// register all the adapter factories
	adapterFactories = new SVNAdapterFactories();
	adapterFactories.startup(null);

       statusCacheManager = new StatusCacheManager();
       getPluginPreferences().addPropertyChangeListener(statusCacheManager);
       
	// Initialize SVN change listeners. Note tha the report type is important.
	IWorkspace workspace = ResourcesPlugin.getWorkspace();

	// this listener will listen to additions of svn meta directories
	teamPrivateListener = new TeamPrivateListener();

	// this listener will listen to modifications to files
	fileModificationManager = new FileModificationManager();
	getPluginPreferences().addPropertyChangeListener(fileModificationManager);

	// this listener will listen to modification to metafiles (files in .svn
	// subdir)
	metaFileSyncListener = new SyncFileChangeListener();

	revertManager = new RevertResourceManager();
	
	workspace.addResourceChangeListener(teamPrivateListener,
			IResourceChangeEvent.POST_CHANGE);
	workspace.addResourceChangeListener(statusCacheManager,
			IResourceChangeEvent.PRE_BUILD);
	workspace.addResourceChangeListener(metaFileSyncListener,
			IResourceChangeEvent.PRE_BUILD);
	workspace.addResourceChangeListener(fileModificationManager,
			IResourceChangeEvent.POST_CHANGE);
	workspace.addResourceChangeListener(revertManager, IResourceChangeEvent.PRE_BUILD);
	
	teamPrivateListener.registerSaveParticipant();
	fileModificationManager.registerSaveParticipant();

	// Must load the change set manager on startup since it listens to deltas
	getChangeSetManager();
	
}
 
Example 17
Source File: WorkspaceSpecManager.java    From tlaplus with MIT License 4 votes vote down vote up
/**
 * Constructor
 */
public WorkspaceSpecManager(final IProgressMonitor monitor)
{
    // initialize the spec life cycle manager
    lifecycleManager = new SpecLifecycleManager();

    final IWorkspace ws = ResourcesPlugin.getWorkspace();

    final String specLoadedName = PreferenceStoreHelper.getInstancePreferenceStore().getString(
            IPreferenceConstants.I_SPEC_LOADED);

    final IProject[] projects = ws.getRoot().getProjects();
    try
    {

        for (int i = 0; i < projects.length; i++)
        {
            // changed from projects[i].isAccessible()
            final IProject project = projects[i];
if (project.isOpen())
            {
                if (project.hasNature(TLANature.ID))
                {
		// Refresh the project in case the actual on-disk
		// representation and the cached Eclipse representation
		// have diverged. This can happen when e.g. another
		// Toolbox opens the project or the files get manually
		// edited. Without calling refresh, code down below 
                	// might throw exceptions due to out-of-sync problems.  
                	project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                    
                	final Spec spec = new Spec(project);
                    // Added by LL on 12 Apr 2011
                    // If spec.rootFile = null, then this is a bad spec. So
                    // we should report it and not perform addSpec(spec).  It
                    // would be nice if we could report it to the user, but
                    // it seems to be impossible to popup a window at this point
                    // in the code.
                    if (spec.getRootFile() == null)
                    {
                        Activator.getDefault().logError("The bad spec is: `" + project.getName() + "'", null);
                    } else
                    {
                        // This to threw a null pointer exception for Tom, probably causing the abortion
                        // of the Toolbox start. But it started on the next attempt.  Should we catch the
                        // and perhaps report the bad spec?
                        addSpec(spec);
                    }
                    
                    // load the spec if found
                    if (spec.getName().equals(specLoadedName))
                    {
                        this.setSpecLoaded(spec);
                    }
                }
            } else
            {
                // DELETE closed projects
                project.delete(IResource.FORCE | IResource.ALWAYS_DELETE_PROJECT_CONTENT, monitor);
            }
        }

        if (specLoadedName != null && !specLoadedName.equals("") && this.loadedSpec == null)
        {
            // there was a spec loaded but it was not found
            // explicit un-set it
            setSpecLoaded(null);
        }

    } catch (CoreException e)
    {
        Activator.getDefault().logError("Error initializing specification workspace", e);
    }

    ws.addResourceChangeListener(this);
    
    Platform.getAdapterManager().registerAdapters(this, IProject.class);
}
 
Example 18
Source File: UIResourceChangeRegistryTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Inject
@Override
public void init(final IWorkspace workspace) {
  workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE);
}
 
Example 19
Source File: WidgetModel.java    From thym with Eclipse Public License 1.0 4 votes vote down vote up
ResourceChangeListener() {
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(this, IResourceChangeEvent.PRE_DELETE);
}
 
Example 20
Source File: CodewindFilewatcherdConnection.java    From codewind-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public CodewindFilewatcherdConnection(String baseHttpUrl, File pathToCwctl, ICodewindProjectTranslator translator,
		IAuthTokenProvider authTokenProvider /* nullable */) {

	if (pathToCwctl == null) {
		throw new RuntimeException("A valid path to the Codewind CLI is required: " + pathToCwctl);
	}

	if (!pathToCwctl.exists() || !pathToCwctl.canExecute()) {
		throw new RuntimeException(this.getClass().getSimpleName() + " was passed an invalid installer path: "
				+ pathToCwctl.getPath());
	}

	this.clientUuid = UUID.randomUUID().toString();

	String url = baseHttpUrl;
	if (!url.startsWith("http://") && !url.startsWith("https://")) {
		throw new IllegalArgumentException("Argument should begin with http:// or https://.");
	}

	// Log to the workspace .metadata directory, rather than to the console.
	File metadataDirectory = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getPath(),
			".metadata");
	FWLogger logger = FWLogger.getInstance();
	logger.setOutputLogsToScreen(false);
	logger.setRollingFileLoggerOutputDir(metadataDirectory);

	this.translator = translator;

	listener = new CodewindResourceChangeListener(this);

	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.addResourceChangeListener(listener);

	// We use the native Eclipse-resource-listener-based watch service for projects
	// inside the workspace, and the Java-NIO-JVM-based watch service for folders
	// outside the workspace (eg the standalone Codewind settings directory).
	this.platformWatchService = new EclipseResourceWatchService();
	this.fileWatcher = new Filewatcher(url, clientUuid, platformWatchService, new JavaNioWatchService(),
			pathToCwctl.getPath(), authTokenProvider);

	this.baseHttpUrl = url;

}