Java Code Examples for org.eclipse.core.runtime.Platform#isRunning()

The following examples show how to use org.eclipse.core.runtime.Platform#isRunning() . 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: LogUtils.java    From eclipsegraphviz with Eclipse Public License 1.0 6 votes vote down vote up
public static void log(Supplier<IStatus> statusSupplier) {
    IStatus status = statusSupplier.get();
    if (!Platform.isRunning()) {
        System.err.println(status.getMessage());
        if (status.getException() != null)
            status.getException().printStackTrace();
        if (status.isMultiStatus())
            for (IStatus child : status.getChildren())
                log(child);
        return;
    }
    Bundle bundle = Platform.getBundle(status.getPlugin());
    if (bundle == null) {
        String thisPluginId = LogUtils.class.getPackage().getName();
        bundle = Platform.getBundle(thisPluginId);
        Platform.getLog(bundle).log(
                new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin()
                        + " for logging as"));
    }
    Platform.getLog(bundle).log(status);
}
 
Example 2
Source File: LibraryManager.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private IStatus runWithWorkspaceLock(Supplier<IStatus> operation) {
	if (Platform.isRunning()) {
		ISchedulingRule rule = ResourcesPlugin.getWorkspace().getRoot();
		try {
			Job.getJobManager().beginRule(rule, null);
			return operation.get();
		} catch (final OperationCanceledException e) {
			LOGGER.info("User cancelled operation.");
			return statusHelper.createCancel("User cancelled operation.");
		} finally {
			Job.getJobManager().endRule(rule);
		}
	} else {
		// locking not available/required in headless case
		return operation.get();
	}
}
 
Example 3
Source File: MDDUtil.java    From textuml with Eclipse Public License 1.0 6 votes vote down vote up
private static String getMetamodelVersion() {
   	if (cachedVersion != null)
   		return cachedVersion;
   	if (Platform.isRunning()) {
   		Version version = FrameworkUtil.getBundle(MDDUtil.class).getVersion();
		return cachedVersion = extractMetamodelVersion(version).toString();
   	}
   	InputStream manifestStream = MDDUtil.class.getResourceAsStream("/META-INF/MANIFEST.MF");
   	try {		
   		Manifest manifest = new Manifest(manifestStream); 
   		String readVersion = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
		return cachedVersion = extractMetamodelVersion(Version.parseVersion(StringUtils.defaultIfBlank(readVersion, "0.1"))).toString();
   	} catch (IOException e) {
   		// ignore
   		cachedVersion = "";
	} finally {
   		IOUtils.closeQuietly(manifestStream);
   	}
   	return cachedVersion; 
}
 
Example 4
Source File: URINormalizationTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testGetElementByClasspathURIEObject() throws Exception {
	with(ImportUriTestLanguageStandaloneSetup.class);
	Main main = (Main) getModel("import 'classpath:/org/eclipse/xtext/linking/05.importuritestlanguage'\n"
			+ "type Bar extends Foo");
	Type bar = main.getTypes().get(0);
	Type foo = bar.getExtends();
	assertNotNull(foo);
	assertFalse(foo.eIsProxy());
	// we don't put contextual classpath:/ uris into the index thus
	// they are partially normalized
	if (Platform.isRunning()) {
		assertEquals("bundleresource", EcoreUtil.getURI(foo).scheme());
	} else {
		assertEquals("file", EcoreUtil.getURI(foo).scheme());
	}
	IScopeProvider scopeProvider = get(IScopeProvider.class);
	IScope scope = scopeProvider.getScope(bar, ImportedURIPackage.Literals.TYPE__EXTENDS);
	Iterable<IEObjectDescription> elements = scope.getElements(foo);
	assertEquals(1, size(elements));
	assertEquals(EcoreUtil2.getPlatformResourceOrNormalizedURI(foo), elements.iterator().next().getEObjectURI());
}
 
Example 5
Source File: ScopeJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Verifies that all referenced extensions can be found.
 *
 * @param model
 *          scope model to check
 */
@Check
public void checkExtensions(final ScopeModel model) {
  ResourceManager resourceManager = null;
  if (Platform.isRunning()) {
    // FIXME: xpand
    // IXtendXpandProject project = Activator.getExtXptModelManager().findProject(ResourcesPlugin.getWorkspace().getRoot().getFile(new
    // Path(model.eResource().getURI().toPlatformString(true))).getProject());
    // if (project != null) {
    // resourceManager = new XpandPluginExecutionContext(project).getResourceManager();
    // }
  } else {
    resourceManager = new ResourceManagerDefaultImpl();
  }
  if (resourceManager == null) {
    return;
  }
  for (Extension ext : model.getExtensions()) {
    final Resource res = resourceManager.loadResource(ext.getExtension(), XtendFile.FILE_EXTENSION);
    if (res == null) {
      error(NLS.bind(Messages.extensionNotFound, ext.getExtension()), ext, ScopePackage.Literals.EXTENSION__EXTENSION, null);
    }
  }
}
 
