Java 类org.eclipse.emf.ecore.xmi.XMIResource 实例源码

项目:neoscada    文件:FactoryImpl.java   
@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 );
}
项目:xtext-extras    文件:SrcSegmentsInUrisAreNotRemovedTests.java   
@Before
public void setUp() throws Exception {

    EcoreResourceFactoryImpl resFactory = new EcoreResourceFactoryImpl();
    set.getResourceFactoryRegistry().getExtensionToFactoryMap()
            .put("ecore", resFactory);

    aRes = (XMIResource) set.createResource(URI.createPlatformResourceURI(
            "/myProject/main/src/some/package/a.ecore", true));
    InputStream stream = new ByteArrayInputStream(
            aResContent.getBytes("US-ASCII"));
    aRes.load(stream, set.getLoadOptions());
    stream.close();

    bRes = (XMIResource) set.createResource(URI.createPlatformResourceURI(
            "/myProject/model/b.ecore", true));

    stream = new ByteArrayInputStream(
            bResContent.getBytes("US-ASCII"));
    bRes.load(stream, set.getLoadOptions());
    stream.close();

}
项目:NoSQLDataEngineering    文件:BuildNoSQLSchema.java   
private void schema2File(NoSQLSchemaPackage packageInstance, NoSQLSchema schema, String outputFile)
{
    // Create a new resource to serialize the ecore model
    Resource outputRes = new ResourceManager(packageInstance).getResourceSet().createResource(URI.createFileURI(outputFile));
    // Add our new package to resource contents
    outputRes.getContents().add(schema);

    // Make the actual URI to be exported in the generated models. This
    // allows using the models without having to register them.
    packageInstance.eResource().setURI(URI.createPlatformResourceURI("es.um.nosql.schemainference/model/nosqlschema.ecore", true));
    Map<Object,Object> options = new HashMap<Object,Object>();
    options.put(XMIResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);
    options.put(XMIResource.OPTION_ENCODING, "UTF-8");

    try
    {
        outputRes.save(new FileOutputStream(outputFile), options);
    } catch (IOException e)
    {
        e.printStackTrace();
    }       
}
项目:xtext-core    文件:SrcSegmentsInUrisAreNotRemovedTests.java   
@Before
public void setUp() throws Exception {
    globalStateMemento = GlobalRegistries.makeCopyOfGlobalState();
    EPackage.Registry.INSTANCE.put(XMLTypePackage.eNS_URI, XMLTypePackage.eINSTANCE);
    EcoreResourceFactoryImpl resFactory = new EcoreResourceFactoryImpl();
    set.getResourceFactoryRegistry().getExtensionToFactoryMap()
            .put("ecore", resFactory);

    aRes = (XMIResource) set.createResource(URI.createPlatformResourceURI(
            "/myProject/main/src/some/package/a.ecore", true));
    InputStream stream = new ByteArrayInputStream(
            aResContent.getBytes("US-ASCII"));
    aRes.load(stream, set.getLoadOptions());
    stream.close();

    bRes = (XMIResource) set.createResource(URI.createPlatformResourceURI(
            "/myProject/model/b.ecore", true));

    stream = new ByteArrayInputStream(
            bResContent.getBytes("US-ASCII"));
    bRes.load(stream, set.getLoadOptions());
    stream.close();

}
项目:NEXCORE-UML-Modeler    文件:DomainModelHandlerUtil.java   
/**
     * 저장시 사용하는 옵션 반환
     * 
     * @return Map<Object,Object>
     */
    public static Map<Object, Object> getSaveOptions() {
        Map<Object, Object> saveOptions = new HashMap<Object, Object>();

        saveOptions.put(XMIResource.OPTION_ENCODING, UMLResource.DEFAULT_ENCODING);
        saveOptions.put(XMIResource.OPTION_USE_XMI_TYPE, true);
        saveOptions.put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
        saveOptions.put(XMLResource.OPTION_USE_DEPRECATED_METHODS, lookupTable);
        saveOptions.put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, true);
        saveOptions.put(XMLResource.OPTION_SAVE_ONLY_IF_CHANGED, true);
        saveOptions.put(XMLResource.OPTION_PROCESS_DANGLING_HREF, XMLResource.OPTION_PROCESS_DANGLING_HREF_RECORD);
        saveOptions.put(XMLResource.OPTION_SCHEMA_LOCATION, true);
//        saveOptions.put(XMLResource.OPTION_FLUSH_THRESHOLD, true);

        return saveOptions;
    }
项目:mondo-demo-wt    文件:PerformantXMIResourceFactoryImpl.java   
@Override
public Resource createResource(URI uri)
{
    XMIResource resource = new PerformantXMIResourceImpl(uri);

    /*Save Options*/
    Map saveOptions = resource.getDefaultSaveOptions();
    saveOptions.put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
    saveOptions.put(XMLResource.OPTION_USE_CACHED_LOOKUP_TABLE, lookupTable);


    /*Load Options*/

    Map loadOptions = resource.getDefaultLoadOptions();
    loadOptions.put(XMLResource.OPTION_DEFER_ATTACHMENT, Boolean.TRUE);
    loadOptions.put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
    loadOptions.put(XMLResource.OPTION_USE_DEPRECATED_METHODS, Boolean.TRUE);
    loadOptions.put(XMLResource.OPTION_USE_PARSER_POOL, parserPool);
    loadOptions.put(XMLResource.OPTION_USE_XML_NAME_TO_FEATURE_MAP, nameToFeatureMap);


    return resource;        
}
项目:ArduinoML-kernel    文件:Main.java   
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);
}
项目:ModelDebugging    文件:ModelExecutor.java   
private void persistTracemodel(String tracemodelPath, EObject stateSystem) {
    URI outputUri = EMFUtil.createFileURI(tracemodelPath);
    Resource traceResource = resourceSet.createResource(outputUri);

    Command cmd = new AddCommand(editingDomain,
            traceResource.getContents(), stateSystem);
    editingDomain.getCommandStack().execute(cmd);

    HashMap<String, Object> options = new HashMap<String, Object>();
    options.put(XMIResource.OPTION_SCHEMA_LOCATION, true);

    // TODO what is the matter with hrefs?
    options.put(XMIResource.OPTION_PROCESS_DANGLING_HREF,
            XMIResource.OPTION_PROCESS_DANGLING_HREF_DISCARD);
    try {
        traceResource.save(options);
    } catch (IOException e) {
        e.printStackTrace();
        Assert.fail();
    }
}
项目:emfstore-rest    文件:ModelUtil.java   
/**
 * Copies the given EObject and converts it to a string.
 * 
 * @param object
 *            the eObject
 * @return the string representation of the EObject
 * @throws SerializationException
 *             if a serialization problem occurs
 */
public static String eObjectToString(EObject object) throws SerializationException {

    if (object == null) {
        return null;
    }

    final ResourceSetImpl resourceSetImpl = new ResourceSetImpl();
    resourceSetImpl.setResourceFactoryRegistry(new ResourceFactoryRegistry());
    final XMIResource res = (XMIResource) resourceSetImpl.createResource(VIRTUAL_URI);
    ((ResourceImpl) res).setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());

    EObject copy;
    if (object instanceof IdEObjectCollection) {
        copy = copyIdEObjectCollection((IdEObjectCollection) object, res);
    } else {
        copy = copyEObject(ModelUtil.getProject(object), object, res);
    }

    return copiedEObjectToString(copy, res);
}
项目:emfstore-rest    文件:ModelUtil.java   
/**
 * Converts the given {@link EObject} to a string.
 * 
 * @param copy The copied {@link EObject}.
 * @param resource The resource for the {@link EObject}.
 * @return The string representing the {@link EObject}.
 * @throws SerializationException If a serialization problem occurs.
 */
public static String copiedEObjectToString(EObject copy, XMIResource resource) throws SerializationException {
    final int step = 200;
    final int initialSize = step;
    resource.getContents().add(copy);

    final StringWriter stringWriter = new StringWriter(initialSize);
    final URIConverter.WriteableOutputStream uws = new URIConverter.WriteableOutputStream(stringWriter, "UTF-8");

    final String lineSeparator = System.getProperty("line.separator");
    try {
        System.setProperty("line.separator", "\r\n");
        resource.save(uws, getResourceSaveOptions());
    } catch (final IOException e) {
        throw new SerializationException(e);
    } finally {
        System.setProperty("line.separator", lineSeparator);
    }

    return stringWriter.toString();
}
项目:emfstore-rest    文件:ModelUtil.java   
/**
 * Computes the checksum for a given {@link IdEObjectCollection}.
 * The checksum for a collection is independent of the order of the
 * collection's elements at the root level.
 * 
 * @param collection
 *            the collection for which to compute a checksum
 * @return the computed checksum
 * 
 * @throws SerializationException
 *             in case any errors occur during computation of the checksum
 */
