org.eclipse.xtext.util.StringInputStream Java Examples

The following examples show how to use org.eclipse.xtext.util.StringInputStream. 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: ManifestMerger2Test.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSplit512Length() throws Exception {
	String packageName = getClass().getPackage().getName().replace('.', '/');
	InputStream resourceAsStream = getClass().getResourceAsStream("/" + packageName + "/Test_Manifest.MF");
	MergeableManifest2 manifest = new MergeableManifest2(resourceAsStream);
	char[] buff = new char[712];
	Arrays.fill(buff, 'c');
	manifest.addExportedPackages(Collections.singleton(new String(buff)));
	assertTrue(manifest.isModified());
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	manifest.write(out);
	String result = out.toString();
	try {
		new Manifest(new StringInputStream(result));
	} catch (Exception e) {
		fail("long line has not been splitted into chunks");
	}
}
 
Example #2
Source File: ProfilerAbstractBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testIncrementalBuildWithBigLibraryFile() throws Exception {
	IJavaProject project = workspace.createJavaProject("foo");
	workspace.addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	int NUM_OBJECTS = 40000;
	StopWatch timer = new StopWatch();
	IFile file = folder.getFile("Test_Library" + F_EXT);
	String contents = "namespace x { ";
	for (int i = 0; i < NUM_OBJECTS; i++) {
		contents += " object Foo" + i;
	}
	contents+="}";
	file.create(new StringInputStream(contents), true, workspace.monitor());
	logAndReset("Creating files", timer);
	workspace.build();
	for (int i =0;i<5;i++) {
		IFile f = folder.getFile("Referencing_"+i+F_EXT);
		logAndReset("Creating library file", timer);
		f.create(new StringInputStream("object Bar"+i+" references x.Foo1"), true, null);
		logAndReset("Auto build", timer);
		workspace.build();
	}
}
 
Example #3
Source File: ImportedNamespaceAwareLocalScopeProviderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testRelativeContext() throws Exception {
	final XtextResource resource = getResource(new StringInputStream(
			  "stuff { " 
			+ "  baz { "
			+ "    datatype String " 
			+ "  } " 
			+ "  entity Person {}" 
			+ "}"), URI
			.createURI("relative.indextestlanguage"));
	Iterable<EObject> allContents = new Iterable<EObject>() {
		@Override
		public Iterator<EObject> iterator() {
			return resource.getAllContents();
		}
	};
	Entity entity = filter(allContents, Entity.class).iterator().next();

	IScope scope = scopeProvider.getScope(entity, IndexTestLanguagePackage.eINSTANCE.getProperty_Type());
	assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("baz.String")));
	assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("stuff.baz.String")));
}
 
Example #4
Source File: ProfilerAbstractBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testFullBuildBigProjectWithRefeernceToJar() throws Exception {
	IJavaProject project = workspace.createJavaProject("foo");
	workspace.addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile jarFile = project.getProject().getFile("my.jar");
	jarFile.create(jarInputStream(new TextFile("my/element"+F_EXT,"object ReferenceMe")), true, workspace.monitor());
	workspace.addJarToClasspath(project, jarFile);
	
	int NUM_FILES = 2000;
	IFile[] files = new IFile[NUM_FILES];
	StopWatch timer = new StopWatch();
	for (int i = 0; i < NUM_FILES; i++) {
		IFile file = folder.getFile("Test_" + i + "_" + F_EXT);
		files[i] = file;
		String contents = "object Foo" + i + " references ReferenceMe";
		file.create(new StringInputStream(contents), true, workspace.monitor());
	}
	logAndReset("Creating files", timer);
	workspace.build();
	logAndReset("Auto build", timer);
	IMarker[] iMarkers = folder.findMarkers(EValidator.MARKER, true, IResource.DEPTH_INFINITE);
	for (IMarker iMarker : iMarkers) {
		System.out.println(iMarker.getAttribute(IMarker.MESSAGE));
	}
	assertEquals(0,iMarkers.length);
}
 
