Java 类org.eclipse.xtext.util.StringInputStream 实例源码

项目:n4js    文件:EclipseBasedProjectModelSetup.java   
private void createManifest(String projectName, String string) throws CoreException, UnsupportedEncodingException {
    IProject project = workspace.getProject(projectName);
    IFile manifestFile = project.getFile(IN4JSProject.N4MF_MANIFEST);
    @SuppressWarnings("resource")
    StringInputStream content = new StringInputStream(string, Charsets.UTF_8.name());
    manifestFile.create(content, false, null);
    manifestFile.setCharset(Charsets.UTF_8.name(), null);

    IFolder src = project.getFolder("src");
    src.create(false, true, null);
    IFolder sub = src.getFolder("sub");
    sub.create(false, true, null);
    IFolder leaf = sub.getFolder("leaf");
    leaf.create(false, true, null);
    src.getFile("A.js").create(new ByteArrayInputStream(new byte[0]), false, null);
    src.getFile("B.js").create(new ByteArrayInputStream(new byte[0]), false, null);
    sub.getFile("B.js").create(new ByteArrayInputStream(new byte[0]), false, null);
    sub.getFile("C.js").create(new ByteArrayInputStream(new byte[0]), false, null);
    leaf.getFile("D.js").create(new ByteArrayInputStream(new byte[0]), false, null);
}
项目:n4js    文件:AbstractN4JSContentAssistTest.java   
/**
 * Creates a project with two files.
 */
