arcgissamples\scenario\map\MapServerConnectionInfo.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
GIS Client
arcgissamples\scenario\map\MapServerConnectionInfo.java
/* Copyright 2015 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 at <your ArcGIS install location>/DeveloperKit10.4/userestrictions.txt.
* 
*/
package arcgissamples.scenario.map;

/** Helper class for performing map server tasks such as
 *  exporting the map, setting the image type ..etc.
 */

import java.io.IOException;
import java.util.Hashtable;
import java.util.TreeMap;
import java.util.Vector;

import com.esri.arcgis.carto.IImageDisplay;
import com.esri.arcgis.carto.IImageType;
import com.esri.arcgis.carto.ILayerDescription;
import com.esri.arcgis.carto.ILayerDescriptions;
import com.esri.arcgis.carto.IMapDescription;
import com.esri.arcgis.carto.IMapImage;
import com.esri.arcgis.carto.IMapLayerInfo;
import com.esri.arcgis.carto.IMapLayerInfos;
import com.esri.arcgis.carto.IMapServer;
import com.esri.arcgis.carto.IMapServerIdentifyResult;
import com.esri.arcgis.carto.IMapServerIdentifyResults;
import com.esri.arcgis.carto.IMapServerInfo;
import com.esri.arcgis.carto.ImageDescription;
import com.esri.arcgis.geometry.Envelope;
import com.esri.arcgis.geometry.IPoint;
import com.esri.arcgis.geometry.esriGeometryType;
import com.esri.arcgis.gisclient.AGSServerConnectionFactory;
import com.esri.arcgis.gisclient.IAGSEnumServerObjectName;
import com.esri.arcgis.gisclient.IAGSServerConnection;
import com.esri.arcgis.gisclient.IAGSServerObjectName;
import com.esri.arcgis.system.IPropertySet;
import com.esri.arcgis.system.LongArray;
import com.esri.arcgis.system.PropertySet;


public abstract class MapServerConnectionInfo {

  public static MapInfo mapInfo; //static instance of this class
  protected IMapServer server = null;
  protected IAGSServerConnection agsServerConnection;
  protected ImageDescription imageDescription;
  protected IImageType imageType = null;
  protected IImageDisplay imageDisplay = null;
  protected IMapImage mapImage;
  protected String activeMap;

  protected double dpi = 96.0;
  protected int imageWidth = 0;
  protected int imageHeight = 0;

  protected Hashtable<String, Object> serverObjectstable = null;
  String mapConfigurationName;

  public MapServerConnectionInfo() {
  }

  /**Initializes server object, layer descriptions, map descriptions.
   */

  public abstract void init();

  /**Sets the configuration name
  * @param mapConfigName
  */

 public void setMapConfigurationName(String mapConfigName) {
   mapConfigurationName = mapConfigName;
 }



  /**Method which returns vector of all the configurations currently available on the system
   * @param url webservices catalog url
   * @param connectionType can be either internet or lan
   * @return
   */

  public java.util.Vector getConfigurationList(String host, String connectionType) {
    Vector<String> mapConfigurations = new Vector<String>();
    try {

        AGSServerConnectionFactory agsServerConnectionFactory = new AGSServerConnectionFactory();
        PropertySet propertySet = new PropertySet();

        if(connectionType.equalsIgnoreCase("internet")) {
          propertySet.setProperty("CONNECTIONTYPE", "esriConnectionTypeInternet");
          propertySet.setProperty("URL", host);

        }
        else {
          propertySet.setProperty("CONNECTIONTYPE", "esriConnectionTypeLAN");
          propertySet.setProperty("machine", host);
        }

        if(serverObjectstable == null)
          serverObjectstable = new Hashtable<String, Object>();

        serverObjectstable.clear();
        agsServerConnection = agsServerConnectionFactory.open(propertySet,0);

        IAGSEnumServerObjectName agsServerObjectNames = agsServerConnection.getServerObjectNames();
        agsServerObjectNames.reset();

        IAGSServerObjectName serverObjectName = agsServerObjectNames.next();
        while (serverObjectName != null ){
          if (serverObjectName.getType().equalsIgnoreCase("mapserver")== true){
            mapConfigurations.add(serverObjectName.getName());
            serverObjectstable.put(serverObjectName.getName(), (Object)serverObjectName);
          }
          serverObjectName = agsServerObjectNames.next();
        }
    } catch (Exception e){
        e.printStackTrace();
        System.out.println(e.getMessage());

    }

    return mapConfigurations;

  }

