Java Code Examples for org.eclipse.xtext.resource.IResourceServiceProvider#get()

The following examples show how to use org.eclipse.xtext.resource.IResourceServiceProvider#get() . 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: ResourceServiceProviderLocator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds the {@link IResourceServiceProvider} for a language by given its id.
 *
 * @param languageId
 *          the language id (grammar name)
 * @return the {@link IResourceServiceProvider} for the given language id
 */
public IResourceServiceProvider getResourceServiceProviderById(final String languageId) {
  ImmutableMap<Map<String, Object>, ? extends Function<String, IResourceServiceProvider>> resourceProvidersMap = getProviderMaps();
  for (Map.Entry<Map<String, Object>, ? extends Function<String, IResourceServiceProvider>> mapEntry : resourceProvidersMap.entrySet()) {
    Map<String, Object> map = mapEntry.getKey();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
      try {
        IResourceServiceProvider resourceServiceProvider = mapEntry.getValue().apply(entry.getKey());
        if (resourceServiceProvider == null) {
          continue;
        }
        IGrammarAccess grammarAccess = resourceServiceProvider.get(IGrammarAccess.class);
        if (grammarAccess != null && grammarAccess.getGrammar().getName().equals(languageId)) {
          return resourceServiceProvider;
        }
        // CHECKSTYLE:OFF
      } catch (ConfigurationException ex) {
        // CHECKSTYLE:ON
        // ignore
      }
    }
  }
  return null;
}
 
Example 2
Source File: CheckCfgUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets the all languages available in the workbench.
 *
 * @return set of all languages
 */
public Set<String> getAllLanguages() {
  Set<String> languages = new HashSet<String>();
  for (String extension : Registry.INSTANCE.getExtensionToFactoryMap().keySet()) {
    final URI dummyUri = URI.createURI("foo:/foo." + extension);
    IResourceServiceProvider resourceServiceProvider = Registry.INSTANCE.getResourceServiceProvider(dummyUri);
    // By checking that description manager is AbstractCachingResourceDescriptionManager we exclude technical languages of the framework
    if (resourceServiceProvider != null && resourceServiceProvider.getResourceDescriptionManager() instanceof AbstractCachingResourceDescriptionManager) {
      try {
        IGrammarAccess grammarAccess = resourceServiceProvider.get(IGrammarAccess.class);
        if (grammarAccess != null && grammarAccess.getGrammar() != null) {
          languages.add(grammarAccess.getGrammar().getName());
        }
      } catch (ConfigurationException e) {
        // Will happen if no binding for IGrammarAccess was present.
      }
    }
  }
  return languages;
}
 
Example 3
Source File: DebugSourceInstallingCompilationParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected OutputConfiguration findOutputConfiguration(SourceRelativeURI dslSourceFile, IFile generatedJavaFile) {
	IResourceServiceProvider serviceProvider = serviceProviderRegistry.getResourceServiceProvider(dslSourceFile.getURI());
	if (serviceProvider == null)
		return null;
	EclipseOutputConfigurationProvider cfgProvider = serviceProvider.get(EclipseOutputConfigurationProvider.class);
	IProject project = generatedJavaFile.getProject();
	Set<OutputConfiguration> configurations = cfgProvider.getOutputConfigurations(project);
	if (!configurations.isEmpty()) {
		if (configurations.size() == 1)
			return configurations.iterator().next();
		for (OutputConfiguration out : configurations) {
			for (String source : out.getSourceFolders()) {
				IContainer container = ResourceUtil.getContainer(project, out.getOutputDirectory(source));
				if (container != null && container.getFullPath().isPrefixOf(generatedJavaFile.getFullPath()))
					return out;
			}
		}
	}
	log.error("Could not find output configuration for file " + generatedJavaFile.getFullPath());
	return null;
}
 
