Search in sources :

Example 1 with LoadOperationException

use of org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException in project xtext-eclipse by eclipse.

the class ClusteringBuilderState method writeNewResourceDescriptions.

/**
 * Create new resource descriptions for a set of resources given by their URIs.
 *
 * @param buildData
 *            The underlying data for the write operation.
 * @param oldState
 *            The old index
 * @param newState
 *            The new index
 * @param monitor
 *            The progress monitor used for user feedback
 */
protected void writeNewResourceDescriptions(BuildData buildData, IResourceDescriptions oldState, CurrentDescriptions newState, final IProgressMonitor monitor) {
    int index = 0;
    ResourceSet resourceSet = buildData.getResourceSet();
    Set<URI> toBeUpdated = buildData.getToBeUpdated();
    // TODO: NLS
    final SubMonitor subMonitor = SubMonitor.convert(monitor, "Write new resource descriptions", toBeUpdated.size() + 1);
    IProject currentProject = getBuiltProject(buildData);
    LoadOperation loadOperation = null;
    try {
        compilerPhases.setIndexing(resourceSet, true);
        loadOperation = globalIndexResourceLoader.create(resourceSet, currentProject);
        loadOperation.load(toBeUpdated);
        while (loadOperation.hasNext()) {
            if (subMonitor.isCanceled()) {
                loadOperation.cancel();
                throw new OperationCanceledException();
            }
            if (!clusteringPolicy.continueProcessing(resourceSet, null, index)) {
                clearResourceSet(resourceSet);
            }
            URI uri = null;
            Resource resource = null;
            try {
                LoadResult loadResult = loadOperation.next();
                uri = loadResult.getUri();
                resource = addResource(loadResult.getResource(), resourceSet);
                subMonitor.subTask("Writing new resource description " + resource.getURI().lastSegment());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Writing new resource description " + uri);
                }
                final IResourceDescription.Manager manager = getResourceDescriptionManager(uri);
                if (manager != null) {
                    // We don't care here about links, we really just want the exported objects so that we can link in the
                    // next phase.
                    final IResourceDescription description = manager.getResourceDescription(resource);
                    final IResourceDescription copiedDescription = new CopiedResourceDescription(description);
                    // We also don't care what kind of Delta we get here; it's just a temporary transport vehicle. That interface
                    // could do with some clean-up, too, because all we actually want to do is register the new resource
                    // description, not the delta.
                    newState.register(new DefaultResourceDescriptionDelta(oldState.getResourceDescription(uri), copiedDescription));
                    buildData.queueURI(uri);
                }
            } catch (final RuntimeException ex) {
                if (ex instanceof LoadOperationException) {
                    uri = ((LoadOperationException) ex).getUri();
                }
                if (uri == null) {
                    // $NON-NLS-1$
                    LOGGER.error("Error loading resource", ex);
                } else {
                    if (resourceSet.getURIConverter().exists(uri, Collections.emptyMap())) {
                        // $NON-NLS-1$
                        LOGGER.error("Error loading resource from: " + uri.toString(), ex);
                    }
                    if (resource != null) {
                        resourceSet.getResources().remove(resource);
                    }
                    final IResourceDescription oldDescription = oldState.getResourceDescription(uri);
                    if (oldDescription != null) {
                        newState.register(new DefaultResourceDescriptionDelta(oldDescription, null));
                    }
                }
            // If we couldn't load it, there's no use trying again: do not add it to the queue
            }
            index++;
            subMonitor.split(1);
        }
    } finally {
        compilerPhases.setIndexing(resourceSet, false);
        if (loadOperation != null)
            loadOperation.cancel();
    }
}
Also used : IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SubMonitor(org.eclipse.core.runtime.SubMonitor) Resource(org.eclipse.emf.ecore.resource.Resource) StorageAwareResource(org.eclipse.xtext.resource.persistence.StorageAwareResource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) URI(org.eclipse.emf.common.util.URI) IProject(org.eclipse.core.resources.IProject) LoadResult(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadResult) LoadOperation(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperation) LoadOperationException(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta)

Example 2 with LoadOperationException

use of org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException in project xtext-eclipse by eclipse.

the class ClusteringBuilderState method doUpdate.

