예제 #1
0
  private void layer(StringBuilder str, TileLayer layer, String baseurl) {
    str.append("  <Layer>\n");
    LayerMetaInformation layerMeta = layer.getMetaInformation();

    if (layerMeta == null) {
      appendTag(str, "    ", "ows:Title", layer.getName(), null);
    } else {
      appendTag(str, "    ", "ows:Title", layerMeta.getTitle(), null);
      appendTag(str, "    ", "ows:Abstract", layerMeta.getDescription(), null);
    }

    layerWGS84BoundingBox(str, layer);
    appendTag(str, "    ", "ows:Identifier", layer.getName(), null);

    // We need the filters for styles and dimensions
    List<ParameterFilter> filters = layer.getParameterFilters();

    layerStyles(str, layer, filters);

    layerFormats(str, layer);

    layerInfoFormats(str, layer);

    if (filters != null) {
      layerDimensions(str, layer, filters);
    }

    layerGridSubSets(str, layer);
    // TODO REST
    // str.append("    <ResourceURL format=\"image/png\" resourceType=\"tile\"
    // template=\"http://www.maps.cat/wmts/BlueMarbleNextGeneration/default/BigWorldPixel/{TileMatrix}/{TileRow}/{TileCol}.png\"/>\n");
    str.append("  </Layer>\n");
  }
예제 #2
0
  /** NB The following code is shared across Google Maps, Mobile Google Maps and Virtual Earth */
  public void handleRequest(ConveyorTile tile) throws GeoWebCacheException {
    if (tile.getHint() != null) {
      // boolean requestTiled = true;

      if (tile.getHint().equals("not_cached,not_metatiled")) {
        // requestTiled = false;
      } else if (!tile.getHint().equals("not_cached")) {
        throw new GeoWebCacheException("Hint " + tile.getHint() + " is not known.");
      }

      TileLayer tl = tld.getTileLayer(tile.getLayerId());

      if (tl == null) {
        throw new GeoWebCacheException("Unknown layer " + tile.getLayerId());
      }

      if (!tl.isCacheBypassAllowed().booleanValue()) {
        throw new GeoWebCacheException(
            "Layer " + tile.getLayerId() + " is not configured to allow bypassing the cache.");
      }

      tile.setTileLayer(tl);
      tl.getNoncachedTile(tile);

      Service.writeTileResponse(tile, false);
    }
  }
예제 #3
0
  public void apply(ConveyorTile convTile) throws RequestFilterException {
    TileLayer tl = convTile.getLayer();
    // SRS srs = convTile.getSRS();
    GridSubset gridSubset = tl.getGridSubset(convTile.getGridSetId());

    int z = (int) convTile.getTileIndex()[2];
    long[] gridCoverage = gridSubset.getCoverage(z);

    // Figure out the radius
    long width = gridCoverage[2] - gridCoverage[0];
    long height = gridCoverage[3] - gridCoverage[1];

    // Rounding must always err on the side of
    // caution if you want to use KML hierarchies
    long maxRad = 0;
    if (width > height) {
      maxRad = (width / 4) + 1;
    } else {
      maxRad = (height / 4) + 1;
    }

    // Figure out how the requested bounds relate
    long midX = gridCoverage[0] + width / 2;
    long midY = gridCoverage[1] + height / 2;

    long xDist = midX - convTile.getTileIndex()[0];
    long yDist = midY - convTile.getTileIndex()[1];

    long rad = Math.round(Math.sqrt(xDist * xDist + yDist * yDist));

    if (rad > maxRad) {
      throw new BlankTileException(this);
    }
  }
예제 #4
0
  private void dimensionDescription(
      StringBuilder str, ParameterFilter filter, List<String> values) {
    str.append("    <Dimension>");
    str.append("      <Identifier>" + filter.key + "</Identifier>");
    String defaultStr = TileLayer.encodeDimensionValue(filter.defaultValue);
    str.append("      <Default>" + encodeXmlChars(defaultStr) + "</Default>");

    Iterator<String> iter = values.iterator();
    while (iter.hasNext()) {
      String value = TileLayer.encodeDimensionValue(iter.next());
      str.append("      <Value>" + encodeXmlChars(value) + "</Value>");
    }
    str.append("    </Dimension>");
  }
예제 #5
0
  private void layerFormats(StringBuilder str, TileLayer layer) {
    Iterator<MimeType> mimeIter = layer.getMimeTypes().iterator();

    while (mimeIter.hasNext()) {
      str.append("    <Format>" + mimeIter.next().getFormat() + "</Format>\n");
    }
  }
예제 #6
0
  private void capabilityVendorSpecificTileset(
      StringBuilder str, TileLayer layer, GridSubset grid, String formatStr, String styleName)
      throws GeoWebCacheException {

    String srsStr = grid.getSRS().toString();
    StringBuilder resolutionsStr = new StringBuilder();
    double[] res = grid.getResolutions();
    for (int i = 0; i < res.length; i++) {
      resolutionsStr.append(Double.toString(res[i]) + " ");
    }

    String[] bs = boundsPrep(grid.getCoverageBestFitBounds());

    str.append("    <TileSet>\n");
    str.append("      <SRS>" + srsStr + "</SRS>\n");
    str.append(
        "      <BoundingBox SRS=\""
            + srsStr
            + "\" minx=\""
            + bs[0]
            + "\" miny=\""
            + bs[1]
            + "\"  maxx=\""
            + bs[2]
            + "\"  maxy=\""
            + bs[3]
            + "\" />\n");
    str.append("      <Resolutions>" + resolutionsStr.toString() + "</Resolutions>\n");
    str.append("      <Width>" + grid.getTileWidth() + "</Width>\n");
    str.append("      <Height>" + grid.getTileHeight() + "</Height>\n");
    str.append("      <Format>" + formatStr + "</Format>\n");
    str.append("      <Layers>" + layer.getName() + "</Layers>\n");
    str.append("      <Styles>").append(ServletUtils.URLEncode(styleName)).append("</Styles>\n");
    str.append("    </TileSet>\n");
  }
