org.eclipse.xtext.resource.impl.ResourceDescriptionsData Java Examples

The following examples show how to use org.eclipse.xtext.resource.impl.ResourceDescriptionsData. 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: XIndexer.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compute deltas for resources affected by the given <code>newDeltas</code> and register them in the given
 * <code>newIndex</code>.
 *
 * @param index
 *            the current index; will be changed by this method.
 * @param remainingURIs
 *            set of URIs that were not processed yet.
 * @param newDeltas
 *            deltas representing the resources processed during the most recent build iteration.
 * @param allDeltas
 *            deltas representing all resources processed so far, including {@link XBuildRequest#getExternalDeltas()
 *            external deltas}.
 * @param context
 *            the build context.
 * @return list of deltas representing the affected resources.
 */
public List<Delta> computeAndIndexAffected(ResourceDescriptionsData index, Set<URI> remainingURIs,
		Collection<Delta> newDeltas, Collection<Delta> allDeltas, XBuildContext context) {

	ResourceDescriptionsData originalIndex = context.getOldState().getResourceDescriptions();
	List<URI> affectedURIs = new ArrayList<>();
	for (URI uri : remainingURIs) {
		IResourceServiceProvider resourceServiceProvider = context.getResourceServiceProvider(uri);
		IResourceDescription.Manager manager = resourceServiceProvider.getResourceDescriptionManager();
		IResourceDescription resourceDescription = originalIndex.getResourceDescription(uri);
		if (isAffected(resourceDescription, manager, newDeltas, allDeltas, index)) {
			affectedURIs.add(uri);
		}
	}

	List<Delta> affectedDeltas = getDeltasForChangedResources(affectedURIs, originalIndex, context);
	for (IResourceDescription.Delta delta : affectedDeltas) {
		index.register(delta);
	}
	return affectedDeltas;
}
 
Example #2
Source File: AbstractBuilderState.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public synchronized ImmutableList<IResourceDescription.Delta> update(BuildData buildData, IProgressMonitor monitor) {
	ensureLoaded();
	final SubMonitor subMonitor = SubMonitor.convert(monitor, Messages.AbstractBuilderState_0, 1);
	subMonitor.subTask(Messages.AbstractBuilderState_0);
	if (buildData.isEmpty())
		return ImmutableList.of();
	if (monitor.isCanceled())
		throw new OperationCanceledException();

	final ResourceDescriptionsData newData = getCopiedResourceDescriptionsData();
	final Collection<IResourceDescription.Delta> result = doUpdate(buildData, newData, subMonitor.split(1));

	if (monitor.isCanceled())
		throw new OperationCanceledException();
	final ResourceDescriptionChangeEvent event = new ResourceDescriptionChangeEvent(result);
	// update the reference
	setResourceDescriptionsData(newData);
	notifyListeners(event);
	return event.getDeltas();
}
 
Example #3
Source File: FlatResourceSetBasedAllContainersState.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean containsURI(String containerHandle, URI candidateURI) {
	if (!HANDLE.equals(containerHandle))
		return false;
	if (resourceSet instanceof XtextResourceSet) {
		ResourceDescriptionsData descriptionsData = findResourceDescriptionsData(resourceSet);
		if (descriptionsData != null) {
			return descriptionsData.getResourceDescription(candidateURI) != null;
		}
		Collection<URI> allUris = ((XtextResourceSet) resourceSet).getNormalizationMap().values();
		for (URI uri : allUris) {
			if (uri.equals(candidateURI)) {
				return true;
			}
		}
		return false;
	}
	URIConverter uriConverter = resourceSet.getURIConverter();
	for (Resource r : resourceSet.getResources()) {
		URI normalized = uriConverter.normalize(r.getURI());
		if (normalized.equals(candidateURI)) {
			return true;
		}
	}
	return false;
}
 
