{
            // Nothing to dispose
        }

package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import org.locationtech.udig.catalog.CatalogPlugin;
import org.locationtech.udig.catalog.ICatalog;
import org.locationtech.udig.catalog.IResolve;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.locationtech.udig.catalog.jgrass.JGrassPlugin;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassService;

/**
 * <p>
 * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a
 * mapset is selected it is passed to the WidgetObservers that are registered with this class.
 * </p>
 *
 * @author Andrea Antonello - www.hydrologis.com
 * @since 1.1.0
 */
public class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {

    private final HashMap<String, JGrassMapsetGeoResource> itemsMap = new HashMap<String, JGrassMapsetGeoResource>();

    private LabelProvider labelProvider = null;

    private List<JGrassMapsetGeoResource> itemLayers;

    /**
     * @param parent
     * @param style
     * @param selectionStyle the tree selection style (single or multiple)
     * @param mapType the types of map to be filtered out (ex.
     *        {@link FeatureLayerTreeViewer.SHAPELAYER})
     */
    public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {
        super(parent, style);
        setLayout(new GridLayout(1, false));
        GridData gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.grabExcessVerticalSpace = true;
        setLayoutData(gridData);
        // Create the tree viewer to display the file tree
        PatternFilter patternFilter = new PatternFilter();
        final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);
        final TreeViewer tv = filter.getViewer();
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new ContentProvider());
        labelProvider = new LabelProvider();
        tv.setLabelProvider(labelProvider);
        // pass a non-null that will be ignored //$NON-NLS-1$
        tv.setInput("dummy");
        tv.addSelectionChangedListener(this);
    }

    public void selectionChanged(SelectionChangedEvent event) {
        // if the selection is empty clear the label
        if (event.getSelection().isEmpty()) {
            return;
        }
        if (event.getSelection() instanceof IStructuredSelection) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Vector<String> itemNames = new Vector<String>();
            for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {
                Object domain = iterator.next();
                String value = labelProvider.getText(domain);
                itemNames.add(value);
            }
            itemLayers = new ArrayList<JGrassMapsetGeoResource>();
            for (String name : itemNames) {
                JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);
                if (tmpLayer != null) {
                    itemLayers.add(tmpLayer);
                }
            }
        }
    }

    /**
     * This class provides the content for the tree in FileTree
     */
    private class ContentProvider implements ITreeContentProvider {

        /**
         * Gets the children of the specified object
         *
         * @param arg0 the parent object
         * @return Object[]
         */
        public Object[] getChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                JGrassService map = (JGrassService) arg0;
                List<IResolve> layers = null;
                try {
                    layers = map.members(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (layers == null)
                    return null;
                return filteredLayers(layers);
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            }
            return null;
        }

        private Object[] filteredLayers(List<IResolve> layers) {
            Vector<JGrassMapsetGeoResource> filteredLayers = new Vector<JGrassMapsetGeoResource>();
            for (IResolve layer : layers) {
                if (layer instanceof JGrassMapsetGeoResource) {
                    filteredLayers.add((JGrassMapsetGeoResource) layer);
                    itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);
                }
            }
            /*
             * now let's sort them for nice visualization
             */
            HashMap<String, JGrassMapsetGeoResource> tmp = new HashMap<String, JGrassMapsetGeoResource>();
            for (JGrassMapsetGeoResource resource : filteredLayers) {
                tmp.put(resource.getTitle(), resource);
            }
            Map<String, JGrassMapsetGeoResource> sortedMap = new TreeMap<String, JGrassMapsetGeoResource>(tmp);
            filteredLayers.removeAllElements();
            for (JGrassMapsetGeoResource map : sortedMap.values()) {
                filteredLayers.add(map);
            }
            return filteredLayers.toArray();
        }

        /**
         * Gets the parent of the specified object
         *
         * @param arg0 the object
         * @return Object
         */
        public Object getParent(Object arg0) {
            if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            } else if (arg0 instanceof JGrassMapGeoResource) {
                try {
                    return ((JGrassMapGeoResource) arg0).parent(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        /**
         * Returns whether the passed object has children
         *
         * @param arg0 the parent object
         * @return boolean
         */
        public boolean hasChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return true;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return false;
            }
            return false;
        }

        /**
         * Gets the root element(s) of the tree
         *
         * @param arg0 the input data
         * @return Object[]
         */
        public Object[] getElements(Object arg0) {
            // add the service to the catalog
            ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
            try {
                ArrayList<IResolve> finalCatalogMembers = new ArrayList<IResolve>();
                List<? extends IResolve> allCatalogMembers = catalog.members(null);
                for (IResolve resolve : allCatalogMembers) {
                    if (resolve instanceof JGrassService) {
                        finalCatalogMembers.add(resolve);
                    }
                }
                if (finalCatalogMembers.size() > 0) {
                    return finalCatalogMembers.toArray();
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * Disposes any created resources
         */
        public void dispose()

        /**
         * Called when the input changes
         *
         * @param arg0 the viewer
         * @param arg1 the old input
         * @param arg2 the new input
         */
        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
            // Nothing to change
        }
    }

    /**
     * This class provides the labels for the file tree
     */
    private static class LabelProvider implements ILabelProvider {

        // The listeners
        private final List<ILabelProviderListener> listeners;

        // Images for tree nodes
        private final Image rasterMaps;

        private final Image mainRasterMaps;

        // Label provider state: preserve case of file names/directories
        /**
         * Constructs a FileTreeLabelProvider
         */
        public LabelProvider() {
            // Create the list to hold the listeners
            listeners = new ArrayList<ILabelProviderListener>();
            // Create the images
            mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrassloc_obj.gif").createImage();
            rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrass_obj.gif").createImage();
        }

        // * Sets the preserve case attribute
        // * @param preserveCase the preserve case attribute
        // // Since this attribute affects how the labels are computed,
        // // notify all the listeners of the change.
        /**
         * Gets the image to display for a node in the tree
         *
         * @param arg0 the node
         * @return Image
         */
        public Image getImage(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return mainRasterMaps;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return rasterMaps;
            } else {
                return null;
            }
        }

        /**
         * Gets the text to display for a node in the tree
         *
         * @param arg0 the node
         * @return String
         */
        public String getText(Object arg0) {
            String text = null;
            try {
                if (arg0 instanceof JGrassMapsetGeoResource) {
                    text = ((JGrassMapsetGeoResource) arg0).getTitle();
                } else if (arg0 instanceof JGrassService) {
                    text = ((JGrassService) arg0).getInfo(null).getTitle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return text;
        }

        /**
         * Adds a listener to this label provider
         *
         * @param arg0 the listener
         */
        public void addListener(ILabelProviderListener arg0) {
            listeners.add(arg0);
        }

        /**
         * Called when this LabelProvider is being disposed
         */
        public void dispose() {
            // Dispose the images
            if (rasterMaps != null)
                rasterMaps.dispose();
        }

        /**
         * Returns whether changes to the specified property on the specified element would affect
         * the label for the element
         *
         * @param arg0 the element
         * @param arg1 the property
         * @return boolean
         */
        public boolean isLabelProperty(Object arg0, String arg1) {
            return false;
        }

        /**
         * Removes the listener
         *
         * @param arg0 the listener to remove
         */
        public void removeListener(ILabelProviderListener arg0) {
            listeners.remove(arg0);
        }
    }

    public List<JGrassMapsetGeoResource> getSelectedLayers() {
        return itemLayers;
    }

    public int getType() {
        return 0;
    }
}


package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import org.locationtech.udig.catalog.CatalogPlugin;
import org.locationtech.udig.catalog.ICatalog;
import org.locationtech.udig.catalog.IResolve;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.locationtech.udig.catalog.jgrass.JGrassPlugin;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassService;

/**
 * <p>
 * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a
 * mapset is selected it is passed to the WidgetObservers that are registered with this class.
 * </p>
 *
 * @author Andrea Antonello - www.hydrologis.com
 * @since 1.1.0
 */
public class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {

    private final HashMap<String, JGrassMapsetGeoResource> itemsMap = new HashMap<String, JGrassMapsetGeoResource>();

    private LabelProvider labelProvider = null;

    private List<JGrassMapsetGeoResource> itemLayers;

    /**
     * @param parent
     * @param style
     * @param selectionStyle the tree selection style (single or multiple)
     * @param mapType the types of map to be filtered out (ex.
     *        {@link FeatureLayerTreeViewer.SHAPELAYER})
     */
    public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {
        super(parent, style);
        setLayout(new GridLayout(1, false));
        GridData gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.grabExcessVerticalSpace = true;
        setLayoutData(gridData);
        // Create the tree viewer to display the file tree
        PatternFilter patternFilter = new PatternFilter();
        final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);
        final TreeViewer tv = filter.getViewer();
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new ContentProvider());
        labelProvider = new LabelProvider();
        tv.setLabelProvider(labelProvider);
        // pass a non-null that will be ignored //$NON-NLS-1$
        tv.setInput("dummy");
        tv.addSelectionChangedListener(this);
    }

    public void selectionChanged(SelectionChangedEvent event) {
        // if the selection is empty clear the label
        if (event.getSelection().isEmpty()) {
            return;
        }
        if (event.getSelection() instanceof IStructuredSelection) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Vector<String> itemNames = new Vector<String>();
            for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {
                Object domain = iterator.next();
                String value = labelProvider.getText(domain);
                itemNames.add(value);
            }
            itemLayers = new ArrayList<JGrassMapsetGeoResource>();
            for (String name : itemNames) {
                JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);
                if (tmpLayer != null) {
                    itemLayers.add(tmpLayer);
                }
            }
        }
    }

    /**
     * This class provides the content for the tree in FileTree
     */
    private class ContentProvider implements ITreeContentProvider {

        /**
         * Gets the children of the specified object
         *
         * @param arg0 the parent object
         * @return Object[]
         */
        public Object[] getChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                JGrassService map = (JGrassService) arg0;
                List<IResolve> layers = null;
                try {
                    layers = map.members(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (layers == null)
                    return null;
                return filteredLayers(layers);
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            }
            return null;
        }

        private Object[] filteredLayers(List<IResolve> layers) {
            Vector<JGrassMapsetGeoResource> filteredLayers = new Vector<JGrassMapsetGeoResource>();
            for (IResolve layer : layers) {
                if (layer instanceof JGrassMapsetGeoResource) {
                    filteredLayers.add((JGrassMapsetGeoResource) layer);
                    itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);
                }
            }
            /*
             * now let's sort them for nice visualization
             */
            HashMap<String, JGrassMapsetGeoResource> tmp = new HashMap<String, JGrassMapsetGeoResource>();
            for (JGrassMapsetGeoResource resource : filteredLayers) {
                tmp.put(resource.getTitle(), resource);
            }
            Map<String, JGrassMapsetGeoResource> sortedMap = new TreeMap<String, JGrassMapsetGeoResource>(tmp);
            filteredLayers.removeAllElements();
            for (JGrassMapsetGeoResource map : sortedMap.values()) {
                filteredLayers.add(map);
            }
            return filteredLayers.toArray();
        }

        /**
         * Gets the parent of the specified object
         *
         * @param arg0 the object
         * @return Object
         */
        public Object getParent(Object arg0) {
            if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            } else if (arg0 instanceof JGrassMapGeoResource) {
                try {
                    return ((JGrassMapGeoResource) arg0).parent(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return nu

        }

        /**
         * Returns whether the passed object has children
         *
         * @param arg0 the parent object
         * @return boolean
         */
        public boolean hasChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return true;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return false;
            }
            return false;
        }

        /**
         * Gets the root element(s) of the tree
         *
         * @param arg0 the input data
         * @return Object[]
         */
        public Object[] getElements(Object arg0) {
            // add the service to the catalog
            ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
            try {
                ArrayList<IResolve> finalCatalogMembers = new ArrayList<IResolve>();
                List<? extends IResolve> allCatalogMembers = catalog.members(null);
                for (IResolve resolve : allCatalogMembers) {
                    if (resolve instanceof JGrassService) {
                        finalCatalogMembers.add(resolve);
                    }
                }
                if (finalCatalogMembers.size() > 0) {
                    return finalCatalogMembers.toArray();
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * Disposes any created resources
         */
        public void dispose() {
            // Nothing to dispose
        }

        /**
         * Called when the input changes
         *
         * @param arg0 the viewer
         * @param arg1 the old input
         * @param arg2 the new input
         */
        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
            // Nothing to change
        }
    }

    /**
     * This class provides the labels for the file tree
     */
    private static class LabelProvider implements ILabelProvider {

        // The listeners
        private final List<ILabelProviderListener> listeners;

        // Images for tree nodes
        private final Image rasterMaps;

        private final Image mainRasterMaps;

        // Label provider state: preserve case of file names/directories
        /**
         * Constructs a FileTreeLabelProvider
         */
        public LabelProvider() {
            // Create the list to hold the listeners
            listeners = new ArrayList<ILabelProviderListener>();
            // Create the images
            mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrassloc_obj.gif").createImage();
            rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrass_obj.gif").createImage();
        }

        // * Sets the preserve case attribute
        // * @param preserveCase the preserve case attribute
        // // Since this attribute affects how the labels are computed,
        // // notify all the listeners of the change.
        /**
         * Gets the image to display for a node in the tree
         *
         * @param arg0 the node
         * @return Image
         */
        public Image getImage(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return mainRasterMaps;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return rasterMaps;
            } else {
                return null;
            }
        }

        /**
         * Gets the text to display for a node in the tree
         *
         * @param arg0 the node
         * @return String
         */
        public String getText(Object arg0) {
            String text = null;
            try {
                if (arg0 instanceof JGrassMapsetGeoResource) {
                    text = ((JGrassMapsetGeoResource) arg0).getTitle();
                } else if (arg0 instanceof JGrassService) {
                    text = ((JGrassService) arg0).getInfo(null).getTitle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return text;
        }

        /**
         * Adds a listener to this label provider
         *
         * @param arg0 the listener
         */
        public void addListener(ILabelProviderListener arg0) {
            listeners.add(arg0);
        }

        /**
         * Called when this LabelProvider is being disposed
         */
        public void dispose() {
            // Dispose the images
            if (rasterMaps != null)
                rasterMaps.dispose();
        }

        /**
         * Returns whether changes to the specified property on the specified element would affect
         * the label for the element
         *
         * @param arg0 the element
         * @param arg1 the property
         * @return boolean
         */
        public boolean isLabelProperty(Object arg0, String arg1) {
            return false;
        }

        /**
         * Removes the listener
         *
         * @param arg0 the listener to remove
         */
        public void removeListener(ILabelProviderListener arg0) {
            listeners.remove(arg0);
        }
    }

    public List<JGrassMapsetGeoResource> getSelectedLayers() {
        return itemLayers;
    }

    public int getType() {
        return 0;
    }
}


public void removeListener(ILabelProviderListener arg0) {
            listeners.remove(arg0);
        }

package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import org.locationtech.udig.catalog.CatalogPlugin;
import org.locationtech.udig.catalog.ICatalog;
import org.locationtech.udig.catalog.IResolve;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.locationtech.udig.catalog.jgrass.JGrassPlugin;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassService;

/**
 * <p>
 * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a
 * mapset is selected it is passed to the WidgetObservers that are registered with this class.
 * </p>
 *
 * @author Andrea Antonello - www.hydrologis.com
 * @since 1.1.0
 */
public class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {

    private final HashMap<String, JGrassMapsetGeoResource> itemsMap = new HashMap<String, JGrassMapsetGeoResource>();

    private LabelProvider labelProvider = null;

    private List<JGrassMapsetGeoResource> itemLayers;

    /**
     * @param parent
     * @param style
     * @param selectionStyle the tree selection style (single or multiple)
     * @param mapType the types of map to be filtered out (ex.
     *        {@link FeatureLayerTreeViewer.SHAPELAYER})
     */
    public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {
        super(parent, style);
        setLayout(new GridLayout(1, false));
        GridData gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.grabExcessVerticalSpace = true;
        setLayoutData(gridData);
        // Create the tree viewer to display the file tree
        PatternFilter patternFilter = new PatternFilter();
        final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);
        final TreeViewer tv = filter.getViewer();
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new ContentProvider());
        labelProvider = new LabelProvider();
        tv.setLabelProvider(labelProvider);
        // pass a non-null that will be ignored //$NON-NLS-1$
        tv.setInput("dummy");
        tv.addSelectionChangedListener(this);
    }

    public void selectionChanged(SelectionChangedEvent event) {
        // if the selection is empty clear the label
        if (event.getSelection().isEmpty()) {
            return;
        }
        if (event.getSelection() instanceof IStructuredSelection) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Vector<String> itemNames = new Vector<String>();
            for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {
                Object domain = iterator.next();
                String value = labelProvider.getText(domain);
                itemNames.add(value);
            }
            itemLayers = new ArrayList<JGrassMapsetGeoResource>();
            for (String name : itemNames) {
                JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);
                if (tmpLayer != null) {
                    itemLayers.add(tmpLayer);
                }
            }
        }
    }

    /**
     * This class provides the content for the tree in FileTree
     */
    private class ContentProvider implements ITreeContentProvider {

        /**
         * Gets the children of the specified object
         *
         * @param arg0 the parent object
         * @return Object[]
         */
        public Object[] getChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                JGrassService map = (JGrassService) arg0;
                List<IResolve> layers = null;
                try {
                    layers = map.members(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (layers == null)
                    return null;
                return filteredLayers(layers);
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            }
            return null;
        }

        private Object[] filteredLayers(List<IResolve> layers) {
            Vector<JGrassMapsetGeoResource> filteredLayers = new Vector<JGrassMapsetGeoResource>();
            for (IResolve layer : layers) {
                if (layer instanceof JGrassMapsetGeoResource) {
                    filteredLayers.add((JGrassMapsetGeoResource) layer);
                    itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);
                }
            }
            /*
             * now let's sort them for nice visualization
             */
            HashMap<String, JGrassMapsetGeoResource> tmp = new HashMap<String, JGrassMapsetGeoResource>();
            for (JGrassMapsetGeoResource resource : filteredLayers) {
                tmp.put(resource.getTitle(), resource);
            }
            Map<String, JGrassMapsetGeoResource> sortedMap = new TreeMap<String, JGrassMapsetGeoResource>(tmp);
            filteredLayers.removeAllElements();
            for (JGrassMapsetGeoResource map : sortedMap.values()) {
                filteredLayers.add(map);
            }
            return filteredLayers.toArray();
        }

        /**
         * Gets the parent of the specified object
         *
         * @param arg0 the object
         * @return Object
         */
        public Object getParent(Object arg0) {
            if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            } else if (arg0 instanceof JGrassMapGeoResource) {
                try {
                    return ((JGrassMapGeoResource) arg0).parent(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        /**
         * Returns whether the passed object has children
         *
         * @param arg0 the parent object
         * @return boolean
         */
        public boolean hasChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return true;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return false;
            }
            return false;
        }

        /**
         * Gets the root element(s) of the tree
         *
         * @param arg0 the input data
         * @return Object[]
         */
        public Object[] getElements(Object arg0) {
            // add the service to the catalog
            ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
            try {
                ArrayList<IResolve> finalCatalogMembers = new ArrayList<IResolve>();
                List<? extends IResolve> allCatalogMembers = catalog.members(null);
                for (IResolve resolve : allCatalogMembers) {
                    if (resolve instanceof JGrassService) {
                        finalCatalogMembers.add(resolve);
                    }
                }
                if (finalCatalogMembers.size() > 0) {
                    return finalCatalogMembers.toArray();
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * Disposes any created resources
         */
        public void dispose() {
            // Nothing to dispose
        }

        /**
         * Called when the input changes
         *
         * @param arg0 the viewer
         * @param arg1 the old input
         * @param arg2 the new input
         */
        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
            // Nothing to change
        }
    }

    /**
     * This class provides the labels for the file tree
     */
    private static class LabelProvider implements ILabelProvider {

        // The listeners
        private final List<ILabelProviderListener> listeners;

        // Images for tree nodes
        private final Image rasterMaps;

        private final Image mainRasterMaps;

        // Label provider state: preserve case of file names/directories
        /**
         * Constructs a FileTreeLabelProvider
         */
        public LabelProvider() {
            // Create the list to hold the listeners
            listeners = new ArrayList<ILabelProviderListener>();
            // Create the images
            mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrassloc_obj.gif").createImage();
            rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrass_obj.gif").createImage();
        }

        // * Sets the preserve case attribute
        // * @param preserveCase the preserve case attribute
        // // Since this attribute affects how the labels are computed,
        // // notify all the listeners of the change.
        /**
         * Gets the image to display for a node in the tree
         *
         * @param arg0 the node
         * @return Image
         */
        public Image getImage(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return mainRasterMaps;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return rasterMaps;
            } else {
                return null;
            }
        }

        /**
         * Gets the text to display for a node in the tree
         *
         * @param arg0 the node
         * @return String
         */
        public String getText(Object arg0) {
            String text = null;
            try {
                if (arg0 instanceof JGrassMapsetGeoResource) {
                    text = ((JGrassMapsetGeoResource) arg0).getTitle();
                } else if (arg0 instanceof JGrassService) {
                    text = ((JGrassService) arg0).getInfo(null).getTitle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return text;
        }

        /**
         * Adds a listener to this label provider
         *
         * @param arg0 the listener
         */
        public void addListener(ILabelProviderListener arg0) {
            listeners.add(arg0);
        }

        /**
         * Called when this LabelProvider is being disposed
         */
        public void dispose() {
            // Dispose the images
            if (rasterMaps != null)
                rasterMaps.dispose();
        }

        /**
         * Returns whether changes to the specified property on the specified element would affect
         * the label for the element
         *
         * @param arg0 the element
         * @param arg1 the property
         * @return boolean
         */
        public boolean isLabelProperty(Object arg0, String arg1) {
            return false;
        }

        /**
         * Removes the listener
         *
         * @param arg0 the listener to remove
         */

    }

    public List<JGrassMapsetGeoResource> getSelectedLayers() {
        return itemLayers;
    }

    public int getType() {
        return 0;
    }
}


for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {
                Object domain = iterator.next();
                String value = labelProvider.getText(domain);
                itemNames.add(value);
            }

package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import org.locationtech.udig.catalog.CatalogPlugin;
import org.locationtech.udig.catalog.ICatalog;
import org.locationtech.udig.catalog.IResolve;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.locationtech.udig.catalog.jgrass.JGrassPlugin;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassService;

/**
 * <p>
 * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a
 * mapset is selected it is passed to the WidgetObservers that are registered with this class.
 * </p>
 *
 * @author Andrea Antonello - www.hydrologis.com
 * @since 1.1.0
 */
public class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {

    private final HashMap<String, JGrassMapsetGeoResource> itemsMap = new HashMap<String, JGrassMapsetGeoResource>();

    private LabelProvider labelProvider = null;

    private List<JGrassMapsetGeoResource> itemLayers;

    /**
     * @param parent
     * @param style
     * @param selectionStyle the tree selection style (single or multiple)
     * @param mapType the types of map to be filtered out (ex.
     *        {@link FeatureLayerTreeViewer.SHAPELAYER})
     */
    public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {
        super(parent, style);
        setLayout(new GridLayout(1, false));
        GridData gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.grabExcessVerticalSpace = true;
        setLayoutData(gridData);
        // Create the tree viewer to display the file tree
        PatternFilter patternFilter = new PatternFilter();
        final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);
        final TreeViewer tv = filter.getViewer();
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new ContentProvider());
        labelProvider = new LabelProvider();
        tv.setLabelProvider(labelProvider);
        // pass a non-null that will be ignored //$NON-NLS-1$
        tv.setInput("dummy");
        tv.addSelectionChangedListener(this);
    }

    public void selectionChanged(SelectionChangedEvent event) {
        // if the selection is empty clear the label
        if (event.getSelection().isEmpty()) {
            return;
        }
        if (event.getSelection() instanceof IStructuredSelection) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Vector<String> itemNames = new Vector<String>();

            itemLayers = new ArrayList<JGrassMapsetGeoResource>();
            for (String name : itemNames) {
                JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);
                if (tmpLayer != null) {
                    itemLayers.add(tmpLayer);
                }
            }
        }
    }

    /**
     * This class provides the content for the tree in FileTree
     */
    private class ContentProvider implements ITreeContentProvider {

        /**
         * Gets the children of the specified object
         *
         * @param arg0 the parent object
         * @return Object[]
         */
        public Object[] getChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                JGrassService map = (JGrassService) arg0;
                List<IResolve> layers = null;
                try {
                    layers = map.members(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (layers == null)
                    return null;
                return filteredLayers(layers);
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            }
            return null;
        }

        private Object[] filteredLayers(List<IResolve> layers) {
            Vector<JGrassMapsetGeoResource> filteredLayers = new Vector<JGrassMapsetGeoResource>();
            for (IResolve layer : layers) {
                if (layer instanceof JGrassMapsetGeoResource) {
                    filteredLayers.add((JGrassMapsetGeoResource) layer);
                    itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);
                }
            }
            /*
             * now let's sort them for nice visualization
             */
            HashMap<String, JGrassMapsetGeoResource> tmp = new HashMap<String, JGrassMapsetGeoResource>();
            for (JGrassMapsetGeoResource resource : filteredLayers) {
                tmp.put(resource.getTitle(), resource);
            }
            Map<String, JGrassMapsetGeoResource> sortedMap = new TreeMap<String, JGrassMapsetGeoResource>(tmp);
            filteredLayers.removeAllElements();
            for (JGrassMapsetGeoResource map : sortedMap.values()) {
                filteredLayers.add(map);
            }
            return filteredLayers.toArray();
        }

        /**
         * Gets the parent of the specified object
         *
         * @param arg0 the object
         * @return Object
         */
        public Object getParent(Object arg0) {
            if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            } else if (arg0 instanceof JGrassMapGeoResource) {
                try {
                    return ((JGrassMapGeoResource) arg0).parent(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        /**
         * Returns whether the passed object has children
         *
         * @param arg0 the parent object
         * @return boolean
         */
        public boolean hasChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return true;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return false;
            }
            return false;
        }

        /**
         * Gets the root element(s) of the tree
         *
         * @param arg0 the input data
         * @return Object[]
         */
        public Object[] getElements(Object arg0) {
            // add the service to the catalog
            ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
            try {
                ArrayList<IResolve> finalCatalogMembers = new ArrayList<IResolve>();
                List<? extends IResolve> allCatalogMembers = catalog.members(null);
                for (IResolve resolve : allCatalogMembers) {
                    if (resolve instanceof JGrassService) {
                        finalCatalogMembers.add(resolve);
                    }
                }
                if (finalCatalogMembers.size() > 0) {
                    return finalCatalogMembers.toArray();
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * Disposes any created resources
         */
        public void dispose() {
            // Nothing to dispose
        }

        /**
         * Called when the input changes
         *
         * @param arg0 the viewer
         * @param arg1 the old input
         * @param arg2 the new input
         */
        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
            // Nothing to change
        }
    }

    /**
     * This class provides the labels for the file tree
     */
    private static class LabelProvider implements ILabelProvider {

        // The listeners
        private final List<ILabelProviderListener> listeners;

        // Images for tree nodes
        private final Image rasterMaps;

        private final Image mainRasterMaps;

        // Label provider state: preserve case of file names/directories
        /**
         * Constructs a FileTreeLabelProvider
         */
        public LabelProvider() {
            // Create the list to hold the listeners
            listeners = new ArrayList<ILabelProviderListener>();
            // Create the images
            mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrassloc_obj.gif").createImage();
            rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrass_obj.gif").createImage();
        }

        // * Sets the preserve case attribute
        // * @param preserveCase the preserve case attribute
        // // Since this attribute affects how the labels are computed,
        // // notify all the listeners of the change.
        /**
         * Gets the image to display for a node in the tree
         *
         * @param arg0 the node
         * @return Image
         */
        public Image getImage(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return mainRasterMaps;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return rasterMaps;
            } else {
                return null;
            }
        }

        /**
         * Gets the text to display for a node in the tree
         *
         * @param arg0 the node
         * @return String
         */
        public String getText(Object arg0) {
            String text = null;
            try {
                if (arg0 instanceof JGrassMapsetGeoResource) {
                    text = ((JGrassMapsetGeoResource) arg0).getTitle();
                } else if (arg0 instanceof JGrassService) {
                    text = ((JGrassService) arg0).getInfo(null).getTitle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return text;
        }

        /**
         * Adds a listener to this label provider
         *
         * @param arg0 the listener
         */
        public void addListener(ILabelProviderListener arg0) {
            listeners.add(arg0);
        }

        /**
         * Called when this LabelProvider is being disposed
         */
        public void dispose() {
            // Dispose the images
            if (rasterMaps != null)
                rasterMaps.dispose();
        }

        /**
         * Returns whether changes to the specified property on the specified element would affect
         * the label for the element
         *
         * @param arg0 the element
         * @param arg1 the property
         * @return boolean
         */
        public boolean isLabelProperty(Object arg0, String arg1) {
            return false;
        }

        /**
         * Removes the listener
         *
         * @param arg0 the listener to remove
         */
        public void removeListener(ILabelProviderListener arg0) {
            listeners.remove(arg0);
        }
    }

    public List<JGrassMapsetGeoResource> getSelectedLayers() {
        return itemLayers;
    }

    public int getType() {
        return 0;
    }
}


try {
                if (arg0 instanceof JGrassMapsetGeoResource) {
                    text = ((JGrassMapsetGeoResource) arg0).getTitle();
                } else if (arg0 instanceof JGrassService) {
                    text = ((JGrassService) arg0).getInfo(null).getTitle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

package org.locationtech.udig.catalog.jgrass.activeregion.dialogs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import org.locationtech.udig.catalog.CatalogPlugin;
import org.locationtech.udig.catalog.ICatalog;
import org.locationtech.udig.catalog.IResolve;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.locationtech.udig.catalog.jgrass.JGrassPlugin;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassMapsetGeoResource;
import org.locationtech.udig.catalog.jgrass.core.JGrassService;

/**
 * <p>
 * This class supplies a tree viewer containing the JGrass mapsets that are in the catalog When a
 * mapset is selected it is passed to the WidgetObservers that are registered with this class.
 * </p>
 *
 * @author Andrea Antonello - www.hydrologis.com
 * @since 1.1.0
 */
public class CatalogJGrassMapsetsTreeViewer extends Composite implements ISelectionChangedListener, IResourcesSelector {

    private final HashMap<String, JGrassMapsetGeoResource> itemsMap = new HashMap<String, JGrassMapsetGeoResource>();

    private LabelProvider labelProvider = null;

    private List<JGrassMapsetGeoResource> itemLayers;

    /**
     * @param parent
     * @param style
     * @param selectionStyle the tree selection style (single or multiple)
     * @param mapType the types of map to be filtered out (ex.
     *        {@link FeatureLayerTreeViewer.SHAPELAYER})
     */
    public CatalogJGrassMapsetsTreeViewer(Composite parent, int style, int selectionStyle) {
        super(parent, style);
        setLayout(new GridLayout(1, false));
        GridData gridData = new GridData();
        gridData.grabExcessHorizontalSpace = true;
        gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
        gridData.grabExcessVerticalSpace = true;
        setLayoutData(gridData);
        // Create the tree viewer to display the file tree
        PatternFilter patternFilter = new PatternFilter();
        final FilteredTree filter = new FilteredTree(this, selectionStyle, patternFilter);
        final TreeViewer tv = filter.getViewer();
        tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
        tv.setContentProvider(new ContentProvider());
        labelProvider = new LabelProvider();
        tv.setLabelProvider(labelProvider);
        // pass a non-null that will be ignored //$NON-NLS-1$
        tv.setInput("dummy");
        tv.addSelectionChangedListener(this);
    }

    public void selectionChanged(SelectionChangedEvent event) {
        // if the selection is empty clear the label
        if (event.getSelection().isEmpty()) {
            return;
        }
        if (event.getSelection() instanceof IStructuredSelection) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            Vector<String> itemNames = new Vector<String>();
            for (Iterator iterator = selection.iterator(); iterator.hasNext(); ) {
                Object domain = iterator.next();
                String value = labelProvider.getText(domain);
                itemNames.add(value);
            }
            itemLayers = new ArrayList<JGrassMapsetGeoResource>();
            for (String name : itemNames) {
                JGrassMapsetGeoResource tmpLayer = itemsMap.get(name);
                if (tmpLayer != null) {
                    itemLayers.add(tmpLayer);
                }
            }
        }
    }

    /**
     * This class provides the content for the tree in FileTree
     */
    private class ContentProvider implements ITreeContentProvider {

        /**
         * Gets the children of the specified object
         *
         * @param arg0 the parent object
         * @return Object[]
         */
        public Object[] getChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                JGrassService map = (JGrassService) arg0;
                List<IResolve> layers = null;
                try {
                    layers = map.members(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (layers == null)
                    return null;
                return filteredLayers(layers);
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            }
            return null;
        }

        private Object[] filteredLayers(List<IResolve> layers) {
            Vector<JGrassMapsetGeoResource> filteredLayers = new Vector<JGrassMapsetGeoResource>();
            for (IResolve layer : layers) {
                if (layer instanceof JGrassMapsetGeoResource) {
                    filteredLayers.add((JGrassMapsetGeoResource) layer);
                    itemsMap.put(((JGrassMapsetGeoResource) layer).getTitle(), (JGrassMapsetGeoResource) layer);
                }
            }
            /*
             * now let's sort them for nice visualization
             */
            HashMap<String, JGrassMapsetGeoResource> tmp = new HashMap<String, JGrassMapsetGeoResource>();
            for (JGrassMapsetGeoResource resource : filteredLayers) {
                tmp.put(resource.getTitle(), resource);
            }
            Map<String, JGrassMapsetGeoResource> sortedMap = new TreeMap<String, JGrassMapsetGeoResource>(tmp);
            filteredLayers.removeAllElements();
            for (JGrassMapsetGeoResource map : sortedMap.values()) {
                filteredLayers.add(map);
            }
            return filteredLayers.toArray();
        }

        /**
         * Gets the parent of the specified object
         *
         * @param arg0 the object
         * @return Object
         */
        public Object getParent(Object arg0) {
            if (arg0 instanceof JGrassMapsetGeoResource) {
                return null;
            } else if (arg0 instanceof JGrassMapGeoResource) {
                try {
                    return ((JGrassMapGeoResource) arg0).parent(null);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        /**
         * Returns whether the passed object has children
         *
         * @param arg0 the parent object
         * @return boolean
         */
        public boolean hasChildren(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return true;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return false;
            }
            return false;
        }

        /**
         * Gets the root element(s) of the tree
         *
         * @param arg0 the input data
         * @return Object[]
         */
        public Object[] getElements(Object arg0) {
            // add the service to the catalog
            ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
            try {
                ArrayList<IResolve> finalCatalogMembers = new ArrayList<IResolve>();
                List<? extends IResolve> allCatalogMembers = catalog.members(null);
                for (IResolve resolve : allCatalogMembers) {
                    if (resolve instanceof JGrassService) {
                        finalCatalogMembers.add(resolve);
                    }
                }
                if (finalCatalogMembers.size() > 0) {
                    return finalCatalogMembers.toArray();
                } else {
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * Disposes any created resources
         */
        public void dispose() {
            // Nothing to dispose
        }

        /**
         * Called when the input changes
         *
         * @param arg0 the viewer
         * @param arg1 the old input
         * @param arg2 the new input
         */
        public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
            // Nothing to change
        }
    }

    /**
     * This class provides the labels for the file tree
     */
    private static class LabelProvider implements ILabelProvider {

        // The listeners
        private final List<ILabelProviderListener> listeners;

        // Images for tree nodes
        private final Image rasterMaps;

        private final Image mainRasterMaps;

        // Label provider state: preserve case of file names/directories
        /**
         * Constructs a FileTreeLabelProvider
         */
        public LabelProvider() {
            // Create the list to hold the listeners
            listeners = new ArrayList<ILabelProviderListener>();
            // Create the images
            mainRasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrassloc_obj.gif").createImage();
            rasterMaps = AbstractUIPlugin.imageDescriptorFromPlugin(JGrassPlugin.PLUGIN_ID, "icons/obj16/jgrass_obj.gif").createImage();
        }

        // * Sets the preserve case attribute
        // * @param preserveCase the preserve case attribute
        // // Since this attribute affects how the labels are computed,
        // // notify all the listeners of the change.
        /**
         * Gets the image to display for a node in the tree
         *
         * @param arg0 the node
         * @return Image
         */
        public Image getImage(Object arg0) {
            if (arg0 instanceof JGrassService) {
                return mainRasterMaps;
            } else if (arg0 instanceof JGrassMapsetGeoResource) {
                return rasterMaps;
            } else {
                return null;
            }
        }

        /**
         * Gets the text to display for a node in the tree
         *
         * @param arg0 the node
         * @return String
         */
        public String getText(Object arg0) {
            String text = null;

            return text;
        }

        /**
         * Adds a listener to this label provider
         *
         * @param arg0 the listener
         */
        public void addListener(ILabelProviderListener arg0) {
            listeners.add(arg0);
        }

        /**
         * Called when this LabelProvider is being disposed
         */
        public void dispose() {
            // Dispose the images
            if (rasterMaps != null)
                rasterMaps.dispose();
        }

        /**
         * Returns whether changes to the specified property on the specified element would affect
         * the label for the element
         *
         * @param arg0 the element
         * @param arg1 the property
         * @return boolean
         */
        public boolean isLabelProperty(Object arg0, String arg1) {
            return false;
        }

        /**
         * Removes the listener
         *
         * @param arg0 the listener to remove
         */
        public void removeListener(ILabelProviderListener arg0) {
            listeners.remove(arg0);
        }
    }

    public List<JGrassMapsetGeoResource> getSelectedLayers() {
        return itemLayers;
    }

    public int getType() {
        return 0;
    }
}


package org.iplass.adminconsole.client.base.ui.widget.form;

import com.smartgwt.client.widgets.form.fields.TextItem;

public class MtpTextItem extends TextItem {

    public MtpTextItem() {
        init();
    }

    public MtpTextItem(String name) {
        super(name);
        init();
    }

    public MtpTextItem(String name, String title) {
        super(name, title);
        init();
    }

{
        setWidth("100%");
        setBrowserSpellCheck(false);
    }
}


{
        setWidth("100%");
        setBrowserSpellCheck(false);
    }

package org.iplass.adminconsole.client.base.ui.widget.form;

import com.smartgwt.client.widgets.form.fields.TextItem;

public class MtpTextItem extends TextItem {

    public MtpTextItem() {
        init();
    }

    public MtpTextItem(String name) {
        super(name);
        init();
    }

    public MtpTextItem(String name, String title) {
        super(name, title);
        init();
    }

    private void init()


package org.iplass.adminconsole.client.base.ui.widget.form;

import com.smartgwt.client.widgets.form.fields.TextItem;

public class MtpTextItem extends TextItem {

    public MtpTextItem() {
        init();
    }

    public MtpTextItem(String name) {
        super(name);
        init();
    }

    public MtpTextItem(String name, String title) {
        super(name, title);
        init();
    }

    private void init() {
        setWidth("100%");
        setBrowserS


@SuppressWarnings("unchecked")
    protected void checkGlobalTag(Property property, Node node, Object object)

package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;

import java.beans.IntrospectionException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;

/**
 * Represent JavaBeans
 */
public class Representer extends SafeRepresenter {

    public Representer() {
        this.representers.put(null, new RepresentJavaBean());
    }

    protected class RepresentJavaBean implements Represent {

        public Node representData(Object data) {
            try {
                return representJavaBean(getProperties(data.getClass()), data);
            } catch (IntrospectionException e) {
                throw new YAMLException(e);
            }
        }
    }

    /**
     * Tag logic:
     * - explicit root tag is set in serializer
     * - if there is a predefined class tag it is used
     * - a global tag with class name is always used as tag. The JavaBean parent
     * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
     * when the property class is the same as runtime class
     *
     * @param properties
     *            JavaBean getters
     * @param javaBean
     *            instance for Node
     * @return Node to get serialized
     */
    protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
        List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
        Tag tag;
        Tag customTag = classTags.get(javaBean.getClass());
        tag = customTag != null ? customTag : new Tag(javaBean.getClass());
        // flow style will be chosen by BaseRepresenter
        MappingNode node = new MappingNode(tag, value, null);
        representedObjects.put(javaBean, node);
        boolean bestStyle = true;
        for (Property property : properties) {
            Object memberValue = property.get(javaBean);
            Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());
            NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);
            if (tuple == null) {
                continue;
            }
            if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {
                bestStyle = false;
            }
            Node nodeValue = tuple.getValueNode();
            if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
                bestStyle = false;
            }
            value.add(tuple);
        }
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
        return node;
    }

    /**
     * Represent one JavaBean property.
     *
     * @param javaBean
     *            - the instance to be represented
     * @param property
     *            - the property of the instance
     * @param propertyValue
     *            - value to be represented
     * @param customTag
     *            - user defined Tag
     * @return NodeTuple to be used in a MappingNode. Return null to skip the
     *         property
     */
    protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
        ScalarNode nodeKey = (ScalarNode) representData(property.getName());
        // the first occurrence of the node must keep the tag
        boolean hasAlias = this.representedObjects.containsKey(propertyValue);
        Node nodeValue = representData(propertyValue);
        if (propertyValue != null && !hasAlias) {
            NodeId nodeId = nodeValue.getNodeId();
            if (customTag == null) {
                if (nodeId == NodeId.scalar) {
                    if (propertyValue instanceof Enum<?>) {
                        nodeValue.setTag(Tag.STR);
                    }
                } else {
                    if (nodeId == NodeId.mapping) {
                        if (property.getType() == propertyValue.getClass()) {
                            if (!(propertyValue instanceof Map<?, ?>)) {
                                if (!nodeValue.getTag().equals(Tag.SET)) {
                                    nodeValue.setTag(Tag.MAP);
                                }
                            }
                        }
                    }
                    checkGlobalTag(property, nodeValue, propertyValue);
                }
            }
        }
        return new NodeTuple(nodeKey, nodeValue);
    }

    /**
     * Remove redundant global tag for a type safe (generic) collection if it is
     * the same as defined by the JavaBean property
     *
     * @param property
     *            - JavaBean property
     * @param node
     *            - representation of the property
     * @param object
     *            - instance represented by the node
     */

{
        // Skip primitive arrays.
        if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {
            return;
        }
        Class<?>[] arguments = property.getActualTypeArguments();
        if (arguments != null) {
            if (node.getNodeId() == NodeId.sequence) {
                // apply map tag where class is the same
                Class<? extends Object> t = arguments[0];
                SequenceNode snode = (SequenceNode) node;
                Iterable<Object> memberList = Collections.EMPTY_LIST;
                if (object.getClass().isArray()) {
                    memberList = Arrays.asList((Object[]) object);
                } else if (object instanceof Iterable<?>) {
                    // list
                    memberList = (Iterable<Object>) object;
                }
                Iterator<Object> iter = memberList.iterator();
                if (iter.hasNext()) {
                    for (Node childNode : snode.getValue()) {
                        Object member = iter.next();
                        if (member != null) {
                            if (t.equals(member.getClass()))
                                if (childNode.getNodeId() == NodeId.mapping) {
                                    childNode.setTag(Tag.MAP);
                                }
                        }
                    }
                }
            } else if (object instanceof Set) {
                Class<?> t = arguments[0];
                MappingNode mnode = (MappingNode) node;
                Iterator<NodeTuple> iter = mnode.getValue().iterator();
                Set<?> set = (Set<?>) object;
                for (Object member : set) {
                    NodeTuple tuple = iter.next();
                    Node keyNode = tuple.getKeyNode();
                    if (t.equals(member.getClass())) {
                        if (keyNode.getNodeId() == NodeId.mapping) {
                            keyNode.setTag(Tag.MAP);
                        }
                    }
                }
            } else if (object instanceof Map) {
                Class<?> keyType = arguments[0];
                Class<?> valueType = arguments[1];
                MappingNode mnode = (MappingNode) node;
                for (NodeTuple tuple : mnode.getValue()) {
                    resetTag(keyType, tuple.getKeyNode());
                    resetTag(valueType, tuple.getValueNode());
                }
            } else {
                // the type for collection entries cannot be
                // detected
            }
        }
    }

    private void resetTag(Class<? extends Object> type, Node node) {
        Tag tag = node.getTag();
        if (tag.matches(type)) {
            if (Enum.class.isAssignableFrom(type)) {
                node.setTag(Tag.STR);
            } else {
                node.setTag(Tag.MAP);
            }
        }
    }

    /**
     * Get JavaBean properties to be serialised. The order is respected. This
     * method may be overridden to provide custom property selection or order.
     *
     * @param type
     *            - JavaBean to inspect the properties
     * @return properties to serialise
     */
    protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException {
        return getPropertyUtils().getProperties(type);
    }
}


{
            try {
                return representJavaBean(getProperties(data.getClass()), data);
            } catch (IntrospectionException e) {
                throw new YAMLException(e);
            }
        }

package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;

import java.beans.IntrospectionException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;

/**
 * Represent JavaBeans
 */
public class Representer extends SafeRepresenter {

    public Representer() {
        this.representers.put(null, new RepresentJavaBean());
    }

    protected class RepresentJavaBean implements Represent {

        public Node representData(Object data)

    }

    /**
     * Tag logic:
     * - explicit root tag is set in serializer
     * - if there is a predefined class tag it is used
     * - a global tag with class name is always used as tag. The JavaBean parent
     * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
     * when the property class is the same as runtime class
     *
     * @param properties
     *            JavaBean getters
     * @param javaBean
     *            instance for Node
     * @return Node to get serialized
     */
    protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
        List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
        Tag tag;
        Tag customTag = classTags.get(javaBean.getClass());
        tag = customTag != null ? customTag : new Tag(javaBean.getClass());
        // flow style will be chosen by BaseRepresenter
        MappingNode node = new MappingNode(tag, value, null);
        representedObjects.put(javaBean, node);
        boolean bestStyle = true;
        for (Property property : properties) {
            Object memberValue = property.get(javaBean);
            Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());
            NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);
            if (tuple == null) {
                continue;
            }
            if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {
                bestStyle = false;
            }
            Node nodeValue = tuple.getValueNode();
            if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
                bestStyle = false;
            }
            value.add(tuple);
        }
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
        return node;
    }

    /**
     * Represent one JavaBean property.
     *
     * @param javaBean
     *            - the instance to be represented
     * @param property
     *            - the property of the instance
     * @param propertyValue
     *            - value to be represented
     * @param customTag
     *            - user defined Tag
     * @return NodeTuple to be used in a MappingNode. Return null to skip the
     *         property
     */
    protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
        ScalarNode nodeKey = (ScalarNode) representData(property.getName());
        // the first occurrence of the node must keep the tag
        boolean hasAlias = this.representedObjects.containsKey(propertyValue);
        Node nodeValue = representData(propertyValue);
        if (propertyValue != null && !hasAlias) {
            NodeId nodeId = nodeValue.getNodeId();
            if (customTag == null) {
                if (nodeId == NodeId.scalar) {
                    if (propertyValue instanceof Enum<?>) {
                        nodeValue.setTag(Tag.STR);
                    }
                } else {
                    if (nodeId == NodeId.mapping) {
                        if (property.getType() == propertyValue.getClass()) {
                            if (!(propertyValue instanceof Map<?, ?>)) {
                                if (!nodeValue.getTag().equals(Tag.SET)) {
                                    nodeValue.setTag(Tag.MAP);
                                }
                            }
                        }
                    }
                    checkGlobalTag(property, nodeValue, propertyValue);
                }
            }
        }
        return new NodeTuple(nodeKey, nodeValue);
    }

    /**
     * Remove redundant global tag for a type safe (generic) collection if it is
     * the same as defined by the JavaBean property
     *
     * @param property
     *            - JavaBean property
     * @param node
     *            - representation of the property
     * @param object
     *            - instance represented by the node
     */
    @SuppressWarnings("unchecked")
    protected void checkGlobalTag(Property property, Node node, Object object) {
        // Skip primitive arrays.
        if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {
            return;
        }
        Class<?>[] arguments = property.getActualTypeArguments();
        if (arguments != null) {
            if (node.getNodeId() == NodeId.sequence) {
                // apply map tag where class is the same
                Class<? extends Object> t = arguments[0];
                SequenceNode snode = (SequenceNode) node;
                Iterable<Object> memberList = Collections.EMPTY_LIST;
                if (object.getClass().isArray()) {
                    memberList = Arrays.asList((Object[]) object);
                } else if (object instanceof Iterable<?>) {
                    // list
                    memberList = (Iterable<Object>) object;
                }
                Iterator<Object> iter = memberList.iterator();
                if (iter.hasNext()) {
                    for (Node childNode : snode.getValue()) {
                        Object member = iter.next();
                        if (member != null) {
                            if (t.equals(member.getClass()))
                                if (childNode.getNodeId() == NodeId.mapping) {
                                    childNode.setTag(Tag.MAP);
                                }
                        }
                    }
                }
            } else if (object instanceof Set) {
                Class<?> t = arguments[0];
                MappingNode mnode = (MappingNode) node;
                Iterator<NodeTuple> iter = mnode.getValue().iterator();
                Set<?> set = (Set<?>) object;
                for (Object member : set) {
                    NodeTuple tuple = iter.next();
                    Node keyNode = tuple.getKeyNode();
                    if (t.equals(member.getClass())) {
                        if (keyNode.getNodeId() == NodeId.mapping) {
                            keyNode.setTag(Tag.MAP);
                        }
                    }
                }
            } else if (object instanceof Map) {
                Class<?> keyType = arguments[0];
                Class<?> valueType = arguments[1];
                MappingNode mnode = (MappingNode) node;
                for (NodeTuple tuple : mnode.getValue()) {
                    resetTag(keyType, tuple.getKeyNode());
                    resetTag(valueType, tuple.getValueNode());
                }
            } else {
                // the type for collection entries cannot be
                // detected
            }
        }
    }

    private void resetTag(Class<? extends Object> type, Node node) {
        Tag tag = node.getTag();
        if (tag.matches(type)) {
            if (Enum.class.isAssignableFrom(type)) {
                node.setTag(Tag.STR);
            } else {
                node.setTag(Tag.MAP);
            }
        }
    }

    /**
     * Get JavaBean properties to be serialised. The order is respected. This
     * method may be overridden to provide custom property selection or order.
     *
     * @param type
     *            - JavaBean to inspect the properties
     * @return properties to serialise
     */
    protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException {
        return getPropertyUtils().getProperties(type);
    }
}


