org.eclipse.core.resources.WorkspaceJob Java Examples

The following examples show how to use org.eclipse.core.resources.WorkspaceJob. 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: UpdateCloudToolsEclipseProjectHandler.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
  IProject project = ProjectFromSelectionHelper.getFirstProject(event);
  if (!CloudToolsEclipseProjectUpdater.hasOldContainers(project)) {
    throw new ExecutionException(Messages.getString("project.appears.up.to.date")); //$NON-NLS-1$
  }
  String jobName = Messages.getString("updating.project", project.getName()); //$NON-NLS-1$
  Job updateJob = new WorkspaceJob(jobName) {
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
      return CloudToolsEclipseProjectUpdater.updateProject(project, SubMonitor.convert(monitor));
    }
  };
  updateJob.setRule(project.getWorkspace().getRoot());
  updateJob.setUser(true);
  updateJob.schedule();
  return null;
}
 
Example #2
Source File: CloudToolsEclipseProjectNotifier.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Override
public void earlyStartup() {
  workbench = PlatformUI.getWorkbench();
  workspace = ResourcesPlugin.getWorkspace();

  Job projectUpdater = new WorkspaceJob(Messages.getString("updating.projects.jobname")) { //$NON-NLS-1$
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
      SubMonitor progress = SubMonitor.convert(monitor, 40);
      progress.subTask(Messages.getString("searching.for.projects")); //$NON-NLS-1$
      Collection<IProject> projects = findCandidates(progress.newChild(10));
      if (projects.isEmpty()) {
        return Status.OK_STATUS;
      }
      projects = promptUser(projects, progress.newChild(5));
      if (projects.isEmpty()) {
        return Status.OK_STATUS;
      }
      progress.subTask(Messages.getString("updating.projects")); //$NON-NLS-1$
      return upgradeProjects(projects, progress.newChild(25));
    }
  };
  projectUpdater.setRule(workspace.getRoot());
  projectUpdater.setUser(true);
  projectUpdater.schedule(500);
}
 
Example #3
Source File: Activator.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private void visit(IJavaElementDelta delta) {
  switch (delta.getElement().getElementType()) {
    case IJavaElement.JAVA_PROJECT:
      if ((delta.getFlags() & IJavaElementDelta.F_CLASSPATH_CHANGED) != 0) {
        final IJavaProject javaProject = (IJavaProject) delta.getElement();
        Job updateContainerStateJob = new WorkspaceJob("Updating Google Cloud libraries") {
          @Override
          public IStatus runInWorkspace(IProgressMonitor monitor) {
            BuildPath.checkLibraryList(javaProject, null);
            return Status.OK_STATUS;
          }
        };
        IWorkspace workspace = javaProject.getProject().getWorkspace();
        ISchedulingRule buildRule = workspace.getRuleFactory().buildRule();
        updateContainerStateJob.setRule(buildRule);
        updateContainerStateJob.setSystem(true);
        updateContainerStateJob.schedule();
      }
      break;
    case IJavaElement.JAVA_MODEL:
      visitChildren(delta);
      break;
    default:
      break;
  }
}
 
