org.eclipse.emf.codegen.ecore.genmodel.GenPackage Java Examples

The following examples show how to use org.eclipse.emf.codegen.ecore.genmodel.GenPackage. 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: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, EPackage> findEPackagesInGenPackages(final Collection<String> packageNsURIs, final ResourceSet resourceSet) {
  final HashMap<String, EPackage> result = CollectionLiterals.<String, EPackage>newHashMap();
  for (final String nsURI : packageNsURIs) {
    {
      final Resource resource = GenModelUtil2.getGenModelResource(null, nsURI, resourceSet);
      if ((resource != null)) {
        final GenModel loadedGenModel = IterableExtensions.<GenModel>head(Iterables.<GenModel>filter(resource.getContents(), GenModel.class));
        if ((loadedGenModel != null)) {
          final GenPackage genPackage = this.findGenPackageByNsURI(loadedGenModel, nsURI);
          result.put(nsURI, genPackage.getEcorePackage());
        }
      }
    }
  }
  return result;
}
 
Example #2
Source File: PropertySetter.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private GenFeature createGenFeature() {
    final EAttribute eAttribute = newEAttribute(field);
    final EClass eClass = EcoreFactory.eINSTANCE.createEClass();
    eClass.getEStructuralFeatures().add(eAttribute);
    final EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
    ePackage.getEClassifiers().add(eClass);
    final GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
    final GenPackage genPackage = genModel.createGenPackage();
    genPackage.setEcorePackage(ePackage);
    final GenClass genClass = genModel.createGenClass();
    genClass.setEcoreClass(eClass);
    final GenFeature genFeature = genModel.createGenFeature();
    genFeature.setEcoreFeature(eAttribute);
    genFeature.setGenClass(genClass);
    genPackage.getGenClasses().add(genClass);
    genModel.getGenPackages().add(genPackage);
    return genFeature;
}
 
Example #3
Source File: CustomClassAwareEcoreGenerator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Registers the given source-paths in the generator.
 */
@Override
public void preInvoke() {
  ResourceSet resSet = new ResourceSetImpl();
  Resource resource = resSet.getResource(URI.createURI(genModel), true);
  for (EObject obj : resource.getContents()) {
    if (obj instanceof GenModel) {
      GenModel model = (GenModel) obj;
      addSourcePathForPlugin(model.getModelPluginID());
      for (GenPackage usedPackage : model.getUsedGenPackages()) {
        addSourcePathForPlugin(usedPackage.getGenModel().getModelPluginID());
      }
    }
  }
  LOGGER.info("Registered source path to discover custom classes: " + Joiner.on(", ").join(this.srcPaths));
}
 
Example #4
Source File: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the qualified package interface name for the given epackage (model).
 *
 * @param ePackage
 *          the model
 * @return the package interface name
 */
public static String getQualifiedPackageInterfaceName(final EPackage ePackage) {
  if (ePackage.getClass() == EPackageImpl.class) {
    // EPackage loaded from ecore model
    GenPackage genPackage = findGenPackage(ePackage);
    if (genPackage != null) {
      return genPackage.getQualifiedPackageInterfaceName();
    }
  } else {
    // EPackage loaded from Java
    Class<?>[] interfaces = ePackage.getClass().getInterfaces();
    if (interfaces != null && interfaces.length > 0) {
      return interfaces[0].getName();
    }
  }
  return null;
}
 
Example #5
Source File: GenModelUtil2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public static GenClassifier getGenClassifier(final EClassifier cls, final ResourceSet resourceSet) {
  final GenPackage genPackage = GenModelUtil2.getGenPackage(cls.getEPackage(), resourceSet);
  EList<GenClassifier> _genClassifiers = genPackage.getGenClassifiers();
  for (final GenClassifier genCls : _genClassifiers) {
    String _name = cls.getName();
    String _name_1 = genCls.getEcoreClassifier().getName();
    boolean _equals = Objects.equal(_name, _name_1);
    if (_equals) {
      return genCls;
    }
  }
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("No GenClassifier named \'");
  String _name_2 = cls.getName();
  _builder.append(_name_2);
  _builder.append("\' found in GenModel ");
  URI _uRI = genPackage.eResource().getURI();
  _builder.append(_uRI);
  throw new RuntimeException(_builder.toString());
}
 