public static long computeChecksum(IdEObjectCollection collection) throws SerializationException {

    final ResourceSetImpl resourceSetImpl = new ResourceSetImpl();
    // TODO: do we need to instantiate the factory registry each time?
    resourceSetImpl.setResourceFactoryRegistry(new ResourceFactoryRegistry());
    final XMIResource res = (XMIResource) resourceSetImpl.createResource(VIRTUAL_URI);
    ((ResourceImpl) res).setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());
    final IdEObjectCollection copy = copyIdEObjectCollection(collection, res);

    ECollections.sort(copy.getModelElements(), new Comparator<EObject>() {
        public int compare(EObject o1, EObject o2) {
            return copy.getModelElementId(o1).getId().compareTo(copy.getModelElementId(o2).getId());
        }
    });

    final String serialized = copiedEObjectToString(copy, res);
    return computeChecksum(serialized);
}
项目:emfstore-rest    文件:ModelUtil.java   
/**
 * Save a list of EObjects to the resource with the given URI.
 * 
 * @param eObjects
 *            the EObjects to be saved
 * @param resourceURI
 *            the URI of the resource, which should be used to save the
 *            EObjects
 * @param options The save options for the resource.
 * @throws IOException
 *             if saving to the resource fails
 */
public static void saveEObjectToResource(List<? extends EObject> eObjects, URI resourceURI,
    Map<Object, Object> options) throws IOException {
    final ResourceSet resourceSet = new ResourceSetImpl();
    final Resource resource = resourceSet.createResource(resourceURI);
    final EList<EObject> contents = resource.getContents();

    for (final EObject eObject : eObjects) {
        contents.add(eObject);
        if (eObject instanceof Project && resource instanceof XMIResource) {
            setXmiIdsOnResource((Project) eObject, (XMIResource) resource);
        }
    }

    contents.addAll(eObjects);
    resource.save(options);
}
项目:emfstore-rest    文件:IdEObjectCollectionImpl.java   
/**
 * Removes the the given {@link EObject} from its {@link XMIResource}.
 * 
 * @param xmiResource
 *            the {@link EObject}'s resource
 * @param eObject
 *            the {@link EObject} to remove
 */
private void removeModelElementFromResource(EObject eObject) {

    if (!(eObject.eResource() instanceof XMIResource)) {
        return;
    }

    final XMIResource xmiResource = (XMIResource) eObject.eResource();

    if (xmiResource.getURI() == null) {
        return;
    }

    xmiResource.setID(eObject, null);

    try {
        ModelUtil.saveResource(xmiResource, ModelUtil.getResourceLogger());
    } catch (final IOException e) {
        throw new RuntimeException("XMI Resource for model element " + eObject + " could not be saved. "
            + "Reason: " + e.getMessage());
    }
}
项目:emfstore-rest    文件:IdEObjectCollectionImpl.java   
/**
 * Returns the {@link ModelElementId} for the given model element. If no
 * such ID exists, a new one will be created.
 * 
 * @param modelElement
 *            a model element to fetch a {@link ModelElementId} for
 * @return the {@link ModelElementId} for the given model element
 */
private ModelElementId getIdForModelElement(EObject modelElement) {

    final Resource resource = modelElement.eResource();

    if (resource != null && resource instanceof XMIResource) {
        // resource available, read ID
        final XMIResource xmiResource = (XMIResource) resource;
        try {
            ModelUtil.loadResource(xmiResource, ModelUtil.getResourceLogger());
        } catch (final IOException e) {
            throw new RuntimeException("Resource of model element " + modelElement + " couldn't be loaded");
        }
        final String id = xmiResource.getID(modelElement);
        if (id != null) {
            final ModelElementId objId = getNewModelElementID();
            objId.setId(id);
            return objId;
        }
    }

    // create new ID
    return getNewModelElementID();
}
项目:emfstore-rest    文件:ResourceHelper.java   
/**
 * Puts an element into a new resource.
 * 
 * @param <T> element type
 * @param element The element to be put
 * @param absoluteFileName filepath of resource
 * @param project the associated project
 * @throws IOException in case of failure
 */
public static <T extends EObject> void putElementIntoNewResourceWithProject(String absoluteFileName, T element,
    Project project) throws IOException {
    final ResourceSetImpl resourceSet = new ResourceSetImpl();
    final Resource resource = resourceSet.createResource(URI.createFileURI(absoluteFileName));
    resource.getContents().add(element);

    if (resource instanceof XMIResource) {
        final XMIResource xmiResource = (XMIResource) resource;
        for (final EObject modelElement : project.getAllModelElements()) {
            final String modelElementId = project.getModelElementId(modelElement).getId();
            xmiResource.setID(modelElement, modelElementId);
        }
    }

    ModelUtil.saveResource(resource, WorkspaceUtil.getResourceLogger());
}
项目:emfstore-rest    文件:ResourceHelper.java   
/**
 * Puts an element into a new resource.
 * 
 * @param <T> element type
 * @param workSpace the workspace to be put
 * @param absoluteFileName filepath of resource
 * @throws IOException in case of failure
 */
