コード例 #1
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * This function would return a Color object for string such as red, green,.. (all that are
   * available from java.awt.color class). It can also return a specific color represented by HEX or
   * Octal number like 0xffeeffee
   */
  protected Color GetColorFromString(String token) {
    String tokstring = (String) token;

    Color result = Color.black;

    if (Debug.debugging("areas")) {
      Debug.output("AreaHandler: GetColorFromString(" + tokstring + ")");
    }

    // Thank the heavens for Emacs macros!
    if (tokstring.equals("black")) result = Color.black;
    else if (tokstring.equals("blue")) result = Color.blue;
    else if (tokstring.equals("cyan")) result = Color.cyan;
    else if (tokstring.equals("darkGray")) result = Color.darkGray;
    else if (tokstring.equals("gray")) result = Color.gray;
    else if (tokstring.equals("green")) result = Color.green;
    else if (tokstring.equals("lightGray")) result = Color.lightGray;
    else if (tokstring.equals("magenta")) result = Color.magenta;
    else if (tokstring.equals("orange")) result = Color.orange;
    else if (tokstring.equals("pink")) result = Color.pink;
    else if (tokstring.equals("red")) result = Color.red;
    else if (tokstring.equals("white")) result = Color.white;
    else if (tokstring.equals("yellow")) result = Color.yellow;
    else
      // decode a hex color string.
      result = Color.decode(tokstring);

    if (Debug.debugging("areas")) {
      Debug.output("AreaHandler.GetColorFromToken returns (" + result + ")");
    }
    return result;
  }
コード例 #2
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * Given the shapefile record number, find the drawing parameters that should be used for the
   * shape.
   *
   * @param recordNumber the zero-based record number from the OMGraphicList.
   */
  public DrawingAttributes getDrawParamsFromCSV(int recordNumber) {
    if (infoFile == null) {
      return drawingAttributes;
    }

    // OFF BY ONE!!! The shape record numbers
    // assigned to the records start with 1, while
    // everything else we do starts with 0...
    Vector info = infoFile.getRecord(recordNumber);

    if (info == null) {
      if (Debug.debugging("areas")) {
        Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has no info");
      }
      return drawingAttributes;
    }

    Object keyObj = info.elementAt(keyIndex);
    String key = null;
    PoliticalArea pa = null;

    if (keyObj != null) {
      key = createStringFromKeyObject(keyObj);
      pa = (PoliticalArea) politicalAreas.get(key);
    }

    if (pa == null) {
      if (Debug.debugging("areas")) {
        Debug.output(
            "AreaHandler.getDrawParameters: record "
                + recordNumber
                + " has key \""
                + key
                + "\" and DEFAULT attributes");
      }
      return drawingAttributes;
    } else {
      // Only bother with this the first time around.
      if (pa.name == null) {
        String name = (String) info.elementAt(nameIndex);
        if (name != null) {
          pa.name = name;
        } else {
          pa.name = "";
        }
      }

      if (Debug.debugging("areas")) {
        Debug.output(
            "AreaHandler.getDrawParameters: record "
                + recordNumber
                + " has key \""
                + key
                + "\" and SPECIALIZED attributes");
      }
      return pa.drawingAttributes;
    }
  }
コード例 #3
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * Given the shapefile record number, find the drawing parameters from the DBF model that should
   * be used for the shape. Returns the default coloring if the key for the drawing parameters isn't
   * found.
   *
   * @param recordNumber the zero-based record number from the OMGraphicList
   */
  public DrawingAttributes getDrawParamsFromDBF(int recordNumber) {
    if (dbfModel == null) {
      return drawingAttributes;
    }

    if (dbfModel == null || dbfModel.getRowCount() < recordNumber) {
      if (Debug.debugging("areas")) {
        Debug.output("AreaHandler.getDrawParameters: record " + recordNumber + " has no info");
      }
      return drawingAttributes;
    }

    Object keyObj = dbfModel.getValueAt(recordNumber, keyIndex);
    String key = null;
    PoliticalArea pa = null;

    if (keyObj != null) {
      key = createStringFromKeyObject(keyObj);
      pa = (PoliticalArea) politicalAreas.get(key);
    }

    if (pa == null) {
      if (Debug.debugging("areas")) {
        Debug.output(
            "AreaHandler.getDrawParameters: record "
                + recordNumber
                + " has key \""
                + key
                + "\" and DEFAULT attributes");
      }
      return drawingAttributes;
    } else {
      // Only bother with this the first time around.
      if (pa.name == null) {
        // String name = (String) info.elementAt(nameIndex);
        String name = (String) dbfModel.getValueAt(recordNumber, nameIndex);
        if (name != null) {
          pa.name = name;
        } else {
          pa.name = "";
        }
      }

      if (Debug.debugging("areas")) {
        Debug.output(
            "AreaHandler.getDrawParameters: record "
                + recordNumber
                + " has key \""
                + key
                + "\" and SPECIALIZED attributes");
      }
      return pa.drawingAttributes;
    }
  }
コード例 #4
0
ファイル: BinaryFile.java プロジェクト: waqas64/debrief
  /**
   * Takes a name of a file, and checks to see if it reflects an entry in a jar file. (Check the
   * filename and see if it looks like "jarfile!jarfileentry".) If it is, it separates the path, and
   * set the inputReader to a JarInputReader and returns true. If not, it returns false.
   */
  protected boolean setJarInputReader(final String name) throws IOException {

    try {
      final int index = name.indexOf("!");
      if (index != -1) {

        // Used to be this, modified by Erik Sanders to work
        // with jdk 1.4 plugin
        // String jarFileName =
        // name.substring(name.indexOf(":") + 1, index);

        // changed to this...
        String jarFileName;

        if (name.startsWith("file:")) {
          // java-plugin 1.3 returns local file: strip file:
          // from string
          jarFileName = name.substring(name.indexOf(":") + 1, index);
        } else {
          // java-plugin 1.4 returns reference to server, so
          // leave http:// part

          // Used to start the substring from 1, but changed
          // to 0 thanks to DGK
          jarFileName = name.substring(0, index);
        }

        // skip !/ "
        final String jarEntryName = name.substring(index + 2);
        if (Debug.debugging("binaryfile")) {
          Debug.output(" got: \n" + jarFileName + "\n" + jarEntryName);
        }

        // If the jar doesn't exist, should return something
        // that indicates this. Should check the performance
        // impllications of this call, though, at some point.

        // DGK added
        final File f = new File(jarFileName);
        if (f.exists() == false) {
          return false;
        }

        setInputReader(new JarInputReader(jarFileName, jarEntryName));
        return true;
      }
    } catch (final java.security.AccessControlException ace) {
      if (Debug.debugging("binaryfile")) {
        Debug.output("BinaryFile.setJarInputFile: AccessControlException for " + name);
      }
    }

    return false;
  }
コード例 #5
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * Initializes this object from the given properties
   *
   * @param props the <code>Properties</code> holding settings for this object
   */
  public void setProperties(String prefix, Properties props) {
    if (Debug.debugging("areas")) {
      Debug.output("AreaHandler: setting properties");
    }

    setPropertyPrefix(prefix);
    originalProperties = props;

    // These will get initialized when someone asks for it.
    // Otherwise, it delays the startup of the map.
    politicalAreas = null;

    String realPrefix = PropUtils.getScopedPropertyPrefix(prefix);

    String transClassName = props.getProperty(realPrefix + ShapeLayer.TransformProperty);
    if (transClassName != null) {
      try {
        coordTransform =
            (GeoCoordTransformation)
                ComponentFactory.create(
                    transClassName, realPrefix + ShapeLayer.TransformProperty, props);
      } catch (ClassCastException cce) {

      }
    }
  }