Example #6
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected List<GenPackage> getGenPackagesForPackages(final GenModel existingGenModel, final Collection<EPackage> packs) {
  final ArrayList<GenPackage> result = CollectionLiterals.<GenPackage>newArrayList();
  for (final EPackage pkg : packs) {
    final Function1<GenPackage, Boolean> _function = (GenPackage it) -> {
      EPackage _ecorePackage = it.getEcorePackage();
      String _nsURI = null;
      if (_ecorePackage!=null) {
        _nsURI=_ecorePackage.getNsURI();
      }
      String _nsURI_1 = pkg.getNsURI();
      return Boolean.valueOf(Objects.equal(_nsURI, _nsURI_1));
    };
    boolean _exists = IterableExtensions.<GenPackage>exists(existingGenModel.getGenPackages(), _function);
    boolean _not = (!_exists);
    if (_not) {
      result.add(GenModelUtil2.getGenPackage(pkg, existingGenModel.eResource().getResourceSet()));
    }
  }
  final Comparator<GenPackage> _function_1 = (GenPackage o1, GenPackage o2) -> {
    return EcoreUtil.getURI(o1).toString().compareTo(EcoreUtil.getURI(o2).toString());
  };
  Collections.<GenPackage>sort(result, _function_1);
  return result;
}
 
Example #7
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected GenModel getSaveAndReconcileGenModel(final Grammar grammar, final List<EPackage> packs, final ResourceSet rs) {
  final GenModel genModel = this.getGenModel(rs, grammar);
  genModel.initialize(packs);
  EList<GenPackage> _genPackages = genModel.getGenPackages();
  for (final GenPackage genPackage : _genPackages) {
    {
      genPackage.setBasePackage(this.getBasePackage(grammar));
      if (this.suppressLoadInitialization) {
        genPackage.setLoadInitialization(false);
      }
      if (((!this.getLanguage().getFileExtensions().isEmpty()) && packs.contains(genPackage.getEcorePackage()))) {
        genPackage.setFileExtensions(IterableExtensions.join(this.getLanguage().getFileExtensions(), ","));
      }
    }
  }
  final Set<EPackage> referencedEPackages = this.getReferencedEPackages(packs);
  final List<GenPackage> usedGenPackages = this.getGenPackagesForPackages(genModel, referencedEPackages);
  this.reconcileMissingGenPackagesInUsedModels(usedGenPackages);
  genModel.getUsedGenPackages().addAll(usedGenPackages);
  this.saveResource(genModel.eResource());
  new GenModelHelper().registerGenModel(genModel);
  return genModel;
}
 