public static <T extends EObject> void putWorkspaceIntoNewResource(String absoluteFileName, Workspace workSpace)
    throws IOException {

    final ResourceSetImpl resourceSet = new ResourceSetImpl();
    final Resource resource = resourceSet.createResource(URI.createFileURI(absoluteFileName));
    resource.getContents().add(workSpace);

    if (resource instanceof XMIResource) {
        final XMIResource xmiResource = (XMIResource) resource;

        for (final ProjectSpace projectSpace : workSpace.getProjectSpaces()) {
            final Project project = projectSpace.getProject();
            final TreeIterator<EObject> it = project.eAllContents();
            while (it.hasNext()) {
                final EObject modelElement = it.next();
                final String modelElementId = project.getModelElementId(modelElement).getId();
                xmiResource.setID(modelElement, modelElementId);
            }
        }
    }

    ModelUtil.saveResource(resource, WorkspaceUtil.getResourceLogger());
}
项目:emfstore-rest    文件:ESRemoteProjectImpl.java   
private ProjectSpace initProjectSpace(final Usersession usersession, final ProjectInfo projectInfoCopy,
    Project project, String projectName) {

    final ProjectSpace projectSpace = ModelFactory.eINSTANCE.createProjectSpace();
    projectSpace.setProjectId(projectInfoCopy.getProjectId());
    projectSpace.setProjectName(projectName);
    projectSpace.setProjectDescription(projectInfoCopy.getDescription());
    projectSpace.setBaseVersion(projectInfoCopy.getVersion());
    projectSpace.setLastUpdated(new Date());
    projectSpace.setUsersession(usersession);
    projectSpace.setProject(project);
    projectSpace.setResourceCount(0);

    final ResourceSetImpl resourceSetImpl = new ResourceSetImpl();
    final XMIResource res = (XMIResource) resourceSetImpl.createResource(ModelUtil.VIRTUAL_URI);
    ((ResourceImpl) res).setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());
    res.getContents().add(project);

    projectSpace.setResourceSet(resourceSetImpl);

    return projectSpace;
}
项目:emfstore-rest    文件:VersionImpl.java   
/**
 * Loads the XMI IDs from the given resource and returns them in a map
 * together with the object each ID belongs to.
 * 
 * @param resource
 *            the resource from which to load the ID mappings
 * @return a map consisting of object/id mappings, if the resource doesn't
 *         contain an eobject/id mapping null will be returned
 */
private EMap<EObject, String> loadIdsFromResourceForEObjects(Set<EObject> modelElements, XMIResource xmiResource) {

    EMap<EObject, String> eObjectToIdMap;

    if (xmiResource != null) {
        // guess a rough initial size by looking at the size of the contents
        eObjectToIdMap = new BasicEMap<EObject, String>(xmiResource.getContents().size());

        for (EObject eObject : modelElements) {
            String objId = xmiResource.getID(eObject);
            if (objId != null) {
                eObjectToIdMap.put(eObject, objId);
            }
        }

        return eObjectToIdMap;
    }

    return null;
}
项目:emfstore-rest    文件:VersionImpl.java   
private void initProjectStateAfterLoad(ProjectImpl project) {
    Resource resource = project.eResource();
    if (resource instanceof XMIResource) {
        Set<EObject> allContainedModelElements = ModelUtil.getAllContainedModelElements(project, false);
        EMap<EObject, String> eObjectToIdMap = loadIdsFromResourceForEObjects(allContainedModelElements,
            (XMIResource) resource);

        // create reverse mapping
        Map<String, EObject> idToEObjectMap = new LinkedHashMap<String, EObject>(eObjectToIdMap.size());

        for (Map.Entry<EObject, String> entry : eObjectToIdMap.entrySet()) {
            idToEObjectMap.put(entry.getValue(), entry.getKey());
        }

        project.initMapping(eObjectToIdMap.map(), idToEObjectMap);
    }
}
项目:emfstore-rest    文件:TO.java   
/**
 * converts an EObject to a String as XML without beeing a complete XML-Document (i. e. no documentType header)
 * @param object
 * @return
 * @throws SerializationException
 */