コード例 #6
0
  /**
   * Create and set the graphic within the state machine. The GraphicAttributes describe the type of
   * poly to create.
   */
  public void createGraphic(GraphicAttributes ga) {
    init();
    stateMachine.setUndefined();
    int renderType = OMGraphic.RENDERTYPE_LATLON;
    int lineType = OMGraphic.LINETYPE_GREATCIRCLE;

    if (ga != null) {
      renderType = ga.getRenderType();
      lineType = ga.getLineType();
    }

    if (Debug.debugging("eomg")) {
      Debug.output("EditableOMDistance.createGraphic(): rendertype = " + renderType);
    }

    if (lineType == OMGraphic.LINETYPE_UNKNOWN) {
      lineType = OMGraphic.LINETYPE_GREATCIRCLE;
      ga.setLineType(OMGraphic.LINETYPE_GREATCIRCLE);
    }

    this.poly = (OMDistance) createGraphic(renderType, lineType);

    if (ga != null) {
      ga.setRenderType(poly.getRenderType());
      ga.setTo(poly, true);
    }
  }
コード例 #7
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * This function takes an OMGraphicList and loads each one with the array representing the records
   * in the dbf file. Each graphics stores the graphic in its object slot.
   */
  public void loadDbfModelIntoGraphics(OMGraphicList list) {
    if (list != null && dbfModel.getRowCount() > 0) {
      int numgraphics = list.size();

      for (int i = 0; i < numgraphics; i++) {
        try {
          OMGraphic omg = list.getOMGraphicAt(i);
          Integer recnum = (Integer) (omg.getAttribute(ShapeConstants.SHAPE_INDEX_ATTRIBUTE));
          // OFF BY ONE!!! The shape record numbers
          // assigned to the records start with 0, while
          // everything else we do starts with 0. The DbfTableModel
          // follows java convention and starts at 0. The integer
          // stored in the OMG should know it too.
          Object inforec = dbfModel.getRecord(recnum.intValue());
          omg.putAttribute(ShapeConstants.SHAPE_DBF_INFO_ATTRIBUTE, inforec);
        } catch (ClassCastException cce) {
          if (Debug.debugging("shape")) {
            cce.printStackTrace();
          }
        } catch (NullPointerException npe) {
          npe.printStackTrace();
        }
      }
    }
  }
コード例 #8
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * DeterminePoliticalAreas goes over a list of omgraphics, and spits out a hashtable that holds
   * PoliticalArea objects for every area key.
   *
   * @param graphicList the list of graphics. The top level graphic entries on the list represent
   *     areas.
   */
  public Hashtable determinePoliticalAreas(OMGraphicList graphicList) {
    if (Debug.debugging("areas")) {
      Debug.output("AreaHandler: Determining political areas from OMGraphicList");
    }

    Hashtable poli_areas = new Hashtable();
    return determinePoliticalAreas(graphicList, poli_areas);
  }
コード例 #9
0
 public void finalize() {
   if (getGraphic() != null) {
     getGraphic().setVisible(true);
   }
   if (Debug.debugging("gc")) {
     Debug.output("EditableOMGraphic gone.");
   }
 }
コード例 #10
0
  /**
   * Return a byte array that contains the GIF encoded image.
   *
   * @param image the image to encode
   * @exception IOException an error occured in encoding the image
   */
  public static byte[] encodeGif(BufferedImage image) throws IOException {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (Debug.debugging("acmegifhelper")) {
      Debug.output("Got output stream..." + out);
    }

    Acme.JPM.Encoders.GifEncoder enc = new Acme.JPM.Encoders.GifEncoder(image, out);
    if (Debug.debugging("acmegifhelper")) {
      Debug.output("Got gif encoder...");
    }

    enc.encode();
    if (Debug.debugging("acmegifhelper")) {
      Debug.output("encoded?");
    }

    return out.toByteArray();
  }
コード例 #11
0
  /**
   * Send a Paint event to all registered listeners.
   *
   * @param graphics PaintEvent
   */
  public void paint(Graphics graphics) {

    if (isEmpty()) return;

    for (PaintListener target : this) {
      if (Debug.debugging("paint")) {
        Debug.output("PaintListenerSupport.paint(): target is: " + target);
      }
      target.listenerPaint(getSource(), graphics);
    }
  }
コード例 #12
0
ファイル: FilterSupport.java プロジェクト: justfriend/openmap
  /**
   * Filters the OMGraphicHandler graphic list so that graphics inside or outside the given shape
   * will be visible. Returns an OMGraphicList with those visible shapes. The returned list should
   * not be assumed to be the same OMGraphicList object that is maintained inside the
   * OMGraphicHandler.
   *
   * @param shapeBoundary java.awt.Shape object defining a boundary.
   * @param getInsideBoundary if true, the filter will look for shapes inside and contacting the
   *     boundary. If false, the filter will look for shapes outside the boundary.
   * @return OMGraphicList containing OMGraphics that are within the Shape.
   */
  public OMGraphicList filter(Shape shapeBoundary, boolean getInsideBoundary) {
    Area area = null;
    if (shapeBoundary != null) {
      area = new Area(shapeBoundary);
    }

    if (Debug.debugging("filtersupportdetail")) {
      Debug.output(getList().getDescription());
    }

    return filterList(getList(), area, getInsideBoundary);
  }
コード例 #13
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /** Read a cache of OMGraphics */
  public OMGraphicList readCachedGraphics(URL url) throws java.io.IOException {

    if (Debug.debugging("areas")) {
      Debug.output("Reading cached graphics");
    }

    OMGraphicList omgraphics = new OMGraphicList();

    if (url != null) {
      omgraphics.readGraphics(url);
    }
    return omgraphics;
  }
コード例 #14
0
ファイル: LinkServer.java プロジェクト: justfriend/openmap
 /** From the Runnable interface. The thread starts here... */
 public void run() {
   try {
     handleClient();
   } catch (IOException ioe) {
     link.cleanUp();
     link = null;
     if (com.bbn.openmap.util.Debug.debugging("link")) {
       System.err.println(ioe);
     }
     com.bbn.openmap.util.Debug.output("LinkServer: Client disconnected");
     System.gc();
   }
 }
コード例 #15
0
  /**
   * The main program. Takes path arguments, and prints the DB it finds
   *
   * @param args the paths to print
   */
  public static void main(String[] args) throws FormatException {
    Debug.init();

    if (args.length == 0) {
      Debug.output(
          "Usage: java com.bbn.openmap.layer.vpf.GenerateVPFProperties <path to vpf database directory> <path to vpf database directory> ...");
      System.exit(0);
    }

    for (int argsi = 0; argsi < args.length; argsi++) {
      rootpath = args[argsi];
      LibrarySelectionTable lst = new LibrarySelectionTable(rootpath);
      if (Debug.debugging("vpf")) {
        Debug.output("Path to database: " + rootpath);
        Debug.output("Database Name: " + lst.getDatabaseName());
      }
      println("### Generated openmap.properties for");
      println("# VPF Data at: " + rootpath);
      println("# Description: " + lst.getDatabaseDescription());
      String[] libraries = lst.getLibraryNames();
      if (Debug.debugging("vpf")) {
        print("Database Libraries: ");
        for (int i = 0; i < libraries.length; i++) {
          print(libraries[i], " ");
        }
        println("");
        println("");
      }
      for (int i = 0; i < libraries.length; i++) {
        String prefix = lst.getDatabaseName() + "_" + libraries[i];
        println("# Library: " + prefix);
        printLibrary(prefix, lst.getCAT(libraries[i]));
        println("");
      }
    }
  }
