Dynamic workspaces shapefile

Download Sample Viewer

Description

This sample shows how to connect to a shapefile folder and display a shapefile (.shp) in a Java application using the API's dynamic workspaces functionality. In this application, a local map service is created using a map package (.mpk) and dynamic layers are enabled before the service is started using localMapService.setEnableDynamicLayers(true).

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.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.esri.client.local.ArcGISLocalTiledLayer;
import com.esri.client.local.LocalMapService;
import com.esri.client.local.WorkspaceInfo;
import com.esri.client.local.WorkspaceInfoSet;
import com.esri.core.geometry.Envelope;
import com.esri.core.map.DrawingInfo;
import com.esri.core.map.DynamicLayerInfo;
import com.esri.core.map.DynamicLayerInfoCollection;
import com.esri.core.map.LayerDataSource;
import com.esri.core.map.TableDataSource;
import com.esri.core.renderer.SimpleRenderer;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.map.ArcGISDynamicMapServiceLayer;
import com.esri.map.JMap;
import com.esri.map.LayerInitializeCompleteEvent;
import com.esri.map.LayerInitializeCompleteListener;
import com.esri.runtime.ArcGISRuntime;

/***
 * This sample shows how to connect to a shapefile folder and display a shapefile
 * (.shp) in a Java application using the API's dynamic workspaces functionality. 
 * In this application, a local map service is created using a map 
 * package (.mpk) and dynamic layers are enabled before the service is 
 * started using <code>localMapService.setEnableDynamicLayers(true)</code>.
 */
public class LocalShapefileApp {

  private JMap map;
  private JButton button;
  private volatile int count = 0;
  private JLayeredPane contentPane;
  private SimpleRenderer simpleRenderer =
      new SimpleRenderer(new SimpleLineSymbol(new Color(0, 100, 250), 3));
  private static final int TRANSPARENCY = 20; // 0 is opaque, 100 is transparent
  private static final String FSP = System.getProperty("file.separator");

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

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------

  /**
   * Set up shapefile workspace
   */
  private void addShapefile(final String fileName, final String fileDir) {

    final String workspaceId = ""+count++; // an arbitrary unique string

    // create a local map service and enable dynamic layers
    LocalMapService localMapService = new LocalMapService(
        getPathSampleData() + "mpks" + FSP + "mpk_blank.mpk");
    localMapService.setEnableDynamicLayers(true);

    // get dynamic workspaces from service
    WorkspaceInfoSet workspaceInfoSet = localMapService.getDynamicWorkspaces();

    // create a workspace info via the static method according to data type
    // e.g. shapefile folder connection
    WorkspaceInfo workspaceInfo = WorkspaceInfo.CreateShapefileFolderConnection(
        workspaceId, fileDir);
    // also:
    // --> WorkspaceInfo.CreateSDEConnection
    // --> WorkspaceInfo.CreateRasterFolderConnection
    // --> WorkspaceInfo.CreateFileGeoDatabaseConnection

    // set dynamic workspaces for our local map service
    workspaceInfoSet.add(workspaceInfo);
    localMapService.setDynamicWorkspaces(workspaceInfoSet);

    // now start service...
    localMapService.start();

    // set up a local dynamic layer
    final ArcGISDynamicMapServiceLayer localDynamicLayer = new ArcGISDynamicMapServiceLayer(
        localMapService.getUrlMapService());

    // add the layer to the map
    map.getLayers().add(localDynamicLayer);

    localDynamicLayer
        .addLayerInitializeCompleteListener(new LayerInitializeCompleteListener() {
          @Override
          public void layerInitializeComplete(LayerInitializeCompleteEvent arg0) {
            if (arg0.getID() == LayerInitializeCompleteEvent.LOCALLAYERCREATE_ERROR) {
              String errMsg = "Failed to initialize due to "
                  + localDynamicLayer.getInitializationError();
              showErrorMsg(errMsg);
            }
            DynamicLayerInfoCollection layerInfos = localDynamicLayer
                .getDynamicLayerInfos();
            DynamicLayerInfo layerInfo = layerInfos.get(0);

            /*
             * Apply a renderer for dynamic layers. Note: It is always necessary
             * to provide a renderer, but the renderer provided does not need to
             * be valid with regard to the actual layer and geometry type, it
             * simply needs to be a valid renderer. If the renderer specified
             * here is not appropriate for the geometry type of the layer the
             * symbology will fall back to a default SimpleMarkerSymbol,
             * SimpleLineSymbol or SimpleFillSymbol.
             */
            DrawingInfo drawingInfo = new DrawingInfo(simpleRenderer,
                TRANSPARENCY);
            layerInfo.setDrawingInfo(drawingInfo);

            // Create the data source
            TableDataSource dataSource = new TableDataSource();
            dataSource.setWorkspaceId(workspaceId);
            dataSource.setDataSourceName(fileName);

            // Set the data source
            LayerDataSource layerDataSource = new LayerDataSource();
            layerDataSource.setDataSource(dataSource);
            layerInfo.setLayerSource(layerDataSource);

            localDynamicLayer.refresh();
          }
        });
  }

