Dynamic workspaces raster

Download Sample Viewer

Description

This sample shows how to connect to a raster folder and display a raster 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.DynamicLayerInfo;
import com.esri.core.map.DynamicLayerInfoCollection;
import com.esri.core.map.LayerDataSource;
import com.esri.core.map.RasterDataSource;
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 raster folder and display a raster
 * 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 LocalRasterApp {

  private JMap map;
  private JButton button;
  private volatile int count = 0;
  private JLayeredPane contentPane;
  private static final String FSP = System.getProperty("file.separator");

  // ------------------------------------------------------------------------
  // Default constructor
  // ------------------------------------------------------------------------
  public LocalRasterApp() { }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  /**
   * Set up raster workspace
   */
  private void addRaster(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. raster folder connection
    WorkspaceInfo workspaceInfo = WorkspaceInfo.CreateRasterFolderConnection(
        workspaceId, fileDir);
    // also:
    // --> WorkspaceInfo.CreateSDEConnection
    // --> WorkspaceInfo.CreateShapefileFolderConnection
    // --> 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);

            // Create the raster data source
            RasterDataSource dataSource = new RasterDataSource();
            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
          LocalRasterApp rasterApp = new LocalRasterApp();

          // create the UI, including the map, for the application.
          JFrame appWindow = createWindow();
          appWindow.add(rasterApp.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() + "rasters");
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "Rasters (*.bmp,*.png,*.sid,*.tif)", "sid", "bmp", "png", "tif");
    fileChooser.setFileFilter(filter);
    JButton button1 = new JButton("Add Raster");
    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 fileDir = fileChooser.getSelectedFile().getParent();

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

  private void showErrorMsg(String message) {
    JOptionPane.showMessageDialog(contentPane, 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 raster folder and display raster data in a map. Click the " +
        "button to select a local raster 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?