下面列出了怎么用org.eclipse.emf.ecore.xmi.XMIResource的API类实例代码及写法,或者点击链接到github查看源代码。
@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 );
}
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
protected Release getRelease(final Migrator targetMigrator, final Resource resource) {
final Map<Object, Object> loadOptions = new HashMap<Object, Object>();
//Ignore unknown features
loadOptions.put(XMIResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
final XMLOptions options = new XMLOptionsImpl();
options.setProcessAnyXML(true);
loadOptions.put(XMLResource.OPTION_XML_OPTIONS, options);
try {
resource.load(loadOptions);
} catch (final IOException e) {
BonitaStudioLog.error(e, CommonRepositoryPlugin.PLUGIN_ID);
}
final String modelVersion = getModelVersion(resource);
for (final Release release : targetMigrator.getReleases()) {
if (release.getLabel().equals(modelVersion)) {
return release;
}
}
return targetMigrator.getReleases().iterator().next(); //First release of all time
}
@Override
protected Release getRelease(final Migrator targetMigrator, final Resource resource) {
final Map<Object, Object> loadOptions = new HashMap<Object, Object>();
//Ignore unknown features
loadOptions.put(XMIResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
final XMLOptions options = new XMLOptionsImpl();
options.setProcessAnyXML(true);
loadOptions.put(XMLResource.OPTION_XML_OPTIONS, options);
try {
resource.load(loadOptions);
} catch (final IOException e) {
BonitaStudioLog.error(e, CommonRepositoryPlugin.PLUGIN_ID);
}
final String modelVersion = getModelVersion(resource);
for (final Release release : targetMigrator.getReleases()) {
if (release.getLabel().equals(modelVersion)) {
return release;
}
}
return targetMigrator.getReleases().iterator().next(); //First release of all time
}
@Override
protected Release getRelease(final Migrator targetMigrator, final Resource resource) {
final Map<Object, Object> loadOptions = new HashMap<Object, Object>();
//Ignore unknown features
loadOptions.put(XMIResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
final XMLOptions options = new XMLOptionsImpl();
options.setProcessAnyXML(true);
loadOptions.put(XMLResource.OPTION_XML_OPTIONS, options);
String modelVersion = null;
try {
resource.load(loadOptions);
modelVersion = getModelVersion(resource);
} catch (final IOException e) {
BonitaStudioLog.error(e, CommonRepositoryPlugin.PLUGIN_ID);
} finally {
resource.unload();
}
for (final Release release : targetMigrator.getReleases()) {
if (release.getLabel().equals(modelVersion)) {
return release;
}
}
return targetMigrator.getReleases().iterator().next(); //First release of all time
}
private boolean isSPDiagram(File file) {
ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(
ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ProcessAdapterFactory());
adapterFactory.addAdapterFactory(new ParameterAdapterFactory());
adapterFactory.addAdapterFactory(new ConnectorDefinitionAdapterFactory());
adapterFactory
.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory
.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
AdapterFactoryEditingDomain editingDomain = new AdapterFactoryEditingDomain(adapterFactory,
new BasicCommandStack(), new HashMap<Resource, Boolean>());
URI fileURI = URI.createFileURI(file.getAbsolutePath());
editingDomain.getResourceSet().getLoadOptions().put(XMIResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
Resource resource = editingDomain.getResourceSet().getResource(fileURI, true);
MainProcess process = (MainProcess) resource.getContents().get(0);
return process.getConfigId().toString().contains("sp");
}
/**
* <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. If no module is found, returns null.
*/
public static String getDeserializedModuleFromDescriptionAsString(IEObjectDescription eObjectDescription,
URI uri) throws IOException {
final TModule module = getDeserializedModuleFromDescription(eObjectDescription, uri);
if (module == null) {
return null;
}
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(USER_DATA_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 ? Base64.getDecoder().decode(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();
final String astMD5 = eObjectDescription.getUserData(USER_DATA_KEY_AST_MD5);
module.setAstMD5(astMD5);
return module;
}
/**
* 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;
}
@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 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;
}
}
protected IDirtyResource createDirtyResource(XMIResource resource) {
IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE
.getResourceServiceProvider(resource.getURI());
if (resourceServiceProvider == null) {
return null;
}
return new XMIDirtyResource(resource, resourceServiceProvider);
}
protected void performMigration(final Migrator migrator,
final URI resourceURI, final Release release)
throws MigrationException {
migrator.setLevel(ValidationLevel.RELEASE);
Map<String, Object> loadOptions = new HashMap<>();
loadOptions.put(XMIResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
try {
migrator.migrateAndSave(Collections.singletonList(resourceURI),
release, null, Repository.NULL_PROGRESS_MONITOR, loadOptions);
} catch (RuntimeException e) {
throw new MigrationException(String.format("Failed to migrate %s", resourceURI), e);
}
}
/**
* 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 #USER_DATA_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 ? Base64.getEncoder().encodeToString(baos.toByteArray())
: baos.toString(TRANSFORMATION_CHARSET_NAME);
final HashMap<String, String> ret = new HashMap<>();
ret.put(USER_DATA_KEY_SERIALIZED_SCRIPT, serializedScript);
final String astMD5 = exportedModule.getAstMD5();
if (astMD5 != null) {
ret.put(USER_DATA_KEY_AST_MD5, astMD5);
}
if (exportedModule.isMainModule()) {
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(USER_DATA_KEY_STATIC_POLYFILL_CONTENTHASH, contentHash);
}
return ret;
}
public XMIDirtyResource(XMIResource resource,
IResourceServiceProvider resourceServiceProvider) {
this.resource = resource;
this.resourceDescriptionManager = resourceServiceProvider
.getResourceDescriptionManager();
}