/**
 * Actually do the build.
 *
 * @param buildData
 *            the data that should be considered for the update
 * @param newData
 *            the new resource descriptions as they are to be persisted (the new index after the build).
 *            Initially contains the old resource descriptions.
 * @param monitor
 *            The progress monitor
 * @return A list of deltas describing all changes made by the build.
 */
@Override
protected Collection<Delta> doUpdate(BuildData buildData, ResourceDescriptionsData newData, IProgressMonitor monitor) {
    // We assume that we have 101 ticks to work with:
    // 20 for writeNewResourceDescription
    // 1 for queueAffectedResources
    // 80 for updating and queueAffectedResources
    // Within the mentioned 80 ticks we assume that 2/3 is spent for updating and 1/3 for queueAffectedResources
    final SubMonitor progress = SubMonitor.convert(monitor, 101);
    // Step 1: Clean the set of deleted URIs. If any of them are also added, they're not deleted.
    final Set<URI> toBeDeleted = buildData.getAndRemoveToBeDeleted();
    // Step 2: Create a new state (old state minus the deleted resources). This, by virtue of the flag
    // NAMED_BUILDER_SCOPE in the resource set's load options
    // and a Guice binding, is the index that is used during the build; i.e., linking during the build will
    // use this. Once the build is completed, the persistable index is reset to the contents of newState by
    // virtue of the newMap, which is maintained in synch with this.
    ResourceSet resourceSet = buildData.getResourceSet();
    final CurrentDescriptions newState = new CurrentDescriptions(resourceSet, newData, buildData);
    buildData.getSourceLevelURICache().cacheAsSourceURIs(toBeDeleted);
    installSourceLevelURIs(buildData);
    // Step 3: Create a queue; write new temporary resource descriptions for the added or updated resources so that we can link
    // subsequently; put all the added or updated resources into the queue.
    writeNewResourceDescriptions(buildData, this, newState, progress.split(20));
    if (progress.isCanceled()) {
        throw new OperationCanceledException();
    }
    // in this set as potential candidates.
    for (final URI uri : toBeDeleted) {
        newData.removeDescription(uri);
    }
    final Set<URI> allRemainingURIs = Sets.newLinkedHashSet(newData.getAllURIs());
    allRemainingURIs.removeAll(buildData.getToBeUpdated());
    for (URI remainingURI : buildData.getAllRemainingURIs()) {
        allRemainingURIs.remove(remainingURI);
    }
    // TODO: consider to remove any entry from upstream projects and independent projects
    // from the set of remaining uris (template method or service?)
    // this should reduce the number of to-be-checked descriptions significantly
    // for common setups (large number of reasonable sized projects)
    // Our return value. It contains all the deltas resulting from this build.
    final Set<Delta> allDeltas = Sets.newHashSet();
    // Step 5: Put all resources depending on a deleted resource into the queue. Also register the deltas in allDeltas.
    if (!toBeDeleted.isEmpty()) {
        for (final URI uri : toBeDeleted) {
            final IResourceDescription oldDescription = this.getResourceDescription(uri);
            if (oldDescription != null) {
                allDeltas.add(new DefaultResourceDescriptionDelta(oldDescription, null));
            }
        }
    }
    // Add all pending deltas to all deltas (may be scheduled java deltas)
    Collection<Delta> pendingDeltas = buildData.getAndRemovePendingDeltas();
    allDeltas.addAll(pendingDeltas);
    queueAffectedResources(allRemainingURIs, this, newState, allDeltas, allDeltas, buildData, progress.split(1));
    installSourceLevelURIs(buildData);
    IProject currentProject = getBuiltProject(buildData);
    LoadOperation loadOperation = null;
    try {
        Queue<URI> queue = buildData.getURIQueue();
        loadOperation = crossLinkingResourceLoader.create(resourceSet, currentProject);
        loadOperation.load(queue);
        // Step 6: Iteratively got through the queue. For each resource, create a new resource description and queue all depending
        // resources that are not yet in the delta. Validate resources.
        final SubMonitor subProgress = progress.split(80);
        CancelIndicator cancelMonitor = new MonitorBasedCancelIndicator(progress);
        while (!queue.isEmpty()) {
            // heuristic: we multiply the size of the queue by 3 and spent 2 ticks for updating
            // and 1 tick for queueAffectedResources since we assume that loading etc. is
            // slower than queueAffectedResources.
            subProgress.setWorkRemaining((queue.size() + 1) * 3);
            int clusterIndex = 0;
            final List<Delta> changedDeltas = Lists.newArrayList();
            while (!queue.isEmpty()) {
                if (subProgress.isCanceled()) {
                    loadOperation.cancel();
                    throw new OperationCanceledException();
                }
                if (!clusteringPolicy.continueProcessing(resourceSet, null, clusterIndex)) {
                    break;
                }
                URI changedURI = null;
                URI actualResourceURI = null;
                Resource resource = null;
                Delta newDelta = null;
                try {
                    // Load the resource and create a new resource description
                    LoadResult loadResult = loadOperation.next();
                    changedURI = loadResult.getUri();
                    actualResourceURI = loadResult.getResource().getURI();
                    resource = addResource(loadResult.getResource(), resourceSet);
                    subProgress.subTask("Updating resource " + resource.getURI().lastSegment());
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Update resource description " + actualResourceURI);
                    }
                    queue.remove(changedURI);
                    if (toBeDeleted.contains(changedURI)) {
                        break;
                    }
                    buildLogger.log("indexing " + changedURI);
                    final IResourceDescription.Manager manager = getResourceDescriptionManager(actualResourceURI);
                    if (manager != null) {
                        // Resolve links here!
                        try {
                            EcoreUtil2.resolveLazyCrossReferences(resource, cancelMonitor);
                            final IResourceDescription description = manager.getResourceDescription(resource);
                            final IResourceDescription copiedDescription = BuilderStateUtil.create(description);
                            newDelta = manager.createDelta(this.getResourceDescription(actualResourceURI), copiedDescription);
                        } catch (OperationCanceledException e) {
                            loadOperation.cancel();
                            throw e;
                        } catch (WrappedException e) {
                            throw e;
                        } catch (RuntimeException e) {
                            LOGGER.error("Error resolving cross references on resource '" + actualResourceURI + "'", e);
                            throw new LoadOperationException(actualResourceURI, e);
                        }
                    }
                } catch (final WrappedException ex) {
                    if (ex instanceof LoadOperationException) {
                        changedURI = ((LoadOperationException) ex).getUri();
                    }
                    Throwable cause = ex.getCause();
                    boolean wasResourceNotFound = false;
                    if (cause instanceof CoreException) {
                        if (IResourceStatus.RESOURCE_NOT_FOUND == ((CoreException) cause).getStatus().getCode()) {
                            wasResourceNotFound = true;
                        }
                    }
                    if (changedURI == null) {
                        // $NON-NLS-1$
                        LOGGER.error("Error loading resource", ex);
                    } else {
                        queue.remove(changedURI);
                        if (toBeDeleted.contains(changedURI))
                            break;
                        if (!wasResourceNotFound)
                            // $NON-NLS-1$
                            LOGGER.error("Error loading resource from: " + changedURI.toString(), ex);
                        if (resource != null) {
                            resourceSet.getResources().remove(resource);
                        }
                        final IResourceDescription oldDescription = this.getResourceDescription(changedURI);
                        final IResourceDescription newDesc = newState.getResourceDescription(changedURI);
                        ResourceDescriptionImpl indexReadyDescription = newDesc != null ? BuilderStateUtil.create(newDesc) : null;
                        if ((oldDescription != null || indexReadyDescription != null) && oldDescription != indexReadyDescription) {
                            newDelta = new DefaultResourceDescriptionDelta(oldDescription, indexReadyDescription);
                        }
                    }
                }
                if (newDelta != null) {
                    allDeltas.add(newDelta);
                    clusterIndex++;
                    if (newDelta.haveEObjectDescriptionsChanged())
                        changedDeltas.add(newDelta);
                    // Make the new resource description known and update the map.
                    newState.register(newDelta);
                    // Validate now.
                    if (!buildData.isIndexingOnly()) {
                        try {
                            updateMarkers(newDelta, resourceSet, subProgress);
                        } catch (OperationCanceledException e) {
                            loadOperation.cancel();
                            throw e;
                        } catch (Exception e) {
                            LOGGER.error("Error validating " + newDelta.getUri(), e);
                        }
                    }
                }
                // 2 ticks for updating since updating makes 2/3 of the work
                subProgress.split(2);
            }
            loadOperation.cancel();
            queueAffectedResources(allRemainingURIs, this, newState, changedDeltas, allDeltas, buildData, subProgress.split(1));
            installSourceLevelURIs(buildData);
            if (queue.size() > 0) {
                loadOperation = crossLinkingResourceLoader.create(resourceSet, currentProject);
                loadOperation.load(queue);
            }
            // Release memory
            if (!queue.isEmpty() && !clusteringPolicy.continueProcessing(resourceSet, null, clusterIndex))
                clearResourceSet(resourceSet);
        }
    } finally {
        if (loadOperation != null)
            loadOperation.cancel();
        if (!progress.isCanceled())
            progress.done();
    }
    return allDeltas;
}
Also used : IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) ResourceDescriptionImpl(org.eclipse.xtext.builder.builderState.impl.ResourceDescriptionImpl) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) URI(org.eclipse.emf.common.util.URI) MonitorBasedCancelIndicator(org.eclipse.xtext.builder.MonitorBasedCancelIndicator) LoadOperation(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperation) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta) WrappedException(org.eclipse.emf.common.util.WrappedException) SubMonitor(org.eclipse.core.runtime.SubMonitor) Resource(org.eclipse.emf.ecore.resource.Resource) StorageAwareResource(org.eclipse.xtext.resource.persistence.StorageAwareResource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) IProject(org.eclipse.core.resources.IProject) LoadResult(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadResult) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) LoadOperationException(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException) WrappedException(org.eclipse.emf.common.util.WrappedException) LoadOperationException(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException) CoreException(org.eclipse.core.runtime.CoreException) Delta(org.eclipse.xtext.resource.IResourceDescription.Delta) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta) MonitorBasedCancelIndicator(org.eclipse.xtext.builder.MonitorBasedCancelIndicator) CancelIndicator(org.eclipse.xtext.util.CancelIndicator)