  /**Returns number of maps in the server
   * @return int
   */

  public int getMapCount() {
    try {
      return server.getMapCount();
    }
    catch (IOException ex) {
      return 0;
    }
  }

  /**Returns the map name at the specified index
   * @param i
   * @return String
   */

  public String getMapName(int i) {
    try {
      return server.getMapName(i);
    }
    catch (IOException ex) {
      return null;
    }
  }


 /**Sets the image width and height
    * @param width
    * @param height
    */

   public void setImageSize(int width, int height) {
     imageWidth = width;
     imageHeight = height;
   }

  /**Sets the extent to the map description
  *@param env IEnvelope
  */

 public abstract void setExtent(Envelope env);


   /**Returns the current extent
   * @return
   */

  public abstract Envelope getExtent();


 /**Returns the focus map
  *
  */

  public String getActiveMap() {
      return activeMap;
  }

  /**Sets the focusmap
   * @return String
   */
  public void setActiveMap(String mapName) {
    activeMap = mapName;
  }


  /**Method to reset the map information.
   * Normally used when new map configuration is selected
   */

  public abstract void resetMapInfo();

  /**Returns mapdescription object for particular map
  * @param activeMap
  * @return IMapDescription
  */

 public abstract IMapDescription getMapDescription(String activeMap);



  /**Sets the layerDescription visibiliy in the LayerDescriptions
  * @param layer
  * @param dataFrameName
  * @param value
  */
 public void setLayerDescriptorVisibility(int ID, String mapFrameName,
                                          boolean visible) {
   try {
     ILayerDescriptions layerDescriptions = getMapDescription(mapFrameName).
         getLayerDescriptions();
     int count = layerDescriptions.getCount();
     ILayerDescription ld = null;
     for (int i = 0; i < count; i++) {
       ld = layerDescriptions.getElement(i);
       if (ld.getID() == ID)
         break;
     }
     ld.setVisible(visible);
   }
   catch (IOException ex) {
     ex.printStackTrace();
   }
 }


  /**Returns list of map objects contained in the mxd document
  * @return java.util.Vector
  */

  public java.util.Vector getMapNames() {
    Vector<String> v = new Vector<String>();
    try {
       for (int i = 0; i < server.getMapCount(); i++) {
         String mapName = server.getMapName(i);
         if(mapName != null)
           v.add(mapName);
        }

    }
    catch (IOException ex) {
      return null;
    }
    return v;
  }


 /**Stops the map server. Frees all the resources used by the server.
  */

  public abstract void stop();

  /**Sets the extent and exports the map image.
   * @param envelope
   * @return String containg the url
   */

  public abstract byte[] exportImage(Envelope envelope);

  /**Exports the map image.
   * @param envelope
   * @return String containg image location
   */


  public abstract byte[] exportImage();


  /**Converts an Envelope screen location to a map coordinate with Envelope as input
  * @param rect Envelope
  * @return IEnvelope with the transformed points
  */

  public abstract Envelope transformScreenToMap(Envelope1 rect);


 /**Converts an Envelope screen location to a map coordinate
   * @param int x
   * @param int y
   * @return IPoint
   */

  public abstract IPoint transformScreenToMap(int x, int y);


  /** In case of pooled objects, creates servercontext, loads the mapDescriptions
  * and imagedescription.For non pooled objects resets the mapdescription
  * Applicable only in case of LAN Connection
  */

  public abstract void activate();

  /**Releases context and save mapdescription and imagedescription objects
  * Applicable only in case of LAN Connection
  */