Example #8
Source File: EcoreGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Use {@link GenModelAccess#getGenPackage(EPackage, ResourceSet)}
 */
@Deprecated
protected List<GenPackage> loadReferencedGenModels(ResourceSet rs) {
	List<GenPackage> result = Lists.newArrayList();
	if (getReferencedGenModels() != null) {
		for (String uri : getReferencedGenModels().split(",")) {
			try {
				Resource resource = rs.getResource(URI.createURI(uri.trim()), true);
				GenModel genmodel = (GenModel) resource.getContents().get(0);
				EList<GenPackage> genPackages = genmodel.getGenPackages();
				for (GenPackage genPackage : genPackages) {
					genPackage.getEcorePackage().getEClassifiers();
					result.add(genPackage);
				}
			} catch (Exception e) {
				log.error("Couldn't find genmodel for uri '" + uri + "'");
				throw new WrappedException(e);
			}
		}
	}
	return result;
}
 
Example #9
Source File: TypeReference.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private static TypeReference.QualifiedClassName getQualifiedName(final EPackage epackage, final ResourceSet resourceSet) {
  TypeReference.QualifiedClassName _xblockexpression = null;
  {
    final GenPackage genPackage = GenModelUtil2.getGenPackage(epackage, resourceSet);
    String _xifexpression = null;
    boolean _isSuppressEMFMetaData = genPackage.getGenModel().isSuppressEMFMetaData();
    if (_isSuppressEMFMetaData) {
      _xifexpression = genPackage.getQualifiedPackageClassName();
    } else {
      _xifexpression = genPackage.getReflectionPackageName();
    }
    final String packageName = _xifexpression;
    String _packageInterfaceName = genPackage.getPackageInterfaceName();
    _xblockexpression = new TypeReference.QualifiedClassName(packageName, _packageInterfaceName);
  }
  return _xblockexpression;
}
 
Example #10
Source File: EPackageChooser.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected List<EPackageInfo> createEPackageInfosFromGenModel(URI genModelURI) {
	ResourceSet resourceSet = createResourceSet(genModelURI);
	Resource resource = resourceSet.getResource(genModelURI, true);
	List<EPackageInfo> ePackageInfos = Lists.newArrayList();
	for (TreeIterator<EObject> i = resource.getAllContents(); i.hasNext();) {
		EObject next = i.next();
		if (next instanceof GenPackage) {
			GenPackage genPackage = (GenPackage) next;
			EPackage ePackage = genPackage.getEcorePackage();
			URI importURI;
			if(ePackage.eResource() == null) {
				importURI = URI.createURI(ePackage.getNsURI());
			} else {
				importURI = ePackage.eResource().getURI();
			}
			EPackageInfo ePackageInfo = new EPackageInfo(ePackage, importURI, genModelURI, genPackage
					.getQualifiedPackageInterfaceName(), genPackage.getGenModel().getModelPluginID());
			ePackageInfos.add(ePackageInfo);
		} else if (!(next instanceof GenModel)) {
			i.prune();
		}
	}
	return ePackageInfos;
}
 
Example #11
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.0
 */
protected GenModel getSaveAndReconcileGenModel(ResourceSet rs, Grammar grammar, XpandExecutionContext ctx,
		List<EPackage> packs) throws ConfigurationException {
	GenModel genModel = getGenModel(rs, grammar, ctx, packs);
	genModel.initialize(packs);
	for (GenPackage genPackage : genModel.getGenPackages()) {
		genPackage.setBasePackage(getBasePackage(grammar));
		if (isSuppressLoadInitialization()) {
			genPackage.setLoadInitialization(false);
		}
		if (getFileExtensions() != null && packs.contains(genPackage.getEcorePackage())) {
			genPackage.setFileExtensions(getFileExtensions());
		}
	}
	Set<EPackage> referencedEPackages = getReferencedEPackages(packs);
	List<GenPackage> usedGenPackages = getGenPackagesForPackages(genModel, referencedEPackages);
	reconcileMissingGenPackagesInUsedModels(usedGenPackages);
	genModel.getUsedGenPackages().addAll(usedGenPackages);
	try {
		saveResource(genModel.eResource());
	} catch (IOException e) {
		throw new WrappedException(e);
	}
	new GenModelHelper().registerGenModel(genModel);
	return genModel;
}
 
Example #12
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private Map<String, EPackage> findEPackagesInGenPackages(Set<String> packageNsURIs, ResourceSet resourceSet) {
	Map<String, EPackage> result = Maps.newHashMap();
	for(String nsURI: packageNsURIs) {
		Resource resource = GenModelAccess.getGenModelResource(null, nsURI, resourceSet);
		if (resource != null) {
			for(EObject content: resource.getContents()) {
				if (content instanceof GenModel) {
					GenModel loadedGenModel = (GenModel) content;
					GenPackage genPackage = findGenPackageByNsURI(loadedGenModel, nsURI);
					result.put(nsURI, genPackage.getEcorePackage());
					break;
				}
			}
		}
	}
	return result;
}
 
Example #13
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.0
 */
protected List<GenPackage> getGenPackagesForPackages(GenModel existingGenModel, Collection<EPackage> packs) {
	List<GenPackage> result = Lists.newArrayList();
	for (EPackage pkg : packs) {
		boolean found = false;
		for (GenPackage gp : existingGenModel.getGenPackages())
			if (gp.getEcorePackage() != null && gp.getEcorePackage().getNsURI() != null
					&& gp.getEcorePackage().getNsURI().equals(pkg.getNsURI()))
				found = true;
		if (!found)
			result.add(GenModelAccess.getGenPackage(pkg, existingGenModel.eResource().getResourceSet()));
	}
	Collections.sort(result, new Comparator<GenPackage>() {
		@Override
		public int compare(GenPackage o1, GenPackage o2) {
			return EcoreUtil.getURI(o1).toString().compareTo(EcoreUtil.getURI(o2).toString());
		}
	});
	return result;
}
 
Example #14
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.11
 */
@Override
public Set<Binding> getGuiceBindingsRt(Grammar grammar) {
	if (isBindEPackageAndEFactory()) {
		BindFactory bindFactory = new BindFactory();
		// Register generated EPackage and EFactory instances in the runtime module
		for (EPackage pkg: getGeneratedEPackages(grammar)) {
			GenPackage genPkg = GenModelUtil2.getGenPackage(pkg, grammar.eResource().getResourceSet());
			bindFactory
				.addTypeToInstance(genPkg.getQualifiedPackageInterfaceName(), genPkg.getQualifiedPackageInterfaceName()+".eINSTANCE")
				.addTypeToInstance(genPkg.getQualifiedFactoryInterfaceName(), genPkg.getQualifiedFactoryInterfaceName()+".eINSTANCE");
		}
		return bindFactory.getBindings();
	} else {
		return Collections.emptySet();
	}
}
 
Example #15
Source File: GenModelAccess.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public static GenPackage getGenPackage(EPackage pkg, ResourceSet resourceSet) {
	String nsURI = pkg.getNsURI();
	String location = null;
	if (pkg.eResource() != null && pkg.eResource().getURI() != null)
		location = pkg.eResource().getURI().toString();
	Resource genModelResource = getGenModelResource(location, nsURI, resourceSet);
	if (genModelResource != null) {
		for (EObject model : genModelResource.getContents()) {
			if (model instanceof GenModel) {
				GenPackage genPkg = ((GenModel) model).findGenPackage(pkg);
				if (genPkg != null) {
					genPkg.getEcorePackage().getEClassifiers();
					return genPkg;
				}
			}
		}
		throw new RuntimeException("No GenPackage for NsURI " + nsURI + " found in " + genModelResource.getURI());
	}
	throw new RuntimeException("No GenPackage for NsURI " + nsURI + ".");
}
 
Example #16
Source File: GenModelAccess.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public static GenClassifier getGenClassifier(EClassifier cls, ResourceSet resourceSet) {
	GenPackage genPackage = getGenPackage(cls.getEPackage(), resourceSet);
	for (GenClassifier genCls : genPackage.getGenClassifiers())
		if (cls.getName().equals(genCls.getEcoreClassifier().getName())) {
			return genCls;
		}
	throw new RuntimeException("No GenClassifier named '" + cls.getName() + "' found in GenModel "
			+ genPackage.eResource().getURI());
}
 
Example #17
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.14
 */
protected void reconcileMissingGenPackagesInUsedModels(final List<GenPackage> usedGenPackages) {
  final HashSet<GenModel> processedModels = Sets.<GenModel>newHashSetWithExpectedSize(usedGenPackages.size());
  for (final GenPackage usedGenPackage : usedGenPackages) {
    {
      final GenModel genModel = usedGenPackage.getGenModel();
      boolean _add = processedModels.add(genModel);
      if (_add) {
        final List<EPackage> missingPackages = genModel.getMissingPackages();
        final List<GenPackage> missingGenPackages = this.getGenPackagesForPackages(genModel, missingPackages);
        genModel.getUsedGenPackages().addAll(missingGenPackages);
      }
    }
  }
}
 
Example #18
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private void reconcileMissingGenPackagesInUsedModels(List<GenPackage> usedGenPackages) {
	Set<GenModel> processedModels = Sets.newHashSet();
	for(GenPackage usedGenPackage: usedGenPackages) {
		GenModel genModel = usedGenPackage.getGenModel();
		if (processedModels.add(genModel)) {
			List<EPackage> missingPackages = genModel.getMissingPackages();
			List<GenPackage> missingGenPackages = getGenPackagesForPackages(genModel, missingPackages);
			genModel.getUsedGenPackages().addAll(missingGenPackages);
		}
	}
}
 
Example #19
Source File: GenModelQualifiedNameProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public QualifiedName getFullyQualifiedName(final EObject obj) {
  return cache.get(Tuples.pair(obj, getCacheKey()), obj.eResource(), new Provider<QualifiedName>() {
    @Override
    public QualifiedName get() {
      if (obj instanceof GenPackage) {
        String nsUri = ((GenPackage) obj).getNSURI();
        return nsUri != null ? QualifiedName.create(nsUri) : null;
      }
      return null;
    }
  });
}
 
Example #20
Source File: GenModelUtil2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public static GenPackage getGenPackage(final EPackage pkg, final ResourceSet resourceSet) {
  final String nsURI = pkg.getNsURI();
  String location = null;
  Resource _eResource = pkg.eResource();
  URI _uRI = null;
  if (_eResource!=null) {
    _uRI=_eResource.getURI();
  }
  boolean _tripleNotEquals = (_uRI != null);
  if (_tripleNotEquals) {
    location = pkg.eResource().getURI().toString();
  }
  final Resource genModelResource = GenModelUtil2.getGenModelResource(location, nsURI, resourceSet);
  if ((genModelResource != null)) {
    EList<EObject> _contents = genModelResource.getContents();
    for (final EObject model : _contents) {
      if ((model instanceof GenModel)) {
        final GenPackage genPkg = ((GenModel)model).findGenPackage(pkg);
        if ((genPkg != null)) {
          genPkg.getEcorePackage().getEClassifiers();
          return genPkg;
        }
      }
    }
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("No GenPackage for NsURI ");
    _builder.append(nsURI);
    _builder.append(" found in ");
    URI _uRI_1 = genModelResource.getURI();
    _builder.append(_uRI_1);
    throw new RuntimeException(_builder.toString());
  }
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("No GenPackage for NsURI ");
  _builder_1.append(nsURI);
  _builder_1.append(".");
  throw new RuntimeException(_builder_1.toString());
}
 
Example #21
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private GenPackage findGenPackageByNsURI(GenModel genModel, String nsURI) {
	List<GenPackage> allGenPackages = genModel.getAllGenUsedAndStaticGenPackagesWithClassifiers();
	for(GenPackage genPackage: allGenPackages) {
		EPackage ecorePackage = genPackage.getEcorePackage();
		if (ecorePackage == null || ecorePackage.eIsProxy()) {
			throw new RuntimeException("Unresolved proxy: " + ecorePackage + " in " + genModel.eResource().getURI());
		}
		if (nsURI.equals(ecorePackage.getNsURI())) {
			return genPackage;
		}
	}
	throw new RuntimeException("No GenPackage for NsURI " + nsURI + " found in " + genModel.eResource().getURI());
}
 
Example #22
Source File: AbstractPortableURIsTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void doTestResource(String platformPath, String... packageNames) {
	Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
	assertNotNull(resource);
	assertEquals(1, resource.getContents().size());
	EObject obj = resource.getContents().get(0);
	if (obj instanceof EPackage) {
		assertEquals(packageNames[0], ((EPackage) obj).getName());
	} else if (obj instanceof GenModel) {
		GenModel model = (GenModel) obj;
		List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
		assertEquals(packageNames.length, packages.size());
		ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
			@Override
			public String apply(GenPackage p) {
				return p.getEcorePackage().getName();
			}
		});
		List<String> packageNamesList = Arrays.asList(packageNames);
		Collections.sort(packageNamesList);
		for(int i = 0; i < packageNamesList.size(); i++) {
			assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
		}
		IStatus status = model.validate();
		assertTrue(printLeafs(status), status.isOK());
		EObject orig = EcoreUtil.copy(obj);
		((GenModel) obj).reconcile();
		if (!EcoreUtil.equals(orig, obj)) {
			Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
				@Override
				public boolean apply(EStructuralFeature f) {
					if (f instanceof EReference) {
						EReference casted = (EReference) f;
						return !casted.isContainment();
					}
					return false;
				}
			};
			String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
			String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
			throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
		}
	} else {
		fail("Unexpected root element type: " + obj.eClass().getName());
	}
}
 
