Search in sources :

Example 1 with HaleConnectException

use of eu.esdihumboldt.hale.io.haleconnect.HaleConnectException in project hale by halestudio.

the class HaleConnectLoginContentProvider method run.

/**
 * @see org.eclipse.ui.intro.config.IIntroAction#run(org.eclipse.ui.intro.IIntroSite,
 *      java.util.Properties)
 */
@Override
public void run(IIntroSite site, Properties params) {
    String username = params.getProperty("username", "");
    String password = params.getProperty("password", "");
    String savecreds = params.getProperty("savecreds", "");
    if (username.trim().isEmpty() || password.trim().isEmpty()) {
        // Using MessageDialog to prevent this from cluttering up the logs
        MessageDialog.openWarning(site.getShell(), "Login to hale connect", "You must provide both user name and password to login to hale connect.");
        return;
    }
    HaleConnectService hcs = HaleUI.getServiceProvider().getService(HaleConnectService.class);
    try {
        if (hcs.login(username, password)) {
            if ("true".equalsIgnoreCase(savecreds)) {
                try {
                    HaleConnectUIPlugin.storeUsername(username);
                    HaleConnectUIPlugin.storePassword(password);
                } catch (StorageException e) {
                    log.error("hale connect credentials could not be saved.", e);
                }
            }
            log.userInfo("Login to hale connect successful.");
            // Close and reopen the intro to update the displayed message
            IIntroPart introPart = PlatformUI.getWorkbench().getIntroManager().getIntro();
            if (introPart != null) {
                PlatformUI.getWorkbench().getIntroManager().closeIntro(introPart);
                PlatformUI.getWorkbench().getIntroManager().showIntro(site.getWorkbenchWindow(), false);
            }
        } else {
            log.userWarn("Login to hale connect failed, please check the credentials.");
        }
    } catch (HaleConnectException e) {
        log.userError("An error occurred while trying to login to hale connect", e);
    }
}
Also used : HaleConnectService(eu.esdihumboldt.hale.io.haleconnect.HaleConnectService) IIntroPart(org.eclipse.ui.intro.IIntroPart) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) StorageException(org.eclipse.equinox.security.storage.StorageException)

Example 2 with HaleConnectException

use of eu.esdihumboldt.hale.io.haleconnect.HaleConnectException in project hale by halestudio.

the class HaleConnectPreferencePage method createFieldEditors.

/**
 * Creates the field editors. Field editors are abstractions of the common
 * GUI blocks needed to manipulate various types of preferences. Each field
 * editor knows how to save and restore itself.
 */
