org.eclipse.core.resources.IWorkspace#run ( )源码实例Demo

下面列出了org.eclipse.core.resources.IWorkspace#run ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ADT_Frontend   文件: TestsPdeAbapGitStagingUtil.java
protected IProject createDummyAbapProject(String projectName) throws CoreException{
	String destinationId = projectName;
	
	IDestinationDataWritable data = AdtDestinationDataFactory.newDestinationData(destinationId);
	data.setUser("TEST_DUMMY_USER"); 
	data.setClient("777"); 
	data.setLanguage("DE"); 
	data.setPassword("TEST_DUMMY_PW"); 
	
	String projectDestinationId = AdtProjectServiceFactory.createProjectService().createDestinationId(projectName);
	final IDestinationData destinationData = data.getReadOnlyClone(projectDestinationId);
	
	final IAbapProjectService abapProjectService = AdtProjectServiceFactory.createProjectService();
	//IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	final AbapProject[] projects = new AbapProject[1];
	workspace.run(new IWorkspaceRunnable() {
		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			projects[0] = (AbapProject) abapProjectService.createAbapProject(projectName, destinationData, monitor);
		}
	}, new NullProgressMonitor());
	return projects[0].getProject();
}
 
protected IProject createDummyAbapProject() throws CoreException{
	String projectName = "ABAPGIT_TEST_PROJECT";
	String destinationId = "ABAPGIT_TEST_PROJECT";
	
	IDestinationDataWritable data = AdtDestinationDataFactory.newDestinationData(destinationId);
	data.setUser("TEST_DUMMY_USER"); 
	data.setClient("777"); 
	data.setLanguage("DE"); 
	data.setPassword("TEST_DUMMY_PW"); 
	
	String projectDestinationId = AdtProjectServiceFactory.createProjectService().createDestinationId(projectName);
	final IDestinationData destinationData = data.getReadOnlyClone(projectDestinationId);
	
	final IAbapProjectService abapProjectService = AdtProjectServiceFactory.createProjectService();
	//IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	final AbapProject[] projects = new AbapProject[1];
	workspace.run(new IWorkspaceRunnable() {
		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			projects[0] = (AbapProject) abapProjectService.createAbapProject(projectName, destinationData, monitor);
		}
	}, new NullProgressMonitor());
	return projects[0].getProject();
}
 
源代码3 项目: n4js   文件: ProjectTestsUtils.java
/**
 * Creates a new workspace project with the given project location in the probands folder (cf.
 * {@code probandsName}).
 *
 * Creates a new workspace project with name {@code workspaceName}. Note that the project folder (based on the given
 * project location) and the project name may differ.
 *
 * Does not copy the proband resources into the workspaces, but keeps the project files at the given location (cf.
 * create new project with non-default location outside of workspace)
 *
 * @throws CoreException
 *             If the project creation does not succeed.
 */
public static IProject createProjectWithLocation(File probandsFolder, String projectLocationFolder,
		String workspaceName) throws CoreException {
	File projectSourceFolder = new File(probandsFolder, projectLocationFolder);
	if (!projectSourceFolder.exists()) {
		throw new IllegalArgumentException("proband not found in " + projectSourceFolder);
	}
	prepareDotProject(projectSourceFolder);

	IProgressMonitor monitor = new NullProgressMonitor();
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IProject project = workspace.getRoot().getProject(workspaceName);

	workspace.run((mon) -> {
		IProjectDescription newProjectDescription = workspace.newProjectDescription(workspaceName);
		final IPath absoluteProjectPath = new org.eclipse.core.runtime.Path(projectSourceFolder.getAbsolutePath());
		newProjectDescription.setLocation(absoluteProjectPath);
		project.create(newProjectDescription, mon);
		project.open(mon);
	}, monitor);

	return project;

}
 