protected String serializeEObjectToString(EObject object) throws SerializationException {

    if (object == null) {
        return null;
    }

    //create a XMLResource and convert the eObject ot a String 
    final ResourceSetImpl resourceSetImpl = new ResourceSetImpl();
    resourceSetImpl.setResourceFactoryRegistry(new ResourceFactoryRegistry());
    final XMIResource res = (XMIResource) resourceSetImpl.createResource(VIRTUAL_URI);
    ((ResourceImpl) res).setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());

    String resultFullXmlDoc = ModelUtil.copiedEObjectToString(object, res);

    //remove the xml doc declaration
    String xmlDocDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    int lastIndexOfXmlDocDeclaration = resultFullXmlDoc.lastIndexOf(xmlDocDecl);
    String result = resultFullXmlDoc.substring(lastIndexOfXmlDocDeclaration + xmlDocDecl.length() + 1).trim();

    //TODO: Remove debug println!
    System.out.println("\n\nProjectDataTO.serializeEObjectToString result:\n" + result + "\n\n");

    return result;
}
项目:n4js    文件:UserdataMapper.java   
/**
 * <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);
}
项目:n4js    文件:UserdataMapper.java   
/**
 * 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;
}
项目:neoscada    文件:WorldResourceFactoryImpl.java   
/**
 * Creates an instance of the resource.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 *
 * @generated NOT
 */
@Override
public Resource createResource ( final URI uri )
{
    final XMIResource result = new WorldResourceImpl ( uri );

    result.getDefaultSaveOptions ().put ( XMLResource.OPTION_URI_HANDLER, new URIHandlerImpl.PlatformSchemeAware () );

    return result;
}
项目:OCCI-Studio    文件:ConverterUtils.java   
public static void save(ResourceSet resourceSet, EObject rootElement, String path) throws IOException {
    Resource resource = resourceSet.createResource(URI.createURI(path));
    resource.getContents().add(rootElement);
    Map<String, String> options = new HashMap<String, String>();
    options.put(XMIResource.OPTION_ENCODING, "UTF-8");
    resource.save(options);
}
项目:org.lovian.eaxmireader    文件:InitResourceSet.java   
/**
 * Initialize the UML resourceSet and register all the packages by default
 * 
 * @return resourceSet
 * @throws IOException
 */
public ResourceSet initResourceSet() throws IOException {
    String method = "InitResourceSet_initResourceSet(): ";
    long startTime = System.currentTimeMillis();
    MyLog.info(method + "start");

    ResourceSet resourceSet = new ResourceSetImpl();
    Registry packageRegistry = resourceSet.getPackageRegistry();

    // Read the namespace configuration file
    String namespaceConfigPath = FileLocator
            .toFileURL(Activator.getDefault().getBundle().getEntry(NAMESPACE_CONFIG_FILE_PAHT)).getPath();
    File namespaceConfigFile = new File(namespaceConfigPath);

    Properties properties = new Properties();
    properties.load(new FileInputStream(namespaceConfigFile));

    // Load and register the self-definition namespaces
    for (String key : properties.stringPropertyNames()) {
        String value = properties.getProperty(key);
        packageRegistry.put(value, UMLPackage.eINSTANCE);
    }

    registSysMLPackages(packageRegistry);

    // Add the load option
    resourceSet.getLoadOptions().put(XMIResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);

    // Define the extension to factory map
    Map<String, Object> extensionToFactoryMap = resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap();
    UMLResourceFactoryImpl umlResourceFactory = new UMLResourceFactoryImpl();
    extensionToFactoryMap.put(XMI2UMLResource.FILE_EXTENSION, umlResourceFactory);

    MyLog.info(method + "end with " + (System.currentTimeMillis() - startTime) + " millisecond");
    MyLog.info();
    return resourceSet;
}
项目:NoSQLDataEngineering    文件:Main.java   
public static void prepareM2MExample(String inputFile, String outputFile)
{
  File INPUT_MODEL = new File(inputFile);
  File OUTPUT_MODEL = new File(outputFile);

  System.out.println("Generating EntityDiff model for " + INPUT_MODEL.getName() + " in " + OUTPUT_MODEL.getPath());

  NoSQLSchemaToEntityDiff transformer = new NoSQLSchemaToEntityDiff();
  EntityDifferentiation diffModel = transformer.m2m(INPUT_MODEL);

  NoSQLSchemaPackage nosqlschemaPackage = NoSQLSchemaPackage.eINSTANCE;
  EntitydifferentiationPackage entitydiffPackage = EntitydifferentiationPackage.eINSTANCE;
  ResourceManager resManager = new ResourceManager(nosqlschemaPackage, entitydiffPackage);

  nosqlschemaPackage.eResource().setURI(URI.createPlatformResourceURI("es.um.nosql.schemainference/model/nosqlschema.ecore", true));
  entitydiffPackage.eResource().setURI(URI.createPlatformResourceURI("es.um.nosql.schemainference.entitydifferentiation/model/entitydifferentiation.ecore", true));

  Resource outputRes = resManager.getResourceSet().createResource(URI.createFileURI(OUTPUT_MODEL.getAbsolutePath()));
  outputRes.getContents().add(diffModel);

  // Configure output
  Map<Object,Object> options = new HashMap<Object,Object>();
  options.put(XMIResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE);
  options.put(XMIResource.OPTION_ENCODING, "UTF-8"); 

  try
  {
    outputRes.save(new FileOutputStream(OUTPUT_MODEL), options);
  } catch (IOException e)
  {
    e.printStackTrace();
  }

  System.out.println("Transformation model finished");
}
项目:xtext-core    文件:InjectableValidatorTest.java   
@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));
}
项目:NEXCORE-UML-Modeler    文件:DomainUtil.java   
/**
 * 저장시 사용하는 옵션 반환
 * 
 * @return Map<Object,Object>
 */