@Override
public void createFieldEditors() {
    final HaleConnectService hcs = HaleUI.getServiceProvider().getService(HaleConnectService.class);
    StringFieldEditor usernameEditor = new StringFieldEditor(PreferenceConstants.HALE_CONNECT_USERNAME, "&User name:", getFieldEditorParent());
    addField(usernameEditor);
    usernameEditor.getTextControl(getFieldEditorParent()).addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            clearResult();
        }
    });
    PasswordFieldEditor passwordEditor = new PasswordFieldEditor(PreferenceConstants.SECURE_NODE_NAME, PreferenceConstants.HALE_CONNECT_PASSWORD, // $NON-NLS-1$
    "&Password:", getFieldEditorParent());
    addField(passwordEditor);
    passwordEditor.getTextControl().addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            clearResult();
        }
    });
    Link link = new Link(getFieldEditorParent(), SWT.NONE);
    link.setText("Not registered yet? <a href=\"https://www.haleconnect.com\">Create an account.</a>");
    link.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            try {
                PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
            } catch (PartInitException | MalformedURLException e1) {
                setResultError("Error opening external browser. Please visit https://www.haleconnect.com to register.");
            }
        }
    });
    link.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
    resultLabel = new Label(getFieldEditorParent(), SWT.NONE);
    resultLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
    clearResult();
    Button validate = new Button(getFieldEditorParent(), SWT.NONE);
    validate.setText("Validate credentials");
    Button clear = new Button(getFieldEditorParent(), SWT.NONE);
    clear.setText("Clear credentials");
    validate.addSelectionListener(new SelectionAdapter() {

        /**
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            performApply();
            try {
                String username = HaleConnectUIPlugin.getStoredUsername();
                String password = HaleConnectUIPlugin.getStoredPassword();
                if (hcs.verifyCredentials(username, password)) {
                    setResultSuccess("Credentials are valid.");
                } else {
                    setResultError("Credentials were rejected.");
                }
            } catch (HaleConnectException ex) {
                log.userError("Error accessing hale connect", ex);
            } catch (StorageException ex) {
                log.userError("Error accessing secure storage", ex);
            }
        }
    });
    clear.addSelectionListener(new SelectionAdapter() {

        /**
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (MessageDialog.openConfirm(getShell(), "Remove credentials", "This will remove the stored credentials and log you out.")) {
                usernameEditor.setStringValue("");
                passwordEditor.getTextControl().setText("");
                performApply();
                clearResult();
                hcs.clearSession();
                log.userInfo("Credentials removed.");
            }
        }
    });
    if (hcs.isLoggedIn()) {
        setResult(MessageFormat.format("Logged in as \"{0}\"", hcs.getSession().getUsername()));
    }
}
Also used : ModifyListener(org.eclipse.swt.events.ModifyListener) PasswordFieldEditor(eu.esdihumboldt.hale.ui.util.components.PasswordFieldEditor) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Label(org.eclipse.swt.widgets.Label) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) URL(java.net.URL) StringFieldEditor(org.eclipse.jface.preference.StringFieldEditor) ModifyEvent(org.eclipse.swt.events.ModifyEvent) HaleConnectService(eu.esdihumboldt.hale.io.haleconnect.HaleConnectService) Button(org.eclipse.swt.widgets.Button) SelectionEvent(org.eclipse.swt.events.SelectionEvent) GridData(org.eclipse.swt.layout.GridData) StorageException(org.eclipse.equinox.security.storage.StorageException) Link(org.eclipse.swt.widgets.Link)

Example 3 with HaleConnectException

use of eu.esdihumboldt.hale.io.haleconnect.HaleConnectException in project hale by halestudio.

the class ChooseHaleConnectProjectWizardPage method createContent.

/**
 * @see eu.esdihumboldt.hale.ui.util.wizard.ConfigurationWizardPage#createContent(org.eclipse.swt.widgets.Composite)
 */
@Override
protected void createContent(Composite parent) {
    Composite page = new Composite(parent, SWT.NONE);
    page.setLayout(new GridLayout(4, false));
    keywordFilter = new Text(page, SWT.SEARCH | SWT.ICON_SEARCH | SWT.BORDER | SWT.ICON_CANCEL);
    keywordFilter.setMessage("Enter search text here...");
    GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(keywordFilter);
    ownerFilter = new ComboViewer(page);
    GridDataFactory.fillDefaults().grab(false, false).applyTo(ownerFilter.getControl());
    ownerFilter.setContentProvider(new IStructuredContentProvider() {

        @Override
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            new Object();
        }

        @Override
        public void dispose() {
        // 
        }

        @Override
        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof List<?>) {
                List<?> elements = (List<?>) inputElement;
                return elements.toArray();
            } else if (inputElement instanceof Object[]) {
                return (Object[]) inputElement;
            }
            return new Object[] {};
        }
    });
    ownerFilter.setLabelProvider(new LabelProvider() {

        @Override
        public String getText(Object element) {
            if (element instanceof OwnerFilterEntry) {
                return ((OwnerFilterEntry) element).getLabel();
            }
            return super.getText(element);
        }
    });
    List<OwnerFilterEntry> availableFilters = new ArrayList<>();
    availableFilters.add(NULL_FILTER);
    availableFilters.add(new OwnerFilterEntry(new Owner[] { new Owner(OwnerType.USER, haleConnect.getSession().getUserId()) }, "My projects"));
    List<Owner> orgs = new ArrayList<>();
    for (String orgId : haleConnect.getSession().getOrganisationIds()) {
        orgs.add(new Owner(OwnerType.ORGANISATION, orgId));
    }
    if (!orgs.isEmpty()) {
        availableFilters.add(new OwnerFilterEntry(orgs.toArray(new Owner[] {}), "My organisations' projects"));
    }
    ownerFilter.setInput(availableFilters);
    ownerFilter.setSelection(new StructuredSelection(NULL_FILTER));
    Composite tableComposite = new Composite(page, SWT.NONE);
    TableColumnLayout columnLayout = new TableColumnLayout();
    tableComposite.setLayout(columnLayout);
    projects = new TableViewer(tableComposite, SWT.V_SCROLL | SWT.BORDER | SWT.H_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION);
    projects.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            update();
        }
    });
    TableViewerColumn nameColumn = new TableViewerColumn(projects, SWT.LEAD);
    nameColumn.getColumn().setText("Project name");
    nameColumn.setLabelProvider(new ColumnLabelProvider() {

        /**
         * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object)
         */
        @Override
        public String getText(Object element) {
            if (element instanceof HaleConnectProjectInfo) {
                return ((HaleConnectProjectInfo) element).getName();
            }
            return element.toString();
        }
    });
    columnLayout.setColumnData(nameColumn.getColumn(), new ColumnWeightData(45, 200, true));
    TableViewerColumn authorColumn = new TableViewerColumn(projects, SWT.LEAD);
    authorColumn.getColumn().setText("Author");
    authorColumn.setLabelProvider(new ColumnLabelProvider() {

        /**
         * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object)
         */
        @Override
        public String getText(Object element) {
            if (element instanceof HaleConnectProjectInfo) {
                return ((HaleConnectProjectInfo) element).getAuthor();
            }
            return element.toString();
        }
    });
    columnLayout.setColumnData(authorColumn.getColumn(), new ColumnWeightData(20, 50, true));
    TableViewerColumn ownerColumn = new TableViewerColumn(projects, SWT.LEAD);
    ownerColumn.getColumn().setText("Owner");
    ownerColumn.setLabelProvider(new ColumnLabelProvider() {

        /**
         * @see org.eclipse.jface.viewers.ColumnLabelProvider#getText(java.lang.Object)
         */
        @Override
        public String getText(Object element) {
            if (element instanceof HaleConnectProjectInfo) {
                Owner owner = ((HaleConnectProjectInfo) element).getOwner();
                if (owner.isUser()) {
                    try {
                        HaleConnectUserInfo user = haleConnect.getUserInfo(owner.getId());
                        if (!StringUtils.isEmpty(user.getFullName())) {
                            return user.getFullName();
                        } else if (!StringUtils.isEmpty(user.getScreenName())) {
                            return user.getScreenName();
                        } else {
                            return MessageFormat.format("<user {0}>", user.getUserId());
                        }
                    } catch (HaleConnectException e) {
                        log.error(e.getMessage(), e);
                        return MessageFormat.format("<user {0}>", owner.getId());
                    }
                } else if (owner.isOrganisation()) {
                    try {
                        return haleConnect.getOrganisationInfo(owner.getId()).getName();
                    } catch (HaleConnectException e) {
                        log.error(e.getMessage(), e);
                        return MessageFormat.format("<organisation {0}>", owner.getId());
                    }
                } else {
                    return "<unknown owner type> ID: " + owner.getId();
                }
            }
            return element.toString();
        }
    });
    columnLayout.setColumnData(ownerColumn.getColumn(), new ColumnWeightData(35, 100, true));
    final Table projectsTable = projects.getTable();
    projectsTable.setHeaderVisible(true);
    projectsTable.setLinesVisible(true);
    tableComposite.setLayoutData(GridDataFactory.fillDefaults().span(4, 1).grab(true, true).create());
    projects.setContentProvider(ArrayContentProvider.getInstance());
    populateProjects();
    final ProjectFilter projectFilter = new ProjectFilter(projects);
    projects.addFilter(projectFilter);
    ownerFilter.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            if (event.getSelection() instanceof StructuredSelection) {
                StructuredSelection selection = (StructuredSelection) event.getSelection();
                if (selection.getFirstElement() instanceof OwnerFilterEntry) {
                    OwnerFilterEntry selectedFilter = (OwnerFilterEntry) selection.getFirstElement();
                    if (selectedFilter.equals(NULL_FILTER)) {
                        projectFilter.clearOwnerFilter();
                    } else {
                        projectFilter.filterByOwners(Arrays.asList(selectedFilter.getOwner()));
                    }
                }
            }
        }
    });
    keywordFilter.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            projectFilter.setSearchText(keywordFilter.getText());
        }
    });
    final Button refresh = new Button(page, SWT.FLAT);
    refresh.setText("Refresh");
    GridDataFactory.fillDefaults().span(1, 1).grab(false, false).applyTo(refresh);
    refresh.addSelectionListener(new SelectionAdapter() {

        /**
         * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
         */
        @Override
        public void widgetSelected(SelectionEvent e) {
            populateProjects();
        }
    });
    ownerFilter.getControl().setFocus();
    setControl(page);
    update();
}
Also used : ColumnWeightData(org.eclipse.jface.viewers.ColumnWeightData) Owner(eu.esdihumboldt.hale.io.haleconnect.Owner) ModifyListener(org.eclipse.swt.events.ModifyListener) ArrayList(java.util.ArrayList) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) HaleConnectUserInfo(eu.esdihumboldt.hale.io.haleconnect.HaleConnectUserInfo) TableViewer(org.eclipse.jface.viewers.TableViewer) ComboViewer(org.eclipse.jface.viewers.ComboViewer) Viewer(org.eclipse.jface.viewers.Viewer) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) ColumnLabelProvider(org.eclipse.jface.viewers.ColumnLabelProvider) GridLayout(org.eclipse.swt.layout.GridLayout) ModifyEvent(org.eclipse.swt.events.ModifyEvent) TableColumnLayout(org.eclipse.jface.layout.TableColumnLayout) Button(org.eclipse.swt.widgets.Button) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ArrayList(java.util.ArrayList) List(java.util.List) TableViewerColumn(org.eclipse.jface.viewers.TableViewerColumn) Table(org.eclipse.swt.widgets.Table) Composite(org.eclipse.swt.widgets.Composite) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) Text(org.eclipse.swt.widgets.Text) HaleConnectProjectInfo(eu.esdihumboldt.hale.io.haleconnect.HaleConnectProjectInfo) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) ComboViewer(org.eclipse.jface.viewers.ComboViewer) IStructuredContentProvider(org.eclipse.jface.viewers.IStructuredContentProvider) ColumnLabelProvider(org.eclipse.jface.viewers.ColumnLabelProvider) LabelProvider(org.eclipse.jface.viewers.LabelProvider) TableViewer(org.eclipse.jface.viewers.TableViewer)

Example 4 with HaleConnectException

use of eu.esdihumboldt.hale.io.haleconnect.HaleConnectException in project hale by halestudio.

the class HaleConnectServiceImpl method testProjectPermission.

@Override
public boolean testProjectPermission(String permission, Owner owner, String projectId) throws HaleConnectException {
    PermissionsApi api = ProjectStoreHelper.getPermissionsApi(this, this.getSession().getToken());
    String combinedBucketId = MessageFormat.format("{0}.{1}.{2}", owner.getType().getJsonValue(), owner.getId(), projectId);
    try {
        api.testBucketPermission(permission, combinedBucketId);
    } catch (com.haleconnect.api.projectstore.v1.ApiException e) {
        if (e.getCode() == 403) {
            // not allowed
            return false;
        }
        // other codes indicate client error or server-side exception
        throw new HaleConnectException(e.getMessage(), e);
    }
    return true;
}
Also used : PermissionsApi(com.haleconnect.api.projectstore.v1.api.PermissionsApi) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException)

Example 5 with HaleConnectException

use of eu.esdihumboldt.hale.io.haleconnect.HaleConnectException in project hale by halestudio.

the class HaleConnectServiceImpl method createUploadFileCallback.

private ApiCallback<Feedback> createUploadFileCallback(final SettableFuture<Boolean> future, final ProgressIndicator progress, final File file, final int totalWork) {
    return new ApiCallback<Feedback>() {

        AtomicLong chunkWritten = new AtomicLong(0);

        AtomicLong bytesReported = new AtomicLong(0);

        @Override
        public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {
        // not required
        }

        @Override
        public void onFailure(com.haleconnect.api.projectstore.v1.ApiException e, int statusCode, Map<String, List<String>> responseHeaders) {
            progress.end();
            future.setException(new HaleConnectException(e.getMessage(), e, statusCode, responseHeaders));
        }

        @Override
        public void onSuccess(Feedback result, int statusCode, Map<String, List<String>> responseHeaders) {
            if (result.getError()) {
                log.error(MessageFormat.format("Error uploading project file \"{0}\": {1}", file.getAbsolutePath(), result.getMessage()));
                future.set(false);
            } else {
                future.set(true);
            }
            progress.end();
        }

        @Override
        public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {
            // bytesWritten contains the accumulated amount of bytes written
            if (totalWork != ProgressIndicator.UNKNOWN) {
                // Wait until at least 1 KiB was written
                long chunk = chunkWritten.get();
                chunk += bytesWritten - bytesReported.get();
                if (chunk >= 1024) {
                    long workToReport = chunk >> 10;
                    // cannot overflow, total size in KiB
                    // is guaranteed to be < Integer.MAX_VALUE
                    progress.advance(Math.toIntExact(workToReport));
                    chunk -= workToReport << 10;
                // chunkWritten now always < 1024
                }
                chunkWritten.set(chunk);
                bytesReported.set(bytesWritten);
            }
        }
    };
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) ApiCallback(com.haleconnect.api.projectstore.v1.ApiCallback) Feedback(com.haleconnect.api.projectstore.v1.model.Feedback) HaleConnectException(eu.esdihumboldt.hale.io.haleconnect.HaleConnectException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ApiException(com.haleconnect.api.user.v1.ApiException)

Aggregations

HaleConnectException (eu.esdihumboldt.hale.io.haleconnect.HaleConnectException)19 Feedback (com.haleconnect.api.projectstore.v1.model.Feedback)5 ApiException (com.haleconnect.api.user.v1.ApiException)5 HaleConnectProjectInfo (eu.esdihumboldt.hale.io.haleconnect.HaleConnectProjectInfo)5 HaleConnectService (eu.esdihumboldt.hale.io.haleconnect.HaleConnectService)5 HaleConnectUserInfo (eu.esdihumboldt.hale.io.haleconnect.HaleConnectUserInfo)5 HaleConnectOrganisationInfo (eu.esdihumboldt.hale.io.haleconnect.HaleConnectOrganisationInfo)4 Owner (eu.esdihumboldt.hale.io.haleconnect.Owner)4 BucketsApi (com.haleconnect.api.projectstore.v1.api.BucketsApi)3 FilesApi (com.haleconnect.api.projectstore.v1.api.FilesApi)3 UsersApi (com.haleconnect.api.user.v1.api.UsersApi)3 UserInfo (com.haleconnect.api.user.v1.model.UserInfo)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Map (java.util.Map)3 ApiCallback (com.haleconnect.api.projectstore.v1.ApiCallback)2 PermissionsApi (com.haleconnect.api.projectstore.v1.api.PermissionsApi)2 BucketIdent (com.haleconnect.api.projectstore.v1.model.BucketIdent)2 NewBucket (com.haleconnect.api.projectstore.v1.model.NewBucket)2 LoginApi (com.haleconnect.api.user.v1.api.LoginApi)2