예제 #7
0
  private void contents(StringBuilder str) {
    str.append("<Contents>\n");
    Iterable<TileLayer> iter = tld.getLayerList();
    for (TileLayer layer : iter) {
      if (!layer.isEnabled()) {
        continue;
      }
      layer(str, layer, baseUrl);
    }

    for (GridSet gset : gsb.getGridSets()) {
      tileMatrixSet(str, gset);
    }

    str.append("</Contents>\n");
  }
예제 #8
0
  private void layerGridSubSets(StringBuilder str, TileLayer layer) {
    Iterator<GridSubset> gridSubsets = layer.getGridSubsets().values().iterator();

    while (gridSubsets.hasNext()) {
      GridSubset gridSubset = gridSubsets.next();

      str.append("    <TileMatrixSetLink>");
      str.append("      <TileMatrixSet>" + gridSubset.getName() + "</TileMatrixSet>\n");

      if (!gridSubset.fullGridSetCoverage()) {
        String[] levelNames = gridSubset.getGridNames();
        long[][] wmtsLimits = gridSubset.getWMTSCoverages();

        str.append("      <TileMatrixSetLimits>\n");
        for (int i = 0; i < levelNames.length; i++) {
          str.append("        <TileMatrixLimits>\n");
          str.append("          <TileMatrix>" + levelNames[i] + "</TileMatrix>\n");
          str.append("          <MinTileRow>" + wmtsLimits[i][1] + "</MinTileRow>\n");
          str.append("          <MaxTileRow>" + wmtsLimits[i][3] + "</MaxTileRow>\n");
          str.append("          <MinTileCol>" + wmtsLimits[i][0] + "</MinTileCol>\n");
          str.append("          <MaxTileCol>" + wmtsLimits[i][2] + "</MaxTileCol>\n");
          str.append("        </TileMatrixLimits>\n");
        }
        str.append("      </TileMatrixSetLimits>\n");
      }
      str.append("    </TileMatrixSetLink>");
    }
  }
예제 #9
0
  protected WMSTileFuser(TileLayerDispatcher tld, StorageBroker sb, HttpServletRequest servReq)
      throws GeoWebCacheException {
    this.sb = sb;

    String[] keys = {
      "layers", "format", "srs", "bbox", "width", "height", "transparent", "bgcolor"
    };

    Map<String, String> values =
        ServletUtils.selectedStringsFromMap(
            servReq.getParameterMap(), servReq.getCharacterEncoding(), keys);

    // TODO Parameter filters?

    String layerName = values.get("layers");
    layer = tld.getTileLayer(layerName);

    List<MimeType> ml = layer.getMimeTypes();
    Iterator<MimeType> iter = ml.iterator();
    while (iter.hasNext()) {
      MimeType mt = iter.next();
      if (mt.getInternalName().equalsIgnoreCase("png")) {
        this.srcFormat = (ImageMime) mt;
      }
    }

    gridSubset = layer.getGridSubsetForSRS(SRS.getSRS(values.get("srs")));

    outputFormat = (ImageMime) ImageMime.createFromFormat(values.get("format"));

    reqBounds = new BoundingBox(values.get("bbox"));

    reqWidth = Integer.valueOf(values.get("width"));

    reqHeight = Integer.valueOf(values.get("height"));

    // if(values[6] != null) {
    // this.reqTransparent = Boolean.valueOf(values[6]);
    // }

    // if(values[7] != null) {
    // this.reqBgColor = values[7];
    // }

    fullParameters =
        layer.getModifiableParameters(servReq.getParameterMap(), servReq.getCharacterEncoding());
  }
예제 #10
0
 private void layerInfoFormats(StringBuilder str, TileLayer layer) {
   // TODO properly
   if (layer.isQueryable()) {
     str.append("    <InfoFormat>text/plain</InfoFormat>\n");
     str.append("    <InfoFormat>text/html</InfoFormat>\n");
     str.append("    <InfoFormat>application/vnd.ogc.gml</InfoFormat>\n");
   }
 }
예제 #11
0
  private void layerStyles(StringBuilder str, TileLayer layer, List<ParameterFilter> filters) {
    String defStyle = layer.getStyles();
    if (filters == null) {
      str.append("    <Style isDefault=\"true\">\n");
      str.append(
          "      <ows:Identifier>"
              + TileLayer.encodeDimensionValue(defStyle)
              + "</ows:Identifier>\n");
      str.append("    </Style>\n");
    } else {
      ParameterFilter stylesFilter = null;
      Iterator<ParameterFilter> iter = filters.iterator();
      while (stylesFilter == null && iter.hasNext()) {
        ParameterFilter filter = iter.next();
        if (filter.key.equalsIgnoreCase("STYLES")) {
          stylesFilter = filter;
        }
      }

      if (stylesFilter != null) {
        String defVal = stylesFilter.defaultValue;
        if (defVal == null) {
          if (defStyle != null) {
            defVal = defStyle;
          } else {
            defVal = "";
          }
        }

        Iterator<String> valIter = stylesFilter.getLegalValues().iterator();
        while (valIter.hasNext()) {
          String value = valIter.next();
          if (value.equals(defVal)) {
            str.append("    <Style isDefault=\"true\">\n");
          } else {
            str.append("    <Style>\n");
          }
          str.append(
              "      <ows:Identifier>"
                  + TileLayer.encodeDimensionValue(value)
                  + "</ows:Identifier>\n");
          str.append("    </Style>\n");
        }
      }
    }
  }
