org.eclipse.core.runtime.Plugin Java Examples

The following examples show how to use org.eclipse.core.runtime.Plugin. 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: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Are we currently outputting items of this severity and this scope? Use this method if you want to check before
 * actually composing an error message.
 * 
 * @return
 */
public static boolean isOutputEnabled(Plugin plugin, StatusLevel severity, String scope)
{
	if (!isSeverityEnabled(severity))
	{
		return false;
	}
	try
	{
		if (!Platform.inDebugMode())
		{
			return true;
		}
	}
	catch (Exception e)
	{
		// ignore. May happen if we're running unit tests outside IDE
	}

	return isScopeEnabled(scope);
}
 
Example #2
Source File: ScopedPreferenceStore.java    From e4Preferences with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Dispose the receiver.
 */
private void disposePreferenceStoreListener() {

	IEclipsePreferences root = (IEclipsePreferences) Platform
			.getPreferencesService().getRootNode().node(
					Plugin.PLUGIN_PREFERENCE_SCOPE);
	try {
		if (!(root.nodeExists(nodeQualifier))) {
			return;
		}
	} catch (BackingStoreException e) {
		return;// No need to report here as the node won't have the
		// listener
	}

	IEclipsePreferences preferences = getStorePreferences();
	if (preferences == null) {
		return;
	}
	if (preferencesListener != null) {
		preferences.removePreferenceChangeListener(preferencesListener);
		preferencesListener = null;
	}
}
 
Example #3
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructs the message to log
 * 
 * @param plugin
 * @param severity
 * @param message
 * @param scope
 * @param th
 * @return
 */
public static String buildMessage(Plugin plugin, int severity, String message, String scope, Throwable th)
{
	if (scope == null)
	{
		scope = StringUtil.EMPTY;
	}

	String version;
	if (EclipseUtil.isStandalone())
	{
		version = EclipseUtil.getProductVersion();
	}
	else
	{
		version = EclipseUtil.getStudioVersion();
	}
	return MessageFormat.format("(Build {0}) {1} {2} {3}", //$NON-NLS-1$
			version, getLabel(severity), scope, message);
}
 
Example #4
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Flushes any cached logging messages
 */
public static void flushCache()
{
	caching = false;

	for (Map.Entry<Plugin, List<IStatus>> entry : earlyMessageCache.entrySet())
	{
		for (IStatus status : entry.getValue())
		{
			StatusLevel severity = getStatusLevel(status.getSeverity());
			if (status.getSeverity() == IStatus.ERROR || isOutputEnabled(entry.getKey(), severity, null))
			{
				log(entry.getKey(), status.getSeverity(), status.getMessage(), null, status.getException());
			}
		}
	}

	earlyMessageCache.clear();
}
 