Example #5
Source File: Bug355821Test.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBuildIsInvokedOnlyOnceWhenManifestChanges() throws Exception {
		IProject fooProject = createPluginProject("Foo");
		build();
		
		IFile manifestFile = fooProject.getFile("META-INF/MANIFEST.MF");
		String manifestContent = "Manifest-Version: 1.0\n";
		manifestContent += "Bundle-ManifestVersion: 2\n";
		manifestContent += "Bundle-Name: Foo\n";
		manifestContent += "Bundle-SymbolicName: Foo; ";
		manifestContent +=	 "singleton:=true\n";
		manifestContent += "Bundle-Version: 1.0.0.qualifier\n";
		manifestContent += "Require-Bundle: org.eclipse.xtext,\n";
		// Add a dependency to change classpath
		manifestContent += " org.eclipse.core.runtime\n";
		manifestContent += "Bundle-ActivationPolicy: lazy\n";
		// Remove this one implies a change of build.properties
//		manifestContent += "Bundle-RequiredExecutionEnvironment: JavaSE-1.8\n";
		reset();
		manifestFile.setContents(new StringInputStream(manifestContent), true, true, monitor());
		build();
		assertEquals(1, getInvocationCount());
	}
 
Example #6
Source File: AcfContentAssistProcessorTestBuilder.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc} Code copied from parent. Override required to run in UI because of getSourceViewer, which creates a new Shell.
 */
@Override
public ICompletionProposal[] computeCompletionProposals(final String currentModelToParse, final int cursorPosition) throws Exception {
  Pair<ICompletionProposal[], BadLocationException> result = UiThreadDispatcher.dispatchAndWait(new Function<Pair<ICompletionProposal[], BadLocationException>>() {
    @Override
    public Pair<ICompletionProposal[], BadLocationException> run() {
      final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
      final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
      return internalComputeCompletionProposals(cursorPosition, xtextDocument);
    }
  });
  if (result.getSecond() != null) {
    throw result.getSecond();
  }
  return result.getFirst();
}
 
Example #7
Source File: ManifestMergerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSplit512Length() throws Exception {
	String packageName = getClass().getPackage().getName().replace('.', '/');
	InputStream resourceAsStream = getClass().getResourceAsStream("/" + packageName + "/Test_Manifest.MF");
	MergeableManifest manifest = new MergeableManifest(resourceAsStream);
	char[] buff = new char[712];
	Arrays.fill(buff, 'c');
	manifest.addExportedPackages(Collections.singleton(new String(buff)));
	assertTrue(manifest.isModified());
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	manifest.write(out);
	String result = out.toString();
	try {
		new Manifest(new StringInputStream(result));
	} catch(Exception e) {
		fail("long line has not been splitted into chunks");
	}
}
 
Example #8
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public ContentAssistProcessorTestBuilder assertMatchString(String matchString)
		throws Exception {
	String currentModelToParse = getModel();
	final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
	final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
	XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
	Shell shell = new Shell();
	try {
		ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
		IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
		String contentType = xtextDocument.getContentType(currentModelToParse.length());
		if (contentAssistant.getContentAssistProcessor(contentType) != null) {
			ContentAssistContext.Factory factory = get(ContentAssistContext.Factory.class);
			ContentAssistContext[] contexts = factory.create(sourceViewer, currentModelToParse.length(), xtextResource);
			for(ContentAssistContext context: contexts) {
				Assert.assertTrue("matchString = '" + matchString + "', actual: '" + context.getPrefix() + "'",
						"".equals(context.getPrefix()) || matchString.equals(context.getPrefix()));
			}
		} else {
			Assert.fail("No content assistant for content type " + contentType);
		}
		return this;
	} finally {
		shell.dispose();
	}
}
 