예제 #12
0
 private static String makeModifiableParameters(TileLayer tl) {
   List<ParameterFilter> parameterFilters = tl.getParameterFilters();
   if (parameterFilters == null || parameterFilters.size() == 0) {
     return "";
   }
   parameterFilters = new ArrayList<ParameterFilter>(parameterFilters);
   Collections.sort(
       parameterFilters,
       new Comparator<ParameterFilter>() {
         public int compare(ParameterFilter o1, ParameterFilter o2) {
           return o1.getKey().compareTo(o2.getKey());
         }
       });
   StringBuilder doc = new StringBuilder();
   doc.append("Modifiable Parameters:\n");
   doc.append("<table>\n");
   for (ParameterFilter pf : parameterFilters) {
     Assert.notNull(pf);
     String key = pf.getKey();
     String defaultValue = pf.getDefaultValue();
     List<String> legalValues = pf.getLegalValues();
     doc.append("<tr><td>").append(key.toUpperCase()).append(": ").append("</td><td>");
     String parameterId = key;
     if (pf instanceof StringParameterFilter) {
       Map<String, String> keysValues = makeParametersMap(defaultValue, legalValues);
       makePullDown(doc, parameterId, keysValues, defaultValue);
     } else if (pf instanceof RegexParameterFilter) {
       makeTextInput(doc, parameterId, 25);
     } else if (pf instanceof FloatParameterFilter) {
       FloatParameterFilter floatParam = (FloatParameterFilter) pf;
       if (floatParam.getValues().isEmpty()) {
         // accepts any value
         makeTextInput(doc, parameterId, 25);
       } else {
         Map<String, String> keysValues = makeParametersMap(defaultValue, legalValues);
         makePullDown(doc, parameterId, keysValues, defaultValue);
       }
     } else if ("org.geowebcache.filter.parameters.NaiveWMSDimensionFilter"
         .equals(pf.getClass().getName())) {
       makeTextInput(doc, parameterId, 25);
     } else {
       // Unknown filter type
       if (legalValues == null) {
         // Doesn't have a defined set of values, just provide a text field
         makeTextInput(doc, parameterId, 25);
       } else {
         // Does have a defined set of values, so provide a drop down
         Map<String, String> keysValues = makeParametersMap(defaultValue, legalValues);
         makePullDown(doc, parameterId, keysValues, defaultValue);
       }
     }
     doc.append("</td></tr>\n");
   }
   doc.append("</table>\n");
   return doc.toString();
 }
예제 #13
0
 private void layerWGS84BoundingBox(StringBuilder str, TileLayer layer) {
   GridSubset subset = layer.getGridSubsetForSRS(SRS.getEPSG4326());
   if (subset != null) {
     double[] coords = subset.getOriginalExtent().getCoords();
     str.append("    <ows:WGS84BoundingBox>\n");
     str.append("      <ows:LowerCorner>" + coords[0] + " " + coords[1] + "</ows:LowerCorner>\n");
     str.append("      <ows:UpperCorner>" + coords[2] + " " + coords[3] + "</ows:UpperCorner>\n");
     str.append("    </ows:WGS84BoundingBox>\n");
   }
 }
  private void vendorSpecificTileset(
      final Translator tx, final TileLayer layer, final GridSubset grid, final String format) {

    String srsStr = grid.getSRS().toString();
    StringBuilder resolutionsStr = new StringBuilder();
    double[] res = grid.getResolutions();
    for (int i = 0; i < res.length; i++) {
      resolutionsStr.append(Double.toString(res[i]) + " ");
    }

    String[] bs = boundsPrep(grid.getCoverageBestFitBounds());

    tx.start("TileSet");

    tx.start("SRS");
    tx.chars(srsStr);
    tx.end("SRS");

    AttributesImpl atts;
    atts = new AttributesImpl();
    atts.addAttribute("", "SRS", "SRS", "", srsStr);
    atts.addAttribute("", "minx", "minx", "", bs[0]);
    atts.addAttribute("", "miny", "miny", "", bs[1]);
    atts.addAttribute("", "maxx", "maxx", "", bs[2]);
    atts.addAttribute("", "maxy", "maxy", "", bs[3]);

    tx.start("BoundingBox", atts);
    tx.end("BoundingBox");

    tx.start("Resolutions");
    tx.chars(resolutionsStr.toString());
    tx.end("Resolutions");

    tx.start("Width");
    tx.chars(String.valueOf(grid.getTileWidth()));
    tx.end("Width");

    tx.start("Height");
    tx.chars(String.valueOf(grid.getTileHeight()));
    tx.end("Height");

    tx.start("Format");
    tx.chars(format);
    tx.end("Format");

    tx.start("Layers");
    tx.chars(layer.getName());
    tx.end("Layers");

    // TODO ignoring styles for now
    tx.start("Styles");
    tx.end("Styles");

    tx.end("TileSet");
  }