源代码4 项目: gef   文件: DotGraphView.java
@Override
public boolean visit(final IResourceDelta delta) {
	IResource resource = delta.getResource();
	if (resource.getType() == IResource.FILE
			&& hasDotFileExtension(((IFile) resource).getName())) {
		try {
			final IFile f = (IFile) resource;
			IWorkspaceRunnable workspaceRunnable = updateGraphRunnable(
					DotFileUtils
							.resolve(f.getLocationURI().toURL()));
			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			if (!workspace.isTreeLocked()) {
				workspace.run(workspaceRunnable, null);
			}
		} catch (Exception e) {
			DotActivatorEx.logError(e);
		}
	}
	return true;
}
 
源代码5 项目: gef   文件: SyncGraphvizExportHandler.java
@Override
public boolean visit(final IResourceDelta delta) {
	IResource resource = delta.getResource();
	if (resource.getType() == IResource.FILE
			&& ((IFile) resource).getName().endsWith(EXTENSION)) {
		try {
			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			if (!workspace.isTreeLocked()) {
				IFile file = (IFile) resource;
				workspace.run(new DotExportRunnable(file), null);
			}
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
	return true;
}
 
源代码6 项目: gwt-eclipse-plugin   文件: ChangeUtilities.java
/**
 * Creates a {@link Change} from the given {@link Refactoring}.
 * 
 * @param errorLevel the error level for the condition checking which should
 *          cause the change creation to fail
 * 
 * @return a non-null {@link Change}
 * @throws RefactoringException if there was a problem creating the change
 */
public static Change createChange(IWorkspace workspace, IProgressMonitor pm,
    Refactoring refactoring, int errorLevel) throws RefactoringException {
  CreateChangeOperation createChangeOperation = ChangeUtilities.createCreateChangeOperation(
      refactoring, errorLevel);
  try {
    workspace.run(createChangeOperation, pm);

    RefactoringStatus status = createChangeOperation.getConditionCheckingStatus();
    if (status.getSeverity() >= errorLevel) {
      // Could not create the change, throw an exception with the failure
      // status message
      throw new RefactoringException(
          status.getMessageMatchingSeverity(status.getSeverity()));
    }
  } catch (CoreException e) {
    throw new RefactoringException(e);
  }

  return createChangeOperation.getChange();
}
 
源代码7 项目: thym   文件: HybridMobileEngineTests.java
@Test
public void testRemoveEngineUsingName() throws CoreException {
	final HybridMobileEngine[] engines = new HybridMobileEngine[2];
	engines[0] = new HybridMobileEngine("android", "6.0.0", null);
	engines[1] = new HybridMobileEngine("ios", "4.4.0", null);
	manager.updateEngines(engines);
	JobUtils.waitForIdle();

	// Run on a IWorkspaceRunnable because it needs to sync with the udpateEngines
	// call.
	IWorkspaceRunnable runnable = new IWorkspaceRunnable() {

		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			manager.removeEngine(engines[0].getName(), monitor, true);
			Widget w = WidgetModel.getModel(testproject.hybridProject()).getWidgetForRead();
			assertEquals(1, w.getEngines().size());
			assertEquals(1, manager.getEngines().length);
			checkEnginesPersistedCorrectly(new HybridMobileEngine[] { engines[1] });
		}
	};
	IWorkspace ws = ResourcesPlugin.getWorkspace();
	ISchedulingRule rule = ws.getRuleFactory().modifyRule(testproject.getProject());
	ws.run(runnable, rule, 0, new NullProgressMonitor());
}
 
源代码8 项目: thym   文件: HybridMobileEngineTests.java
@Test
public void testRemoveEngine() throws CoreException {
	final HybridMobileEngine[] engines = new HybridMobileEngine[2];
	engines[0] = new HybridMobileEngine("android", "6.0.0", null);
	engines[1] = new HybridMobileEngine("ios", "4.4.0", null);
	manager.updateEngines(engines);
	JobUtils.waitForIdle();

	// Run on a IWorkspaceRunnable because it needs to sync with the udpateEngines
	// call.
	IWorkspaceRunnable runnable = new IWorkspaceRunnable() {

		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			manager.removeEngine(engines[0], monitor, true);
			Widget w = WidgetModel.getModel(testproject.hybridProject()).getWidgetForRead();
			assertEquals(1, w.getEngines().size());
			checkEnginesPersistedCorrectly(new HybridMobileEngine[] { engines[1] });
		}
	};
	IWorkspace ws = ResourcesPlugin.getWorkspace();
	ISchedulingRule rule = ws.getRuleFactory().modifyRule(testproject.getProject());
	ws.run(runnable, rule, 0, new NullProgressMonitor());
}
 