Example #4
Source File: DefinitionContributionItem.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected void run ( final String name ) throws URISyntaxException
{
    final WorkspaceJob job = new WorkspaceJob ( String.format ( "Run recipe: %s", name ) ) {

        @Override
        public IStatus runInWorkspace ( final IProgressMonitor monitor ) throws CoreException
        {
            try
            {
                RecipeHelper.processFile ( DefinitionContributionItem.this.parent, DefinitionContributionItem.this.definition, getProfile (), monitor );
            }
            catch ( final Exception e )
            {
                logger.warn ( "Failed to process", e );
                return StatusHelper.convertStatus ( Activator.PLUGIN_ID, e );
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser ( true );
    job.setSystem ( false );
    job.schedule ();
}
 
Example #5
Source File: AbstractFSSynchronizationTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void testCleanUpDerivedResourcesWithDeleteDerived(IContainer output) {
	File outputDirectory = output.getLocation().toFile();
	final int expectedSize;
	if (outputDirectory.exists()) {
		expectedSize = outputDirectory.list().length;
	} else {
		expectedSize = 0;
	}
	createFile(project.getFile(("src/Foo" + F_EXT)).getFullPath(), "object Foo");
	build();
	Assert.assertNotEquals(expectedSize, outputDirectory.list().length);
	disableAutobuild(() -> {
		IFile file = output.getFile(new Path("Foo.txt"));
		new WorkspaceJob("file.delete") {
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
				Assert.assertTrue(file.getLocation().toFile().delete());
				Assert.assertFalse(isSynchronized(file));
				return Status.OK_STATUS;
			}
		}.run(monitor());
		cleanBuild();
		Assert.assertEquals(expectedSize, outputDirectory.list().length);
	});
}
 
Example #6
Source File: BuilderUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Schedules a full rebuild on a project.
 * 
 * @param project the project to rebuild
 */
public static void scheduleRebuild(final IProject project) {
  WorkspaceJob buildJob = new WorkspaceJob("Building " + project.getName()) {
    @Override
    public boolean belongsTo(Object family) {
      return ResourcesPlugin.FAMILY_MANUAL_BUILD.equals(family);
    }

    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor)
        throws CoreException {
      project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
      return Status.OK_STATUS;
    }
  };

  buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().buildRule());
  buildJob.setUser(true);
  buildJob.schedule();
}
 
Example #7
Source File: ConvertToHybridProjectHandler.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    
    IProject project = getProject(event);
    if(project != null ){
        final IProject theProject = project;//to pass to Job
        WorkspaceJob job = new WorkspaceJob(NLS.bind("Convert {0} to Hybrid Mobile project", project.getName())) {
            
            @Override
            public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
                HybridProjectCreator creator = new HybridProjectCreator();
                creator.convertProject(theProject, new NullProgressMonitor());
                return Status.OK_STATUS;
            }
        };
        job.schedule();
    }
    return null;
}
 
Example #8
Source File: WebAppProjectCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private void jobSetupFacets(final IProject project) {
  // Facet setup is done in a workspace job since this can be long running,
  // hence shouldn't be from the UI thread.
  WorkspaceJob setupFacetsJob = new WorkspaceJob("Setting up facets") {
    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor) {
      try {
        // Create faceted project
        IFacetedProject facetedProject = ProjectFacetsManager.create(project, true, monitor);
        // Add Java facet by default
        IProjectFacet javaFacet = ProjectFacetsManager.getProjectFacet(FACET_JST_JAVA);
        facetedProject.installProjectFacet(javaFacet.getDefaultVersion(), null, monitor);
        return Status.OK_STATUS;
      } catch (CoreException e) {
        // Log and continue
        GdtPlugin.getLogger().logError(e);
        return new Status(IStatus.ERROR, GdtPlugin.PLUGIN_ID, e.toString(), e);
      }
    }
  };
  setupFacetsJob.schedule();
}
 
Example #9
Source File: AddSvnAndRefreshStartUp.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void earlyStartup() {
	Job job = new WorkspaceJob("refresh svn view")
	{
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor)
				throws CoreException {
			monitor.beginTask("refresh", 4);
			initData();
			monitor.worked(1);
			saveFeatureInfo(ip, userName, cookie);
			monitor.worked(1);
			addSvnToView(ip, userName, cookie);
			monitor.worked(1);
			monitor.done();
			return Status.OK_STATUS;
		}
	};
	job.setPriority(Job.SHORT);
	job.setSystem(true);
	job.schedule(200L);
}
 
Example #10
Source File: SyncSVNPathActionDelegate.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run(IAction action) {
	Job job = new WorkspaceJob("refresh svn view")
	{
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor)
				throws CoreException {
			monitor.beginTask("refresh", 2);
			initData();
			monitor.worked(1);
			addSvnToView();
			monitor.worked(2);
			monitor.done();
			return Status.OK_STATUS;
		}
	};
	job.setPriority(Job.SHORT);
	job.setSystem(true);
	job.schedule(200L);
}
 