Example #4
Source File: XProjectManager.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/** Build this project. */
protected XBuildResult doBuild(Set<URI> dirtyFiles, Set<URI> deletedFiles,
		List<IResourceDescription.Delta> externalDeltas, boolean propagateIssues, boolean doGenerate,
		CancelIndicator cancelIndicator) {

	URI persistenceFile = projectStateHolder.getPersistenceFile(projectConfig);
	dirtyFiles.remove(persistenceFile);
	deletedFiles.remove(persistenceFile);

	XBuildRequest request = newBuildRequest(dirtyFiles, deletedFiles, externalDeltas, propagateIssues, doGenerate,
			cancelIndicator);
	resourceSet = request.getResourceSet(); // resourceSet is already used during the build via #getResource(URI)

	XBuildResult result = incrementalBuilder.build(request);

	projectStateHolder.updateProjectState(request, result, projectConfig);

	ResourceDescriptionsData resourceDescriptions = projectStateHolder.getIndexState().getResourceDescriptions();
	fullIndex.setContainer(projectDescription.getName(), resourceDescriptions);

	return result;
}
 
Example #5
Source File: Indexer.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Process the deleted resources.
 */
protected List<IResourceDescription.Delta> getDeltasForDeletedResources(BuildRequest request,
		ResourceDescriptionsData oldIndex, BuildContext context) {
	List<IResourceDescription.Delta> deltas = new ArrayList<>();
	for (URI deleted : request.getDeletedFiles()) {
		IResourceServiceProvider resourceServiceProvider = context.getResourceServiceProvider(deleted);
		if (resourceServiceProvider != null) {
			operationCanceledManager.checkCanceled(context.getCancelIndicator());
			IResourceDescription oldDescription = oldIndex != null ? oldIndex.getResourceDescription(deleted)
					: null;
			if (oldDescription != null) {
				DefaultResourceDescriptionDelta delta = new DefaultResourceDescriptionDelta(oldDescription, null);
				deltas.add(delta);
			}
		}
	}
	return deltas;
}
 
Example #6
Source File: XIndexer.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Process the deleted resources.
 */
protected List<IResourceDescription.Delta> getDeltasForDeletedResources(XBuildRequest request,
		ResourceDescriptionsData oldIndex, XBuildContext context) {

	List<IResourceDescription.Delta> deltas = new ArrayList<>();
	for (URI deleted : request.getDeletedFiles()) {
		IResourceServiceProvider resourceServiceProvider = context.getResourceServiceProvider(deleted);
		if (resourceServiceProvider != null) {
			this.operationCanceledManager.checkCanceled(context.getCancelIndicator());
			IResourceDescription oldDescription = oldIndex != null ? oldIndex.getResourceDescription(deleted)
					: null;
			if (oldDescription != null) {
				DefaultResourceDescriptionDelta delta = new DefaultResourceDescriptionDelta(oldDescription, null);
				deltas.add(delta);
			}
		}
	}
	return deltas;
}
 
Example #7
Source File: XIndexer.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Process the changed resources.
 */
protected List<IResourceDescription.Delta> getDeltasForChangedResources(Iterable<URI> changedURIs,
		ResourceDescriptionsData oldIndex, XBuildContext context) {
	try {
		this.compilerPhases.setIndexing(context.getResourceSet(), true);
		List<IResourceDescription.Delta> result = new ArrayList<>();
		List<Delta> deltas = context.executeClustered(changedURIs, it -> addToIndex(it, true, oldIndex, context));
		for (IResourceDescription.Delta delta : deltas) {
			if (delta != null) {
				result.add(delta);
			}
		}
		return result;
	} finally {
		this.compilerPhases.setIndexing(context.getResourceSet(), false);
	}
}
 
Example #8
Source File: ProjectStatePersister.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param stream
 *            the stream to read from.
 * @param expectedLanguageVersion
 *            the language version as it is expected to be present in the stream
 * @throws IOException
 *             if things go bananas.
 * @throws ClassNotFoundException
 *             if things go bananas.
 */
public PersistedState readProjectState(InputStream stream, String expectedLanguageVersion)
		throws IOException, ClassNotFoundException {

	int version = stream.read();
	if (version != CURRENT_VERSION) {
		return null;
	}

	try (DataInputStream input = new DataInputStream(new BufferedInputStream(new GZIPInputStream(stream, 8192)))) {
		String languageVersion = input.readUTF();
		if (!expectedLanguageVersion.equals(languageVersion)) {
			return null;
		}
		ResourceDescriptionsData resourceDescriptionsData = readResourceDescriptions(input);

		XSource2GeneratedMapping fileMappings = readFileMappings(input);

		Map<URI, HashedFileContent> fingerprints = readFingerprints(input);

		Multimap<URI, LSPIssue> validationIssues = readValidationIssues(input);

		XIndexState indexState = new XIndexState(resourceDescriptionsData, fileMappings);
		return new PersistedState(indexState, fingerprints, validationIssues);
	}
}
 
