Portal groups

Download Sample Viewer

Description

This sample shows how to use the Portal API classes to find featured groups in a portal, search for web maps within a portal group, and load/display web maps. The portal used in this sample is ArcGIS Online (arcgis.com) but the same API can be used against any portal instance. The steps are as follows: 1) Create a Portal instance using the portal URL and appropriate user credentials. 2) Fetch the list of featured group query strings from the portal via its PortalInfo. 3) Loop through the list of queries and retrieve each PortalGroup using Portal's findGroups method. 4) For each portal group, fetch the title and display it in a list. 5) For the selected group, fetch the group's WebMap content items using Portal's findItems method. 5) For each WebMap found, display it in a list. 6) When a WebMap list item is selected, display it in the application.

Code snippet


  myPortal = new Portal(PORTAL_URL, credentials);

  // get the list of query strings for getting the portal's featured groups
  List<String> querys = myPortal.fetchPortalInfo().getFeaturedGroupsQueries();

  // loop through list of query strings to find each featured group in your portal
  for (String query : querys) {
    PortalQueryResultSet<PortalGroup> result = myPortal.findGroups(new PortalQueryParams(query));
    for (final PortalGroup group : result.getResults()) {
          MyGroup mygroup = new MyGroup(group);
          portalGroupData.add(mygroup);
        }
  }
  

Sample Code

/* Copyright 2014 Esri

All rights reserved under the copyright laws of the United States
and applicable international laws, treaties, and conventions.

You may freely redistribute and use this sample code, with or
without modification, provided you include the original copyright
notice and use restrictions.

See the use restrictions.*/
package com.esri.client.samples.webmap;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

import com.esri.core.io.UserCredentials;
import com.esri.core.portal.Portal;
import com.esri.core.portal.PortalGroup;
import com.esri.core.portal.PortalInfo;
import com.esri.core.portal.PortalItem;
import com.esri.core.portal.PortalItemType;
import com.esri.core.portal.PortalQueryParams;
import com.esri.core.portal.PortalQueryResultSet;
import com.esri.core.portal.WebMap;
import com.esri.map.JMap;

/**
 * This sample shows how to use the Portal API classes to find featured groups in 
 * a portal, search for web maps within a portal group, and load/display web maps.
 * The portal used in this sample is ArcGIS Online (arcgis.com) but the same API 
 * can be used against any portal instance.
 * <p>
 * The steps are as follows:
 * <ol>
 * <li>Create a {@link Portal} instance using the portal URL and appropriate user credentials
 * <li>Fetch the list of featured group query strings from the portal via its {@link PortalInfo}
 * <li>Loop through the list of queries and retrieve each {@link PortalGroup} using Portal's 
 * <code>findGroups</code> method 
 * <li>For each portal group, fetch the title and display it in a list
 * <li>For the selected group, fetch the group's WebMap content items using Portal's 
 * <code>findItems</code> method
 * <li>For each WebMap found, display it in a list
 * <li>When a WebMap list item is selected, display it in the application.
 * </ol>
 *
 */
public class FeaturedGroupListApp {
  
  private JList<MyGroup> portalGroupList;
  private JList<MyItem> webMapList;
  private JComponent contentPane;
  private JProgressBar progressBar;

  private String PORTAL_URL = "https://arcgis.com/";
  private UserCredentials credentials;
  private Portal myPortal;

  private ArrayList<MyGroup> portalGroupData = new ArrayList<>();
  private ArrayList<MyItem> webMapData = new ArrayList<>();

