Geoprocessing task info

Download Sample Viewer

Description

This application creates a local geoprocessing service from a chosen geoprocessing package (.gpk) and displays the information contained in the service about the task and the task parameters.

Code snippet


    // how to get the GPServiceInfo from the service URL
    GPServiceInfo serviceInfo = GPServiceInfo.fromUrl(localGpService.getUrlGeoprocessingService());

    // how to get tasks Strings from GPServiceInfo
    for (String task : serviceInfo.getTasks()) {
        taskBox.addItem(task);
    }

    // how to get the GPTaskInfo from the task URL
    String taskUrl = localGpService.getUrlGeoprocessingService() + "/" + taskString;
    taskUrl = taskUrl.replaceAll("\\s", "%20");
    GPTaskInfo taskInfo = GPTaskInfo.fromUrl(taskUrl);
  

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.geoprocessing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
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.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Arrays;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.esri.client.local.GPServiceType;
import com.esri.client.local.LocalGeoprocessingService;
import com.esri.client.local.LocalServiceStartCompleteEvent;
import com.esri.client.local.LocalServiceStartCompleteListener;
import com.esri.client.local.LocalServiceStatus;
import com.esri.toolkit.utilities.BrowserLauncher;
import com.esri.core.tasks.ags.geoprocessing.GPServiceInfo;
import com.esri.core.tasks.ags.geoprocessing.GPTaskInfo;
import com.esri.core.tasks.ags.geoprocessing.GPTaskInfo.GPParameterInfo;
import com.esri.runtime.ArcGISRuntime;

/**
 * This application creates a local geoprocessing service from a geoprocessing package
 * (.gpk) and displays the information contained in the service about the task and
 * the task parameters.
 */
public class LocalGPTaskInfoApp {

  private LocalGeoprocessingService localGpService;
  private String taskUrl;

  // swing components
  private JComponent contentPane;
  private JTextField gpkTextField;
  private JTextArea paramTextArea;
  private JTextArea taskTextArea;
  private JComboBox<String> taskBox;
  private UrlLabel urlLabel;
  private JProgressBar progressBar;

  // constants
  private static final String DEFAULT_GPK = "gpks/SimpleBuffer/SimpleBuffer.gpk";
  private static final int SPACING = 5;
  private static String FSP = System.getProperty("file.separator");

  // ------------------------------------------------------------------------
  // Constructor
  // ------------------------------------------------------------------------
  public LocalGPTaskInfoApp() { }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  private GPTaskInfo getGPTaskInfo(String task) {

    // get the task URL
    taskUrl = localGpService.getUrlGeoprocessingService() + "/" + task;
    taskUrl = taskUrl.replaceAll("\\s", "%20");

    // get the GPTaskInfo from the task URL
    GPTaskInfo taskInfo = null;
    try {
      taskInfo = GPTaskInfo.fromUrl(taskUrl);
    } catch (Exception e) {
      System.err.println("Exception at GPTaskInfo creation");
      e.printStackTrace();
    }
    return taskInfo;
  }

  /**
   * Creates and starts a local geoprocessing service from the provided path to a 
   * GPK, and once the service has started, gets the tasks via the geoprocessing 
   * service info.
   * @param gpkPath
   */
  private void getGPTasks(String gpkPath) {

    // create and start the local geoprocessing service
    localGpService = new LocalGeoprocessingService(gpkPath);
    localGpService.setServiceType(GPServiceType.EXECUTE);
    localGpService.addLocalServiceStartCompleteListener(new LocalServiceStartCompleteListener() {

      @Override
      public void localServiceStartComplete(LocalServiceStartCompleteEvent arg0) {

        if (localGpService.getStatus() == LocalServiceStatus.STARTED) {
          // get GP service info
          GPServiceInfo serviceInfo = null;
          try {
            serviceInfo = GPServiceInfo.fromUrl(localGpService.getUrlGeoprocessingService());
            // clear previous tasks
            taskBox.removeAllItems();
            // get tasks from service and add to comboBox
            for (String task : serviceInfo.getTasks()) {
              taskBox.addItem(task);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        } else {
          showErrorMsg("Service was unable to start. Service status: " + localGpService.getStatus());
        }
        updateProgressBarUI(null, false);
      }
    });
    // start the local gp service asynchronously
    localGpService.startAsync();
  }

  /**
   * Updates the UI with the task and parameter info for a given task. 
   * Called e.g. when a new task is selected from the combo box.
   * @param taskName
   */
  private void updateUI(final String taskName) {
    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {
        if (localGpService != null) {

          // get GP task info for the task and display
          GPTaskInfo taskInfo = getGPTaskInfo(taskName);
          displayTaskInfo(taskInfo);

          // get and display the parameter info for this task
          GPParameterInfo[] parameters = taskInfo.getParameters();
          displayParameterInfo(parameters);
        }
        contentPane.getParent().repaint();
      }
    });
  }

