Java 类org.eclipse.xtext.resource.XtextResourceSet 实例源码

项目:n4js    文件:N4HeadlessCompiler.java   
/**
 * Creates the common resource set to use during compilation. Installs a light weight index.
 *
 * @return the resource set
 */
private ResourceSet createResourceSet() {
    // TODO try to reuse code from IN4JSCore.createResourceSet

    XtextResourceSet resourceSet = xtextResourceSetProvider.get();
    resourceSet.setClasspathURIContext(classLoader);

    // Install containerState as adapter.
    resourceSet.eAdapters().add(new DelegatingIAllContainerAdapter(rsbAcs));

    // Install a lightweight index.
    OrderedResourceDescriptionsData index = new OrderedResourceDescriptionsData(Collections.emptyList());
    ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(resourceSet, index);

    return resourceSet;
}
项目:n4js    文件:ManifestMerger.java   
/**
 * Merges the content of two {@link ProjectDescription project description} instances that are representing the
 * actual N4JS manifests.
 *
 * @param fromLocation
 *            the source location. These attributes and references will be merged to the other one given with the
 *            {@code toLocation}.
 * @param toLocation
 *            the target location. The project description that has to be updated with the content of the
 *            {@code fromLocation}.
 * @return the merged project description that has been detached from its resource.
 */
