Esempio n. 1
0
  private Set<Resource> addProjectBuildBundles(Resolver resolver) {
    if (!Project.BNDFILE.equals(runFile.getName())) return Collections.emptySet();

    Set<Resource> result = new HashSet<Resource>();
    try {

      Project model = Workspace.getProject(runFile.getProject().getLocation().toFile());
      for (Builder builder : model.getSubBuilders()) {
        File file = new File(model.getTarget(), builder.getBsn() + ".jar");
        if (file.isFile()) {
          JarInputStream stream = null;
          try {
            stream = new JarInputStream(new FileInputStream(file));
            Manifest manifest = stream.getManifest();

            Resource resource = helper.createResource(manifest.getMainAttributes());
            result.add(resource);
            resolver.add(resource);
          } catch (IOException e) {
            Plugin.logError("Error reading project bundle " + file, e);
          } finally {
            if (stream != null) stream.close();
          }
        }
      }
    } catch (Exception e) {
      Plugin.logError("Error getting builders for project: " + runFile.getProject(), e);
    }
    return result;
  }
  ILaunchConfiguration[] getLaunchConfigsForProject(IProject project) {
    ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();

    ILaunchConfigurationType type = manager.getLaunchConfigurationType(launchId);
    try {
      ILaunchConfiguration[] all = manager.getLaunchConfigurations(type);
      List<ILaunchConfiguration> result = new ArrayList<ILaunchConfiguration>(all.length);

      return result.toArray(new ILaunchConfiguration[result.size()]);
    } catch (CoreException e) {
      Plugin.logError("Error retrieving launch configurations.", e);
      return null;
    }
  }
Esempio n. 3
0
  private static URL getURL(IConfigurationElement element) {
    URL result = null;

    String urlAttribute = element.getAttribute("url");
    String resourceAttribute = element.getAttribute("resource");

    if (urlAttribute != null) {
      try {
        result = new URL(urlAttribute);
      } catch (MalformedURLException e) {
        Plugin.logError("Invalid URL defined in built-in OBR configuration.", e);
      }
    } else if (resourceAttribute != null) {
      String bundleId = element.getContributor().getName();
      Bundle bundle =
          BundleUtils.findBundle(Plugin.getDefault().getBundleContext(), bundleId, null);

      if (bundle != null) {
        result = bundle.getEntry(resourceAttribute);
      }
    }

    return result;
  }
 Project getProject() {
   Project project = null;
   try {
     BndEditModel model = (BndEditModel) getManagedForm().getInput();
     IResource resource = model.getBndResource();
     File projectDir = resource.getProject().getLocation().toFile();
     if (Project.BNDFILE.equals(resource.getName())) {
       project = Workspace.getProject(projectDir);
     } else {
       project = new Project(Central.getWorkspace(), projectDir, resource.getLocation().toFile());
     }
   } catch (Exception e) {
     Plugin.logError("Error getting project from editor model", e);
   }
   return project;
 }
Esempio n. 5
0
 private File getFile() {
   try {
     File file;
     if (repo instanceof RemoteRepositoryPlugin) {
       ResourceHandle handle =
           ((RemoteRepositoryPlugin) repo).getHandle(bsn, "latest", Strategy.HIGHEST, null);
       if (handle.getLocation() == Location.local
           || handle.getLocation() == Location.remote_cached) file = handle.request();
       else file = null;
     } else {
       file = repo.get(bsn, "latest", Strategy.HIGHEST, null);
     }
     return file;
   } catch (Exception e) {
     Plugin.logError(
         MessageFormat.format(
             "Failed to query repository {0} for bundle {1}.", repo.getName(), bsn),
         e);
     return null;
   }
 }
Esempio n. 6
0
  public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
    Object result = null;

    if (IFile.class.equals(adapter)) { // || IResource.class.equals(adapter)) {
      try {
        File file = getFile();
        if (file != null) {
          IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
          result = root.getFileForLocation(new Path(file.getAbsolutePath()));
        }
      } catch (Exception e) {
        Plugin.logError(
            MessageFormat.format(
                "Failed to query repository {0} for bundle {1}.", repo.getName(), bsn),
            e);
      }
    } else if (File.class.equals(adapter)) {
      result = getFile();
    }

    return result;
  }
 protected static void enableTraceOptionIfSetOnConfiguration(
     ILaunchConfiguration configuration, ProjectLauncher launcher) throws CoreException {
   if (configuration.hasAttribute(LaunchConstants.ATTR_TRACE)) {
     launcher.setTrace(
         configuration.getAttribute(LaunchConstants.ATTR_TRACE, LaunchConstants.DEFAULT_TRACE));
   }
   String logLevelStr = configuration.getAttribute(ATTR_LOGLEVEL, (String) null);
   if (logLevelStr != null) {
     Plugin.getDefault()
         .getLog()
         .log(
             new Status(
                 IStatus.WARNING,
                 Plugin.PLUGIN_ID,
                 0,
                 MessageFormat.format(
                     "The {0} attribute is no longer supported, use {1} instead.",
                     ATTR_LOGLEVEL, LaunchConstants.ATTR_TRACE),
                 null));
     Level logLevel = Level.parse(logLevelStr);
     launcher.setTrace(launcher.getTrace() || logLevel.intValue() <= Level.FINE.intValue());
   }
 }
  public ImportBundleRepositoryWizard() {
    setNeedsProgressMonitor(true);

    BundleContext bc = Plugin.getDefault().getBundleContext();
    repoAdmin = new RepositoryAdminImpl(bc, new Logger(bc));

    bundlePage = new RemoteRepositoryBundleSelectionPage(repoAdmin);
    repoPage = new OBRSelectionPage(repoAdmin, bundlePage);
    dependenciesPage =
        new DependentResourcesWizardPage(repoAdmin, new LocalRepositoryIndexer(false));

    bundlePage.addPropertyChangeListener(
        RemoteRepositoryBundleSelectionPage.PROP_SELECTION,
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent evt) {
            dependenciesPage.setSelectedResources(bundlePage.getSelectedResources());
          }
        });

    addPage(repoPage);
    addPage(bundlePage);
    addPage(dependenciesPage);
  }
