@Override protected Entry<ComponentFactory> createService ( final UserInformation userInformation, final String configurationId, final BundleContext context, final Map<String, String> parameters ) throws Exception { final ConfigurationDataHelper cfg = new ConfigurationDataHelper ( parameters ); final String xml = cfg.getStringNonEmpty ( "configuration" ); final XMIResource xmi = new XMIResourceImpl (); final Map<?, ?> options = new HashMap<Object, Object> (); final InputSource is = new InputSource ( new StringReader ( xml ) ); xmi.load ( is, options ); final Object c = EcoreUtil.getObjectByType ( xmi.getContents (), ParserPackage.Literals.COMPONENT ); if ( ! ( c instanceof Component ) ) { throw new RuntimeException ( String.format ( "Configuration did not contain an object of type %s", Component.class.getName () ) ); } final ComponentFactoryWrapper wrapper = new ComponentFactoryWrapper ( this.executor, (Component)c ); final Dictionary<String, ?> properties = new Hashtable<> (); final ServiceRegistration<ComponentFactory> handle = context.registerService ( ComponentFactory.class, wrapper, properties ); return new Entry<ComponentFactory> ( configurationId, wrapper, handle ); }
@Test public void testNestedPackage() throws Exception { Resource resource = new XMIResourceImpl(); EPackage parent = EcoreFactory.eINSTANCE.createEPackage(); parent.setName("parent"); parent.setNsURI("http://parent"); EPackage child = EcoreFactory.eINSTANCE.createEPackage(); child.setName("child"); child.setNsURI("http://child"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("Test"); child.getEClassifiers().add(eClass); parent.getESubpackages().add(child); resource.getContents().add(parent); Map<QualifiedName, IEObjectDescription> index = createIndex(resource); checkEntry(index, parent, false, "parent"); checkEntry(index, child, false, "parent", "child"); checkEntry(index, eClass, false, "parent", "child", "Test"); checkEntry(index, parent, true, "http://parent"); checkEntry(index, child, true, "http://child"); checkEntry(index, eClass, true, "http://child", "Test"); assertEquals(6,index.size()); }
@Test public void testMissingMiddleName() { Resource resource = new XMIResourceImpl(); EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setName("test"); ePackage.setNsURI("http://test"); EClass unnamedEClass = EcoreFactory.eINSTANCE.createEClass(); EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute(); eAttribute.setName("test"); unnamedEClass.getEStructuralFeatures().add(eAttribute); ePackage.getEClassifiers().add(unnamedEClass); resource.getContents().add(ePackage); Map<QualifiedName, IEObjectDescription> index = createIndex(resource); checkEntry(index, ePackage, false, "test"); checkEntry(index, ePackage, true, "http://test"); assertEquals(2,index.size()); unnamedEClass.setName("Test"); index = createIndex(resource); checkEntry(index, ePackage, false, "test"); checkEntry(index, ePackage, true, "http://test"); checkEntry(index, unnamedEClass, false, "test", "Test"); checkEntry(index, unnamedEClass, true, "http://test", "Test"); checkEntry(index, eAttribute, false, "test", "Test", "test"); checkEntry(index, eAttribute, true, "http://test", "Test", "test"); assertEquals(6,index.size()); }
@BeforeClass public static void beforeClass() throws CoreException, IOException { final NullProgressMonitor monitor = new NullProgressMonitor(); final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("TestProject"); project.create(monitor); project.open(monitor); final IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path( "TestProject/TestFolder")); folder.create(true, true, monitor); final Resource resource = new XMIResourceImpl(URI.createPlatformResourceURI( "TestProject/TestFolder/TestFile.xmi", true)); resource.getContents().add(EcorePackage.eINSTANCE.getEcoreFactory().createEClass()); resource.getContents().add(EcorePackage.eINSTANCE.getEcoreFactory().createEClass()); resource.getContents().add(EcorePackage.eINSTANCE.getEcoreFactory().createEClass()); resource.save(null); }
@Test public void getContainerEObject() throws IOException, CoreException { final EObjectContainerProvider provider = new EObjectContainerProvider(); final EObject element = MappingPackage.eINSTANCE.getMappingFactory().createBase(); final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( EObjectContainerProviderTests.class.getCanonicalName()); project.create(new NullProgressMonitor()); project.open(new NullProgressMonitor()); final IFile file = project.getFile(new Path("test.xmi")); final Resource resource = new XMIResourceImpl(URI.createPlatformResourceURI(file.getFullPath() .toString(), true)); resource.getContents().add(element); resource.save(null); final Object result = provider.getContainer(element); assertEquals(file, result); }
/** * Updates {@link IEObjectLocation#getSavedURIFragment() saved URI fragment}. * * @param container * the {@link ILocationContainer} * @param eObjectContainer * the {@link IEObjectContainer} * @param newResource * the new {@link Resource} * @throws Exception * if the XMI serialization failed or elements couldn't be created */ private static void updateSavedURIFragment(ILocationContainer container, IEObjectContainer eObjectContainer, Resource newResource) throws Exception { final IBase base = MappingUtils.getBase(container); final Copier copier = new Copier(); final Collection<EObject> copiedContents = copier.copyAll(newResource.getContents()); copier.copyReferences(); final XMIResourceImpl newXMIResource = new XMIResourceImpl(); newXMIResource.getContents().addAll(copiedContents); for (Entry<EObject, EObject> entry : copier.entrySet()) { final EObject newEObject = entry.getKey(); final EObject savedEObject = entry.getValue(); final ICouple couple = base.getFactory().createElement(ICouple.class); couple.setKey(newResource.getURIFragment(newEObject)); couple.setValue(newXMIResource.getURIFragment(savedEObject)); eObjectContainer.getSavedURIFragments().add(couple); } }
@Test public void testParsingOnLoad() throws Exception { File tmpFile = File.createTempFile("SCTResource", "test.test"); tmpFile.deleteOnExit(); URI uri = URI.createFileURI(tmpFile.getPath().toString()); Resource resource = new XMIResourceImpl(uri); Statechart statechart = createStatechart("internal: event Event1"); resource.getContents().add(statechart); Transition transition = createTransition("Event1 [true] / 3 * 3"); resource.getContents().add(transition); resource.save(Collections.EMPTY_MAP); res.setURI(uri); res.load(Collections.EMPTY_MAP); statechart = (Statechart) res.getContents().get(0); transition = (Transition) res.getContents().get(1); assertEquals("" + res.getErrors(), 0, res.getErrors().size()); ReactionTrigger trigger = (ReactionTrigger) transition.getTrigger(); RegularEventSpec eventSpec = (RegularEventSpec) trigger.getTriggers().get(0); ElementReferenceExpression expression = (ElementReferenceExpression) eventSpec.getEvent(); EventDefinition reference = (EventDefinition) expression.getReference(); assertNotNull(reference); assertEquals("Event1", reference.getName()); }
private static String xmi2NativeArduino(String xmiPath) throws IOException{ // register ArduinoML ResourceSet resourceSet = new ResourceSetImpl(); Map<String, Object> packageRegistry = resourceSet.getPackageRegistry(); packageRegistry.put(arduinoML.ArduinoMLPackage.eNS_URI, arduinoML.ArduinoMLPackage.eINSTANCE); // load the xmi file XMIResource resource = new XMIResourceImpl(URI.createURI("file:"+xmiPath)); resource.load(null); // get the root of the model App app = (App) resource.getContents().get(0); // Launch the visitor on the root ArduinoMLSwitchPrinter visitor = new ArduinoMLSwitchPrinter(); return visitor.doSwitch(app); }
@Override public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if ( editor instanceof AtlEditorExt ) { AtlEditorExt atlEditor = (AtlEditorExt) editor; IFile file = (IFile) atlEditor.getUnderlyingResource(); AnalysisResult r = AnalysisIndex.getInstance().getAnalysis(file); for (MetamodelNamespace ns : r.getNamespace().getMetamodels()) { MetamodelPrunner prunner = new MetamodelPrunner(r.getATLModel(), ns); XMIResourceImpl res = new XMIResourceImpl(); prunner.extractSource(res, ns.getName(), ns.getName() + "/prunned", ns.getName()); try { res.save(new FileOutputStream(file.getLocation().removeLastSegments(1).append(ns.getName() + ".ecore").toOSString()), null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; }
public static void createGenModel(final EPackage rootPackage, final IPath ecorePath, final IResource genmodelResource) { GenModel genModel = GenModelFactory.eINSTANCE.createGenModel(); genModel.setComplianceLevel(GenJDKLevel.JDK60_LITERAL); genModel.setModelDirectory(ecorePath.removeLastSegments(1).toString()); genModel.getForeignModel().add(ecorePath.lastSegment()); genModel.setModelName(rootPackage.getName()); genModel.setRootExtendsInterface(""); genModel.initialize(Collections.singleton(rootPackage)); GenPackage genPackage = (GenPackage) genModel.getGenPackages().get(0); genPackage.setPrefix(""); try { URI genModelURI = URI.createURI(genmodelResource.getLocationURI().toString()); final XMIResourceImpl genModelResource = new XMIResourceImpl(genModelURI); genModelResource.getContents().add(genModel); genModelResource.save(Collections.EMPTY_MAP); } catch (IOException e) { e.printStackTrace(); } }
private void saveModel(List<Package> pkgs) throws IOException { // Create a resource-set to contain the resource(s) that we are saving ResourceSet resourceSet = new ResourceSetImpl(); // Initialize registrations of resource factories, library models, // profiles, Ecore metadata, and other dependencies required for // serializing and working with UML resources. This is only necessary in // applications that are not hosted in the Eclipse platform run-time, in // which case these registrations are discovered automatically from // Eclipse extension points. UMLResourcesUtil.init(resourceSet); // Create the output resource and add our model package to it. // Resource resource = resourceSet.createResource(uri); Resource resource = new XMIResourceImpl(); for (Package pkg : pkgs) { resource.getContents().add(pkg); } // And save. Map<?, ?> options = null; // No save options needed. resource.save(outputStream, options); outputStream.close(); }
/** * Used by updateEMFResource and emfResourceChanged to load the new resource. * * @return new Resource. */ private Resource getNewEMFResource() { if (resource == null) { getEMFResource(); } Diagram d = getDiagramTypeProvider().getDiagram(); URI uri = d.eResource().getURI(); uri = uri.trimFragment(); uri = uri.trimFileExtension(); uri = uri.appendFileExtension(BLOCKS_FILE_EXTENSION); Resource newResource = new XMIResourceImpl(uri); try { newResource.load(null); } catch (IOException e) { e.printStackTrace(); } return newResource; }
/** * Loads the given data flow graph. The file given in the editor input must be a valid graph. Its function block * models are loaded into a list and returned. * * @param input * the input of the editor * @return a collection of FunctionBlockModels that were defined in the model * @throws IOException * if reading fails */ private Collection<FunctionBlockModel> loadInput(final FileEditorInput input) throws IOException { LOGGER.entry(input); Collection<FunctionBlockModel> blockModelList = new ArrayList<FunctionBlockModel>(); graphicsManager.setAppName(input.getFile().getName() .replaceAll("\\.blocks", Messages.DEPLOYGRAPHICS_EMPTYSTRING)); //$NON-NLS-1$ //$NON-NLS-2$ URI uri = URI.createURI(input.getURI().toASCIIString()); resource = new XMIResourceImpl(uri); resource.setTrackingModification(true); resource.load(null); for (EObject object : resource.getContents()) { if (object instanceof FunctionBlockModel) { LOGGER.trace("found FunctionBlockModel {}", object); //$NON-NLS-1$ FunctionBlockModel blockmodel = (FunctionBlockModel) object; blockModelList.add(blockmodel); } } return blockModelList; }
public void loadBlocks() { Collection<FunctionBlockModel> functionBlocks = new ArrayList<FunctionBlockModel>(); ModelFactory.eINSTANCE.eClass(); URI uri = URI.createURI(new File(path).toURI().toASCIIString()); Resource resource = new XMIResourceImpl(uri); try { resource.load(null); } catch (IOException e) { System.out.println("Loading blocks failed."); e.printStackTrace(); } for (EObject object : resource.getContents()) { if (object instanceof FunctionBlockModel) { FunctionBlockModel blockmodel = (FunctionBlockModel) object; functionBlocks.add(blockmodel); System.out.println(blockmodel.getBlockName()); } } blocks = functionBlocks; }
private <T extends QObjectNameable> Resource getResource(String repository, Class<T> klass) { String resourceKey = repository+"/"+klass.getName(); Resource resource = resources.get(resourceKey); if(resource == null) { XMIResourceImpl xmiResource = (XMIResourceImpl) resourceSet.createResource(URI.createURI(basePath+repository+"/"+klass.getSimpleName()+".xmi")); xmiResource.setEncoding("UTF-8"); resource = xmiResource; try { resource.load(Collections.EMPTY_MAP); } catch (IOException e) { // first load try { resource.save(Collections.EMPTY_MAP); } catch (IOException e1) { throw new OperatingSystemRuntimeException(e); } } resources.put(resourceKey, resource); } return resource; }
/** * <b>ONLY INTENDED FOR TESTS OR DEBUGGING. DON'T USE IN PRODUCTION CODE.</b> * <p> * Same as {@link #getDeserializedModuleFromDescription(IEObjectDescription, URI)}, but always returns the module as * an XMI-serialized string. */ public static String getDeserializedModuleFromDescriptionAsString(IEObjectDescription eObjectDescription, URI uri) throws IOException { final TModule module = getDeserializedModuleFromDescription(eObjectDescription, uri); final XMIResource resourceForUserData = new XMIResourceImpl(uri); resourceForUserData.getContents().add(module); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); resourceForUserData.save(baos, getOptions(uri, false)); return baos.toString(TRANSFORMATION_CHARSET_NAME); }
/** * Reads the TModule stored in the given IEObjectDescription. */ public static TModule getDeserializedModuleFromDescription(IEObjectDescription eObjectDescription, URI uri) { final String serializedData = eObjectDescription.getUserData(USERDATA_KEY_SERIALIZED_SCRIPT); if (Strings.isNullOrEmpty(serializedData)) { return null; } final XMIResource xres = new XMIResourceImpl(uri); try { final boolean binary = !serializedData.startsWith("<"); final ByteArrayInputStream bais = new ByteArrayInputStream( binary ? XMLTypeFactory.eINSTANCE.createBase64Binary(serializedData) : serializedData.getBytes(TRANSFORMATION_CHARSET_NAME)); xres.load(bais, getOptions(uri, binary)); } catch (Exception e) { LOGGER.warn("error deserializing module from IEObjectDescription: " + uri); //$NON-NLS-1$ if (LOGGER.isTraceEnabled()) { LOGGER.trace("error deserializing module from IEObjectDescription=" + eObjectDescription + ": " + uri, e); //$NON-NLS-1$ } // fail safe, because not uncommon (serialized data might have been created with an old version of the N4JS // IDE, so the format could be out of date (after an update of the IDE)) return null; } final List<EObject> contents = xres.getContents(); if (contents.isEmpty() || !(contents.get(0) instanceof TModule)) { return null; } final TModule module = (TModule) contents.get(0); xres.getContents().clear(); return module; }
private String makeXml ( final Component component ) throws IOException { final XMIResourceImpl xmi = new XMIResourceImpl (); xmi.getContents ().add ( EcoreUtil.copy ( component ) ); final StringWriter writer = new StringWriter (); xmi.save ( writer, null ); return writer.toString (); }
@Override public void initiateSynchronisationDialogue() { srcModel = new XMIResourceImpl(); trgModel = new XMIResourceImpl(); FamilyRegister familiesRoot = FamiliesFactory.eINSTANCE .createFamilyRegister(); srcModel.getContents().add(familiesRoot); setConfigurator(new Configurator<Decisions>() .makeDecision(Decisions.PREFER_CREATING_PARENT_TO_CHILD, true) .makeDecision(Decisions.PREFER_EXISTING_FAMILY_TO_NEW, true)); transform(RIGHT); }
@Test public void testMissingNsURI() { Resource resource = new XMIResourceImpl(); EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setName("test"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("Test"); ePackage.getEClassifiers().add(eClass); resource.getContents().add(ePackage); Map<QualifiedName, IEObjectDescription> index = createIndex(resource); checkEntry(index, ePackage, false, "test"); checkEntry(index, eClass, false, "test", "Test"); assertEquals(2,index.size()); }
@Test public void testMissingName() { Resource resource = new XMIResourceImpl(); EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setNsURI("http://test"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("Test"); ePackage.getEClassifiers().add(eClass); resource.getContents().add(ePackage); Map<QualifiedName, IEObjectDescription> index = createIndex(resource); checkEntry(index, ePackage, true, "http://test"); checkEntry(index, eClass, true, "http://test", "Test"); assertEquals(2,index.size()); }
/** * Constructor. * * @param testFolder * the test folder path * @throws IOException * if the tested template can't be read * @throws DocumentParserException * if the tested template can't be parsed */ public AbstractTemplatesTestSuite(String testFolder) throws IOException, DocumentParserException { MyDslPackage.eINSTANCE.getName();// make sure MyDsl is loaded (XText) UMLPackage.eINSTANCE.getName(); // make sure UML2 is loaded this.testFolderPath = testFolder.replaceAll("\\\\", "/"); final URI genconfURI = getGenconfURI(new File(testFolderPath)); if (URIConverter.INSTANCE.exists(genconfURI, Collections.EMPTY_MAP)) { final ResourceSet rs = getResourceSetForGenconf(); generation = getGeneration(genconfURI, rs); } else { generation = GenconfFactory.eINSTANCE.createGeneration(); Resource r = new XMIResourceImpl(genconfURI); r.getContents().add(generation); } final URI templateURI = getTemplateURI(new File(testFolderPath)); setTemplateFileName(generation, URI.decode(templateURI.deresolve(genconfURI).toString())); queryEnvironment = GenconfUtils.getQueryEnvironment(generation); final List<Exception> exceptions = new ArrayList<>(); new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration(); resourceSetForModels = getResourceSetForModel(exceptions); documentTemplate = M2DocUtils.parse(resourceSetForModels.getURIConverter(), templateURI, queryEnvironment, new ClassProvider(this.getClass().getClassLoader())); for (Exception e : exceptions) { final XWPFRun run = documentTemplate.getDocument().getParagraphs().get(0).getRuns().get(0); documentTemplate.getBody().getValidationMessages() .add(new TemplateValidationMessage(ValidationMessageLevel.ERROR, e.getMessage(), run)); } variables = GenconfUtils.getVariables(generation, resourceSetForModels); }
@Test public void testWrongResource() throws Exception { Main main = LangATestLanguageFactory.eINSTANCE.createMain(); XMIResource xmiResource = new XMIResourceImpl(); xmiResource.getContents().add(main); assertTrue(languageSpecificValidator.validate(main, new BasicDiagnostic(), null)); assertTrue(languageSpecificValidator.validate(main, new BasicDiagnostic(), context)); context.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME, xtextResource.getLanguageName()); assertFalse(languageSpecificValidator.validate(main, new BasicDiagnostic(), context)); context.clear(); assertFalse(languageAgnosticValidator.validate(main, new BasicDiagnostic(), null)); assertFalse(languageAgnosticValidator.validate(main, new BasicDiagnostic(), context)); context.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME, xtextResource.getLanguageName()); assertFalse(languageAgnosticValidator.validate(main, new BasicDiagnostic(), context)); }
protected EPackage createExample() { ResourceSetImpl resourceSet = new ResourceSetImpl(); Resource resource = new XMIResourceImpl(URI.createURI("test")); resourceSet.getResources().add(resource); EPackage root = EcoreFactory.eINSTANCE.createEPackage(); resource.getContents().add(root); EClass child = EcoreFactory.eINSTANCE.createEClass(); root.getEClassifiers().add(child); return root; }
private Resource getResource(String resourceURI, String references) { XMIResourceImpl res = new XMIResourceImpl(); res.setURI(URI.createURI(resourceURI)); EcoreFactory f = EcoreFactory.eINSTANCE; EClass class1 = f.createEClass(); res.getContents().add(class1); class1.setName("mytype"); if (references!=null) { EClass referencedProxy = f.createEClass(); String fragment = res.getURIFragment(class1); ((InternalEObject)referencedProxy).eSetProxyURI(URI.createURI(references).appendFragment(fragment)); class1.getESuperTypes().add(referencedProxy); } return res; }
@Test public void testCrossResourceContainment() throws Exception { Element parent = CrossContainmentFactory.eINSTANCE.createElement(); Element child = CrossContainmentFactory.eINSTANCE.createElement(); parent.getContainment().add(child); Resource resource0 = new XMIResourceImpl(URI.createFileURI("test0.xmi")); resource0.getContents().add(parent); DefaultTransientValueService defaultTransientValueService = new DefaultTransientValueService(); assertTrue(defaultTransientValueService.isTransient(child, CrossContainmentPackage.Literals.ELEMENT__CONTAINER, 0)); Resource resource1 =new XMIResourceImpl(URI.createFileURI("test0.xmi")); resource1.getContents().add(child); assertEquals(parent, child.getContainer()); assertFalse(defaultTransientValueService.isTransient(child, CrossContainmentPackage.Literals.ELEMENT__CONTAINER, 0)); }
@Test public void getContainerEObjectNoCDOResource() { final CDOContainerProvider provider = new CDOContainerProvider(); final EObject element = MappingPackage.eINSTANCE.getMappingFactory().createBase(); final Resource r = new XMIResourceImpl(); r.getContents().add(element); final Object result = provider.getContainer(element); assertNull(result); }
/** * Updates the given {@link IEObjectContainer} with the given {@link Resource}. * * @param container * the {@link ILocationContainer} * @param eObjectContainer * the {@link IEObjectContainer} * @param newResource * the {@link Resource} * @throws Exception * if the XMI serialization failed */ public void updateEObjectContainer(ILocationContainer container, IEObjectContainer eObjectContainer, Resource newResource) throws Exception { if (eObjectContainer.getXMIContent() != null && !eObjectContainer.getXMIContent().isEmpty()) { final XMIResourceImpl oldResource = new XMIResourceImpl(URI.createURI("")); oldResource.load(new ByteArrayInputStream(eObjectContainer.getXMIContent().getBytes(UTF_8)), new HashMap<Object, Object>()); final IComparisonScope scope = new DefaultComparisonScope(oldResource, newResource, null); final Comparison comparison = EMFCompare.builder().build().compare(scope); for (ILocation child : new ArrayList<ILocation>(eObjectContainer.getContents())) { if (child instanceof IEObjectLocation && !child.isMarkedAsDeleted()) { final IEObjectLocation location = (IEObjectLocation)child; updateEObjectLocation(oldResource, comparison, location, needSavedURIFragment( newResource)); } } } eObjectContainer.getSavedURIFragments().clear(); if (needSavedURIFragment(newResource)) { updateSavedURIFragment(container, eObjectContainer, newResource); } final String newXMIContent = XMLHelperImpl.saveString(new HashMap<Object, Object>(), newResource .getContents(), UTF_8, null); eObjectContainer.setXMIContent(newXMIContent); }
@Override public Resource createResource(URI uri) { String domainID = DomainRegistry.determineDomainID(uri); if (domainID == null || DomainRegistry.getDomain(domainID) == null) { return new XMIResourceImpl(uri); } IDomain domain = DomainRegistry.getDomain(domainID); Injector injector = getInjector(domain); Resource resource = injector.getInstance(Resource.class); ResourceSet set = new ResourceSetImpl(); set.getResources().add(resource); resource.setURI(uri); return resource; }
private ResourceProfileMember createResourceProfileMember() { Profile profile0 = createProfileInResource("http://whatever.junit.org/profile0.xmi", ID0); Resource resource = new XMIResourceImpl(URI.createURI("http://whatever.junit.org/profileMember.xmi")); ResourceProfileMember member = ProfileFactory.eINSTANCE.createResourceProfileMember(); resource.getContents().add(member); member.getResourceProfiles().add(profile0); return member; }
protected void generateErrorSlice(String metamodelName, String errorSliceMMUri) throws IOException { XMIResourceImpl r = new XMIResourceImpl(URI.createURI(errorSliceMMUri)); new ErrorSliceGenerator(analyser, analyser.getDependencyGraph()) .generate(r); r.save(null); }
protected void generateErrorSlice(String metamodelName, String errorSliceMMUri, String location) throws IOException { XMIResourceImpl r = new XMIResourceImpl(URI.createURI(errorSliceMMUri)); new ErrorSliceGenerator(analyser, analyser.getDependencyGraph()) .generate(r, location); r.save(null); }
private void run() throws Exception { Resource atlTrafo = AtlLoader.load(TRANSFORMATION); AnalysisLoader loader = AnalysisLoader.fromResource(atlTrafo, new Object[] { UML_METAMODEL, JAVA_METAMODEL }, new String[] { "UML", "Java" }); AnalysisResult result = loader.analyse(); // Extract the footprint XMIResourceImpl r = new XMIResourceImpl(URI.createURI("examples/uml2java/metamodels/UML_footprint.ecore")); TrafoMetamodelData data = new TrafoMetamodelData(result.getATLModel(), result.getNamespace().getNamespace("UML")); new EffectiveMetamodelBuilder(data).extractSource(r, "uml_footprint", "http://uml_footprint", "uml_footprint", "UML Footprint"); r.save(null); }
private EObject loadWithEMF(final File file) throws IOException { registerEPackageFromEcore("java", "http://www.eclipse.org/MoDisco/Java/0.2.incubation/java"); registerEPackageFromEcore("uml", "http://schema.omg.org/spec/UML/2.1"); Resource resource = new XMIResourceImpl(); resource.load(new FileInputStream(file), Collections.emptyMap()); return resource.getContents().get(0); }
private static void init() { IConfigurationElement[] elements = Platform.getExtensionRegistry() .getConfigurationElementsFor( "org.scaledl.overview.Specification"); for (IConfigurationElement el : elements) { try { IExtension declaringExtension = el.getDeclaringExtension(); IContributor contributor = declaringExtension.getContributor(); Bundle bundle = Platform.getBundle(contributor.getName()); // Specification model URL -- this is correct way to get URI in product URL fileURL = bundle.getEntry(el.getAttribute("model")); URL resolvedFileURL = FileLocator.toFileURL(fileURL); URI resolvedURI = new URI (resolvedFileURL.getProtocol(), resolvedFileURL.getPath(), null); File file = new File(resolvedURI); // Load specification resource and add specification to registry XMIResourceImpl resource = new XMIResourceImpl(); //File file = new File(FileLocator.resolve(fileURL).toURI()); resource.load(new FileInputStream(file), new HashMap<Object,Object>()); Specification specification = (Specification)resource.getContents().get(0); instance.addSpecification(specification); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public static Collection<ASGAnnotation> loadAnnotations(ResultAlternative resultFolder) { IFile resultFile = (IFile)resultFolder.getSubResource(ToolchainUtils.KEY_FILE_ANTIPATTERNS_PSA); if (resultFile == null) return null; URI resultUri = URI.createPlatformResourceURI(resultFile.getFullPath().toString(), true); ResourceSet ress = new ResourceSetImpl(); Resource res = ress.getResource(resultUri, true); // load resource try { res.load(getLoadOptions((XMIResourceImpl) res)); } catch (IOException e) { e.printStackTrace(); return new TreeSet<ASGAnnotation>(); } // get annotations Set<ASGAnnotation> annos = new HashSet<ASGAnnotation>(); for (EObject element : res.getContents()) { if (element instanceof ASGAnnotation) { annos.add((ASGAnnotation) element); } } return annos; }
protected static Map<Object, Object> getLoadOptions(XMIResourceImpl resource) { Map<Object, Object> options = resource.getDefaultLoadOptions(); options.put(XMLResource.OPTION_DEFER_ATTACHMENT, Boolean.TRUE); options.put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE); options.put(XMLResource.OPTION_USE_DEPRECATED_METHODS, Boolean.TRUE); options.put(XMLResource.OPTION_USE_PARSER_POOL, new XMLParserPoolImpl()); options.put(XMLResource.OPTION_USE_XML_NAME_TO_FEATURE_MAP, new HashMap<Object, Object>()); resource.setIntrinsicIDToEObjectMap(new HashMap<String, EObject>()); return options; }
private MGridConfigurationSet getConfiguration(String configFile) throws IOException { GridPackage.eINSTANCE.eClass(); Resource resourceModel = new XMIResourceImpl(); resourceModel.load(PersonSample.class.getResourceAsStream(configFile), null); //$NON-NLS-1$ MGrid config = (MGrid) resourceModel.getContents().get(0); return config.getDefaultConfiguration(); }
private void writeGenModel(GenModel genModel, final String genModelLocation) { try { org.eclipse.emf.common.util.URI genModelURI = URI.createFileURI(genModelLocation); final XMIResourceImpl genModelResource = new XMIResourceImpl(genModelURI); //genModelResource.getDefaultSaveOptions().put(XMLResource.OPTION_ENCODING, Constants.GEN_MODEL_XML_ENCODING.getValue()); genModelResource.getContents().add(genModel); genModelResource.save(Collections.EMPTY_MAP); } catch (IOException e) { MessageDialog.openError(shell, "Write Gen Model", e.getMessage()); } }
private StringBuffer extractSource(QJob job, Document document) throws ParserConfigurationException, SAXException, IOException, OperatingSystemRuntimeException, IntegratedLanguageExpressionException { StringBuffer src = null; // search reference NodeList nl = document.getElementsByTagName("reference"); if (nl.getLength() > 0) { Element reference = (Element) nl.item(0); String fileName = reference.getAttribute("file"); String memberName = reference.getAttribute("member"); QSourceEntry source = null; for (String library : job.getLibraries()) { QSourceEntry file = sourceManager.getObjectEntry(job, library, QFile.class, fileName); if (file == null) continue; source = sourceManager.getChildEntry(job, file, memberName + ".XMI"); if (source != null) break; } if (source == null) throw new IOException("Invalid SRC reference: "+ fileName + "/" + memberName + ".XMI"); Resource resource = new XMIResourceImpl(); resource.load(source.getInputStream(), null); QFileMember qFileMember = (QFileMember) resource.getContents().get(0); src = loadMember(qFileMember); } return src; }