org.eclipse.xtext.resource.persistence.StorageAwareResource Java Examples

The following examples show how to use org.eclipse.xtext.resource.persistence.StorageAwareResource. 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: N4ClusteringBuilderState.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
protected void installSourceLevelURIs(BuildData buildData) {
	ResourceSet resourceSet = buildData.getResourceSet();
	Iterable<URI> sourceLevelUris = Iterables.concat(buildData.getToBeUpdated(), buildData.getURIQueue());
	Set<URI> sourceUris = newHashSet();
	for (URI uri : sourceLevelUris) {
		if (buildData.getSourceLevelURICache().getOrComputeIsSource(uri, resourceServiceProviderRegistry)) {
			sourceUris.add(uri);
			// unload resources loaded from storage previously
			Resource resource = resourceSet.getResource(uri, false);
			if (resource instanceof StorageAwareResource) {
				if (((StorageAwareResource) resource).isLoadedFromStorage()) {
					resource.unload();
				}
			}
		}
	}
	SourceLevelURIsAdapter.setSourceLevelUris(resourceSet, sourceUris);
}
 
Example #2
Source File: XtendBatchCompiler.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void generateJavaFiles(ResourceSet resourceSet) {
	JavaIoFileSystemAccess javaIoFileSystemAccess = javaIoFileSystemAccessProvider.get();
	javaIoFileSystemAccess.setOutputPath(outputPath);
	javaIoFileSystemAccess.setWriteTrace(writeTraceFiles);

	GeneratorContext context = new GeneratorContext();
	context.setCancelIndicator(CancelIndicator.NullImpl);
	for (Resource resource : newArrayList(resourceSet.getResources())) {
		if (isSourceFile(resource)) {
			if (isWriteStorageFiles()) {
				StorageAwareResource storageAwareResource = (StorageAwareResource)resource;
				storageAwareResource.getResourceStorageFacade().saveResource(storageAwareResource, javaIoFileSystemAccess);
			}
			generator.generate(resource, javaIoFileSystemAccess, context);
		}
	}
}
 
Example #3
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Resource addResource(final Resource resource, final ResourceSet resourceSet) {
  URI uri = resource.getURI();
  Resource r = resourceSet.getResource(uri, false);
  if (r == null) {
    resourceSet.getResources().add(resource);
    return resource;
  } else if (r instanceof StorageAwareResource && ((StorageAwareResource) r).isLoadedFromStorage()) {
    // make sure to not process any binary resources in builder as it could have incorrect linking
    r.unload();
    resourceSet.getResources().set(resourceSet.getResources().indexOf(r), resource);
    return resource;
  } else {
    return r;
  }
}
 
Example #4
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Stores the process resource as a binary if it doesn't contain syntax or linking errors.
 *
 * @param resource
 *          resource to store, must not be {@code null}
 * @param buildData
 *          build data, must not be {@code null}
 */
protected void storeBinaryResource(final Resource resource, final BuildData buildData) {
  if (isBinaryModelStorageAvailable && resource instanceof StorageAwareResource && ((StorageAwareResource) resource).getResourceStorageFacade() != null
      && fileSystemAccess instanceof IFileSystemAccessExtension3) {
    CompletableFuture.runAsync(() -> {
      final long maxTaskExecutionNanos = TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS);

      try {
        long elapsed = System.nanoTime();

        IResourceStorageFacade storageFacade = ((StorageAwareResource) resource).getResourceStorageFacade();
        storageFacade.saveResource((StorageAwareResource) resource, (IFileSystemAccessExtension3) fileSystemAccess);
        buildData.getSourceLevelURICache().getSources().remove(resource.getURI());

        elapsed = System.nanoTime() - elapsed;
        if (elapsed > maxTaskExecutionNanos) {
          LOGGER.info("saving binary taking longer than expected (" + elapsed + " ns) : " + resource.getURI()); //$NON-NLS-1$ //$NON-NLS-2$
        }
        // CHECKSTYLE:OFF
      } catch (Throwable ex) {
        // CHECKSTYLE:ON
        LOGGER.error("Failed to save binary for " + resource.getURI(), ex); //$NON-NLS-1$
      }
    }, binaryStorageExecutor);
  }
}
 