コード例 #16
0
ファイル: DDFField.java プロジェクト: justfriend/openmap
  protected void addSubfield(DDFSubfield ddfs) {
    if (Debug.debugging("iso8211")) {
      Debug.output("DDFField(" + getFieldDefn().getName() + ").addSubfield(" + ddfs + ")");
    }

    String sfName = ddfs.getDefn().getName().trim().intern();
    Object sf = subfields.get(sfName);
    if (sf == null) {
      subfields.put(sfName, ddfs);
    } else {
      if (sf instanceof List) {
        ((List) sf).add(ddfs);
      } else {
        Vector subList = new Vector();
        subList.add(sf);
        subList.add(ddfs);
        subfields.put(sfName, subList);
      }
    }
  }
コード例 #17
0
  /**
   * Prints a VPF Library
   *
   * @param prefix lines get printed with this prefix
   * @param cat the CoverageAttributeTable (Library) to print
   */
  public static void printLibrary(String prefix, CoverageAttributeTable cat) {
    StringBuffer printedlayers = new StringBuffer();
    String printedlayername = null;

    if (cat == null) {
      System.err.println(prefix + "Library doesn't exist");
      return;
    }
    String[] coverages = cat.getCoverageNames();
    if (Debug.debugging("vpf")) {
      Debug.output(prefix + "uses " + (cat.isTiledData() ? "tiled" : "untiled") + " data");
    }
    for (int i = 0; i < coverages.length; i++) {
      printedlayername = printCoverageProperties(prefix, cat, coverages[i]);
      if (printedlayername != null) {
        printedlayers.append(" " + printedlayername);
      }
    }
    println("# Summary:" + printedlayers);
  }
コード例 #18
0
ファイル: WMSPlugIn.java プロジェクト: justfriend/openmap
  /**
   * Does more than just set the version, it also adjusts other parameters based on version. Be
   * careful calling this without knowing what it does and how it affects other settings.
   *
   * @param wmsVer
   */
  public void setWmsVersion(String wmsVer) {
    if (wmsVer == null || wmsVer.length() == 0) {
      wmsVer = "1.1.1";
      Debug.output("WMSPlugin: wmsVersion was null, now set to 1.1.1");
    }

    if (Debug.debugging("wms")) {
      Debug.output("WMSPlugIn: set up with header \"" + queryHeader + "\"");
    }

    java.util.StringTokenizer st = new java.util.StringTokenizer(wmsVer, ".");
    int majorVersion = Integer.parseInt(st.nextToken());
    int midVersion = Integer.parseInt(st.nextToken());
    int minorVersion = Integer.parseInt(st.nextToken());

    // set the REQUEST parameter
    if (majorVersion == 1 && midVersion == 0 && minorVersion < 3) {
      mapRequestName = WMTConstants.MAP;
    }

    // set the image type parameter
    if (majorVersion == 1 && minorVersion > 7 && !imageFormat.startsWith("image/")) {
      imageFormat = "image/" + imageFormat;
    }

    // set the error handling parameter
    if (majorVersion == 1 && midVersion == 0) {
      errorHandling = "INIMAGE";
    } else if (majorVersion == 1 && midVersion >= 1 && minorVersion > 1) {
      errorHandling = "application/vnd.ogc.se+inimage";
    } else if (majorVersion > 1) {
      errorHandling = "application/vnd.ogc.se+inimage";
    }

    this.wmsVersion = wmsVer;
  }
コード例 #19
0
ファイル: WMSPlugIn.java プロジェクト: justfriend/openmap
  /** Create the query to be sent to the server, based on current settings. */
  public String createQueryString(Projection p) {

    if (queryHeader == null) {
      return null;
    }

    String bbox = "undefined";
    String height = "undefined";
    String width = "undefined";

    String sCoordParamName = WMTConstants.SRS;

    if (p != null) {
      Point2D ul = p.getUpperLeft();
      Point2D lr = p.getLowerRight();

      if (wmsVersion.compareTo("1.3.0") == 0) {
        bbox =
            Double.toString(lr.getY())
                + ","
                + Double.toString(ul.getX())
                + ","
                + Double.toString(ul.getY())
                + ","
                + Double.toString(lr.getX());
        sCoordParamName = WMTConstants.CRS;
        errorHandling = "INIMAGE";
      } else {
        bbox =
            Double.toString(ul.getX())
                + ","
                + Double.toString(lr.getY())
                + ","
                + Double.toString(lr.getX())
                + ","
                + Double.toString(ul.getY());
      }

      height = Integer.toString(p.getHeight());
      width = Integer.toString(p.getWidth());
    }

    StringBuffer buf = new StringBuffer(queryHeader);
    buf.append("?")
        .append(WMTConstants.VERSION)
        .append("=")
        .append(wmsVersion)
        .append("&")
        .append(WMTConstants.REQUEST)
        .append("=")
        .append(mapRequestName)
        .append("&")
        .append(sCoordParamName)
        .append("=")
        .append("EPSG:4326")
        .append("&")
        .append(WMTConstants.BBOX)
        .append("=")
        .append(bbox)
        .append("&")
        .append(WMTConstants.HEIGHT)
        .append("=")
        .append(height)
        .append("&")
        .append(WMTConstants.WIDTH)
        .append("=")
        .append(width)
        .append("&")
        .append(WMTConstants.EXCEPTIONS)
        .append("=")
        .append(errorHandling);

    if (imageFormat != null) {
      buf.append("&").append(WMTConstants.FORMAT).append("=").append(imageFormat);

      String baseImageFormat = imageFormat;
      if (baseImageFormat.indexOf('/') > 0)
        baseImageFormat = baseImageFormat.substring(baseImageFormat.indexOf('/'));
      if (baseImageFormat.equals(WMTConstants.IMAGEFORMAT_JPEG)) {
        buf.append("&quality=").append(imageQuality);
      }
    }

    if (transparent != null) {
      buf.append("&").append(WMTConstants.TRANSPARENT).append("=").append(transparent);
    }

    if (backgroundColor != null) {
      buf.append("&").append(WMTConstants.BGCOLOR).append("=").append(backgroundColor);
    }

    if (layers != null) {
      buf.append("&").append(WMTConstants.LAYERS).append("=").append(layers);
    }

    String cStyles = styles;
    if (cStyles == null) {
      cStyles = "";
    }

    // if (styles != null) {
    buf.append("&").append(WMTConstants.STYLES).append("=").append(cStyles);
    // }

    if (Debug.debugging("wms")) {
      Debug.output("query string: " + buf);
    }

    /*
     * Included to allow for one or more vendor specific parameters to be
     * specified such as ESRI's ArcIMS's "ServiceName" parameter.
     */
    if (vendorSpecificNames != null) {
      if (vendorSpecificValues != null) {
        StringTokenizer nameTokenizer = new StringTokenizer(vendorSpecificNames, ",");
        StringTokenizer valueTokenizer = new StringTokenizer(vendorSpecificValues, ",");
        String paramName = null;
        String paramValue = null;
        while (nameTokenizer.hasMoreTokens()) {
          try {
            paramName = nameTokenizer.nextToken();
            paramValue = valueTokenizer.nextToken();
            buf.append("&").append(paramName).append("=").append(paramValue);
          } catch (NoSuchElementException e) {
            if (Debug.debugging("wms")) {
              Debug.output(
                  "WMSPlugIn.getRectangle(): " + "parameter \"" + paramName + "\" has no value");
            }
          }
        }
      }
    }
    return buf.toString();
  }