Example #5
Source File: ActivatorTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static IPath getAbsoluteFilePath(String relativePath) {
    Plugin plugin = getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #6
Source File: TmfCoreTestPlugin.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static @NonNull IPath getAbsoluteFilePath(String relativePath) {
    Plugin plugin = TmfCoreTestPlugin.getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #7
Source File: ActivatorTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return a path to a file relative to this plugin's base directory
 *
 * @param relativePath
 *            The path relative to the plugin's root directory
 * @return The path corresponding to the relative path in parameter
 */
public static IPath getAbsoluteFilePath(String relativePath) {
    Plugin plugin = getDefault();
    if (plugin == null) {
        /*
         * Shouldn't happen but at least throw something to get the test to
         * fail early
         */
        throw new IllegalStateException();
    }
    URL location = FileLocator.find(plugin.getBundle(), new Path(relativePath), null);
    try {
        return new Path(FileLocator.toFileURL(location).getPath());
    } catch (IOException e) {
        throw new IllegalStateException();
    }
}
 
Example #8
Source File: FixedScopedPreferenceStore.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Dispose the preference store listener.
 */
private void disposePreferenceStoreListener() {

	IEclipsePreferences root = (IEclipsePreferences) Platform
			.getPreferencesService().getRootNode().node(
					Plugin.PLUGIN_PREFERENCE_SCOPE);
	try {
		if (!(root.nodeExists(nodeQualifier))) {
			return;
		}
	} catch (BackingStoreException e) {
		return;// No need to report here as the node won't have the
		// listener
	}

	IEclipsePreferences preferences = getStorePreferences();
	if (preferences == null) {
		return;
	}
	if (preferencesListener != null) {
		preferences.removePreferenceChangeListener(preferencesListener);
		preferencesListener = null;
	}
}
 
Example #9
Source File: BundleClasspathUriResolver.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public URI resolve(Object context, URI classpathUri) {
       if (context instanceof Plugin) {
           context = ((Plugin) context).getBundle();
       }
       if (!(context instanceof Bundle)) {
           throw new IllegalArgumentException("Context must implement Bundle");
       }
       Bundle bundle = (Bundle) context;
       try {
           if (ClasspathUriUtil.isClasspathUri(classpathUri)) {
               URI result = findResourceInBundle(bundle, classpathUri);
				if (classpathUri.fragment() != null)
					result = result.appendFragment(classpathUri.fragment());
				return result;
           }
       } catch (Exception exc) {
           throw new ClasspathUriResolutionException(exc);
       }
       return classpathUri;
   }
 
Example #10
Source File: EclipseUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the bundle version of a plugin.
 * 
 * @param plugin
 *            the plugin to retrieve from
 * @return the bundle version, or null if not found.
 */
public static String getPluginVersion(Plugin plugin)
{
	if (!isPluginLoaded(plugin))
	{
		return null;
	}
	return plugin.getBundle().getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION).toString(); // $codepro.audit.disable
																										// com.instantiations.assist.eclipse.analysis.unnecessaryToString
}
 
Example #11
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Logs an error
 * 
 * @param plugin
 * @param message
 * @param th
 */
public static void logError(Plugin plugin, String message, Throwable th, String scope)
{
	if (isErrorEnabled(plugin, scope))
	{
		log(plugin, IStatus.ERROR, message, scope, th);
	}
	else
	{
		logTrace(plugin, IStatus.ERROR, message, scope, th);
	}
}
 
Example #12
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Logs a warning
 * 
 * @param plugin
 * @param message
 * @param th
 */
public static void logWarning(Plugin plugin, String message, Throwable th, String scope)
{
	if (isWarningEnabled(plugin, scope))
	{
		log(plugin, IStatus.WARNING, message, scope, th);
	}
	else
	{
		logTrace(plugin, IStatus.INFO, message, scope, th);
	}
}
 
Example #13
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Logs an informational message
 * 
 * @param plugin
 * @param message
 * @param th
 */
public static void logInfo(Plugin plugin, String message, Throwable th, String scope)
{
	if (isInfoEnabled(plugin, scope))
	{
		log(plugin, IStatus.INFO, message, scope, th);
	}
	else
	{
		logTrace(plugin, IStatus.INFO, message, scope, th);
	}
}
 
Example #14
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Trace this message out anyway if we are in debug mode
 * 
 * @param plugin
 * @param message
 * @param scope
 * @param th
 */
private static void logTrace(Plugin plugin, int severity, String message, String scope, Throwable th)
{
	if (isScopeEnabled(IDebugScopes.LOGGER))
	{
		StatusLevel newSeverity = getStatusLevel(severity);
		boolean inSeverity = isSeverityEnabled(newSeverity);

		String cause = StringUtil.EMPTY;
		if (!inSeverity)
		{
			cause = "Not logging items of current severity."; //$NON-NLS-1$
		}
		else if (!isScopeEnabled(scope))
		{
			cause = "Scope not enabled."; //$NON-NLS-1$
		}

		String traceMessage = MessageFormat.format(
				"(Build {0}) Skipping log of {1} {2} {3}. Cause: {4}", EclipseUtil.getPluginVersion(plugin), //$NON-NLS-1$
				getLabel(severity), scope, message, cause);

		if (plugin != null)
		{
			Status logStatus = new Status(severity, plugin.getBundle().getSymbolicName(), IStatus.OK, traceMessage,
					th);
			plugin.getLog().log(logStatus);
		}
		else
		{
			System.err.println(traceMessage); // CHECKSTYLE:ON
		}
	}
}
 
Example #15
Source File: BaseUtils.java    From http4e with Apache License 2.0 5 votes vote down vote up
public static void writeToPrefs( String prefName, byte[] prefData){
   try {
      Plugin pl = (Plugin) CoreContext.getContext().getObject("p");
      Preferences prefs = pl.getPluginPreferences();

      String str64 = new String(Base64.encodeBase64(prefData), "UTF8");
      prefs.setValue(prefName, str64);
      pl.savePluginPreferences();

   } catch (UnsupportedEncodingException e) {
      ExceptionHandler.handle(e);
   } catch (Exception ignore) {
      ExceptionHandler.handle(ignore);
   }
}
 
Example #16
Source File: PluginProperties.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create an instance by reading in the properties file associated with the
 * plugin class. If there is a failure while reading the file, then fail
 * silently and output an error message.
 * 
 * @param pluginClass the plugin class for which the associated properties
 *          should be loaded
 */
public PluginProperties(Class<? extends Plugin> pluginClass) {
  String propsPath = pluginClass.getName().replace('.', '/').concat(
      ".properties");

  props = new Properties();

  try {
    InputStream instream = pluginClass.getClassLoader().getResourceAsStream(
        propsPath);

    if (instream != null) {
      props.load(instream);
    } else {
      System.err.println("Unable to read properties from file " + propsPath
          + ". The " + pluginClass.getName()
          + " plugin may not run correctly.");
    }
  } catch (IOException iox) {
    /*
     * TODO: Once we start exposing property values through accessors off of
     * plugin classes, we'll be able to pass a proper logger. Right now, we
     * can't do this, because this code is called from static blocks in the
     * plugin classes.
     */
    System.err.println("Unable to read properties from file " + propsPath
        + ". The " + pluginClass.getName() + " plugin may not run correctly.");
    iox.printStackTrace();
  }
}
 
Example #17
Source File: IdeLog.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Logs an item to the current plugin's log
 * 
 * @param plugin
 * @param status
 * @param message
 * @param th
 */
public static void log(Plugin plugin, int severity, String message, String scope, Throwable th)
{
	String tempMessage = buildMessage(plugin, severity, message, scope, th);
	String symbolicName = CorePlugin.PLUGIN_ID;
	if (plugin != null && plugin.getBundle() != null)
	{
		symbolicName = plugin.getBundle().getSymbolicName();
	}
	Status logStatus = new Status(severity, symbolicName, IStatus.OK, tempMessage, th);
	log(plugin, logStatus, scope);
}
 
Example #18
Source File: BaseUtils.java    From http4e with Apache License 2.0 5 votes vote down vote up
public static byte[] readFromPrefs( String prefName){
   try {
      Plugin pl = (Plugin) CoreContext.getContext().getObject("p");
      Preferences prefs = pl.getPluginPreferences();
      String str64 = prefs.getString(prefName);
      byte[] data = Base64.decodeBase64(str64.getBytes("UTF8"));
      return data;

   } catch (UnsupportedEncodingException e) {
      ExceptionHandler.handle(e);
   } catch (Exception ignore) {
      ExceptionHandler.handle(ignore);
   }
   return null;
}
 
Example #19
Source File: Dialogs.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Opens an {@link Dialogs}
 * @param title - The title  (if null it will be "Error")
 * @param body - The message (if null it will be e.getLocalizedMessage() )
 * @param e - A Throwable
 */
public static void errorMsgb(String title, String body, Throwable e){
	Plugin plugin = ResourcesPlugin.getPlugin();
	if(title == null){
		title = "Error";
	}
	
	if(body == null){
		body = e.getLocalizedMessage();
	}
	
	StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);

    final String trace = sw.toString(); // stack trace as a string

    // Temp holder of child statuses
    List<Status> childStatuses = new ArrayList<>();

    // Split output by OS-independend new-line
    for (String line : trace.split(System.getProperty("line.separator"))) {
        // build & add status
        childStatuses.add(new Status(IStatus.ERROR, plugin.getBundle().getSymbolicName(), line));
    }

    MultiStatus ms = new MultiStatus(plugin.getBundle().getSymbolicName(), IStatus.ERROR,
            childStatuses.toArray(new Status[] {}), // convert to array of statuses
            e.getLocalizedMessage(), e);
    ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, body, ms);
}
 