Esempio n. 9
0
  public void run(IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, "Resolving...", 0);

    MultiStatus status =
        new MultiStatus(Plugin.PLUGIN_ID, 0, "Problems during OBR resolution", null);

    // Get the repositories
    List<OBRIndexProvider> indexProviders;
    try {
      indexProviders = loadIndexProviders();
    } catch (Exception e) {
      status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error loading OBR indexes.", e));
      result = createErrorResult(status);
      return;
    }

    // Create the dummy system bundle and repository admin
    File frameworkFile = findFramework(status);
    if (frameworkFile == null) {
      result = createErrorResult(status);
      return;
    }
    DummyBundleContext bundleContext;
    try {
      bundleContext = new DummyBundleContext(frameworkFile);
    } catch (IOException e) {
      status.add(
          new Status(
              IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error reading system bundle manifest.", e));
      result = createErrorResult(status);
      return;
    }

    // Load repository indexes
    List<Repository> repos = new LinkedList<Repository>();
    for (OBRIndexProvider prov : indexProviders) {
      String repoName;
      if (prov instanceof RepositoryPlugin) {
        RepositoryPlugin repo = (RepositoryPlugin) prov;
        repoName = repo.getName();
      } else {
        repoName = prov.toString();
      }

      File cacheDir;
      if (prov instanceof RemoteRepositoryPlugin) {
        cacheDir = ((RemoteRepositoryPlugin) prov).getCacheDirectory();
      } else {
        cacheDir = Plugin.getDefault().getStateLocation().toFile();
      }

      try {
        for (URL indexUrl : prov.getOBRIndexes()) {
          addRepository(indexUrl, repos, cacheDir);
        }
      } catch (Exception e) {
        status.add(
            new Status(
                IStatus.ERROR,
                Plugin.PLUGIN_ID,
                0,
                "Error processing index for repository " + repoName,
                e));
      }
    }

    RepositoryAdminImpl repoAdmin =
        new RepositoryAdminImpl(bundleContext, new Logger(Plugin.getDefault().getBundleContext()));

    repos.add(
        0,
        repoAdmin
            .getLocalRepository()); // BUG? Calling `resolver(Repository[])` excludes the local and
                                    // system repos!
    repos.add(0, repoAdmin.getSystemRepository());
    Resolver resolver = repoAdmin.resolver(repos.toArray(new Repository[repos.size()]));

    // Add project builders
    Set<Resource> projectBuildResources = addProjectBuildBundles(resolver);

    // Add EE capabilities
    EE ee = model.getEE();
    if (ee == null) ee = EE.J2SE_1_5; // TODO: read default from the workbench
    resolver.addGlobalCapability(createEeCapability(ee));
    for (EE compat : ee.getCompatible()) {
      resolver.addGlobalCapability(createEeCapability(compat));
    }

    // Add JRE package capabilities
    try {
      addJREPackageCapabilities(resolver, ee);
    } catch (IOException e) {
      status.add(
          new Status(
              IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error adding JRE package capabilities", e));
      result = createErrorResult(status);
      return;
    }

    // HACK: add capabilities for usual framework services (not all frameworks declare these
    // statically)
    String[] frameworkServices =
        new String[] {
          "org.osgi.service.packageadmin.PackageAdmin",
          "org.osgi.service.startlevel.StartLevel",
          "org.osgi.service.permissionadmin.PermissionAdmin"
        };
    for (String frameworkService : frameworkServices) {
      Map<String, String> props = new HashMap<String, String>();
      props.put(ObrConstants.FILTER_SERVICE, frameworkService);
      resolver.addGlobalCapability(helper.capability(ObrConstants.REQUIREMENT_SERVICE, props));
    }

    // Add system packages-extra capabilities (from -runsystempackages)
    List<ExportedPackage> systemPackages = model.getSystemPackages();
    if (systemPackages != null) addSystemPackagesExtraCapabilities(resolver, systemPackages);

    // Add requirements
    List<bndtools.api.Requirement> requirements = model.getRunRequire();
    if (requirements != null)
      for (bndtools.api.Requirement req : requirements) {
        resolver.add(helper.requirement(req.getName(), req.getFilter()));
      }

    boolean resolved = resolver.resolve();

    result =
        new ObrResolutionResult(
            resolved,
            Status.OK_STATUS,
            filterGlobalResource(resolver.getRequiredResources()),
            filterGlobalResource(resolver.getOptionalResources()),
            Arrays.asList(resolver.getUnsatisfiedRequirements()));
  }
public class RepoTemplateSelectionWizardPage extends WizardPage {

  public static final String PROP_TEMPLATE = "template";

  private static final String NO_HELP_CONTENT = "<form>No help content available</form>";

  private final ILog log = Plugin.getDefault().getLog();

  private final PropertyChangeSupport propSupport = new PropertyChangeSupport(this);
  private final String templateType;
  private final String templateExtPoint;
  private final Template emptyTemplate;

  private final Map<Template, Image> loadedImages = new IdentityHashMap<>();

  private Tree tree;
  private TreeViewer viewer;
  private RepoTemplateContentProvider contentProvider;
  private final LatestTemplateFilter latestFilter = new LatestTemplateFilter();
  private Button btnLatestOnly;
  private ScrolledFormText txtDescription;

  private Template selected = null;

  private boolean shown = false;

  public RepoTemplateSelectionWizardPage(
      String pageName, String templateType, String templateExtPoint, Template emptyTemplate) {
    super(pageName);
    this.templateType = templateType;
    this.templateExtPoint = templateExtPoint;
    this.emptyTemplate = emptyTemplate;
  }

  @Override
  public void setVisible(boolean visible) {
    super.setVisible(visible);
    if (visible && !shown) {
      shown = true;
      loadTemplates();
    }
  }

  /*
   * Don't allow wizard to complete before this page is shown
   */
  @Override
  public boolean isPageComplete() {
    return shown && selected != null && super.isPageComplete();
  }

  public void addPropertyChangeListener(PropertyChangeListener listener) {
    propSupport.addPropertyChangeListener(listener);
  }

  public void removePropertyChangeListener(PropertyChangeListener listener) {
    propSupport.removePropertyChangeListener(listener);
  }

  public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
    propSupport.addPropertyChangeListener(propertyName, listener);
  }

  public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
    propSupport.removePropertyChangeListener(propertyName, listener);
  }

  @Override
  public void createControl(Composite parent) {
    GridData gd;

    Composite composite = new Composite(parent, SWT.NULL);
    setControl(composite);

    composite.setLayout(new GridLayout(1, false));

    new Label(composite, SWT.NONE).setText("Select Template:");

    tree = new Tree(composite, SWT.BORDER | SWT.FULL_SELECTION);
    gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    gd.heightHint = 100;
    tree.setLayoutData(gd);

    viewer = new TreeViewer(tree);
    contentProvider = new RepoTemplateContentProvider(false);
    viewer.setContentProvider(contentProvider);
    viewer.setLabelProvider(new RepoTemplateLabelProvider(loadedImages));
    viewer.addFilter(latestFilter);
    setTemplates(Collections.singletonList(emptyTemplate));

    btnLatestOnly = new Button(composite, SWT.CHECK);
    btnLatestOnly.setText("Show latest versions only");
    btnLatestOnly.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
    btnLatestOnly.setSelection(true);

    new Label(composite, SWT.NONE).setText("Description:");

    Composite cmpDescription = new Composite(composite, SWT.BORDER);
    cmpDescription.setBackground(tree.getBackground());

    txtDescription = new ScrolledFormText(cmpDescription, SWT.V_SCROLL | SWT.H_SCROLL, false);
    FormText formText = new FormText(txtDescription, SWT.NO_FOCUS);
    txtDescription.setFormText(formText);
    txtDescription.setBackground(tree.getBackground());
    formText.setBackground(tree.getBackground());
    formText.setForeground(tree.getForeground());
    formText.setFont("fixed", JFaceResources.getTextFont());
    formText.setFont("italic", JFaceResources.getFontRegistry().getItalic(""));

    GridData gd_cmpDescription = new GridData(SWT.FILL, SWT.FILL, true, true);
    gd_cmpDescription.heightHint = 100;
    cmpDescription.setLayoutData(gd_cmpDescription);

    GridLayout layout_cmpDescription = new GridLayout(1, false);
    cmpDescription.setLayout(layout_cmpDescription);

    GridData gd_txtDescription = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
    gd_txtDescription.heightHint = 100;
    txtDescription.setLayoutData(gd_txtDescription);

    Hyperlink linkRetina = new Hyperlink(composite, SWT.NONE);
    linkRetina.setText("Why is this text blurred?");
    linkRetina.setUnderlined(true);
    linkRetina.setForeground(JFaceColors.getHyperlinkText(getShell().getDisplay()));
    linkRetina.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));

    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          @Override
          public void selectionChanged(SelectionChangedEvent event) {
            Object element = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            setTemplate(element instanceof Template ? (Template) element : null);
            getContainer().updateButtons();
          }
        });
    viewer.addOpenListener(
        new IOpenListener() {
          @Override
          public void open(OpenEvent event) {
            Object element = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            setTemplate(element instanceof Template ? (Template) element : null);
            getContainer().updateButtons();
            IWizardPage nextPage = getNextPage();
            if (nextPage != null) getContainer().showPage(nextPage);
          }
        });
    btnLatestOnly.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            boolean latestOnly = btnLatestOnly.getSelection();
            if (latestOnly) viewer.addFilter(latestFilter);
            else viewer.removeFilter(latestFilter);
          }
        });
    linkRetina.addHyperlinkListener(
        new HyperlinkAdapter() {
          @Override
          public void linkActivated(HyperlinkEvent ev) {
            try {
              IWorkbenchBrowserSupport browser = PlatformUI.getWorkbench().getBrowserSupport();
              browser
                  .getExternalBrowser()
                  .openURL(
                      new URL(
                          "https://github.com/bndtools/bndtools/wiki/Blurry-Form-Text-on-High-Resolution-Displays"));
            } catch (Exception e) {
              log.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Browser open error", e));
            }
          }
        });
  }

  private class LoadTemplatesJob implements IRunnableWithProgress {

    private final Shell shell;
    private final String originalMessage;

    public LoadTemplatesJob(Shell shell, String originalMessage) {
      this.shell = shell;
      this.originalMessage = originalMessage;
    }

    @Override
    public void run(IProgressMonitor progress) throws InvocationTargetException {
      SubMonitor monitor = SubMonitor.convert(progress, 3);
      monitor.setTaskName("Loading Templates...");
      try {
        final Set<Template> templates = new LinkedHashSet<>();
        final List<String> errors = new LinkedList<>();

        // Load from workspace, if one exists
        Workspace ws = Central.getWorkspaceIfPresent();
        if (ws != null) {
          List<Repository> repos = ws.getPlugins(Repository.class);
          RepoPluginsBundleLocator locator = new RepoPluginsBundleLocator(ws.getRepositories());
          templates.addAll(
              new ReposTemplateLoader(repos, locator)
                  .findTemplates(
                      templateType, errors, monitor.newChild(1, SubMonitor.SUPPRESS_NONE)));
        }

        // Load from the preferences-configured template repository
        BndPreferences bndPrefs = new BndPreferences();
        if (bndPrefs.getEnableTemplateRepo()) {
          try {
            FixedIndexedRepo repo = loadRepo(bndPrefs.getTemplateRepoUriList());
            RepoPluginsBundleLocator locator =
                new RepoPluginsBundleLocator(Collections.<RepositoryPlugin>singletonList(repo));
            ReposTemplateLoader loader =
                new ReposTemplateLoader(Collections.<Repository>singletonList(repo), locator);
            templates.addAll(
                loader.findTemplates(
                    templateType, errors, monitor.newChild(1, SubMonitor.SUPPRESS_NONE)));
          } catch (Exception e) {
            throw new InvocationTargetException(e);
          }
        }

        // Log errors
        for (String error : errors) {
          Plugin.getDefault()
              .getLog()
              .log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, error, null));
        }

        // Add the build-in empty template if provided
        if (emptyTemplate != null) templates.add(emptyTemplate);

        // Load from extension registry
        if (templateExtPoint != null) {
          IConfigurationElement[] elements =
              Platform.getExtensionRegistry()
                  .getConfigurationElementsFor(Plugin.PLUGIN_ID, templateExtPoint);
          if (elements == null) elements = new IConfigurationElement[0];
          monitor.setWorkRemaining(elements.length);

          for (IConfigurationElement element : elements) {
            String elementName = element.getName();
            IContributor contributor = element.getContributor();
            try {
              Template extTemplate = (Template) element.createExecutableExtension("class");
              templates.add(extTemplate);
            } catch (CoreException e) {
              Plugin.getDefault()
                  .getLog()
                  .log(
                      new Status(
                          IStatus.ERROR,
                          Plugin.PLUGIN_ID,
                          0,
                          String.format(
                              "Error loading template '%s' from bundle %s",
                              elementName, contributor.getName()),
                          e));
            } finally {
              monitor.worked(1);
            }
          }
        }

        // Display results
        Control control = viewer.getControl();
        if (control != null && !control.isDisposed()) {
          control
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      setTemplates(templates);
                      IconLoaderJob iconLoaderJob =
                          new IconLoaderJob(templates, viewer, loadedImages, 5);
                      iconLoaderJob.setSystem(true);
                      iconLoaderJob.schedule(0);
                    }
                  });
        }

      } finally {
        monitor.done();
        // Restore the original message to the page
        if (!shell.isDisposed())
          shell
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      setMessage(originalMessage);
                    }
                  });
      }
    }

    private FixedIndexedRepo loadRepo(List<String> uris) throws IOException, URISyntaxException {
      FixedIndexedRepo repo = new FixedIndexedRepo();
      StringBuilder sb = new StringBuilder();
      for (Iterator<String> iter = uris.iterator(); iter.hasNext(); ) {
        sb.append(iter.next());
        if (iter.hasNext()) sb.append(',');
      }
      repo.setLocations(sb.toString());
      return repo;
    }
  }

  protected void loadTemplates() {
    final String oldMessage = getMessage();
    final Shell shell = getShell();

    setMessage("Loading templates...");
    try {
      getContainer().run(true, true, new LoadTemplatesJob(shell, oldMessage));
    } catch (InterruptedException e) {
      // ignore
    } catch (InvocationTargetException e) {
      Throwable exception = e.getTargetException();
      ErrorDialog.openError(
          getShell(),
          "Error",
          null,
          new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error loading templates.", exception));
    }
  }

  @Override
  public void dispose() {
    super.dispose();

    for (Entry<Template, Image> entry : loadedImages.entrySet()) {
      Image img = entry.getValue();
      if (!img.isDisposed()) img.dispose();
    }
  }

  private void setTemplates(final Collection<Template> templates) {
    viewer.setInput(templates);
    viewer.expandAll();

    Template first = contentProvider.getFirstTemplate();
    viewer.setSelection(
        first != null ? new StructuredSelection(first) : StructuredSelection.EMPTY, true);
  }

  public void setTemplate(final Template template) {
    Template old = this.selected;
    this.selected = template;
    propSupport.firePropertyChange(PROP_TEMPLATE, old, template);

    if (template != null) {
      txtDescription.setText(
          String.format(
              "<form>Loading help content for template '%s'...</form>", template.getName()));
      Job updateDescJob = new UpdateDescriptionJob(template, txtDescription);
      updateDescJob.setSystem(true);
      updateDescJob.schedule();
    } else {
      txtDescription.setText(NO_HELP_CONTENT);
    }
  }

  public Template getTemplate() {
    return selected;
  }

  private final class UpdateDescriptionJob extends Job {
    private final Template template;
    private final ScrolledFormText control;

    private UpdateDescriptionJob(Template template, ScrolledFormText control) {
      super("update description");
      this.template = template;
      this.control = control;
    }

    @Override
    protected IStatus run(IProgressMonitor monitor) {
      String tmp = NO_HELP_CONTENT;
      if (template != null) {
        URI uri = template.getHelpContent();
        if (uri != null) {
          try {
            URLConnection conn = uri.toURL().openConnection();
            conn.setUseCaches(false);
            tmp = IO.collect(conn.getInputStream());
          } catch (IOException e) {
            log.log(
                new Status(
                    IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error loading template help content.", e));
          }
        }
      }

      final String text = tmp;
      if (control != null && !control.isDisposed()) {
        control
            .getDisplay()
            .asyncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    if (!control.isDisposed()) control.setText(text);
                  }
                });
      }

      return Status.OK_STATUS;
    }
  }
}
    @Override
    public void run(IProgressMonitor progress) throws InvocationTargetException {
      SubMonitor monitor = SubMonitor.convert(progress, 3);
      monitor.setTaskName("Loading Templates...");
      try {
        final Set<Template> templates = new LinkedHashSet<>();
        final List<String> errors = new LinkedList<>();

        // Load from workspace, if one exists
        Workspace ws = Central.getWorkspaceIfPresent();
        if (ws != null) {
          List<Repository> repos = ws.getPlugins(Repository.class);
          RepoPluginsBundleLocator locator = new RepoPluginsBundleLocator(ws.getRepositories());
          templates.addAll(
              new ReposTemplateLoader(repos, locator)
                  .findTemplates(
                      templateType, errors, monitor.newChild(1, SubMonitor.SUPPRESS_NONE)));
        }

        // Load from the preferences-configured template repository
        BndPreferences bndPrefs = new BndPreferences();
        if (bndPrefs.getEnableTemplateRepo()) {
          try {
            FixedIndexedRepo repo = loadRepo(bndPrefs.getTemplateRepoUriList());
            RepoPluginsBundleLocator locator =
                new RepoPluginsBundleLocator(Collections.<RepositoryPlugin>singletonList(repo));
            ReposTemplateLoader loader =
                new ReposTemplateLoader(Collections.<Repository>singletonList(repo), locator);
            templates.addAll(
                loader.findTemplates(
                    templateType, errors, monitor.newChild(1, SubMonitor.SUPPRESS_NONE)));
          } catch (Exception e) {
            throw new InvocationTargetException(e);
          }
        }

        // Log errors
        for (String error : errors) {
          Plugin.getDefault()
              .getLog()
              .log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, error, null));
        }

        // Add the build-in empty template if provided
        if (emptyTemplate != null) templates.add(emptyTemplate);

        // Load from extension registry
        if (templateExtPoint != null) {
          IConfigurationElement[] elements =
              Platform.getExtensionRegistry()
                  .getConfigurationElementsFor(Plugin.PLUGIN_ID, templateExtPoint);
          if (elements == null) elements = new IConfigurationElement[0];
          monitor.setWorkRemaining(elements.length);

          for (IConfigurationElement element : elements) {
            String elementName = element.getName();
            IContributor contributor = element.getContributor();
            try {
              Template extTemplate = (Template) element.createExecutableExtension("class");
              templates.add(extTemplate);
            } catch (CoreException e) {
              Plugin.getDefault()
                  .getLog()
                  .log(
                      new Status(
                          IStatus.ERROR,
                          Plugin.PLUGIN_ID,
                          0,
                          String.format(
                              "Error loading template '%s' from bundle %s",
                              elementName, contributor.getName()),
                          e));
            } finally {
              monitor.worked(1);
            }
          }
        }

        // Display results
        Control control = viewer.getControl();
        if (control != null && !control.isDisposed()) {
          control
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      setTemplates(templates);
                      IconLoaderJob iconLoaderJob =
                          new IconLoaderJob(templates, viewer, loadedImages, 5);
                      iconLoaderJob.setSystem(true);
                      iconLoaderJob.schedule(0);
                    }
                  });
        }

      } finally {
        monitor.done();
        // Restore the original message to the page
        if (!shell.isDisposed())
          shell
              .getDisplay()
              .asyncExec(
                  new Runnable() {
                    @Override
                    public void run() {
                      setMessage(originalMessage);
                    }
                  });
      }
    }