Example #23
Source File: URIsInEcoreFilesXtendTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void doTestResource(String platformPath, String... packageNames) {
	Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
	assertNotNull(resource);
	assertEquals(1, resource.getContents().size());
	EObject obj = resource.getContents().get(0);
	if (obj instanceof EPackage) {
		assertEquals(packageNames[0], ((EPackage) obj).getName());
	} else if (obj instanceof GenModel) {
		GenModel model = (GenModel) obj;
		List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
		assertEquals(packageNames.length, packages.size());
		ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
			@Override
			public String apply(GenPackage p) {
				return p.getEcorePackage().getName();
			}
		});
		List<String> packageNamesList = Arrays.asList(packageNames);
		Collections.sort(packageNamesList);
		for(int i = 0; i < packageNamesList.size(); i++) {
			assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
		}
		IStatus status = model.validate();
		assertTrue(printLeafs(status), status.isOK());
		EObject orig = EcoreUtil.copy(obj);
		((GenModel) obj).reconcile();
		if (!EcoreUtil.equals(orig, obj)) {
			Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
				@Override
				public boolean apply(EStructuralFeature f) {
					if (f instanceof EReference) {
						EReference casted = (EReference) f;
						return !casted.isContainment();
					}
					return false;
				}
			};
			String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
			String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
			throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
		}
	} else {
		fail("Unexpected root element type: " + obj.eClass().getName());
	}
}
 