Example 4
Source File: XStatefulIncrementalBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isResourceInOutputDirectory(Resource resource, IResourceServiceProvider serviceProvider) {
	XWorkspaceManager workspaceManager = serviceProvider.get(XWorkspaceManager.class);
	if (workspaceManager == null) {
		return false;
	}
	OutputConfigurationProvider outputConfProvider = serviceProvider.get(OutputConfigurationProvider.class);
	URI resourceUri = resource.getURI();
	IProjectConfig projectConfig = workspaceManager.getProjectConfig(resourceUri);
	Set<OutputConfiguration> outputConfigurations = outputConfProvider.getOutputConfigurations(resource);
	URI projectBaseUri = projectConfig.getPath();
	Path resourcePath = URIUtils.toPath(resourceUri);

	for (OutputConfiguration outputConf : outputConfigurations) {
		for (String outputDir : outputConf.getOutputDirectories()) {
			URI outputUri = projectBaseUri.appendSegment(outputDir);
			Path outputPath = URIUtils.toPath(outputUri);
			if (resourcePath.startsWith(outputPath)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 5
Source File: XbaseBreakpointDetailPaneFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IDetailPane createDetailPane(String paneID) {
	if (XBASE_DETAIL_PANE.equals(paneID)) {
		return new LineBreakpointDetailPane() {
			@Override
			public void display(IStructuredSelection selection) {
				super.display(selection);
				AbstractJavaBreakpointEditor editor = getEditor();
				Object input = null;
				if (selection != null && selection.size() == 1) {
					input = selection.getFirstElement();
				}
				try {
					if (input instanceof IJavaStratumLineBreakpoint) {
						IJavaStratumLineBreakpoint stratumBreakpoint = (IJavaStratumLineBreakpoint) input;
						URI uri = URI.createURI((String) stratumBreakpoint.getMarker().getAttribute(StratumBreakpointAdapterFactory.ORG_ECLIPSE_XTEXT_XBASE_SOURCE_URI));
						IResourceServiceProvider resourceServiceProvider = registry.getResourceServiceProvider(uri);
						if (resourceServiceProvider != null) {
							JavaBreakPointProvider javaBreakPointProvider = resourceServiceProvider.get(JavaBreakPointProvider.class);
							input = javaBreakPointProvider.getBreakpointWithJavaLocation(stratumBreakpoint);
						}
					}
					editor.setInput(input);
				} catch (CoreException e) {
					JDIDebugUIPlugin.log(e);
				}
			}
		};
	} else {
		return super.createDetailPane(paneID);
	}
}
 
Example 6
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.16
 */
protected IDocumentSymbolService getIDocumentSymbolService(IResourceServiceProvider serviceProvider) {
	if (serviceProvider == null) {
		return null;
	}
	if (isHierarchicalDocumentSymbolSupport()) {
		return serviceProvider.get(HierarchicalDocumentSymbolService.class);
	} else {
		return serviceProvider.get(DocumentSymbolService.class);
	}
}
 
Example 7
Source File: AbstractCopyQualifiedNameHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected ICopyQualifiedNameService getCopyQualifiedNameService(EObject selectedElement) {
	if (selectedElement == null) {
		return null;
	}
	IResourceServiceProvider resourceServiceProvider = registry.getResourceServiceProvider(selectedElement.eResource().getURI());
	if (resourceServiceProvider == null) {
		return null;
	}
	return resourceServiceProvider.get(ICopyQualifiedNameService.class);
}
 
Example 8
Source File: CompilationTestHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void doGenerate() {
	if (access == null) {
		doValidation();
		access = fileSystemAccessProvider.get();
		
		access.setOutputConfigurations(outputConfigurations);
		for (Resource resource : sources) {
			if (resource instanceof XtextResource) {
				access.setProjectName(PROJECT_NAME);
				XtextResource xtextResource = (XtextResource) resource;
				IResourceServiceProvider resourceServiceProvider = xtextResource.getResourceServiceProvider();
				GeneratorDelegate generator = resourceServiceProvider.get(GeneratorDelegate.class);
				if (generator != null) {
					GeneratorContext context = new GeneratorContext();
					context.setCancelIndicator(CancelIndicator.NullImpl);
					generator.generate(xtextResource, access, context);
				}
			}
		}
		generatedCode = newHashMap();
		for (final GeneratedFile e : access.getGeneratedFiles()) {
			if (e.getJavaClassName() != null) {
				generatedCode.put(e.getJavaClassName(), e.getContents().toString());
			}
		}
	}
}
 
Example 9
Source File: ExecutableCommandRegistry.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void initialize(Iterable<? extends IResourceServiceProvider> allLanguages, ClientCapabilities capabilities,
		LanguageClient client) {
	this.client = client;
	this.registeredCommands = HashMultimap.create();
	boolean hasDynamicRegistration = false;
	WorkspaceClientCapabilities workspace = capabilities.getWorkspace();
	if (workspace != null) {
		ExecuteCommandCapabilities executeCommandCapabilities = workspace.getExecuteCommand();
		if (executeCommandCapabilities != null) {
			Boolean dynamicRegistration = executeCommandCapabilities.getDynamicRegistration();
			if (dynamicRegistration != null) {
				hasDynamicRegistration = dynamicRegistration.booleanValue();
			}
		}
	}
	for (IResourceServiceProvider lang : allLanguages) {
		IExecutableCommandService service = lang.get(IExecutableCommandService.class);
		if (service != null) {
			List<String> commands = service.initialize();
			for (String c : commands) {
				registeredCommands.put(c, service);
			}
			if (hasDynamicRegistration) {
				service.initializeDynamicRegistration((String command) -> {
					return register(command, service);
				});
			}
		}
	}
}
 
Example 10
Source File: DerivedResourceMarkerCopier.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private String determinateMarkerTypeByURI(SourceRelativeURI resourceURI) {
	IResourceServiceProvider serviceProvider = serviceProviderRegistry.getResourceServiceProvider(resourceURI.getURI());
	if (serviceProvider == null)
		return null;
	MarkerTypeProvider typeProvider = serviceProvider.get(MarkerTypeProvider.class);
	Issue.IssueImpl issue = new Issue.IssueImpl();
	issue.setType(CheckType.NORMAL);
	return typeProvider.getMarkerType(issue);
}
 
Example 11
Source File: TargetURICollector.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public void add(EObject object, TargetURIs targetURIs) {
	IResourceServiceProvider serviceProvider = serviceProviderRegistry.getResourceServiceProvider(EcoreUtil.getURI(object));
	if (serviceProvider != null) {
		TargetURICollector languageSpecific = serviceProvider.get(TargetURICollector.class);
		if (languageSpecific != null) {
			languageSpecific.doAdd(object, targetURIs);
			return;
		}
	}
	doAdd(object, targetURIs);
}
 
Example 12
Source File: RegistryBuilderParticipant.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * For each {@link IResourceDescription.Delta} searches and calls the responsible {@link ILanguageSpecificBuilderParticipant}s.
 *
 * @param buildContext
 *          the {@link IBuildContext}, must not be {@code null}
 * @param monitor
 *          the {@link IProgressMonitor}, must not be {@code null}
 */
protected void buildLanguageSpecificParticipants(final IBuildContext buildContext, final IProgressMonitor monitor) {
  initParticipants();
  SubMonitor progress = SubMonitor.convert(monitor, buildContext.getDeltas().size() * MONITOR_PARTICIPANTS_PER_LANGUAGE);
  Map<String, BuildContext> languageIdToBuildContext = Maps.newHashMap();
  for (IResourceDescription.Delta delta : buildContext.getDeltas()) {
    IResourceServiceProvider resourceServiceProvider = IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(delta.getUri());
    if (resourceServiceProvider == null) {
      progress.worked(MONITOR_PARTICIPANTS_PER_LANGUAGE);
      continue;
    }
    IGrammarAccess grammarAccess = null;
    try {
      grammarAccess = resourceServiceProvider.get(IGrammarAccess.class);
    } catch (ConfigurationException e) {
      progress.worked(MONITOR_PARTICIPANTS_PER_LANGUAGE);
      continue;
    }
    if (grammarAccess == null) {
      progress.worked(MONITOR_PARTICIPANTS_PER_LANGUAGE);
      continue;
    }
    String languageId = grammarAccess.getGrammar().getName();
    BuildContext entryBuildContext = languageIdToBuildContext.get(languageId);
    if (entryBuildContext == null) {
      entryBuildContext = new BuildContext(buildContext.getBuiltProject(), buildContext.getResourceSet(), buildContext.getBuildType());
      languageIdToBuildContext.put(languageId, entryBuildContext);
    }
    entryBuildContext.addDelta(delta);
  }
  builLanguageSpecificContext(buildContext, progress, languageIdToBuildContext);
}
 
Example 13
Source File: JavaSearchHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public void search(URI uri, IProgressMonitor monitor) {
	int numResources = Iterables.size(resourceDescriptions.getAllResourceDescriptions());
	SubMonitor subMonitor = SubMonitor.convert(monitor, numResources / 10);
	subMonitor.subTask("Find references in EMF resources");
	try {
		int i = 0;
		for (IResourceDescription resourceDescription : resourceDescriptions.getAllResourceDescriptions()) {
			URI resourceURI = resourceDescription.getURI();
			IResourceServiceProvider resourceServiceProvider = serviceProviderRegistry.getResourceServiceProvider(resourceURI);
			if(resourceServiceProvider != null) {
				IJavaSearchParticipation javaSearchParticipation = resourceServiceProvider
						.get(IJavaSearchParticipation.class);
				if(javaSearchParticipation == null || javaSearchParticipation.canContainJvmReferences(resourceURI))
					searchIn(uri, resourceDescription);
			}
			if (++i % 10 == 0) {
				if (subMonitor.isCanceled()) {
					return; // not throwing OperationCanceledException, as the client in JDT doesn't seem to handle it properly
				}
				subMonitor.worked(1);
			}
		}
		for(ResourceSet resourceSet: projectToResourceSet.values()) {
			resourceSet.getResources().clear();
			resourceSet.eAdapters().clear();
		}
	} finally {
		subMonitor.done();
	}
}
 
Example 14
Source File: MarkerUpdaterImpl.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected IMarkerContributor getMarkerContributor(URI uri) {
	IResourceServiceProvider provider = resourceServiceProviderRegistry.getResourceServiceProvider(uri);
	if (provider != null) {
		return provider.get(IMarkerContributor.class);
	}
	return null;
}
 
Example 15
Source File: AbstractLabelProvider.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Get the label from the given eObject's {@link IResourceServiceProvider}.
 *
 * @param eObject
 *          the target object
 * @return the label for the given eObject
 */
private String getForeignObjectLabel(final EObject eObject) {
  IResourceServiceProvider serviceProvider = ((XtextResource) eObject.eResource()).getResourceServiceProvider();
  ILabelProvider labelProvider = serviceProvider.get(ILabelProvider.class);
  if (labelProvider != null) {
    return labelProvider.getText(eObject);
  }
  return null;
}
 
Example 16
Source File: XStatefulIncrementalBuilder.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/** Generate code for the given resource */
protected void generate(Resource resource, XSource2GeneratedMapping newMappings,
		IResourceServiceProvider serviceProvider) {
	GeneratorDelegate generator = serviceProvider.get(GeneratorDelegate.class);
	if (generator == null) {
		return;
	}

	if (isResourceInOutputDirectory(resource, serviceProvider)) {
		return;
	}

	URI source = resource.getURI();
	Set<URI> previous = newMappings.deleteSource(source);
	URIBasedFileSystemAccess fileSystemAccess = this.createFileSystemAccess(serviceProvider, resource);
	fileSystemAccess.setBeforeWrite((uri, outputCfgName, contents) -> {
		newMappings.addSource2Generated(source, uri, outputCfgName);
		previous.remove(uri);
		request.setResultGeneratedFile(source, uri);
		return contents;
	});
	fileSystemAccess.setBeforeDelete((uri) -> {
		newMappings.deleteGenerated(uri);
		request.setResultDeleteFile(uri);
		return true;
	});
	fileSystemAccess.setContext(resource);
	if (request.isWriteStorageResources() && resource instanceof StorageAwareResource) {
		IResourceStorageFacade resourceStorageFacade = ((StorageAwareResource) resource)
				.getResourceStorageFacade();
		if (resourceStorageFacade != null) {
			resourceStorageFacade.saveResource((StorageAwareResource) resource, fileSystemAccess);
		}
	}
	if (request.canGenerate()) {
		GeneratorContext generatorContext = new GeneratorContext();
		generatorContext.setCancelIndicator(request.getCancelIndicator());
		generator.generate(resource, fileSystemAccess, generatorContext);
		XtextResourceSet resourceSet = request.getResourceSet();
		for (URI noLongerCreated : previous) {
			try {
				resourceSet.getURIConverter().delete(noLongerCreated, CollectionLiterals.emptyMap());
				request.setResultDeleteFile(noLongerCreated);
			} catch (IOException e) {
				Exceptions.sneakyThrow(e);
			}
		}
	}
}
 
Example 17
Source File: MarkerUpdaterImpl.java    From xtext-eclipse with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Searches for a {@link IResourceUIValidatorExtension} implementation in
 * {@link org.eclipse.xtext.resource.IResourceServiceProvider.Registry}<br>
 * 
 * @return {@link IResourceUIValidatorExtension} for the given {@link URI} or <code>null</code> if not found.
 * @see org.eclipse.xtext.resource.IResourceServiceProvider.Registry#getResourceServiceProvider(URI)
 * @see IResourceServiceProvider#get(Class)
 */
protected IResourceUIValidatorExtension getResourceUIValidatorExtension(URI uri) {
	IResourceServiceProvider provider = resourceServiceProviderRegistry.getResourceServiceProvider(uri);
	if (provider != null) {
		return provider.get(IResourceUIValidatorExtension.class);
	}
	return null;
}
 
Example 18
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * @param <Service>
 *            the type of the service
 * @param resourceServiceProvider
 *            the resource service provider. May be null
 * @param type
 *            the type of the service
 * @return the service instance or null if not available.
 */
protected <Service> Service getService(IResourceServiceProvider resourceServiceProvider, Class<Service> type) {
	if (resourceServiceProvider == null) {
		return null;
	}
	return resourceServiceProvider.get(type);
}
 
Example 19
Source File: InjectorUtil.java    From dsl-devkit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * A file extension specific way to obtain an implementation for a certain type.
 *
 * @param <T>
 *          the type for which to get the implementation instance for, or a subtype of that
 * @param fileExtension
 *          the file extension of the {@link IResourceServiceProvider} to use, must not be {@code null}
 * @param clazz
 *          the type clazz, must not be {@code null}
 * @return implementation, or {@code null} if no implementation of the given type can be provided
 */
public static <T> T getByExtension(final String fileExtension, final Class<? extends T> clazz) {
  final IResourceServiceProvider resourceServiceProvider = new ResourceServiceProviderLocator().getResourceServiceProviderByExtension(fileExtension);
  if (resourceServiceProvider != null) {
    return resourceServiceProvider.get(clazz);
  }
  return null;
}
 
Example 20
Source File: AbstractCheckExtensionHelper.java    From dsl-devkit with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Gets an instance from the service provider with a given URI.
 *
 * @param <T>
 *          the generic type
 * @param type
 *          the instance type
 * @param uri
 *          the URI of the source object
 * @return the instance
 */
protected <T> T getFromServiceProvider(final Class<T> type, final URI uri) {
  IResourceServiceProvider serviceProvider = IResourceServiceProvider.Registry.INSTANCE.getResourceServiceProvider(uri);
  return serviceProvider.get(type);
}