コード例 #20
0
ファイル: FilterSupport.java プロジェクト: justfriend/openmap
  /**
   * Method that provides a recursive mechanism to go through OMGraphicsLists to filter out areas,
   * inside or outside another.
   */
  protected OMGraphicList filterList(OMGraphicList omgl, Area area, boolean getInsideArea) {
    OMGraphicList ret = new OMGraphicList();
    boolean DEBUG_DETAIL = Debug.debugging("filtersupportdetail");
    boolean DEBUG = Debug.debugging("filtersupport") || DEBUG_DETAIL;

    if (DEBUG) {
      Debug.output("FilterSupport.filterList");
    }

    int count = 0; // for debugging

    if (area != null && omgl != null) { // just checking

      for (OMGraphic omg : omgl) {

        if (DEBUG) {
          Debug.output("FilterSupport.filterList evaluating " + (count++) + " OMGraphic, " + omg);
        }

        boolean outsideFilter = true;

        // If not visible, automatically fails...
        if (!omg.isVisible()) {
          if (DEBUG) {
            Debug.output("   OMGraphic not visible, ignoring");
          }
          continue;
        }

        if (omg instanceof OMGraphicList) {
          if (omg == omgl) {
            Debug.output("   OMGraphic is parent list (points to itself), ignoring...");
            continue;
          }

          if (DEBUG) {
            Debug.output("  (filterList recursiving handing OMGraphicList)");
          }

          OMGraphicList subList = filterList((OMGraphicList) omg, area, getInsideArea);

          if (!subList.isEmpty()) {
            if (DEBUG) {
              Debug.output(
                  "  +++ OMGraphicList's contents (" + subList.size() + ") pass filter, adding...");
            }

            if (((OMGraphicList) omg).isVague()) {
              passedFilter(omg);
              omg.setVisible(true);
              ret.add(omg);
            } else {
              passedFilter(subList);
              ret.add(subList);
            }
          } else {
            if (DEBUG) {
              Debug.output("  --- OMGraphicList's contents fail filter, ignoring...");
            }

            failedFilter(omg);
          }
          continue;
        } else {
          Shape omgShape = omg.getShape();
          if (omgShape != null) {
            if (omgShape.getBounds2D().getWidth() == 0 && omgShape.getBounds2D().getHeight() == 0) {
              if (area.contains(omgShape.getBounds2D().getX(), omgShape.getBounds2D().getY())) {
                if (DEBUG_DETAIL) {
                  Debug.output("   +++ omg contains position");
                }

                outsideFilter = false;
              }
            } else if (area.intersects(omgShape.getBounds2D())) {
              if (DEBUG_DETAIL) {
                Debug.output("   +++ omg intersects bounds");
              }

              // The area.interects() method above is a
              // general case. If you care about
              // preciseness, set the precise flag.
              // Depending on the performance cost, we might
              // want to make it permanent.

              if (precise) {
                Area omgArea = new Area(omgShape);
                if (!omgArea.isSingular()) {
                  Area clone = (Area) area.clone();
                  clone.intersect(omgArea);
                  if (!clone.isEmpty()) {
                    outsideFilter = false;
                  }
                } else {
                  outsideFilter = false;
                }
              } else {
                outsideFilter = false;
              }
            }
          }

          // decide what to do depending on filteredOut and
          // getInsideArea
          if ((outsideFilter && !getInsideArea) || (!outsideFilter && getInsideArea)) {

            if (DEBUG) {
              Debug.output("   +++ OMGraphic passes filter, adding...");
            }

            passedFilter(omg);
            ret.add(omg);
          } else {
            if (DEBUG) {
              Debug.output("   --- OMGraphic fails filter, hiding...");
            }

            failedFilter(omg);
          }
        }
      }
    }

    return ret;
  }
コード例 #21
0
ファイル: DTEDLayer.java プロジェクト: jrecursive/passage
  /** Creates the interface palette. */
  public java.awt.Component getGUI() {

    if (paletteBox == null) {
      if (Debug.debugging("dted")) Debug.output("DTEDLayer: creating DTED Palette.");

      paletteBox = Box.createVerticalBox();
      Box subbox1 = Box.createHorizontalBox();
      Box subbox2 = Box.createVerticalBox();
      Box subbox3 = Box.createHorizontalBox();

      // palette = new JPanel();
      // palette.setLayout(new GridLayout(0, 1));

      // The DTED Level selector
      JPanel levelPanel = PaletteHelper.createPaletteJPanel("DTED Level");
      ButtonGroup levels = new ButtonGroup();

      ActionListener al =
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              if (cache != null) {
                String ac = e.getActionCommand();
                int newLevel;
                if (ac.equalsIgnoreCase(level2Command)) newLevel = DTEDFrameSubframe.LEVEL_2;
                else if (ac.equalsIgnoreCase(level1Command)) newLevel = DTEDFrameSubframe.LEVEL_1;
                else newLevel = DTEDFrameSubframe.LEVEL_0;
                DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo();
                dfsi.dtedLevel = newLevel;
                // cache.setSubframeInfo(dfsi);
              }
            }
          };

      JRadioButton level0 = new JRadioButton("Level 0");
      level0.addActionListener(al);
      level0.setActionCommand(level0Command);
      JRadioButton level1 = new JRadioButton("Level 1");
      level1.addActionListener(al);
      level1.setActionCommand(level1Command);
      JRadioButton level2 = new JRadioButton("Level 2");
      level2.addActionListener(al);
      level2.setActionCommand(level2Command);

      levels.add(level0);
      levels.add(level1);
      levels.add(level2);

      switch (dtedLevel) {
        case 2:
          level2.setSelected(true);
          break;
        case 1:
          level1.setSelected(true);
          break;
        case 0:
        default:
          level0.setSelected(true);
      }

      levelPanel.add(level0);
      levelPanel.add(level1);
      levelPanel.add(level2);

      // The DTED view selector
      JPanel viewPanel = PaletteHelper.createPaletteJPanel("View Type");
      String[] viewStrings = {
        "None", "Shading", "Elevation Shading", "Elevation Bands (Meters)", "Elevation Bands (Feet)"
      };

      JComboBox viewList = new JComboBox(viewStrings);
      viewList.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              JComboBox jcb = (JComboBox) e.getSource();
              int newView = jcb.getSelectedIndex();
              switch (newView) {
                case 0:
                  viewType = DTEDFrameSubframe.NOSHADING;
                  break;
                case 1:
                  viewType = DTEDFrameSubframe.SLOPESHADING;
                  break;
                case 2:
                  viewType = DTEDFrameSubframe.COLOREDSHADING;
                  break;
                case 3:
                  viewType = DTEDFrameSubframe.METERSHADING;
                  break;
                case 4:
                  viewType = DTEDFrameSubframe.FEETSHADING;
                  break;
                default:
                  viewType = DTEDFrameSubframe.NOSHADING;
              }
              if (cache != null) {
                DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo();
                dfsi.viewType = viewType;
                // cache.setSubframeInfo(dfsi);
              }
            }
          });
      int selectedView;
      switch (viewType) {
        case 0:
        case 1:
          selectedView = viewType;
          break;
        case 2:
        case 3:
          selectedView = viewType + 1;
          break;
        case 4:
          // This puts the layer in testing mode, and the menu
          // changes.
          String[] viewStrings2 = {
            "None",
            "Shading",
            "Elevation Bands (Meters)",
            "Elevation Bands (Feet)",
            "Subframe Testing",
            "Elevation Shading"
          };
          viewList = new JComboBox(viewStrings2);
          viewList.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  JComboBox jcb = (JComboBox) e.getSource();
                  int newView = jcb.getSelectedIndex();
                  if (cache != null) {
                    DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo();
                    dfsi.viewType = newView;
                    // cache.setSubframeInfo(dfsi);
                  }
                }
              });
          selectedView = viewType;
          break;
        case 5:
          selectedView = 2; // DTEDFrameSubframe.COLOREDSHADING
          break;
        default:
          selectedView = DTEDFrameSubframe.NOSHADING;
      }

      viewList.setSelectedIndex(selectedView);
      viewPanel.add(viewList);

      // The DTED Contrast Adjuster
      JPanel contrastPanel = PaletteHelper.createPaletteJPanel("Contrast Adjustment");
      JSlider contrastSlide =
          new JSlider(JSlider.HORIZONTAL, 1 /* min */, 5 /* max */, slopeAdjust /* initial */);
      java.util.Hashtable<Integer, JLabel> dict = new java.util.Hashtable<Integer, JLabel>();
      dict.put(new Integer(1), new JLabel("min"));
      dict.put(new Integer(5), new JLabel("max"));
      contrastSlide.setLabelTable(dict);
      contrastSlide.setPaintLabels(true);
      contrastSlide.setMajorTickSpacing(1);
      contrastSlide.setPaintTicks(true);
      contrastSlide.setSnapToTicks(true);
      contrastSlide.addChangeListener(
          new ChangeListener() {
            public void stateChanged(ChangeEvent ce) {
              JSlider slider = (JSlider) ce.getSource();
              if (slider.getValueIsAdjusting()) {
                fireRequestInfoLine(getName() + " - Contrast Slider value = " + slider.getValue());
                slopeAdjust = slider.getValue();
                if (cache != null) {
                  DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo();
                  dfsi.slopeAdjust = slopeAdjust;
                  // cache.setSubframeInfo(dfsi);
                }
              }
            }
          });
      contrastPanel.add(contrastSlide);

      // The DTED Band Height Adjuster
      JPanel bandPanel = PaletteHelper.createPaletteJPanel("Band Elevation Spacing");
      JSlider bandSlide =
          new JSlider(JSlider.HORIZONTAL, 0 /* min */, 1000 /* max */, bandHeight /* initial */);
      bandSlide.setLabelTable(bandSlide.createStandardLabels(250));
      bandSlide.setPaintLabels(true);
      bandSlide.setMajorTickSpacing(250);
      bandSlide.setMinorTickSpacing(50);
      bandSlide.setPaintTicks(true);
      bandSlide.addChangeListener(
          new ChangeListener() {
            public void stateChanged(ChangeEvent ce) {
              JSlider slider = (JSlider) ce.getSource();
              if (slider.getValueIsAdjusting()) {
                fireRequestInfoLine(getName() + " - Band Slider value = " + slider.getValue());
                bandHeight = slider.getValue();
                if (cache != null) {
                  DTEDFrameSubframeInfo dfsi = cache.getSubframeInfo();
                  dfsi.bandHeight = bandHeight;
                  // cache.setSubframeInfo(dfsi);
                }
              }
            }
          });

      bandPanel.add(bandSlide);

      JButton redraw = new JButton("Redraw DTED Layer");
      redraw.setActionCommand(RedrawCmd);
      redraw.addActionListener(this);

      subbox1.add(levelPanel);
      subbox1.add(viewPanel);
      paletteBox.add(subbox1);
      subbox2.add(contrastPanel);
      subbox2.add(bandPanel);
      paletteBox.add(subbox2);
      subbox3.add(redraw);
      paletteBox.add(subbox3);
    }

    return paletteBox;
  }