源代码9 项目: uima-uimaj   文件: JgPluginRunner.java
@Override
public Object run(Object object) {
  try {
    final String[] arguments = (String[]) object;
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final Jg jg = new Jg();
    IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
      @Override
      public void run(IProgressMonitor progressMonitor) throws CoreException {
        jg.main0(arguments, new MergerImpl(), null, // no progressMonitor,
                new EP_LogThrowErrorImpl());
      }
    };
    workspace.run(runnable, null);
    return 0;
  } catch (Exception exception) {
    exception.printStackTrace();
  }

  return 1;
}
 
源代码10 项目: n4js   文件: ProjectCacheInvalidationPluginTest.java
/**
 * Runs the given {@link ICoreRunnable} as an atomic workspace operation with a lock on the whole workspace.
 *
 * All resource changes performed by the given {@code operation} will be collected and a single
 * {@link IResourceChangeEvent} will be issued for all changes.
 */
private void runAtomicWorkspaceOperation(ICoreRunnable operation) throws CoreException {
	final IWorkspace workspace = ResourcesPlugin.getWorkspace();
	workspace.run(operation, workspace.getRoot(),
			IWorkspace.AVOID_UPDATE, // issue one resource change event at the end of the operation
			new NullProgressMonitor());
}
 
源代码11 项目: eclipse.jdt.ls   文件: ProjectCommand.java
/**
 * Gets the classpaths and modulepaths.
 *
 * @param uri
 *                    Uri of the source/class file that needs to be queried.
 * @param options
 *                    Query options.
 * @return <code>ClasspathResult</code> containing both classpaths and
 *         modulepaths.
 * @throws CoreException
 * @throws URISyntaxException
 */
public static ClasspathResult getClasspaths(String uri, ClasspathOptions options) throws CoreException, URISyntaxException {
	IJavaProject javaProject = getJavaProjectFromUri(uri);
	Optional<IBuildSupport> bs = JavaLanguageServerPlugin.getProjectsManager().getBuildSupport(javaProject.getProject());
	if (!bs.isPresent()) {
		throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "No BuildSupport for the project: " + javaProject.getElementName()));
	}
	ILaunchConfiguration launchConfig = bs.get().getLaunchConfiguration(javaProject, options.scope);
	JavaLaunchDelegate delegate = new JavaLaunchDelegate();
	ClasspathResult[] result = new ClasspathResult[1];

	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	ISchedulingRule currentRule = Job.getJobManager().currentRule();
	ISchedulingRule schedulingRule;
	if (currentRule != null && currentRule.contains(javaProject.getSchedulingRule())) {
		schedulingRule = null;
	} else {
		schedulingRule = javaProject.getSchedulingRule();
	}
	workspace.run(new IWorkspaceRunnable() {
		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			String[][] paths = delegate.getClasspathAndModulepath(launchConfig);
			result[0] = new ClasspathResult(javaProject.getProject().getLocationURI(), paths[0], paths[1]);
		}
	}, schedulingRule, IWorkspace.AVOID_UPDATE, new NullProgressMonitor());

	if (result[0] != null) {
		return result[0];
	}

	throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "Failed to get the classpaths."));
}
 
源代码12 项目: xds-ide   文件: ResourceUtils.java
public static void runWorkspaceRunnable(IWorkspaceRunnable operation, ISchedulingRule rule)
          throws CoreException {
  	IWorkspace workspace = ResourcesPlugin.getWorkspace();
  	try {
	workspace.run(operation, rule, IWorkspace.AVOID_UPDATE, null);
} catch (CoreException e1) {
	LogHelper.logError(e1);
}
  }
 