Example #9
Source File: XIndexer.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Index the given resource.
 *
 * @param isPreIndexing
 *            can be evaluated to produce different index entries depending on the phase
 */
protected IResourceDescription.Delta addToIndex(Resource resource, boolean isPreIndexing,
		ResourceDescriptionsData oldIndex, XBuildContext context) {
	this.operationCanceledManager.checkCanceled(context.getCancelIndicator());
	if (context.getResourceSet() != resource.getResourceSet()) {
		// we are seeing an out-of-sequence resource - don't index it
		return null;
	}
	URI uri = resource.getURI();
	IResourceServiceProvider serviceProvider = context.getResourceServiceProvider(uri);
	IResourceDescription.Manager manager = serviceProvider.getResourceDescriptionManager();
	IResourceDescription newDescription = manager.getResourceDescription(resource);
	IResourceDescription toBeAdded = new XIndexer.XResolvedResourceDescription(newDescription);
	IResourceDescription.Delta delta = manager
			.createDelta(oldIndex != null ? oldIndex.getResourceDescription(uri) : null, toBeAdded);
	return delta;
}
 
Example #10
Source File: XIncrementalBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Run the build.
 * <p>
 * Cancellation behavior: does not throw exception but returns with a partial result.
 */
public XBuildResult build(XBuildRequest request, IResourceClusteringPolicy clusteringPolicy) {

	ResourceDescriptionsData resDescrsCopy = request.getState().getResourceDescriptions().copy();
	XSource2GeneratedMapping fileMappingsCopy = request.getState().getFileMappings().copy();
	XIndexState oldState = new XIndexState(resDescrsCopy, fileMappingsCopy);

	XtextResourceSet resourceSet = request.getResourceSet();
	XBuildContext context = new XBuildContext(languagesRegistry::getResourceServiceProvider,
			resourceSet, oldState, clusteringPolicy, request.getCancelIndicator());

	XStatefulIncrementalBuilder builder = provider.get();
	builder.setContext(context);
	builder.setRequest(request);

	return builder.launch();
}
 
Example #11
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Flushes the changes (added / removed resources) to the database without committing them.
 *
 * @param newData
 *          resource descriptions data
 */
protected void flushChanges(final ResourceDescriptionsData newData) {
  if (newData instanceof IResourceDescriptionsData) {
    long time = System.currentTimeMillis();
    try {
      traceSet.started(BuildFlushEvent.class);
      ((IResourceDescriptionsData) newData).flushChanges();
    } finally {
      traceSet.ended(BuildFlushEvent.class);
    }
    long flushTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - time);
    if (flushTime > COMMIT_WARN_WAIT_SEC) {
      LOGGER.warn("Flushing of the database changes took " + flushTime + " seconds."); //$NON-NLS-1$//$NON-NLS-2$
    }
  }
}
 
Example #12
Source File: DoUpdateImplementation.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
public DoUpdateImplementation(N4ClusteringBuilderState state, BuildData buildData,
		ResourceDescriptionsData newData, IProgressMonitor monitor, IBuildLogger buildLogger,
		IResourceLoader crossLinkingResourceLoader, IResourceClusteringPolicy clusteringPolicy) {
	this.clusteringPolicy = clusteringPolicy;
	this.crossLinkingResourceLoader = crossLinkingResourceLoader;
	this.buildLogger = buildLogger;
	this.state = state;
	this.buildData = buildData;
	this.newData = newData;
	this.progress = SubMonitor.convert(monitor);
	this.cancelMonitor = new MonitorBasedCancelIndicator(progress);
	this.toBeDeleted = buildData.getAndRemoveToBeDeleted();
	this.resourceSet = buildData.getResourceSet();
	this.newState = new CurrentDescriptions(resourceSet, newData, buildData);
	this.currentProject = state.getBuiltProject(buildData);
	this.queue = buildData.getURIQueue();
}
 
Example #13
Source File: XcoreReader.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param resourceSet
 *            the resource set to index
 */