Example 3 with LoadOperationException

use of org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException in project dsl-devkit by dsldevkit.

the class MonitoredClusteringBuilderState method doUpdate.

/**
 * {@inheritDoc}
 */
@Override
protected // CHECKSTYLE:CHECK-OFF NestedTryDepth
Collection<Delta> doUpdate(final BuildData buildData, final ResourceDescriptionsData newData, final IProgressMonitor monitor) {
    // NOPMD
    final SubMonitor progress = SubMonitor.convert(monitor, 100);
    // Step 1: Clean the set of deleted URIs. If any of them are also added, they're not deleted.
    final Set<URI> toBeDeleted = Sets.newHashSet(buildData.getToBeDeleted());
    toBeDeleted.removeAll(buildData.getToBeUpdated());
    ResourceSet resourceSet = buildData.getResourceSet();
    // Step 2: Create a new state (old state minus the deleted resources). This, by virtue of the flag above
    // and a Guice binding, is the index that is used during the build; i.e., linking during the build will
    // use this. Once the build is completed, the persistable index is reset to the contents of newState by
    // virtue of the newMap, which is maintained in synch with this.
    final CurrentDescriptions2 newState = createCurrentDescriptions(resourceSet, newData);
    final Map<URI, IResourceDescription> oldDescriptions = saveOldDescriptions(buildData);
    buildData.getSourceLevelURICache().cacheAsSourceURIs(toBeDeleted);
    installSourceLevelURIs(buildData);
    // Step 3: Create a queue; write new temporary resource descriptions for the added or updated resources
    // so that we can link subsequently; put all the added or updated resources into the queue.
    // CHECKSTYLE:CONSTANTS-OFF
    writeNewResourceDescriptions(buildData, this, newState, newData, progress.newChild(20));
    // CHECKSTYLE:CONSTANTS-ON
    // clear resource set to wipe out derived state of phase 1 model inference and all corresponding references
    clearResourceSet(resourceSet);
    LOGGER.info(Messages.MonitoredClusteringBuilderState_PHASE_ONE_DONE);
    checkForCancellation(progress);
    // in this set as potential candidates. Make sure that notInDelta is a modifiable Set, not some immutable view.
    for (final URI uri : toBeDeleted) {
        checkForCancellation(monitor);
        newData.removeDescription(uri);
    }
    final Set<URI> allRemainingURIs = createCandidateSet(newData.getAllURIs());
    allRemainingURIs.removeAll(buildData.getToBeUpdated());
    for (URI remainingURI : buildData.getAllRemainingURIs()) {
        allRemainingURIs.remove(remainingURI);
    }
    flushChanges(newData);
    // Our return value. It contains all the deltas resulting from this build.
    final Set<Delta> allDeltas = Sets.newHashSet();
    // Step 5: Put all resources depending on a deleted resource into the queue. Also register the deltas in allDeltas.
    if (!toBeDeleted.isEmpty()) {
        addDeletedURIsToDeltas(toBeDeleted, allDeltas, oldDescriptions);
        // Here, we have only the deltas for deleted resources in allDeltas. Make sure that all markers are removed.
        // Normally, resources in toBeDeleted will have their storage(s) deleted, so Eclipse will automatically
        // remove the markers. However, if the ToBeBuiltComputer adds resources to the tobeDeleted set that are not or
        // have not been physically removed, markers would otherwise remain even though the resource is no longer part
        // of the Xtext world (index). Since the introduction of IResourcePostProcessor, we also need to do this to give
        // the post-processor a chance to do whatever needs doing when a resource is removed.
        updateDeltas(allDeltas, resourceSet, progress.newChild(1));
    }
    // Add all pending deltas to all deltas (may be scheduled java deltas)
    Collection<Delta> pendingDeltas = buildData.getAndRemovePendingDeltas();
    allDeltas.addAll(pendingDeltas);
    queueAffectedResources(allRemainingURIs, this, newState, allDeltas, allDeltas, buildData, progress.newChild(1));
    IProject currentProject = getBuiltProject(buildData);
    IResourceLoader.LoadOperation loadOperation = null;
    final BuilderWatchdog watchdog = new BuilderWatchdog();
    try {
        traceSet.started(BuildLinkingEvent.class);
        Queue<URI> queue = buildData.getURIQueue();
        loadOperation = crossLinkingResourceLoader.create(resourceSet, currentProject);
        loadOperation.load(queue);
        // Step 6: Iteratively got through the queue. For each resource, create a new resource description and queue all depending
        // resources that are not yet in the delta. Validate resources. Do this in chunks.
        final SubMonitor subProgress = progress.newChild(80);
        final CancelIndicator cancelMonitor = new CancelIndicator() {

            @Override
            public boolean isCanceled() {
                return subProgress.isCanceled();
            }
        };
        watchdog.start();
        int index = 1;
        while (!queue.isEmpty()) {
            // CHECKSTYLE:CONSTANTS-OFF
            subProgress.setWorkRemaining(queue.size() * 3);
            // CHECKSTYLE:CONSTANTS-ON
            final List<Delta> newDeltas = Lists.newArrayListWithExpectedSize(clusterSize);
            final List<Delta> changedDeltas = Lists.newArrayListWithExpectedSize(clusterSize);
            while (!queue.isEmpty() && loadingStrategy.mayProcessAnotherResource(resourceSet, newDeltas.size())) {
                if (subProgress.isCanceled() || !loadOperation.hasNext()) {
                    if (!loadOperation.hasNext()) {
                        LOGGER.warn(Messages.MonitoredClusteringBuilderState_NO_MORE_RESOURCES);
                    }
                    loadOperation.cancel();
                    throw new OperationCanceledException();
                }
                // Load the resource and create a new resource description
                URI changedURI = null;
                Resource resource = null;
                Delta newDelta = null;
                final long initialMemory = Runtime.getRuntime().freeMemory();
                final int initialResourceSetSize = resourceSet.getResources().size();
                final long initialTime = System.nanoTime();
                try {
                    // Load the resource and create a new resource description
                    resource = addResource(loadOperation.next().getResource(), resourceSet);
                    changedURI = resource.getURI();
                    traceSet.started(ResourceProcessingEvent.class, changedURI);
                    queue.remove(changedURI);
                    if (toBeDeleted.contains(changedURI)) {
                        break;
                    }
                    watchdog.reportWorkStarted(changedURI);
                    traceSet.started(ResourceLinkingEvent.class, changedURI);
                    final IResourceDescription.Manager manager = getResourceDescriptionManager(changedURI);
                    if (manager != null) {
                        final Object[] bindings = { Integer.valueOf(index), Integer.valueOf(index + queue.size()), URI.decode(resource.getURI().lastSegment()) };
                        subProgress.subTask(NLS.bind(Messages.MonitoredClusteringBuilderState_UPDATE_DESCRIPTIONS, bindings));
                        // Resolve links here!
                        try {
                            EcoreUtil2.resolveLazyCrossReferences(resource, cancelMonitor);
                            final IResourceDescription description = manager.getResourceDescription(resource);
                            final IResourceDescription copiedDescription = descriptionCopier.copy(description);
                            newDelta = manager.createDelta(getSavedResourceDescription(oldDescriptions, changedURI), copiedDescription);
                        } catch (StackOverflowError ex) {
                            queue.remove(changedURI);
                            logStackOverflowErrorStackTrace(ex, changedURI);
                        }
                    }
                // CHECKSTYLE:CHECK-OFF IllegalCatch - guard against ill behaved implementations
                } catch (final Exception ex) {
                    // CHECKSTYLE:CHECK-ON IllegalCatch
                    pollForCancellation(monitor);
                    if (ex instanceof LoadOperationException) {
                        // NOPMD
                        LoadOperationException loadException = (LoadOperationException) ex;
                        if (loadException.getCause() instanceof TimeoutException) {
                            // Load request timed out, URI of the resource is not available
                            String message = loadException.getCause().getMessage();
                            LOGGER.warn(message);
                        } else {
                            // Exception when loading resource, URI should be available
                            changedURI = ((LoadOperationException) ex).getUri();
                            LOGGER.error(NLS.bind(Messages.MonitoredClusteringBuilderState_CANNOT_LOAD_RESOURCE, changedURI), ex);
                        }
                    } else {
                        LOGGER.error(NLS.bind(Messages.MonitoredClusteringBuilderState_CANNOT_LOAD_RESOURCE, changedURI), ex);
                    }
                    if (changedURI != null) {
                        queue.remove(changedURI);
                    }
                    if (resource != null) {
                        resourceSet.getResources().remove(resource);
                    }
                    final IResourceDescription oldDescription = getSavedResourceDescription(oldDescriptions, changedURI);
                    if (oldDescription != null) {
                        newDelta = new DefaultResourceDescriptionDelta(oldDescription, null);
                    }
                } finally {
                    traceSet.ended(ResourceLinkingEvent.class);
                }
                if (newDelta != null) {
                    allDeltas.add(newDelta);
                    if (newDelta.haveEObjectDescriptionsChanged()) {
                        changedDeltas.add(newDelta);
                    }
                    if (recordDeltaAsNew(newDelta)) {
                        newDeltas.add(newDelta);
                        // Make the new resource description known in the new index.
                        newState.register(newDelta);
                    }
                    try {
                        // Validate directly, instead of bulk validating after the cluster.
                        updateMarkers(newDelta, resourceSet, subProgress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                        postProcess(newDelta, resourceSet, subProgress.newChild(1));
                    } catch (StackOverflowError ex) {
                        queue.remove(changedURI);
                        logStackOverflowErrorStackTrace(ex, changedURI);
                    }
                } else {
                    subProgress.worked(2);
                }
                if (changedURI != null) {
                    final long memoryDelta = Runtime.getRuntime().freeMemory() - initialMemory;
                    final int resourceSetSizeDelta = resourceSet.getResources().size() - initialResourceSetSize;
                    final long timeDelta = System.nanoTime() - initialTime;
                    traceSet.trace(ResourceLinkingMemoryEvent.class, changedURI, memoryDelta, resourceSetSizeDelta, timeDelta);
                    watchdog.reportWorkEnded(index, index + queue.size());
                }
                // Clear caches of resource
                if (resource instanceof XtextResource) {
                    ((XtextResource) resource).getCache().clear(resource);
                }
                traceSet.ended(ResourceProcessingEvent.class);
                buildData.getSourceLevelURICache().getSources().remove(changedURI);
                subProgress.worked(1);
                index++;
            }
            loadOperation.cancel();
            queueAffectedResources(allRemainingURIs, this, newState, changedDeltas, allDeltas, buildData, subProgress.newChild(1));
            newDeltas.clear();
            changedDeltas.clear();
            if (queue.size() > 0) {
                loadOperation = crossLinkingResourceLoader.create(resourceSet, currentProject);
                loadOperation.load(queue);
            }
            if (!queue.isEmpty()) {
                traceSet.trace(ClusterClosedEvent.class, Long.valueOf(resourceSet.getResources().size()));
                clearResourceSet(resourceSet);
            }
        // TODO flush required here or elsewhere ?
        // flushChanges(newData);
        }
    } finally {
        // Report the current size of the resource set
        traceSet.trace(ClusterClosedEvent.class, Long.valueOf(resourceSet.getResources().size()));
        if (loadOperation != null) {
            loadOperation.cancel();
        }
        traceSet.ended(BuildLinkingEvent.class);
        watchdog.interrupt();
    }
    return allDeltas;
// CHECKSTYLE:CHECK-ON NestedTryDepth
}
Also used : IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) XtextResource(org.eclipse.xtext.resource.XtextResource) URI(org.eclipse.emf.common.util.URI) Manager(org.eclipse.xtext.resource.IResourceDescription.Manager) IResourceLoader(org.eclipse.xtext.builder.resourceloader.IResourceLoader) TimeoutException(java.util.concurrent.TimeoutException) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta) SubMonitor(org.eclipse.core.runtime.SubMonitor) Resource(org.eclipse.emf.ecore.resource.Resource) StorageAwareResource(org.eclipse.xtext.resource.persistence.StorageAwareResource) XtextResource(org.eclipse.xtext.resource.XtextResource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) IProject(org.eclipse.core.resources.IProject) TimeoutException(java.util.concurrent.TimeoutException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) WrappedException(org.eclipse.emf.common.util.WrappedException) LoadOperationException(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException) LoadOperationException(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException) Delta(org.eclipse.xtext.resource.IResourceDescription.Delta) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta) CancelIndicator(org.eclipse.xtext.util.CancelIndicator)