Esempio n. 12
0
public class RepositoriesView extends ViewPart implements RepositoryListenerPlugin {
  static final Pattern LABEL_PATTERN = Pattern.compile("(-)?(!)?([^{}]+)(?:\\{([^}]+)\\})?");
  private static final String DROP_TARGET = "dropTarget";

  private static final ILogger logger = Logger.getLogger(RepositoriesView.class);

  private final FilterPanelPart filterPart =
      new FilterPanelPart(Plugin.getDefault().getScheduler());
  private final SearchableRepositoryTreeContentProvider contentProvider =
      new SearchableRepositoryTreeContentProvider();
  private TreeViewer viewer;

  private Action collapseAllAction;
  private Action refreshAction;
  private Action addBundlesAction;

  private ServiceRegistration<RepositoryListenerPlugin> registration;

  @Override
  public void createPartControl(Composite parent) {
    // CREATE CONTROLS
    Composite mainPanel = new Composite(parent, SWT.NONE);
    Control filterPanel = filterPart.createControl(mainPanel, 5, 5);
    Tree tree = new Tree(mainPanel, SWT.FULL_SELECTION | SWT.MULTI);
    filterPanel.setBackground(tree.getBackground());

    viewer = new TreeViewer(tree);
    viewer.setContentProvider(contentProvider);
    ColumnViewerToolTipSupport.enableFor(viewer);

    viewer.setLabelProvider(new RepositoryTreeLabelProvider(false));
    getViewSite().setSelectionProvider(viewer);

    createActions();

    JpmPreferences jpmPrefs = new JpmPreferences();
    final boolean showJpmOnClick =
        jpmPrefs.getBrowserSelection() != JpmPreferences.PREF_BROWSER_EXTERNAL;

    // LISTENERS
    filterPart.addPropertyChangeListener(
        new PropertyChangeListener() {
          @Override
          public void propertyChange(PropertyChangeEvent event) {
            String filter = (String) event.getNewValue();
            updatedFilter(filter);
          }
        });
    ViewerDropAdapter dropAdapter =
        new ViewerDropAdapter(viewer) {
          @Override
          public boolean validateDrop(Object target, int operation, TransferData transferType) {
            if (canDrop(target, transferType)) return true;

            boolean valid = false;
            if (target instanceof RepositoryPlugin) {
              if (((RepositoryPlugin) target).canWrite()) {

                if (URLTransfer.getInstance().isSupportedType(transferType)) return true;

                if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
                  ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
                  if (selection instanceof IStructuredSelection) {
                    for (Iterator<?> iter = ((IStructuredSelection) selection).iterator();
                        iter.hasNext(); ) {
                      Object element = iter.next();
                      if (element instanceof RepositoryBundle
                          || element instanceof RepositoryBundleVersion) {
                        valid = true;
                        break;
                      }
                      if (element instanceof IFile) {
                        valid = true;
                        break;
                      }
                      if (element instanceof IAdaptable) {
                        IFile file = (IFile) ((IAdaptable) element).getAdapter(IFile.class);
                        if (file != null) {
                          valid = true;
                          break;
                        }
                      }
                    }
                  }
                } else {
                  valid = true;
                }
              }
            }
            return valid;
          }

          @Override
          public void dragEnter(DropTargetEvent event) {
            super.dragEnter(event);
            event.detail = DND.DROP_COPY;
          }

          @Override
          public boolean performDrop(Object data) {
            if (RepositoriesView.this.performDrop(
                getCurrentTarget(), getCurrentEvent().currentDataType)) {
              viewer.refresh(getCurrentTarget(), true);
              return true;
            }

            boolean copied = false;
            if (URLTransfer.getInstance().isSupportedType(getCurrentEvent().currentDataType)) {
              try {
                URL url =
                    new URL(
                        (String)
                            URLTransfer.getInstance()
                                .nativeToJava(getCurrentEvent().currentDataType));
                File tmp = File.createTempFile("dwnl", ".jar");
                IO.copy(url, tmp);
                copied =
                    addFilesToRepository((RepositoryPlugin) getCurrentTarget(), new File[] {tmp});
              } catch (Exception e) {
                return false;
              }
            } else if (data instanceof String[]) {
              String[] paths = (String[]) data;
              File[] files = new File[paths.length];
              for (int i = 0; i < paths.length; i++) {
                files[i] = new File(paths[i]);
              }
              copied = addFilesToRepository((RepositoryPlugin) getCurrentTarget(), files);
            } else if (data instanceof IResource[]) {
              IResource[] resources = (IResource[]) data;
              File[] files = new File[resources.length];
              for (int i = 0; i < resources.length; i++) {
                files[i] = resources[i].getLocation().toFile();
              }
              copied = addFilesToRepository((RepositoryPlugin) getCurrentTarget(), files);
            } else if (data instanceof IStructuredSelection) {
              File[] files = convertSelectionToFiles((IStructuredSelection) data);
              if (files != null && files.length > 0)
                copied = addFilesToRepository((RepositoryPlugin) getCurrentTarget(), files);
            }
            return copied;
          }
        };
    dropAdapter.setFeedbackEnabled(false);
    dropAdapter.setExpandEnabled(false);