예제 #15
0
  private void capabilityRequestGetFeatureInfo(StringBuilder str) {

    // Find all the info formats we support
    Iterable<TileLayer> layerIter = tld.getLayerList();

    HashSet<String> formats = new HashSet<String>();

    for (TileLayer layer : layerIter) {
      if (!layer.isEnabled()) {
        continue;
      }
      if (layer.getMimeTypes() != null) {
        Iterator<MimeType> mimeIter = layer.getInfoMimeTypes().iterator();
        while (mimeIter.hasNext()) {
          MimeType mime = mimeIter.next();
          formats.add(mime.getFormat());
        }
      } else {
        formats.add("text/plain");
        formats.add("text/html");
        formats.add("application/vnd.ogc.gml");
      }
    }

    str.append("    <GetFeatureInfo>\n");
    Iterator<String> formatIter = formats.iterator();
    while (formatIter.hasNext()) {
      str.append("      <Format>" + formatIter.next() + "</Format>\n");
    }
    str.append("      <DCPType>\n");
    str.append("        <HTTP>\n");
    str.append("        <Get>\n");
    str.append(
        "          <OnlineResource xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:type=\"simple\" xlink:href=\""
            + urlStr
            + "\"/>\n");
    str.append("        </Get>\n");
    str.append("        </HTTP>\n");
    str.append("      </DCPType>\n");
    str.append("    </GetFeatureInfo>\n");
  }
  /**
   * @see
   *     org.geoserver.wms.ExtendedCapabilitiesProvider#encode(org.geoserver.wms.ExtendedCapabilitiesProvider.Translator,
   *     org.geoserver.wms.WMSInfo, org.geotools.util.Version)
   */
  public void encode(final Translator tx, final WMSInfo wms, final GetCapabilitiesRequest request)
      throws IOException {
    Version version = WMS.version(request.getVersion(), true);
    if (!WMS.VERSION_1_1_1.equals(version) || !isTiled(request)) {
      return;
    }

    String namespacePrefixFilter = request.getNamespace();
    Iterable<TileLayer> tileLayers = gwc.getTileLayersByNamespacePrefix(namespacePrefixFilter);

    for (TileLayer layer : tileLayers) {

      Set<String> layerGrids = layer.getGridSubsets();

      for (String gridId : layerGrids) {
        GridSubset grid = layer.getGridSubset(gridId);
        for (MimeType mime : layer.getMimeTypes()) {
          vendorSpecificTileset(tx, layer, grid, mime.getFormat());
        }
      }
    }
  }
예제 #17
0
  private void capabilityLayerOuter(StringBuilder str) {
    str.append("  <Layer>\n");
    str.append("    <Title>GeoWebCache WMS</Title>\n");
    str.append(
        "    <Abstract>Note that not all GeoWebCache instances provide a full WMS service.</Abstract>\n");
    str.append(
        "    <LatLonBoundingBox minx=\"-180.0\" miny=\"-90.0\" maxx=\"180.0\" maxy=\"90.0\"/>\n");

    Iterable<TileLayer> layerIter = tld.getLayerList();
    for (TileLayer layer : layerIter) {
      if (!layer.isEnabled()) {
        continue;
      }
      try {
        capabilityLayerInner(str, layer);
      } catch (GeoWebCacheException e) {
        log.error(e.getMessage());
      }
    }

    str.append("  </Layer>\n");
  }
  @Test
  public void testParseMaplinkAndLayersWithGeoJSONFromJsonTest()
      throws IOException, ParseException, com.vividsolutions.jts.io.ParseException {

    XMLConfiguration config = shared.getConfig();

    TileLayer tileLayer = config.getTileLayer(layerTemplate);
    GridSubset gridSubset = tileLayer.getGridSubset(gridSubsetName);

    MapLayerJSONParser layerJsonParser = new MapLayerJSONParser(props);

    MaplinkGeoJsonParser parser = new MaplinkGeoJsonParser();
    parser.setDebug(true);

    InputStream inp = MapProducer.class.getResourceAsStream("geojsPrintTest.json");

    try {

      assertTrue(MapLinkGeoJsonParseContext.Default.getPm().buildMap);

      Map<String, ?> root = parser.parse(inp);

      assertTrue(root.size() != 0);
      assertTrue(root.get("layers") != null);
      assertTrue(root.get("maplink") != null);
      assertTrue(root.get("state") != null);

      assertTrue(root.get("layers") != null);

      MapLink mapLink =
          layerJsonParser.parseMapLinkJSON(root, shared.getGf(), gridSubset.getResolutions());

      assertTrue(mapLink != null);

    } finally {
      inp.close();
    }
  }
예제 #19
0
  private void capabilityVendorSpecific(StringBuilder str) {
    str.append("  <VendorSpecificCapabilities>\n");
    Iterable<TileLayer> layerIter = tld.getLayerList();
    for (TileLayer layer : layerIter) {
      if (!layer.isEnabled()) {
        continue;
      }

      for (String gridSetId : layer.getGridSubsets()) {
        GridSubset grid = layer.getGridSubset(gridSetId);

        List<String> formats = new ArrayList<String>(2);

        if (layer.getMimeTypes() != null) {
          for (MimeType mime : layer.getMimeTypes()) {
            formats.add(mime.getFormat());
          }
        } else {
          formats.add(ImageMime.png.getFormat());
          formats.add(ImageMime.jpeg.getFormat());
        }

        List<String> styles = getStyles(layer.getParameterFilters());
        for (String format : formats) {
          for (String style : styles) {
            try {
              capabilityVendorSpecificTileset(str, layer, grid, format, style);
            } catch (GeoWebCacheException e) {
              log.error(e.getMessage());
            }
          }
        }
      }
    }
    str.append("  </VendorSpecificCapabilities>\n");
  }