public static Map<Object, Object> getSaveOptions() {
    Map<Object, Object> saveOptions = new HashMap<Object, Object>();

    saveOptions.put(XMIResource.OPTION_ENCODING, UMLResource.DEFAULT_ENCODING);
    saveOptions.put(XMIResource.OPTION_USE_XMI_TYPE, true);
    saveOptions.put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
    saveOptions.put(XMLResource.OPTION_USE_DEPRECATED_METHODS, new ArrayList());
    saveOptions.put(XMLResource.OPTION_SAVE_ONLY_IF_CHANGED, true);

    return saveOptions;
}
项目:statecharts    文件:DirtyStateListener.java   
protected boolean createAndRegisterDirtyState(XMIResource resource) {
    IDirtyResource dirtyResource = createDirtyResource(resource);
    if (dirtyResource == null) {
        return true;
    } else {
        boolean isSuccess = dirtyStateManager
                .manageDirtyState(dirtyResource);
        if (isSuccess) {
            uri2dirtyResource.put(resource.getURI(), dirtyResource);
        }
        return isSuccess;
    }
}
项目:statecharts    文件:DirtyStateListener.java   
protected IDirtyResource createDirtyResource(XMIResource resource) {
    IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE
            .getResourceServiceProvider(resource.getURI());
    if (resourceServiceProvider == null) {
        return null;
    }
    return new XMIDirtyResource(resource, resourceServiceProvider);
}
项目:mondo-demo-wt    文件:Modular_Diagram.java   
public EObject GetObjectRoot(XMIResource res,EObject root, EObject param_obj){

    //EObject result = CoreFactoryImpl.eINSTANCE.create(param_obj.eClass());
      EObject result = WTSpec4MFactoryImpl.eINSTANCE.create(param_obj.eClass());
    EList<EAttribute> result_attr = result.eClass().getEAllAttributes();

    for (EAttribute eAttribute : result_attr) {
        result.eSet(eAttribute, param_obj.eGet(eAttribute));
    }   

    Update_CrossReferences(result,res,root,param_obj);

    return result;
}
项目:SAMPLE-CODE-PUBLIC    文件:PerformantXMIResourceFactoryImpl.java   
protected void configureResource(XMIResource resource){
        Map<Object,Object> saveOptions = resource.getDefaultSaveOptions();
        saveOptions.put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
        saveOptions.put(XMLResource.OPTION_USE_CACHED_LOOKUP_TABLE, lookupTable);       
        saveOptions.put(XMLResource.OPTION_ENCODING,"UTF-8");
//      saveOptions.put(XMLResource.OPTION_USE_FILE_BUFFER, Boolean.TRUE);


        Map<Object,Object> loadOptions = resource.getDefaultLoadOptions();
        loadOptions.put(XMLResource.OPTION_DEFER_ATTACHMENT, Boolean.TRUE);
        loadOptions.put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, Boolean.TRUE);
        loadOptions.put(XMLResource.OPTION_USE_DEPRECATED_METHODS, Boolean.FALSE);
        loadOptions.put(XMLResource.OPTION_USE_PARSER_POOL, parserPool);
    }