コード例 #22
0
ファイル: FilterSupport.java プロジェクト: justfriend/openmap
/**
 * This class provides support for implementing the OMGraphicHandler interface. If you already
 * calculate an OMGraphicList, you can use this class to apply filtering to it. The graphics on the
 * list you provide it will be made visible or not depending on whether they meet the filter
 * criteria.
 *
 * <p>The visibility of the graphics is affected when a filter is applied, and visibility is used as
 * the test if whether a graphic is added to a returned list. Use resetFiltering() to turn
 * visibility back on for all the OMGraphics. If a graphic is not visible when a filter is applied,
 * then the filter test will automatically fail.
 */
public class FilterSupport implements OMGraphicHandler, Serializable {

  /** The source graphic list. */
  protected OMGraphicList list = null;

  /** A flag to use the Area.intersect(Area) test, which may be a performance hit. */
  protected boolean precise = true;

  protected boolean DEBUG = Debug.debugging("list");

  public FilterSupport() {}

  public FilterSupport(OMGraphicList omgl) {
    setList(omgl);
  }

  /**
   * Filters the OMGraphicHandler graphic list so that graphics within the given shape will be
   * visible. Returns an OMGraphicList with those visible shapes. The returned list should not be
   * assumed to be the same OMGraphicList object that is maintained inside the OMGraphicHandler.
   * Same as calling filter(withinThisShape, true).
   *
   * @param withinThisShape java.awt.Shape object defining a boundary.
   * @return OMGraphicList containing OMGraphics that are within the Shape.
   */
  public OMGraphicList filter(Shape withinThisShape) {
    return filter(withinThisShape, true);
  }

  /**
   * Filters the OMGraphicHandler graphic list so that graphics inside or outside the given shape
   * will be visible. Returns an OMGraphicList with those visible shapes. The returned list should
   * not be assumed to be the same OMGraphicList object that is maintained inside the
   * OMGraphicHandler.
   *
   * @param shapeBoundary java.awt.Shape object defining a boundary.
   * @param getInsideBoundary if true, the filter will look for shapes inside and contacting the
   *     boundary. If false, the filter will look for shapes outside the boundary.
   * @return OMGraphicList containing OMGraphics that are within the Shape.
   */
  public OMGraphicList filter(Shape shapeBoundary, boolean getInsideBoundary) {
    Area area = null;
    if (shapeBoundary != null) {
      area = new Area(shapeBoundary);
    }

    if (Debug.debugging("filtersupportdetail")) {
      Debug.output(getList().getDescription());
    }

    return filterList(getList(), area, getInsideBoundary);
  }

  /**
   * Method that provides a recursive mechanism to go through OMGraphicsLists to filter out areas,
   * inside or outside another.
   */
  protected OMGraphicList filterList(OMGraphicList omgl, Area area, boolean getInsideArea) {
    OMGraphicList ret = new OMGraphicList();
    boolean DEBUG_DETAIL = Debug.debugging("filtersupportdetail");
    boolean DEBUG = Debug.debugging("filtersupport") || DEBUG_DETAIL;

    if (DEBUG) {
      Debug.output("FilterSupport.filterList");
    }

    int count = 0; // for debugging

    if (area != null && omgl != null) { // just checking

      for (OMGraphic omg : omgl) {

        if (DEBUG) {
          Debug.output("FilterSupport.filterList evaluating " + (count++) + " OMGraphic, " + omg);
        }

        boolean outsideFilter = true;

        // If not visible, automatically fails...
        if (!omg.isVisible()) {
          if (DEBUG) {
            Debug.output("   OMGraphic not visible, ignoring");
          }
          continue;
        }

        if (omg instanceof OMGraphicList) {
          if (omg == omgl) {
            Debug.output("   OMGraphic is parent list (points to itself), ignoring...");
            continue;
          }

          if (DEBUG) {
            Debug.output("  (filterList recursiving handing OMGraphicList)");
          }

          OMGraphicList subList = filterList((OMGraphicList) omg, area, getInsideArea);

          if (!subList.isEmpty()) {
            if (DEBUG) {
              Debug.output(
                  "  +++ OMGraphicList's contents (" + subList.size() + ") pass filter, adding...");
            }

            if (((OMGraphicList) omg).isVague()) {
              passedFilter(omg);
              omg.setVisible(true);
              ret.add(omg);
            } else {
              passedFilter(subList);
              ret.add(subList);
            }
          } else {
            if (DEBUG) {
              Debug.output("  --- OMGraphicList's contents fail filter, ignoring...");
            }

            failedFilter(omg);
          }
          continue;
        } else {
          Shape omgShape = omg.getShape();
          if (omgShape != null) {
            if (omgShape.getBounds2D().getWidth() == 0 && omgShape.getBounds2D().getHeight() == 0) {
              if (area.contains(omgShape.getBounds2D().getX(), omgShape.getBounds2D().getY())) {
                if (DEBUG_DETAIL) {
                  Debug.output("   +++ omg contains position");
                }

                outsideFilter = false;
              }
            } else if (area.intersects(omgShape.getBounds2D())) {
              if (DEBUG_DETAIL) {
                Debug.output("   +++ omg intersects bounds");
              }

              // The area.interects() method above is a
              // general case. If you care about
              // preciseness, set the precise flag.
              // Depending on the performance cost, we might
              // want to make it permanent.

              if (precise) {
                Area omgArea = new Area(omgShape);
                if (!omgArea.isSingular()) {
                  Area clone = (Area) area.clone();
                  clone.intersect(omgArea);
                  if (!clone.isEmpty()) {
                    outsideFilter = false;
                  }
                } else {
                  outsideFilter = false;
                }
              } else {
                outsideFilter = false;
              }
            }
          }

          // decide what to do depending on filteredOut and
          // getInsideArea
          if ((outsideFilter && !getInsideArea) || (!outsideFilter && getInsideArea)) {

            if (DEBUG) {
              Debug.output("   +++ OMGraphic passes filter, adding...");
            }

            passedFilter(omg);
            ret.add(omg);
          } else {
            if (DEBUG) {
              Debug.output("   --- OMGraphic fails filter, hiding...");
            }

            failedFilter(omg);
          }
        }
      }
    }

    return ret;
  }