Example #24
Source File: DataObjectGenerator.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
public void generatePackages(GenModel genModel, List<GenPackage> genPackages, VirtualFile basedir) {
	for (GenPackage genPackage : genPackages) {
		genPackage.prepareCache();

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String packageClassPathImpl = MODEL_PACKAGE + genPackage.getPackageName() + ".impl.";
		packageClassPathImpl = packageClassPathImpl.replace(".", File.separator) + genPackage.getPackageClassName() + ".java";
		VirtualFile packageVirtualFileImpl = basedir.createFile(packageClassPathImpl);
		packageVirtualFileImpl.setStringContent(new PackageClass().generate(new Object[] { genPackage, false, true }));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String packageClassPathInterface = MODEL_PACKAGE + genPackage.getPackageName() + ".";
		packageClassPathInterface = packageClassPathInterface.replace(".", File.separator) + genPackage.getPackageInterfaceName() + ".java";
		VirtualFile packageVirtualFileInterface = basedir.createFile(packageClassPathInterface);
		packageVirtualFileInterface.setStringContent(new PackageClass().generate(new Object[] { genPackage, true, false }));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String factoryClassPathImpl = MODEL_PACKAGE + genPackage.getPackageName() + ".impl.";
		factoryClassPathImpl = factoryClassPathImpl.replace(".", File.separator) + genPackage.getFactoryClassName() + ".java";
		VirtualFile factoryVirtualFileImpl = basedir.createFile(factoryClassPathImpl);
		factoryVirtualFileImpl.setStringContent(new FactoryClass().generate(new Object[] { genPackage, false, true }));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String factoryClassPathInterface = MODEL_PACKAGE + genPackage.getPackageName() + ".";
		factoryClassPathInterface = factoryClassPathInterface.replace(".", File.separator) + genPackage.getFactoryInterfaceName() + ".java";
		VirtualFile factoryVirtualFileInterface = basedir.createFile(factoryClassPathInterface);
		factoryVirtualFileInterface.setStringContent(new FactoryClass().generate(new Object[] { genPackage, true, false }));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String adapterFactoryClassPath = MODEL_PACKAGE + genPackage.getPackageName() + ".util.";
		adapterFactoryClassPath = adapterFactoryClassPath.replace(".", File.separator) + genPackage.getAdapterFactoryClassName() + ".java";
		VirtualFile adapterFactoryVirtualFile = basedir.createFile(adapterFactoryClassPath);
		adapterFactoryVirtualFile.setStringContent(new AdapterFactoryClass().generate(genPackage));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String switchClassPath = MODEL_PACKAGE + genPackage.getPackageName() + ".util.";
		switchClassPath = switchClassPath.replace(".", File.separator) + genPackage.getSwitchClassName() + ".java";
		VirtualFile switchClassVirtualFile = basedir.createFile(switchClassPath);
		switchClassVirtualFile.setStringContent(new SwitchClass().generate(genPackage));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String xmlClassPath = MODEL_PACKAGE + genPackage.getPackageName() + ".util.";
		xmlClassPath = xmlClassPath.replace(".", File.separator) + genPackage.getXMLProcessorClassName() + ".java";
		VirtualFile xmlClassVirtualFile = basedir.createFile(xmlClassPath);
		xmlClassVirtualFile.setStringContent(new XMLProcessorClass().generate(genPackage));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String resourceFactoryClassPath = MODEL_PACKAGE + genPackage.getPackageName() + ".util.";
		resourceFactoryClassPath = resourceFactoryClassPath.replace(".", File.separator) + genPackage.getResourceFactoryClassName() + ".java";
		VirtualFile resourceFactoryClassVirtualFile = basedir.createFile(resourceFactoryClassPath);
		resourceFactoryClassVirtualFile.setStringContent(new ResourceFactoryClass().generate(genPackage));

		genModel.setImportManager(new ImportManager("org.bimserver.models"));

		String resourceClassPath = MODEL_PACKAGE + genPackage.getPackageName() + ".util.";
		resourceClassPath = resourceClassPath.replace(".", File.separator) + genPackage.getResourceClassName() + ".java";
		VirtualFile resourceClassVirtualFile = basedir.createFile(resourceClassPath);
		resourceClassVirtualFile.setStringContent(new ResourceClass().generate(genPackage));

		// String validatorClassPath = "com.logiclabs.streamdb.models." +
		// genPackage.getPackageName() + ".util.";
		// validatorClassPath = validatorClassPath.replace(".",
		// File.separator) + genPackage.getValidatorClassName() + ".java";
		// VirtualFile validatorClassVirtualFile =
		// basedir.createFile(validatorClassPath);
		// validatorClassVirtualFile.setStringContent(new
		// ValidatorClass().generate(genPackage));

		for (GenClass genClass : genPackage.getGenClasses()) {
			genModel.setImportManager(new ImportManager("org.bimserver.models"));
			String implFileName = MODEL_PACKAGE + genPackage.getPackageName() + ".impl.";
			implFileName = implFileName.replace(".", File.separator) + genClass.getName() + "Impl.java";
			VirtualFile implVirtualFile = basedir.createFile(implFileName);
			implVirtualFile.setStringContent(new org.eclipse.emf.codegen.ecore.templates.model.Class().generate(new Object[] { genClass, false, true }));

			genModel.setImportManager(new ImportManager("org.bimserver.models"));
			String interfaceFileName = MODEL_PACKAGE + genPackage.getPackageName() + ".";
			interfaceFileName = interfaceFileName.replace(".", File.separator) + genClass.getName() + ".java";
			VirtualFile interfaceVirtualFile = basedir.createFile(interfaceFileName);
			interfaceVirtualFile.setStringContent(new org.eclipse.emf.codegen.ecore.templates.model.Class().generate(new Object[] { genClass, true, false }));
		}
		for (GenEnum genEnum : genPackage.getGenEnums()) {
			genModel.setImportManager(new ImportManager("org.bimserver.models"));

			String enumFileName = MODEL_PACKAGE + genPackage.getPackageName() + ".";
			enumFileName = enumFileName.replace(".", File.separator) + genEnum.getName() + ".java";
			VirtualFile enumVirtualFile = basedir.createFile(enumFileName);
			enumVirtualFile.setStringContent(new EnumClass().generate(genEnum));
		}
	}
}
 