Example 4 with LoadOperationException

use of org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException in project dsl-devkit by dsldevkit.

the class MonitoredClusteringBuilderState method writeResources.

/**
 * Writes a list of resources into the index given their {@link URI}s.
 *
 * @param toWrite
 *          The {@link URI} of the resources to write
 * @param buildData
 *          The underlying data for the write operation.
 * @param oldState
 *          The old index
 * @param newState
 *          The new index
 * @param monitor
 *          The progress monitor used for user feedback
 * @return a List with the list of loaded resources {@link URI} in the first position and a list of {@link URI}s of resources that could not be loaded in the
 *         second position.
 */
@SuppressWarnings("unchecked")
private List<List<URI>> writeResources(final Collection<URI> toWrite, final BuildData buildData, final IResourceDescriptions oldState, final CurrentDescriptions newState, final IProgressMonitor monitor) {
    ResourceSet resourceSet = buildData.getResourceSet();
    IProject currentProject = getBuiltProject(buildData);
    List<URI> toBuild = Lists.newLinkedList();
    List<URI> toRetry = Lists.newLinkedList();
    IResourceLoader.LoadOperation loadOperation = null;
    try {
        int resourcesToWriteSize = toWrite.size();
        int index = 1;
        loadOperation = globalIndexResourceLoader.create(resourceSet, currentProject);
        loadOperation.load(toWrite);
        // large resources and "scarce" memory (say, about 500MB).
        while (loadOperation.hasNext()) {
            if (monitor.isCanceled()) {
                loadOperation.cancel();
                throw new OperationCanceledException();
            }
            URI uri = null;
            Resource resource = null;
            try {
                resource = addResource(loadOperation.next().getResource(), resourceSet);
                uri = resource.getURI();
                final Object[] bindings = { Integer.valueOf(index), Integer.valueOf(resourcesToWriteSize), uri.fileExtension(), URI.decode(uri.lastSegment()) };
                monitor.subTask(NLS.bind(Messages.MonitoredClusteringBuilderState_WRITE_ONE_DESCRIPTION, bindings));
                traceSet.started(ResourceIndexingEvent.class, uri);
                final IResourceDescription.Manager manager = getResourceDescriptionManager(uri);
                if (manager != null) {
                    final IResourceDescription description = manager.getResourceDescription(resource);
                    // We don't care here about links, we really just want the exported objects so that we can link in the next phase.
                    // Set flag to make unresolvable cross-references raise an error
                    resourceSet.getLoadOptions().put(ILazyLinkingResource2.MARK_UNRESOLVABLE_XREFS, Boolean.FALSE);
                    final IResourceDescription copiedDescription = new FixedCopiedResourceDescription(description);
                    final boolean hasUnresolvedLinks = resourceSet.getLoadOptions().get(ILazyLinkingResource2.MARK_UNRESOLVABLE_XREFS) == Boolean.TRUE;
                    if (hasUnresolvedLinks) {
                        toRetry.add(uri);
                        resourceSet.getResources().remove(resource);
                    } else {
                        final Delta intermediateDelta = manager.createDelta(oldState.getResourceDescription(uri), copiedDescription);
                        newState.register(intermediateDelta);
                        toBuild.add(uri);
                    }
                }
            } catch (final WrappedException ex) {
                pollForCancellation(monitor);
                if (uri == null && ex instanceof LoadOperationException) {
                    // NOPMD
                    uri = ((LoadOperationException) ex).getUri();
                }
                LOGGER.error(NLS.bind(Messages.MonitoredClusteringBuilderState_CANNOT_LOAD_RESOURCE, uri), ex);
                if (resource != null) {
                    resourceSet.getResources().remove(resource);
                }
                if (uri != null) {
                    final IResourceDescription oldDescription = oldState.getResourceDescription(uri);
                    if (oldDescription != null) {
                        newState.register(new DefaultResourceDescriptionDelta(oldDescription, null));
                    }
                }
            // CHECKSTYLE:CHECK-OFF IllegalCatch
            // If we couldn't load it, there's no use trying again: do not add it to the queue
            } catch (final Throwable e) {
                // unfortunately the parser sometimes crashes (yet unreported Xtext bug)
                // CHECKSTYLE:CHECK-ON IllegalCatch
                pollForCancellation(monitor);
                LOGGER.error(NLS.bind(Messages.MonitoredClusteringBuilderState_CANNOT_LOAD_RESOURCE, uri), e);
                if (resource != null) {
                    resourceSet.getResources().remove(resource);
                }
            } finally {
                // Clear caches of resource
                if (resource instanceof XtextResource) {
                    ((XtextResource) resource).getCache().clear(resource);
                }
                traceSet.ended(ResourceIndexingEvent.class);
                monitor.worked(1);
            }
            if (!loadingStrategy.mayProcessAnotherResource(resourceSet, resourceSet.getResources().size())) {
                clearResourceSet(resourceSet);
            }
            index++;
        }
    } finally {
        if (loadOperation != null) {
            loadOperation.cancel();
        }
    }
    return Lists.newArrayList(toBuild, toRetry);
}
Also used : WrappedException(org.eclipse.emf.common.util.WrappedException) IResourceDescription(org.eclipse.xtext.resource.IResourceDescription) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) Resource(org.eclipse.emf.ecore.resource.Resource) StorageAwareResource(org.eclipse.xtext.resource.persistence.StorageAwareResource) XtextResource(org.eclipse.xtext.resource.XtextResource) XtextResource(org.eclipse.xtext.resource.XtextResource) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) URI(org.eclipse.emf.common.util.URI) IProject(org.eclipse.core.resources.IProject) LoadOperationException(org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException) Delta(org.eclipse.xtext.resource.IResourceDescription.Delta) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta) Manager(org.eclipse.xtext.resource.IResourceDescription.Manager) IResourceLoader(org.eclipse.xtext.builder.resourceloader.IResourceLoader) DefaultResourceDescriptionDelta(org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta)