Example #20
Source File: AbstractExtraLanguageGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Load a property file from the resources.
 * This function is able to get the resource from an OSGi bundles if it is specified,
 * or from the application classpath.
 *
 * @param filename the name of the resource, without the starting slash character.
 * @param bundledPlugin the plugin that is able to provide the bundle that contains the resources, or {@code null}
 *     to use the application classpath.
 * @param readerClass the class that has called this function. It is used for obtaining the resource if
 *     the bundled plugin is not provided.
 * @param statusBuilder the builder of a status that takes the exception as parameter and creates a status object.
 *     This builder is used only if the {@code bundledPlugin} is not {@code null}.
 * @return the loaded resources.
 */
public static List<Pair<String, String>> loadPropertyFile(String filename, Plugin bundledPlugin,
		Class<?> readerClass,
		Function1<IOException, IStatus> statusBuilder) {
	final URL url;
	if (bundledPlugin != null) {
		url = FileLocator.find(
				bundledPlugin.getBundle(),
				Path.fromPortableString(filename),
				null);
	} else {
		url = readerClass.getClassLoader().getResource(filename);
	}
	if (url == null) {
		return Lists.newArrayList();
	}
	final OrderedProperties properties = new OrderedProperties();
	try (InputStream is = url.openStream()) {
		properties.load(is);
	} catch (IOException exception) {
		if (bundledPlugin != null) {
			bundledPlugin.getLog().log(statusBuilder.apply(exception));
		} else {
			throw new RuntimeException(exception);
		}
	}
	return properties.getOrderedProperties();
}
 