Example #11
Source File: SyncApplicationDialog.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
public void run(final CountDownLatch threadSignal) {
	for(Control c :composite.getChildren()) {
		if(c instanceof SyncApplicationComposite) {
			final SyncApplicationComposite sac = (SyncApplicationComposite)c;
			Job job = new WorkspaceJob("")
			{
				@Override
				public IStatus runInWorkspace(IProgressMonitor monitor)
						throws CoreException {
					try {
						sac.run(threadSignal);
					} catch (Exception e) {
						return Status.CANCEL_STATUS;
					}
					return Status.OK_STATUS;
				}
			};
			job.schedule();
		}
	}
	
}
 
Example #12
Source File: WorkspaceModelsManager.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static void linkSampleModelsToWorkspace() {

		final WorkspaceJob job = new WorkspaceJob("Updating the Built-in Models Library") {

			@Override
			public IStatus runInWorkspace(final IProgressMonitor monitor) {
				// DEBUG.OUT("Asynchronous link of models library...");
				GAMA.getGui().refreshNavigator();
				return GamaBundleLoader.ERRORED ? Status.CANCEL_STATUS : Status.OK_STATUS;
			}

		};
		job.setUser(true);
		job.schedule();

	}
 
Example #13
Source File: RefreshAction.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
	if (super.getSelectedResources().isEmpty()) {
		final WorkspaceJob job = new WorkspaceJob("Refreshing the GAMA Workspace") {

			@Override
			public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
				final IRefreshHandler refresh = WorkbenchHelper.getService(IRefreshHandler.class);
				if (refresh != null) {
					refresh.completeRefresh(resources);
				}
				return OK_STATUS;
			};
		};
		job.setUser(true);
		job.schedule();
	} else {
		super.run();
	}
}
 
Example #14
Source File: ModelEditor.java    From tlaplus with MIT License 5 votes vote down vote up
/**
   * Invoke this to save the model via a workspace job.
   */
  public void saveModel() {
  	final Job job = new WorkspaceJob("Saving updated model...") {
	public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
		getModel().save(monitor);
		return Status.OK_STATUS;
	}
};
job.setRule(ResourcesPlugin.getWorkspace().getRoot());
job.setUser(true);
job.schedule();
  }
 
Example #15
Source File: RepositoryNotifier.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public void postSave(final IRepositoryFileStore fileStore) {
    if (fileStore != null) {
        new WorkspaceJob("Post save refresh") {
            
            @Override
            public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
                fileStore.getParentStore().refresh();
                AbstractFileStore.refreshExplorerView();
                return Status.OK_STATUS;
            }
        }.schedule();
        repository.handleFileStoreEvent(new FileStoreChangeEvent(EventType.POST_SAVE, fileStore));
    }
}
 
Example #16
Source File: BuilderUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Schedules a full rebuild on all projects in the workspace that have any of
 * the specified natures.
 */
public static void scheduleRebuildAll(final String... natureIds) {
  final IWorkspace workspace = ResourcesPlugin.getWorkspace();
  WorkspaceJob buildJob = new WorkspaceJob("Building workspace projects") {
    @Override
    public boolean belongsTo(Object family) {
      return ResourcesPlugin.FAMILY_MANUAL_BUILD.equals(family);
    }

    @Override
    public IStatus runInWorkspace(IProgressMonitor monitor)
        throws CoreException {
      for (IProject project : workspace.getRoot().getProjects()) {
        for (String natureId : natureIds) {
          if (NatureUtils.hasNature(project, natureId)) {
            project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
            break;
          }
        }
      }

      return Status.OK_STATUS;
    }
  };

  buildJob.setRule(workspace.getRuleFactory().buildRule());
  buildJob.setUser(true);
  buildJob.schedule();
}
 
