Search in sources :

Example 1 with Pair

use of bndtools.types.Pair in project bndtools by bndtools.

the class RepositoryBundleSelectionPart method createSection.

void createSection(Section section, FormToolkit toolkit) {
    // Toolbar buttons
    ToolBar toolbar = new ToolBar(section, SWT.FLAT);
    section.setTextClient(toolbar);
    fillToolBar(toolbar);
    Composite composite = toolkit.createComposite(section);
    section.setClient(composite);
    table = toolkit.createTable(composite, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER | SWT.H_SCROLL);
    viewer = new TableViewer(table);
    viewer.setContentProvider(new ArrayContentProvider());
    viewer.setLabelProvider(getLabelProvider());
    // Listeners
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            ToolItem remove = getRemoveItemTool();
            if (remove != null)
                remove.setEnabled(isRemovable(event.getSelection()));
        }
    });
    ViewerDropAdapter dropAdapter = new ViewerDropAdapter(viewer) {

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

        @Override
        public boolean validateDrop(Object target, int operation, TransferData transferType) {
            if (FileTransfer.getInstance().isSupportedType(transferType))
                return true;
            if (ResourceTransfer.getInstance().isSupportedType(transferType))
                return true;
            if (URLTransfer.getInstance().isSupportedType(transferType))
                return true;
            ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
            if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) {
                return false;
            }
            Iterator<?> iterator = ((IStructuredSelection) selection).iterator();
            while (iterator.hasNext()) {
                if (!selectionIsDroppable(iterator.next())) {
                    return false;
                }
            }
            return true;
        }

        private boolean selectionIsDroppable(Object element) {
            return element instanceof RepositoryBundle || element instanceof RepositoryBundleVersion || element instanceof ProjectBundle || element instanceof RepositoryResourceElement;
        }

        @Override
        public boolean performDrop(Object data) {
            TransferData transfer = getCurrentEvent().currentDataType;
            if (URLTransfer.getInstance().isSupportedType(transfer)) {
                String urlStr = (String) URLTransfer.getInstance().nativeToJava(transfer);
                return handleURLDrop(urlStr);
            } else if (data instanceof String[]) {
                return handleFileNameDrop((String[]) data);
            } else if (data instanceof IResource[]) {
                return handleResourceDrop((IResource[]) data);
            } else {
                return handleSelectionDrop();
            }
        }

        private boolean handleResourceDrop(IResource[] resources) {
            File[] files = new File[resources.length];
            for (int i = 0; i < resources.length; i++) {
                files[i] = resources[i].getLocation().toFile();
            }
            return handleFileDrop(files);
        }

        private boolean handleFileNameDrop(String[] paths) {
            File[] files = new File[paths.length];
            for (int i = 0; i < paths.length; i++) {
                files[i] = new File(paths[i]);
            }
            return handleFileDrop(files);
        }

        private boolean handleFileDrop(File[] files) {
            if (files.length > 0) {
                BndPreferences prefs = new BndPreferences();
                boolean hideWarning = prefs.getHideWarningExternalFile();
                if (!hideWarning) {
                    MessageDialogWithToggle dialog = MessageDialogWithToggle.openWarning(getSection().getShell(), "Add External Files", "External files cannot be directly added to a project, they must be added to a local repository first.", "Do not show this warning again.", false, null, null);
                    if (Window.CANCEL == dialog.getReturnCode())
                        return false;
                    if (dialog.getToggleState()) {
                        prefs.setHideWarningExternalFile(true);
                    }
                }
                AddFilesToRepositoryWizard wizard = new AddFilesToRepositoryWizard(null, files);
                WizardDialog dialog = new WizardDialog(getSection().getShell(), wizard);
                if (Window.OK == dialog.open()) {
                    List<Pair<String, String>> addingBundles = wizard.getSelectedBundles();
                    List<VersionedClause> addingClauses = new ArrayList<VersionedClause>(addingBundles.size());
                    for (Pair<String, String> addingBundle : addingBundles) {
                        Attrs attribs = new Attrs();
                        attribs.put(Constants.VERSION_ATTRIBUTE, addingBundle.getSecond());
                        addingClauses.add(new VersionedClause(addingBundle.getFirst(), attribs));
                    }
                    handleAdd(addingClauses);
                }
                return true;
            }
            return false;
        }

        private boolean handleSelectionDrop() {
            ISelection selection = LocalSelectionTransfer.getTransfer().getSelection();
            if (selection.isEmpty() || !(selection instanceof IStructuredSelection)) {
                return false;
            }
            List<VersionedClause> adding = new LinkedList<VersionedClause>();
            Iterator<?> iterator = ((IStructuredSelection) selection).iterator();
            while (iterator.hasNext()) {
                Object item = iterator.next();
                if (item instanceof RepositoryBundle) {
                    VersionedClause newClause = RepositoryBundleUtils.convertRepoBundle((RepositoryBundle) item);
                    adding.add(newClause);
                } else if (item instanceof RepositoryBundleVersion) {
                    RepositoryBundleVersion bundleVersion = (RepositoryBundleVersion) item;
                    VersionedClause newClause = RepositoryBundleUtils.convertRepoBundleVersion(bundleVersion, phase);
                    adding.add(newClause);
                } else if (item instanceof RepositoryResourceElement) {
                    RepositoryResourceElement elt = (RepositoryResourceElement) item;
                    VersionedClause newClause = RepositoryBundleUtils.convertRepoBundleVersion(elt.getRepositoryBundleVersion(), phase);
                    adding.add(newClause);
                }
            }
            handleAdd(adding);
            return true;
        }

        private boolean handleURLDrop(String urlStr) {
            try {
                URI uri = new URI(sanitizeUrl(urlStr));
                AddJpmDependenciesWizard wizard = new AddJpmDependenciesWizard(uri);
                WizardDialog dialog = new WizardDialog(getSection().getShell(), wizard);
                if (dialog.open() == Window.OK) {
                    Set<ResourceDescriptor> resources = wizard.getResult();
                    List<VersionedClause> newBundles = new ArrayList<VersionedClause>(resources.size());
                    for (ResourceDescriptor resource : resources) {
                        Attrs attrs = new Attrs();
                        attrs.put(Constants.VERSION_ATTRIBUTE, resource.version != null ? resource.version.toString() : Version.emptyVersion.toString());
                        VersionedClause clause = new VersionedClause(resource.bsn, attrs);
                        newBundles.add(clause);
                    }
                    handleAdd(newBundles);
                    return true;
                }
                return false;
            } catch (URISyntaxException e) {
                MessageDialog.openError(getSection().getShell(), "Error", "The dropped URL was invalid: " + urlStr);
                return false;
            }
        }

        private String sanitizeUrl(String urlStr) {
            int newline = urlStr.indexOf('\n');
            if (newline > -1)
                return urlStr.substring(0, newline).trim();
            return urlStr;
        }

        private void handleAdd(Collection<VersionedClause> newClauses) {
            if (newClauses == null || newClauses.isEmpty())
                return;
            List<VersionedClause> toAdd = new LinkedList<VersionedClause>();
            for (VersionedClause newClause : newClauses) {
                boolean found = false;
                for (ListIterator<VersionedClause> iter = bundles.listIterator(); iter.hasNext(); ) {
                    VersionedClause existing = iter.next();
                    if (newClause.getName().equals(existing.getName())) {
                        int index = iter.previousIndex();
                        iter.set(newClause);
                        viewer.replace(newClause, index);
                        found = true;
                        break;
                    }
                }
                if (!found)
                    toAdd.add(newClause);
            }
            bundles.addAll(toAdd);
            viewer.add(toAdd.toArray());
            markDirty();
        }
    };
    dropAdapter.setFeedbackEnabled(false);
    dropAdapter.setExpandEnabled(false);
    viewer.addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, new Transfer[] { LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance(), ResourceTransfer.getInstance(), URLTransfer.getInstance() }, dropAdapter);
    table.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.character == SWT.DEL) {
                doRemove();
            } else if (e.character == '+') {
                doAdd();
            }
        }
    });
    // Layout
    GridLayout layout = new GridLayout(1, false);
    layout.horizontalSpacing = 0;
    layout.verticalSpacing = 0;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    composite.setLayout(layout);
    GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    gd.widthHint = 50;
    gd.heightHint = getTableHeightHint();
    table.setLayoutData(gd);
}
Also used : RepositoryBundle(bndtools.model.repo.RepositoryBundle) RepositoryBundleVersion(bndtools.model.repo.RepositoryBundleVersion) BndPreferences(bndtools.preferences.BndPreferences) VersionedClause(aQute.bnd.build.model.clauses.VersionedClause) KeyAdapter(org.eclipse.swt.events.KeyAdapter) ArrayList(java.util.ArrayList) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) ProjectBundle(bndtools.model.repo.ProjectBundle) MessageDialogWithToggle(org.eclipse.jface.dialogs.MessageDialogWithToggle) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) DropTargetEvent(org.eclipse.swt.dnd.DropTargetEvent) LinkedList(java.util.LinkedList) Collection(java.util.Collection) File(java.io.File) AddFilesToRepositoryWizard(bndtools.wizards.workspace.AddFilesToRepositoryWizard) Attrs(aQute.bnd.header.Attrs) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) KeyEvent(org.eclipse.swt.events.KeyEvent) GridLayout(org.eclipse.swt.layout.GridLayout) TransferData(org.eclipse.swt.dnd.TransferData) ISelection(org.eclipse.jface.viewers.ISelection) ToolItem(org.eclipse.swt.widgets.ToolItem) Pair(bndtools.types.Pair) Composite(org.eclipse.swt.widgets.Composite) ViewerDropAdapter(org.eclipse.jface.viewers.ViewerDropAdapter) RepositoryResourceElement(bndtools.model.repo.RepositoryResourceElement) ToolBar(org.eclipse.swt.widgets.ToolBar) ArrayContentProvider(org.eclipse.jface.viewers.ArrayContentProvider) GridData(org.eclipse.swt.layout.GridData) AddJpmDependenciesWizard(org.bndtools.core.ui.wizards.jpm.AddJpmDependenciesWizard) TableViewer(org.eclipse.jface.viewers.TableViewer) WizardDialog(org.eclipse.jface.wizard.WizardDialog) IResource(org.eclipse.core.resources.IResource) ResourceDescriptor(aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor)

