Java Code Examples for org.eclipse.core.runtime.NullProgressMonitor

The following examples show how to use org.eclipse.core.runtime.NullProgressMonitor. These examples are extracted from open source projects. 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 Project: eclipse.jdt.ls   Source File: ImportOrganizeTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void addFilesFromJar(IJavaProject javaProject, File jarFile, String encoding) throws InvocationTargetException, CoreException, IOException {
	IFolder src = (IFolder) fSourceFolder.getResource();
	File targetFile = src.getLocation().toFile();
	try (JarFile file = new JarFile(jarFile)) {
		for (JarEntry entry : Collections.list(file.entries())) {
			if (entry.isDirectory()) {
				continue;
			}
			try (InputStream in = file.getInputStream(entry); Reader reader = new InputStreamReader(in, encoding)) {
				File outFile = new File(targetFile, entry.getName());
				outFile.getParentFile().mkdirs();
				try (OutputStream out = new FileOutputStream(outFile); Writer writer = new OutputStreamWriter(out, encoding)) {
					IOUtils.copy(reader, writer);
				}
			}
		}
	}
	javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
}
 
Example 2
@Override
public void click(MouseEvent event) {
	if (event.getClickCount() == 2) {
		// double click, so open nested graph, if it exists
		final Graph nestedGraph = getHost().getContent().getNestedGraph();
		if (nestedGraph != null) {
			IViewer viewer = getHost().getRoot().getViewer();
			try {
				// navigate to nested graph
				viewer.getDomain().execute(new NavigateOperation(viewer, nestedGraph, true),
						new NullProgressMonitor());
			} catch (ExecutionException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
 
Example 3
public IStatus apply(final IProject project, boolean promptForOverwrite)
{
	IInputStreamTransformer transform = new TemplateSubstitutionTransformer(project);
	File zipFile = new File(getDirectory(), getLocation());
	try
	{
		return ZipUtil.extract(zipFile, project.getLocation().toFile(),
				promptForOverwrite ? ZipUtil.Conflict.PROMPT : ZipUtil.Conflict.OVERWRITE, transform,
				new NullProgressMonitor());
	}
	catch (IOException e)
	{
		return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, 0, MessageFormat.format(
				"IOException reading zipfile {0}", zipFile.getAbsolutePath()), e); //$NON-NLS-1$
	}
}
 
Example 4
private void assertAndApplySingleResolution(XtextEditor xtextEditor, String issueCode, int issueDataCount, String resolutionLabel,
		boolean isCleanAfterApply) {
	IXtextDocument document = xtextEditor.getDocument();
	List<Issue> issues = getIssues(document);
	assertFalse(issues.toString(), issues.isEmpty());
	Issue issue = issues.iterator().next();
	assertEquals(issueCode, issue.getCode());
	assertNotNull(issue.getData());
	assertEquals(issueDataCount, issue.getData().length);
	List<IssueResolution> resolutions = issueResolutionProvider.getResolutions(issue);

	assertEquals(1, resolutions.size());
	IssueResolution resolution = resolutions.iterator().next();
	assertEquals(resolutionLabel, resolution.getLabel());
	try {
		resolution.apply();
		assertEquals(getIssues(document).toString(), isCleanAfterApply, getIssues(document).isEmpty());
	} finally {
		// Save xtextEditor in any case. Otherwise test will stuck,
		// because the "save changed resource dialog" waits for user input.
		xtextEditor.doSave(new NullProgressMonitor());
	}
}
 
Example 5
Source Project: codewind-eclipse   Source File: ImportUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static IProject importExistingMavenProjects(IPath path, String projectName) throws Exception {
	File root = path.toFile();
	String location = path.toOSString();
	MavenModelManager modelManager = MavenPlugin.getMavenModelManager();
	LocalProjectScanner scanner = new LocalProjectScanner(root, location, false, modelManager);
	scanner.run(new NullProgressMonitor());
	List<MavenProjectInfo> infos = new ArrayList<MavenProjectInfo>();
	infos.addAll(scanner.getProjects());
	for(MavenProjectInfo info : scanner.getProjects()){
		infos.addAll(info.getProjects());
	}
	ImportMavenProjectsJob job = new ImportMavenProjectsJob(infos, new ArrayList<IWorkingSet>(), new ProjectImportConfiguration());
	job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
	job.schedule();
	IProject project = waitForProject(projectName);
	return project;
}
 
Example 6
Source Project: eclipse-cs   Source File: Auditor.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private IDocument connectFileBuffer(IResource resource) {

      if (!(resource instanceof IFile)) {
        return null;
      }

      IDocument document = null;

      try {
        IPath path = resource.getFullPath();
        mFileBufferManager.connect(path, new NullProgressMonitor());

        mConnectedFileBufferPaths.add(path);
        document = mFileBufferManager.getTextFileBuffer(path).getDocument();
      } catch (CoreException e) {
        CheckstyleLog.log(e);
      }
      return document;
    }
 
Example 7
Source Project: tesb-studio-se   Source File: BundleJavaProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void generatePom(int option) {
    super.generatePom(option);
    if (option == TalendProcessOptionConstants.GENERATE_IS_MAINJOB) {
        try {
            IRepositoryObject repositoryObject = new RepositoryObject(getProperty());

            // Fix TESB-22660: Avoide to operate repo viewer before it open
            if (PlatformUI.isWorkbenchRunning()) {
                RepositorySeekerManager.getInstance().searchRepoViewNode(getProperty().getId(), false);
            }

            IRunnableWithProgress action = new JavaCamelJobScriptsExportWSAction(repositoryObject, getProperty().getVersion(),
                    "", false);
            action.run(new NullProgressMonitor());
        } catch (Exception e) {
            ExceptionHandler.process(e);
        }
    }
}
 
Example 8
protected void pushKey(char c, int k) throws Exception {
	String textBefore = editor.getDocument().get();
	Event event = new Event();
	event.type = SWT.KeyDown;
	event.character = c;
	event.keyCode = k;
	myDisplay.post(event);
	syncUtil.yieldToQueuedDisplayJobs(new NullProgressMonitor());
	Event event2 = new Event();
	event2.type = SWT.KeyUp;
	event2.character = c;
	event2.keyCode = k;
	myDisplay.post(event2);
	int maxTries = 10;
	while (maxTries-- > 0) {
		if (!Objects.equal(editor.getDocument().get(), textBefore)) {
			syncUtil.waitForReconciler(editor);
			return;
		}
		Thread.sleep(10);
		syncUtil.yieldToQueuedDisplayJobs(new NullProgressMonitor());
	}
	Assert.fail("Document didn't change on keystroke");
}
 
Example 9
/**
   * Set the selection and focus to the list of elements
   * @param elements the object to be selected and displayed
   */
  public void setSelection(final List<?> elements) {
      if (elements == null || elements.size() == 0)
          return;
try {
       ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
       	public void run(IProgressMonitor monitor) throws CoreException {
       		fPackageViewer.refresh();
               IStructuredSelection selection= new StructuredSelection(elements);
               fPackageViewer.setSelection(selection, true);
               fPackageViewer.getTree().setFocus();

               if (elements.size() == 1 && elements.get(0) instanceof IJavaProject)
                   fPackageViewer.expandToLevel(elements.get(0), 1);
           }
       }, ResourcesPlugin.getWorkspace().getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor());
      } catch (CoreException e) {
       JavaPlugin.log(e);
      }
  }
 
Example 10
Source Project: tlaplus   Source File: SpecTest.java    License: MIT License 6 votes vote down vote up
private void createDelete(final String specName, boolean forget) throws IOException, CoreException {
	// Create...
	final File tempFile = File.createTempFile(specName, TLAConstants.Files.TLA_EXTENSION);
	final Spec spec = Spec.createNewSpec("TestCreateDeleteSpec", tempFile.getAbsolutePath(), false, new NullProgressMonitor());
	final IProject project = spec.getProject();
	
	final WorkspaceSpecManager wsm = new WorkspaceSpecManager(new NullProgressMonitor());
	wsm.removeSpec(spec, new NullProgressMonitor(), forget);
	
	// Make sure that the project has been deleted.
	assertFalse(project.exists());
	final IWorkspace ws = ResourcesPlugin.getWorkspace();
	for (final IProject aProject : ws.getRoot().getProjects()) {
		assertNotSame(project.getName(), aProject.getName());
	}
	
	Spec mostRecentlyOpenedSpec = wsm.getMostRecentlyOpenedSpec();
	assertNull(mostRecentlyOpenedSpec != null ? mostRecentlyOpenedSpec.getName() : "", mostRecentlyOpenedSpec);
}
 
Example 11
Source Project: JReFrameworker   Source File: JReFrameworker.java    License: MIT License 6 votes vote down vote up
private static IJavaProject createProject(String projectName, IPath projectPath, IProject project, IProgressMonitor monitor) throws CoreException {
	IProjectDescription projectDescription = project.getWorkspace().newProjectDescription(project.getName());
	URI location = getProjectLocation(projectName, projectPath);
	projectDescription.setLocationURI(location);
	
	// make this a JReFrameworker project
	projectDescription.setNatureIds(new String[] { JReFrameworkerNature.NATURE_ID, JavaCore.NATURE_ID });

	// build first with Java compiler then JReFramewoker bytecode operations
	BuildCommand javaBuildCommand = new BuildCommand();
	javaBuildCommand.setBuilderName(JavaCore.BUILDER_ID);
	BuildCommand jrefBuildCommand = new BuildCommand();
	jrefBuildCommand.setBuilderName(JReFrameworkerBuilder.BUILDER_ID);
	projectDescription.setBuildSpec(new ICommand[]{ javaBuildCommand, jrefBuildCommand});

	// create and open the Eclipse project
	project.create(projectDescription, null);
	IJavaProject jProject = JavaCore.create(project);
	project.open(new NullProgressMonitor());
	return jProject;
}
 
Example 12
Source Project: n4js   Source File: IDEBUG_856_PluginTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks whether the external refreshing does not cause deadlock due to incorrect workspace checkpoints and
 * incorrect job family configuration.
 */
@Test
public void testMultipleExternalRefresh() throws Exception {
	// initial load to trigger cloning
	libManager.synchronizeNpms(new NullProgressMonitor());

	LOG.info("------------------------------------------------------------");
	for (int i = 1; i <= ITERATION_COUNT; i++) {
		LOG.info("Iteration " + i + " of " + ITERATION_COUNT + ".");
		libManager.synchronizeNpms(new NullProgressMonitor());
		// schedule second reload to see if they deadlock
		libManager.synchronizeNpms(new NullProgressMonitor());
		LOG.info("waiting for build.");
		waitForAutoBuild();
	}
	LOG.info("------------------------------------------------------------");
}
 
Example 13
@Override
protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
	super.addEdits(document, editRoot);
	ASTRewrite rewrite= getRewrite();
	if (rewrite != null) {
		try {
			TextEdit edit= rewrite.rewriteAST();
			editRoot.addChild(edit);
		} catch (IllegalArgumentException e) {
			throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
		}
	}
	if (fImportRewrite != null) {
		editRoot.addChild(fImportRewrite.rewriteImports(new NullProgressMonitor()));
	}
}
 