  // ------------------------------------------------------------------------
  // 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
          LocalShapefileApp shapefileApp = new LocalShapefileApp();

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

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------

  public JComponent createUI() {
    // application content
    contentPane = createContentPane();

    // UI elements
    JPanel buttonPanel = createUserPanel();
    contentPane.add(buttonPanel);

    // map
    map = createMap();
    contentPane.add(map);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * Creates the JMap, adds a base layer
   * @return a map
   */
  private JMap createMap() {

    final JMap jMap = new JMap();

    ArcGISLocalTiledLayer tiledLayer = new ArcGISLocalTiledLayer(
        getPathSampleData() + "tpks" + FSP + "Topographic.tpk");
    jMap.getLayers().add(tiledLayer);
    
    jMap.setExtent(new Envelope(-19856505, -8827900, 18574809, 16806021));

    return jMap;
  }

  private JPanel createUserPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout(0, 0));
    panel.setSize(240, 140);
    panel.setLocation(10, 10);

    // description
    JTextArea description = createDescription();

    // button
    button = createButton();

    panel.add(description, BorderLayout.CENTER);
    panel.add(button, BorderLayout.SOUTH);
    panel.setBackground(new Color(0, 0, 0, 0));
    panel.setBorder(new LineBorder(new Color(0, 0, 0, 80), 5, false));

    return panel;
  }

  private JButton createButton() {
    final JFileChooser fileChooser = new JFileChooser(getPathSampleData() + "shapefiles");
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "Shapefiles (.shp)", "shp");
    fileChooser.setFileFilter(filter);
    JButton button1 = new JButton("Add Shapefile");
    button1.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        int returnVal = fileChooser.showOpenDialog(contentPane);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
          try {
            String fileNameRaw = fileChooser.getSelectedFile().getName();
            String fileName = fileNameRaw.substring(0, fileNameRaw.length()-4);
            String fileDir = fileChooser.getSelectedFile().getParent();

            addShapefile(fileName, fileDir);
          }
          catch (Exception e) {
            showErrorMsg("Unable to load the shapefile. " +
                "Check that the path is correct or try another shapefile.");
            e.printStackTrace();
          }
        }
      }
    });
    return button1;
  }

  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();
    window.setBounds(100, 100, 1000, 700);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout(0, 0));
    window.setVisible(true);
    return window;
  }

  /**
   * Creates a content pane.
   * @return a content pane.
   */
  private static JLayeredPane createContentPane() {
    JLayeredPane contentPane = new JLayeredPane();
    contentPane.setBounds(100, 100, 1000, 700);
    contentPane.setLayout(new BorderLayout(0, 0));
    contentPane.setVisible(true);
    return contentPane;
  }

  /**
   * Creates a description for this application.
   * @return description
   */
  private JTextArea createDescription() {
    JTextArea description = new JTextArea(
        "This application shows how to create a dynamic workspace connection " +
            "to a shapefile folder and display shapefile data in a map. Click the " +
        "button to select a local shapefile and add it to the map.");
    description.setFont(new Font("Verdana", Font.PLAIN, 11));
    description.setForeground(Color.WHITE);
    description.setEditable(false);
    description.setLineWrap(true);
    description.setWrapStyleWord(true);
    description.setBackground(new Color(0, 0, 0, 180));
    description.setBorder(BorderFactory.createEmptyBorder(5,10,5,5));
    return description;
  }

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