Example 2 with Pair

use of bndtools.types.Pair in project bndtools by bndtools.

the class AddFilesToRepositoryWizard method performFinishAddFiles.

private IStatus performFinishAddFiles(IProgressMonitor monitor) {
    MultiStatus status = new MultiStatus(Plugin.PLUGIN_ID, 0, "Failed to install one or more bundles", null);
    List<File> files = fileSelectionPage.getFiles();
    selectedBundles = new LinkedList<Pair<String, String>>();
    monitor.beginTask("Processing files", files.size());
    for (File file : files) {
        monitor.subTask(file.getName());
        try (Jar jar = new Jar(file)) {
            jar.setDoNotTouchManifest();
            Attributes mainAttribs = jar.getManifest().getMainAttributes();
            String bsn = BundleUtils.getBundleSymbolicName(mainAttribs);
            String version = mainAttribs.getValue(Constants.BUNDLE_VERSION);
            if (version == null)
                version = "0";
            selectedBundles.add(Pair.newInstance(bsn, version));
        } catch (Exception e) {
            status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format("Failed to analyse JAR: {0}", file.getPath()), e));
            continue;
        }
        try {
            RepositoryPlugin.PutResult result = repository.put(new BufferedInputStream(IO.stream(file)), new RepositoryPlugin.PutOptions());
            if (result.artifact != null && result.artifact.getScheme().equals("file")) {
                File newFile = new File(result.artifact);
                RefreshFileJob refreshJob = new RefreshFileJob(newFile, false);
                if (refreshJob.needsToSchedule())
                    refreshJob.schedule();
            }
        } catch (Exception e) {
            status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, MessageFormat.format("Failed to add JAR to repository: {0}", file.getPath()), e));
            continue;
        }
        monitor.worked(1);
    }
    return status;
}
Also used : MultiStatus(org.eclipse.core.runtime.MultiStatus) Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) Attributes(java.util.jar.Attributes) MultiStatus(org.eclipse.core.runtime.MultiStatus) RepositoryPlugin(aQute.bnd.service.RepositoryPlugin) RefreshFileJob(bndtools.central.RefreshFileJob) CoreException(org.eclipse.core.runtime.CoreException) BufferedInputStream(java.io.BufferedInputStream) Jar(aQute.bnd.osgi.Jar) File(java.io.File) Pair(bndtools.types.Pair)