예제 #20
0
  protected void renderCanvas() throws OutsideCoverageException, GeoWebCacheException, IOException {
    // Now we loop over all the relevant tiles and write them to the canvas,
    // Starting at the bottom, moving to the right and up

    // Bottom row of tiles, in tile coordinates
    long starty = srcRectangle[1];

    // gridy is the tile row index
    for (long gridy = starty; gridy <= srcRectangle[3]; gridy++) {

      int tiley = 0;
      int canvasy = (int) (srcRectangle[3] - gridy) * gridSubset.getTileHeight();
      int tileHeight = gridSubset.getTileHeight();

      if (canvOfs.top > 0) {
        // Add padding
        canvasy += canvOfs.top;
      } else {
        // Top tile is cut off
        if (gridy == srcRectangle[3]) {
          // This one starts at the top, so canvasy remains 0
          tileHeight = tileHeight + canvOfs.top;
          tiley = -canvOfs.top;
        } else {
          // Offset that the first tile contributed,
          // rather, we subtract what it did not contribute
          canvasy += canvOfs.top;
        }
      }

      if (gridy == srcRectangle[1] && canvOfs.bottom < 0) {
        // Check whether we only use part of the first tiles (bottom row)
        // Offset is negative, slice the bottom off the tile
        tileHeight += canvOfs.bottom;
      }

      long startx = srcRectangle[0];
      for (long gridx = startx; gridx <= srcRectangle[2]; gridx++) {

        long[] gridLoc = {gridx, gridy, srcIdx};

        ConveyorTile tile =
            new ConveyorTile(
                sb,
                layer.getName(),
                gridSubset.getName(),
                gridLoc,
                ImageMime.png,
                fullParameters,
                null,
                null);

        // Check whether this tile is to be rendered at all
        try {
          layer.applyRequestFilters(tile);
        } catch (RequestFilterException e) {
          log.debug(e.getMessage());
          continue;
        }

        layer.getTile(tile);

        BufferedImage tileImg = ImageIO.read(tile.getBlob().getInputStream());

        int tilex = 0;
        int canvasx = (int) (gridx - startx) * gridSubset.getTileWidth();
        int tileWidth = gridSubset.getTileWidth();

        if (canvOfs.left > 0) {
          // Add padding
          canvasx += canvOfs.left;
        } else {
          // Leftmost tile is cut off
          if (gridx == srcRectangle[0]) {
            // This one starts to the left top, so canvasx remains 0
            tileWidth = tileWidth + canvOfs.left;
            tilex = -canvOfs.left;
          } else {
            // Offset that the first tile contributed,
            // rather, we subtract what it did not contribute
            canvasx += canvOfs.left;
          }
        }

        if (gridx == srcRectangle[2] && canvOfs.right < 0) {
          // Check whether we only use part of the first tiles (bottom row)
          // Offset is negative, slice the bottom off the tile
          tileWidth = tileWidth + canvOfs.right;
        }

        // TODO We should really ensure we can never get here
        if (tileWidth == 0 || tileHeight == 0) {
          log.debug("tileWidth: " + tileWidth + " tileHeight: " + tileHeight);
          continue;
        }

        // Cut down the tile to the part we want
        if (tileWidth != gridSubset.getTileWidth() || tileHeight != gridSubset.getTileHeight()) {
          log.debug(
              "tileImg.getSubimage("
                  + tilex
                  + ","
                  + tiley
                  + ","
                  + tileWidth
                  + ","
                  + tileHeight
                  + ")");
          tileImg = tileImg.getSubimage(tilex, tiley, tileWidth, tileHeight);
        }

        // Render the tile on the big canvas
        log.debug(
            "drawImage(subtile," + canvasx + "," + canvasy + ",null) " + Arrays.toString(gridLoc));
        gfx.drawImage(tileImg, canvasx, canvasy, null); // imageObserver
      }
    }

    gfx.dispose();
  }
예제 #21
0
  public static void makeMap(
      TileLayerDispatcher tileLayerDispatcher,
      GridSetBroker gridSetBroker,
      String action,
      HttpServletRequest request,
      HttpServletResponse response)
      throws GeoWebCacheException {

    String page = null;

    // Do we have a layer, or should we make a list?
    if (action != null) {
      String layerName = ServletUtils.URLDecode(action, request.getCharacterEncoding());

      TileLayer layer = tileLayerDispatcher.getTileLayer(layerName);

      String rawGridSet = request.getParameter("gridSet");
      String gridSetStr = null;
      if (rawGridSet != null)
        gridSetStr = ServletUtils.URLDecode(rawGridSet, request.getCharacterEncoding());

      if (gridSetStr == null) {
        gridSetStr = request.getParameter("srs");

        if (gridSetStr == null) {
          gridSetStr = layer.getGridSubsets().iterator().next();
        }
      }

      String formatStr = request.getParameter("format");

      if (formatStr != null) {
        if (!layer.supportsFormat(formatStr)) {
          throw new GeoWebCacheException("Unknow or unsupported format " + formatStr);
        }
      } else {
        formatStr = layer.getDefaultMimeType().getFormat();
      }

      if (request.getPathInfo().startsWith("/demo")) {
        // Running in GeoServer
        page = generateHTML(layer, gridSetStr, formatStr, true);
      } else {
        page = generateHTML(layer, gridSetStr, formatStr, false);
      }

    } else {
      if (request.getRequestURI().endsWith("/")) {
        try {
          String reqUri = request.getRequestURI();
          response.sendRedirect(
              response.encodeRedirectURL(reqUri.substring(0, reqUri.length() - 1)));
        } catch (IOException e) {
          e.printStackTrace();
        }
        return;
      } else {
        page = generateHTML(tileLayerDispatcher, gridSetBroker);
      }
    }
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    try {
      response.getOutputStream().write(page.getBytes());
    } catch (IOException ioe) {
      throw new GeoWebCacheException("failed to render HTML");
    }
  }