private void runInWorkspace(final IWorkspaceRunnable r) {
  try {
    IWorkspace _workspace = ResourcesPlugin.getWorkspace();
    NullProgressMonitor _nullProgressMonitor = new NullProgressMonitor();
    _workspace.run(r, _nullProgressMonitor);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
源代码14 项目: gwt-eclipse-plugin   文件: ChangeUtilities.java
/**
 * Performs the given change.
 * 
 * @return The undo change as produced by the refactoring's change.
 */
public static Change performChange(IWorkspace workspace, IProgressMonitor pm,
    Change change) throws CoreException {
  PerformChangeOperation performChangeOperation = new PerformChangeOperation(
      change);
  try {
    workspace.run(performChangeOperation, pm);
  } finally {
    if (!performChangeOperation.changeExecuted()) {
      change.dispose();
    }
  }

  return performChangeOperation.getUndoChange();
}
 
源代码15 项目: thym   文件: HybridMobileEngineTests.java
@Test
public void testAddEngine() throws CoreException {
	final HybridMobileEngine[] engines = new HybridMobileEngine[2];
	engines[0] = new HybridMobileEngine("android", "6.0.0", null);
	engines[1] = new HybridMobileEngine("ios", "4.4.0", null);
	final HybridMobileEngine newEngine = new HybridMobileEngine("windows", "5.0.0", null);
	manager.updateEngines(engines);
	JobUtils.waitForIdle();

	// Run on a IWorkspaceRunnable because it needs to sync with the udpateEngines
	// call.
	IWorkspaceRunnable runnable = new IWorkspaceRunnable() {

		@Override
		public void run(IProgressMonitor monitor) throws CoreException {
			Widget w = WidgetModel.getModel(testproject.hybridProject()).getWidgetForRead();
			assertEquals(engines.length, w.getEngines().size());
			assertEquals(engines.length, manager.getEngines().length);
			manager.addEngine(newEngine.getName(), newEngine.getSpec(), monitor, true);
			w = WidgetModel.getModel(testproject.hybridProject()).getWidgetForRead();
			assertEquals(engines.length + 1, w.getEngines().size());
			assertEquals(engines.length + 1, manager.getEngines().length);
			checkEnginesPersistedCorrectly(new HybridMobileEngine[] { engines[0], engines[1], newEngine });
		}
	};
	IWorkspace ws = ResourcesPlugin.getWorkspace();
	ISchedulingRule rule = ws.getRuleFactory().modifyRule(testproject.getProject());
	ws.run(runnable, rule, 0, new NullProgressMonitor());
}
 
/**
 * Start a build on given project or workspace using given options.
 * 
 * @param javaProject Project which must be (full) build or null if all
 * workspace has to be built.
 * @param options Options used while building
 */
void build(final IJavaProject javaProject, Hashtable options, boolean noWarning) throws IOException, CoreException {
  if (DEBUG)
    System.out.print("\tstart build...");
  JavaCore.setOptions(options);
  if (PRINT)
    System.out.println("JavaCore options: " + options);

  // Build workspace if no project
  if (javaProject == null) {
    // single measure
    ENV.fullBuild();
  } else {
    if (PRINT)
      System.out.println("Project options: " + javaProject.getOptions(false));
    IWorkspaceRunnable compilation = new IWorkspaceRunnable() {
      public void run(IProgressMonitor monitor) throws CoreException {
        ENV.fullBuild(javaProject.getPath());
      }
    };
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    workspace.run(compilation, null/* don't take any lock */, IWorkspace.AVOID_UPDATE, null/*
                                                                                            * no
                                                                                            * progress
                                                                                            * available
                                                                                            * here
                                                                                            */);
  }

  // Verify markers
  IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
  IMarker[] markers = workspaceRoot.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
  List resources = new ArrayList();
  List messages = new ArrayList();
  int warnings = 0;
  for (int i = 0, length = markers.length; i < length; i++) {
    IMarker marker = markers[i];
    switch (((Integer) marker.getAttribute(IMarker.SEVERITY)).intValue()) {
    case IMarker.SEVERITY_ERROR:
      resources.add(marker.getResource().getName());
      messages.add(marker.getAttribute(IMarker.MESSAGE));
      break;
    case IMarker.SEVERITY_WARNING:
      warnings++;
      if (noWarning) {
        resources.add(marker.getResource().getName());
        messages.add(marker.getAttribute(IMarker.MESSAGE));
      }
      break;
    }
  }
  workspaceRoot.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);

  // Assert result
  int size = messages.size();
  if (size > 0) {
    StringBuffer debugBuffer = new StringBuffer();
    for (int i = 0; i < size; i++) {
      debugBuffer.append(resources.get(i));
      debugBuffer.append(":\n\t");
      debugBuffer.append(messages.get(i));
      debugBuffer.append('\n');
    }
    System.out.println("Unexpected ERROR marker(s):\n" + debugBuffer.toString());
    System.out.println("--------------------");
    String target = javaProject == null ? "workspace" : javaProject.getElementName();
    // assertEquals("Found "+size+" unexpected errors while building "+target,
    // 0, size);
  }
  if (DEBUG)
    System.out.println("done");
}
 
源代码17 项目: uima-uimaj   文件: MultiPageEditor.java
/**
 * Do J cas gen.
 *
 * @param monitor the monitor
 */
public void doJCasGen(IProgressMonitor monitor) {
  if (0 < mergedTypesAddingFeatures.size()) {
    if (Window.CANCEL == 
    Utility.popOkCancel("Type feature merging extended features",
            "Before generating the JCas classes for the CAS types, please note that " +
            "the following types were generated by merging different type descriptors, " +
            "where the resulting number of features is larger than that of the components. " +
            "Although the resulting generated JCas classes are correct, " +
            "doing this kind of merging makes reuse of this component more difficult." +
            makeMergeMessage(mergedTypesAddingFeatures) +
            "\n   Press OK to generate the JCas classes anyway, or cancel to skip generating the JCas classes.", 
            MessageDialog.WARNING)) 
      return;
  }
  final JCasGenThrower jCasGenThrower = new JCasGenThrower();

  try {

    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final Jg jg = new Jg();
    final TypeDescription[] types = mergedTypeSystemDescription.getTypes();
    final String outputDirectory = getPrimarySourceFolder().getLocation().toOSString();
    final String inputFile = file.getLocation().toOSString(); // path to descriptor file
    IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
      @Override
      public void run(IProgressMonitor progressMonitor) {
        try {
          jg.mainForCde(new MergerImpl(), new JCasGenProgressMonitor(progressMonitor),
                  jCasGenThrower, inputFile, outputDirectory, types, (CASImpl) getCurrentView(),
                  getProject().getLocation().toString(),  // https://issues.apache.org/jira/browse/UIMA-5715
                       // getLocationURI().getPath(),  // on linux/mars, was returning /default/project.name etc
                  limitJCasGenToProjectScope,
                  mergedTypesAddingFeatures);
        } catch (IOException e) {
          Utility.popMessage(Messages.getString("MultiPageEditor.25"), //$NON-NLS-1$
                  Messages.getString("MultiPageEditor.26") //$NON-NLS-1$
                          + getMessagesToRootCause(e), MessageDialog.ERROR);
        }
      }
    };
    workspace.run(runnable, monitor);
    getPrimarySourceFolder().refreshLocal(IResource.DEPTH_INFINITE, null);

    String jcasMsg = jCasGenThrower.getMessage();
    if (null != jcasMsg && jcasMsg.length() > 0) {
      Utility.popMessage(Messages.getString("MultiPageEditor.JCasGenErrorTitle"), //$NON-NLS-1$
              Messages.getFormattedString("MultiPageEditor.jcasGenErr", //$NON-NLS-1$
                      new String[] { jcasMsg }), MessageDialog.ERROR);
      System.out.println(jcasMsg);
    }
  } catch (Exception ex) {
    Utility.popMessage(Messages.getString("MultiPageEditor.JCasGenErrorTitle"), //$NON-NLS-1$
            Messages.getFormattedString("MultiPageEditor.jcasGenErr", //$NON-NLS-1$
                    new String[] { jCasGenThrower.getMessage() }), MessageDialog.ERROR);
    ex.printStackTrace();
  }
}