项目:NeoEMF    文件:BackendHelper.java   
private static File createResource(File sourceFile, InternalBackend targetBackend) throws Exception {
    String targetFileName = Files.getNameWithoutExtension(sourceFile.getName()) + "." + targetBackend.getResourceExtension() + "." + ZXMI;
    File targetFile = Workspace.getResourcesDirectory().resolve(targetFileName).toFile();

    if (targetFile.exists()) {
        log.info("Already existing resource {}", targetFile);
        return targetFile;
    }

    ResourceSet resourceSet = loadResourceSet();

    URI sourceURI = URI.createFileURI(sourceFile.getAbsolutePath());

    log.info("Loading '{}'", sourceURI);
    Resource sourceResource = resourceSet.getResource(sourceURI, true);

    URI targetURI = URI.createFileURI(targetFile.getAbsolutePath());
    Resource targetResource = resourceSet.createResource(targetURI);

    log.info("Migrating");
    targetResource.getContents().add(migrate(sourceResource.getContents().get(0), targetBackend.initAndGetEPackage()));

    sourceResource.unload();

    log.info("Saving to '{}'", targetResource.getURI());
    Map<String, Object> saveOpts = new HashMap<>();
    saveOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
    targetResource.save(saveOpts);

    targetResource.unload();

    return targetFile;
}
项目:emfstore-rest    文件:EObjectTypeParser.java   
private static EObject getResultfromResource(XMIResource res) throws SerializationException {
    EObject result = res.getContents().get(0);

    if (result instanceof IdEObjectCollection) {
        IdEObjectCollection collection = (IdEObjectCollection) result;
        Map<EObject, String> eObjectToIdMap = new LinkedHashMap<EObject, String>();
        Map<String, EObject> idToEObjectMap = new LinkedHashMap<String, EObject>();

        for (EObject modelElement : collection.getAllModelElements()) {
            String modelElementId;
            if (ModelUtil.isIgnoredDatatype(modelElement)) {
                // create random ID for generic types, won't get serialized
                // anyway
                modelElementId = ModelFactory.eINSTANCE.createModelElementId().getId();
            } else {
                modelElementId = res.getID(modelElement);
            }

            if (modelElementId == null) {
                throw new SerializationException("Failed to retrieve ID for EObject contained in project: "
                    + modelElement);
            }

            eObjectToIdMap.put(modelElement, modelElementId);
            idToEObjectMap.put(modelElementId, modelElement);
        }

        collection.initMapping(eObjectToIdMap, idToEObjectMap);
    }

    EcoreUtil.resolveAll(result);
    res.getContents().remove(result);

    return result;
}
项目:emfstore-rest    文件:ResourceHelper.java   
private void saveInResourceWithProject(EObject obj, URI resourceURI, Project project) throws FatalESException {
    final Resource resource = serverSpace.eResource().getResourceSet().createResource(resourceURI);
    resource.getContents().add(obj);

    if (resource instanceof XMIResource) {
        final XMIResource xmiResource = (XMIResource) resource;
        for (final EObject modelElement : project.getAllModelElements()) {
            final ModelElementId modelElementId = project.getModelElementId(modelElement);
            xmiResource.setID(modelElement, modelElementId.getId());
        }
    }

    save(obj);
}
项目:emfstore-rest    文件:ResourceHelper.java   
/**
 * Saves the given EObject and sets the IDs on the eObject's resource for
 * all model elements contained in the given project.
 * 
 * @param eObject
 *            the EObject to be saved
 * @param project
 *            the project, that is used to set the IDs of all model elements
 *            within the project on the resource
 * @throws FatalESException
 *             in case of failure
 */
public void saveWithProject(EObject eObject, Project project) throws FatalESException {
    final Resource resource = eObject.eResource();

    if (resource instanceof XMIResource) {
        final XMIResource xmiResource = (XMIResource) resource;
        for (final EObject modelElement : project.getAllModelElements()) {
            final ModelElementId modelElementId = project.getModelElementId(modelElement);
            xmiResource.setID(modelElement, modelElementId.getId());
        }
    }

    save(eObject);
}
项目:emfstore-rest    文件:ResourcePersister.java   
private void setModelElementIdOnResource(XMIResource resource, EObject modelElement) {

        if (modelElement instanceof IdEObjectCollection) {
            return;
        }

        final String modelElementId = getIDForEObject(modelElement);
        resource.setID(modelElement, modelElementId);
    }