private void installIndex(ResourceSet resourceSet) {
	// Fill index
	ResourceDescriptionsData index = new ResourceDescriptionsData(Lists.newArrayList());
	List<Resource> resources = Lists.newArrayList(resourceSet.getResources());
	for (Resource resource : resources) {
		index(resource, resource.getURI(), index);
	}
	ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(resourceSet, index);
}
 
Example #14
Source File: LiveShadowedChunkedContainerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  try {
    WorkspaceConfig _workspaceConfig = new WorkspaceConfig();
    this.workspaceConfig = _workspaceConfig;
    ProjectConfig _projectConfig = new ProjectConfig("foo", this.workspaceConfig);
    this.fooProject = _projectConfig;
    ProjectConfig _projectConfig_1 = new ProjectConfig("bar", this.workspaceConfig);
    this.barProject = _projectConfig_1;
    final XtextResourceSet rs0 = this.resourceSetProvider.get();
    this.fooURI = IterableExtensions.<SourceFolder>head(this.fooProject.getSourceFolders()).getPath().trimSegments(1).appendSegment("foo.livecontainertestlanguage");
    this.barURI = IterableExtensions.<SourceFolder>head(this.barProject.getSourceFolders()).getPath().trimSegments(1).appendSegment("bar.livecontainertestlanguage");
    ResourceDescriptionsData _createResourceDescriptionData = this.createResourceDescriptionData(this._parseHelper.parse("foo", this.fooURI, rs0).eResource());
    Pair<String, ResourceDescriptionsData> _mappedTo = Pair.<String, ResourceDescriptionsData>of("foo", _createResourceDescriptionData);
    ResourceDescriptionsData _createResourceDescriptionData_1 = this.createResourceDescriptionData(this._parseHelper.parse("bar", this.barURI, rs0).eResource());
    Pair<String, ResourceDescriptionsData> _mappedTo_1 = Pair.<String, ResourceDescriptionsData>of("bar", _createResourceDescriptionData_1);
    final Map<String, ResourceDescriptionsData> chunks = Collections.<String, ResourceDescriptionsData>unmodifiableMap(CollectionLiterals.<String, ResourceDescriptionsData>newHashMap(_mappedTo, _mappedTo_1));
    this.rs1 = this.resourceSetProvider.get();
    new ChunkedResourceDescriptions(chunks, this.rs1);
    ProjectConfigAdapter.install(this.rs1, this.fooProject);
    this.liveShadowedChunkedResourceDescriptions = this.provider.get();
    this.liveShadowedChunkedResourceDescriptions.setContext(this.rs1);
    LiveShadowedChunkedContainer _liveShadowedChunkedContainer = new LiveShadowedChunkedContainer(this.liveShadowedChunkedResourceDescriptions, "foo");
    this.fooContainer = _liveShadowedChunkedContainer;
    LiveShadowedChunkedContainer _liveShadowedChunkedContainer_1 = new LiveShadowedChunkedContainer(this.liveShadowedChunkedResourceDescriptions, "bar");
    this.barContainer = _liveShadowedChunkedContainer_1;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #15
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void writeNewResourceDescriptions(final BuildData buildData, final IResourceDescriptions oldState, final CurrentDescriptions newState, final ResourceDescriptionsData newData, final IProgressMonitor monitor) {
  final List<List<URI>> toWriteGroups = phaseOneBuildSorter.sort(buildData.getToBeUpdated());
  final List<URI> toBuild = Lists.newLinkedList();
  ResourceSet resourceSet = buildData.getResourceSet();
  BuildPhases.setIndexing(resourceSet, true);
  int totalSize = 0;
  for (List<URI> group : toWriteGroups) {
    totalSize = totalSize + group.size();
  }
  final SubMonitor subMonitor = SubMonitor.convert(monitor, Messages.MonitoredClusteringBuilderState_WRITE_DESCRIPTIONS, totalSize);

  try {
    traceSet.started(BuildIndexingEvent.class);
    /*
     * We handle one group at a time to enforce strict ordering between some specific source types.
     * I.e. We start processing a source type (or a set of them) only after all occurrences of another source on which the depend has been written into the
     * index.
     * One list sorted by source type would not be enough to enforce such ordering in a parallel loading scenario.
     * In fact, in this case we might start processing sources before the ones they depend on are still being handled.
     */
    for (Collection<URI> fileExtensionBuildGroup : toWriteGroups) {
      toBuild.addAll(writeResources(fileExtensionBuildGroup, buildData, oldState, newState, subMonitor));
    }
    flushChanges(newData);
  } finally {
    // Clear the flags
    BuildPhases.setIndexing(resourceSet, false);
    resourceSet.getLoadOptions().remove(ILazyLinkingResource2.MARK_UNRESOLVABLE_XREFS);
    phaseTwoBuildSorter.sort(toBuild).stream().flatMap(List::stream).forEach(buildData::queueURI);
    traceSet.ended(BuildIndexingEvent.class);
  }

}
 
Example #16
Source File: ProjectManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create and configure a new resource set for this project.
 */
public XtextResourceSet createNewResourceSet(ResourceDescriptionsData newIndex) {
	XtextResourceSet result = resourceSetProvider.get();
	projectDescription.attachToEmfObject(result);
	ProjectConfigAdapter.install(result, projectConfig);
	ChunkedResourceDescriptions index = new ChunkedResourceDescriptions(indexProvider.get(), result);
	index.setContainer(projectDescription.getName(), newIndex);
	externalContentSupport.configureResourceSet(result, openedDocumentsContentProvider);
	return result;
}
 
Example #17
Source File: ReusedTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
	super.setUp();
	if (ReusedTypeProviderTest.typeProvider == null) {
		String pathToSources = "/org/eclipse/xtext/common/types/testSetups";
		List<String> files = ReusedTypeProviderTest.readResource(pathToSources + "/files.list");
		ResourceDescriptionsData part = new ResourceDescriptionsData(Collections.emptySet());
		XtextResourceSet resourceSet = resourceSetProvider.get();
		ProjectDescription projectDesc = new ProjectDescription();
		projectDesc.setName("my-test-project");
		projectDesc.attachToEmfObject(resourceSet);
		ChunkedResourceDescriptions index = new ChunkedResourceDescriptions(Collections.emptyMap(), resourceSet);
		index.setContainer(projectDesc.getName(), part);
		resourceSet.setClasspathURIContext(ReusedTypeProviderTest.class.getClassLoader());

		typeProviderFactory.createTypeProvider(resourceSet);
		BuildRequest buildRequest = new BuildRequest();
		for (String file : files) {
			if (file != null) {
				String fullPath = pathToSources + "/" + file;
				URL url = ReusedTypeProviderTest.class.getResource(fullPath);
				buildRequest.getDirtyFiles().add(URI.createURI(url.toExternalForm()));
			}
		}
		buildRequest.setResourceSet(resourceSet);
		buildRequest.setState(new IndexState(part, new Source2GeneratedMapping()));
		builder.build(buildRequest, (URI it) -> {
			return resourceServiceProviderRegistry.getResourceServiceProvider(it);
		});
		ReusedTypeProviderTest.typeProvider = typeProviderFactory.findTypeProvider(resourceSet);
	}
}
 