  /** Returns true if the OMGraphicHandler can handle SQL statements for filtering. */
  public boolean supportsSQL() {
    return false;
  }

  /**
   * Filters the OMGraphicHandler graphic list so that graphics meeting the SQL query statement will
   * be visible. Returns an OMGraphicList with those visible shapes. The returned list should not be
   * assumed to be the same OMGraphicList object that is maintained inside the OMGraphicHandler.
   *
   * @param SQLQuery a SELECT SQL statement
   * @return OMGraphicList containing OMGraphics that meet the SELECT statement criteria.
   */
  public OMGraphicList filter(String SQLQuery) {
    return new OMGraphicList();
  }

  /**
   * Allows the OMGraphicHandler to receive graphics or take some action on one.
   *
   * @param graphic the OMGraphic to do the action on.
   * @param action the OMAction describing what to do to the graphic.
   * @return true if the action was able to be carried out.
   */
  public boolean doAction(OMGraphic graphic, OMAction action) {
    OMGraphicList list = getList();
    if (list != null) {
      list.doAction(graphic, action);
    }
    return true; // we can handle it.
  }

  /**
   * Return the graphic list currently being used by the OMGraphicHandler. If filters have been
   * applied, then the OMGraphics that have made it through the filter are visible. List may be
   * null, if it hasn't been set.
   *
   * @see OMGraphic#isVisible().
   */
  public synchronized OMGraphicList getList() {
    if (DEBUG) {
      Debug.output(
          "FilterSupport.getList() with "
              + (list != null ? list.size() + " graphics." : "null list."));
    }
    return list;
  }

  /** Indicates if the OMGraphicHandler can have its OMGraphicList set. */
  public boolean canSetList() {
    return true;
  }

  /** Set the OMGraphicList within this OMGraphicHandler. Works if canSetGraphicList == true. */
  public synchronized void setList(OMGraphicList omgl) {
    if (DEBUG) {
      Debug.output(
          "FilterSupport.setList() with "
              + (omgl != null ? omgl.size() + " graphics." : "null list."));
    }
    list = omgl;
  }

  /** Remove all filters, and reset all graphics to be visible. */
  public void resetFiltering() {
    OMGraphicList list = getList();
    if (list != null) list.setVisible(true);
  }

  /**
   * Method called when FilterSupport finds an OMGraphic that fails the filter test. The OMGraphic
   * is not being added to a list that is being returned for passing OMGraphics in another method,
   * this call-out is an opportunity to make settings on OMGraphics that pass the filter. By
   * default, the visibility of the OMGraphic is set to false.
   */
  protected void failedFilter(OMGraphic omg) {
    omg.setVisible(false);
  }

  /**
   * Method called when FilterSupport finds an OMGraphic that passes the filter test. The OMGraphic
   * is already being added to a list that is being returned in another method, this call-out is an
   * opportunity to make settings on OMGraphics that pass the filter.
   */
  protected void passedFilter(OMGraphic omg) {
    // NO-OP, by default
  }
}
コード例 #23
0
ファイル: BinaryFile.java プロジェクト: waqas64/debrief
  /**
   * Constructs a new BinaryFile with the specified file as the input. The byte-order is undefined.
   * Reads start at the first byte of the file. This constructor looks for the file with the string
   * given, and will call the correct constructor as appropriate. If the string represents a file
   * available locally, then the BinaryFile will be accessed with a FileInputReader using a
   * RandomAccessFile. If it's only available as a resource, then a StreamInputReader will be used.
   * The name should be a path to a file, or the name of a resource that can be found in the
   * classpath, or a URL.
   *
   * @param name the name of the file to be opened for reading
   * @exception IOException pass-through errors from opening the file.
   */
  public BinaryFile(final String name) throws IOException {
    boolean showDebug = false;
    if (Debug.debugging("binaryfile")) {
      showDebug = true;
    }

    if (showDebug) {
      Debug.output("BinaryFile: trying to figure out how to handle " + name);
    }

    try {
      File file = null;
      URL url = null;

      if (!Environment.isApplet()) {
        file = new File(name);
      }

      if (file != null && file.exists()) {
        // If the string represents a file, then we want to
        // use the RandomAccessFile aspect of the BinaryFile.
        setInputReader(new FileInputReader(file));
      } else {
        // url = ClassLoader.getSystemResource(name);
        url = Thread.currentThread().getContextClassLoader().getResource(name);

        // OK, now we want to look around for the file, in the
        // classpaths, and as a resource. It may be a file in
        // a classpath, available for direct access.
        if (url != null) {

          final String newname = url.getFile();
          if (showDebug) {
            Debug.output("BinaryFile: looking for " + newname);
          }

          if (!Environment.isApplet()) {
            file = new File(newname);
          }

          if (file != null && file.exists()) {
            // It's still a file, available directly.
            // Access it with the RandomAccessFile
            setInputReader(new FileInputReader(file));
          } else {
            // Need to get it as a resource. Needs
            // special handling if it's coming in a jar
            // file. Jar file references have a "!" in
            // them
            if (!setJarInputReader(newname)) {
              if (showDebug) {
                Debug.output(" trying as url: " + url);
              }
              setInputReader(new URLInputReader(url));
            }
          }

        } else if (Environment.isApplet()) {
          if (showDebug) {
            Debug.output(" As applet, checking codebase...");
          }
          // Look in the codebase for applets...
          final URL[] cba = new URL[1];
          cba[0] = Environment.getApplet().getCodeBase();

          final URLClassLoader ucl = URLClassLoader.newInstance(cba);
          url = ucl.getResource(name);

          if (url != null) {
            setInputReader(new URLInputReader(url));
          }
        }

        // It's not in the classpath, so try it as a URL.
        if (inputReader == null) {

          if (showDebug) {
            Debug.output(" lastly, trying as URL: " + name);
          }
          try {
            setInputReader(new URLInputReader(new URL(name)));
          } catch (final java.security.AccessControlException ace) {
            Debug.output("BinaryFile: " + name + " couldn't be accessed.");
            throw new IOException("AccessControlException trying to fetch " + name + " as a URL");
          }
        }
      }

      if (inputReader == null) {
        throw new FileNotFoundException("BinaryFile can't find: " + name);
      }

    } catch (final IOException ioe) {
      throw ioe;
    }
  }
