Java Code Examples for org.eclipse.emf.ecore.resource.Resource#save()

The following examples show how to use org.eclipse.emf.ecore.resource.Resource#save() . 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: ModelWriter.java    From orcas with Apache License 2.0 6 votes vote down vote up
public static String getSkriptXml( Model pModel )
{
  Resource.Factory.Registry lRegistry = Resource.Factory.Registry.INSTANCE;
  Map<String,Object> lMap = lRegistry.getExtensionToFactoryMap();
  lMap.put( "xml", new XMLResourceFactoryImpl() );

  ResourceSet lResourceSet = new ResourceSetImpl();
  Resource lResource = lResourceSet.createResource( URI.createFileURI( "*.xml" ) );

  ((XMLResource)lResource).getDefaultSaveOptions();

  lResource.getContents().add( pModel );
  try
  {
    ByteArrayOutputStream lByteArrayOutputStream = new ByteArrayOutputStream();
    lResource.save( lByteArrayOutputStream, Collections.EMPTY_MAP );

    return new String( lByteArrayOutputStream.toByteArray() );
  }
  catch( IOException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 2
Source File: FormatterSerializerIntegrationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testFormatterIntegrationWithSerializer() {
  try {
    final Resource resource = this.factory.createResource(URI.createURI("dummy.ext"));
    new ResourceSetImpl().getResources().add(resource);
    final IDList model = FormattertestlanguageFactory.eINSTANCE.createIDList();
    EList<String> _ids = model.getIds();
    _ids.add("foo");
    EList<EObject> _contents = resource.getContents();
    _contents.add(model);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedOutputStream _bufferedOutputStream = new BufferedOutputStream(out);
    resource.save(_bufferedOutputStream, Collections.<Object, Object>emptyMap());
    Assert.assertEquals("idlist  foo", out.toString());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 3
Source File: AbstractDefFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void doSave(final Object content) {
    if (content instanceof ConnectorDefinition) {
        final Resource emfResource = getEMFResource();
        emfResource.getContents().clear();
        final DocumentRoot root = ConnectorDefinitionFactory.eINSTANCE.createDocumentRoot();
        root.setConnectorDefinition((ConnectorDefinition) EcoreUtil.copy((EObject) content));
        emfResource.getContents().add(root);
        try {
            final Map<String, Object> options = new HashMap<String, Object>();
            options.put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE);
            options.put(XMLResource.OPTION_ENCODING, "UTF-8");
            emfResource.save(options);
        } catch (final IOException e) {
            BonitaStudioLog.error(e);
        }
    }
}
 
Example 4
Source File: Main.java    From ArduinoML-kernel with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void ArduinoML2xmi(String modelPath, String destinationPath) throws IOException{
       // register ArduinoML
	ResourceSet resources = new ResourceSetImpl();
    Map<String, Object> packageRegistry = resources.getPackageRegistry();
       packageRegistry.put(arduinoML.ArduinoMLPackage.eNS_URI, arduinoML.ArduinoMLPackage.eINSTANCE);
	
	// load ArduinoML dependencies 
	Injector injector = new ArduinoMLStandaloneSetup().createInjectorAndDoEMFRegistration();
	XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
	
	// load the dsl file and parse it
	URI uri = URI.createURI(modelPath);
	Resource xtextResource = resourceSet.getResource(uri, true);
	EcoreUtil.resolveAll(xtextResource);
	Resource xmiResource = resourceSet.createResource(URI.createURI(destinationPath));
	// add the root (often forgotten)
	xmiResource.getContents().add(xtextResource.getContents().get(0));
	
	xmiResource.save(null);
}
 
Example 5
Source File: OrganizationFileStore.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void doSave(final Object content) {
    if (content instanceof Organization) {
        final Resource emfResource = getEMFResource();
        emfResource.getContents().clear();
        final DocumentRoot root = OrganizationFactory.eINSTANCE.createDocumentRoot();
        root.setOrganization((Organization) EcoreUtil.copy((EObject) content));
        emfResource.getContents().add(root);
        try {
            final Map<Object, Object> options = new HashMap<>();
            options.put(XMLResource.OPTION_ENCODING, "UTF-8");
            options.put(XMLResource.OPTION_XML_VERSION, "1.0");
            if (emfResource instanceof XMLResourceImpl) {
                options.putAll(((XMLResourceImpl) emfResource).getDefaultSaveOptions());
            }
            emfResource.save(options);
        } catch (final IOException e) {
            BonitaStudioLog.error(e);
        }
    }
}
 
Example 6
Source File: SerializerImpl.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
public void write( DesignValues cModel, OutputStream os )
		throws IOException
{
	DocumentRoot documentRoot = ModelFactory.eINSTANCE.createDocumentRoot( );
	documentRoot.setDesignValues( cModel );

	cModel.setVersion( IConstants.DESINGER_VALUES_VERSION );
	
	ModelXMLProcessor xmlProcessor = new ModelXMLProcessor( );
	Resource resource = xmlProcessor.createResource( URI
			.createFileURI( "test.designValue" ) ); //$NON-NLS-1$
	resource.getContents( ).add( documentRoot );

	Map options = new HashMap( );
	options.put( XMLResource.OPTION_ENCODING, "UTF-8" ); //$NON-NLS-1$

	resource.save( os, options );
}
 
Example 7
Source File: SGenNewFileWizard.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
private Resource createDefaultModel(URI uri) {
	List<EObject> selectedObjects = generatorConfigPage.getSelectedElements();
	IGeneratorDescriptor selectedGenerator = generatorConfigPage.getSelectedGenerator();
	ModelCreator creator = new ModelCreator(selectedGenerator, selectedObjects);
	GeneratorModel model = creator.create();

	Resource resource = resourceSet.createResource(uri);
	resource.getContents().add(model);
	try {
		resource.save(Collections.EMPTY_MAP);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return resource;
}
 
Example 8
Source File: CommonPackageHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Inject the CA bootstrap property to the profile
 *
 * @param file
 *            the profile.xml file in the package target
 * @throws IOException
 */
protected void patchProfile ( final String appName, final File file ) throws IOException
{
    final ResourceSet rs = new ResourceSetImpl ();
    final Resource r = rs.createResource ( URI.createFileURI ( file.toString () ) );
    r.load ( null );

    final Profile profile = (Profile)EcoreUtil.getObjectByType ( r.getContents (), ProfilePackage.Literals.PROFILE );
    Profiles.addSystemProperty ( profile, "org.eclipse.scada.ca.file.provisionJsonUrl", "file:///usr/share/" + Constants.NEOSCADA_USER + "/ca.bootstrap/bootstrap." + appName + ".json" );
    r.save ( null );
}
 
Example 9
Source File: CreateProjectOperation.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected static Resource save ( final ResourceSet rs, final URI base, final String localName, final EObject content, final String contentType ) throws IOException
{
    final Resource resource = rs.createResource ( base.appendSegments ( localName.split ( "\\/" ) ), contentType );
    resource.getContents ().add ( content );
    resource.save ( null );
    return resource;
}
 
Example 10
Source File: ChartView.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void saveState ( final IMemento memento )
{
    super.saveState ( memento );
    if ( memento == null )
    {
        return;
    }

    final Resource resource = new XMIResourceFactoryImpl ().createResource ( null );
    resource.getContents ().add ( this.configuration );

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();

    final Map<?, ?> options = new HashMap<Object, Object> ();

    try
    {
        resource.save ( outputStream, options );
        final IMemento child = memento.createChild ( CHILD_CONFIGURATION );

        child.putTextData ( StringUtils.newStringUtf8 ( Base64.encodeBase64 ( outputStream.toByteArray (), true ) ) );
    }
    catch ( final Exception e )
    {
        StatusManager.getManager ().handle ( StatusHelper.convertStatus ( Activator.PLUGIN_ID, e ), StatusManager.LOG );
    }
}
 
Example 11
Source File: RefactorActorMappingsOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
        InterruptedException {
    monitor.beginTask(Messages.refactoringActorMappings, IProgressMonitor.UNKNOWN);

    final ProcessConfigurationRepositoryStore confStore = RepositoryManager.getInstance()
            .getRepositoryStore(ProcessConfigurationRepositoryStore.class);
    final DiagramRepositoryStore diagramStore = RepositoryManager.getInstance()
            .getRepositoryStore(DiagramRepositoryStore.class);

    final Comparison comparison = compareOrganizations();

    List<Configuration> configurations = getConfigurations(confStore, diagramStore);
    for (Configuration config : configurations) {
        EditingDomain editingDomain = TransactionUtil.getEditingDomain(config);
        if (editingDomain == null) {
            editingDomain = confStore.getEditingDomain();
        }
        refactorConfiguration(config, comparison, editingDomain);
        if(config.eContainer() == null) {
            try {
                final Resource eResource = config.eResource();
                if (eResource != null) {
                    eResource.save(Collections.emptyMap());
                }
            } catch (final IOException e) {
                BonitaStudioLog.error(e);
            }
        }
      
    }
    diagramStore.refresh();
}
 
Example 12
Source File: MetaModelHandler.java    From kieker with Apache License 2.0 5 votes vote down vote up
/**
 * Saves the given meta model project to the given file.
 * 
 * @param file
 *            The file in which the project will be stored.
 * @param project
 *            The meta model project.
 * 
 * @throws IOException
 *             If something went wrong during the saving.
 */
public static final void saveProjectToFile(final File file, final MIProject project) throws IOException {
	// Create a resource and put the given project into it
	final ResourceSet resourceSet = new ResourceSetImpl();
	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
	final Resource resource = resourceSet.createResource(URI.createFileURI(file.getAbsolutePath()));
	resource.getContents().add(project);

	// Make sure that the controller uses utf8 instead of ascii.
	final Map<String, String> options = new HashMap<String, String>(); // NOPMD (no concurrent access)
	options.put(XMLResource.OPTION_ENCODING, "UTF-8");

	// Now try to save the resource
	resource.save(options);
}
 
Example 13
Source File: LinkedEditingRefactoringIntegrationTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testRefactorEcoreCrossLanguage() throws Exception {
	EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage();
	ePackage.setName("test");
	ePackage.setNsPrefix("test");
	ePackage.setNsURI("http://test");
	EClass eClass = EcoreFactory.eINSTANCE.createEClass();
	eClass.setName(TEST_CLASS);
	ePackage.getEClassifiers().add(eClass);
	Resource ecoreResource = new ResourceSetImpl().createResource(URI.createPlatformResourceURI(TEST_PROJECT + "/Test.ecore", true));
	ecoreResource.getContents().add(ePackage);
	ecoreResource.save(null);
	ecoreResource.unload();
	project.refreshLocal(IResource.DEPTH_INFINITE, null);
	
	String model = "ref test." + TEST_CLASS;
	IFile file = createFile(TEST_PROJECT + "/ref.referringtestlanguage", model);
	waitForBuild();
	final XtextEditor editor = openEditor(file);
	final TextSelection selection = new TextSelection(model.indexOf(TEST_CLASS), TEST_CLASS.length());
	editor.getSelectionProvider().setSelection(selection);
	waitForDisplay();
	IRenameElementContext context = editor.getDocument().readOnly(new IUnitOfWork<IRenameElementContext, XtextResource>() {
		@Override
		public IRenameElementContext exec(XtextResource state) throws Exception {
			Reference ref = (Reference) state.getContents().get(0).eContents().get(0);
			EObject referenced = ref.getReferenced();
			assertNotNull(referenced);
			return new IRenameElementContext.Impl(EcoreUtil.getURI(referenced), referenced.eClass(), editor, selection, state.getURI());
		}
	});
	renameRefactoringController.startRefactoring(context);
	waitForDisplay();
	pressKeys(editor, "NewTestClass\n");
	waitForReconciler(editor);
	waitForDisplay();
	waitForBuild();
	ecoreResource.load(null);
	assertEquals("NewTestClass", ((EPackage)ecoreResource.getContents().get(0)).getEClassifiers().get(0).getName());
}
 
Example 14
Source File: RepositoryContentHandlerV2.java    From ADT_Frontend with MIT License 5 votes vote down vote up
@Override
public IMessageBody serialize(IRepositories repositories, Charset charset) {

	Resource resource = new AbapgitrepositoriesResourceFactoryImpl().createResource(this.virtualResourceUri);
	resource.getContents().add(repositories);

	ByteArrayOutputStream outputStream = new ByteArrayOutputStream(FileUtils.DEFAULT_BUF_SIZE);

	try {
		resource.save(outputStream, null);
	} catch (IOException e) {
		throw new ContentHandlerException("Error while serializing repositories ", e); //$NON-NLS-1$
	}
	return new MessageBody(outputStream);
}
 
Example 15
Source File: SerializerImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public ByteArrayOutputStream asXml( Chart cModel, boolean bStripHeaders )
		throws IOException
{
	// REMOVE ANY TRANSIENT RUNTIME SERIES
	cModel.clearSections( IConstants.RUN_TIME );

	ByteArrayOutputStream baos = new ByteArrayOutputStream( );

	// Create and setup local ResourceSet
	ResourceSet rsChart = new ResourceSetImpl( );
	rsChart.getResourceFactoryRegistry( )
			.getExtensionToFactoryMap( )
			.put( "chart", new ModelResourceFactoryImpl( ) ); //$NON-NLS-1$

	// Create resources to represent the disk files to be used to store the
	// models
	Resource rChart = rsChart.createResource( URI.createFileURI( "test.chart" ) ); //$NON-NLS-1$

	// Add the chart to the resource
	rChart.getContents( ).add( cModel );

	Map<String, Object> options = new HashMap<String, Object>( );
	options.put( XMLResource.OPTION_ENCODING, "UTF-8" ); //$NON-NLS-1$
	if ( bStripHeaders )
	{
		options.put( XMLResource.OPTION_DECLARE_XML, Boolean.FALSE );
	}

	// Save the resource to disk
	rChart.save( baos, options );
	return baos;
}
 
Example 16
Source File: AbstractURIHandlerTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected byte[] getBytes(Resource resource) throws Exception {
	ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
	resource.save(out, null);
	byte[] bytes = out.toByteArray();
	return bytes;
}
 
Example 17
Source File: ModelDefinitionItemProviderTests.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Initializes test resources.
 */
@Before
public void before() {
    final ResourceSet rs = new ResourceSetImpl();
    rs.getURIConverter().getURIHandlers().add(0, uriHandler);
    rs.getResourceFactoryRegistry().getContentTypeToFactoryMap().put("*", new XMIResourceFactoryImpl());
    final Resource res = rs
            .createResource(URI.createURI(TestMemoryURIHandler.PROTOCOL + "://resources/test.genconf", false));

    final Generation generation = GenconfPackage.eINSTANCE.getGenconfFactory().createGeneration();
    generation.setTemplateFileName("test.docx");
    res.getContents().add(generation);

    definition = GenconfPackage.eINSTANCE.getGenconfFactory().createModelDefinition();
    definition.setKey("self");
    generation.getDefinitions().add(definition);

    final EPackage ePkg1 = EcorePackage.eINSTANCE.getEcoreFactory().createEPackage();
    ePkg1.setName("package1");
    final EPackage ePkg2 = EcorePackage.eINSTANCE.getEcoreFactory().createEPackage();
    ePkg2.setName("package2");
    final EPackage ePkg3 = EcorePackage.eINSTANCE.getEcoreFactory().createEPackage();
    ePkg3.setName("package3");
    final EClass eCls1 = EcorePackage.eINSTANCE.getEcoreFactory().createEClass();
    eCls1.setName("Class1");
    final EClass eCls2 = EcorePackage.eINSTANCE.getEcoreFactory().createEClass();
    eCls2.setName("Class2");
    final EClass eCls3 = EcorePackage.eINSTANCE.getEcoreFactory().createEClass();
    eCls3.setName("Class3");

    res.getContents().add(ePkg1);
    res.getContents().add(ePkg2);
    res.getContents().add(ePkg3);

    res.getContents().add(eCls1);
    res.getContents().add(eCls2);
    res.getContents().add(eCls3);

    try {
        res.save(null);
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    document = new XWPFDocument();

    properties = new TemplateCustomProperties(document);
    properties.getPackagesURIs().add(GenconfPackage.eINSTANCE.getNsURI());
}
 
Example 18
Source File: EMFGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
private void saveResource(Resource resource) throws IOException {
	Map<String, Object> saveOptions = Maps.newHashMap();
	saveOptions.put(XMLResource.OPTION_URI_HANDLER, new ToPlatformResourceDeresolvingURIHandler());
	saveOptions.put(Resource.OPTION_LINE_DELIMITER, getLineDelimiter());
	resource.save(saveOptions);
}
 
Example 19
Source File: DiagramRepositoryStore.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected InputStream handlePreImport(final String fileName,
        final InputStream inputStream) throws MigrationException, IOException {
    
    DiagramFileStore fileStore = getChild(fileName, false);
    Display.getDefault().syncExec(() ->  {
        if(fileStore != null && fileStore.isOpened()) {
            fileStore.close();
        }
    });
   
    CopyInputStream copyIs = null;
    Resource diagramResource = null;
    try {
        final InputStream is = super.handlePreImport(fileName, inputStream);
        copyIs = new CopyInputStream(is);
        diagramResource = getTmpEMFResource("beforeImport.proc",
                copyIs.getFile());

        diagramResource.load(Collections.EMPTY_MAP);
        if (diagramResource.getContents().isEmpty()) {
            throw new IOException("Resource is empty.");
        }

        final Iterable<EObject> mainProcess = filter(diagramResource.getContents(), instanceOf(MainProcess.class));
        final Iterator<EObject> iterator = mainProcess.iterator();
        final MainProcess diagram = (MainProcess) iterator.next();
        if (iterator.hasNext()) {
            throw new IOException(
                    "Resource content is invalid. There should be only one MainProcess per .proc file.");
        }
        if (diagram == null) {
            throw new IOException("Resource content is null.");
        }

        if (!ConfigurationIdProvider.getConfigurationIdProvider()
                .isConfigurationIdValid(diagram)) {
            return openError(fileName);
        }
        //Sanitize model
        new RemoveDanglingReferences(diagram).execute();
        diagram.eResource().getContents().stream().filter(Diagram.class::isInstance).findFirst()
                .ifPresent(d -> new RemoveDanglingReferences(d).execute());
        diagram.eResource().getContents().removeIf(eObject -> isFormDiagram(eObject));
        updateConfigurationId(diagramResource, diagram);

        ProcessConfigurationRepositoryStore confStore = RepositoryManager.getInstance()
                .getRepositoryStore(ProcessConfigurationRepositoryStore.class);
        for (Pool process : ModelHelper.getAllElementOfTypeIn(diagram, Pool.class)) {
            ProcessConfigurationFileStore file = confStore.getChild(ModelHelper.getEObjectID(process) + ".conf",
                    true);
            if (file != null) {
                synchronizer.synchronize(process, file.getContent());
            }
            process.getConfigurations().stream().forEach(conf -> synchronizer.synchronize(process, conf));
        }
        try {
            diagramResource.save(ProcessDiagramEditorUtil.getSaveOptions());
        } catch (final IOException e) {
            BonitaStudioLog.error(e);
        }

        return new FileInputStream(new File(diagramResource.getURI()
                .toFileString()));
    } finally {
        if (copyIs != null) {
            copyIs.close();
        }
        if (diagramResource != null) {
            diagramResource.delete(Collections.emptyMap());
        }
    }
}
 
Example 20
Source File: GenconfUtils.java    From M2Doc with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Save the contents of the resource to the file system.
 * 
 * @param resource
 *            Resource
 * @throws IOException
 *             if the resource can't be serialized
 */
private static void saveResource(Resource resource) throws IOException {
    Map<Object, Object> options = new HashMap<>();
    options.put(XMLResource.OPTION_ENCODING, "UTF-8");
    resource.save(options);
}