    viewer.addDropSupport(
        DND.DROP_COPY | DND.DROP_MOVE,
        new Transfer[] {
          URLTransfer.getInstance(),
          FileTransfer.getInstance(),
          ResourceTransfer.getInstance(),
          LocalSelectionTransfer.getTransfer()
        },
        dropAdapter);
    viewer.addDragSupport(
        DND.DROP_COPY | DND.DROP_MOVE,
        new Transfer[] {LocalSelectionTransfer.getTransfer()},
        new SelectionDragAdapter(viewer));

    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          @Override
          public void selectionChanged(SelectionChangedEvent event) {
            boolean writableRepoSelected = false;
            IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
            Object element = selection.getFirstElement();
            if (element instanceof RepositoryPlugin) {
              RepositoryPlugin repo = (RepositoryPlugin) element;
              writableRepoSelected = repo.canWrite();
            }
            addBundlesAction.setEnabled(writableRepoSelected);
          }
        });
    tree.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseUp(MouseEvent ev) {
            Object element = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            if (element instanceof ContinueSearchElement) {
              try {
                getViewSite()
                    .getPage()
                    .showView(
                        Plugin.JPM_BROWSER_VIEW_ID,
                        null,
                        showJpmOnClick ? IWorkbenchPage.VIEW_ACTIVATE : IWorkbenchPage.VIEW_CREATE);
              } catch (PartInitException e) {
                Plugin.getDefault().getLog().log(e.getStatus());
              }
            }
          }
        });
    viewer.addDoubleClickListener(
        new IDoubleClickListener() {
          @Override
          public void doubleClick(DoubleClickEvent event) {
            if (!event.getSelection().isEmpty()) {
              IStructuredSelection selection = (IStructuredSelection) event.getSelection();
              Object element = selection.getFirstElement();
              if (element instanceof IAdaptable) {
                URI uri = (URI) ((IAdaptable) element).getAdapter(URI.class);
                if (uri != null) {
                  IWorkbenchPage page = getSite().getPage();
                  try {
                    IFileStore fileStore = EFS.getLocalFileSystem().getStore(uri);
                    IDE.openEditorOnFileStore(page, fileStore);
                  } catch (PartInitException e) {
                    logger.logError("Error opening editor for " + uri, e);
                  }
                }
              } else if (element instanceof ContinueSearchElement) {
                ContinueSearchElement searchElement = (ContinueSearchElement) element;
                try {
                  JpmPreferences jpmPrefs = new JpmPreferences();
                  if (jpmPrefs.getBrowserSelection() == JpmPreferences.PREF_BROWSER_EXTERNAL)
                    getViewSite()
                        .getWorkbenchWindow()
                        .getWorkbench()
                        .getBrowserSupport()
                        .getExternalBrowser()
                        .openURL(new URL("https://www.jpm4j.org/" + searchElement.getFilter()));
                  else
                    getViewSite()
                        .getPage()
                        .showView(Plugin.JPM_BROWSER_VIEW_ID, null, IWorkbenchPage.VIEW_VISIBLE);
                } catch (PartInitException e) {
                  Plugin.getDefault().getLog().log(e.getStatus());
                } catch (MalformedURLException e) {
                  // ignore
                }
              }
            }
          }
        });

    createContextMenu();

    // LOAD
    Central.onWorkspaceInit(
        new Function<Workspace, Void>() {
          @Override
          public Void run(Workspace a) {
            final List<RepositoryPlugin> repositories = RepositoryUtils.listRepositories(true);
            SWTConcurrencyUtil.execForControl(
                viewer.getControl(),
                true,
                new Runnable() {
                  @Override
                  public void run() {
                    viewer.setInput(repositories);
                  }
                });
            return null;
          }
        });

    // LAYOUT
    GridLayout layout = new GridLayout(1, false);
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = 0;
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    mainPanel.setLayout(layout);

    tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    filterPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

    // Toolbar
    createActions();
    fillToolBar(getViewSite().getActionBars().getToolBarManager());

    // Register as repository listener
    registration =
        Activator.getDefault()
            .getBundleContext()
            .registerService(RepositoryListenerPlugin.class, this, null);
  }

  @Override
  public void setFocus() {
    filterPart.setFocus();
  }

  private static File[] convertSelectionToFiles(ISelection selection) {
    if (!(selection instanceof IStructuredSelection)) return new File[0];

    IStructuredSelection structSel = (IStructuredSelection) selection;
    List<File> files = new ArrayList<File>(structSel.size());

    for (Iterator<?> iter = structSel.iterator(); iter.hasNext(); ) {
      Object element = iter.next();
      if (element instanceof IFile) files.add(((IFile) element).getLocation().toFile());
      else if (element instanceof IAdaptable) {
        IAdaptable adaptable = (IAdaptable) element;
        IFile ifile = (IFile) adaptable.getAdapter(IFile.class);
        if (ifile != null) {
          files.add(ifile.getLocation().toFile());
        } else {
          File file = (File) adaptable.getAdapter(File.class);
          if (file != null) {
            files.add(file);
          }
        }
      }
    }

    return files.toArray(new File[files.size()]);
  }

  @Override
  public void dispose() {
    registration.unregister();
    super.dispose();
  }

  boolean addFilesToRepository(RepositoryPlugin repo, File[] files) {
    AddFilesToRepositoryWizard wizard = new AddFilesToRepositoryWizard(repo, files);
    WizardDialog dialog = new WizardDialog(getViewSite().getShell(), wizard);
    dialog.open();
    viewer.refresh(repo);
    return true;
  }

  private void updatedFilter(String filterString) {
    String newFilter;
    if (filterString == null || filterString.length() == 0 || filterString.trim().equals("*"))
      newFilter = null;
    else newFilter = "*" + filterString.trim() + "*";

    contentProvider.setFilter(newFilter);
    viewer.refresh();
    if (newFilter != null) viewer.expandToLevel(2);
  }

  void createActions() {
    collapseAllAction =
        new Action() {
          @Override
          public void run() {
            viewer.collapseAll();
          }
        };
    collapseAllAction.setText("Collapse All");
    collapseAllAction.setToolTipText("Collapse All");
    collapseAllAction.setImageDescriptor(
        AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/collapseall.gif"));

    refreshAction =
        new Action() {
          @Override
          public void run() {
            doRefresh();
          }
        };
    refreshAction.setText("Refresh");
    refreshAction.setToolTipText("Refresh Repositories Tree");
    refreshAction.setImageDescriptor(
        AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/arrow_refresh.png"));

    addBundlesAction =
        new Action() {
          @Override
          public void run() {
            IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
            Object element = selection.getFirstElement();
            if (element != null && element instanceof RepositoryPlugin) {
              RepositoryPlugin repo = (RepositoryPlugin) element;
              if (repo.canWrite()) {
                AddFilesToRepositoryWizard wizard =
                    new AddFilesToRepositoryWizard(repo, new File[0]);
                WizardDialog dialog = new WizardDialog(getViewSite().getShell(), wizard);
                dialog.open();

                viewer.refresh(repo);
              }
            }
          }
        };
    addBundlesAction.setEnabled(false);
    addBundlesAction.setText("Add");
    addBundlesAction.setToolTipText("Add Bundles to Repository");
    addBundlesAction.setImageDescriptor(
        AbstractUIPlugin.imageDescriptorFromPlugin(Plugin.PLUGIN_ID, "/icons/brick_add.png"));
  }

  void createContextMenu() {
    MenuManager mgr = new MenuManager();
    Menu menu = mgr.createContextMenu(viewer.getControl());
    viewer.getControl().setMenu(menu);
    mgr.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
    getSite().registerContextMenu(mgr, viewer);

    mgr.addMenuListener(
        new IMenuListener() {

          @Override
          public void menuAboutToShow(IMenuManager manager) {
            try {
              manager.removeAll();
              IStructuredSelection selection = (IStructuredSelection) viewer.getSelection();
              if (!selection.isEmpty()) {
                Object firstElement = selection.getFirstElement();
                if (firstElement instanceof Actionable) {
                  //
                  // Use the Actionable interface to fill the menu
                  // Should extend this to allow other menu entries
                  // from the view, but currently there are none
                  //
                  final Actionable act = (Actionable) firstElement;
                  Map<String, Runnable> actions = act.actions();
                  if (actions != null) {
                    for (final Entry<String, Runnable> e : actions.entrySet()) {
                      String label = e.getKey();
                      boolean enabled = true;
                      boolean checked = false;
                      String description = null;
                      Matcher m = LABEL_PATTERN.matcher(label);
                      if (m.matches()) {
                        if (m.group(1) != null) enabled = false;

                        if (m.group(2) != null) checked = true;

                        label = m.group(3);

                        description = m.group(4);
                      }
                      Action a =
                          new Action(label) {
                            @Override
                            public void run() {
                              try {
                                e.getValue().run();
                              } catch (Exception e) {
                                throw new RuntimeException(e);
                              }
                              viewer.refresh(act);
                            }
                          };
                      a.setEnabled(enabled);
                      if (description != null) a.setDescription(description);
                      a.setChecked(checked);
                      manager.add(a);
                    }
                  }
                }
              }
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }
        });
  }

  private void doRefresh() {
    // Remember names of expanded repositories
    Set<String> expandedRepoNames = new HashSet<String>();
    Object[] expandedElems = viewer.getExpandedElements();
    for (Object expandedElem : expandedElems) {
      if (expandedElem instanceof RepositoryPlugin) {
        expandedRepoNames.add(((RepositoryPlugin) expandedElem).getName());
      }
    }

    // Reload repositories
    List<RepositoryPlugin> repos = RepositoryUtils.listRepositories(true);
    viewer.setInput(repos);

    // Expand any repos that have the same name as a repository that
    // was expanded before the reload.
    for (RepositoryPlugin repo : repos) {
      if (expandedRepoNames.contains(repo.getName())) {
        viewer.setExpandedState(repo, true);
      }
    }
  }

  private void fillToolBar(IToolBarManager toolBar) {
    toolBar.add(refreshAction);
    toolBar.add(collapseAllAction);
    toolBar.add(addBundlesAction);
    toolBar.add(new Separator());
  }

  @Override
  public void bundleAdded(final RepositoryPlugin repository, Jar jar, File file) {
    if (viewer != null)
      SWTConcurrencyUtil.execForControl(
          viewer.getControl(),
          true,
          new Runnable() {
            @Override
            public void run() {
              viewer.refresh(repository);
            }
          });
  }

  @Override
  public void bundleRemoved(final RepositoryPlugin repository, Jar jar, File file) {
    if (viewer != null)
      SWTConcurrencyUtil.execForControl(
          viewer.getControl(),
          true,
          new Runnable() {
            @Override
            public void run() {
              viewer.refresh(repository);
            }
          });
  }

  @Override
  public void repositoryRefreshed(final RepositoryPlugin repository) {
    if (viewer != null)
      SWTConcurrencyUtil.execForControl(
          viewer.getControl(),
          true,
          new Runnable() {
            @Override
            public void run() {
              viewer.refresh(repository);
            }
          });
  }

  @Override
  public void repositoriesRefreshed() {
    if (viewer != null)
      SWTConcurrencyUtil.execForControl(
          viewer.getControl(),
          true,
          new Runnable() {
            @Override
            public void run() {
              doRefresh();
            }
          });
  }

  /**
   * Handle the drop on targets that understand drops.
   *
   * @param target The current target
   * @param data The transfer data
   * @return true if the data is acceptable, otherwise false
   */
  boolean canDrop(Object target, TransferData data) {
    try {
      Class<?> type = toJavaType(data);
      if (type != null) {
        target.getClass().getMethod(DROP_TARGET, type);
        return true;
      }
    } catch (Exception e) {
      // Ignore
    }
    return false;
  }

  /**
   * Try a drop on the target. A drop is allowed if the target implements a {@code dropTarget}
   * method that returns a boolean.
   *
   * @param target the target being dropped upon
   * @param data the data
   * @return true if dropped and processed, false if not
   */
  boolean performDrop(Object target, TransferData data) {
    try {
      Object java = toJava(data);
      if (java == null) return false;

      Method m = target.getClass().getMethod(DROP_TARGET, java.getClass());
      return (Boolean) m.invoke(target, java);
    } catch (Exception e) {
      return false;
    }
  }

  /**
   * Return the class of the dropped object
   *
   * <pre>
   *    URLTransfer             URI
   *    FileTransfer            File[]
   *    TextTransfer            String
   *    ImageTransfer           ImageData
   * </pre>
   *
   * @param data the dropped object
   * @return the class of the dropped object, or null when it's unknown
   * @throws Exception upon error
   */
  Class<?> toJavaType(TransferData data) throws Exception {
    if (URLTransfer.getInstance().isSupportedType(data)) return URI.class;
    if (FileTransfer.getInstance().isSupportedType(data)) return File[].class;
    if (TextTransfer.getInstance().isSupportedType(data)) return String.class;
    //        if (ImageTransfer.getInstance().isSupportedType(data))
    //            return Image.class;
    return null;
  }

  /**
   * Return a native data type that represents the dropped object
   *
   * <pre>
   *    URLTransfer             URI
   *    FileTransfer            File[]
   *    TextTransfer            String
   *    ImageTransfer           ImageData
   * </pre>
   *
   * @param data the dropped object
   * @return a native data type that represents the dropped object, or null when the data type is
   *     unknown
   * @throws Exception upon error
   */
  Object toJava(TransferData data) throws Exception {
    if (URLTransfer.getInstance().isSupportedType(data))
      return Converter.cnv(URI.class, URLTransfer.getInstance().nativeToJava(data));
    else if (FileTransfer.getInstance().isSupportedType(data)) {
      return Converter.cnv(File[].class, FileTransfer.getInstance().nativeToJava(data));
    } else if (TextTransfer.getInstance().isSupportedType(data)) {
      return TextTransfer.getInstance().nativeToJava(data);
    }
    // Need to write the transfer code since the ImageTransfer turns it into
    // something very Eclipsy
    //        else if (ImageTransfer.getInstance().isSupportedType(data))
    //            return ImageTransfer.getInstance().nativeToJava(data);

    return null;
  }
}