  /**
   * Displays the task info to a text area
   * @param taskInfo
   */
  private void displayTaskInfo(GPTaskInfo taskInfo) {

    // display clickable help URL
    urlLabel.setText(taskUrl);
    urlLabel.setUrl(taskUrl);

    // display task info
    taskTextArea.setText("Display name: " + taskInfo.getDisplayName() + "\n");
    taskTextArea.append("Category: " + taskInfo.getCategory() + "\n");
    taskTextArea.append("Execution type: " + taskInfo.getExecutionType() + "\n");
  }

  /**
   * Displays the parameter info to a text area
   * @param parameters
   */
  private void displayParameterInfo(GPParameterInfo[] parameters) {

    paramTextArea.setText("");
    for (GPParameterInfo parameter : parameters) {
      paramTextArea.append("Parameter: "+parameter.getName() +"\n");
      paramTextArea.append("\tDisplay name: "+parameter.getDisplayName()+"\n");
      paramTextArea.append("\tCategory: "+parameter.getCategory()+"\n");
      paramTextArea.append("\tData type: "+parameter.getDataType()+"\n");
      paramTextArea.append("\tDefault value: "+parameter.getDefaultValue()+"\n"); // to string?
      paramTextArea.append("\tDirection: "+parameter.getDirection()+"\n");
      paramTextArea.append("\tParameter type: "+parameter.getParameterType()+"\n");
      paramTextArea.append("\tChoice list: "+Arrays.toString(parameter.getChoiceList())+"\n\n");
    }
  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------
  /**
   * Creates and displays the UI, including the map, for this application.
   * @return the UI for this sample.
   */
  public JComponent createUI() {

    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(SPACING, SPACING, SPACING, SPACING));
    contentPane.setLayout(new BorderLayout(0, 0));

    // progress bar
    progressBar = new JProgressBar();
    progressBar.setSize(200, 20);
    contentPane.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentResized(ComponentEvent e) {
        progressBar.setLocation(
            contentPane.getWidth()/2 - progressBar.getWidth()/2,
            contentPane.getHeight() - progressBar.getHeight() - 20);
      }
    });
    progressBar.setStringPainted(true);
    progressBar.setIndeterminate(true);
    progressBar.setVisible(false);

    JPanel topPanel = new JPanel();
    topPanel.setMinimumSize(new Dimension(550, 85));
    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));

    topPanel.add(Box.createRigidArea(new Dimension(0,10)));
    topPanel.add(createLoadPanel());
    topPanel.add(Box.createRigidArea(new Dimension(0,10)));
    topPanel.add(createTaskPanel());
    topPanel.add(Box.createRigidArea(new Dimension(0,10)));

    JPanel parameterPanel = createParameterPanel();

    contentPane.add(topPanel, BorderLayout.NORTH);
    contentPane.add(parameterPanel, BorderLayout.CENTER);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // 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
          LocalGPTaskInfoApp gpApp = new LocalGPTaskInfoApp();

          // create the UI, including the map, for the application
          JFrame appWindow = createWindow();
          appWindow.add(gpApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------

  private JPanel createTaskPanel() {

    JPanel panel = new JPanel();
    panel.setMinimumSize(new Dimension(550, 85));
    panel.setLayout(new BorderLayout(0, 5));
    panel.setAlignmentX(Component.LEFT_ALIGNMENT);

    taskBox = new JComboBox<>();
    taskBox.setMinimumSize(new Dimension(300, 40));
    taskBox.setAlignmentX(Component.LEFT_ALIGNMENT);
    taskBox.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        String taskName = (String) ((JComboBox<String>) e.getSource()).getSelectedItem();
        if (taskName != null) {
          updateUI(taskName);
        }
      }
    });

    JPanel urlPanel = new JPanel();
    urlPanel.setLayout(new BoxLayout(urlPanel, BoxLayout.X_AXIS));
    urlPanel.add(new JLabel("Task URL:   "));
    urlLabel = new UrlLabel("","");
    urlPanel.add(urlLabel);

    taskTextArea = new JTextArea();
    taskTextArea.setEditable(false);
    taskTextArea.setRows(4);

    panel.add(taskBox, BorderLayout.NORTH);
    panel.add(urlPanel, BorderLayout.CENTER);
    panel.add(taskTextArea, BorderLayout.SOUTH);
    panel.setBorder(BorderFactory.createTitledBorder("Tasks in the geoprocessing service:"));

    return panel;
  }

  private JPanel createParameterPanel() {

    JPanel panel = new JPanel();
    panel.setMinimumSize(new Dimension(550, 85));
    panel.setLayout(new BorderLayout(0, 5));
    panel.setAlignmentX(Component.LEFT_ALIGNMENT);

    paramTextArea = new JTextArea();
    paramTextArea.setEditable(false);
    paramTextArea.setRows(20);
    JScrollPane scrollPane = new JScrollPane(paramTextArea);
    scrollPane.setAutoscrolls(true);

    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setBorder(BorderFactory.createTitledBorder("Parameter Info for this task:"));

    return panel;
  }

  private JPanel createLoadPanel() {
    JPanel panel = new JPanel();
    panel.setMinimumSize(new Dimension(550, 85));
    panel.setLayout(new BorderLayout(0, 5));
    panel.setAlignmentX(Component.LEFT_ALIGNMENT);

    gpkTextField = new JTextField(getPathSampleData() + DEFAULT_GPK);
    JPanel buttonPanel = createButtonPanel();

    panel.add(gpkTextField, BorderLayout.CENTER);
    panel.add(buttonPanel, BorderLayout.SOUTH);
    panel.setBorder(BorderFactory.createTitledBorder("Select a Geoprocessing Package (*.gpk) by browsing to a file or " +
        "entering the path below, then click 'Get tasks':"));

    return panel;
  }

  private JPanel createButtonPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    JButton loadButton = createLoadButton();
    JButton openButton = createBrowseButton();
    panel.setBackground(new Color(0, 0, 0, 0));
    panel.add(openButton);
    panel.add(Box.createRigidArea(new Dimension(5,0)));
    panel.add(loadButton);
    panel.add(Box.createRigidArea(new Dimension(5,0)));
    panel.add(progressBar);
    return panel;
  }

  private JButton createLoadButton() {
    JButton loadButton = new JButton("Get tasks");
    loadButton.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        progressBar.setVisible(true);
        progressBar.setString("Getting tasks...");

        // get the gpk path from the UI
        String gpkPath = gpkTextField.getText();
        // get GP task info
        getGPTasks(gpkPath);
      }
    });
    return loadButton;
  }

  private JButton createBrowseButton() {
    final JFileChooser fileChooser = new JFileChooser(getPathSampleData() + "gpks");
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "Geoprocessing Packages (GPKs)", "gpk");
    fileChooser.setFileFilter(filter);
    JButton button = new JButton("Browse for a GPK");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        int returnVal = fileChooser.showOpenDialog(contentPane);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
          String tpkPath = null;
          try {
            tpkPath = fileChooser.getSelectedFile().getPath();
          }
          catch (Exception e) {
            showErrorMsg("Unable to load the geoprocessing package. " +
                "Check that the path is correct or try another geoprocessing package.");
            e.printStackTrace();
          }
          finally {
            gpkTextField.setText(tpkPath);
          }
        }
      }
    });

    return button;
  }

  private void showErrorMsg(String message) {
    JOptionPane.showMessageDialog(contentPane.getParent(), wrap(message),
        "", JOptionPane.ERROR_MESSAGE);
  }

  /**
   * Creates a window.
   * @return a window.
   */
  private static JFrame createWindow() {
    JFrame window = new JFrame("Geoprocessing Task Info");
    window.setBounds(100, 100, 1000, 700);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout(0, 0));
    return window;
  }

  private String getPathSampleData() {
    String dataPath = null;
    String javaPath = ArcGISRuntime.getInstallDirectory();
    if (javaPath != null) {
      if (!(javaPath.endsWith("/") || javaPath.endsWith("\\"))){
        javaPath += FSP;
      }
      dataPath = javaPath + "sdk" + FSP + "samples" + FSP + "data" + FSP;
    }
    File dataFile = new File(dataPath);
    if (!dataFile.exists()) { 
      dataPath = ".." + FSP + "data" + FSP;
    }
    return dataPath;
  }

  /**
   * Updates progress bar UI from the Swing's Event Dispatch Thread.
   * @param str string to be set.
   * @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);
      }
    }); 
  }

  class UrlLabel extends JLabel {

    private static final long serialVersionUID = 1L;
    private String url;
    private Color selected_color = new Color(160,160,160);
    private Color link_color = Color.BLUE;

    UrlLabel(String labelText, String url) {
      super(labelText);
      this.url = url;
      setForeground(link_color);
      addMouseListener(new UrlMouseListener());
    }

    public String getUrl() {
      return url;
    }

    public void setUrl(String url) {
      this.url = url;
    }

    class UrlMouseListener extends MouseAdapter {

      @Override
      public void mouseEntered(MouseEvent event) {
        handleMouseEntered();
      }

      @Override
      public void mouseExited(MouseEvent event) {
        handleMouseExited();
      }

      @Override
      public void mouseClicked(MouseEvent event) {
        handleMouseClicked();
      }

    }

    void handleMouseEntered() {
      setForeground(selected_color);
      setCursor(new Cursor(Cursor.HAND_CURSOR));
    }

    void handleMouseExited() {
      setForeground(link_color);
      setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }

    void handleMouseClicked() {
      BrowserLauncher.openURL(url);
    }

  }
  
  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?