コード例 #24
0
ファイル: BinaryFile.java プロジェクト: waqas64/debrief
 /** Set the input reader used by the BinaryFile. Make sure it's intialized properly. */
 public void setInputReader(final InputReader reader) {
   if (Debug.debugging("binaryfile")) {
     Debug.output("Setting inputReader");
   }
   inputReader = reader;
 }
コード例 #25
0
ファイル: BinaryFile.java プロジェクト: waqas64/debrief
  /**
   * A simple test method to determine if a file or directory, represented by a string, can be found
   * by the current Java environment. Uses the same tests as BinaryFile constructor for tracking
   * down a file.
   *
   * @param name A path to a file, a URL, or a path to a jar file entry.
   */
  public static boolean exists(final String name) {
    boolean exists = false;
    try {
      File file = null;
      URL url = null;

      if (!Environment.isApplet()) {
        file = new File(name);
      }

      if (file != null && file.exists()) {
        exists = true;
      } else {
        // url = ClassLoader.getSystemResource(name);
        url = Thread.currentThread().getContextClassLoader().getResource(name);

        // OK, now we want to look around for the file, in the
        // classpaths, and as a resource. It may be a file in
        // a classpath, available for direct access.
        if (url != null) {
          exists = true;
        } else if (Environment.isApplet()) {
          if (Debug.debugging("binaryfile")) {
            Debug.output(" As applet, checking codebase...");
          }
          // Look in the codebase for applets...
          final URL[] cba = new URL[1];
          cba[0] = Environment.getApplet().getCodeBase();

          final URLClassLoader ucl = URLClassLoader.newInstance(cba);
          if (ucl.getResource(name) != null) {
            exists = true;

            // This has been commented out because the
            // AppletDataNugget has been deprecated, and
            // is not needed.

            // } else {
            // url = AppletDataNugget.findResource(name);

            // if (url != null) {
            // exists = true;
            // }
          }
        }

        // It's not in the classpath, so try it as a URL to a
        // webserver.
        if (!exists && name.indexOf("http:") != -1) {

          try {
            final InputStream stream = new URL(name).openStream();
            stream.close();
            exists = true;
          } catch (final java.security.AccessControlException ace) {
            exists = false;
          }
        }
      }

    } catch (final IOException ioe) {
      Debug.message("binaryfile", "BinaryFile.exists() caught IOException");
      exists = false;
    }

    if (Debug.debugging("binaryfile")) {
      Debug.output("BinaryFile.exists(" + name + ") = " + exists);
    }

    return exists;
  }
コード例 #26
0
ファイル: DDFField.java プロジェクト: justfriend/openmap
  /**
   * Creates a string with variety of information about this field, and all it's subfields is
   * written to the given debugging file handle. Note that field definition information (ala
   * DDFFieldDefn) isn't written.
   *
   * @return String containing info.
   */
  public String toString() {
    StringBuffer buf = new StringBuffer("  DDFField:\n");
    buf.append("\tTag = ").append(poDefn.getName()).append("\n");
    buf.append("\tDescription = ").append(poDefn.getDescription()).append("\n");
    int size = getDataSize();
    buf.append("\tDataSize = ").append(size).append("\n");

    if (pachData == null) {
      buf.append("\tHeader offset = ").append(headerOffset).append("\n");
      buf.append("\tData position = ").append(dataPosition).append("\n");
      buf.append("\tData length = ").append(dataLength).append("\n");
      return buf.toString();
    }

    buf.append("\tData = ");
    for (int i = 0; i < Math.min(size, 40); i++) {
      if (pachData[i] < 32 || pachData[i] > 126) {
        buf.append(" | ").append((char) pachData[i]);
      } else {
        buf.append(pachData[i]);
      }
    }

    if (size > 40) buf.append("...");
    buf.append("\n");

    /* -------------------------------------------------------------------- */
    /* dump the data of the subfields. */
    /* -------------------------------------------------------------------- */
    if (Debug.debugging("iso8211.raw")) {
      int iOffset = 0;
      MutableInt nBytesConsumed = new MutableInt(0);

      for (int nLoopCount = 0; nLoopCount < getRepeatCount(); nLoopCount++) {
        if (nLoopCount > 8) {
          buf.append("      ...\n");
          break;
        }

        for (int i = 0; i < poDefn.getSubfieldCount(); i++) {
          byte[] subPachData = new byte[pachData.length - iOffset];
          System.arraycopy(pachData, iOffset, subPachData, 0, subPachData.length);

          buf.append(poDefn.getSubfieldDefn(i).dumpData(subPachData, subPachData.length));

          poDefn.getSubfieldDefn(i).getDataLength(subPachData, subPachData.length, nBytesConsumed);
          iOffset += nBytesConsumed.value;
        }
      }
    } else {
      buf.append("      Subfields:\n");

      for (Enumeration enumeration = subfields.keys(); enumeration.hasMoreElements(); ) {
        Object obj = subfields.get(enumeration.nextElement());

        if (obj instanceof List) {
          for (Iterator it = ((List) obj).iterator(); it.hasNext(); ) {
            DDFSubfield ddfs = (DDFSubfield) it.next();
            buf.append("        ").append(ddfs.toString()).append("\n");
          }
        } else {
          buf.append("        ").append(obj.toString()).append("\n");
        }
      }
    }

    return buf.toString();
  }
コード例 #27
0
 protected EditableOMGraphic() {
   DEBUG = Debug.debugging("eomg");
   DEBUG_DETAIL = Debug.debugging("eomgdetail");
 }
コード例 #28
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * DeterminePoliticalAreas goes over a list of omgraphics, and spits out a hashtable that holds
   * PoliticalArea objects for every area key. When an ID is found in the graphics, it is checked in
   * the hashtable for like graphics, and added to that PoliticalArea if found. If not found, a new
   * PoliticalArea is created and placed in the Hashtable. This will duplicate graphics if you call
   * it more than once for the same graphic list.
   *
   * @param graphicList the list of graphics. The top level graphic entries on the list represent
   *     areas.
   */
  public Hashtable determinePoliticalAreas(OMGraphicList graphicList, Hashtable poli_areas) {

    // Simple case. No graphics means an empty list of regions.
    String name = null;
    String key = null;

    if (graphicList != null) {
      int size = graphicList.size();
      for (int i = 0; i < size; i++) {
        OMGraphic graphic = graphicList.getOMGraphicAt(i);
        // below should be a vector like [ "Massachusetts",
        // "MA" ];

        Object obj = graphic.getAttribute(ShapeConstants.SHAPE_DBF_INFO_ATTRIBUTE);
        if (obj == null) {
          if (Debug.debugging("areas")) {
            Debug.error("AreaHandler: No attributes for graphic #" + i);
          }
          continue;
        }

        if (obj instanceof Vector) {
          Vector pair = (Vector) obj;

          name = (String) pair.elementAt(nameIndex);
          key = ((String) pair.elementAt(keyIndex)).toUpperCase().intern();
          if (Debug.debugging("areas")) {
            Debug.output("AreaHandler: looking at " + name + ", " + key);
          }
        } else if (obj instanceof String) {
          // Assume that the key is stored here, I guess.
          key = (String) obj;
          if (Debug.debugging("areas")) {
            Debug.output("AreaHandler: String app object, looking at " + key);
          }
        } else {
          if (Debug.debugging("areas")) {
            Debug.output("AreaHandler: Unidentified app object type " + obj);
          }
        }

        // Get the political area object for this keyiation.
        PoliticalArea area = (PoliticalArea) poli_areas.get(key);

        if (area == null) { // key is not in table
          area = new PoliticalArea(name, key);
          poli_areas.put(key, area); // add it to the table
          // AreaDrawParams adp =
          // (AreaDrawParams)drawingParams.get(key);
          // if (adp != null) {
          // area.setDrawingAttributes(adp.drawingAttributes);
          // }
        }

        // Add the graphic to the list for this political
        // area.
        area.addGraphic(graphic);
      }

      if (Debug.debugging("areas")) {
        Debug.output(
            "AreaHandler: Finished determinePoliticalAreas: "
                + poli_areas.size()
                + " areas defined.");
      }
    }

    return poli_areas;
  }