Example #9
Source File: ImportedNamespaceAwareLocalScopeProviderTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testResourceSetReferencingResourceSet2() throws Exception {
	ResourceSetReferencingResourceSetImpl rs = new ResourceSetReferencingResourceSetImpl();
	Resource res = rs.createResource(URI.createURI("file2.indextestlanguage"));
	res.load(new StringInputStream("bar {" + "  entity Bar{}" + "}"), null);

	ResourceSetReferencingResourceSetImpl rs1 = new ResourceSetReferencingResourceSetImpl();
	rs1.getReferencedResourceSets().add(rs);
	final Resource res1 = rs1.createResource(URI.createURI("file1.indextestlanguage"));
	res1.load(new StringInputStream("foo { " + "  import bar.Bar" + "  entity Foo {" + "  }" + "}"), null);

	ResourceSetReferencingResourceSetImpl rs2 = new ResourceSetReferencingResourceSetImpl();
	rs2.getReferencedResourceSets().add(rs1);
	final Resource res2 = rs2.createResource(URI.createURI("file2.indextestlanguage"));
	res2.load(new StringInputStream("baz {" + "  entity Baz{}" + "}"), null);

	Entity baz = getEntityByName(res2,"Baz");

	IScope scope = scopeProvider.getScope(baz, IndexTestLanguagePackage.eINSTANCE.getProperty_Type());
	assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("foo.Foo")));
	assertNull(scope.getSingleElement(nameConverter.toQualifiedName("bar.Bar")));
}
 