Example #25
Source File: GenModelAccess.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.1
 */
@Deprecated
public static Resource getGenModelResource(String locationInfo, String nsURI, ResourceSet resourceSet) {
	URI genModelURI = EcorePlugin.getEPackageNsURIToGenModelLocationMap(false).get(nsURI);
	if (genModelURI == null) {
		if (EcorePackage.eNS_URI.equals(nsURI)) // if we really want to use the registered ecore ...
			return null;
		
		// look into the resource set to find a genpackage for the given URI
		for (Resource res: resourceSet.getResources()) {
			
			// we only look into the first level, as genmodels are usually among the top level elements.
			// this just to avoid traversing all eobjects in the resource set.
			for (EObject obj : res.getContents()) {
				if (obj instanceof GenModel) {
					for (GenPackage genPackage:((GenModel) obj).getGenPackages()) {
						if (genPackage.getNSURI().equals(nsURI)) {
							return genPackage.eResource();
						}
					}
				}
			}
		}
		
		StringBuilder buf = new StringBuilder();
		if (locationInfo != null && locationInfo.length() > 0)
			locationInfo = " from " + locationInfo; 
		else 
			locationInfo = "";
		buf.append("Could not find a GenModel for EPackage '").append(nsURI).append("'").append(locationInfo).append("\n");
		buf.append("If the missing GenModel has been generated via " + EMFGeneratorFragment.class.getSimpleName() + " or " + 
				org.eclipse.xtext.generator.ecore.EcoreGeneratorFragment.class.getSimpleName());
		buf.append(" make sure to run it first in the workflow.\n");
		buf.append("If you have a *.genmodel-file, make sure to register it via StandaloneSetup.registerGenModelFile(String)");
		throw new RuntimeException(buf.toString());
	}
	if (resourceSet == null)
		throw new RuntimeException("There is no ResourceSet for EPackage '" + nsURI + "'. "
				+ "Please make sure the EPackage has been loaded from a .ecore file "
				+ "and not from the generated Java file.");
	Resource genModelResource = resourceSet.getResource(genModelURI, true);
	if (genModelResource == null)
		throw new RuntimeException("Error loading GenModel " + genModelURI);
	for(EObject content: genModelResource.getContents()) {
		if (content instanceof GenModel)
			((GenModel) content).reconcile();
	}
	return genModelResource;
}
 