Example 3 with Pair

use of bndtools.types.Pair in project bndtools by bndtools.

the class AddFilesToRepositoryWizardPage method createControl.

@Override
@SuppressWarnings("unused")
public void createControl(Composite parent) {
    setTitle("Add Files to Repository");
    Composite composite = new Composite(parent, SWT.NONE);
    new Label(composite, SWT.NONE).setText("Selected files:");
    // Spacer;
    new Label(composite, SWT.NONE);
    Table table = new Table(composite, SWT.FULL_SELECTION | SWT.MULTI | SWT.BORDER);
    table.setLinesVisible(true);
    table.setHeaderVisible(true);
    TableColumn col;
    col = new TableColumn(table, SWT.NONE);
    col.setText("Path");
    col.setWidth(300);
    col = new TableColumn(table, SWT.NONE);
    col.setText("Bundle Name/Version");
    col.setWidth(300);
    viewer = new TableViewer(table);
    viewer.setContentProvider(new ArrayContentProvider());
    viewer.setLabelProvider(new StyledCellLabelProvider() {

        @Override
        public void update(ViewerCell cell) {
            File file = (File) cell.getElement();
            Pair<String, String> bundleId = bsnMap.get(file);
            int index = cell.getColumnIndex();
            if (index == 0) {
                if (bundleId == null) {
                    cell.setImage(errorImg);
                } else {
                    cell.setImage(jarImg);
                }
                StyledString label = new StyledString(file.getName());
                String parentPath = file.getParent();
                if (parentPath != null) {
                    label.append(" (" + parentPath + ")", StyledString.QUALIFIER_STYLER);
                }
                cell.setText(label.getString());
                cell.setStyleRanges(label.getStyleRanges());
            } else if (index == 1) {
                if (bundleId == null) {
                    cell.setImage(errorImg);
                    cell.setText("Not a JAR file");
                } else {
                    String bsn = bundleId.getFirst();
                    String version = bundleId.getSecond();
                    if (bsn == null) {
                        cell.setImage(warnImg);
                        cell.setText("Not a Bundle JAR");
                    } else {
                        cell.setImage(okayImg);
                        StyledString styledString = new StyledString(bsn);
                        if (version != null) {
                            styledString.append(" [" + version + "]", StyledString.COUNTER_STYLER);
                            cell.setText(styledString.getString());
                            cell.setStyleRanges(styledString.getStyleRanges());
                        }
                    }
                }
            }
        }
    });
    viewer.setInput(files);
    validate();
    final Button btnAdd = new Button(composite, SWT.PUSH);
    btnAdd.setText("Add JARs...");
    final Button btnAddExternal = new Button(composite, SWT.PUSH);
    btnAddExternal.setText("Add External JARs...");
    final Button btnRemove = new Button(composite, SWT.NONE);
    btnRemove.setText("Remove");
    btnRemove.setEnabled(false);
    // LISTENERS
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            btnRemove.setEnabled(!viewer.getSelection().isEmpty());
        }
    });
    btnAdd.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            doAdd();
        }
    });
    btnAddExternal.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            doAddExternal();
        }
    });
    btnRemove.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            doRemove();
        }
    });
    // LAYOUT
    composite.setLayout(new GridLayout(2, false));
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 4));
    btnAdd.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    btnRemove.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    setControl(composite);
}
Also used : StyledCellLabelProvider(org.eclipse.jface.viewers.StyledCellLabelProvider) Table(org.eclipse.swt.widgets.Table) Composite(org.eclipse.swt.widgets.Composite) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Label(org.eclipse.swt.widgets.Label) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) StyledString(org.eclipse.jface.viewers.StyledString) StyledString(org.eclipse.jface.viewers.StyledString) TableColumn(org.eclipse.swt.widgets.TableColumn) ViewerCell(org.eclipse.jface.viewers.ViewerCell) GridLayout(org.eclipse.swt.layout.GridLayout) Button(org.eclipse.swt.widgets.Button) ArrayContentProvider(org.eclipse.jface.viewers.ArrayContentProvider) SelectionEvent(org.eclipse.swt.events.SelectionEvent) GridData(org.eclipse.swt.layout.GridData) TableViewer(org.eclipse.jface.viewers.TableViewer) IFile(org.eclipse.core.resources.IFile) File(java.io.File) Pair(bndtools.types.Pair)