Example 14
Source Project: xtext-xtend   Source File: ContentAssistTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static IProject createPluginProject(String name) throws CoreException {
	Injector injector = XtendActivator.getInstance().getInjector("org.eclipse.xtend.core.Xtend");
	PluginProjectFactory projectFactory = injector.getInstance(PluginProjectFactory.class);
	projectFactory.setBreeToUse(JREContainerProvider.PREFERRED_BREE);
	projectFactory.setProjectName(name);
	projectFactory.setProjectDefaultCharset(StandardCharsets.ISO_8859_1.name());
	projectFactory.addFolders(Collections.singletonList("src"));
	projectFactory.addBuilderIds(
		JavaCore.BUILDER_ID, 
		"org.eclipse.pde.ManifestBuilder",
		"org.eclipse.pde.SchemaBuilder",
		XtextProjectHelper.BUILDER_ID);
	projectFactory.addProjectNatures(JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature", XtextProjectHelper.NATURE_ID);
	projectFactory.addRequiredBundles(Lists.newArrayList(
			"org.eclipse.xtext.xbase.lib",
			"org.eclipse.xtend.lib"));
	IProject result = projectFactory.createProject(new NullProgressMonitor(), null);
	JavaProjectSetupUtil.makeJava8Compliant(JavaCore.create(result));
	return result;
}
 
Example 15
Source Project: Pydev   Source File: AbstractWorkbenchTestCase.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected static void configureInterpreters() {
    if (!interpretersConfigured) {
        interpretersConfigured = true;
        InterpreterInfo.configurePathsCallback = new ICallback<Boolean, Tuple<List<String>, List<String>>>() {
            @Override
            public Boolean call(Tuple<List<String>, List<String>> arg) {
                return Boolean.TRUE;
            }
        };
        IEclipsePreferences node = PydevPrefs.getEclipsePreferences();
        InterpreterManagersAPI.setJythonInterpreterManager(new JythonInterpreterManager(node));
        InterpreterManagersAPI.setPythonInterpreterManager(new PythonInterpreterManager(node));

        ProjectModulesManager.IN_TESTS = true;

        NullProgressMonitor monitor = new NullProgressMonitor();

        createJythonInterpreterManager(monitor);
        createPythonInterpreterManager(monitor);
    }
}
 
Example 16
@Override
protected void setInput ( final IEditorInput input )
{
    final ConfigurationEditorInput configurationInput = (ConfigurationEditorInput)input;

    if ( !this.nested )
    {
        configurationInput.performLoad ( new NullProgressMonitor () );
    }

    this.dirtyValue = configurationInput.getDirtyValue ();
    this.dirtyValue.addValueChangeListener ( new IValueChangeListener () {

        @Override
        public void handleValueChange ( final ValueChangeEvent event )
        {
            firePropertyChange ( IEditorPart.PROP_DIRTY );
        }
    } );

    super.setInput ( input );
}
 
Example 17
@Test
public void should_groovy_connector_configuration_be_converted_at_export() throws Exception {
    RepositoryAccessor repositoryAccessor = new RepositoryAccessor();
    repositoryAccessor.init();
    final ImportBosArchiveOperation op = new ImportBosArchiveOperation(repositoryAccessor);
    final URL fileURL1 = FileLocator
            .toFileURL(TestDatabaseConnectorResulset.class.getResource("GroovyConnectorTest-1.0.bos")); //$NON-NLS-1$
    op.setArchiveFile(FileLocator.toFileURL(fileURL1).getFile());
    op.setCurrentRepository(repositoryAccessor.getCurrentRepository());
    op.run(new NullProgressMonitor());
    for (final IRepositoryFileStore fStore : op.getFileStoresToOpen()) {
        fStore.open();
    }
    final MainProcess mainProcess = (MainProcess) op.getFileStoresToOpen().get(0).getContent();

    final RunProcessCommand runProcessCommand = new RunProcessCommand(true);
    final Status status = (Status) runProcessCommand
            .execute(ProcessSelector.createExecutionEvent((AbstractProcess) mainProcess.getElements().get(0)));
    assertThat(status.isOK()).isTrue();

}
 
Example 18
/**
 * 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 19
/**
 * Tests the following project name configuration.
 *
 * <pre>
 * File System: 	file-other-system
 * Package.json: 	file-system
 * Eclipse: 		file-system
 * </pre>
 */
@Test
public void testDifferentFileSystemName() throws CoreException {
	// workspace setup
	final IProject testProject = ProjectTestsUtils.createProjectWithLocation(projectsRoot,
			"file-other-system", "file-system");
	configureProjectWithXtext(testProject);
	waitForAutoBuild();

	// obtain package.json resource
	final IResource packageJsonResource = testProject.findMember(IN4JSProject.PACKAGE_JSON);

	// assert project name markers
	assertHasMarker(packageJsonResource, IssueCodes.PKGJ_PACKAGE_NAME_MISMATCH);
	assertHasNoMarker(packageJsonResource, IssueCodes.PKGJ_PROJECT_NAME_ECLIPSE_MISMATCH);

	// tear down
	testProject.delete(false, true, new NullProgressMonitor());
}
 
Example 20
private SearchResult findTypesBySimpleName(String simpleTypeName, final boolean searchForSources) {
	final SearchResult result = new SearchResult();
	try {
		new SearchEngine().searchAllTypeNames(null, 0, // match all package names
				simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
					IJavaSearchConstants.TYPE,
					SearchEngine.createWorkspaceScope(),
					new TypeNameMatchRequestor() {
						@Override
						public void acceptTypeNameMatch(TypeNameMatch match) {
							IPackageFragmentRoot fragmentRoot = match.getPackageFragmentRoot();
							boolean externalLib = fragmentRoot.isArchive() || fragmentRoot.isExternal();
							if (externalLib ^ searchForSources) {
								result.foundTypes.add(match.getType());
							}
						}
					}, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, // wait for the jdt index to be ready
					new NullProgressMonitor());
	} catch (JavaModelException e) {
		logger.error(e.getMessage(), e);
	}
	return result;
}
 
Example 21
Source Project: eclipse-extras   Source File: ProjectHelper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static void cleanWorkspace() throws CoreException {
  projects.clear();
  IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects( INCLUDE_HIDDEN );
  for( IProject project : allProjects ) {
    delete( project );
    project.refreshLocal( IResource.DEPTH_ZERO, new NullProgressMonitor() );
  }
}
 
Example 22
Source Project: xds-ide   Source File: HistoryFs.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFileStore getStore(URI uri) {
	IFile f = ResourceUtils.getWorkspaceRoot().getFile(new Path(uri.getPath()));
	long time = getTime(uri.getQuery());
	IFileState[] history = null;
	try {
		history = f.getHistory(new NullProgressMonitor());
	} catch (CoreException e) {
		LogHelper.logError(e);
	}
	IFileState fileState = findFileState(history, time);
	HistoryFileStore s = new HistoryFileStore(uri, fileState);
	return s;
}
 
Example 23
Source Project: tlaplus   Source File: TraceExplorerHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Writes the trace to MC_TE.out.
 * @param trace
 */
public static void serializeTrace(Model model)
{
    try
    {
        List<TLCState> trace = getErrorOfOriginalTrace(model).getStates(Length.ALL);
        Assert.isNotNull(trace);
        Iterator<TLCState> it = trace.iterator();
        IFile traceSourceFile = model.getTraceSourceFile();
        ModelHelper.createOrClearFiles(new IFile[] { traceSourceFile }, new NullProgressMonitor());
        while (it.hasNext())
        {
            traceSourceFile.appendContents(new ByteArrayInputStream((MP.DELIM + MP.STARTMSG + "0000" + MP.COLON
                    + MP.STATE + " " + MP.DELIM + "\n").getBytes()), IResource.FORCE | IWorkspace.AVOID_UPDATE,
                    new NullProgressMonitor());
            TLCState state = (TLCState) it.next();
            StringBuffer toAppend = new StringBuffer();
            toAppend.append(state.getStateNumber()).append(": ").append(state.getLabel()).append("\n").append(
                    state.toString());

            traceSourceFile.appendContents(new ByteArrayInputStream(toAppend.toString().getBytes()),
                    IResource.FORCE | IWorkspace.AVOID_UPDATE, new NullProgressMonitor());

            traceSourceFile.appendContents(new ByteArrayInputStream(
                    (MP.DELIM + MP.ENDMSG + "0000" + " " + MP.DELIM + "\n").getBytes()), IResource.FORCE
                    | IWorkspace.AVOID_UPDATE, new NullProgressMonitor());

        }
    } catch (CoreException e)
    {
        TLCUIActivator.getDefault().logError("Error writing trace contents to file", e);
    }
}
 
Example 24
/**
 * 返回与此编辑器相关的进度监视器。
 * @return 与此编辑器相关的进度监视器
 */
protected IProgressMonitor getProgressMonitor() {
	IProgressMonitor pm = null;
	IStatusLineManager manager = getStatusLineManager();
	if (manager != null)
		pm = manager.getProgressMonitor();
	return pm != null ? pm : new NullProgressMonitor();
}
 
Example 25
/** {@inheritDoc} */
@Override
public void removeTestSource(final TestSource testSource) {
  IFile file = testSource.getiFile();
  if (file != null) {
    try {
      file.delete(true, new NullProgressMonitor());
    } catch (CoreException e) {
      throw new WrappedException(e);
    }
  }
}
 
Example 26
Source Project: bonita-studio   Source File: TestJBPMImport.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testSimpleProcess() throws Exception {
    URL srcUrl = getClass().getResource("testSimpleProcess1/processdefinition.xml");
    File destFile = new JBPM3ToProc().createDiagram(srcUrl, new NullProgressMonitor());
    destFile.deleteOnExit();
    ResourceSet resourceSet = new ResourceSetImpl();
    Resource resource = resourceSet.getResource(toEMFURI(destFile), true);
    MainProcess mainProcess = (MainProcess) resource.getContents().get(0);

    assertNbItems(mainProcess, 1, 1, 1, 0, 2, 2, 1, 9, 2);
    Activity mailNode = findActivity(mainProcess, "mail-node1");
    assertEquals("No mail connector found", "email", mailNode.getConnectors().get(0).getDefinitionId());

    final AbstractProcess process = (AbstractProcess) mainProcess.getElements().get(0);
    final ProcessConfigurationRepositoryStore store = (ProcessConfigurationRepositoryStore) RepositoryManager
            .getInstance().getRepositoryStore(ProcessConfigurationRepositoryStore.class);
    final String fileName = ModelHelper.getEObjectID(process) + ".conf";
    ProcessConfigurationFileStore fileStore = store.getChild(fileName, true);
    if (fileStore == null) {
        fileStore = store.createRepositoryFileStore(fileName);
        fileStore.save(ConfigurationFactory.eINSTANCE.createConfiguration());
    }
    final Configuration configuration = fileStore.getContent();
    final ConfigurationSynchronizer configurationSynchronizer = new ConfigurationSynchronizer(process, configuration);
    configurationSynchronizer.synchronize();
    assertFalse("Configuration should not be valid", configurationSynchronizer.isConfigurationValid());
    resource.unload();

}
 
Example 27
Source Project: tracecompass   Source File: ResourceUtilTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private @NonNull IResource createAndVerifyResource(String name, boolean isFile) throws CoreException {
    IResource resource;
    if (isFile) {
        resource = fTestFolder.getFile(name);
        ((IFile) resource).create(new ByteArrayInputStream(new byte[0]), false, new NullProgressMonitor());
    } else {
        resource = fTestFolder.getFolder(name);
        ((IFolder) resource).create(true, true, null);
    }
    assertNotNull(resource);
    assertTrue(resource.exists());
    return resource;
}
 
Example 28
Source Project: xds-ide   Source File: NewProjectCreator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static IProject createFromSources (NewProjectSettings settings) {
      final IProject project = createProject(settings.getProjectName(), settings.getProjectRoot());
      openProject(project);
      ExternalResourceManager.recreateExternalsFolder(project, new NullProgressMonitor());
      
      final XdsProjectSettings xdsProjectSettings = XdsProjectSettingsManager.getXdsProjectSettings(project);

      if (settings.getXdsProjectFile() != null) {
      	xdsProjectSettings.setProjectType(XdsProjectType.PROJECT_FILE);
      	xdsProjectSettings.setXdsProjectFile(ResourceUtils.getRelativePath(project, settings.getXdsProjectFile()));
      } else {
      	xdsProjectSettings.setProjectType(XdsProjectType.MAIN_MODULE);
      	xdsProjectSettings.setMainModule(ResourceUtils.getRelativePath(project, settings.getMainModule()));
      }

   xdsProjectSettings.setProjectSdk(settings.getProjectSdk());

      NatureUtils.addNature(project, NatureIdRegistry.MODULA2_SOURCE_PROJECT_NATURE_ID);
      
      ResourceUtils.scheduleWorkspaceRunnable(new IWorkspaceRunnable() {
    @Override
    public void run(IProgressMonitor monitor) throws CoreException {
        xdsProjectSettings.flush();
    }
}, project, Messages.NewProjectCreator_BuildingProject, false);
      
      return project;
  }
 
Example 29
Source Project: Pydev   Source File: InlineLocalTestCase.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void runTest() throws Throwable {
    FileUtils.IN_TESTS = true;

    IDocument document = new Document(data.source);
    ICoreTextSelection selection = new CoreTextSelection(document, data.sourceSelection.getOffset(),
            data.sourceSelection.getLength());
    RefactoringInfo info = new RefactoringInfo(document, selection, new IGrammarVersionProvider() {

        @Override
        public int getGrammarVersion() throws MisconfigurationException {
            return IGrammarVersionProvider.GRAMMAR_PYTHON_VERSION_2_7;
        }

        @Override
        public AdditionalGrammarVersionsToCheck getAdditionalGrammarVersions() throws MisconfigurationException {
            return null;
        }
    });
    InlineLocalRefactoring refactoring = new InlineLocalRefactoring(info);

    NullProgressMonitor monitor = new NullProgressMonitor();
    RefactoringStatus result = refactoring.checkAllConditions(monitor);

    assertTrue("Refactoring is not ok: " + result.getMessageMatchingSeverity(RefactoringStatus.WARNING),
            result.isOK());

    Change change = refactoring.createChange(monitor);
    change.perform(monitor);

    assertEquals(data.result, document.get());

    FileUtils.IN_TESTS = false;
}
 
Example 30
Source Project: neoscada   Source File: InfrastructureEditor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected void doSaveAs ( URI uri, IEditorInput editorInput )
{
    ( editingDomain.getResourceSet ().getResources ().get ( 0 ) ).setURI ( uri );
    setInputWithNotify ( editorInput );
    setPartName ( editorInput.getName () );
    IProgressMonitor progressMonitor = getActionBars ().getStatusLineManager () != null ? getActionBars ().getStatusLineManager ().getProgressMonitor () : new NullProgressMonitor ();
    doSave ( progressMonitor );
}