Console app

Download Sample Viewer

Description

This application shows a simple way to use the Local Server within a console application. It uses only synchronous methods and no asynchronous callbacks. This ensures there is just one thread of execution which is typical of console applications and keeps the flow simple. The Local Server and Local Services can be started synchronously, then using synchronous methods on tasks like Query ensure the results are retured to the calling thread.

Code snippet


    // initialize the Local Server synchronously
    LocalServer.getInstance().initialize();

    // create local map service and start synchronously
    LocalMapService localMapService = new LocalMapService("file path to .mpk");
    localMapService.start();

    // ... create and execute a query synchronously ...

    // when query done shutdown the local server synchronously
    LocalServer.getInstance().shutdown();
  

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

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;

import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import com.esri.client.local.LocalMapService;
import com.esri.client.local.LocalServer;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
import com.esri.runtime.ArcGISRuntime;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Iterator;

/***
 * This application shows a simple way to use the ArcGIS Runtime local server within a console 
 * application. It uses only synchronous methods and no asynchronous callbacks. This ensures 
 * there is just one thread of execution which is typical of console applications and keeps 
 * the flow simple. The local server and local services can be started synchronously, then 
 * using synchronous methods on tasks like the query task ensure the results are retured to 
 * the calling thread.
 */
public class ConsoleApp {

  // Swing components
  private JTextArea consoleArea;
  private JButton btnStart;

  // UI constants
  private static final int SPACING = 5;
  private static final int BUTTON_HEIGHT = 40;
  private static final int BUTTON_WIDTH = 250;
  private static String FSP = System.getProperty("file.separator");

  /**
   * Constructor.
   */
  public ConsoleApp() { }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  /**
   * A listener class which starts the sample.
   */
  public class StartSample implements ActionListener {

    private static final String WHERE = "POP2000 > 1000000";

    @Override
    public void actionPerformed(ActionEvent arg0) {

      // deactivate button once it's been clicked
      ((JButton) arg0.getSource()).setEnabled(false);

      writeToConsoleArea("Starting Local Server ...");

      // initialize the Local Server synchronously
      LocalServer.getInstance().initialize();

      writeToConsoleArea("Starting Local Map Service ...");

      LocalMapService localMapService =
          new LocalMapService(getPathSampleData() + "mpks" + FSP + "USCitiesStates.mpk");

      // start the local map service synchronously
      localMapService.start();

      // query some data from the first layer in the map service
      QueryTask queryTask = new QueryTask(localMapService.getUrlMapService() + "/0");

      QueryParameters query = new QueryParameters();
      query.setOutFields(new String[]{"*"});
      query.setWhere(WHERE);

      writeToConsoleArea("Querying US cities with a population of more than 1 million in the year 2000 ...");

      // execute a query synchronously
      FeatureResult featureSet;
      try {
        featureSet = queryTask.execute(query);

        if (featureSet != null) {
          // Output some results to the console area
          writeToConsoleArea("Found " + featureSet.featureCount() + " cities.");
          Iterator<Object> it = featureSet.iterator();
          while (it.hasNext()) {
            Object o = it.next();
            if (o instanceof Feature) {
              Feature feature = (Feature) o;
              Integer pop = (Integer) feature.getAttributeValue("POP2000");
              writeToConsoleArea(feature.getAttributeValue("AREANAME") + " population: " + pop);
            }
          }
        } else {
          writeToConsoleArea("No cities found.");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      // Shutdown the local server synchronously
      LocalServer.getInstance().shutdown();
      writeToConsoleArea("Sample complete.");
    }

  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------
  /**
   * Creates the UI for this application, including the buttons, combo box,
   * text area, and list.
   * @return contentPane
   */
  public JComponent createUI() {

    // content pane
    JComponent contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(SPACING, SPACING, SPACING, SPACING));
    contentPane.setLayout(new BorderLayout(SPACING, SPACING));

    // top panel
    JPanel topPanel = new JPanel();
    topPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

    Dimension preferredSize = new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT);
    Dimension fillerSize = new Dimension(20, 200);
    btnStart = new JButton("Start Console Sample");
    btnStart.setPreferredSize(preferredSize);
    btnStart.setAlignmentX(Component.LEFT_ALIGNMENT);
    btnStart.addActionListener(new StartSample());
    topPanel.add(btnStart);

    // text area for text output
    consoleArea = new JTextArea();
    consoleArea.setForeground(Color.WHITE);
    consoleArea.setBackground(Color.BLACK);
    consoleArea.setFont(new Font("Monospaced", Font.BOLD, 14));
    JScrollPane scrollPane = new JScrollPane(consoleArea);
    scrollPane.setAutoscrolls(true);

    contentPane.add(topPanel, BorderLayout.NORTH);
    contentPane.add(scrollPane, BorderLayout.CENTER);
    contentPane.add(new Box.Filler(fillerSize, fillerSize, fillerSize), BorderLayout.SOUTH);

    return contentPane;
  }

  private void writeToConsoleArea(final String text) {
    consoleArea.append(" > " + text + "\n");
    System.out.println(" > " + text);
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          ConsoleApp app = new ConsoleApp();

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

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

  /**
   * Creates a window.
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Console Application");
    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;
  }
}
Feedback on this topic?