Example #26
Source File: AbstractPortableURIsTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected void doTestResource(String platformPath, String... packageNames) {
	Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
	assertNotNull(resource);
	assertEquals(1, resource.getContents().size());
	EObject obj = resource.getContents().get(0);
	if (obj instanceof EPackage) {
		assertEquals(packageNames[0], ((EPackage) obj).getName());
	} else if (obj instanceof GenModel) {
		GenModel model = (GenModel) obj;
		List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
		assertEquals(packageNames.length, packages.size());
		ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
			@Override
			public String apply(GenPackage p) {
				return p.getEcorePackage().getName();
			}
		});
		List<String> packageNamesList = Arrays.asList(packageNames);
		Collections.sort(packageNamesList);
		for(int i = 0; i < packageNamesList.size(); i++) {
			assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
		}
		IStatus status = model.validate();
		assertTrue(printLeafs(status), status.isOK());
		EObject orig = EcoreUtil.copy(obj);
		((GenModel) obj).reconcile();
		if (!EcoreUtil.equals(orig, obj)) {
			Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
				@Override
				public boolean apply(EStructuralFeature f) {
					if (f instanceof EReference) {
						EReference casted = (EReference) f;
						return !casted.isContainment();
					}
					return false;
				}
			};
			String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
			String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
			throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
		}
	} else {
		fail("Unexpected root element type: " + obj.eClass().getName());
	}
}
 