@SuppressWarnings("resource")
@BeforeClass
public static void createTestProject() throws Exception {
    staticProject = ProjectUtils.createJSProject(PROJECT_NAME);
    IFolder path = staticProject.getFolder("src").getFolder("path");
    path.create(true, true, null);
    IFile libFile = path.getFile("Libs.n4js");
    libFile.create(new StringInputStream(
            "export public class MyFirstClass {} export public class MySecondClass {} class MyHiddenClass {}",
            libFile.getCharset()), true, monitor());
    IFile moreLibFile = path.getFile("MoreLibs.n4js");
    moreLibFile.create(new StringInputStream(
            "export public class MoreLibFirstClass {} export public class MoreLibSecondClass {}",
            moreLibFile.getCharset()), true, monitor());
    IFile testFile = path.getFile("Test.n4js");
    testFile.create(new StringInputStream("", testFile.getCharset()), true, monitor());
    addNature(staticProject, XtextProjectHelper.NATURE_ID);
    ProjectUtils.waitForAutoBuild();
}
项目:solidity-ide    文件:NewFileWizard.java   
@Override
public void addPages() {
    super.addPages();
    String fileExtension = fileExtensions.split("\\s*,\\s*")[0];
    mainPage = new WizardNewFileCreationPage("New File Page", getSelection()) {
        @Override
        protected InputStream getInitialContents() {
            NewFileTemplate template = new NewFileTemplate(this.getFileName().replace("."+fileExtension, ""), solidityVersion);

            return new StringInputStream(template.generate().toString());
        }
    };
    mainPage.setTitle("Solidity File");
    mainPage.setFileName("my_contract");
    mainPage.setFileExtension(fileExtension);
    addPage(mainPage);
}
项目:xtext-core    文件:ContentAssistContextTestHelper.java   
private XtextResource parse(final String doc) {
  try {
    String _primaryFileExtension = this.fileExtension.getPrimaryFileExtension();
    String _plus = ("dummy." + _primaryFileExtension);
    final URI uri = URI.createURI(_plus);
    Resource _createResource = this.resFactory.createResource(uri);
    final XtextResource res = ((XtextResource) _createResource);
    EList<Resource> _resources = new XtextResourceSet().getResources();
    _resources.add(res);
    if ((this.entryPoint != null)) {
      res.setEntryPoint(this.entryPoint);
    }
    StringInputStream _stringInputStream = new StringInputStream(doc);
    res.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    this.validator.assertNoErrors(res);
    return res;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目:xtext-core    文件:ManifestMergerTest.java   
@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");
    }
}
项目:xtext-core    文件:XtextValidationTest.java   
@Test
public void testBug322875_04() throws Exception {
    String testGrammarNsURI = "grammar foo.Bar with org.eclipse.xtext.common.Terminals\n " +
            " import 'http://www.eclipse.org/emf/2002/Ecore'  " +
            "Model returns EClass: name=ID;";
    String testGrammarPlatformPlugin = "grammar foo.Bar with org.eclipse.xtext.common.Terminals\n " +
            " import 'platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore'  " +
            "Model returns EClass: name=ID;";
    XtextResource resourceOk = getResourceFromString(testGrammarNsURI);
    XtextResource resourceOk2 = (XtextResource) resourceOk.getResourceSet().createResource(URI.createURI("unused.xtext"));
    resourceOk2.load(new StringInputStream(testGrammarPlatformPlugin), null);
    Diagnostic diagOK = Diagnostician.INSTANCE.validate(resourceOk.getContents().get(0));
    assertNotNull("diag", diagOK);
    assertEquals(diagOK.toString(), 0, diagOK.getChildren().size());
    diagOK = Diagnostician.INSTANCE.validate(resourceOk2.getContents().get(0));
    assertNotNull("diag", diagOK);
    assertEquals(diagOK.toString(), 0, diagOK.getChildren().size());
}
项目:xtext-core    文件:OffsetInformationTest.java   
@Test public void testCheckParsing() throws Exception {
    String string = "spielplatz 34 'holla' {\n"
        + "  kind (Horst 3)\n"
        + "  erwachsener (Julia 45)\n"
        + "  erwachsener (Herrmann 50)\n" 
        + "  erwachsener (Herrmann 50)\n" 
        + "  erwachsener (Herrmann 50)\n" 
        + "  erwachsener (Herrmann 50)\n" 
        + "  erwachsener (Herrmann 50)\n" 
        + "}";
    XtextResource resource = getResource(new StringInputStream(string));
    ICompositeNode rootNode = resource.getParseResult().getRootNode();

    for (int i=0;i<string.length()/2;i++) {
        String substring = string.substring(i, string.length()-i);
        resource.update(i, substring.length(), substring);
        ICompositeNode model = resource.getParseResult().getRootNode();
        new InvariantChecker().checkInvariant(model);
        assertSameStructure(rootNode, model);
    }

}
项目:xtext-core    文件:AbstractLiveContainerTest.java   
@Test
public void testContainerLoadUnload() throws Exception {
    ResourceSet resourceSet = new XtextResourceSet();
    Resource res = parse("local", resourceSet).eResource();
    Resource foo = resourceSet.createResource(computeUnusedUri(resourceSet));
    IResourceDescription resourceDescription = descriptionManager.getResourceDescription(res);
    IResourceDescriptions resourceDescriptions = descriptionsProvider.getResourceDescriptions(res);
    List<IContainer> containers = containerManager.getVisibleContainers(resourceDescription, resourceDescriptions);
    assertEquals(1, containers.size());
    IContainer container = containers.get(0);

    //      assertEquals("local", format(container.getExportedObjects()));

    foo.load(new StringInputStream("foo"), null);
    assertEquals("foo, local", format(container.getExportedObjects()));

    //      foo.unload();
    //      assertEquals("local", format(container.getExportedObjects()));
}
项目:xtext-core    文件:DefaultReferenceDescriptionTest.java   
@Test public void testgetReferenceDescriptions() throws Exception {
    with(new LangATestLanguageStandaloneSetup());
    XtextResource targetResource = getResource("type C", "bar.langatestlanguage");
    EObject typeC = targetResource.getContents().get(0).eContents().get(0);
    XtextResource resource = (XtextResource) targetResource.getResourceSet().createResource(URI.createURI("foo.langatestlanguage"));
    resource.load(new StringInputStream("type A extends C type B extends A"), null);
    EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
    IResourceDescription resDesc = resource.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(resource);
    Iterable<IReferenceDescription> descriptions = resDesc.getReferenceDescriptions();
    Collection<IReferenceDescription> collection = Lists.newArrayList(descriptions);
    assertEquals(1,collection.size());
    IReferenceDescription refDesc = descriptions.iterator().next();
    Main m = (Main) resource.getParseResult().getRootASTElement();
    assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc.getSourceEObjectUri(),false));
    assertEquals(typeC, resource.getResourceSet().getEObject(refDesc.getTargetEObjectUri(),false));
    assertEquals(-1,refDesc.getIndexInList());
    assertEquals(LangATestLanguagePackage.Literals.TYPE__EXTENDS,refDesc.getEReference());
}
项目:xtext-core    文件:DefaultReferenceDescriptionTest.java   
@Test public void testgetReferenceDescriptionForMultiValue() throws Exception {
    with(new LangATestLanguageStandaloneSetup());
    XtextResource targetResource = getResource("type C type D", "bar.langatestlanguage");
    EObject typeC = targetResource.getContents().get(0).eContents().get(0);
    EObject typeD = targetResource.getContents().get(0).eContents().get(1);
    XtextResource resource = (XtextResource) targetResource.getResourceSet().createResource(URI.createURI("foo.langatestlanguage"));
    resource.load(new StringInputStream("type A implements B,C,D type B"), null);
    EcoreUtil2.resolveLazyCrossReferences(resource, CancelIndicator.NullImpl);
    IResourceDescription resDesc = resource.getResourceServiceProvider().getResourceDescriptionManager().getResourceDescription(resource);
    Iterable<IReferenceDescription> descriptions = resDesc.getReferenceDescriptions();
    Collection<IReferenceDescription> collection = Lists.newArrayList(descriptions);
    assertEquals(2,collection.size());
    Iterator<IReferenceDescription> iterator = descriptions.iterator();
    IReferenceDescription refDesc1 = iterator.next();
    IReferenceDescription refDesc2 = iterator.next();
    Main m = (Main) resource.getParseResult().getRootASTElement();
    assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc1.getSourceEObjectUri(),false));
    assertEquals(typeC,resource.getResourceSet().getEObject(refDesc1.getTargetEObjectUri(),false));
    assertEquals(1,refDesc1.getIndexInList());
    assertEquals(LangATestLanguagePackage.Literals.TYPE__IMPLEMENTS,refDesc1.getEReference());
    assertEquals(m.getTypes().get(0),resource.getResourceSet().getEObject(refDesc2.getSourceEObjectUri(),false));
    assertEquals(typeD,resource.getResourceSet().getEObject(refDesc2.getTargetEObjectUri(),false));
    assertEquals(2,refDesc2.getIndexInList());
    assertEquals(LangATestLanguagePackage.Literals.TYPE__IMPLEMENTS,refDesc2.getEReference());
}
项目:xtext-core    文件:XtextGrammarReconcilationTest.java   
@Test public void testSimple() throws Exception {
    // this fails see bug #252181
    String model = "grammar foo with org.eclipse.xtext.common.Terminals Honolulu : name=ID;";

    // load grammar model
    XtextResourceSet rs = get(XtextResourceSet.class);
    Resource resource = rs.createResource(URI.createURI("foo.xtext"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
    resource.load(new StringInputStream(model), null);
    Grammar object = (Grammar) resource.getContents().get(0);

    // modify first rule
    object.getRules().get(0).setName("HONOLULU");

    // save
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    resource.save(out, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
    String result = new String(out.toByteArray());

    // check
    assertFalse(model.equals(result));
    String expectedModel = LineDelimiters.toPlatform("grammar foo with org.eclipse.xtext.common.Terminals\n\nHONOLULU:\n    name=ID;");
    assertEquals(expectedModel, result);
}
项目:xtext-core    文件:Bug302128Test.java   
@Test public void testTheBug2() throws Exception {
    with(new Bug302128TestLanguageStandaloneSetup());
    String text = "VARIABLE += value.val value2.val\n" 
            + "VARIABLE2 += value3.val value4.val\n\n"
            + "#Comment comment comment\n\n" 
            + "VARIABLE3 += value5.val value6.val\n"
            + "VARIABLE4 += value.val value2.val\n" 
            + "VARIABLE5 += value3.val value4.val\n\n" 
            + "#Comment comment comment\n\n" +
              "VARIABLE.varible += value5.val value6.val\n";
    XtextResource resource = getResource(new StringInputStream(text));
    Model model = (Model) resource.getContents().get(0);
    model.getElements().get(2).setValue("+= value5.val value6.val\n");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    resource.save(outputStream, null);
    assertEquals(text, new String(outputStream.toByteArray()));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@Test public void testImports() throws Exception {
    XtextResource resource = getResource(new StringInputStream("import foo.bar.* "), URI
            .createURI("import.indextestlanguage"));
    resource.getResourceSet().createResource(URI.createURI("foo.indextestlanguage")).load(
            new StringInputStream(
                    "foo.bar { " 
                    + "  entity Person {  " 
                    + "    String name " 
                    + "  } "
                    + "  datatype String " 
                    + "}"), null);

    IScope scope = scopeProvider.getScope(resource.getContents().get(0), IndexTestLanguagePackage.eINSTANCE
            .getFile_Elements());
    List<QualifiedName> names = toListOfNames(scope.getAllElements());
    assertEquals(names.toString(), 5, names.size());
    assertTrue(names.contains(nameConverter.toQualifiedName("Person")));
    assertTrue(names.contains(nameConverter.toQualifiedName("String")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.Person")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.String")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@Test public void testImports_02() throws Exception {
    XtextResource resource = getResource(new StringInputStream("import foo.* "), URI
            .createURI("import.indextestlanguage"));
    resource.getResourceSet().createResource(URI.createURI("foo.indextestlanguage")).load(
            new StringInputStream(
                    "foo.bar { " 
                    + "  entity Person {  " 
                    + "    String name " 
                    + "  } "
                    + "  datatype String " 
                    + "}"), null);

    IScope scope = scopeProvider.getScope(resource.getContents().get(0), IndexTestLanguagePackage.eINSTANCE
            .getFile_Elements());
    List<QualifiedName> names = toListOfNames(scope.getAllElements());
    assertEquals(names.toString(), 6, names.size());
    assertTrue(names.contains(nameConverter.toQualifiedName("bar.Person")));
    assertTrue(names.contains(nameConverter.toQualifiedName("bar.String")));
    assertTrue(names.contains(nameConverter.toQualifiedName("bar")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.Person")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.String")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@Test public void testImports_03() throws Exception {
    XtextResource resource = getResource(new StringInputStream("import foo.bar"), URI
            .createURI("import.indextestlanguage"));
    resource.getResourceSet().createResource(URI.createURI("foo.indextestlanguage")).load(
            new StringInputStream(
                    "foo.bar { " 
                    + "  entity Person {  " 
                    + "    String name " 
                    + "  } "
                    + "  datatype String " 
                    + "}"), null);

    IScope scope = scopeProvider.getScope(resource.getContents().get(0), IndexTestLanguagePackage.eINSTANCE
            .getFile_Elements());
    List<QualifiedName> names = toListOfNames(scope.getAllElements());
    assertEquals(names.toString(), 4, names.size());
    assertTrue(names.contains(nameConverter.toQualifiedName("bar")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.Person")));
    assertTrue(names.contains(nameConverter.toQualifiedName("foo.bar.String")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@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")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@Test public void testRelativePath() throws Exception {
    final XtextResource resource = getResource(new StringInputStream(
              "stuff { " 
            + "  import baz.*" 
            + "  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("String")));
    assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("baz.String")));
    assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("stuff.baz.String")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@Test public void testReexports2() throws Exception {
    final XtextResource resource = getResource(new StringInputStream(
              "A { " 
            + "  B { " 
            + "    entity D {}" + "  }"
            + "}" 
            + "E {" 
            + "  import A.B.*" 
            + "  entity D {}" 
            + "  datatype Context" 
            + "}"), URI
            .createURI("testReexports2.indextestlanguage"));
    Iterable<EObject> allContents = new Iterable<EObject>() {
        @Override
        public Iterator<EObject> iterator() {
            return resource.getAllContents();
        }
    };
    Datatype datatype = filter(allContents, Datatype.class).iterator().next();

    IScope scope = scopeProvider.getScope(datatype, IndexTestLanguagePackage.eINSTANCE.getProperty_Type());
    assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("D")));
    assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("E.D")));
    assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("A.B.D")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@Test public void testLocalElementsNotFromIndex() throws Exception {
    final XtextResource resource = getResource(new StringInputStream(
              "A { " 
            + "  B { " 
            + "    entity D {}" 
            + "  }"
            + "}" 
            + "E {" 
            + "  datatype Context" 
            + "}"), URI.createURI("foo23.indextestlanguage"));
    Iterable<EObject> allContents = new Iterable<EObject>() {
        @Override
        public Iterator<EObject> iterator() {
            return resource.getAllContents();
        }
    };
    Datatype datatype = filter(allContents, Datatype.class).iterator().next();
    IScope scope = scopeProvider.getScope(datatype, IndexTestLanguagePackage.eINSTANCE.getProperty_Type());
    assertNotNull(scope.getSingleElement(nameConverter.toQualifiedName("A.B.D")));
}
项目:xtext-core    文件:ImportedNamespaceAwareLocalScopeProviderTest.java   
@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")));
}
项目:xtext-core    文件:BasicLazyLinkingTest.java   
@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));
}
项目:xtext-core    文件:BasicLazyLinkingTest.java   
@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));
}
项目:xtext-core    文件:BasicLazyLinkingTest.java   
@Test public void testBug281775_02() throws Exception {
    String model = "type A {\n" +
            "  unresolved A B a;\n" +
            "}\n" +
            "type B {\n" +
            "  unresolved 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());

    UnresolvedProxyProperty propA = t1.getUnresolvedProxyProperty().get(0);
    assertEquals(2, propA.getType().size());
    assertEquals(t1, propA.getType().get(0));
    assertEquals(t2, propA.getType().get(1));

    UnresolvedProxyProperty propB = t2.getUnresolvedProxyProperty().get(0);
    assertEquals(2, propB.getType().size());
    assertEquals(t2, propB.getType().get(0));
    assertEquals(t1, propB.getType().get(1));
}
项目:xtext-core    文件:LazyLinkingResourceTest.java   
@Test public void testResolveLazyCrossReferences_02() throws Exception {
    with(lazyLinkingTestLangaugeSetup());
    ResourceSetImpl rs = new ResourceSetImpl();
    final Resource res1 = rs.createResource(URI.createURI("file1.lazylinkingtestlanguage"));
    Resource res2 = rs.createResource(URI.createURI("file2.lazylinkingtestlanguage"));
    res1.load(new StringInputStream("type Foo { } type Baz { Foo Bar prop; } }"), null);
    res2.load(new StringInputStream("type Bar { }"), null);
    res1.eAdapters().add(notificationAlert);

    Model m = (Model) res1.getContents().get(0);
    Type t = m.getTypes().get(1);
    Property p = t.getProperties().get(0);
    final InternalEList<Type> types = (InternalEList<Type>) p.getType();
    assertEquals(2, types.size());
    for (Iterator<Type> it = types.basicIterator(); it.hasNext();) {
        final Type tt = it.next();
        assertTrue(tt.eIsProxy());
    }
    ((LazyLinkingResource) res1).resolveLazyCrossReferences(CancelIndicator.NullImpl);
    assertFalse(types.basicGet(0).eIsProxy());
    assertTrue(types.basicGet(1).eIsProxy());
    res1.eAdapters().remove(notificationAlert);
    EcoreUtil.resolveAll(res1);
    assertFalse(types.basicGet(0).eIsProxy());
    assertFalse(types.basicGet(1).eIsProxy());
}
项目:xtext-core    文件:SetEntryPointOnXtextResourceTest.java   
@Test
public void test1() {
  try {
    this.with(ReferenceGrammarTestLanguageStandaloneSetup.class);
    final String model = "kind (Hugo 13)";
    final ParserRule kindRule = this.<ReferenceGrammarTestLanguageGrammarAccess>get(ReferenceGrammarTestLanguageGrammarAccess.class).getKindRule();
    final XtextResource resource = this.createResource();
    resource.setEntryPoint(kindRule);
    StringInputStream _stringInputStream = new StringInputStream(model);
    resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    Assert.assertTrue(resource.getErrors().isEmpty());
    Assert.assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
    final String originalNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
    resource.update(0, model.length(), ((" " + model) + " "));
    final String reparsedNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
    Assert.assertEquals(originalNodeModel, reparsedNodeModel);
    final ParserRule erwachsenerRule = this.<ReferenceGrammarTestLanguageGrammarAccess>get(ReferenceGrammarTestLanguageGrammarAccess.class).getErwachsenerRule();
    resource.setEntryPoint(erwachsenerRule);
    resource.update(0, model.length(), "erwachsener (Peter 30)");
    Assert.assertEquals(erwachsenerRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目:xtext-core    文件:Bug451668Test.java   
@Test
public void testUnloadAndGetContents() throws IOException {
  try {
    this.with(OptionalEmptyTestLanguageStandaloneSetup.class);
    Bug451668Test.TestResource r = this.<Bug451668Test.TestResource>get(Bug451668Test.TestResource.class);
    r.setURI(URI.createURI("foo.dummy"));
    StringInputStream _stringInputStream = new StringInputStream("");
    r.load(_stringInputStream, null);
    Assert.assertTrue(r.isLoaded());
    final int callsBeforeUnload = r.contentsCalls;
    r.unload();
    Assert.assertEquals(callsBeforeUnload, r.contentsCalls);
    Assert.assertFalse(r.isLoaded());
    Assert.assertNull(r.getParseResult());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目:dsl-devkit    文件:AcfContentAssistProcessorTestBuilder.java   
/**
 * {@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();
}
项目:openhab-hdl    文件:ScriptEngineImpl.java   
private XExpression parseScriptIntoXTextEObject(String scriptAsString) throws ScriptParsingException {
    Resource resource = resourceSet.createResource(computeUnusedUri(resourceSet)); // IS-A XtextResource
    try {
        resource.load(new StringInputStream(scriptAsString), resourceSet.getLoadOptions());
    } catch (IOException e) {
        throw new ScriptParsingException("Unexpected IOException; from close() of a String-based ByteArrayInputStream, no real I/O; how is that possible???", scriptAsString, e);
    }

    List<Diagnostic> errors = resource.getErrors();
    if (errors.size() != 0) {
        throw new ScriptParsingException("Failed to parse expression (due to managed SyntaxError/s)", scriptAsString).addDiagnosticErrors(errors);
    }

    EList<EObject> contents = resource.getContents();

    if (!contents.isEmpty()) {
        Iterable<Issue> validationErrors = getValidationErrors(contents.get(0));
        if(!validationErrors.iterator().hasNext()) {
            return (XExpression) contents.get(0);
        } else {
            throw new ScriptParsingException("Failed to parse expression (due to managed ValidationError/s)", scriptAsString).addValidationIssues(validationErrors);
        }
    } else {
        return null;
    }
}
项目:osate2-agcl    文件:AGCLUtil.java   
public static void saveFile(IFile file, String contents) {
    Logger.getLogger(AGCLUtil.class).debug("saving file '" + file.getName() + "'");
    StringInputStream source = new StringInputStream(contents);
    try {
        if (!file.exists()) {
            file.create(source, true, null);
        }
        else {
            file.setContents(source, true, true, null);
        }
    }
    catch (CoreException e) {
        Logger.getLogger(AGCLUtil.class).error("unable to save file '" + file.getName() + "'");
        e.printStackTrace();
    }
}
项目:n4js    文件:AbstractBuilderParticipantTest.java   
/***/
@SuppressWarnings("resource")
protected IFile doCreateTestFile(IFolder folder, String fullName, CharSequence content) throws CoreException {
    IFile file = folder.getFile(fullName);
    file.create(new StringInputStream(content.toString()), true, monitor());
    waitForAutoBuild();
    return file;
}
项目:n4js    文件:AbstractBuilderParticipantTest.java   
/**
 * Changes content of an existing file to the given {@link CharSequence}.
 */
@SuppressWarnings("resource")
protected IFile changeTestFile(IFile file, CharSequence newContent) throws CoreException {
    assertTrue("test file should exist", file.exists());
    file.setContents(new StringInputStream(newContent.toString()), true, true, monitor());
    return file;
}
项目:n4js    文件:AbstractSmokeTester.java   
private Script completeScript(String string) throws Exception {
    Resource resource = newResourceSet().createResource(URI.createURI("sample.js"));
    StringInputStream stream = new StringInputStream(string);
    try {
        resource.load(stream, null);
        Script script = (Script) resource.getContents().get(0);
        return script;
    } finally {
        stream.close();
    }
}
项目:n4js    文件:BuilderParticipantPluginTest.java   
/**
 *
 * 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);
}
项目:xtext-extras    文件:DebugAntlrGeneratorFragment.java   
/**
 * @since 2.7
 */
protected void prettyPrint(String absoluteGrammarFileName, Charset encoding) {
    try {
        String content = readFileIntoString(absoluteGrammarFileName, encoding);
        final ILineSeparatorInformation lineSeparatorInformation = new ILineSeparatorInformation() {
            @Override
            public String getLineSeparator() {
                return DebugAntlrGeneratorFragment.this.getLineDelimiter();
            }
        };
        Injector injector = new SimpleAntlrStandaloneSetup() {
            @Override
            public Injector createInjector() {
                return Guice.createInjector(new SimpleAntlrRuntimeModule() {
                    @Override
                    public void configure(Binder binder) {
                        super.configure(binder);
                        binder.bind(ILineSeparatorInformation.class).toInstance(lineSeparatorInformation);
                    }
                });
            }
        }.createInjectorAndDoEMFRegistration();
        XtextResource resource = injector.getInstance(XtextResource.class);
        resource.setURI(URI.createFileURI(absoluteGrammarFileName));
        resource.load(new StringInputStream(content, encoding.name()),
                Collections.singletonMap(XtextResource.OPTION_ENCODING, encoding.name()));
        if (!resource.getErrors().isEmpty()) {
            String errors = Joiner.on(getLineDelimiter()).join(resource.getErrors());
            throw new GeneratorWarning("Non fatal problem: Debug grammar could not be formatted due to:" + getLineDelimiter() + errors);
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(content.length());
        resource.save(outputStream, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
        String toBeWritten = new NewlineNormalizer(getLineDelimiter()).normalizeLineDelimiters(
                new String(outputStream.toByteArray(), encoding.name()));
        writeStringIntoFile(absoluteGrammarFileName, toBeWritten, encoding);
    } catch(IOException e) {
        throw new GeneratorWarning(e.getMessage());
    }
}
项目:xtext-extras    文件:EMFGeneratorFragment.java   
void updateBuildProperties(XpandExecutionContext ctx) throws Exception {
    if (!updateBuildProperties || modelPluginID != null)
        return;
    Outlet rootOutlet = ctx.getOutput().getOutlet(org.eclipse.xtext.generator.Generator.PLUGIN_RT);
    Outlet modelOutlet = ctx.getOutput().getOutlet(org.eclipse.xtext.generator.Generator.MODEL);
    String buildPropertiesPath = rootOutlet.getPath() + "/build.properties";
    String modelPath = modelOutlet.getPath().substring(rootOutlet.getPath().length() + 1) + "/";
    Properties buildProperties = new Properties();
    Reader reader = new InputStreamReader(new FileInputStream(new File(buildPropertiesPath)), Charset.forName(rootOutlet.getFileEncoding()));
    try {
        String existingContent = CharStreams.toString(reader);
        // for encodign details, see Properties.load
        buildProperties.load(new StringInputStream(existingContent, "ISO-8859-1"));
        String binIncludes = buildProperties.getProperty("bin.includes");
        boolean changed = false;
        if (binIncludes == null) {
            existingContent += "bin.includes = " + modelPath + Strings.newLine()+ "               ";
            changed = true;
        } else if (!binIncludes.contains(modelPath)) {
            existingContent = existingContent.replace("bin.includes = ", "bin.includes = " + modelPath + ",\\" + Strings.newLine() +"               ");
            changed = true;
        }
        if (changed) {
            Writer writer = new OutputStreamWriter(new FileOutputStream(new File(buildPropertiesPath)), Charset.forName(rootOutlet.getFileEncoding()));
            writer.write(existingContent);
            writer.close();
        }
    } finally {
        reader.close();
    }
}
项目:xtext-extras    文件:JvmModelTest.java   
@Override
protected Resource newResource(final CharSequence input) throws IOException {
  final XtextResourceSet resourceSet = this.resourceSetProvider.get();
  final Resource resource = resourceSet.createResource(URI.createURI("Test.___xbase"));
  String _string = input.toString();
  StringInputStream _stringInputStream = new StringInputStream(_string);
  resource.load(_stringInputStream, null);
  return resource;
}
项目:xtext-core    文件:InMemoryFileSystemAccess.java   
/**
 * @since 2.4
 */
@Override
public InputStream readBinaryFile(String fileName, String outputCfgName) throws RuntimeIOException {
    String name = getFileName(fileName, outputCfgName);
    Object contents = files.get(name);
    if (contents == null)
        throw new RuntimeIOException("File not found: " + name);
    if (contents instanceof byte[])
        return new ByteArrayInputStream((byte[]) contents);
    if (contents instanceof CharSequence)
        return new StringInputStream(contents.toString());
    throw new RuntimeIOException("Unknown File Data Type: " + contents.getClass() + " File: " + name);
}
项目:xtext-core    文件:CodeActionService.java   
private WorkspaceEdit recordWorkspaceEdit(final Document doc, final XtextResource resource, final IChangeSerializer.IModification<Resource> mod) {
  try {
    final XtextResourceSet rs = new XtextResourceSet();
    final Resource copy = rs.createResource(resource.getURI());
    String _text = resource.getParseResult().getRootNode().getText();
    StringInputStream _stringInputStream = new StringInputStream(_text);
    copy.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
    this.serializer.<Resource>addModification(copy, mod);
    final ArrayList<IEmfResourceChange> documentchanges = CollectionLiterals.<IEmfResourceChange>newArrayList();
    this.serializer.applyModifications(CollectionBasedAcceptor.<IEmfResourceChange>of(documentchanges));
    WorkspaceEdit _workspaceEdit = new WorkspaceEdit();
    final Procedure1<WorkspaceEdit> _function = (WorkspaceEdit it) -> {
      Iterable<ITextDocumentChange> _filter = Iterables.<ITextDocumentChange>filter(documentchanges, ITextDocumentChange.class);
      for (final ITextDocumentChange documentchange : _filter) {
        {
          final Function1<ITextReplacement, TextEdit> _function_1 = (ITextReplacement replacement) -> {
            TextEdit _textEdit = new TextEdit();
            final Procedure1<TextEdit> _function_2 = (TextEdit it_1) -> {
              it_1.setNewText(replacement.getReplacementText());
              Position _position = doc.getPosition(replacement.getOffset());
              Position _position_1 = doc.getPosition(replacement.getEndOffset());
              Range _range = new Range(_position, _position_1);
              it_1.setRange(_range);
            };
            return ObjectExtensions.<TextEdit>operator_doubleArrow(_textEdit, _function_2);
          };
          final List<TextEdit> edits = ListExtensions.<ITextReplacement, TextEdit>map(documentchange.getReplacements(), _function_1);
          it.getChanges().put(documentchange.getNewURI().toString(), edits);
        }
      }
    };
    return ObjectExtensions.<WorkspaceEdit>operator_doubleArrow(_workspaceEdit, _function);
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目:xtext-core    文件:ResourceValidatorImplTest.java   
@Test public void testLinkingError() throws Exception {
    XtextResource resource = getResourceAndExpect(new StringInputStream("type foo extends Bar"), 1);
    List<Issue> list = getValidator().validate(resource, CheckMode.NORMAL_AND_FAST, null);
    assertEquals(1,list.size());
    assertTrue(!list.get(0).isSyntaxError());
    assertEquals(org.eclipse.xtext.diagnostics.Diagnostic.LINKING_DIAGNOSTIC, list.get(0).getCode());
}
项目:xtext-core    文件:ResourceValidatorImplTest.java   
@Test public void testSemanticError() throws Exception {
    XtextResource resource = getResourceAndExpect(new StringInputStream("type Foo"), 0);
    List<Issue> list = getValidator().validate(resource, CheckMode.NORMAL_AND_FAST, null);
    assertEquals(1,list.size());
    assertFalse(list.get(0).isSyntaxError());
    assertEquals(Severity.ERROR, list.get(0).getSeverity());
}