예제 #22
0
  private static String generateHTML(
      TileLayer layer, String gridSetStr, String formatStr, boolean asPlugin)
      throws GeoWebCacheException {
    String layerName = layer.getName();

    GridSubset gridSubset = layer.getGridSubset(gridSetStr);

    BoundingBox bbox = gridSubset.getGridSetBounds();
    BoundingBox zoomBounds = gridSubset.getOriginalExtent();

    String res = "resolutions: " + Arrays.toString(gridSubset.getResolutions()) + ",\n";

    String units = "units: \"" + gridSubset.getGridSet().guessMapUnits() + "\",\n";

    String openLayersPath;
    if (asPlugin) {
      openLayersPath = "../openlayers/OpenLayers.js";
    } else {
      openLayersPath = "../openlayers/OpenLayers.js";
    }

    String page =
        "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>\n"
            + "<meta http-equiv=\"imagetoolbar\" content=\"no\">\n"
            + "<title>"
            + layerName
            + " "
            + gridSubset.getName()
            + " "
            + formatStr
            + "</title>\n"
            + "<style type=\"text/css\">\n"
            + "body { font-family: sans-serif; font-weight: bold; font-size: .8em; }\n"
            + "body { border: 0px; margin: 0px; padding: 0px; }\n"
            + "#map { width: 85%; height: 85%; border: 0px; padding: 0px; }\n"
            + "</style>\n"
            + "<script src=\""
            + openLayersPath
            + "\"></script>    \n"
            + "<script type=\"text/javascript\">               \n"
            + "var map, demolayer;                               \n"
            + "  // sets the chosen modifiable parameter        \n"
            + "  function setParam(name, value){                \n"
            + "   str = \"demolayer.mergeNewParams({\" + name + \": '\" + value + \"'})\" \n"
            + "   // alert(str);                                   \n"
            + "   eval(str);                                    \n"
            + "  }                                              \n"
            + "OpenLayers.DOTS_PER_INCH = "
            + gridSubset.getDotsPerInch()
            + ";\n"
            + "OpenLayers.Util.onImageLoadErrorColor = 'transparent';\n"
            + "function init(){\n"
            + "var mapOptions = { \n"
            + res
            + "projection: new OpenLayers.Projection('"
            + gridSubset.getSRS().toString()
            + "'),\n"
            + "maxExtent: new OpenLayers.Bounds("
            + bbox.toString()
            + "),\n"
            + units
            + "controls: []\n"
            + "};\n"
            + "map = new OpenLayers.Map('map', mapOptions );\n"
            + "map.addControl(new OpenLayers.Control.PanZoomBar({\n"
            + "		position: new OpenLayers.Pixel(2, 15)\n"
            + "}));\n"
            + "map.addControl(new OpenLayers.Control.Navigation());\n"
            + "map.addControl(new OpenLayers.Control.Scale($('scale')));\n"
            + "map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));\n"
            + "demolayer = new OpenLayers.Layer.WMS(\n"
            + "\""
            + layerName
            + "\",\"../service/wms\",\n"
            + "{layers: '"
            + layerName
            + "', format: '"
            + formatStr
            + "' },\n"
            + "{ tileSize: new OpenLayers.Size("
            + gridSubset.getTileWidth()
            + ","
            + gridSubset.getTileHeight()
            + ")";

    /*
     * If the gridset has a top left tile origin, lets tell that to open layers. Otherwise it'll
     * calculate tile bounds based on the bbox bottom left corner, leading to misaligned
     * requests.
     */
    GridSet gridSet = gridSubset.getGridSet();
    if (gridSet.isTopLeftAligned()) {
      page +=
          ",\n tileOrigin: new OpenLayers.LonLat(" + bbox.getMinX() + ", " + bbox.getMaxY() + ")";
    }

    page +=
        "});\n"
            + "map.addLayer(demolayer);\n"
            + "map.zoomToExtent(new OpenLayers.Bounds("
            + zoomBounds.toString()
            + "));\n"
            + "// The following is just for GetFeatureInfo, which is not cached. Most people do not need this \n"
            + "map.events.register('click', map, function (e) {\n"
            + "  document.getElementById('nodelist').innerHTML = \"Loading... please wait...\";\n"
            + "  var params = {\n"
            + "    REQUEST: \"GetFeatureInfo\",\n"
            + "    EXCEPTIONS: \"application/vnd.ogc.se_xml\",\n"
            + "    BBOX: map.getExtent().toBBOX(),\n"
            + "    X: e.xy.x,\n"
            + "    Y: e.xy.y,\n"
            + "    INFO_FORMAT: 'text/html',\n"
            + "    QUERY_LAYERS: map.layers[0].params.LAYERS,\n"
            + "    FEATURE_COUNT: 50,\n"
            + "    Layers: '"
            + layerName
            + "',\n"
            + "    Styles: '',\n"
            + "    Srs: '"
            + gridSubset.getSRS().toString()
            + "',\n"
            + "    WIDTH: map.size.w,\n"
            + "    HEIGHT: map.size.h,\n"
            + "    format: \""
            + formatStr
            + "\" };\n"
            + "  OpenLayers.loadURL(\"../service/wms\", params, this, setHTML, setHTML);\n"
            + "  OpenLayers.Event.stop(e);\n"
            + "  });\n"
            + "}\n"
            + "function setHTML(response){\n"
            + "    document.getElementById('nodelist').innerHTML = response.responseText;\n"
            + "};\n"
            + "</script>\n"
            + "</head>\n"
            + "<body onload=\"init()\">\n"
            + "<div id=\"params\">"
            + makeModifiableParameters(layer)
            + "</div>\n"
            + "<div id=\"map\"></div>\n"
            + "<div id=\"nodelist\"></div>\n"
            + "</body>\n"
            + "</html>";
    return page;
  }
예제 #23
0
  private static String tableRows(
      TileLayerDispatcher tileLayerDispatcher, GridSetBroker gridSetBroker)
      throws GeoWebCacheException {
    StringBuffer buf = new StringBuffer();

    Set<String> layerList = new TreeSet<String>(tileLayerDispatcher.getLayerNames());
    for (String layerName : layerList) {
      TileLayer layer = tileLayerDispatcher.getTileLayer(layerName);
      buf.append(
          "<tr><td style=\"min-width: 100px;\"><strong>" + layer.getName() + "</strong><br />\n");
      buf.append("<a href=\"rest/seed/" + layer.getName() + "\">Seed this layer</a>\n");
      buf.append("</td><td>" + layer.isEnabled() + "</td>");
      buf.append("<td><table width=\"100%\">");

      int count = 0;
      for (String gridSetId : layer.getGridSubsets()) {
        GridSubset gridSubset = layer.getGridSubset(gridSetId);
        String gridSetName = gridSubset.getName();
        if (gridSetName.length() > 20) {
          gridSetName = gridSetName.substring(0, 20) + "...";
        }
        buf.append("<tr><td style=\"width: 170px;\">").append(gridSetName);

        buf.append("</td><td>OpenLayers: [");
        Iterator<MimeType> mimeIter = layer.getMimeTypes().iterator();
        boolean prependComma = false;
        while (mimeIter.hasNext()) {
          MimeType mime = mimeIter.next();
          if (mime instanceof ImageMime) {
            if (prependComma) {
              buf.append(", ");
            } else {
              prependComma = true;
            }
            buf.append(generateDemoUrl(layer.getName(), gridSubset.getName(), (ImageMime) mime));
          }
        }
        buf.append("]</td><td>\n");

        if (gridSubset.getName().equals(gridSetBroker.WORLD_EPSG4326.getName())) {
          buf.append(" &nbsp; KML: [");
          String prefix = "";
          prependComma = false;
          Iterator<MimeType> kmlIter = layer.getMimeTypes().iterator();
          while (kmlIter.hasNext()) {
            MimeType mime = kmlIter.next();
            if (mime instanceof ImageMime || mime == XMLMime.kml) {
              if (prependComma) {
                buf.append(", ");
              } else {
                prependComma = true;
              }
              buf.append(
                  "<a href=\""
                      + prefix
                      + "service/kml/"
                      + layer.getName()
                      + "."
                      + mime.getFileExtension()
                      + ".kml\">"
                      + mime.getFileExtension()
                      + "</a>");
            } else if (mime == XMLMime.kmz) {
              if (prependComma) {
                buf.append(", ");
              } else {
                prependComma = true;
              }
              buf.append(
                  "<a href=\"" + prefix + "service/kml/" + layer.getName() + ".kml.kmz\">kmz</a>");
            }
          }
          buf.append("]");
        } else {
          // No Google Earth support
        }
        buf.append("</td></tr>");
        count++;
      }

      // if(count == 0) {
      // buf.append("<tr><td colspan=\"2\"><i>None</i></td></tr>\n");
      // }

      buf.append("</table></td>\n");
      buf.append("</tr>\n");
    }

    return buf.toString();
  }
  @Test
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testParseMaplinkAndLayersWithGeoJSONFromJsonEmbedded()
      throws IOException, ParseException, com.vividsolutions.jts.io.ParseException {

    XMLConfiguration config = shared.getConfig();

    TileLayer tileLayer = config.getTileLayer(layerTemplate);
    GridSubset gridSubset = tileLayer.getGridSubset(gridSubsetName);

    MapLayerJSONParser layerJsonParser = new MapLayerJSONParser(props);

    MaplinkGeoJsonParser parser = new MaplinkGeoJsonParser();
    parser.setDebug(true);

    InputStream inp = MapProducer.class.getResourceAsStream("action_route_parcel.json");

    try {

      assertTrue(MapLinkGeoJsonParseContext.Default.getPm().buildMap);

      Map<String, ?> root = parser.parse(inp);

      assertTrue(root.size() != 0);
      assertTrue(root.get("layers") != null);
      assertTrue(root.get("maplink") != null);
      assertTrue(root.get("state") != null);

      assertTrue(root.get("layers") != null);
      assertTrue(((List<Map<String, Object>>) root.get("layers")).size() == 11);
      assertTrue(
          "geojson".equals(((List<Map<String, Object>>) root.get("layers")).get(10).get("type")));
      assertTrue(
          ((List<Map<String, Object>>) root.get("layers")).get(10).get(".data")
              instanceof FeatureCollection);
      FeatureCollection fc10 =
          (FeatureCollection) ((List<Map<String, Object>>) root.get("layers")).get(10).get(".data");
      FeatureIterator fi = fc10.features();

      assertTrue(fi.hasNext());

      Feature f = fc10.features().next();
      assertTrue(f != null);
      assertTrue(f.getProperty("prop0") != null);
      assertTrue(f.getProperty("prop0").getValue() != null);
      Object pv = f.getProperty("prop0").getValue();
      assertTrue(pv instanceof String);
      assertTrue("value0forPoints".equals(pv));
      assertTrue(f.getDefaultGeometryProperty() != null);
      GeometryAttribute g = f.getDefaultGeometryProperty();
      assertTrue(g.getValue() != null);
      Object gv = g.getValue();
      assertTrue(gv instanceof Point);
      Point pt = (Point) gv;

      System.out.println(pt.toText());

      Style style = null;
      new FeatureLayer(fc10, style);

      MapLink mapLink =
          layerJsonParser.parseMapLinkJSON(root, shared.getGf(), gridSubset.getResolutions());

      /* assertions */
      assertTrue(mapLink != null);
      assertTrue(mapLink.getScale() != null);

      assertTrue(mapLink.getCentre() != null);
      assertTrue(Double.valueOf(530163).equals(mapLink.getCentre().getX()));
      assertTrue(Double.valueOf(6754057).equals(mapLink.getCentre().getY()));

      assertTrue(Integer.valueOf(11).equals(mapLink.getZoom()));

      assertTrue(mapLink.getMapLinkLayers() != null);
      assertTrue(mapLink.getMapLinkLayers().size() == 4);

      assertTrue("base_35".equals(mapLink.getMapLinkLayers().get(0).getLayerid()));

      assertTrue(mapLink.getMapLinkLayers().get(0).getGeom() == null);

    } finally {
      inp.close();
    }
  }
예제 #25
0
  private void capabilityLayerInner(StringBuilder str, TileLayer layer)
      throws GeoWebCacheException {
    if (layer.isQueryable()) {
      str.append("    <Layer queryable=\"1\">\n");
    } else {
      str.append("    <Layer>\n");
    }

    str.append("      <Name>" + layer.getName() + "</Name>\n");

    if (layer.getMetaInformation() != null) {
      LayerMetaInformation metaInfo = layer.getMetaInformation();
      str.append("      <Title>" + metaInfo.getTitle() + "</Title>\n");
      str.append("      <Abstract>" + metaInfo.getDescription() + "</Abstract>\n");
    } else {
      str.append("      <Title>" + layer.getName() + "</Title>\n");
    }

    TreeSet<SRS> srsSet = new TreeSet<SRS>();
    StringBuilder boundingBoxStr = new StringBuilder();
    for (String gridSetId : layer.getGridSubsets()) {
      GridSubset curGridSubSet = layer.getGridSubset(gridSetId);
      SRS curSRS = curGridSubSet.getSRS();
      if (!srsSet.contains(curSRS)) {
        str.append("      <SRS>" + curSRS.toString() + "</SRS>\n");

        // Save bounding boxes for later
        String[] bs = boundsPrep(curGridSubSet.getCoverageBestFitBounds());
        boundingBoxStr.append(
            "      <BoundingBox SRS=\""
                + curGridSubSet.getSRS().toString()
                + "\" minx=\""
                + bs[0]
                + "\" miny=\""
                + bs[1]
                + "\" maxx=\""
                + bs[2]
                + "\" maxy=\""
                + bs[3]
                + "\"/>\n");

        srsSet.add(curSRS);
      }
    }

    GridSubset epsg4326GridSubSet = layer.getGridSubsetForSRS(SRS.getEPSG4326());
    if (null != epsg4326GridSubSet) {
      String[] bs = boundsPrep(epsg4326GridSubSet.getCoverageBestFitBounds());
      str.append(
          "      <LatLonBoundingBox minx=\""
              + bs[0]
              + "\" miny=\""
              + bs[1]
              + "\" maxx=\""
              + bs[2]
              + "\" maxy=\""
              + bs[3]
              + "\"/>\n");
    }

    // Bounding boxes gathered earlier
    str.append(boundingBoxStr);

    // WMS 1.1 Dimensions
    if (layer.getParameterFilters() != null) {
      StringBuilder dims = new StringBuilder();
      StringBuilder extents = new StringBuilder();
      for (ParameterFilter parameterFilter : layer.getParameterFilters()) {
        if (parameterFilter instanceof WMSDimensionProvider) {
          ((WMSDimensionProvider) parameterFilter).appendDimensionElement(dims, "      ");
          ((WMSDimensionProvider) parameterFilter).appendExtentElement(extents, "      ");
        }
      }

      if (dims.length() > 0 && extents.length() > 0) {
        str.append(dims);
        str.append(extents);
      }
    }

    // TODO style?
    str.append("    </Layer>\n");
  }
예제 #26
0
  GridSubset findBestGridSubset(WMSMapContent map) {
    GetMapRequest req = map.getRequest();
    Map formatOpts = req.getFormatOptions();

    GridSetBroker gridSetBroker = gwc.getGridSetBroker();
    GridSet gridSet = null;

    // first check format options to see if explicitly specified
    if (formatOpts.containsKey("gridset")) {
      gridSet = gridSetBroker.get(formatOpts.get("gridset").toString());
    }

    // next check srs
    if (gridSet == null) {
      gridSet = gridSetBroker.get(req.getSRS().toUpperCase());
    }

    if (gridSet != null) {
      return GridSubsetFactory.createGridSubSet(gridSet);
    }

    CoordinateReferenceSystem crs = map.getCoordinateReferenceSystem();

    // look up epsg code
    Integer epsgCode = null;
    try {
      epsgCode = CRS.lookupEpsgCode(crs, false);
    } catch (Exception e) {
      throw new ServiceException("Unable to determine epsg code for " + crs, e);
    }
    if (epsgCode == null) {
      throw new ServiceException("Unable to determine epsg code for " + crs);
    }

    SRS srs = SRS.getSRS(epsgCode);

    // figure out the appropriate grid sub set
    Set<GridSubset> gridSubsets = new LinkedHashSet<GridSubset>();
    for (MapLayerInfo l : req.getLayers()) {
      TileLayer tl = gwc.getTileLayerByName(l.getName());
      if (tl == null) {
        throw new ServiceException("No tile layer for " + l.getName());
      }

      List<GridSubset> theseGridSubsets = tl.getGridSubsetsForSRS(srs);
      if (gridSubsets.isEmpty()) {
        gridSubsets.addAll(theseGridSubsets);
      } else {
        gridSubsets.retainAll(theseGridSubsets);
      }

      if (gridSubsets.isEmpty()) {
        throw new ServiceException(
            "No suitable " + epsgCode + " grid subset for " + req.getLayers());
      }
    }

    if (gridSubsets.size() > 1) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        StringBuilder msg = new StringBuilder("Found multiple grid subsets: ");
        for (GridSubset gs : gridSubsets) {
          msg.append(gs.getName()).append(", ");
        }
        msg.setLength(msg.length() - 2);
        msg.append(". Choosing first.");
        LOGGER.warning(msg.toString());
      }
    }

    return gridSubsets.iterator().next();
  }