项目:BfROpenLab    文件:EmfUtils.java   
private static Resource createResource() {
    ResourceSet resourceSet = new ResourceSetImpl();

    resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("*", new XMIResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(CommonPackage.eNS_URI, CommonPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(DataPackage.eNS_URI, DataPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(ModelsPackage.eNS_URI, ModelsPackage.eINSTANCE);

    XMIResource resource = (XMIResource) resourceSet.createResource(URI.createURI("file:///null"));

    resource.setEncoding(StandardCharsets.UTF_8.name());

    return resource;
}
项目:ttc2017smartGrids    文件:App.java   
private void runIteration(String cim, String cosem, String substation, int index, String changeSet, String runIndex, String phase, TransformationExecutor executor, ExecutionContextImpl context) {

        List<ModelExtent> modelExtents = new ArrayList<ModelExtent>();
        long loadModelsstart = System.nanoTime();
        modelExtents.add(this.createModelExtent(cim));
        if ("outagePrevention".equals(this.transformation)) {
            modelExtents.add(this.createModelExtent(substation));
        }
        modelExtents.add(this.createModelExtent(cosem));
        long loadModelsEnd = System.nanoTime();
        if (phase == "Initial") {
            System.out.println("ModelJoin;" + this.transformation + ";" + changeSet + ";" + runIndex + ";" + Integer.toString(index) + ";" + phase + ";Time;" + Long.toString(loadModelsEnd-loadModelsstart));
        }
        ModelExtent output = new BasicModelExtent();
        modelExtents.add(output);
        modelExtents.add(new BasicModelExtent());

        long start = System.nanoTime();
        ExecutionDiagnostic result = executor.execute(context,
                modelExtents.toArray(new ModelExtent[modelExtents.size()]));
        long end = System.nanoTime();

        if (result.getSeverity() == Diagnostic.OK) {
            // the output objects got captured in the output extent
            XMIResource outResource = (XMIResource) rs
                    .createResource(URI.createFileURI(new File(this.transformation + ".xmi").getAbsolutePath()));
            outResource.getContents().addAll(output.getContents());
            try {
                outResource.save(null);
                System.out.println("ModelJoin;" + this.transformation + ";" + changeSet + ";" + runIndex + ";" + Integer.toString(index) + ";" + phase + ";Time;" + Long.toString(end-start));
                System.out.println("ModelJoin;" + this.transformation + ";" + changeSet + ";" + runIndex + ";" + Integer.toString(index) + ";" + phase + ";Elements;" + Integer.toString(outResource.getContents().size()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            IStatus status = BasicDiagnostic.toIStatus(result);
            StringBuilder s = new StringBuilder();
            s.append("Failed to execute ");
            s.append(this.transformation);
            s.append(": ");
            s.append(status.getMessage());
            for (IStatus child : status.getChildren()) {
                s.append("\n " + child.getMessage());
            }
            System.err.println(s);
        }
    }
项目:n4js    文件:UserdataMapper.java   
/**
 * Serializes an exported script (or other {@link EObject}) stored in given resource content at index 1, and stores
 * that in a map under key {@link #USERDATA_KEY_SERIALIZED_SCRIPT}.
 */
public static Map<String, String> createUserData(final TModule exportedModule) throws IOException,
        UnsupportedEncodingException {
    if (exportedModule.isPreLinkingPhase()) {
        throw new AssertionError("Module may not be from the preLinkingPhase");
    }
    // TODO GH-230 consider disallowing serializing reconciled modules to index with fail-fast
    // if (exportedModule.isReconciled()) {
    // throw new IllegalArgumentException("module must not be reconciled");
    // }
    final Resource originalResourceUncasted = exportedModule.eResource();
    if (!(originalResourceUncasted instanceof N4JSResource)) {
        throw new IllegalArgumentException("module must be contained in an N4JSResource");
    }
    final N4JSResource originalResource = (N4JSResource) originalResourceUncasted;

    // resolve resource (i.e. resolve lazy cross-references, resolve DeferredTypeRefs, etc.)
    originalResource.performPostProcessing();
    if (EcoreUtilN4.hasUnresolvedProxies(exportedModule) || TypeUtils.containsDeferredTypeRefs(exportedModule)) {
        // don't write invalid TModule to index
        // TODO GHOLD-193 reconsider handling of this error case
        // 2016-05-11: keeping fail-safe behavior for now (in place at least since end of 2014).
        // Fail-fast behavior not possible, because common case (e.g. typo in an identifier in the source code, that
        // leads to an unresolvable proxy in the TModule)
        return createTimestampUserData(exportedModule);
    }

    // add copy -- EObjects can only be contained in a single resource, and
    // we do not want to mess up the original resource
    URI resourceURI = originalResource.getURI();
    XMIResource resourceForUserData = new XMIResourceImpl(resourceURI);

    resourceForUserData.getContents().add(TypeUtils.copyWithProxies(exportedModule));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    resourceForUserData.save(baos, getOptions(resourceURI, BINARY));

    String serializedScript = BINARY ? XMLTypeFactory.eINSTANCE.convertBase64Binary(baos.toByteArray())
            : baos.toString(TRANSFORMATION_CHARSET_NAME);

    final HashMap<String, String> ret = new HashMap<>();
    ret.put(USERDATA_KEY_SERIALIZED_SCRIPT, serializedScript);

    ret.put(N4JSResourceDescriptionStrategy.MAIN_MODULE_KEY, Boolean.toString(exportedModule.isMainModule()));

    // in case of filling file store fingerprint to keep filled type updated by the incremental builder.
    // required to trigger rebuilds even if only minor changes happened to the content.
    if (exportedModule.isStaticPolyfillModule()) {
        final String contentHash = Integer.toHexString(originalResource.getParseResult().getRootNode().hashCode());
        ret.put(USERDATA_KEY_STATIC_POLYFILL_CONTENTHASH, contentHash);
    }
    return ret;
}