コード例 #29
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * Go through the properties, loading the shapefile, information file and attributes files, and
   * resolve how everything should be drawn. Might take awhile if the files are large. Called from
   * getRectangle, which is called when the AreaShapeLayer is added to the map.
   *
   * @param prefix property file entry header name
   * @param props the properties to look through.
   */
  public void initialize(String prefix, Properties props) {

    if (props == null) {
      Debug.error(
          "AreaHandler: initialize received bad input:\n\tprefix: "
              + prefix
              + "\n\tproperties: "
              + (props == null ? "null" : "OK"));
      politicalAreas = null;
      return;
    }

    prefix = PropUtils.getScopedPropertyPrefix(prefix);

    politicalAreas = new Hashtable();

    // OK, Get the graphics. We are not expecting that all the
    // graphics in the file are not too much to handle. Also, we
    // test for the serialized graphics file first, and if it
    // isn't designated, then look for a shapefile and spatial
    // index file to create an OMGraphicsList.
    String cacheFile = props.getProperty(prefix + CacheFileProperty);

    // First find the resource, if not, then try as a file-URL...
    try {
      cacheURL = PropUtils.getResourceOrFileOrURL(this, cacheFile);

      if (cacheURL != null) {
        omgraphics = readCachedGraphics(cacheURL);
      } else {
        // We'll use the spatial index set from the
        // ShapeLayer.

        // Now, get the attribute file
        String dbfFile = props.getProperty(prefix + dbfFileProperty);
        URL dbfFileURL = null;
        if (dbfFile != null) {
          dbfFileURL = PropUtils.getResourceOrFileOrURL(this, dbfFile);
        }
        if (dbfFileURL != null) {
          InputStream is = dbfFileURL.openStream();
          dbfModel = new DbfTableModel(new DbfInputStream(is));
        }
        if (dbfModel == null) {
          String csvFile = props.getProperty(prefix + csvFileProperty);
          URL infofileURL = null;
          if (csvFile != null) {
            infofileURL = PropUtils.getResourceOrFileOrURL(this, csvFile);
          }

          // Read them in.
          if (infofileURL != null) {
            infoFile = new CSVShapeInfoFile(csvFile);
            infoFile.setHeadersExist(
                PropUtils.booleanFromProperties(props, prefix + csvHeaderProperty, true));
            infoFile.loadData(true);
          }
        }
      }
    } catch (java.net.MalformedURLException murle) {
      omgraphics = new OMGraphicList();
    } catch (java.io.IOException ioe) {
      omgraphics = new OMGraphicList();
    } catch (Exception exc) {
      omgraphics = new OMGraphicList();
    }

    // This is handled properly yet. The PoliticalArea should be
    // updated to handle URLs for area points, and have different
    // icons for different areas.
    // String defaultPointImageURLString =
    // props.getProperty(prefix + pointImageURLProperty);

    // Now, match the attributes to the graphics. Find the
    // indexes of the name and the search key. Also figure out
    // which areas have special coloring needs.
    keyIndex = PropUtils.intFromProperties(props, prefix + keyIndexProperty, keyIndex);
    nameIndex = PropUtils.intFromProperties(props, prefix + nameIndexProperty, nameIndex);
    String areas = props.getProperty(prefix + areasProperty);

    if (areas == null) areas = "";

    StringTokenizer tokenizer = new StringTokenizer(areas, " ");
    // All this uses the properties to set the individual colors
    // of any area
    String currentArea;

    while (tokenizer.hasMoreTokens()) {
      currentArea = tokenizer.nextToken();

      PoliticalArea newParams = new PoliticalArea(currentArea);

      if (Debug.debugging("areas")) {
        Debug.output("AreaHandler: setting SPECIALIZED attributes for \"" + newParams.id + "\"");
      }

      areasItems.addElement(currentArea);

      newParams.drawingAttributes =
          new DrawingAttributes(prefix + areasProperty + "." + currentArea, props);

      politicalAreas.put(newParams.id.toUpperCase().intern(), newParams);
    }

    if (Debug.debugging("areas")) {
      Debug.output("AreaHandler: finished initialization");
    }
  }
コード例 #30
0
ファイル: AreaHandler.java プロジェクト: justfriend/openmap
  /**
   * Get the graphics for a particular lat/lon area.
   *
   * @param ulLat upper left latitude, in decimal degrees.
   * @param ulLon upper left longitude, in decimal degrees.
   * @param lrLat lower right latitude, in decimal degrees.
   * @param lrLon lower right longitude, in decimal degrees.
   * @param proj the current map projection.
   * @return OMGraphicList
   */
  public OMGraphicList getGraphics(
      double ulLat, double ulLon, double lrLat, double lrLon, Projection proj) {

    if (cacheURL != null) {
      return omgraphics;
    }

    if (spatialIndex == null) {
      return new OMGraphicList();
    }

    if (politicalAreas == null) {
      initialize(originalPrefix, originalProperties);
    }

    OMGraphicList list = new OMGraphicList();

    // check for dateline anomaly on the screen. we check for
    // ulLon >= lrLon, but we need to be careful of the check for
    // equality because of floating point arguments...
    if (ProjMath.isCrossingDateline(ulLon, lrLon, proj.getScale())) {
      if (Debug.debugging("areas")) {
        Debug.output("AreaHander.getGraphics(): Dateline is on screen");
      }

      double ymin = Math.min(ulLat, lrLat);
      double ymax = Math.max(ulLat, lrLat);

      try {

        list =
            spatialIndex.getOMGraphics(
                ulLon, ymin, 180.0d, ymax, list, drawingAttributes, proj, coordTransform);
        list =
            spatialIndex.getOMGraphics(
                -180.0d, ymin, lrLon, ymax, list, drawingAttributes, proj, coordTransform);

      } catch (InterruptedIOException iioe) {
        // This means that the thread has been interrupted,
        // probably due to a projection change. Not a big
        // deal, just return, don't do any more work, and let
        // the next thread solve all problems.
        list = null;
      } catch (IOException ex) {
        ex.printStackTrace();
      } catch (FormatException fe) {
        fe.printStackTrace();
      }

    } else {

      double xmin = (double) Math.min(ulLon, lrLon);
      double xmax = (double) Math.max(ulLon, lrLon);
      double ymin = (double) Math.min(ulLat, lrLat);
      double ymax = (double) Math.max(ulLat, lrLat);
      try {
        list =
            spatialIndex.getOMGraphics(
                xmin, ymin, xmax, ymax, list, drawingAttributes, proj, coordTransform);
      } catch (InterruptedIOException iioe) {
        // This means that the thread has been interrupted,
        // probably due to a projection change. Not a big
        // deal, just return, don't do any more work, and let
        // the next thread solve all problems.
        list = null;
      } catch (java.io.IOException ex) {
        ex.printStackTrace();
      } catch (FormatException fe) {
        fe.printStackTrace();
      }
    }

    updateDrawingParameters(list);
    return list;
  }