Example #21
Source File: PreferencesAdapterFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public Object getAdapter( Object adaptableObject, Class adapterType )
{
	String pluginId = ( (Plugin) adaptableObject ).getBundle( )
			.getSymbolicName( );
	if ( !factoryMap.containsKey( pluginId ) )
	{
		IDEReportPreferenceFactory factory = new IDEReportPreferenceFactory( (Plugin) adaptableObject );
		factoryMap.put( pluginId, factory );
	}
	return factoryMap.get( pluginId );
}
 
Example #22
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IClasspathEntry addPlatformJarToClasspath(final Plugin srcPlugin, final String jarFileName,
		final IJavaProject destProject) throws JavaModelException, IOException {
	final IPath jarFilePath = PluginUtil.findPathInPlugin(srcPlugin, jarFileName);
	final IClasspathEntry newLibraryEntry = JavaCore.newLibraryEntry(jarFilePath, null, null);
	addToClasspath(destProject, newLibraryEntry);
	return newLibraryEntry;
}
 
Example #23
Source File: PluginUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IFile copyFileToWorkspace(Plugin srcPlugin,
		String srcFilePath, IFile destFile) throws IOException,
		CoreException {
	Bundle bundle = srcPlugin.getBundle();
	URL bundleUrl = bundle.getResource(srcFilePath);
	URL fileUrl = FileLocator.toFileURL(bundleUrl);
	InputStream openStream = new BufferedInputStream(fileUrl.openStream());
	if (destFile.exists()) {
		destFile.delete(true, null);
	}
	destFile.create(openStream, true, null);
	return destFile;
}
 
Example #24
Source File: PluginUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IPath findPathInPlugin(Plugin srcPlugin, String fileName)
		throws IOException {
	URL bundleUrl = srcPlugin.getBundle().getResource(fileName);
	URL fileUrl = FileLocator.toFileURL(bundleUrl);
	Path filePath = new Path(fileUrl.getPath());
	return filePath;
}
 
Example #25
Source File: JavaProjectSetupUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IClasspathEntry addPlatformJarToClasspath(final Plugin srcPlugin, final String jarFileName,
		final IJavaProject destProject) throws JavaModelException, IOException {
	final IPath jarFilePath = PluginUtil.findPathInPlugin(srcPlugin, jarFileName);
	final IClasspathEntry newLibraryEntry = JavaCore.newLibraryEntry(jarFilePath, null, null);
	addToClasspath(destProject, newLibraryEntry);
	return newLibraryEntry;
}
 
Example #26
Source File: PluginUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IFile copyFileToWorkspace(Plugin srcPlugin,
		String srcFilePath, IFile destFile) throws IOException,
		CoreException {
	Bundle bundle = srcPlugin.getBundle();
	URL bundleUrl = bundle.getResource(srcFilePath);
	URL fileUrl = FileLocator.toFileURL(bundleUrl);
	InputStream openStream = new BufferedInputStream(fileUrl.openStream());
	if (destFile.exists()) {
		destFile.delete(true, null);
	}
	destFile.create(openStream, true, null);
	return destFile;
}
 
Example #27
Source File: PluginUtil.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static IPath findPathInPlugin(Plugin srcPlugin, String fileName)
		throws IOException {
	URL bundleUrl = srcPlugin.getBundle().getResource(fileName);
	URL fileUrl = FileLocator.toFileURL(bundleUrl);
	Path filePath = new Path(fileUrl.getPath());
	return filePath;
}
 
Example #28
Source File: PluginUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public static IFile copyFileToWorkspace(Plugin srcPlugin,
		String srcFilePath, IProject project, String destFilePath)
		throws IOException, CoreException {
	IFile destFile = project.getFile(destFilePath);
	return copyFileToWorkspace(srcPlugin, srcFilePath, destFile);
}
 
Example #29
Source File: MechanicLog.java    From workspacemechanic with Eclipse Public License 1.0 4 votes vote down vote up
MechanicLog(Plugin plugin) {
  this(plugin.getLog());
}
 
Example #30
Source File: IDEReportPreferenceFactory.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public IDEReportPreferenceFactory( Plugin plugin )
{
	this.pluginId = plugin.getBundle( ).getSymbolicName( );
}