Example #17
Source File: RunMobileDialog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
protected void buttonPressed(int buttonId) {
	if (buttonId == 0) {
		StructuredSelection ss = (StructuredSelection)this.list.getSelection();
		IProject project = (IProject)ss.getFirstElement();
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		if(validate(getID(project),project)){
			
		
		final SyncApplicationDialog sad = new SyncApplicationDialog(shell, aMobiles,iMobiles, project);
		final CountDownLatch threadSignal = new CountDownLatch(aMobiles.size()+iMobiles.size());
		sad.open();
		sad.run(threadSignal);
		Job job = new WorkspaceJob("")
		{
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor)
					throws CoreException {
				try {
					threadSignal.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				sad.finish();
				return Status.OK_STATUS;
			}
		};
		job.schedule();
		close();
	}else if (buttonId == 1) {
		close();
	}else{
		close();
	}
	} else{
		close();
	}
}
 
Example #18
Source File: NewMavenSarlProjectWizard.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Override
public boolean performFinish() {
	if (!super.performFinish()) {
		return false;
	}
	final Job job = new WorkspaceJob("Force the SARL nature") { //$NON-NLS-1$
		@SuppressWarnings({ "deprecation", "synthetic-access" })
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			final Model model = NewMavenSarlProjectWizard.this.lastModel;
			if (model != null) {
				final Plugin plugin = Iterables.find(model.getBuild().getPlugins(), it -> PLUGIN_ARTIFACT_ID.equals(it.getArtifactId()));
				plugin.setExtensions(true);
				final IWorkspace workspace = ResourcesPlugin.getWorkspace();
				final IWorkspaceRoot root = workspace.getRoot();
				final IProject project = NewMavenSarlProjectWizard.this.importConfiguration.getProject(root, model);
				// Fixing the "extensions" within the pom file
				final IFile pomFile = project.getFile(IMavenConstants.POM_FILE_NAME);
				pomFile.delete(true, new NullProgressMonitor());
				MavenPlugin.getMavenModelManager().createMavenModel(pomFile, model);
				// Update the project
				final SubMonitor submon = SubMonitor.convert(monitor);
				MavenPlugin.getProjectConfigurationManager().updateProjectConfiguration(project, submon.newChild(1));
				project.refreshLocal(IResource.DEPTH_ONE, submon.newChild(1));
			}
			return Status.OK_STATUS;
		}
	};
	job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
	job.schedule();
	return true;
}
 
Example #19
Source File: BuildICEHandler.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

	// Get the Launch Manager
	ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();

	if (manager != null) {
		IProject aggregatorProject = ResourcesPlugin.getWorkspace().getRoot().getProject("org.eclipse.ice.aggregator");

		if (aggregatorProject != null) {
			// Get the Launch Configurations files
			IFile mvnInstall = aggregatorProject.getFile("Build ICE.launch");

			// Get the Launch Configuration from those files
			ILaunchConfiguration installConfig = manager.getLaunchConfiguration(mvnInstall);

			// Create and launch the Job. 
			Job job = new WorkspaceJob("Building ICE") {

				@Override
				public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
					installConfig.launch(ILaunchManager.RUN_MODE, monitor);
					return Status.OK_STATUS;
				}

			};
			job.schedule();
		} else {
			logger.info("Info: Could not build ICE because it hasn't been cloned yet. Please clone ICE to the current workspace.");
		}
	} else {
		logger.error("Error in launching the ICE Build - Could not get the Launch Manager.");
	}
	return null;
}
 
Example #20
Source File: GitCloneHandler.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This private method is used to import existing projects into the project
 * explorer.
 * 
 * @param repository
 * @param sets
 */