Example #18
Source File: ProjectManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create an empty resource set.
 */
protected XtextResourceSet createFreshResourceSet(ResourceDescriptionsData newIndex) {
	if (resourceSet == null) {
		resourceSet = createNewResourceSet(newIndex);
	} else {
		ChunkedResourceDescriptions resDescs = ChunkedResourceDescriptions.findInEmfObject(resourceSet);
		for (Map.Entry<String, ResourceDescriptionsData> entry : indexProvider.get().entrySet()) {
			resDescs.setContainer(entry.getKey(), entry.getValue());
		}
		resDescs.setContainer(projectDescription.getName(), newIndex);
	}
	return resourceSet;
}
 
Example #19
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Set the resource descriptions data, unless cancellation has been requested.
 *
 * @param newData
 *          the new resource descriptions data
 * @param monitor
 *          the monitor to check for cancellation
 */
protected void setResourceDescriptionsData(final ResourceDescriptionsData newData, final IProgressMonitor monitor) {
  checkForCancellation(monitor);
  rawData = newData;
  if (newData instanceof IResourceDescriptions2) {
    myData = (IResourceDescriptions2) newData;
  } else {
    myData = new ResourceDescriptions2(newData);
  }
  super.setResourceDescriptionsData(newData);
  if (isLoaded && newData instanceof AbstractResourceDescriptionsData) {
    ((AbstractResourceDescriptionsData) newData).commitChanges();
  }
  isLoaded = true;
}
 