Example #27
Source File: GenModelUtil2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
public static Resource getGenModelResource(final String locationInfo, final String nsURI, final ResourceSet resourceSet) {
  final URI genModelURI = EcorePlugin.getEPackageNsURIToGenModelLocationMap(false).get(nsURI);
  if ((genModelURI == null)) {
    boolean _equals = Objects.equal(EcorePackage.eNS_URI, nsURI);
    if (_equals) {
      return null;
    }
    EList<Resource> _resources = resourceSet.getResources();
    for (final Resource res : _resources) {
      EList<EObject> _contents = res.getContents();
      for (final EObject obj : _contents) {
        if ((obj instanceof GenModel)) {
          EList<GenPackage> _genPackages = ((GenModel)obj).getGenPackages();
          for (final GenPackage genPackage : _genPackages) {
            String _nSURI = genPackage.getNSURI();
            boolean _equals_1 = Objects.equal(_nSURI, nsURI);
            if (_equals_1) {
              return genPackage.eResource();
            }
          }
        }
      }
    }
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("Could not find a GenModel for EPackage \'");
    _builder.append(nsURI);
    _builder.append("\'");
    {
      boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(locationInfo);
      boolean _not = (!_isNullOrEmpty);
      if (_not) {
        _builder.append(" from ");
        _builder.append(locationInfo);
      }
    }
    _builder.append(".");
    _builder.newLineIfNotEmpty();
    _builder.append("If the missing GenModel has been generated via ");
    String _simpleName = EMFGeneratorFragment2.class.getSimpleName();
    _builder.append(_simpleName);
    _builder.append(", make sure to run it first in the workflow.");
    _builder.newLineIfNotEmpty();
    _builder.append("If you have a *.genmodel-file, make sure to register it via StandaloneSetup.registerGenModelFile(String).");
    _builder.newLine();
    throw new RuntimeException(_builder.toString());
  }
  if ((resourceSet == null)) {
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("There is no ResourceSet for EPackage \'");
    _builder_1.append(nsURI);
    _builder_1.append("\'. Please make sure the EPackage has been loaded from a .ecore file and not from the generated Java file.");
    throw new RuntimeException(_builder_1.toString());
  }
  final Resource genModelResource = resourceSet.getResource(genModelURI, true);
  if ((genModelResource == null)) {
    StringConcatenation _builder_2 = new StringConcatenation();
    _builder_2.append("Error loading GenModel ");
    _builder_2.append(genModelURI);
    throw new RuntimeException(_builder_2.toString());
  }
  EList<EObject> _contents_1 = genModelResource.getContents();
  for (final EObject content : _contents_1) {
    if ((content instanceof GenModel)) {
      ((GenModel)content).reconcile();
    }
  }
  return genModelResource;
}
 
Example #28
Source File: AbstractPortableURIsTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void doTestResource(String platformPath, String... packageNames) {
	Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
	assertNotNull(resource);
	assertEquals(1, resource.getContents().size());
	EObject obj = resource.getContents().get(0);
	if (obj instanceof EPackage) {
		assertEquals(packageNames[0], ((EPackage) obj).getName());
	} else if (obj instanceof GenModel) {
		GenModel model = (GenModel) obj;
		List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
		assertEquals(packageNames.length, packages.size());
		ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
			@Override
			public String apply(GenPackage p) {
				return p.getEcorePackage().getName();
			}
		});
		List<String> packageNamesList = Arrays.asList(packageNames);
		Collections.sort(packageNamesList);
		for(int i = 0; i < packageNamesList.size(); i++) {
			assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
		}
		IStatus status = model.validate();
		assertTrue(printLeafs(status), status.isOK());
		EObject orig = EcoreUtil.copy(obj);
		((GenModel) obj).reconcile();
		if (!EcoreUtil.equals(orig, obj)) {
			Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
				@Override
				public boolean apply(EStructuralFeature f) {
					if (f instanceof EReference) {
						EReference casted = (EReference) f;
						return !casted.isContainment();
					}
					return false;
				}
			};
			String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
			String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
			throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
		}
	} else {
		fail("Unexpected root element type: " + obj.eClass().getName());
	}
}
 
Example #29
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 #30
Source File: AbstractPortableURIsTest.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected void doTestResource(String platformPath, String... packageNames) {
	Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
	assertNotNull(resource);
	assertEquals(1, resource.getContents().size());
	EObject obj = resource.getContents().get(0);
	if (obj instanceof EPackage) {
		assertEquals(packageNames[0], ((EPackage) obj).getName());
	} else if (obj instanceof GenModel) {
		GenModel model = (GenModel) obj;
		List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
		assertEquals(packageNames.length, packages.size());
		ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
			@Override
			public String apply(GenPackage p) {
				return p.getEcorePackage().getName();
			}
		});
		List<String> packageNamesList = Arrays.asList(packageNames);
		Collections.sort(packageNamesList);
		for(int i = 0; i < packageNamesList.size(); i++) {
			assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
		}
		IStatus status = model.validate();
		assertTrue(printLeafs(status), status.isOK());
		EObject orig = EcoreUtil.copy(obj);
		((GenModel) obj).reconcile();
		if (!EcoreUtil.equals(orig, obj)) {
			Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
				@Override
				public boolean apply(EStructuralFeature f) {
					if (f instanceof EReference) {
						EReference casted = (EReference) f;
						return !casted.isContainment();
					}
					return false;
				}
			};
			String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
			String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
			throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
		}
	} else {
		fail("Unexpected root element type: " + obj.eClass().getName());
	}
}