protected void importProjects(final Repository repository, final IWorkingSet[] sets) {
	String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
	Job importJob = new WorkspaceJob(MessageFormat.format(UIText.GitCloneWizard_jobImportProjects, repoName)) {

		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) {
			List<File> files = new ArrayList<File>();
			ProjectUtil.findProjectFiles(files, repository.getWorkTree(), true, monitor);
			if (files.isEmpty()) {
				return Status.OK_STATUS;
			}

			Set<ProjectRecord> projectRecords = new LinkedHashSet<ProjectRecord>();
			for (File file : files) {
				projectRecords.add(new ProjectRecord(file));
			}
			try {
				ProjectUtils.createProjects(projectRecords, sets, monitor);
			} catch (InvocationTargetException | InterruptedException e) {
				Activator.logError(e.getLocalizedMessage(), e);
			}

			return Status.OK_STATUS;
		}
	};
	importJob.schedule();
}
 
Example #21
Source File: WorkspaceAction.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Run the action in the background rather than with the
 * progress dialog.
 * @param rule The rule to apply to the background job or
 * <code>null</code> if there isn't one.
 * @param jobFamilies the families the job should belong
 * to or <code>null</code> if none.
 *
 * @since 3.1
 */
public void runInBackground(ISchedulingRule rule, final Object[] jobFamilies) {
    //obtain a copy of the selected resources before the job is forked
    final List<IResource> resources = new ArrayList<IResource>(getActionResources());
    Job job = new WorkspaceJob(removeMnemonics(getText())) {

        /* (non-Javadoc)
         * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
         */
        @Override
        public boolean belongsTo(Object family) {
            if (jobFamilies == null || family == null) {
                return false;
            }
            for (int i = 0; i < jobFamilies.length; i++) {
                if (family.equals(jobFamilies[i])) {
                    return true;
                }
            }
            return false;
        }

        /* (non-Javadoc)
         * @see org.eclipse.core.resources.WorkspaceJob#runInWorkspace(org.eclipse.core.runtime.IProgressMonitor)
         */
        @Override
        public IStatus runInWorkspace(IProgressMonitor monitor) {
            return WorkspaceAction.this.execute(resources, monitor);
        }
    };
    if (rule != null) {
        job.setRule(rule);
    }
    job.setUser(true);
    job.schedule();
}
 
Example #22
Source File: TraceExplorerComposite.java    From tlaplus with MIT License 5 votes vote down vote up
private void saveModel() {
      view.getModel().setTraceExplorerExpression(FormHelper.getSerializedInput(tableViewer));
      
  	final Job job = new WorkspaceJob("Saving updated model...") {
	public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
		view.getModel().save(monitor);
		return Status.OK_STATUS;
	}
};
job.setRule(ResourcesPlugin.getWorkspace().getRoot());
job.setUser(true);
job.schedule();
  }
 
Example #23
Source File: ConvertToJava8RuntimeHandler.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
  List<IProject> projects = ProjectFromSelectionHelper.getProjects(event);
  Preconditions.checkArgument(!projects.isEmpty());
  Job updateJob = new WorkspaceJob(Messages.getString("reconfiguringToJava8")) { // $NON-NLS-1$
        @Override
        public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
          SubMonitor progress = SubMonitor.convert(monitor, projects.size());
          for (IProject project : projects) {
            progress.subTask(
                Messages.getString("reconfiguringProject", project.getName())); // $NON-NLS-1$
            IFile appEngineWebXml =
                AppEngineConfigurationUtil.findConfigurationFile(project, APPENGINE_DESCRIPTOR);
            if (appEngineWebXml != null) {
              // add the <runtime> and the rest should be handled for us
              AppEngineDescriptorTransform.addJava8Runtime(appEngineWebXml);
            }
            progress.worked(1);
          }
          return Status.OK_STATUS;
        }

        @Override
        public boolean belongsTo(Object family) {
          return super.belongsTo(family)
              || J2EEElementChangedListener.PROJECT_COMPONENT_UPDATE_JOB_FAMILY.equals(family);
        }
      };
  updateJob.setRule(getWorkspaceRoot());
  updateJob.setUser(true);
  updateJob.schedule();
  return null;
}
 
