org.eclipse.emf.ecore.resource.ContentHandler Java Examples

The following examples show how to use org.eclipse.emf.ecore.resource.ContentHandler. 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: Xtext2EcoreTransformerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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());
  }
}
 
Example #2
Source File: XtextGrammarReconcilationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: GrammarAccessFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void generate(Grammar grammar, XpandExecutionContext ctx) {
	RuleNames.ensureAdapterInstalled(grammar);
	super.generate(grammar, ctx);

	final ResourceSaveIndicator isSaving = new ResourceSaveIndicator();
	// create a defensive clone
	Grammar copy = deepCopy(grammar, isSaving);
	ResourceSet set = copy.eResource().getResourceSet();

	// save grammar model
	String path;
	if (xmlVersion == null) {
		path = GrammarUtil.getClasspathRelativePathToBinGrammar(copy);
	} else {
		log.warn("'xmlVersion' has been specified for this "
				+ GrammarAccessFragment.class.getSimpleName()
				+ ". Therefore, the grammar is persisted as XMI and not as binary. This can be a performance drawback.");
		path = GrammarUtil.getClasspathRelativePathToXmi(copy);
	}
	URI uri = URI.createURI(ctx.getOutput().getOutlet(Generator.SRC_GEN).getPath() + "/" + path);
	Resource resource = set.createResource(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	addAllGrammarsToResource(resource, copy, new HashSet<Grammar>());
	isSaving.set(Boolean.TRUE);
	Map<String, Object> saveOptions = Maps.newHashMap();
	if (resource instanceof XMLResource) {
		((XMLResource) resource).setXMLVersion(getXmlVersion());
	} else if (resource instanceof BinaryResourceImpl){
		saveOptions.put(BinaryResourceImpl.OPTION_VERSION, BinaryResourceImpl.BinaryIO.Version.VERSION_1_1);
		saveOptions.put(BinaryResourceImpl.OPTION_STYLE_DATA_CONVERTER, Boolean.TRUE);
	}
	try {
		resource.save(saveOptions);
	} catch (IOException e) {
		log.error(e.getMessage(), e);
	} finally {
		isSaving.set(Boolean.FALSE);
	}
}
 
Example #4
Source File: GrammarAccessFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected void movePackageToNewResource(EPackage pack, ResourceSet set) {
	Resource resource = set.createResource(
			URI.createURI("___temp___." + FragmentFakingEcoreResourceFactoryImpl.ECORE_SUFFIX),
			ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	resource.setURI(URI.createURI(pack.getNsURI()));
	resource.getContents().add(pack);
}
 
Example #5
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Resource createResourceForEPackages(Grammar grammar, XpandExecutionContext ctx, List<EPackage> packs,
		ResourceSet rs) {
	URI ecoreFileUri = getEcoreFileUri(grammar, ctx);
	ecoreFileUri = toPlatformResourceURI(ecoreFileUri);
	Resource existing = rs.getResource(ecoreFileUri, false);
	if (existing != null) {
		existing.unload();
		rs.getResources().remove(existing);
	}
	Resource ecoreFile = rs.createResource(ecoreFileUri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	ecoreFile.getContents().addAll(packs);
	return ecoreFile;
}
 
Example #6
Source File: ResourceForIEditorInputFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected XtextResource createResource(ResourceSet resourceSet, URI uri) {
	//TODO use the resource factory directly (injected), since the user might open any file with this editor.
	Resource aResource = resourceSet.createResource(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	if (!(aResource instanceof XtextResource))
		throw new IllegalStateException("The resource factory registered for " + uri
				+ " does not yield an XtextResource. Make sure the file name extension is correct (case matters).");
	return (XtextResource) aResource;
}
 
Example #7
Source File: ResourceServiceProviderRegistryImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected synchronized URIConverter getURIConverter() {
	if (this.uriConverter == null) {
		List<ContentHandler> withoutPlatformDelegate = Lists.newArrayList();
		for (ContentHandler contentHandler : ContentHandler.Registry.INSTANCE.contentHandlers()) {
			if (!isTooEager(contentHandler))
				withoutPlatformDelegate.add(contentHandler);
		}
		this.uriConverter = new ExtensibleURIConverterImpl(URIHandler.DEFAULT_HANDLERS, withoutPlatformDelegate);
	}
	return this.uriConverter;
}
 
Example #8
Source File: ResourceServiceProviderLocator.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the {@link IResourceServiceProvider} for a language given its file extension.
 *
 * @param extension
 *          the language's file extension
 * @return the resource service provider for the {@code extension} or null if there is none
 */
public IResourceServiceProvider getResourceServiceProviderByExtension(final String extension) {
  Object object = IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().get(extension);
  if (object instanceof IResourceServiceProvider) {
    return (IResourceServiceProvider) object;
  } else {
    URI fake = URI.createURI("fake:/foo." + extension); //$NON-NLS-1$
    return IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(fake, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  }
}
 
Example #9
Source File: XtextGrammarSerializationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void _testXtestSerializationSelfTest() throws Exception {
  Resource res = this.<XtextResourceSet>get(XtextResourceSet.class).createResource(URI.createURI("myfile.xtext"), 
    ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  res.getContents().add(this.<XtextGrammarAccess>get(XtextGrammarAccess.class).getGrammar());
  OutputStream outputStream = new ByteArrayOutputStream();
  res.save(outputStream, Collections.<Object, Object>emptyMap());
}
 
Example #10
Source File: GrammarAccessFragment2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected void movePackageToNewResource(final EPackage pack, final ResourceSet set) {
  final Resource resource = set.createResource(
    URI.createURI(("___temp___." + FragmentFakingEcoreResource.FactoryImpl.ECORE_SUFFIX)), 
    ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  resource.setURI(URI.createURI(pack.getNsURI()));
  resource.getContents().add(pack);
}
 
Example #11
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected Resource createResourceForEPackages(final Grammar grammar, final List<EPackage> packs, final ResourceSet rs) {
  final URI ecoreFileUri = this.getEcoreFileUri(grammar);
  final Resource existing = rs.getResource(ecoreFileUri, false);
  if ((existing != null)) {
    existing.unload();
    rs.getResources().remove(existing);
  }
  final Resource ecoreFile = rs.createResource(ecoreFileUri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  ecoreFile.getContents().addAll(packs);
  return ecoreFile;
}
 
Example #12
Source File: EcoreUtil2Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testClone() throws Exception {
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION,
			new XMIResourceFactoryImpl());
	EPackage.Registry.INSTANCE.put(EcorePackage.eINSTANCE.getNsURI(), EcorePackage.eINSTANCE);
	
	ResourceSetImpl rs = new ResourceSetImpl();
	Resource r1 = rs.createResource(URI.createURI("foo.xmi"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	Resource r2 = rs.createResource(URI.createURI("bar.xmi"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	EClass a = EcoreFactory.eINSTANCE.createEClass();
	a.setName("a");
	EClass b = EcoreFactory.eINSTANCE.createEClass();
	r1.getContents().add(a);
	b.setName("b");
	b.getESuperTypes().add(a);
	r2.getContents().add(b);
	
	ResourceSetImpl clone = EcoreUtil2.clone(new ResourceSetImpl(), rs);
	EList<Resource> list = clone.getResources();
	
	Resource resA = list.get(0);
	assertEquals(URI.createURI("foo.xmi"),resA.getURI());
	assertNotSame(resA, r1);
	
	Resource resB = list.get(1);
	assertEquals(URI.createURI("bar.xmi"),resB.getURI());
	assertNotSame(resB, r2);
	
	EClass a1 = (EClass)resA.getContents().get(0);
	EClass b1 = (EClass)resB.getContents().get(0);
	assertEquals("a", a1.getName());
	assertNotSame(a, a1);
	assertEquals("b", b1.getName());
	assertNotSame(b, b1);
	assertSame(b1.getESuperTypes().get(0),a1);
	assertSame(b.getESuperTypes().get(0),a);
}
 
Example #13
Source File: EcoreUtil2Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testEPackageURI() throws Exception {
	ResourceSet rs = new ResourceSetImpl();
	Resource foo = rs.createResource(URI.createURI("foo.xmi"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	foo.getContents().add(ePackage);
	
	assertEquals(true, EcoreUtil2.isValidUri(ePackage, URI.createURI(EcorePackage.eNS_URI)));
}
 
Example #14
Source File: EcoreUtil2Test.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSimple() throws Exception {
	ResourceSet rs = new ResourceSetImpl();
	Resource foo = rs.createResource(URI.createURI("foo.xmi"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	foo.getContents().add(ePackage);
	Resource bar = rs.createResource(URI.createURI("bar.xmi"), ContentHandler.UNSPECIFIED_CONTENT_TYPE);
	bar.getContents().add(EcoreFactory.eINSTANCE.createEAttribute());
	
	assertEquals(true, EcoreUtil2.isValidUri(ePackage, URI.createURI("bar.xmi")));
}
 
Example #15
Source File: XtextSetup.java    From doclipser with Eclipse Public License 1.0 4 votes vote down vote up
private static void register(ContentHandler h) {
  ContentHandler.Registry registry = ContentHandler.Registry.INSTANCE;
  registry.put(HIGH_PRIORITY, h);
}
 
Example #16
Source File: EmptyAuthorityAddingNormalizer.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @see org.eclipse.emf.ecore.resource.URIConverter#getContentHandlers()
 */
@Override
public EList<ContentHandler> getContentHandlers() {
	return delegate.getContentHandlers();
}
 
Example #17
Source File: ResourceSetBasedResourceDescriptionsTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IResourceServiceProvider getResourceServiceProvider(URI uri) {
	return getResourceServiceProvider(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
}
 
Example #18
Source File: NamesAreUniqueValidatorTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IResourceServiceProvider getResourceServiceProvider(URI uri) {
	return getResourceServiceProvider(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
}
 
Example #19
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected GenModel getGenModel(final ResourceSet rs, final Grammar grammar) {
  try {
    final URI genModelUri = this.getGenModelUri(grammar);
    final Resource resource = rs.getResource(genModelUri, false);
    if ((resource != null)) {
      resource.unload();
      rs.getResources().remove(resource);
    }
    final Resource genModelFile = rs.createResource(genModelUri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
    GenModel genModel = null;
    boolean _exists = rs.getURIConverter().exists(genModelUri, null);
    if (_exists) {
      genModelFile.load(null);
      boolean _hasFragment = genModelUri.hasFragment();
      if (_hasFragment) {
        EObject _eObject = genModelFile.getEObject(genModelUri.fragment());
        genModel = ((GenModel) _eObject);
      } else {
        EObject _head = IterableExtensions.<EObject>head(genModelFile.getContents());
        genModel = ((GenModel) _head);
      }
    } else {
      genModel = new GenModelImpl() {
        @Override
        public GenPackage createGenPackage() {
          return new GenPackageImpl() {
            @Override
            public String getSerializedPackageFilename() {
              String _name = this.getName();
              return (_name + ".loadinitialization_ecore");
            }
          };
        }
      };
      genModel.setModelName(this.getModelName(grammar));
      genModel.setModelPluginID(this.getModelPluginID());
      genModel.setModelDirectory(this.getJavaModelDirectory());
      if (this.generateEdit) {
        genModel.setEditPluginID(this.getEditPluginID());
        genModel.setEditDirectory(this.getEditDirectory());
      }
      if (this.generateEditor) {
        genModel.setEditorPluginID(this.getEditorPluginID());
        genModel.setEditorDirectory(this.getEditorDirectory());
      }
      genModel.setValidateModel(false);
      genModel.setForceOverwrite(true);
      genModel.setFacadeHelperClass(null);
      genModel.setBundleManifest(true);
      genModel.setUpdateClasspath(false);
      genModel.setComplianceLevel(this.jdkLevel);
      genModel.setRuntimeVersion(this.emfRuntimeVersion);
      genModel.setRootExtendsClass(this.rootExtendsClass);
      genModel.setLineDelimiter(this.codeConfig.getLineDelimiter());
      String _fileHeader = this.codeConfig.getFileHeader();
      boolean _tripleNotEquals = (_fileHeader != null);
      if (_tripleNotEquals) {
        genModel.setCopyrightText(this.trimMultiLineComment(this.codeConfig.getFileHeader()));
      }
    }
    genModelFile.getContents().add(genModel);
    return genModel;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #20
Source File: GrammarAccessFragment2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected void writeGrammar() {
  final Wrapper<Boolean> isSaving = Wrapper.<Boolean>wrap(Boolean.valueOf(false));
  final ResourceSet cloneInto = new ResourceSetImpl();
  Map<String, Object> _extensionToFactoryMap = cloneInto.getResourceFactoryRegistry().getExtensionToFactoryMap();
  FragmentFakingEcoreResource.FactoryImpl _factoryImpl = new FragmentFakingEcoreResource.FactoryImpl(isSaving);
  _extensionToFactoryMap.put(
    FragmentFakingEcoreResource.FactoryImpl.ECORE_SUFFIX, _factoryImpl);
  final ResourceSet resourceSet = EcoreUtil2.<ResourceSet>clone(cloneInto, this.getLanguage().getGrammar().eResource().getResourceSet());
  EObject _head = IterableExtensions.<EObject>head(resourceSet.getResource(this.getLanguage().getGrammar().eResource().getURI(), true).getContents());
  final Grammar copy = ((Grammar) _head);
  String _xifexpression = null;
  if ((this.xmlVersion == null)) {
    _xifexpression = GrammarUtil.getClasspathRelativePathToBinGrammar(copy);
  } else {
    String _xblockexpression = null;
    {
      String _simpleName = GrammarAccessFragment2.class.getSimpleName();
      String _plus = ("The property \'xmlVersion\' has been specified for this " + _simpleName);
      String _plus_1 = (_plus + ". Therefore, the grammar is persisted as XMI and not as binary. This can be a performance drawback.");
      GrammarAccessFragment2.LOG.warn(_plus_1);
      _xblockexpression = GrammarUtil.getClasspathRelativePathToXmi(copy);
    }
    _xifexpression = _xblockexpression;
  }
  final String path = _xifexpression;
  final URI uri = this.getProjectConfig().getRuntime().getSrcGen().getURI(path);
  final Resource resource = resourceSet.createResource(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
  HashSet<Grammar> _hashSet = new HashSet<Grammar>();
  this.addAllGrammarsToResource(resource, copy, _hashSet);
  isSaving.set(Boolean.valueOf(true));
  final Map<String, Object> saveOptions = CollectionLiterals.<String, Object>newHashMap();
  if ((resource instanceof XMLResource)) {
    String _elvis = null;
    if (this.xmlVersion != null) {
      _elvis = this.xmlVersion;
    } else {
      _elvis = "1.0";
    }
    ((XMLResource)resource).setXMLVersion(_elvis);
  } else {
    if ((resource instanceof BinaryResourceImpl)) {
      saveOptions.put(BinaryResourceImpl.OPTION_VERSION, BinaryResourceImpl.BinaryIO.Version.VERSION_1_1);
      saveOptions.put(BinaryResourceImpl.OPTION_STYLE_DATA_CONVERTER, Boolean.valueOf(true));
    }
  }
  try {
    resource.save(saveOptions);
  } catch (final Throwable _t) {
    if (_t instanceof IOException) {
      final IOException e = (IOException)_t;
      GrammarAccessFragment2.LOG.error(e.getMessage(), e);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  } finally {
    isSaving.set(Boolean.valueOf(false));
  }
}
 
Example #21
Source File: ResourceServiceProviderRegistryImpl.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public IResourceServiceProvider getResourceServiceProvider(URI uri) {
	return getResourceServiceProvider(uri, ContentHandler.UNSPECIFIED_CONTENT_TYPE);
}
 
Example #22
Source File: ClasspathTypeProvider.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public EList<ContentHandler> getContentHandlers() {
	return existing.getContentHandlers();
}