Example #10
Source File: DirtyStateResourceDescriptionTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
public XtextResource parse(final String fileName, final CharSequence model) {
  try {
    XtextResource _xblockexpression = null;
    {
      final XtextResourceSet rs = this.resourceSetProvider.get();
      Resource _createResource = rs.createResource(URI.createURI((fileName + ".xtend")));
      final XtextResource r = ((XtextResource) _createResource);
      String _string = model.toString();
      StringInputStream _stringInputStream = new StringInputStream(_string);
      r.load(_stringInputStream, Collections.<Object, Object>unmodifiableMap(CollectionLiterals.<Object, Object>newHashMap()));
      _xblockexpression = r;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #11
Source File: LiveShadowedAllContainerStateTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testInMemoryResourceWithoutProject() {
  try {
    final XtextResourceSet rs = new XtextResourceSet();
    rs.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE);
    String _primaryFileExtension = this._fileExtensionProvider.getPrimaryFileExtension();
    String _plus = ("myproject/myfile." + _primaryFileExtension);
    final Resource resource = rs.createResource(URI.createPlatformResourceURI(_plus, true));
    StringInputStream _stringInputStream = new StringInputStream("stuff foo");
    resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("container myproject isEmpty=false {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("resourceURI=platform:/resource/myproject/myfile.testlanguage exported=[foo]");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final String expected = _builder.toString();
    Assert.assertEquals(expected, this.formatContainers(rs));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #12
Source File: WorkspaceFileGenerator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException {
	SubMonitor subMonitor = SubMonitor.convert(monitor, files.size());
	try {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		for (Map.Entry<String, CharSequence> fileEntry : files.entrySet()) {
			IFile file = workspace.getRoot().getFile(new Path(fileEntry.getKey()));
			file.create(new StringInputStream(fileEntry.getValue().toString()), true, subMonitor);
			if (firstFile == null) {
				firstFile = file;
			}
			subMonitor.worked(1);
		}
	} finally {
		subMonitor.done();
	}
}
 
Example #13
Source File: SourceBasedJdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testClassAnnotationValue_07() throws Exception {
	IJavaProject project = projectProvider.getJavaProject(null);
	String typeName = EmptyAbstractClass.class.getName();
	IFile javaFile = (IFile) project.getProject().findMember(new Path("src/" + typeName.replace('.', '/') + ".java"));
	assertNotNull(javaFile);
	String content = Files.readStreamIntoString(javaFile.getContents());
	try {
		String newContent = content.replace(
				"public abstract ", 
				"@SimpleAnnotation( type = DoesNotExist.class ) public abstract ");
		javaFile.setContents(new StringInputStream(newContent), IResource.NONE, new NullProgressMonitor());
		
		JvmDeclaredType type = (JvmDeclaredType) getTypeProvider().findTypeByName(typeName);
		List<JvmAnnotationReference> annotations = type.getAnnotations();
		assertEquals(1, annotations.size());
		JvmAnnotationReference annotation = annotations.get(0);
		assertEquals(1, annotation.getExplicitValues().size());
		JvmAnnotationValue value = annotation.getExplicitValues().get(0);
		assertTrue(value instanceof JvmTypeAnnotationValue);
		assertTrue(((JvmTypeAnnotationValue) value).getValues().isEmpty());
	} finally {
		javaFile.setContents(new StringInputStream(content), IResource.NONE, new NullProgressMonitor());
	}
}
 
Example #14
Source File: BasicLazyLinkingTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug281775_01() throws Exception {
	String model = "type A {\n" +
			"  A B a;\n" +
			"}\n" +
			"type B {\n" +
			"  B A b;\n" +
			"}";
	XtextResource resource = getResource(new StringInputStream(model));
	Model m = (Model) resource.getContents().get(0);
	Type t1 = m.getTypes().get(0);
	assertEquals("A", t1.getName());
	Type t2 = m.getTypes().get(1);
	assertEquals("B", t2.getName());
	
	Property propA = t1.getProperties().get(0);
	assertEquals(2, propA.getType().size());
	assertEquals(t1, propA.getType().get(0));
	assertEquals(t2, propA.getType().get(1));
	
	Property propB = t2.getProperties().get(0);
	assertEquals(2, propB.getType().size());
	assertEquals(t2, propB.getType().get(0));
	assertEquals(t1, propB.getType().get(1));
}
 
Example #15
Source File: EclipseResourceFileSystemAccess2Test.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testMarkNotSupported() throws Exception {
	fsa.generateFile("tmp/bar", new StringInputStream("you should never see this"));
	InputStream input = new StringInputStream("foo") {
		@Override
		public boolean markSupported() {
			return false;
		}
		@Override
		public synchronized void reset() {
			throw new RuntimeIOException("mark/reset not supported");
		}
	};
	fsa.generateFile("tmp/bar", input);
	IFolder dir = project.getFolder("src-gen/tmp");
	assertTrue(dir.exists());
	IFile file = dir.getFile("bar");
	assertTrue(file.exists());
	assertEquals("foo", fsa.readTextFile("tmp/bar"));
}
 
Example #16
Source File: EclipseResourceFileSystemAccess2.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void generateFile(String fileName, String outputName, CharSequence contents) {
	if (monitor.isCanceled())
		throw new OperationCanceledException();
	OutputConfiguration outputConfig = getOutputConfig(outputName);

	if (!ensureOutputConfigurationDirectoryExists(outputConfig))
		return;

	IFile file = getFile(fileName, outputName);
	if (file == null)
		return;
	IFile traceFile = getTraceFile(file);
	try {
		String encoding = getEncoding(file);
		CharSequence postProcessedContent = postProcess(fileName, outputName, contents, encoding);
		String contentsAsString = postProcessedContent.toString();
		StringInputStream newContent = getInputStream(contentsAsString, encoding);
		generateFile(file, newContent, traceFile, postProcessedContent, outputConfig);
	} catch (CoreException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example #17
Source File: BuilderParticipantTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateIntoProjectOutputDirectory() throws Exception {
	IJavaProject project = createJavaProject("testGenerateIntoProjectOutputDirectory");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	preferenceStoreAccess.getWritablePreferenceStore(project.getProject()).setValue(getDefaultOutputDirectoryKey(),
			"./");
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	IFile generatedFile = project.getProject().getFile("./Foo.txt");
	assertTrue(generatedFile.exists());
	preferenceStoreAccess.getWritablePreferenceStore(project.getProject()).setValue(getDefaultOutputDirectoryKey(),
			".");
	file = folder.getFile("Bar" + F_EXT);
	file.create(new StringInputStream("object Bar"), true, monitor());
	build();
	generatedFile = project.getProject().getFile("./Bar.txt");
	assertTrue(generatedFile.exists());
}
 
Example #18
Source File: BuilderParticipantTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGenerateIntoDifferentOutputFolders() throws Exception {
	IJavaProject project = createJavaProject("testGenerateIntoDifferentOutputFolders");
	addSourceFolder(project, "other-src");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IPreferenceStore preferences = preferenceStoreAccess.getWritablePreferenceStore(project.getProject());
	preferences.setValue(getUseOutputPerSourceFolderKey(), "true");
	preferences.setValue(getOutputForSourceFolderKey("other-src"), "other-gen");

	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());

	folder = project.getProject().getFolder("other-src");
	file = folder.getFile("Bar" + F_EXT);
	file.create(new StringInputStream("object Bar"), true, monitor());

	build();
	IFile generatedFile = project.getProject().getFile("src-gen/Foo.txt");
	assertTrue(generatedFile.exists());
	generatedFile = project.getProject().getFile("other-gen/Bar.txt");
	assertTrue(generatedFile.exists());
}
 
Example #19
Source File: BuilderParticipantTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCleanUpDerivedResources() throws Exception {
	IJavaProject project = createJavaProject("foo");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	IFile generatedFile = project.getProject().getFile("./src-gen/Foo.txt");
	assertTrue(generatedFile.exists());
	preferenceStoreAccess.getWritablePreferenceStore(project.getProject()).setValue(getDefaultOutputDirectoryKey(),
			"./src2-gen");

	DerivedResourceCleanerJob derivedResourceCleanerJob = derivedResourceCleanerJobProvider.get();
	derivedResourceCleanerJob.setUser(true);
	derivedResourceCleanerJob.initialize(project.getProject(), "src-gen");
	derivedResourceCleanerJob.schedule();
	derivedResourceCleanerJob.join();
	generatedFile = project.getProject().getFile("./src-gen/Foo.txt");
	assertFalse(generatedFile.exists());
	file.touch(monitor());
	build();
	generatedFile = project.getProject().getFile("./src2-gen/Foo.txt");
	assertTrue(generatedFile.exists());
}
 
Example #20
Source File: BuilderParticipantTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testClean() throws Exception {
	IJavaProject project = createJavaProject("foo");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	IFile generatedFile = project.getProject().getFile("./src-gen/Foo.txt");
	assertTrue(generatedFile.exists());
	assertTrue(generatedFile.isDerived());
	assertTrue(generatedFile.findMarkers(DerivedResourceMarkers.MARKER_ID, false, IResource.DEPTH_ZERO).length == 1);
	assertEquals("object Foo", readFile(generatedFile).trim());
	disableAutobuild(()->{
		cleanBuild();
		assertFalse(generatedFile.exists());	
	});
}
 
Example #21
Source File: XtendLibClasspathAdderTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testAddToBrokenPlugin() throws Exception {
	pluginProjectFactory.setProjectName("test");
	pluginProjectFactory.addFolders(Collections.singletonList("src"));
	pluginProjectFactory.addBuilderIds(JavaCore.BUILDER_ID, "org.eclipse.pde.ManifestBuilder",
			"org.eclipse.pde.SchemaBuilder", XtextProjectHelper.BUILDER_ID);
	pluginProjectFactory.addProjectNatures(JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature",
			XtextProjectHelper.NATURE_ID);
	IProject project = pluginProjectFactory.createProject(null, null);
	IJavaProject javaProject = JavaCore.create(project);
	JavaProjectSetupUtil.makeJava8Compliant(javaProject);
	project.findMember("META-INF").delete(true, null);
	IFile file = project.getFile("src/Foo.xtend");
	file.create(new StringInputStream("import org.eclipse.xtend.lib.annotations.Accessors class Foo { @Accessors int bar }"),
			true, null);
	syncUtil.waitForBuild(null);
	markerAssert.assertErrorMarker(file, IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH);
	adder.addLibsToClasspath(javaProject, null);
	waitForAutoBuild();
	syncUtil.waitForBuild(null);
	markerAssert.assertNoErrorMarker(file);
}
 
Example #22
Source File: ContentAssistProcessorTestBuilder.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public ContentAssistProcessorTestBuilder assertMatchString(String matchString)
		throws Exception {
	String currentModelToParse = getModel();
	final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse, getEncoding()));
	final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
	XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
	Shell shell = new Shell();
	try {
		ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
		IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
		String contentType = xtextDocument.getContentType(currentModelToParse.length());
		if (contentAssistant.getContentAssistProcessor(contentType) != null) {
			ContentAssistContext.Factory factory = get(ContentAssistContext.Factory.class);
			ContentAssistContext[] contexts = factory.create(sourceViewer, currentModelToParse.length(), xtextResource);
			for(ContentAssistContext context: contexts) {
				Assert.assertTrue("matchString = '" + matchString + "', actual: '" + context.getPrefix() + "'",
						"".equals(context.getPrefix()) || matchString.equals(context.getPrefix()));
			}
		} else {
			Assert.fail("No content assistant for content type " + contentType);
		}
		return this;
	} finally {
		shell.dispose();
	}
}
 
Example #23
Source File: AbstractQuickfixTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected XtextResource getXtextResource(String model) {
	StringInputStream in = new StringInputStream(Strings.emptyIfNull(model));
	URI uri = URI.createURI(""); // creating an in-memory EMF Resource

	ResourceSet resourceSet = resourceSetProvider.get(project);
	Resource resource = injector.getInstance(IResourceFactory.class).createResource(uri);
	resourceSet.getResources().add(resource);

	try {
		resource.load(in, null);
		if (resource instanceof LazyLinkingResource) {
			((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
		} else {
			EcoreUtil.resolveAll(resource);
		}
		return (XtextResource) resource;
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #24
Source File: SetEntryPointOnXtextResourceTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void test1() throws Exception {
	with(ReferenceGrammarTestLanguageStandaloneSetup.class);
	String model = "kind (Hugo 13)";
	ParserRule kindRule = get(ReferenceGrammarTestLanguageGrammarAccess.class).getKindRule();
	XtextResource resource = createResource();
	// test 1: parse and assume there are no errors
	resource.setEntryPoint(kindRule);
	resource.load(new StringInputStream(model), Collections.emptyMap());
	Assert.assertTrue(resource.getErrors().isEmpty());
	Assert.assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
	// test 2: update and assume node model does not change
	String originalNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
	resource.update(0, model.length(), " " + model + " ");
	String reparsedNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
	Assert.assertEquals(originalNodeModel, reparsedNodeModel);
	// test 3: change parser rule
	ParserRule erwachsenerRule = get(ReferenceGrammarTestLanguageGrammarAccess.class).getErwachsenerRule();
	resource.setEntryPoint(erwachsenerRule);
	resource.update(0, model.length(), "erwachsener (Peter 30)");
	Assert.assertEquals(erwachsenerRule,
			NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
}
 
Example #25
Source File: BasicLazyLinkingTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testLazyMultiRefDuplicates() throws Exception {
	XtextResource resource = getResource(new StringInputStream("type A {} type B { A B A a; }"));
	Model m = (Model) resource.getContents().get(0);
	Type t1 = m.getTypes().get(0);
	Type t2 = m.getTypes().get(1);
	
	Property property = t2.getProperties().get(0);
	EList<Type> types = property.getType();
	assertEquals(t1, types.get(0));
	assertEquals(t2, types.get(1));
	assertEquals(t1, types.get(2));
	
	assertEquals(t1, types.get(0));
	assertEquals(t2, types.get(1));
	assertEquals(t1, types.get(2));
}
 
Example #26
Source File: IntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testDeleteFile() throws Exception {
	IJavaProject project = createJavaProject("foo");
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	assertTrue(indexContainsElement(file.getFullPath().toString(), "Foo"));
	assertEquals(1, countResourcesInIndex());

	getBuilderState().addListener(this);
	file.delete(true, monitor());
	build();
	assertEquals(1, getEvents().get(0).getDeltas().size());
	assertNull(getEvents().get(0).getDeltas().get(0).getNew());
	assertEquals(0, countResourcesInIndex());
}
 
Example #27
Source File: IntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test public void testModelWithSyntaxErrorInDerivedFolder() throws Exception {
	IJavaProject javaProject = createJavaProjectWithRootSrc("foo");
	IProject project = javaProject.getProject();
	IFolder folder = project.getFolder("non-src");
	folder.create(true, true, monitor());
	folder.setDerived(true);
	IFile file = createFile("foo/non-src/foo" + F_EXT, "objekt Foo ");
	file.setDerived(true);
	build();
	assertEquals(1, countMarkers(file));
	file.setContents(new StringInputStream("object Foo"), true, true, monitor());
	assertTrue(file.isDerived());
	build();
	assertEquals(0, countMarkers(file));
}
 
Example #28
Source File: ProfilerAbstractBuilderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testFullBuildBigProject() throws Exception {
	IJavaProject project = workspace.createJavaProject("foo");
	workspace.addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	IFolder folder = project.getProject().getFolder("src");
	int NUM_FILES = 200;
	IFile[] files = new IFile[NUM_FILES];
	StopWatch timer = new StopWatch();
	for (int i = 0; i < NUM_FILES; i++) {
		IFile file = folder.getFile("Test_" + i + "_" + F_EXT);
		files[i] = file;
		String contents = "object Foo" + i + " references Foo" + (i + 1);
		if (i == NUM_FILES)
			contents = "object Foo" + i;
		file.create(new StringInputStream(contents), true, workspace.monitor());
	}
	logAndReset("Creating files", timer);
	workspace.build();
	logAndReset("Auto build", timer);
}
 
Example #29
Source File: Bug386476Test.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private IFile createSomeBuilderRelatedFile(IProject project) throws CoreException {
	IFolder folder = project.getProject().getFolder("src");
	IFile file = folder.getFile("Foo" + F_EXT);
	file.create(new StringInputStream("object Foo"), true, monitor());
	build();
	return file;
}
 
Example #30
Source File: BuilderParticipantPluginTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 *
 * 01. MyClassOne import MyVariableTwo, calls in chain
 * 01a. method of variable type (MyClassTwo),
 * 01b. method of type of this variable type method (MyRoleThree),
 * 01c. MyRoleThree method (typed with MyInterfaceFour)
 * 01d. finally a MyInterfaceFour's method
 * 02. Creating files in an order that there are initial error markers as required files are not created yet
 * 03. When all files have been created no file should have error markers
 *
 * @throws Exception when creating resources fails
 */
@SuppressWarnings("resource")
//@formatter:on
@Test
public void testRenamingMethodAccessedViaSubclass() throws Exception {
	final IProject project = createJSProject("testRenamingMethodAccessedViaSubclass");
	IFolder folder = configureProjectWithXtext(project);
	IFolder moduleFolder = createFolder(folder, TransitiveInheritMemberTestFiles.moduleFolder());

	IFile fileC = createTestFile(moduleFolder, "C", TransitiveInheritMemberTestFiles.C());
	IFile fileB = createTestFile(moduleFolder, "B", TransitiveInheritMemberTestFiles.B());
	IFile fileA = createTestFile(moduleFolder, "A", TransitiveInheritMemberTestFiles.A());
	waitForAutoBuild();

	assertMarkers("File A should have no errors", fileA, 0);
	assertMarkers("File B should have no errors", fileB, 0);
	assertMarkers("File C should have no errors", fileC, 0);

	fileC.setContents(new StringInputStream(TransitiveInheritMemberTestFiles.CChanged().toString()),
			true,
			true,
			monitor());
	waitForAutoBuild();

	assertMarkers("File A with other missing method name in chain should have errors", fileA,
			1);
	assertMarkers("File B should have no errors", fileB, 0);
	assertMarkers("File C should have no errors", fileC, 0);

	fileC.setContents(new StringInputStream(TransitiveInheritMemberTestFiles.C().toString()),
			true,
			true,
			monitor());
	waitForAutoBuild();

	assertMarkers("File A with old method name in chain should have no errors", fileA, 0);
}