All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.tototec.utils.jface.viewer.SelectionHelper Maven / Gradle / Ivy

The newest version!
package de.tototec.utils.jface.viewer;

import java.util.Optional;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SelectionHelper {

	private final Logger log = LoggerFactory.getLogger(SelectionHelper.class);

	public  Optional getSelected(final ISelectionProvider selectionProvider, final Class type) {
		return getSelected(selectionProvider.getSelection(), type);
	}

	public  Optional getSelected(final ISelection selection, final Class type) {
		if (selection.isEmpty()) {
			return Optional.empty();
		}

		if (!(selection instanceof IStructuredSelection)) {
			log.error("Selection of type {} required, but got: {}.", IStructuredSelection.class.getName(),
					selection.getClass().getName());
			return Optional.empty();
		}

		final IStructuredSelection structSelect = (IStructuredSelection) selection;
		final Object firstElement = structSelect.getFirstElement();
		if (!type.isInstance(firstElement)) {
			log.error("Selection must contain a {}, but has a {}.",
					type.getName(), firstElement.getClass().getName());
			return Optional.empty();
		} else {
			return Optional.of(type.cast(firstElement));
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy