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

The following examples show how to use org.eclipse.emf.codegen.ecore.genmodel.GenModel. 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: 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 #2
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 #3
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 #4
Source File: ExtendedLanguageConfig.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Registers all EPackages (transitively) referenced by registered GenModels prior to calling {@link LanguageConfig#setUri(String)}.
 */
@Override
public void setUri(final String uri) {
  ResourceSet rs = new ResourceSetImpl();
  Set<URI> result = Sets.newHashSet();
  @SuppressWarnings("deprecation")
  Map<String, URI> genModelLocationMap = EcorePlugin.getEPackageNsURIToGenModelLocationMap();
  for (Map.Entry<String, URI> entry : genModelLocationMap.entrySet()) {
    Resource resource = GenModelAccess.getGenModelResource(null, entry.getKey(), rs);
    if (resource != null) {
      for (EObject model : resource.getContents()) {
        if (model instanceof GenModel) {
          GenModel genModel = (GenModel) model;
          result.addAll(getReferencedEPackages(genModel));
        }
      }
    }
  }
  for (URI u : result) {
    addLoadedResource(u.toString());
  }
  super.setUri(uri);
}
 
Example #5
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 #6
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 #7
Source File: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given an array of {@link IContainers}, searches through all *.genmodel files in all {@link IFolders}, ignoring nested folders, trying to find a
 * {@link GenModel} for the given {@link EPackage}.
 *
 * @param containers
 *          To search, may be empty, but must not be {@code null}
 * @param baseURI
 *          of these containers; must not be {@code null}
 * @param ePackage
 *          to find a genmodel for; must not be {@code null}
 * @param resourceSet
 *          to use for resource loading; must not be {@code null}
 * @return the genmodel, if found, or {@code null} if not.
 * @throws CoreException
 *           if enumerating folder contents does so
 */
private static GenModel findGenModelInContainers(final IContainer[] containers, final URI baseURI, final EPackage ePackage, final ResourceSet resourceSet) throws CoreException {
  Preconditions.checkNotNull(containers);
  Preconditions.checkNotNull(baseURI);
  Preconditions.checkNotNull(ePackage);
  Preconditions.checkNotNull(resourceSet);
  final URIConverter uriConverter = resourceSet.getURIConverter();
  for (IContainer container : containers) {
    if (!(container instanceof IFolder)) {
      continue;
    }
    IResource[] resources = container.members();
    for (IResource r : resources) {
      if (r.exists() && r instanceof IFile && GENMODEL_EXTENSION.equals(r.getFileExtension())) {
        URI uriToTry = uriConverter.normalize(baseURI.appendSegment(URI.encodeSegment(r.getName(), false)));
        GenModel result = loadGenModel(uriToTry, ePackage, resourceSet);
        if (result != null) {
          return result;
        }
      }
    }
  }
  return null;
}
 
Example #8
Source File: GeneratorAdapterDescriptor.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Adapter createGenModelAdapter() {
  if (genModelGeneratorAdapter == null) {
    genModelGeneratorAdapter = new GenModelGeneratorAdapter(this) {
      @Override
      protected void createImportManager(final String packageName, final String className) {
        importManager = new CustomImportManager(packageName, typeMapper);
        importManager.addMasterImport(packageName, className);
        if (generatingObject != null) {
          ((GenBase) generatingObject).getGenModel().setImportManager(importManager);
        }
      }

      /**
       * We handle this one on our own, see
       * {@link org.eclipse.xtext.generator.ecore.CvsIdFilteringGeneratorAdapterFactoryDescriptor.IdFilteringGenModelGeneratorAdapterFactory# createGenModelAdapter()}
       * . Note that the original source comment vanishes in de-compiled Java code.
       */
      @Override
      protected void generateModelPluginProperties(final GenModel genModel, final org.eclipse.emf.common.util.Monitor monitor) {
        // Do nothing.
      }
    };
  }
  return genModelGeneratorAdapter;
}
 
Example #9
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 #10
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 #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
/**
 * @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 #13
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 #14
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 #15
Source File: DataObjectGenerator.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
public VirtualFile generate(VirtualFile basedir) throws DatabaseException {
		GenModel genModel = GenModelFactory.eINSTANCE.createGenModel();
		genModel.setRuntimeVersion(GenRuntimeVersion.EMF25);
		genModel.setComplianceLevel(GenJDKLevel.JDK60_LITERAL);
		genModel.setFeatureDelegation(GenDelegationKind.REFLECTIVE_LITERAL);
		genModel.setRootExtendsClass("org.bimserver.emf.IdEObjectImpl");
		genModel.setRootExtendsInterface("org.bimserver.emf.IdEObject");
		genModel.setSuppressContainment(true);
		genModel.setCodeFormatting(true);
		genModel.setCopyrightText(StringUtils.readFromFile(new File("copyright.txt")));
		genModel.setCanGenerate(true);
		genModel.setModelDirectory("test");
		genModel.setModelName("model name");
		genModel.setForceOverwrite(true);
		genModel.setSuppressNotification(false);
		genModel.setContainmentProxies(false);
		genModel.setBinaryCompatibleReflectiveMethods(false);
		genModel.setPublicConstructors(false);
		genModel.setMinimalReflectiveMethods(true); // More code, but faster
		genModel.setUpdateClasspath(false);

		genModel.initialize(schema.getEPackages());
		
		GeneratorAdapterFactory.Descriptor.Registry.INSTANCE.addDescriptor(GenModelPackage.eNS_URI, GenModelGeneratorAdapterFactory.DESCRIPTOR);
		Generator generator = new Generator();
		generator.setInput(genModel);
		generator.generate(genModel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, new BasicMonitor.Printing(System.out));

		
//		List<GenPackage> genPackages = createGenPackages(genModel, basedir);
//		generatePackages(genModel, genPackages, basedir);

		return basedir;
	}
 
Example #16
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 #17
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 #18
Source File: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Loads the given resource, and if it contains a GenModel for the given ePackage, resturns that.
 *
 * @param uri
 *          to load resource from
 * @param ePackage
 *          to check for
 * @param resourceSet
 *          to use for loading resources
 * @return the GenModel for the given ePackage, or null if none found.
 */
private static GenModel loadGenModel(final URI uri, final EPackage ePackage, final ResourceSet resourceSet) {
  try {
    Resource res = resourceSet.getResource(uri, true);
    for (GenModel model : Iterables.filter(res.getContents(), GenModel.class)) {
      if (model.findGenPackage(ePackage) != null) {
        return model;
      }
    }
    // CHECKSTYLE:CHECK-OFF IllegalCatch
  } catch (Exception ex) {
    // CHECKSTYLE:CHECK-ON IllegalCatch
  }
  return null;
}
 
Example #19
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 #20
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 #21
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected void doGenerate(final GenModel genModel) {
  final Generator generator = new Generator() {
    @Override
    public JControlModel getJControlModel() {
      if ((this.jControlModel == null)) {
        JControlModel _jControlModel = new JControlModel();
        this.jControlModel = _jControlModel;
        this.jControlModel.initialize(null, this.options.mergeRulesURI);
      }
      return this.jControlModel;
    }
  };
  GeneratorAdapterFactory.Descriptor.Registry _adapterFactoryDescriptorRegistry = generator.getAdapterFactoryDescriptorRegistry();
  String _lineDelimiter = this.codeConfig.getLineDelimiter();
  CvsIdFilteringGeneratorAdapterFactoryDescriptor _cvsIdFilteringGeneratorAdapterFactoryDescriptor = new CvsIdFilteringGeneratorAdapterFactoryDescriptor(_lineDelimiter);
  _adapterFactoryDescriptorRegistry.addDescriptor(GenModelPackage.eNS_URI, _cvsIdFilteringGeneratorAdapterFactoryDescriptor);
  genModel.setCanGenerate(true);
  generator.setInput(genModel);
  BasicMonitor _basicMonitor = new BasicMonitor();
  final Diagnostic diagnostic = generator.generate(genModel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, _basicMonitor);
  int _severity = diagnostic.getSeverity();
  boolean _notEquals = (_severity != Diagnostic.OK);
  if (_notEquals) {
    EMFGeneratorFragment2.LOG.warn(diagnostic);
  }
  if (this.generateEdit) {
    BasicMonitor _basicMonitor_1 = new BasicMonitor();
    final Diagnostic editDiag = generator.generate(genModel, GenBaseGeneratorAdapter.EDIT_PROJECT_TYPE, _basicMonitor_1);
    int _severity_1 = editDiag.getSeverity();
    boolean _notEquals_1 = (_severity_1 != Diagnostic.OK);
    if (_notEquals_1) {
      EMFGeneratorFragment2.LOG.warn(editDiag);
    }
  }
  if (this.generateEditor) {
    BasicMonitor _basicMonitor_2 = new BasicMonitor();
    final Diagnostic editorDiag = generator.generate(genModel, GenBaseGeneratorAdapter.EDITOR_PROJECT_TYPE, _basicMonitor_2);
    int _severity_2 = editorDiag.getSeverity();
    boolean _notEquals_2 = (_severity_2 != Diagnostic.OK);
    if (_notEquals_2) {
      EMFGeneratorFragment2.LOG.warn(editorDiag);
    }
  }
}
 
Example #22
Source File: AbstractGeneratorFragmentTests.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected GenModel getSaveAndReconcileGenModel(final Grammar grammar, final List<EPackage> packs, final ResourceSet rs) {
  return super.getSaveAndReconcileGenModel(grammar, packs, rs);
}
 
Example #23
Source File: CustomClassEcoreGeneratorFragment.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void doGenerate(final GenModel genModel) {
  if (LOGGER.isInfoEnabled()) {
    LOGGER.info("generating EMF code for " + genModel.eResource().getURI()); //$NON-NLS-1$
  }

  Generator generator = new Generator() {
    @Override
    public JControlModel getJControlModel() {
      return new JControlModel() {
        @Override
        public boolean canMerge() {
          return false;
        }
      };
    }
  };

  genModel.setNonNLSMarkers(generateNonNLSMarkers);

  generator.getAdapterFactoryDescriptorRegistry().addDescriptor(GenModelPackage.eNS_URI, new GeneratorAdapterDescriptor(loggedTypeMappings, getTypeMapper()));
  generator.setInput(genModel);

  Diagnostic diagnostic = generator.generate(genModel, GenBaseGeneratorAdapter.MODEL_PROJECT_TYPE, new BasicMonitor());

  if (diagnostic.getSeverity() != Diagnostic.OK) {
    LOGGER.info(diagnostic);
  }

  if (isGenerateEdit()) {
    Diagnostic editDiag = generator.generate(genModel, GenBaseGeneratorAdapter.EDIT_PROJECT_TYPE, new BasicMonitor());
    if (editDiag.getSeverity() != Diagnostic.OK) {
      LOGGER.info(editDiag);
    }
  }

  if (isGenerateEditor()) {
    Diagnostic editorDiag = generator.generate(genModel, GenBaseGeneratorAdapter.EDITOR_PROJECT_TYPE, new BasicMonitor());
    if (editorDiag.getSeverity() != Diagnostic.OK) {
      LOGGER.info(editorDiag);
    }
  }
}
 
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: 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 #26
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void generate(Grammar grammar, XpandExecutionContext ctx) {
	try {
		// early exit
		if (!hasGeneratedMetamodel(grammar))
			return;

		// Create a clone of the grammar that can be safely modified
		Grammar clonedGrammar = cloneGrammarIntoNewResourceSet(grammar);
		ResourceSet workingResourceSet = clonedGrammar.eResource().getResourceSet();
		
		// Let's collect all the copies of the generated EPackages of this grammar
		List<EPackage> generatedPackages = getGeneratedEPackages(clonedGrammar);

		// now we register the to-be-used genmodel
		// if it was explicitly set
		registerUsedGenModel(workingResourceSet.getURIConverter());
					
		// just to make sure that we really have a generated package and not only a 
		// meta model declaration
		if (!generatedPackages.isEmpty()) {
			// create an index for all EPackages that are used by the generated packages
			Map<String, EPackage> usedEPackages = findAllUsedEPackages(generatedPackages);
			
			// try to find the *.ecore files for the potentially installed packages 
			Map<String, EPackage> loadedEPackages = findEPackagesInGenPackages(usedEPackages.keySet(), workingResourceSet);
			
			// map the elements from the installed version to the file-version
			Map<EObject, EObject> eNamedElementMapping = createENamedElementMapping(usedEPackages, loadedEPackages);
			
			// and finally replace all the references to installed elements with their 
			// loaded equivalent
			replaceReferencesInGeneratedPackages(generatedPackages, eNamedElementMapping);
			
			// put all the generated packages into a single resource
			Resource ePackageResource = createResourceForEPackages(clonedGrammar, ctx, generatedPackages, workingResourceSet);
			if (!skipGenerate) {
				// obtain the genmodel - either load the given resource (this.genModel) or create a new one
				GenModel genModel = getSaveAndReconcileGenModel(workingResourceSet, clonedGrammar, ctx, generatedPackages);
				// make sure everything is set
				genModel.reconcile();
				// execute the emf generator
				doGenerate(genModel);
				if (basePackage == null)
					basePackage = genModel.getGenPackages().get(0).getBasePackage();
				super.generate(clonedGrammar, ctx);
			}
			// finally save the ecore packages to the file system
			saveResource(ePackageResource);
		}
		updateBuildProperties(ctx);
	} catch (Throwable e) {
		e.printStackTrace();
	}
}
 
Example #27
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 #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: 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 #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());
	}
}