  private FetchPortalThread fetchPortalThread = new FetchPortalThread();
  private JMap map;

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  private class FetchPortalThread extends Thread {
    @Override
    public void run() {
      try {
        updateProgressBarUI("Fetching portal groups...", true);

        credentials = new UserCredentials();
        credentials.setUserAccount("democsf", "devdemo");

        myPortal = new Portal(PORTAL_URL, credentials);

        // get the list of query strings for getting the portal's featured groups
        List<String> querys = myPortal.fetchPortalInfo().getFeaturedGroupsQueries();

        // loop through list of query strings to find each featured group in your portal
        for (String query : querys) {
          PortalQueryResultSet<PortalGroup> result = myPortal.findGroups(new PortalQueryParams(query));
          for (final PortalGroup group : result.getResults()) {
            MyGroup mygroup = new MyGroup(group);
            portalGroupData.add(mygroup);
          }
        }

        if (portalGroupData.size() == 0) {
          JOptionPane.showMessageDialog(contentPane.getParent(),
              "There are no portal groups.", "", JOptionPane.ERROR_MESSAGE);
        }
        portalGroupList.setListData(portalGroupData.toArray(new MyGroup[portalGroupData.size()]));
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(contentPane.getParent(),
            wrap("Failed to fetch the portal groups: " + ex.getLocalizedMessage()), "", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
      }
      updateProgressBarUI(null, false);
    }
  }

  private class ListWebMaps implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent event) {
      //clear the current lists
      webMapData.clear();
      webMapList.setListData(new MyItem[0]);

      //get the selected portal group
      if (portalGroupList.isSelectionEmpty()){
        JOptionPane.showMessageDialog(contentPane.getParent(),
            "There is no selected portal group.", "",
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      updateProgressBarUI("Fetching web maps...", true);

      PortalGroup selectedGroup = portalGroupData.get(
          portalGroupList.getSelectedIndex()).getGroup();

      // Set up the query with the groupId and select only those items
      // that are web maps
      PortalQueryParams queryParams = new PortalQueryParams();
      queryParams.setQuery(PortalItemType.WEBMAP, selectedGroup.getGroupId(), null);

      PortalQueryResultSet<PortalItem> results;
      try {
        results = myPortal.findItems(queryParams);

        for (PortalItem item : results.getResults()) {
          MyItem portalItemData = new MyItem(item);
          webMapData.add(portalItemData);
        }
      } catch (Exception e) {
        JOptionPane.showMessageDialog(contentPane.getParent(),
            wrap("An error occured while finding WebMap items: " + e.getLocalizedMessage()), "",
            JOptionPane.ERROR_MESSAGE);
      }

      if (webMapData.size() == 0) {
        JOptionPane.showMessageDialog(contentPane.getParent(),
            "There are no WebMap items for this group.", "",
            JOptionPane.ERROR_MESSAGE);
      }

      //display the list of webmaps
      webMapList.setListData(webMapData.toArray(new MyItem[0]));

      updateProgressBarUI(null, false);
    }
  }