package org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer;

import java.beans.IntrospectionException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.MappingNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.error.YAMLException;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.introspector.Property;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Node;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeId;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.NodeTuple;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.ScalarNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.SequenceNode;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.nodes.Tag;
import org.jenkinsci.plugins.pipeline.utility.steps.shaded.org.yaml.snakeyaml.representer.Represent;

/**
 * Represent JavaBeans
 */
public class Representer extends SafeRepresenter {

    public Representer() {
        this.representers.put(null, new RepresentJavaBean());
    }

    protected class RepresentJavaBean implements Represent {

        public Node representData(Object data) {
            try {
                return representJavaBean(getProperties(data.getClass()), data);
            } catch (IntrospectionException e) {
                throw new YAMLException(e);
            }
        }
    }

    /**
     * Tag logic:
     * - explicit root tag is set in serializer
     * - if there is a predefined class tag it is used
     * - a global tag with class name is always used as tag. The JavaBean parent
     * of the specified JavaBean may set another tag (tag:yaml.org,2002:map)
     * when the property class is the same as runtime class
     *
     * @param properties
     *            JavaBean getters
     * @param javaBean
     *            instance for Node
     * @return Node to get serialized
     */
    protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
        List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size());
        Tag tag;
        Tag customTag = classTags.get(javaBean.getClass());
        tag = customTag != null ? customTag : new Tag(javaBean.getClass());
        // flow style will be chosen by BaseRepresenter
        MappingNode node = new MappingNode(tag, value, null);
        representedObjects.put(javaBean, node);
        boolean bestStyle = true;
        for (Property property : properties) {
            Object memberValue = property.get(javaBean);
            Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue.getClass());
            NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag);
            if (tuple == null) {
                continue;
            }
            if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) {
                bestStyle = false;
            }
            Node nodeValue = tuple.getValueNode();
            if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
                bestStyle = false;
            }
            value.add(tuple);
        }
        if (defaultFlowStyle != FlowStyle.AUTO) {
            node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
        } else {
            node.setFlowStyle(bestStyle);
        }
        return node;
    }

    /**
     * Represent one JavaBean property.
     *
     * @param javaBean
     *            - the instance to be represented
     * @param property
     *            - the property of the instance
     * @param propertyValue
     *            - value to be represented
     * @param customTag
     *            - user defined Tag
     * @return NodeTuple to be used in a MappingNode. Return null to skip the
     *         property
     */
    protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
        ScalarNode nodeKey = (ScalarNode) representData(property.getName());
        // the first occurrence of the node must keep the tag
        boolean hasAlias = this.representedObjects.containsKey(propertyValue);
        Node nodeValue = representData(propertyValue);
        if (propertyValue != null && !hasAlias) {
            NodeId nodeId = nodeValue.getNodeId();
            if (customTag == null) {
                if (nodeId == NodeId.scalar) {
                    if (propertyValue instanceof Enum<?>) {
                        nodeValue.setTag(Tag.STR);
                    }
                } else {
                    if (nodeId == NodeId.mapping) {
                        if (property.getType() == propertyValue.getClass()) {
                            if (!(propertyValue instanceof Map<?, ?>)) {
                                if (!nodeValue.getTag().equals(Tag.SET)) {
                                    nodeValue.setTag(Tag.MAP);
                                }
                            }
                        }
                    }
                    checkGlobalTag(property, nodeValue, propertyValue);
                }
            }
        }
        return new NodeTuple(nodeKey, nodeValue);
    }

    /**
     * Remove redundant global tag for a type safe (generic) collection if it is
     * the same as defined by the JavaBean property
     *
     * @param property
     *            - JavaBean property
     * @param node
     *            - representation of the property
     * @param object
     *            - instance represented by the node
     */
    @SuppressWarnings("unchecked")
    protected void checkGlobalTag(Property property, Node node, Object object) {
        // Skip primitive arrays.
        if (object.getClass().isArray() && object.getClass().getComponentType().isPrimitive()) {
            return;
        }
        Class<?>[] arguments = property.getActu

        if (arguments != null) {
            if (node.getNodeId() == NodeId.sequence) {
                // apply map tag where class is the same
                Class<? extends Object> t = arguments[0];
                SequenceNode snode = (SequenceNode) node;
                Iterable<Object> memberList = Collections.EMPTY_LIST;
                if (object.getClass().isArray()) {
                    memberList = Arrays.asList((Object[]) object);
                } else if (object instanceof Iterable<?>) {
                    // list
                    memberList = (Iterable<Object>) object;
                }
                Iterator<Object> iter = memberList.iterator();
                if (iter.hasNext()) {
                    for (Node childNode : snode.getValue()) {
                        Object member = iter.next();
                        if (member != null) {
                            if (t.equals(member.getClass()))
                                if (childNode.getNodeId() == NodeId.mapping) {
                                    childNode.setTag(Tag.MAP);
                                }
                        }
                    }
                }
            } else if (object instanceof Set) {
                Class<?> t = arguments[0];
                MappingNode mnode = (MappingNode) node;
                Iterator<NodeTuple> iter = mnode.getValue().iterator();
                Set<?> set = (Set<?>) object;
                for (Object member : set) {
                    NodeTuple tuple = iter.next();
                    Node keyNode = tuple.getKeyNode();
                    if (t.equals(member.getClass())) {
                        if (keyNode.getNodeId() == NodeId.mapping) {
                            keyNode.setTag(Tag.MAP);
                        }
                    }
                }
            } else if (object instanceof Map) {
                Class<?> keyType = arguments[0];
                Class<?> valueType = arguments[1];
                MappingNode mnode = (MappingNode) node;
                for (NodeTuple tuple : mnode.getValue()) {
                    resetTag(keyType, tuple.getKeyNode());
                    resetTag(valueType, tuple.getValueNode());
                }
            } else {
                // the type for collection entries cannot be
                // detected
            }
        }
    }

    private void resetTag(Class<? extends Object> type, Node node) {
        Tag tag = node.getTag();
        if (tag.matches(type)) {
            if (Enum.class.isAssignableFrom(type)) {
                node.setTag(Tag.STR);
            } else {
                node.setTag(Tag.MAP);
            }
        }
    }

    /**
     * Get JavaBean properties to be serialised. The order is respected. This
     * method may be overridden to provide custom property selection or order.
     *
     * @param type
     *            - JavaBean to inspect the properties
     * @return properties to serialise
     */
    protected Set<Property> getProperties(Class<? extends Object> type) throws IntrospectionException {
        return getPropertyUtils().getProperties(type);
    }
}