Example #24
Source File: AbstractFSSynchronizationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void testCleanUpDerivedResourcesWithUpdateDerived(IContainer output) {
	File outputDirectory = output.getLocation().toFile();
	final int expectedSize;
	if (outputDirectory.exists()) {
		expectedSize = outputDirectory.list().length;
	} else {
		expectedSize = 0;
	}
	createFile(project.getFile(("src/Foo" + F_EXT)).getFullPath(), "object Foo");
	build();
	Assert.assertNotEquals(expectedSize, outputDirectory.list().length);
	disableAutobuild(() -> {
		try {
			IFile file = output.getFile(new Path("Foo.txt"));
			file.setLocalTimeStamp(1L);
			new WorkspaceJob("file.setContent") {
				@Override
				public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
					setContent(file.getLocation().toFile(), "Lalala");
					Assert.assertFalse(isSynchronized(file));
					return Status.OK_STATUS;
				}
			}.run(monitor());
			cleanBuild();
			Assert.assertEquals(expectedSize, outputDirectory.list().length);
		} catch (CoreException e) {
			throw Exceptions.sneakyThrow(e);
		}
	});
}
 
Example #25
Source File: AbstractFSSynchronizationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void testDeleteUpdatedDerivedResource(IContainer output) {
	try {
		File outputDirectory = output.getLocation().toFile();
		final int expectedSize;
		if (outputDirectory.exists()) {
			expectedSize = outputDirectory.list().length;
		} else {
			expectedSize = 0;
		}
		IFile sourceFile = createFile(project.getFile(("src/Foo" + F_EXT)).getFullPath(), "object Foo");
		build();
		Assert.assertNotEquals(expectedSize, outputDirectory.list().length);
		IFile file = output.getFile(new Path("Foo.txt"));
		file.setLocalTimeStamp(1L);
		new WorkspaceJob("file.setContent") {
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
				setContent(file.getLocation().toFile(), "Lalala");
				Assert.assertFalse(isSynchronized(file));
				return Status.OK_STATUS;
			}
		}.run(monitor());
		sourceFile.delete(false, monitor());
		build();
		Assert.assertEquals(expectedSize, outputDirectory.list().length);
	} catch (CoreException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example #26
Source File: AbstractFSSynchronizationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void testDeleteDeletedDerivedResource(IContainer output) {
	try {
		File outputDirectory = output.getLocation().toFile();
		int expectedSize = 0;
		if (outputDirectory.exists()) {
			expectedSize = outputDirectory.list().length;
		}
		IFile sourceFile = createFile(project.getFile(("src/Foo" + F_EXT)).getFullPath(), "object Foo");
		build();
		Assert.assertNotEquals(expectedSize, outputDirectory.list().length);
		IFile file = output.getFile(new Path("Foo.txt"));
		file.refreshLocal(0, null);
		Assert.assertTrue(isSynchronized(file));
		new WorkspaceJob("file.delete") {
			@Override
			public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
				Assert.assertTrue(file.getLocation().toFile().delete());
				Assert.assertFalse(isSynchronized(file));
				return Status.OK_STATUS;
			}
		}.run(monitor());
		sourceFile.delete(false, monitor());
		build();
		Assert.assertEquals(expectedSize, outputDirectory.list().length);
	} catch (CoreException e) {
		throw Exceptions.sneakyThrow(e);
	}
}
 
Example #27
Source File: ListenerRegistrar.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void initialize() {
	workspace.addResourceChangeListener(listener);
	
	// If there are no open projects in a workspace after a restart, a newly opened Xtext project will
	// trigger the infrastructure's initialization procedure. Since the listeners are than registered
	// after the fact, the project-open event is already done. Thus no build is triggered for the newly
	// opened project and the index state is corrupt.
	// thus we trigger a recovery build here
	class RecoveryBuildTrigger extends WorkspaceJob {

		public RecoveryBuildTrigger() {
			super("Schedule Xtext recovery build on start-up");
		}

		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
			if (monitor.isCanceled()) {
				return Status.CANCEL_STATUS;
			}
			if (builderState.isEmpty()) {
				buildManager.scheduleBuildIfNecessary(Arrays.asList(workspace.getRoot().getProjects()), IBuildFlag.RECOVERY_BUILD);
			}
			return Status.OK_STATUS;
		}
	}
	RecoveryBuildTrigger recoveryBuildTrigger = new RecoveryBuildTrigger();
	recoveryBuildTrigger.schedule();
}
 
Example #28
Source File: ProjectsManager.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Job updateProject(IProject project, boolean force) {
	if (project == null || (!ProjectUtils.isMavenProject(project) && !ProjectUtils.isGradleProject(project))) {
		return null;
	}
	JavaLanguageServerPlugin.sendStatus(ServiceStatus.Message, "Updating " + project.getName() + " configuration");
	WorkspaceJob job = new WorkspaceJob("Update project " + project.getName()) {

		@Override
		public boolean belongsTo(Object family) {
			return IConstants.UPDATE_PROJECT_FAMILY.equals(family) || (IConstants.JOBS_FAMILY + "." + project.getName()).equals(family) || IConstants.JOBS_FAMILY.equals(family);
		}

		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) {
			IStatus status = Status.OK_STATUS;
			String projectName = project.getName();
			SubMonitor progress = SubMonitor.convert(monitor, 100).checkCanceled();
			try {
				long start = System.currentTimeMillis();
				project.refreshLocal(IResource.DEPTH_INFINITE, progress.split(5));
				Optional<IBuildSupport> buildSupport = getBuildSupport(project);
				if (buildSupport.isPresent()) {
					buildSupport.get().update(project, force, progress.split(95));
					registerWatchers(true);
				}
				long elapsed = System.currentTimeMillis() - start;
				JavaLanguageServerPlugin.logInfo("Updated " + projectName + " in " + elapsed + " ms");
			} catch (CoreException e) {
				String msg = "Error updating " + projectName;
				JavaLanguageServerPlugin.logError(msg);
				status = StatusFactory.newErrorStatus(msg, e);
			}
			return status;
		}
	};
	job.schedule();
	return job;
}
 
Example #29
Source File: JobHelpers.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void waitForWorkspaceJobsToComplete(IProgressMonitor monitor) throws InterruptedException {
	IJobManager jobManager = Job.getJobManager();
	jobManager.suspend();
	try {
		Job[] jobs = jobManager.find(null);
		for(int i = 0; i < jobs.length; i++ ) {
			if(jobs[i] instanceof WorkspaceJob || jobs[i].getClass().getName().endsWith("JREUpdateJob")) {
				jobs[i].join();
			}
		}
	} finally {
		jobManager.resume();
	}
}
 
Example #30
Source File: SyntaxInitHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void triggerInitialization(Collection<IPath> roots) {

	Job job = new WorkspaceJob("Initialize Workspace") {
		@Override
		public IStatus runInWorkspace(IProgressMonitor monitor) {
			long start = System.currentTimeMillis();
			try {
				projectsManager.initializeProjects(roots, monitor);
				JavaLanguageServerPlugin.logInfo("Workspace initialized in " + (System.currentTimeMillis() - start) + "ms");
			} catch (Exception e) {
				JavaLanguageServerPlugin.logException("Initialization failed ", e);
			}

			return Status.OK_STATUS;
		}

		/* (non-Javadoc)
		 * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
		 */
		@SuppressWarnings("unchecked")
		@Override
		public boolean belongsTo(Object family) {
			Collection<IPath> rootPathsSet = roots.stream().collect(Collectors.toSet());
			boolean equalToRootPaths = false;
			if (family instanceof Collection<?>) {
				equalToRootPaths = rootPathsSet.equals(((Collection<IPath>) family).stream().collect(Collectors.toSet()));
			}

			return JAVA_LS_INITIALIZATION_JOBS.equals(family) || equalToRootPaths;
		}
	};
	job.setPriority(Job.BUILD);
	job.setRule(ResourcesPlugin.getWorkspace().getRoot());
	job.schedule();
}