Example #5
Source File: ResourceStorageTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test(expected = IOException.class)
public void testFailedWrite() throws Exception {
  final XtendFile file = this.file("class C{}");
  ByteArrayOutputStream _byteArrayOutputStream = new ByteArrayOutputStream();
  Resource _eResource = file.eResource();
  new BatchLinkableResourceStorageWritable(_byteArrayOutputStream, false) {
    @Override
    protected void writeAssociationsAdapter(final BatchLinkableResource resource, final OutputStream zipOut) throws IOException {
      final Function1<Adapter, Boolean> _function = (Adapter it) -> {
        return Boolean.valueOf((it instanceof JvmModelAssociator.Adapter));
      };
      final Adapter removeMe = IterableExtensions.<Adapter>findFirst(resource.eAdapters(), _function);
      Assert.assertTrue(resource.eAdapters().remove(removeMe));
      super.writeAssociationsAdapter(resource, zipOut);
    }
  }.writeResource(((StorageAwareResource) _eResource));
}
 
Example #6
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Override which installs an {@link DirectLinkingSourceLevelURIsAdapter} instead of Xtext's
 * {@link org.eclipse.xtext.resource.persistence.SourceLevelURIsAdapter} so that the builder can modify
 * {@link org.eclipse.xtext.builder.impl.SourceLevelURICache#getSources()} and get these changes reflected in the adapter.
 */
@Override
protected void installSourceLevelURIs(final BuildData buildData) {
  ResourceSet resourceSet = buildData.getResourceSet();
  Iterable<URI> sourceLevelUris = Iterables.concat(buildData.getToBeUpdated(), buildData.getURIQueue());
  for (URI uri : sourceLevelUris) {
    if (buildData.getSourceLevelURICache().getOrComputeIsSource(uri, resourceServiceProviderRegistry)) {
      // unload resources loaded from storage previously
      Resource resource = resourceSet.getResource(uri, false);
      if (resource instanceof StorageAwareResource && ((StorageAwareResource) resource).isLoadedFromStorage()) {
        resource.unload();
      }
    }
  }
  DirectLinkingSourceLevelURIsAdapter.setSourceLevelUris(resourceSet, buildData.getSourceLevelURICache().getSources());
}
 
Example #7
Source File: ClusteringBuilderState.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void installSourceLevelURIs(BuildData buildData) {
	ResourceSet resourceSet = buildData.getResourceSet();
	Iterable<URI> sourceLevelUris = Iterables.concat(buildData.getToBeUpdated(), buildData.getURIQueue());
	Set<URI> sourceUris = newHashSet();
	for (URI uri : sourceLevelUris) {
		if (buildData.getSourceLevelURICache().getOrComputeIsSource(uri, resourceServiceProviderRegistry)) {
			sourceUris.add(uri);
			// unload resources loaded from storage previously
			Resource resource = resourceSet.getResource(uri, false);
			if (resource instanceof StorageAwareResource) {
				if (((StorageAwareResource) resource).isLoadedFromStorage()) {
					resource.unload();
				}
			}
		}
	}
	SourceLevelURIsAdapter.setSourceLevelUris(resourceSet, sourceUris);
}
 
Example #8
Source File: ResourceForIEditorInputFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void configureResourceSet(ResourceSet resourceSet, URI primaryURI) {
	// TODO: Filter external content - primary resource should not use dirty state
	externalContentSupport.configureResourceSet(resourceSet, externalContentProvider);
	if (!(resourceServiceProvider instanceof IResourceServiceProviderExtension) 
			|| ((IResourceServiceProviderExtension)resourceServiceProvider).isSource(primaryURI)) {
		SourceLevelURIsAdapter.setSourceLevelUris(resourceSet, Collections.singleton(primaryURI));
		resourceSet.eAdapters().add(new ResourceStorageProviderAdapter() {
			
			@Override
			public ResourceStorageLoadable getResourceStorageLoadable(StorageAwareResource resource) {
				if (!dirtyStateManager.hasContent(resource.getURI())) {
					return null;
				}
				return ((DirtyStateManager)dirtyStateManager).getResourceStorageLoadable(resource.getURI());
			}
		});
	}
}
 
Example #9
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Loads the binary storage into the given resource in the given {@link Mode}.
 *
 * @param resource
 *          resource to load into, must not be {@code null}
 * @param loadMode
 *          load mode, must not be {@code null}
 * @throws IOException
 *           if an I/O exception occurred
 */
public void loadIntoResource(final StorageAwareResource resource, final ResourceLoadMode loadMode) throws IOException {
  if (loadMode.instruction(Constituent.RESOURCE) != Instruction.LOAD) {
    throw new IllegalArgumentException("Incompatible resource load mode: " + loadMode.instruction(Constituent.RESOURCE)); //$NON-NLS-1$
  }
  this.mode = loadMode;
  traceSet.started(ResourceLoadStorageEvent.class, resource.getURI(), loadMode);
  try {
    super.loadIntoResource(resource);
    // CHECKSTYLE:OFF
  } catch (IOException | RuntimeException e) {
    // CHECKSTYLE:ON
    LOG.info("Error loading " + resource.getURI() + " from binary storage", e); //$NON-NLS-1$ //$NON-NLS-2$
    // TODO: remove with upgrade to Xtext x.x (https://github.com/eclipse/xtext/issues/1651)
    resource.getContents();
    resource.eAdapters();
    if (e instanceof IOException) { // NOPMD
      throw e;
    }
    throw new IOException(e);
  } finally {
    traceSet.ended(ResourceLoadStorageEvent.class);
  }
}
 
Example #10
Source File: StandaloneBuilder.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void generate(List<Resource> sourceResources) {
	GeneratorContext context = new GeneratorContext();
	context.setCancelIndicator(CancelIndicator.NullImpl);
	for (Resource it : sourceResources) {
		LOG.info("Starting generator for input: '" + it.getURI().lastSegment() + "'");
		registerCurrentSource(it.getURI());
		LanguageAccess access = languageAccess(it.getURI());
		JavaIoFileSystemAccess fileSystemAccess = getFileSystemAccess(access);
		if (isWriteStorageResources()) {
			if (it instanceof StorageAwareResource) {
				IResourceStorageFacade resourceStorageFacade = ((StorageAwareResource) it)
						.getResourceStorageFacade();
				if (resourceStorageFacade != null) {
					resourceStorageFacade.saveResource((StorageAwareResource) it, fileSystemAccess);
				}
			}
		}
		access.getGenerator().generate(it, fileSystemAccess, context);
	}
}
 
Example #11
Source File: AbstractExpressionGenerator.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Get the string representation of an operator.
 *
 * @param call the call to the operator feature.
 * @return the string representation of the operator or {@code null} if not a valid operator.
 */
protected String getOperatorSymbol(XAbstractFeatureCall call) {
	if (call != null) {
		final Resource res = call.eResource();
		if (res instanceof StorageAwareResource) {
			final boolean isLoadedFromStorage = ((StorageAwareResource) res).isLoadedFromStorage();
			if (isLoadedFromStorage) {
				final QualifiedName operator = getOperatorMapping().getOperator(
						QualifiedName.create(call.getFeature().getSimpleName()));
				return Objects.toString(operator);
			}
		}
		return call.getConcreteSyntaxFeatureName();
	}
	return null;
}
 
Example #12
Source File: AbstractConstantExpressionsInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected String getOperator(final XAbstractFeatureCall call) {
  String _switchResult = null;
  Resource _eResource = call.eResource();
  final Resource res = _eResource;
  boolean _matched = false;
  if (res instanceof StorageAwareResource) {
    boolean _isLoadedFromStorage = ((StorageAwareResource)res).isLoadedFromStorage();
    if (_isLoadedFromStorage) {
      _matched=true;
      QualifiedName _operator = this.operatorMapping.getOperator(QualifiedName.create(call.getFeature().getSimpleName()));
      String _string = null;
      if (_operator!=null) {
        _string=_operator.toString();
      }
      return _string;
    }
  }
  if (!_matched) {
    _switchResult = call.getConcreteSyntaxFeatureName();
  }
  return _switchResult;
}
 
Example #13
Source File: DirectLinkingResourceStorageWritable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void writeNodeModel(final StorageAwareResource resource, final OutputStream outputStream) {
  try {
    DataOutputStream out = new DataOutputStream(outputStream);
    SerializableNodeModel serializableNodeModel = new SerializableNodeModel(resource);
    SerializationConversionContext conversionContext = new ProxyAwareSerializationConversionContext(resource);
    serializableNodeModel.writeObjectData(out, conversionContext);
    out.flush();
  } catch (IOException e) {
    throw new WrappedException(e);
  }
}
 
Example #14
Source File: ClusteringStorageAwareResourceLoader.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Execute the given operation in a clustered fashion.
 */
public <T> Iterable<T> executeClustered(Iterable<URI> uris, Function1<? super Resource, ? extends T> operation) {
	int loadedURIsCount = 0;
	Set<URI> sourceLevelURIs = new HashSet<>();
	List<Resource> resources = new ArrayList<>();
	List<T> result = new ArrayList<>();
	Iterator<URI> iter = uris.iterator();
	while (iter.hasNext()) {
		URI uri = iter.next();
		XtextResourceSet resourceSet = context.getResourceSet();
		if (!context.getClusteringPolicy().continueProcessing(resourceSet, uri, loadedURIsCount)) {
			FluentIterable.from(resources).transform(operation::apply).copyInto(result);
			clearResourceSet();
			resources.clear();
			loadedURIsCount = 0;
		}
		loadedURIsCount++;
		if (isSource(uri)) {
			sourceLevelURIs.add(uri);
			Resource existingResource = resourceSet.getResource(uri, false);
			if (existingResource instanceof StorageAwareResource) {
				if (((StorageAwareResource) existingResource).isLoadedFromStorage()) {
					existingResource.unload();
				}
			}
			SourceLevelURIsAdapter.setSourceLevelUrisWithoutCopy(resourceSet, sourceLevelURIs);
		}
		resources.add(resourceSet.getResource(uri, true));
	}
	FluentIterable.from(resources).transform(operation::apply).copyInto(result);
	return result;
}
 
Example #15
Source File: PortableURIsTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPortableUris() {
  try {
    final XtextResourceSet resourceSet = this.<XtextResourceSet>get(XtextResourceSet.class);
    Resource _createResource = resourceSet.createResource(URI.createURI("hubba:/bubba.langatestlanguage"));
    final StorageAwareResource resourceA = ((StorageAwareResource) _createResource);
    Resource _createResource_1 = resourceSet.createResource(URI.createURI("hubba:/bubba2.langatestlanguage"));
    final StorageAwareResource resourceB = ((StorageAwareResource) _createResource_1);
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("type B");
    _builder.newLine();
    resourceB.load(this.getAsStream(_builder.toString()), null);
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("import \'hubba:/bubba2.langatestlanguage\'");
    _builder_1.newLine();
    _builder_1.newLine();
    _builder_1.append("type A extends B");
    _builder_1.newLine();
    resourceA.load(this.getAsStream(_builder_1.toString()), null);
    final Type extended = IterableExtensions.<Type>head(IterableExtensions.<Main>head(Iterables.<Main>filter(resourceA.getContents(), Main.class)).getTypes()).getExtends();
    final URI uri = EcoreUtil.getURI(extended);
    final URI portableURI = resourceA.getPortableURIs().toPortableURI(resourceA, uri);
    Assert.assertEquals(resourceA.getURI(), portableURI.trimFragment());
    Assert.assertTrue(resourceA.getPortableURIs().isPortableURIFragment(portableURI.fragment()));
    Assert.assertSame(extended, resourceA.getEObject(portableURI.fragment()));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #16
Source File: XClusteringStorageAwareResourceLoader.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute the given operation in a clustered fashion.
 */
public <T> List<T> executeClustered(Iterable<URI> uris, Function1<? super Resource, ? extends T> operation) {
	int loadedURIsCount = 0;
	Set<URI> sourceLevelURIs = new HashSet<>();
	List<Resource> resources = new ArrayList<>();
	List<T> result = new ArrayList<>();
	Iterator<URI> iter = uris.iterator();
	while (iter.hasNext()) {
		URI uri = iter.next();
		XtextResourceSet resourceSet = context.getResourceSet();
		if (!context.getClusteringPolicy().continueProcessing(resourceSet, uri, loadedURIsCount)) {
			result.addAll(ListExtensions.map(resources, operation::apply));
			this.clearResourceSet();
			resources.clear();
			loadedURIsCount = 0;
		}
		loadedURIsCount++;
		if (this.isSource(uri)) {
			sourceLevelURIs.add(uri);
			Resource existingResource = resourceSet.getResource(uri, false);
			if (existingResource instanceof StorageAwareResource) {
				if (((StorageAwareResource) existingResource).isLoadedFromStorage()) {
					existingResource.unload();
				}
			}
			SourceLevelURIsAdapter.setSourceLevelUrisWithoutCopy(resourceSet, sourceLevelURIs);
		}
		resources.add(resourceSet.getResource(uri, true));
	}
	result.addAll(ListExtensions.map(resources, operation::apply));
	return result;
}
 
Example #17
Source File: PortableURIsTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPortableReferenceDescriptions() {
  try {
    final XtextResourceSet resourceSet = this.<XtextResourceSet>get(XtextResourceSet.class);
    Resource _createResource = resourceSet.createResource(URI.createURI("hubba:/bubba.langatestlanguage"));
    final StorageAwareResource resourceA = ((StorageAwareResource) _createResource);
    Resource _createResource_1 = resourceSet.createResource(URI.createURI("hubba:/bubba2.langatestlanguage"));
    final StorageAwareResource resourceB = ((StorageAwareResource) _createResource_1);
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("type B");
    _builder.newLine();
    resourceB.load(this.getAsStream(_builder.toString()), null);
    StringConcatenation _builder_1 = new StringConcatenation();
    _builder_1.append("import \'hubba:/bubba2.langatestlanguage\'");
    _builder_1.newLine();
    _builder_1.newLine();
    _builder_1.append("type A extends B");
    _builder_1.newLine();
    resourceA.load(this.getAsStream(_builder_1.toString()), null);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    final ResourceStorageWritable writable = resourceA.getResourceStorageFacade().createResourceStorageWritable(bout);
    writable.writeResource(resourceA);
    IResourceStorageFacade _resourceStorageFacade = resourceA.getResourceStorageFacade();
    byte[] _byteArray = bout.toByteArray();
    ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_byteArray);
    final ResourceStorageLoadable loadable = _resourceStorageFacade.createResourceStorageLoadable(_byteArrayInputStream);
    Resource _createResource_2 = resourceSet.createResource(URI.createURI("hubba:/bubba3.langatestlanguage"));
    final StorageAwareResource resourceC = ((StorageAwareResource) _createResource_2);
    resourceC.loadFromStorage(loadable);
    final IReferenceDescription refDesc = IterableExtensions.<IReferenceDescription>head(resourceC.getResourceDescription().getReferenceDescriptions());
    EObject _head = IterableExtensions.<EObject>head(resourceB.getContents());
    Assert.assertSame(IterableExtensions.<Type>head(((Main) _head).getTypes()), resourceSet.getEObject(refDesc.getTargetEObjectUri(), false));
    EObject _head_1 = IterableExtensions.<EObject>head(resourceC.getContents());
    Assert.assertSame(IterableExtensions.<Type>head(((Main) _head_1).getTypes()), resourceSet.getEObject(refDesc.getSourceEObjectUri(), false));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #18
Source File: LazyLinkingResource2.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Set<String> getUnresolvableURIFragments() {
  Set<String> unresolveableProxies = getCache().get(UNRESOLVEABLE_PROXIES_KEY, this, new Provider<Set<String>>() {
    @Override
    public Set<String> get() {
      return isLoadedFromStorage() ? Sets.newHashSet(StorageAwareResource.UNRESOLVABLE_FRAGMENT) : Sets.newHashSet();
    }
  });
  return unresolveableProxies;
}
 
Example #19
Source File: DirectLinkingResourceStorageFacade.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * If the resource contains errors, any existing storage will be deleted.
 */
@Override
public void saveResource(final StorageAwareResource resource, final IFileSystemAccessExtension3 fsa) {
  // delete storage first in case saving fails
  deleteStorage(resource.getURI(), (IFileSystemAccess) fsa);
  if (resource.getErrors().isEmpty()) {
    super.saveResource(resource, fsa);
  }
}
 
Example #20
Source File: DirectLinkingResourceStorageFacade.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean shouldLoadFromStorage(final StorageAwareResource resource) {
  DirectLinkingSourceLevelURIsAdapter adapter = DirectLinkingSourceLevelURIsAdapter.findInstalledAdapter(resource.getResourceSet());
  if (adapter == null) {
    return false;
  } else if (adapter.getSourceLevelURIs().contains(resource.getURI())) {
    return false;
  } else if (ResourceLoadMode.get(resource).instruction(Constituent.RESOURCE) == Instruction.SKIP) {
    return false;
  }
  return doesStorageExist(resource);
}
 
Example #21
Source File: DirectLinkingResourceStorageWritable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private void writeMapping(final Entry<EObject, Deque<EObject>> entry, final DirectLinkingEObjectOutputStream objOut, final StorageAwareResource resource) throws IOException {
  objOut.writeEObjectURI(entry.getKey(), resource);
  objOut.writeCompressedInt(entry.getValue().size());
  for (EObject target : entry.getValue()) {
    objOut.writeEObjectURI(target, resource);
  }
}
 
Example #22
Source File: ProxyModelAssociationsAdapter.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Installs a {@link ProxyModelAssociationsAdapter} unless the given resource already has an {@link InferredModelAssociator.Adapter}.
 * 
 * @param resource
 *          resource to add adapter to, must not be {@code null}
 */
static void install(final StorageAwareResource resource) {
  InferredModelAssociator.Adapter adapter = (InferredModelAssociator.Adapter) EcoreUtil.getAdapter(resource.eAdapters(), InferredModelAssociator.Adapter.class);
  if (adapter == null) {
    adapter = new ProxyModelAssociationsAdapter(resource);
    resource.eAdapters().add(adapter);
  }
}
 
Example #23
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void readContents(final StorageAwareResource resource, final InputStream inputStream) throws IOException {
  // Implementation is copied over from org.eclipse.xtext.resource.persistence.ResourceStorageLoadable
  // The only difference is that the stream overrides 'loadFeatureValue' to add some error logging
  final BinaryResourceImpl.EObjectInputStream in = new BinaryResourceImpl.EObjectInputStream(inputStream, Collections.emptyMap()) {

    @Override
    public int readCompressedInt() throws IOException {
      // HACK! null resource set, to avoid usage of resourceSet's package registry
      resourceSet = null;
      return super.readCompressedInt();
    }

    @Override
    public InternalEObject loadEObject() throws IOException {
      final InternalEObject result = super.loadEObject();
      handleLoadEObject(result, this);
      return result;
    }

    @Override
    protected void loadFeatureValue(final InternalEObject internalEObject, final EStructuralFeatureData eStructuralFeatureData) throws IOException {
      try {
        super.loadFeatureValue(internalEObject, eStructuralFeatureData);
        // CHECKSTYLE:OFF
      } catch (Exception e) {
        StringBuilder infoMessage = new StringBuilder(100);
        // CHECKSTYLE:ON
        infoMessage.append("Failed to load feature's value. Owner: ").append(internalEObject.eClass()); //$NON-NLS-1$
        if (eStructuralFeatureData.eStructuralFeature != null) {
          infoMessage.append(", feature name: ").append(eStructuralFeatureData.eStructuralFeature.getName()); //$NON-NLS-1$
        }
        LOG.info(infoMessage);
        throw e;
      }
    }
  };
  in.loadResource(resource);
}
 
Example #24
Source File: DirectLinkingPortableURIs.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public URI toPortableURI(final StorageAwareResource sourceResource, final URI uri) {
  String fragment = uri.fragment();
  if (uriEncoder.isCrossLinkFragment(sourceResource, fragment)) {
    return uri.trimFragment().appendFragment(UNRESOLVED_LAZY_LINK);
  }
  return null;
}
 
Example #25
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private Deque<EObject> readMappedEObjects(final DirectLinkingEObjectInputStream objIn, final StorageAwareResource resource) throws IOException {
  int collectionSize = objIn.readCompressedInt();
  Deque<EObject> deque = new ArrayDeque<>(collectionSize);
  for (int j = 0; j < collectionSize; j++) {
    EObject target = objIn.readEObject(resource);
    if (target != null) {
      deque.add(target);
    }
  }
  return deque;
}
 
Example #26
Source File: DirectLinkingPortableURIs.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public EObject resolve(final StorageAwareResource resource, final String portableFragment) {
  if (portableFragment.equals(UNRESOLVED_LAZY_LINK)) {
    return null;
  }
  return super.resolve(resource, portableFragment);
}
 
Example #27
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
private void mapListOfObjects(final DirectLinkingEObjectInputStream objIn, final Map<EObject, Deque<EObject>> destinationMap, final StorageAwareResource resource) throws IOException {
  EObject from = objIn.readEObject(resource);
  Deque<EObject> to = readMappedEObjects(objIn, resource);
  if (from != null && !to.isEmpty()) {
    destinationMap.put(from, to);
  }
}
 
Example #28
Source File: DirectLinkingResourceStorageLoadable.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Reads the {@link InferredModelAssociator.Adapter#getSourceToInferredModelMap()} map and the
 * {@link InferredModelAssociator.Adapter#getInferredModelToSourceMap()} map.
 *
 * @param resource
 *          resource being deserialized, must not be {@code null}
 * @param stream
 *          zip input stream, never {@code null}
 * @throws IOException
 *           if an I/O exception occurred
 * @see DirectLinkingResourceStorageWritable#writeAssociationsAdapter(StorageAwareResource, java.io.OutputStream)
 */
protected void readAssociationsAdapter(final StorageAwareResource resource, final InputStream stream) throws IOException {
  DirectLinkingEObjectInputStream objIn = new DirectLinkingEObjectInputStream(stream, null);
  int size = objIn.readCompressedInt();
  if (size == 0) {
    return;
  }

  InferredModelAssociator.Adapter adapter = (InferredModelAssociator.Adapter) EcoreUtil.getAdapter(resource.eAdapters(), InferredModelAssociator.Adapter.class);
  if (adapter == null) {
    adapter = new InferredModelAssociator.Adapter();
    resource.eAdapters().add(adapter);
  }

  Map<EObject, Deque<EObject>> destinationMap = adapter.getSourceToInferredModelMap();
  for (int i = 0; i < size; i++) {
    mapListOfObjects(objIn, destinationMap, resource);
  }
  if (objIn.readByte() != Ascii.GS) {
    LOG.warn("Encountered unexpected data while loading " + resource.getURI()); //$NON-NLS-1$
    return;
  }

  destinationMap = adapter.getInferredModelToSourceMap();
  if (objIn.readBoolean()) {
    size = objIn.readCompressedInt();
    for (int i = 0; i < size; i++) {
      mapListOfObjects(objIn, destinationMap, resource);
    }
  } else {
    for (Map.Entry<EObject, Deque<EObject>> entry : adapter.getSourceToInferredModelMap().entrySet()) {
      EObject source = entry.getKey();
      for (EObject target : entry.getValue()) {
        Deque<EObject> singleton = new ArrayDeque<>(1);
        singleton.add(source);
        destinationMap.put(target, singleton);
      }
    }
  }
}
 
Example #29
Source File: ConstantExpressionsInterpreter.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isResolveProxies(final EObject ctx) {
  boolean _switchResult = false;
  Resource _eResource = ctx.eResource();
  final Resource res = _eResource;
  boolean _matched = false;
  if (res instanceof StorageAwareResource) {
    _matched=true;
    _switchResult = ((StorageAwareResource)res).isLoadedFromStorage();
  }
  if (!_matched) {
    _switchResult = false;
  }
  return _switchResult;
}
 
Example #30
Source File: ConstantConditionsInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public XExpression getAssociatedExpression(final JvmField field) {
  final Resource resource = field.eResource();
  if ((resource instanceof StorageAwareResource)) {
    boolean _isLoadedFromStorage = ((StorageAwareResource)resource).isLoadedFromStorage();
    if (_isLoadedFromStorage) {
      return null;
    }
  }
  return this.logicalContainerProvider.getAssociatedExpression(field);
}