Example #20
Source File: DefaultXtextTargetPlatform.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IResourceDescriptionsData getIResourceDescriptionsData() {
  if (index == null) {
    index = new DelegatingResourceDescriptionsData(new ResourceDescriptionsData(stateLoader.load()));
  }
  return index;
}
 
Example #21
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public synchronized void load() {
  if (!isLoaded) {
    IXtextTargetPlatform platform = targetPlatformManager.getPlatform();
    setDerivedObjectAssociationsStore(platform.getAssociationsStore());
    setResourceDescriptionsData((ResourceDescriptionsData) platform.getIResourceDescriptionsData());
    updateBinaryStorageAvailability(platform);
    isLoaded = true;
  }
}
 
Example #22
Source File: MonitoredClusteringBuilderState.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@SuppressWarnings("PMD.AvoidInstanceofChecksInCatchClause")
public synchronized ImmutableList<Delta> update(final BuildData buildData, final IProgressMonitor monitor) {
  ensureLoaded();
  final SubMonitor subMonitor = SubMonitor.convert(monitor, org.eclipse.xtext.builder.builderState.Messages.AbstractBuilderState_0, 1);
  subMonitor.subTask(org.eclipse.xtext.builder.builderState.Messages.AbstractBuilderState_0);

  checkForCancellation(monitor);

  final ResourceDescriptionsData newData = getCopiedResourceDescriptionsData();
  Collection<IResourceDescription.Delta> result = null;
  try {
    result = doUpdate(buildData, newData, subMonitor.newChild(1));
    // update the reference
    setResourceDescriptionsData(newData, monitor);
    // CHECKSTYLE:CHECK-OFF IllegalCatch
  } catch (Throwable t) {
    // CHECKSTYLE:CHECK-ON IllegalCatch
    if (!operationCanceledManager.isOperationCanceledException(t)) {
      LOGGER.error("Failed to update index. Executing rollback.", t); //$NON-NLS-1$
    }
    if (newData instanceof AbstractResourceDescriptionsData) {
      ((AbstractResourceDescriptionsData) newData).rollbackChanges();
    }
    throw t;
  }

  final ResourceDescriptionChangeEvent event = new ResourceDescriptionChangeEvent(result);
  notifyListeners(event);
  return event.getDeltas();
}
 
Example #23
Source File: LanguageConfig.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private void installIndex(ResourceSet resourceSet) {
	if (ResourceDescriptionsData.ResourceSetAdapter.findResourceDescriptionsData(resourceSet) == null) {
		// Fill index
		ResourceDescriptionsData index = new ResourceDescriptionsData(Collections.<IResourceDescription>emptyList());
		List<Resource> resources = Lists.newArrayList(resourceSet.getResources());
		for (Resource resource : resources) {
			index(resource, resource.getURI(), index);
		}
		ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(resourceSet, index);
	}
}
 
Example #24
Source File: IndexedJvmTypeAccessTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetIndexedJvmTypeByURI() throws ClassNotFoundException {
	ProjectDescription projectDescription = new ProjectDescription();
	projectDescription.setName("test-project");
	ChunkedResourceDescriptions index = new ChunkedResourceDescriptions(Collections.emptyMap(), resourceSet);
	ResourceDescriptionsData data = new ResourceDescriptionsData(new ArrayList<>());
	index.setContainer(projectDescription.getName(), data);
	ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(resourceSet, data);

	Resource resource = resourceSet.createResource(URI.createURI("test.typesRefactoring"));

	BinaryClass binaryClass = BinaryClass.forName("testdata.Outer", getClass().getClassLoader());
	JvmDeclaredType outerType = declaredTypeFactory.createType(binaryClass);
	resource.getContents().add(outerType);
	JvmDeclaredType innerType = findType(outerType, "Inner");
	JvmDeclaredType innerMostType = findType(outerType, "InnerMost");

	IResourceServiceProvider serviceProvider = IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(resource.getURI());
	IResourceDescription description = serviceProvider.getResourceDescriptionManager().getResourceDescription(resource);
	data.addDescription(description.getURI(), description);

	URI javaObjectURI = EcoreUtil.getURI(getOperation(outerType, "getOuter").getReturnType().getType());
	EObject outerTypeFromIndex = indexedJvmTypeAccess.getIndexedJvmType(javaObjectURI , resourceSet);
	assertSame(outerType, outerTypeFromIndex);

	javaObjectURI = EcoreUtil.getURI(getOperation(outerType, "getInner").getReturnType().getType());
	EObject innerTypeFromIndex = indexedJvmTypeAccess.getIndexedJvmType(javaObjectURI , resourceSet);
	assertSame(innerType, innerTypeFromIndex);

	javaObjectURI = EcoreUtil.getURI(getOperation(outerType, "getInnerMost").getReturnType().getType());
	EObject innerMostTypeFromIndex = indexedJvmTypeAccess.getIndexedJvmType(javaObjectURI , resourceSet);
	assertSame(innerMostType, innerMostTypeFromIndex);
}
 