  private class DisplayWebMap implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
      if (webMapList.isSelectionEmpty()){
        JOptionPane.showMessageDialog(contentPane.getParent(),
            "There is no selected webmap item.", "",
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      //get the selected portal item from the list
      PortalItem selectedItem = webMapData.get(
          webMapList.getSelectedIndex()).getItem();

      try {
        // create a WebMap using the portal item
        WebMap webMap = WebMap.newInstance(selectedItem);
        // display the web map
        map.loadWebMap(webMap);
      } catch (Exception e) {
        JOptionPane.showMessageDialog(contentPane.getParent(),
            wrap("Error creating the web map: " + e.getLocalizedMessage()), "",
            JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
      }
    }
  }

  // ------------------------------------------------------------------------
  // Nested classes
  // ------------------------------------------------------------------------
  /**
   * This class is used to store the PortalGroup and to display the group's title in our UI component.
   */
  private class MyGroup {
    private PortalGroup group;

    public MyGroup(PortalGroup pg) {
      this.group = pg;
    }

    @Override
    public String toString() {
      return group.getTitle();
    }

    public PortalGroup getGroup() {
      return group;
    }
  }

  /**
   * This class is used to store the PortalItem and to display the item's title in our UI component.
   */
  private class MyItem {
    private PortalItem item;

    public MyItem(PortalItem item) {
      this.item = item;
    }

    @Override
    public String toString() {
      return item.getTitle();
    }

    public PortalItem getItem(){
      return item;
    }
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  /**
   * Starting point of this application.
   *
   * @param args
   *            arguments to this application.
   */
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          FeaturedGroupListApp featuredGroupApp = new FeaturedGroupListApp();

          // create the UI, including the map, for the application.
          JFrame appWindow = featuredGroupApp.createWindow();
          appWindow.add(featuredGroupApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          // on any error, display the stack trace.
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------
  /**
   * Creates and displays the UI, including the map, for this application.
   */
  public JComponent createUI() throws Exception {
    // application content
    contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout());

    // progress bar
    progressBar = createProgressBar(contentPane);

    // fetch portal asynchronously
    fetchPortalThread.start();

    // panel to display list of Portal Groups
    JPanel groupListPanel = new JPanel();
    groupListPanel.setLayout(new BoxLayout(groupListPanel, BoxLayout.Y_AXIS));
    groupListPanel.setBorder(BorderFactory
        .createTitledBorder("Portal Groups"));
    portalGroupList = new JList<>();
    portalGroupList.setVisibleRowCount(6);
    JButton listWebMapsButton = new JButton("List WebMaps for selected Portal Group");
    listWebMapsButton.addActionListener(new ListWebMaps());

    JScrollPane listScroll = new JScrollPane(portalGroupList);
    listScroll.setAlignmentX(Component.LEFT_ALIGNMENT);
    groupListPanel.add(listScroll);
    groupListPanel.add(listWebMapsButton);

    // panel to display list of WebMaps
    JPanel webMapListPanel = new JPanel();
    webMapListPanel.setLayout(new BoxLayout(webMapListPanel, BoxLayout.Y_AXIS));
    webMapListPanel.setBorder(BorderFactory
        .createTitledBorder("WebMaps"));
    webMapList = new JList<>();
    webMapList.setVisibleRowCount(6);
    JButton displayWebMapButton = new JButton("Display selected WebMap");
    displayWebMapButton.addActionListener(new DisplayWebMap());

    JScrollPane webMapScroll = new JScrollPane(webMapList);
    webMapScroll.setAlignmentX(Component.LEFT_ALIGNMENT);
    webMapListPanel.add(webMapScroll);
    webMapListPanel.add(displayWebMapButton);

    // panel to contain 2 list panels - Portal Groups and WebMaps
    JPanel listPanel = new JPanel();
    listPanel.setLayout(new BoxLayout(listPanel, BoxLayout.X_AXIS));
    listPanel.add(groupListPanel);
    listPanel.add(webMapListPanel);
    
    // panel for displaying web maps
    JPanel mapPanel = new JPanel();
    mapPanel.setLayout(new BorderLayout());
    mapPanel.setMinimumSize(new Dimension(500, 500));
    map = new JMap();
    mapPanel.add(map, BorderLayout.CENTER);

    // add lists and map to content pane
    contentPane.add(mapPanel, BorderLayout.CENTER);
    contentPane.add(listPanel, BorderLayout.NORTH);
    contentPane.add(progressBar, BorderLayout.SOUTH);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * Creates the application window. Dispose the JMap on application exit.
   *
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Portal Featured Groups Application");
    window.setBounds(100, 100, 1000, 700);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent windowEvent) {
        super.windowClosing(windowEvent);
        if (map != null) {
          map.dispose();
        }
      }
    });
    return window;
  }

  /**
   * Creates a progress bar.
   * @param parent progress bar's parent. The horizontal axis of the progress bar will be
   * center-aligned to the parent.
   * @return a progress bar.
   */
  private static JProgressBar createProgressBar(final JComponent parent) {
    final JProgressBar progressBar = new JProgressBar();
    progressBar.setSize(260, 20);
    parent.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentResized(ComponentEvent e) {
        progressBar.setLocation(
            parent.getWidth()/2 - progressBar.getWidth()/2,
            parent.getHeight() - progressBar.getHeight() - 20);
      }
    });
    progressBar.setStringPainted(true);
    progressBar.setIndeterminate(true);
    progressBar.setVisible(false);
    return progressBar;
  }

  /**
   * Updates progress bar UI from Swing's Event Dispatch Thread.
   * @param str string to be displayed in the progress bar
   * @param visible flag to indicate visibility of the progress bar.
   */
  private void updateProgressBarUI(final String str, final boolean visible) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        if (str != null) {
          progressBar.setString(str);
        }
        progressBar.setVisible(visible);
      }
    }); 
  }
  
  private String wrap(String str) {
    // create a HTML string that wraps text when longer
    return "<html><p style='width:200px;'>" + str + "</html>";
  }
}
Feedback on this topic?