Example 6
Source File: ExportJavaValidator.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Verifies that all referenced extensions can be found.
 *
 * @param model
 *          export model to check
 */
@Check
public void checkExtensions(final ExportModel model) {
  ResourceManager resourceManager = null;
  if (Platform.isRunning()) {
    // FIXME: sort out xpand
    // IXtendXpandProject project = Activator.getExtXptModelManager().findProject(ResourcesPlugin.getWorkspace().getRoot().getFile(new
    // Path(model.eResource().getURI().toPlatformString(true))).getProject());
    // if (project != null) {
    // resourceManager = new XpandPluginExecutionContext(project).getResourceManager();
    // }
  } else {
    resourceManager = new ResourceManagerDefaultImpl();
  }
  if (resourceManager == null) {
    return;
  }
  for (Extension ext : model.getExtensions()) {
    final Resource res = resourceManager.loadResource(ext.getExtension(), XtendFile.FILE_EXTENSION);
    if (res == null) {
      error(NLS.bind("Extension ''{0}'' not found", ext.getExtension()), ext, ExportPackage.Literals.EXTENSION__EXTENSION, null);
    }
  }
}
 
Example 7
Source File: XpectN4JSES5TranspilerHelper.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Load Xpect configuration
 */
private void loadXpectConfiguration(
		org.eclipse.xpect.setup.ISetupInitializer<Object> init, FileSetupContext fileSetupContext) {
	if (Platform.isRunning()) {
		readOutConfiguration = new ReadOutWorkspaceConfiguration(fileSetupContext, core, fileExtensionProvider);
	} else {
		readOutConfiguration = new ReadOutResourceSetConfiguration(fileSetupContext, core);
	}
	init.initialize(readOutConfiguration);
}
 
Example 8
Source File: MarshallerServiceClassRegistry.java    From dawnsci with Eclipse Public License 1.0 5 votes vote down vote up
public MarshallerServiceClassRegistry(List<IClassRegistry> extraRegistries) throws ClassRegistryDuplicateIdException, CoreException {
	List<IClassRegistry> registries = new ArrayList<IClassRegistry>();
	platformIsRunning = Platform.isRunning();

	if (extraRegistries!=null) registries.addAll(extraRegistries);

	// Extensions not available for unit tests / non-OSGI mode.
	registries.addAll(getAvailableRegistryExtensions());

	for (IClassRegistry registry : registries) {
		populateClassMap(registry);
	}
}
 