Example #25
Source File: ProjectDescriptionBasedContainerManager.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
protected IContainer createContainer(IResourceDescriptions resourceDescriptions,
		ChunkedResourceDescriptions chunkedResourceDescriptions, String projectName) {
	if (resourceDescriptions instanceof LiveShadowedChunkedResourceDescriptions) {
		return new LiveShadowedChunkedContainer((LiveShadowedChunkedResourceDescriptions) resourceDescriptions,
				projectName);
	} else {
		ResourceDescriptionsData container = chunkedResourceDescriptions.getContainer(projectName);
		return new ResourceDescriptionsBasedContainer(
				container != null ? container : new ResourceDescriptionsData(Collections.emptySet()));
	}
}
 
Example #26
Source File: N4JSRuntimeCore.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void installIndex(ResourceSet resourceSet) {
	// Fill index
	ResourceDescriptionsData index = new OrderedResourceDescriptionsData(
			Collections.<IResourceDescription> emptyList());
	List<Resource> resources = Lists.newArrayList(resourceSet.getResources());
	for (Resource resource : resources) {
		index(resource, resource.getURI(), index);
	}
	Adapter existing = EcoreUtil.getAdapter(resourceSet.eAdapters(), ResourceDescriptionsData.class);
	if (existing != null) {
		resourceSet.eAdapters().remove(existing);
	}
	ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(resourceSet, index);
}
 
Example #27
Source File: ContainerStructureSnapshot.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** See {@link ContainerStructureSnapshot}. */
public static ContainerStructureSnapshot create(Map<String, ResourceDescriptionsData> descriptions,
		Map<String, ImmutableSet<String>> visibleContainers) {

	ImmutableMap.Builder<String, ImmutableSet<URI>> containerHandle2URIs = ImmutableMap.builder();
	for (Entry<String, ResourceDescriptionsData> entry : descriptions.entrySet()) {
		Iterable<URI> uris = Iterables.transform(entry.getValue().getAllResourceDescriptions(),
				IResourceDescription::getURI);
		containerHandle2URIs.put(entry.getKey(), ImmutableSet.copyOf(uris));
	}

	return new ContainerStructureSnapshot(containerHandle2URIs.build(), ImmutableMap.copyOf(visibleContainers));
}
 
Example #28
Source File: OpenFileContext.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
protected XtextResourceSet createResourceSet() {
	XtextResourceSet result = resourceSetProvider.get();
	ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(result, index);
	externalContentSupport.configureResourceSet(result, new OpenFileContentProvider());

	IAllContainersState allContainersState = new OpenFileAllContainersState(this);
	result.eAdapters().add(new DelegatingIAllContainerAdapter(allContainersState));

	return result;
}
 
Example #29
Source File: OpenFileContext.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("hiding")
public synchronized void initialize(OpenFilesManager parent, URI uri, boolean isTemporary,
		ResourceDescriptionsData index, ContainerStructureSnapshot containerStructure) {
	this.parent = parent;
	this.mainURI = uri;
	this.temporary = isTemporary;
	this.index = index;
	this.containerStructure = containerStructure;

	this.mainResourceSet = createResourceSet();
}
 
Example #30
Source File: OpenFilesManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** Creates an index containing the persisted state shadowed by the dirty state of all open files. */
public synchronized ResourceDescriptionsData createLiveScopeIndex() {
	ResourceDescriptionsData result = createPersistedStateIndex();
	sharedDirtyState.getAllResourceDescriptions()
			.forEach(desc -> result.addDescription(desc.getURI(), desc));
	return result;
}