Aggregations

Pair (bndtools.types.Pair)3 File (java.io.File)3 ArrayContentProvider (org.eclipse.jface.viewers.ArrayContentProvider)2 ISelectionChangedListener (org.eclipse.jface.viewers.ISelectionChangedListener)2 SelectionChangedEvent (org.eclipse.jface.viewers.SelectionChangedEvent)2 TableViewer (org.eclipse.jface.viewers.TableViewer)2 VersionedClause (aQute.bnd.build.model.clauses.VersionedClause)1 Attrs (aQute.bnd.header.Attrs)1 Jar (aQute.bnd.osgi.Jar)1 RepositoryPlugin (aQute.bnd.service.RepositoryPlugin)1 ResourceDescriptor (aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor)1 RefreshFileJob (bndtools.central.RefreshFileJob)1 ProjectBundle (bndtools.model.repo.ProjectBundle)1 RepositoryBundle (bndtools.model.repo.RepositoryBundle)1 RepositoryBundleVersion (bndtools.model.repo.RepositoryBundleVersion)1 RepositoryResourceElement (bndtools.model.repo.RepositoryResourceElement)1 BndPreferences (bndtools.preferences.BndPreferences)1 AddFilesToRepositoryWizard (bndtools.wizards.workspace.AddFilesToRepositoryWizard)1 BufferedInputStream (java.io.BufferedInputStream)1 URI (java.net.URI)1