  public abstract void passivate();

  /**Creates new envelope
  */

  public abstract Envelope createNewEnvelope();



/*Method which returns a treemap containing layername and identifyinfo.
  * IdentifyInfo class is used to store the keys and values for a layer.
  * Identify results are stored as follows:
  *  <Layer 1> <field1> <keys> <values>
  *            <field2> <keys> <values>
  *            ....
  *
  *  <layer 2> <field1> <keys> <values>
  *             <field2> <keys> <values>
  *             ....
  * @param env
  * @param tolerence
  * @param option
  * @param layerids
  * @return java.util.TreeMap
  */

 public java.util.TreeMap identify(Envelope env, int tolerence, int option, LongArray layerids) {
    try {
     TreeMap<String, IdentifyInfo> treeMap = new TreeMap<String, IdentifyInfo>();
     IMapServerIdentifyResults identifyResults = server.identify(getMapDescription(activeMap), imageDisplay, env, tolerence, option, layerids);
     if ( identifyResults != null && identifyResults.getCount() > 0 ) {

       IMapServerIdentifyResult result;
       IPropertySet pset;

       Object objkeys[] = new Object[]{ new Object() };
       Object objvalues[] = new Object[]{ new Object() };
       String[] keys;
       Object[] vals;

       int lid = -1;

       for ( int i = 0; i < identifyResults.getCount(); i++ ) {
         result = identifyResults.getElement(i);
         lid = result.getLayerID();
         if (lid == -1)
           continue;

         pset = result.getProperties();
         pset.getAllProperties(objkeys, objvalues);
         keys = (String[]) objkeys[0];
         vals = (Object[]) objvalues[0];

         setShapeValue(keys, vals, result.getShape().getGeometryType());
         IMapLayerInfo mapLayerInfo = getLayerInfoFromID(result.getLayerID(), activeMap);
         String idField = mapLayerInfo.getDisplayField();
         if(idField != null) {
           String layerName = mapLayerInfo.getName();
           IdentifyInfo identifyData = null;
           if(treeMap.containsKey(layerName))
             identifyData = (IdentifyInfo)treeMap.get(layerName);
           else
             identifyData = new IdentifyInfo();

          Object idFieldValue = null;
          try {
            idFieldValue = pset.getProperty(idField);
            if(idFieldValue == null) throw new NullPointerException();
          }
          catch (Exception ex1) {
            idFieldValue = vals[1];
            if(idFieldValue == null)
              idFieldValue = vals[0];

          }
          identifyData.setLayerData(mapLayerInfo.getName(), keys, vals, idFieldValue);
          treeMap.put(layerName, identifyData);
         }
       }
     }

     return treeMap;
    } catch (Exception ex) {
       ex.printStackTrace();
       return null;
     }
  }

  /**Method to convert geometry type from integer to string
   * @param env
   * @param tolerence
   * @param option
   * @param layerids
   * @return java.util.TreeMap
   */


  public static String getGeometryTypeString(int geometryType) {
    switch (geometryType) {
      case esriGeometryType.esriGeometryAny:
        return "Any";
      case esriGeometryType.esriGeometryBag:
        return "Bag";
      case esriGeometryType.esriGeometryBezier3Curve:
        return "Bezier 3 Curve";
      case esriGeometryType.esriGeometryCircularArc:
        return "Circular Arc";
      case esriGeometryType.esriGeometryEllipticArc:
        return "Elliptic Arc";
      case esriGeometryType.esriGeometryEnvelope:
        return "Envelope";
      case esriGeometryType.esriGeometryLine:
        return "Line";
      case esriGeometryType.esriGeometryMultiPatch:
        return "Multi Patch";
      case esriGeometryType.esriGeometryMultipoint:
        return "Multi Point";
      case esriGeometryType.esriGeometryNull:
        return "Null";
      case esriGeometryType.esriGeometryPath:
        return "Path";
      case esriGeometryType.esriGeometryPoint:
        return "Point";
      case esriGeometryType.esriGeometryPolygon:
        return "Polygon";
      case esriGeometryType.esriGeometryPolyline:
        return "Polyline";
      case esriGeometryType.esriGeometryRay:
        return "Ray";
      case esriGeometryType.esriGeometryRing:
        return "Ring";
      case esriGeometryType.esriGeometrySphere:
        return "Sphere";
      case esriGeometryType.esriGeometryTriangleFan:
        return "Triangle Fan";
      case esriGeometryType.esriGeometryTriangleStrip:
        return "Triangle Strip";
      default:
        return "Unknown";
    }
  }