Aggregations

IProject (org.eclipse.core.resources.IProject)4 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)4 URI (org.eclipse.emf.common.util.URI)4 Resource (org.eclipse.emf.ecore.resource.Resource)4 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)4 LoadOperationException (org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperationException)4 IResourceDescription (org.eclipse.xtext.resource.IResourceDescription)4 DefaultResourceDescriptionDelta (org.eclipse.xtext.resource.impl.DefaultResourceDescriptionDelta)4 StorageAwareResource (org.eclipse.xtext.resource.persistence.StorageAwareResource)4 SubMonitor (org.eclipse.core.runtime.SubMonitor)3 WrappedException (org.eclipse.emf.common.util.WrappedException)3 Delta (org.eclipse.xtext.resource.IResourceDescription.Delta)3 IResourceLoader (org.eclipse.xtext.builder.resourceloader.IResourceLoader)2 LoadOperation (org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadOperation)2 LoadResult (org.eclipse.xtext.builder.resourceloader.IResourceLoader.LoadResult)2 Manager (org.eclipse.xtext.resource.IResourceDescription.Manager)2 XtextResource (org.eclipse.xtext.resource.XtextResource)2 CancelIndicator (org.eclipse.xtext.util.CancelIndicator)2 TimeoutException (java.util.concurrent.TimeoutException)1 CoreException (org.eclipse.core.runtime.CoreException)1