Example 9
Source File: MarshallerService.java    From dawnsci with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor for testing to allow IMarshaller(s) or IClassRegistry('s) to be injected.
 *
 * @param extra_registries
 * @param marshallers
 */
public MarshallerService(List<IClassRegistry> extra_registries, List<IMarshaller> marshallers) {
	platformIsRunning = Platform.isRunning();

	if (marshallers!=null) this.marshallers = Collections.unmodifiableList(marshallers);

	this.extra_registries = new ArrayList<IClassRegistry>();
	this.extra_registries.add(new ROIClassRegistry());
	this.extra_registries.add(new ArrayRegistry());
	if (extra_registries!=null) this.extra_registries.addAll(extra_registries);

	this.extra_registries = Collections.unmodifiableList(this.extra_registries);
}
 
Example 10
Source File: ExternalFoldersManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ExternalFoldersManager() {
	// Prevent instantiation
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=377806
	if (Platform.isRunning()) {
		getFolders();
	}
}
 
Example 11
Source File: BundleManager.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Load the bundle in the specified directory
 * 
 * @param bundleDirectory
 *            The directory containing a bundle and its children
 * @param wait
 *            Allows us to be synchronous when executing this
 */
public void loadBundle(File bundleDirectory, boolean wait)
{
	BundleLoadJob job = new BundleLoadJob(bundleDirectory);

	// If we're running and not testing, schedule in parallel but limit how many run in parallel based on processor
	// count
	if (!EclipseUtil.isTesting() && Platform.isRunning())
	{
		job.setRule(new SerialPerObjectRule(counter++));

		if (counter >= maxBundlesToLoadInParallel())
		{
			counter = 0;
		}

		job.setPriority(Job.SHORT);
		job.schedule();
		if (wait)
		{
			try
			{
				job.join();
			}
			catch (InterruptedException e)
			{
				// ignore error
			}
		}
	}
	else
	{
		// We're already running inline, so don't need to ever "wait"
		job.run(new NullProgressMonitor());
	}
}
 
Example 12
Source File: EclipseConsoleLogger.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public void init() {
	if (Platform.isRunning()) {
		console = getConsole();
		info = console.newMessageStream();
		error = console.newMessageStream();
		error.setActivateOnWrite(true);
	}
}
 
Example 13
Source File: LibraryExtensions.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static List<ILibraryDescriptor> getLibraryDescriptors() {

		if (descriptors == null) {
			descriptors = Lists.newArrayList();
			if (Platform.isRunning()) {
				initFromExtensions();
			}
		}
		return descriptors;
	}
 
Example 14
Source File: GeneratorExtensions.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public static List<IGeneratorDescriptor> getGeneratorDescriptors() {
	if (descriptors == null) {
		descriptors = Lists.newArrayList();
		if (Platform.isRunning()) {
			initFromExtensions();
		}
	}
	return descriptors;
}
 
Example 15
Source File: EclipseLogAppender.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private synchronized void ensureInitialized() {
	if (!initialized) {
		if (!Platform.isRunning()) {
			LOGGER.warn("You appear to be running outside Eclipse; you might want to remove the jar org.eclipse.xtext.logging*.jar from your classpath and supply your own log4j.properties.");
		} else {
			log = Platform.getLog(Platform.getBundle(LOG4J_BUNDLE_NAME));
		}
		initialized = true;
	}
}
 
Example 16
Source File: ExternalProjectsCollector.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private Set<String> getAllEclipseWorkspaceProjectNames() {
	if (Platform.isRunning()) {
		return from(Arrays.asList(getWorkspace().getRoot().getProjects()))
				.filter(p -> p.isAccessible())
				.transform(p -> p.getName())
				.toSet();
	}
	return Collections.emptySet();
}
 
Example 17
Source File: EclipseLogAppender.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private synchronized void ensureInitialized() {
	if (!initialized) {
		if (!Platform.isRunning()) {
			LOGGER.warn(
					"You appear to be running outside Eclipse; you might want to remove the jar org.eclipse.xtext.logging*.jar from your classpath and supply your own log4j.properties.");
		} else {
			log = Platform.getLog(Platform.getBundle(LOG4J_BUNDLE_NAME));
		}
		initialized = true;
	}
}
 
Example 18
Source File: PackageJsonXpectInjectorSetup.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Creates
public Injector createInjector() {
	// if the Eclipse Platform Runtime is available, there is no need for a custom
	// injector setup
	if (Platform.isRunning()) {
		throw new IllegalStateException(
				"Detected use of the PackageJsonXpectInjectorSetup although the Eclipse Platform is running."
						+ " Do not use this injector setup for Plug-In UI Tests.");
	}

	// obtain JSON injector using the super method
	final Injector jsonInjector = super.createInjector();

	// obtain N4JS-specific package.json validator extensions
	final AbstractPackageJSONValidatorExtension packageJsonValidatorExtension = n4jsInjector.get()
			.getInstance(PackageJsonValidatorExtension.class);
	final AbstractPackageJSONValidatorExtension projectSetupValidatorExtension = n4jsInjector.get()
			.getInstance(N4JSProjectSetupJsonValidatorExtension.class);

	// obtain JSON validation extension registry
	final JSONExtensionRegistry extensionRegistry = jsonInjector.getInstance(JSONExtensionRegistry.class);

	// X!PECTs injector initialization causes an invalid state of the EValidator
	// registry in which the registered validators use a different injector than the
	// rest of the language infrastructure (see
	// https://github.com/eclipse/Xpect/issues/233). Therefore, at this point we
	// clear the validator registry and re-initialize it to restore a consistent
	// state.
	final Registry validatorRegistry = EValidator.Registry.INSTANCE;
	validatorRegistry.remove(JSONPackage.eINSTANCE);

	// register the correct instance of the generic JSON validator as sole validator
	// for the JSON package
	final JSONValidator jsonValidator = jsonInjector.getInstance(JSONValidator.class);
	jsonValidator.register(jsonInjector.getInstance(EValidatorRegistrar.class));

	// finally, manually register the N4JS package.json validation extensions
	extensionRegistry.register(packageJsonValidatorExtension);
	extensionRegistry.register(projectSetupValidatorExtension);

	// TODO re-think this approach In order for the FileBasedWorkspace to correctly
	// detect the test data as valid N4JS projects, (cf.
	// FileBasedWorkspace#tryFindProjectRecursivelyByManifest) we must explicitly
	// register the JSONFactory as resource factory for '*.xt' as otherwise, EMF
	// will fall-back to its XMI parser for 'package.json.xt' resources.
	Map<String, Object> factoryMap = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap();

	Object jsonFactory = factoryMap.get("json");
	factoryMap.put("xt", jsonFactory);

	return jsonInjector;
}
 
Example 19
Source File: ValidPreferenceStore.java    From dsl-devkit with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Return the string value for the specified key. Look in the nodes which
 * are specified by this object's list of search scopes. If the value does
 * not exist then return <code>null</code>.
 *
 * @param key
 *          the key to search with
 * @return String or <code>null</code> if the value does not exist or executing in non-Eclipse environment.
 */
private String internalGet(final String key) {
  // TODO SUPPORT PREFERENCES IN STANDALONE BUILD ?
  return Platform.isRunning() ? Platform.getPreferencesService().get(key, null, getPreferenceNodes(true)) : null; // NOPMD:NullAssignment
}