public ProjectDescription mergeContent(final URI fromLocation, final URI toLocation) {

    final XtextResourceSet fromResourceSet = getResourceSet(fromLocation);
    final XtextResourceSet toResourceSet = getResourceSet(toLocation);
    if (null == fromResourceSet || null == toResourceSet) {
        return null;
    }

    try {

        final Resource from = fromResourceSet.getResource(fromLocation, true);
        final Resource to = toResourceSet.getResource(toLocation, true);
        return mergeContent(from, to);

    } catch (final Exception e) {
        LOGGER.error("Error while trying to merge N4JS manifest content. Source URI: " + fromLocation
                + ". Target URI: " + toLocation + ".", e);
    }
    return null;
}
项目:gemoc-studio    文件:TestXtextSerializer2.java   
public static void loadGexpressionTestFile() {
    // Getting the serializer
    GExpressionsStandaloneSetup setup = new GExpressionsStandaloneSetup();
    Injector injector = setup.createInjectorAndDoEMFRegistration();
    GexpressionsPackage.eINSTANCE.eClass();
    Serializer serializer = injector.getInstance(Serializer.class);

    // Load the model
    URI modelURI = URI
            .createFileURI("/home/flatombe/thesis/gemoc/git/gemoc-dev/org/eclipse/gemoc/GEL/org.eclipse.gemoc.gel.gexpressions.test/model/test.gexpressions");
    XtextResourceSet resSet = injector.getInstance(XtextResourceSet.class);
    resSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
    Resource resource = resSet.getResource(modelURI, true);
    GProgram program = (GProgram) resource.getContents().get(0);

    List<GExpression> exps = program.getExpressions();
    for (GExpression exp : exps) {
        // Serializing
        String s = serializer.serialize(exp);
        System.out.println(s);
    }
}
项目:SurveyDSL    文件:QueryITToXMIConverter.java   
public static void convertERDSLtoXMI(String inputM, String outputM) {
    Injector injector = new QueryITStandaloneSetup().createInjectorAndDoEMFRegistration();

    XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);


    URI uri = URI.createURI(inputM);


    Resource xtextResource = resourceSet.getResource(uri, true);

    EcoreUtil.resolveAll(xtextResource);

    Resource xmiResource = resourceSet.createResource(URI.createURI(outputM));
    xmiResource.getContents().add(xtextResource.getContents().get(0));
    try {
        xmiResource.save(null);
        System.out.println("Saved " + outputM);
        System.out.println("QueryIT file converted successfully to XMI");
        System.out.println("-------------------------------------");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:dsl-devkit    文件:BugAig1314.java   
/**
 * Tests that querying the same scope twice doesn't make the resource set grow.
 */
@Test
public void testSameScopeUseTwice() {
  XtextResourceSet rs = new XtextResourceSet();
  URL url = createURL();
  ModelLocation modelLocation = createModelLocation(url);
  CatalogFromExtensionPointScope scope = new TestScope(modelLocation, rs);
  assertResourceSetEmpty(rs);
  Iterable<IEObjectDescription> elements = scope.getAllElements();
  assertIterableNotEmpty(elements);
  int nofResourcesInMap = rs.getURIResourceMap().size();
  int nofResourcesInSet = rs.getResources().size();
  elements = scope.getAllElements();
  assertIterableNotEmpty(elements);
  assertResourceSet(rs, nofResourcesInSet, nofResourcesInMap);
}
项目:xtext-extras    文件:EcoreGeneratorFragment.java   
/**
 * @since 2.0
 */
@Deprecated
protected void registerReferencedGenModels() {
    try {
        if (getReferencedGenModels() != null && getReferencedGenModels().length() > 0) {
            ResourceSet rs = new XtextResourceSet();
            GenModelHelper gmh = new GenModelHelper();
            for (String uriStr : getReferencedGenModels().split(",")) {
                URI uri = URI.createURI(uriStr.trim());
                gmh.registerGenModel(rs, uri);
            }
        }
    } catch (ConfigurationException ce) {
        throw ce;
    } catch (Exception e) {
        log.error(e, e);
    }
}
项目:xtext-extras    文件:ClasspathTypeProviderFactory.java   
public ClassLoader getClassLoader(ResourceSet resourceSet) {
    if (resourceSet instanceof XtextResourceSet) {
        XtextResourceSet xtextResourceSet = (XtextResourceSet) resourceSet;
        Object ctx = xtextResourceSet.getClasspathURIContext();
        if (ctx != null) {
            if (ctx instanceof Class<?>) {
                return ((Class<?>)ctx).getClassLoader();
            }
            if (!(ctx instanceof ClassLoader)) {
                return ctx.getClass().getClassLoader();
            }
            return (ClassLoader) ctx;
        }
    }
    return classLoader;
}
项目:dsl-devkit    文件:AbstractCheckContentAssistBugTest.java   
/** {@inheritDoc} */
@Override
public XtextResource getResourceFor(final InputStream stream) {
  try {
    XtextResourceSet set = get(XtextResourceSet.class);
    XtextResource resource = (XtextResource) set.createResource(URI.createURI("Test." + getFileExtension()));
    resource.load(stream, null);
    initializeTypeProvider(set);
    return resource;
    // CHECKSTYLE:OFF
  } catch (Exception e) {
    // CHECKSTYLE:ON
    fail(e.getMessage());
  }
  return null;
}
项目:xtext-extras    文件:AbstractURIHandlerTest.java   
public void doTest(final URI usedPrimaryURI, final URI initialReferencedURI, final URI usedReferencedURI) {
  this.referencedResource.setURI(initialReferencedURI);
  final byte[] primaryBytes = this.getBytes(this.primaryResource);
  final byte[] referencedBytes = this.getBytes(this.referencedResource);
  final XtextResourceSet otherResourceSet = this.getNewResourceSet();
  final Resource newPrimaryResource = otherResourceSet.createResource(usedPrimaryURI);
  this.load(newPrimaryResource, primaryBytes);
  final Resource newReferencedResource = otherResourceSet.createResource(usedReferencedURI);
  this.load(newReferencedResource, referencedBytes);
  EcoreUtil.resolveAll(otherResourceSet);
  int _size = otherResourceSet.getResources().size();
  boolean _notEquals = (_size != 2);
  if (_notEquals) {
    throw new UnexpectedResourcesException(otherResourceSet);
  }
  final Map<EObject, Collection<EStructuralFeature.Setting>> unresolved = EcoreUtil.UnresolvedProxyCrossReferencer.find(otherResourceSet);
  boolean _isEmpty = unresolved.isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    throw new UnexpectedProxiesException(unresolved);
  }
}
项目:NoSQLDataEngineering    文件:Model_odm2model_xmi.java   
private void exportXMI(String inM, String outM) {
    // change MyLanguage with your language name
    Injector injector = new ODMParameterStandaloneSetupGenerated()
            .createInjectorAndDoEMFRegistration();
    XtextResourceSet resourceSet = injector
            .getInstance(XtextResourceSet.class);

    // .ext is the extension of the model file
    String inputURI =inM;//"tests/movies.odm";
    String outputURI =outM;//"tests/movies_dsl_output.xmi";
    System.out.println(inputURI+" "+outputURI);
    URI uri = URI.createURI(inputURI);
    Resource xtextResource = resourceSet.getResource(uri, true);

    EcoreUtil.resolveAll(xtextResource);

    Resource xmiResource = resourceSet
            .createResource(URI.createURI(outputURI));
    xmiResource.getContents().add(xtextResource.getContents().get(0));
    try {
        xmiResource.save(null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:xtext-core    文件:SerializationUtil.java   
public static String getCompleteContent(XtextResource xr) throws IOException, UnsupportedEncodingException {
    XtextResourceSet resourceSet = (XtextResourceSet) xr.getResourceSet();
    URIConverter uriConverter = resourceSet.getURIConverter();
    URI uri = xr.getURI();
    String encoding = xr.getEncoding();

    InputStream inputStream = null;

    try {
        inputStream = uriConverter.createInputStream(uri);

        return getCompleteContent(encoding, inputStream);
    } finally {
        tryClose(inputStream, null);
    }
}
项目:xtext-core    文件:BaseEPackageAccess.java   
public static Resource loadResource(String string, XtextResourceSet resourceSet) {
    URI uri = URI.createURI(string);
    Resource resource;
    try {
        resource = resourceSet.getResource(uri, true);
        if (resource == null) {
            throw new IllegalArgumentException("Couldn't create resource for URI : " + uri);
        }
    } catch (Exception e) {
        throw new WrappedException(e);
    }
    EList<EObject> contents = resource.getContents();
    if (contents.size() < 1) {
        throw new IllegalStateException("loading classpath:" + string + " : Expected at least root element but found "
                + contents.size());
    }
    return resource;
}
项目:xtext-core    文件:FlatResourceSetBasedAllContainersState.java   
@Override
public Collection<URI> getContainedURIs(String containerHandle) {
    if (!HANDLE.equals(containerHandle))
        return Collections.emptySet();
    if (resourceSet instanceof XtextResourceSet) {
        ResourceDescriptionsData descriptionsData = findResourceDescriptionsData(resourceSet);
        if (descriptionsData != null) {
            return descriptionsData.getAllURIs();
        }
        return newArrayList(((XtextResourceSet) resourceSet).getNormalizationMap().values());
    }
    List<URI> uris = Lists.newArrayListWithCapacity(resourceSet.getResources().size());
    URIConverter uriConverter = resourceSet.getURIConverter();
    for (Resource r : resourceSet.getResources())
        uris.add(uriConverter.normalize(r.getURI()));
    return uris;
}
项目:xtext-core    文件:FlatResourceSetBasedAllContainersState.java   
@Override
public boolean containsURI(String containerHandle, URI candidateURI) {
    if (!HANDLE.equals(containerHandle))
        return false;
    if (resourceSet instanceof XtextResourceSet) {
        ResourceDescriptionsData descriptionsData = findResourceDescriptionsData(resourceSet);
        if (descriptionsData != null) {
            return descriptionsData.getResourceDescription(candidateURI) != null;
        }
        Collection<URI> allUris = ((XtextResourceSet) resourceSet).getNormalizationMap().values();
        for (URI uri : allUris) {
            if (uri.equals(candidateURI)) {
                return true;
            }
        }
        return false;
    }
    URIConverter uriConverter = resourceSet.getURIConverter();
    for (Resource r : resourceSet.getResources()) {
        URI normalized = uriConverter.normalize(r.getURI());
        if (normalized.equals(candidateURI)) {
            return true;
        }
    }
    return false;
}
项目:xtext-core    文件:IncrementalBuilder.java   
public IncrementalBuilder.Result build(final BuildRequest request, final Function1<? super URI, ? extends IResourceServiceProvider> languages, final IResourceClusteringPolicy clusteringPolicy) {
  try {
    final XtextResourceSet resourceSet = request.getResourceSet();
    ResourceDescriptionsData _copy = request.getState().getResourceDescriptions().copy();
    Source2GeneratedMapping _copy_1 = request.getState().getFileMappings().copy();
    final IndexState oldState = new IndexState(_copy, _copy_1);
    CancelIndicator _cancelIndicator = request.getCancelIndicator();
    final BuildContext context = new BuildContext(languages, resourceSet, oldState, clusteringPolicy, _cancelIndicator);
    final IncrementalBuilder.InternalStatefulIncrementalBuilder builder = this.provider.get();
    builder.context = context;
    builder.request = request;
    try {
      return builder.launch();
    } catch (final Throwable _t) {
      if (_t instanceof Throwable) {
        final Throwable t = (Throwable)_t;
        this._operationCanceledManager.propagateIfCancelException(t);
        throw t;
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目: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    文件:EMFGeneratorFragment2.java   
private void registerUsedGenModel(final URIConverter converter, final Grammar grammar) {
  final URI genModelUri = this.getGenModelUri(grammar);
  boolean _exists = converter.exists(genModelUri, null);
  if (_exists) {
    try {
      GenModelHelper _genModelHelper = new GenModelHelper();
      XtextResourceSet _xtextResourceSet = new XtextResourceSet();
      _genModelHelper.registerGenModel(_xtextResourceSet, genModelUri);
    } catch (final Throwable _t) {
      if (_t instanceof Exception) {
        final Exception e = (Exception)_t;
        EMFGeneratorFragment2.LOG.error("Failed to register GenModel", e);
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  }
}
项目:xtext-core    文件:AbstractLiveContainerTest.java   
@Test
public void testContainerAddRemove() throws Exception {
    ResourceSet resourceSet = new XtextResourceSet();
    Resource res = parse("local", resourceSet).eResource();
    parse("other", 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, other", format(container.getExportedObjects()));

    Resource foo = parse("foo", resourceSet).eResource();
    assertEquals("foo, local, other", format(container.getExportedObjects()));

    resourceSet.getResources().remove(foo);
    assertEquals("local, other", format(container.getExportedObjects()));
}
项目: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    文件:LiveShadowedAllContainerStateTest.java   
@Test
public void testContainsURI() {
    String fileExtension = fep.getPrimaryFileExtension();
    XtextResourceSet xtextResourceSet1 = rsp.get();
    xtextResourceSet1.createResource(URI.createURI("/a/x." + fileExtension));
    xtextResourceSet1.createResource(URI.createURI("/b/x1." + fileExtension));
    ResourceSetBasedResourceDescriptions liveState = new ResourceSetBasedResourceDescriptions();
    liveState.setContext(xtextResourceSet1);
    liveState.setRegistry(registry);
    Multimap<String, URI> container2Uris = ArrayListMultimap.create();
    container2Uris.put("a", URI.createURI("/a/x." + fileExtension));
    container2Uris.put("a", URI.createURI("/a/y." + fileExtension));
    container2Uris.put("b", URI.createURI("/b/x1." + fileExtension));
    container2Uris.put("b", URI.createURI("/b/x2." + fileExtension));
    IAllContainersState containersState = containerStateProvider.get(liveState,
            new FakeAllContainerState(container2Uris));
    assertTrue(containersState.containsURI("a", URI.createURI("/a/x." + fileExtension)));
    assertTrue(containersState.containsURI("a", URI.createURI("/a/y." + fileExtension)));
    assertFalse(containersState.containsURI("b", URI.createURI("/a/x." + fileExtension)));
    assertFalse(containersState.containsURI("b", URI.createURI("/a/y." + fileExtension)));
    assertTrue(containersState.containsURI("b", URI.createURI("/b/x1." + fileExtension)));
    assertTrue(containersState.containsURI("b", URI.createURI("/b/x2." + fileExtension)));
    assertFalse(containersState.containsURI("a", URI.createURI("/b/x1." + fileExtension)));
    assertFalse(containersState.containsURI("a", URI.createURI("/b/x2." + fileExtension)));
}
项目: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    文件:Xtext2EcoreTransformerTest.java   
@Test
public void testBug_266807() throws Exception {
  final XtextResourceSet rs = this.<XtextResourceSet>get(XtextResourceSet.class);
  rs.setClasspathURIContext(this.getClass());
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("classpath:/");
  String _replace = this.getClass().getPackage().getName().replace(Character.valueOf('.').charValue(), Character.valueOf('/').charValue());
  _builder.append(_replace);
  _builder.append("/Test.xtext");
  Resource _createResource = rs.createResource(
    URI.createURI(_builder.toString()), 
    ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  final XtextResource resource = ((XtextResource) _createResource);
  resource.load(null);
  EList<Resource.Diagnostic> _errors = resource.getErrors();
  for (final Resource.Diagnostic d : _errors) {
    Assert.fail(d.getMessage());
  }
}
项目:n4js    文件:NewlineAwareXcoreStandaloneSetup.java   
@Override
public XtextResourceSet getInitializedResourceSet() {
    XtextResourceSet resourceSet = new XtextResourceSet() {
        @Override
        public Resource createResource(URI uri) {
            Resource result = getResource(uri, false);
            if (result == null)
                return super.createResource(uri);
            return result;
        }
    };
    injector.injectMembers(resourceSet);
    resourceSet.eAdapters().add(new AllContainerAdapter(resourceSet));
    return resourceSet;
}
项目:n4js    文件:ECMA6TestSuite.java   
/**
 * generated instances of the tests will use this base implementation
 */
@Override
@Test
public void test() throws Exception {
    if (this.parserN4JS == null) {
        throw new Error("parser instance is null");
    }

    String code = TestCodeProvider.getContentsFromFileEntry(config.entry, config.resourceName);
    if (code == null) {
        throw new Error("test data code instance is null");
    }

    Analyser analyser = createAnalyzer(code);
    XtextResourceSet resourceSet = resourceSetProvider.get();
    URI uri = URI.createURI(config.entry.getName());
    // ECMA 6 test suite was changed - "use strict" is synthesized by the test runner
    // we do the same here
    if (code.contains("flags: [onlyStrict]")) {
        // by using the proper file extension
        uri = uri.trimFileExtension().appendFileExtension("n4js");
    }
    Script script = doParse(code, uri, resourceSet, analyser);
    if (config.isValidator()) {
        // validation flag is bogus since it will produce linking issues
        // thus the negative tests will likely succeed for bogus reasons
        throw new IllegalStateException(config.entry.getName());
    }
    // try {
    analyser.analyse(script, config.entry.getName(), code);
    // } catch (AssertionError e) {
    // System.out.println(config.entry.getName());
    // throw e;
    // }
}
项目:n4js    文件:AbstractECMATestSuiteBase.java   
/**
 * generated instances of the tests will use this base implementation
 */
@Test
public void test() throws Exception {
    if (this.parserN4JS == null) {
        throw new Error("parser instance is null");
    }

    String code = TestCodeProvider.getContentsFromFileEntry(config.entry, config.resourceName);
    if (code == null) {
        throw new Error("test data code instance is null");
    }

    Analyser analyser = createAnalyzer(code);
    XtextResourceSet resourceSet = resourceSetProvider.get();
    URI uri = URI.createURI(config.entry.getName());
    if (isStrictModeTestCase(code)) {
        uri = uri.trimFileExtension().appendFileExtension("n4js");
    }
    try {
        Script script = doParse(code, uri, resourceSet, analyser);
        if (config.isValidator()) {
            Analyser syntaxAnalyzer = new PositiveAnalyser(logger, tester);
            syntaxAnalyzer.analyse(script, config.entry.getName(), code);
            // TODO figure out why we ignore the validation result
            validationTestHelper.validate(script);
        }

        analyser.analyse(script, config.entry.getName(), code);
    } catch (Throwable t) {
        if (!t.getStackTrace()[10].getClassName().contains("Black")) {
            System.out.println(config.entry.getName());
        }
        throw t;
    }
}
项目:n4js    文件:BuiltInTypeScopePluginTest.java   
@SuppressWarnings("javadoc")
@Test
public void testLoadingBuiltInTypes() {
    XtextResourceSet resourceSet = (XtextResourceSet) resourceSetProvider.get(null);
    resourceSet.setClasspathURIContext(N4JSResource.class.getClassLoader());
    BuiltInTypeScope scope = BuiltInTypeScope.get(resourceSet);
    IEObjectDescription anyType = scope.getSingleElement(QualifiedName.create("any"));
    Assert.assertNotNull(anyType);
}
项目:n4js    文件:ECMA6TestSuiteForJSX.java   
@Override
protected Script doParse(String code, URI uri, XtextResourceSet resourceSet, Analyser analyser) throws Exception {

    if (isStrictModeTestCase(code)) {
        uri = uri.trimFileExtension().appendFileExtension("n4jsx");
    } else {
        uri = uri.trimFileExtension().appendFileExtension("jsx");
    }
    // ensure code contains JSX syntax to fail in case of wrong
    // configuration
    if (!analyser.isNegative()) {
        code = code + "\nvar x42 = <div/>\n";
    }
    return parserN4JS.parse(code, uri, resourceSet);
}
项目:n4js    文件:ECMA5TestSuiteForJSX.java   
@Override
protected Script doParse(String code, URI uri, XtextResourceSet resourceSet, Analyser analyser) throws Exception {
    if (isStrictModeTestCase(code)) {
        uri = uri.trimFileExtension().appendFileExtension("n4jsx");
    } else {
        uri = uri.trimFileExtension().appendFileExtension("jsx");
    }
    // ensure code contains JSX syntax to fail in case of wrong
    // configuration
    if (!analyser.isNegative()) {
        code = code + "\nvar x42 = <div/>\n";
    }
    return parserN4JS.parse(code, uri, resourceSet);
}
项目:xtext-core    文件:PortableURIsTest.java   
@Test
public void testPortableReferenceDescriptions() {
  try {
    final XtextResourceSet resourceSet = this.<XtextResourceSet>get(XtextResourceSet.class);
    Resource _createResource = resourceSet.createResource(URI.createURI("hubba:/bubba.langatestlanguage"));
    final StorageAwareResource resourceA = ((StorageAwareResource) _createResource);
    Resource _createResource_1 = resourceSet.createResource(URI.createURI("hubba:/bubba2.langatestlanguage"));
    final StorageAwareResource resourceB = ((StorageAwareResource) _createResource_1);
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("type B");
    _builder.newLine();
    resourceB.load(this.getAsStream(_builder.toString()), null);
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("import \'hubba:/bubba2.langatestlanguage\'");
    _builder_1.newLine();
    _builder_1.newLine();
    _builder_1.append("type A extends B");
    _builder_1.newLine();
    resourceA.load(this.getAsStream(_builder_1.toString()), null);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    final ResourceStorageWritable writable = resourceA.getResourceStorageFacade().createResourceStorageWritable(bout);
    writable.writeResource(resourceA);
    byte[] _byteArray = bout.toByteArray();
    ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_byteArray);
    final ResourceStorageLoadable loadable = resourceA.getResourceStorageFacade().createResourceStorageLoadable(_byteArrayInputStream);
    Resource _createResource_2 = resourceSet.createResource(URI.createURI("hubba:/bubba3.langatestlanguage"));
    final StorageAwareResource resourceC = ((StorageAwareResource) _createResource_2);
    resourceC.loadFromStorage(loadable);
    final IReferenceDescription refDesc = IterableExtensions.<IReferenceDescription>head(resourceC.getResourceDescription().getReferenceDescriptions());
    EObject _head = IterableExtensions.<EObject>head(resourceB.getContents());
    Assert.assertSame(IterableExtensions.<Type>head(((Main) _head).getTypes()), resourceSet.getEObject(refDesc.getTargetEObjectUri(), false));
    EObject _head_1 = IterableExtensions.<EObject>head(resourceC.getContents());
    Assert.assertSame(IterableExtensions.<Type>head(((Main) _head_1).getTypes()), resourceSet.getEObject(refDesc.getSourceEObjectUri(), false));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
项目:xtext-extras    文件:CompilationTestHelper.java   
/**
 * same as {@link #resourceSet(Pair...)} but without actually loading the created resources.
 */
public ResourceSet unLoadedResourceSet(Pair<String,? extends CharSequence> ...resources ) throws IOException {
    XtextResourceSet result = resourceSetProvider.get();
    for (Pair<String, ? extends CharSequence> entry : resources) {
        URI uri = copyToWorkspace(getSourceFolderPath()+"/"+entry.getKey(), entry.getValue());
        Resource resource = result.createResource(uri);
        if (resource == null)
            throw new IllegalStateException("Couldn't create resource for URI "+uri+". Resource.Factory not registered?");
    }
    return result;
}
项目:xtext-extras    文件:JavaSourceLanguageTest.java   
@Test
public void testOverridenInterfaceMethod() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("public interface MySuperClass {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("public java.util.Collection<? extends CharSequence> getThem();");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  Pair<String, String> _mappedTo = Pair.<String, String>of("MySuperClass.java", _builder.toString());
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("public interface MySubClass extends MySuperClass {");
  _builder_1.newLine();
  _builder_1.append("    ");
  _builder_1.append("@Override");
  _builder_1.newLine();
  _builder_1.append("    ");
  _builder_1.append("public java.util.List<? extends String> getThem();");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  Pair<String, String> _mappedTo_1 = Pair.<String, String>of("MySubClass.java", _builder_1.toString());
  final XtextResourceSet rs = this.resourceSet(_mappedTo, _mappedTo_1);
  final Function1<Resource, Boolean> _function = (Resource it) -> {
    return Boolean.valueOf(it.getURI().toString().endsWith("MySubClass.java"));
  };
  final Resource resource = IterableExtensions.<Resource>findFirst(rs.getResources(), _function);
  EObject _head = IterableExtensions.<EObject>head(resource.getContents());
  final JvmGenericType clazz = ((JvmGenericType) _head);
  final JvmTypeReference referenced = IterableExtensions.<JvmOperation>head(clazz.getDeclaredOperations()).getReturnType();
  Assert.assertNotNull(IterableExtensions.<JvmTypeReference>head(((JvmParameterizedTypeReference) referenced).getArguments()));
}
项目:xtext-extras    文件:JavaSourceLanguageTest.java   
@Test
public void testClassShadowing() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("package org.eclipse.xtext.java.tests;");
  _builder.newLine();
  _builder.append("public class MySuperClass2 {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("public void doSomething() {");
  _builder.newLine();
  _builder.append("        ");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("}");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  Pair<String, String> _mappedTo = Pair.<String, String>of("org/eclipse/xtext/java/tests/MySuperClass2.java", _builder.toString());
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("package org.eclipse.xtext.java.tests;");
  _builder_1.newLine();
  _builder_1.append("public class MySubClass2 extends MySuperClass2 {");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  Pair<String, String> _mappedTo_1 = Pair.<String, String>of("org/eclipse/xtext/java/tests/MySubClass2.java", _builder_1.toString());
  final XtextResourceSet rs = this.resourceSet(_mappedTo, _mappedTo_1);
  final Function1<Resource, Boolean> _function = (Resource it) -> {
    return Boolean.valueOf(it.getURI().toString().endsWith("MySuperClass2.java"));
  };
  final Resource superResource = IterableExtensions.<Resource>findFirst(rs.getResources(), _function);
  EObject _head = IterableExtensions.<EObject>head(superResource.getContents());
  final JvmGenericType clazz = ((JvmGenericType) _head);
  Assert.assertNotNull(IterableExtensions.<JvmOperation>head(clazz.getDeclaredOperations()));
}
项目:xtext-extras    文件:ResourceDescriptionProviderTest.java   
protected void resultsIn(final CharSequence javaCode, final Procedure1<? super IResourceDescription> assertion) {
  String _string = javaCode.toString();
  Pair<String, String> _mappedTo = Pair.<String, String>of("SomeJava.java", _string);
  final XtextResourceSet resourceSet = this.resourceSet(_mappedTo);
  this.compilerPhases.setIndexing(resourceSet, true);
  final Resource resource = IterableExtensions.<Resource>head(resourceSet.getResources());
  final IResourceDescription description = this.resourceDesriptionManager.getResourceDescription(resource);
  assertion.apply(description);
}
项目:xtext-core    文件:AbstractXtextResourceSetTest.java   
@Test
public void testResourcesAreInMapWithNormalizedURI_02() {
  final XtextResourceSet rs = this.createEmptyResourceSet();
  Assert.assertEquals(0, rs.getURIResourceMap().size());
  final XtextResource resource = new XtextResource();
  resource.setURI(URI.createURI("/a/../foo"));
  EList<Resource> _resources = rs.getResources();
  ArrayList<Resource> _newArrayList = CollectionLiterals.<Resource>newArrayList(resource);
  Iterables.<Resource>addAll(_resources, _newArrayList);
  Assert.assertEquals(2, rs.getURIResourceMap().size());
  rs.getResources().remove(resource);
  Assert.assertTrue(resource.eAdapters().isEmpty());
  Assert.assertEquals(0, rs.getURIResourceMap().size());
}
项目:xtext-extras    文件:EMFGeneratorFragment.java   
private void registerUsedGenModel(URIConverter converter) {
    if (genModel == null)
        return;
    URI genModelUri = URI.createURI(genModel);
    genModelUri = toPlatformResourceURI(genModelUri);
    if (converter.exists(genModelUri, null)) {
        try {
            new GenModelHelper().registerGenModel(new XtextResourceSet(), genModelUri);
        } catch (ConfigurationException ce) {
            throw ce;
        } catch (Exception e) {
            log.error(e, e);
        }
    }
}
项目:xtext-extras    文件:EMFGeneratorFragment.java   
/**
 * Create a clone of the original grammar. The clone will not refer to a node model.
 */
private Grammar cloneGrammarIntoNewResourceSet(Grammar original) {
    Resource originalResource = original.eResource();
    ResourceSet clonedResourceSet = EcoreUtil2.clone(new XtextResourceSet(), originalResource.getResourceSet());
    Resource clonedResource = clonedResourceSet.getResource(originalResource.getURI(), false);
    Grammar clonedGrammar = (Grammar) clonedResource.getContents().get(0);
    return clonedGrammar;
}
项目:xtext-extras    文件:NoJRESmokeTester.java   
@Override
public void processFile(String data) throws Exception {
    XtextResourceSet resourceSet = new XtextResourceSet();
    NoOpClassLoader classLoader = new NoOpClassLoader();
    resourceSet.setClasspathURIContext(classLoader);
    ClasspathTypeProviderFactory factory = new ClasspathTypeProviderFactory(classLoader, typeResourceServices);
    factory.createTypeProvider(resourceSet);
    EObject parsed = parseHelperNoJRE.parse(data, resourceSet);
    EcoreUtil.resolveAll(parsed);
    checkNoErrorsInValidator(data, (XtextResource) parsed.eResource());
}
项目: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-extras    文件:JvmTypesBuilderTest.java   
@Inject
public JvmTypeReferenceBuilder setJvmTypeReferenceBuilder(final JvmTypeReferenceBuilder.Factory factory, final XtextResourceSet resourceSet) {
  JvmTypeReferenceBuilder _xblockexpression = null;
  {
    this.resourceSet = resourceSet;
    _xblockexpression = this._jvmTypeReferenceBuilder = factory.create(resourceSet);
  }
  return _xblockexpression;
}
项目:xtext-core    文件:AbstractXtextResourceSetTest.java   
@Test
public void testResourcesAreCleared_01() {
  final XtextResourceSet rs = this.createEmptyResourceSet();
  Assert.assertEquals(0, rs.getURIResourceMap().size());
  final XtextResource resource = new XtextResource();
  resource.setURI(URI.createFileURI(new File("foo").getAbsolutePath()));
  EList<Resource> _resources = rs.getResources();
  ArrayList<Resource> _newArrayList = CollectionLiterals.<Resource>newArrayList(resource);
  Iterables.<Resource>addAll(_resources, _newArrayList);
  Assert.assertEquals(1, rs.getURIResourceMap().size());
  rs.getResources().clear();
  Assert.assertTrue(resource.eAdapters().isEmpty());
  Assert.assertEquals(0, rs.getURIResourceMap().size());
}