  /**Returns an array of string containing geometry types
   * @param keys array of geometry type in integer
   * @return values array of geometry type in string
   * @param geometryType
   */

  public void setShapeValue(String keys[], Object values[], int geometryType) {
    for (int i = 0; i < keys.length; i++) {
      if (keys[i].compareToIgnoreCase("shape") == 0)
        values[i] = getGeometryTypeString(geometryType);
    }
  }

  /**Returns the layer info object based on the layer id
  * @param int ID
  * @return IMapLayerInfo
  */

 public IMapLayerInfo getLayerInfoFromID(int ID) {
   try {
     IMapServerInfo mapServerInfo = server.getServerInfo(activeMap);
     IMapLayerInfos layerInfos = mapServerInfo.getMapLayerInfos();
     IMapLayerInfo layerInfo = null;
     int count = layerInfos.getCount();
     for (int i = 0; i < count; i++) {
       layerInfo = layerInfos.getElement(i);
       if (layerInfo.getID() == ID) {
         break;
       }
     }
     return layerInfo;
   }
   catch (IOException ex) {
     return null;
   }
 }

 /**Returns the layer info object based on the layer id
  * @param int ID
  * @return IMapLayerInfo
  */

 public IMapLayerInfo getLayerInfoFromID(int ID, String mapName) {
   try {
     IMapServerInfo mapServerInfo = server.getServerInfo(mapName);
     IMapLayerInfos layerInfos = mapServerInfo.getMapLayerInfos();
     IMapLayerInfo layerInfo = null;
     int count = layerInfos.getCount();
     for (int i = 0; i < count; i++) {
       layerInfo = layerInfos.getElement(i);
       if (layerInfo.getID() == ID) {
         break;
       }
     }
     return layerInfo;
   }
   catch (IOException ex) {
     return null;
   }
 }

 /**Returns the layer name from the layer id
  * @param ID
  * @return string
  */
 public String layerNameFromID(int ID, String mapName) {
   try {
     IMapServerInfo serverInfo = server.getServerInfo(mapName);
     IMapLayerInfos layerInfos = serverInfo.getMapLayerInfos();
     IMapLayerInfo layerInfo;
     String name = null;
     int count = layerInfos.getCount();
     for (int i = 0; i < count; i++) {
       layerInfo = layerInfos.getElement(i);
       if (layerInfo.getID() == ID) {
         name = layerInfo.getName();
         break;
       }
     }
     return name;
   }
   catch (IOException ex) {
     return null;
   }
 }


 /**Returns list of layerID and their visibility value in a hashtable
 * @return hashTable containing layerIds and visibility
 */

 public java.util.Vector getLayerInfo(String mapName) {
   Vector<LayerInfo> layerTable = new Vector<LayerInfo>();
   try {
     IMapDescription mapDescription = null;
     ILayerDescriptions layerDescriptions;
     ILayerDescription layerDescription;
     mapDescription = getMapDescription(mapName);
     layerDescriptions = mapDescription.getLayerDescriptions();
     for (int i = 0; i < layerDescriptions.getCount(); i++) {
       layerDescription = layerDescriptions.getElement(i);
       int id = layerDescription.getID();
       boolean visible = layerDescription.isVisible();
       String name = this.layerNameFromID(id, mapName);
       //Create a LayerInfo object
       LayerInfo layerinfo = new LayerInfo(name, visible, id);
       layerTable.add(layerinfo);
     }
   }
   catch (IOException ex) {
   }
   return layerTable;
 }


}