Пример #1
0
  public void testImportKMLIndirect() throws Exception {
    File dir = unpack("kml/sample.zip");
    String wsName = getCatalog().getDefaultWorkspace().getName();
    DataStoreInfo h2DataStore = createH2DataStore(wsName, "kmltest");
    SpatialFile importData = new SpatialFile(new File(dir, "sample.kml"));
    ImportContext context = importer.createContext(importData, h2DataStore);
    assertEquals(1, context.getTasks().size());
    ImportTask task = context.getTasks().get(0);

    LayerInfo layer = task.getLayer();
    ResourceInfo resource = layer.getResource();
    assertEquals("Invalid srs", "EPSG:4326", resource.getSRS());
    ReferencedEnvelope emptyBounds = new ReferencedEnvelope();
    emptyBounds.setToNull();
    assertTrue("Unexpected bounding box", emptyBounds.equals(resource.getNativeBoundingBox()));
    // transform chain to limit characters
    // otherwise we get a sql exception thrown
    TransformChain transformChain = task.getTransform();
    transformChain.add(new DescriptionLimitingTransform());
    importer.run(context);
    Exception error = task.getError();
    if (error != null) {
      error.printStackTrace();
      fail(error.getMessage());
    }
    assertFalse("Bounding box not updated", emptyBounds.equals(resource.getNativeBoundingBox()));
    FeatureTypeInfo fti = (FeatureTypeInfo) resource;
    assertEquals("Invalid type name", "sample", fti.getName());
    FeatureSource<? extends FeatureType, ? extends Feature> featureSource =
        fti.getFeatureSource(null, null);
    assertEquals("Unexpected feature count", 20, featureSource.getCount(Query.ALL));
  }
  public void testLayer() throws Exception {

    String layerId = getLayerId(MockData.PRIMITIVEGEOFEATURE);
    LayerInfo layer = getCatalog().getLayerByName(layerId);
    addAuthUrl("layerAuth1", "http://geoserver/wms/auth1", layer.getAuthorityURLs());
    addIdentifier("layerAuth1", "layerId1", layer.getIdentifiers());
    getCatalog().save(layer);

    Document doc =
        getAsDOM(
            "sf/PrimitiveGeoFeature/wms?service=WMS&request=getCapabilities&version=1.3.0", true);

    String layerName = MockData.PRIMITIVEGEOFEATURE.getLocalPart();
    assertXpathExists(
        "//wms:Layer[wms:Name='" + layerName + "']/wms:AuthorityURL[@name = 'layerAuth1']", doc);
    assertXpathEvaluatesTo(
        "http://geoserver/wms/auth1",
        "//wms:Layer[wms:Name='"
            + layerName
            + "']/wms:AuthorityURL[@name = 'layerAuth1']/wms:OnlineResource/@xlink:href",
        doc);

    assertXpathExists(
        "//wms:Layer[wms:Name='" + layerName + "']/wms:Identifier[@authority = 'layerAuth1']", doc);
    assertXpathEvaluatesTo(
        "layerId1",
        "//wms:Layer[wms:Name='" + layerName + "']/wms:Identifier[@authority = 'layerAuth1']",
        doc);
  }
Пример #3
0
  public void testImportCSV() throws Exception {
    File dir = unpack("csv/locations.zip");
    ImportContext context = importer.createContext(new SpatialFile(new File(dir, "locations.csv")));
    assertEquals(1, context.getTasks().size());

    ImportTask task = context.getTasks().get(0);
    assertEquals(ImportTask.State.NO_CRS, task.getState());

    LayerInfo layer = task.getLayer();
    ResourceInfo resource = layer.getResource();
    resource.setSRS("EPSG:4326");

    assertTrue("Item not ready", importer.prep(task));
    assertEquals(ImportTask.State.READY, task.getState());

    context.updated();
    assertEquals(ImportContext.State.PENDING, context.getState());
    importer.run(context);
    assertEquals(ImportContext.State.COMPLETE, context.getState());
    FeatureTypeInfo fti = (FeatureTypeInfo) resource;
    SimpleFeatureType featureType = (SimpleFeatureType) fti.getFeatureType();
    GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor();
    assertNull("Expecting no geometry", geometryDescriptor);
    assertEquals(4, featureType.getAttributeCount());
  }
  void setupExtras(org.geoserver.data.test.SystemTestData testData, Catalog catalog)
      throws IOException {
    // associate Lakes to Buildings as an extra style
    LayerInfo buildings = catalog.getLayerByName(getLayerId(BUILDINGS));
    buildings.getStyles().add(catalog.getStyleByName(LAKES.getLocalPart()));
    catalog.save(buildings);

    // add a layer group
    CatalogFactory factory = catalog.getFactory();
    LayerGroupInfo globalGroup = factory.createLayerGroup();
    globalGroup.setName(LAKES_GROUP);
    globalGroup.getLayers().add(catalog.getLayerByName(getLayerId(LAKES)));
    globalGroup.getLayers().add(catalog.getLayerByName(getLayerId(FORESTS)));
    globalGroup.getLayers().add(catalog.getLayerByName(getLayerId(BRIDGES)));
    catalog.add(globalGroup);

    // add a layer group containing a layer group
    LayerGroupInfo nestGroup = factory.createLayerGroup();
    nestGroup.setName(NEST_GROUP);
    nestGroup.getLayers().add(catalog.getLayerByName(getLayerId(LAKES)));
    nestGroup.getLayers().add(globalGroup);
    catalog.add(nestGroup);

    // add a workspace specific style
    WorkspaceInfo ws = catalog.getWorkspaceByName(CITE_PREFIX);
    testData.addStyle(ws, WS_STYLE, "Streams.sld", SystemTestData.class, catalog);
  };
Пример #5
0
  public MockCatalogBuilder layerGroup(
      String name, List<String> layerNames, List<String> styleNames) {

    final LayerGroupInfo lg = createMock(LayerGroupInfo.class);
    layerGroups.add(lg);

    expect(lg.getId()).andReturn(newId()).anyTimes();
    expect(lg.getName()).andReturn(name).anyTimes();

    List<PublishedInfo> grpLayers = new ArrayList<PublishedInfo>();
    List<StyleInfo> grpStyles = new ArrayList<StyleInfo>();
    for (int i = 0; i < layerNames.size(); i++) {
      String layerName = layerNames.get(i);
      LayerInfo l = null;
      for (LayerInfo layer : layers) {
        if (layerName.equals(layer.getName())) {
          l = layer;
          break;
        }
      }

      if (l == null) {
        throw new RuntimeException("No such layer: " + layerName);
      }

      grpLayers.add(l);

      StyleInfo s = null;
      if (styleNames != null) {
        String styleName = styleNames.get(i);
        for (StyleInfo style : styles) {
          if (styleName.equals(style.getName())) {
            s = style;
            break;
          }
        }
      }

      grpStyles.add(s);
    }
    expect(lg.getLayers()).andReturn(grpLayers).anyTimes();
    expect(lg.getStyles()).andReturn(grpStyles).anyTimes();

    lg.accept((CatalogVisitor) anyObject());
    expectLastCall()
        .andAnswer(
            new VisitAnswer() {
              @Override
              protected void doVisit(CatalogVisitor visitor) {
                visitor.visit(lg);
              }
            })
        .anyTimes();

    expect(catalog.getLayerGroupByName(name)).andReturn(lg).anyTimes();

    callback.onLayerGroup(name, lg, this);
    replay(lg);
    return this;
  }
  @Before
  public void setUp() throws URISyntaxException, IOException {
    outputFormat = new HTMLFeatureInfoOutputFormat(getWMS());

    currentTemplate = "test_content.ftl";
    // configure template loader
    GeoServerTemplateLoader templateLoader =
        new GeoServerTemplateLoader(this.getClass(), getDataDirectory()) {

          @Override
          public Object findTemplateSource(String path) throws IOException {
            String templatePath;
            if (path.toLowerCase().contains("content")) {
              templatePath = currentTemplate;

            } else {
              templatePath = "empty.ftl";
            }
            try {
              return new File(this.getClass().getResource(templateFolder + templatePath).toURI());
            } catch (URISyntaxException e) {
              return null;
            }
          }
        };
    outputFormat.templateLoader = templateLoader;

    // test request with some parameters to use in templates
    Request request = new Request();
    parameters = new HashMap<String, Object>();
    parameters.put("LAYER", "testLayer");
    Map<String, String> env = new HashMap<String, String>();
    env.put("TEST1", "VALUE1");
    env.put("TEST2", "VALUE2");
    parameters.put("ENV", env);
    request.setKvp(parameters);

    Dispatcher.REQUEST.set(request);

    final FeatureTypeInfo featureType = getFeatureTypeInfo(MockData.PRIMITIVEGEOFEATURE);

    fcType = WfsFactory.eINSTANCE.createFeatureCollectionType();
    fcType.getFeature().add(featureType.getFeatureSource(null, null).getFeatures());

    // fake layer list
    List<MapLayerInfo> queryLayers = new ArrayList<MapLayerInfo>();
    LayerInfo layerInfo = new LayerInfoImpl();
    layerInfo.setType(PublishedType.VECTOR);
    ResourceInfo resourceInfo = new FeatureTypeInfoImpl(null);
    NamespaceInfo nameSpace = new NamespaceInfoImpl();
    nameSpace.setPrefix("topp");
    nameSpace.setURI("http://www.topp.org");
    resourceInfo.setNamespace(nameSpace);
    layerInfo.setResource(resourceInfo);
    MapLayerInfo mapLayerInfo = new MapLayerInfo(layerInfo);
    queryLayers.add(mapLayerInfo);
    getFeatureInfoRequest = new GetFeatureInfoRequest();
    getFeatureInfoRequest.setQueryLayers(queryLayers);
  }
Пример #7
0
 void addLayer() {
   LayerInfo l = catalog.getLayerByName(new NameImpl("sf", "states"));
   if (l == null) {
     l = catalog.getFactory().createLayer();
     l.setResource(catalog.getResourceByName("sf", "states", WMSLayerInfo.class));
     catalog.add(l);
   }
 }
Пример #8
0
 private void mockCatalog() {
   when(catalog.getLayers()).thenReturn(Arrays.asList(layer));
   when(catalog.getLayerGroups()).thenReturn(Arrays.asList(layerGroup));
   when(catalog.getLayer(eq(layer.getId()))).thenReturn(layer);
   when(catalog.getLayerGroup(layerGroup.getId())).thenReturn(layerGroup);
   when(catalog.getLayerByName(eq(layer.getResource().prefixedName()))).thenReturn(layer);
   when(catalog.getLayerGroupByName(tileLayerName(layerGroup))).thenReturn(layerGroup);
 }
Пример #9
0
 private JSONObj layer(JSONObj json, LayerInfo info, boolean details) {
   if (details) {
     IO.layer(json, info, null);
     // Todo add URL
   } else {
     json.put("name", info.getName())
         .put("workspace", info.getResource().getStore().getWorkspace().getName());
   }
   return json;
 }
Пример #10
0
  LayerInfo createLayer(ResourceInfo r, String name, NamespaceInfo ns) {
    String lId = newId();
    StyleInfo s = styles.peekLast();

    final LayerInfo l = createNiceMock(LayerInfo.class);
    layers.add(l);

    expect(l.getId()).andReturn(lId).anyTimes();
    expect(l.getName()).andReturn(name).anyTimes();
    expect(l.getType()).andReturn(LayerInfo.Type.VECTOR).anyTimes();
    expect(l.getResource()).andReturn(r).anyTimes();
    expect(l.getDefaultStyle()).andReturn(s).anyTimes();
    expect(l.isEnabled()).andReturn(true).anyTimes();
    expect(l.isAdvertised()).andReturn(true).anyTimes();

    expect(catalog.getLayer(lId)).andReturn(l).anyTimes();
    expect(catalog.getLayerByName(name)).andReturn(l).anyTimes();
    expect(catalog.getLayerByName(ns.getPrefix() + ":" + name)).andReturn(l).anyTimes();
    expect(catalog.getLayerByName(new NameImpl(ns.getPrefix(), name))).andReturn(l).anyTimes();
    expect(catalog.getLayerByName(new NameImpl(ns.getURI(), name))).andReturn(l).anyTimes();
    expect(catalog.getLayers(r)).andReturn(Arrays.asList(l)).anyTimes();
    l.accept((CatalogVisitor) anyObject());
    expectLastCall()
        .andAnswer(
            new VisitAnswer() {
              @Override
              protected void doVisit(CatalogVisitor visitor) {
                visitor.visit(l);
              }
            })
        .anyTimes();

    callback.onLayer(name, l, this);
    return l;
  }
  /**
   * Builds a raster filter for the specified resource, i.e. a MultiPolygon delimiting the area the
   * user <strong>can</strong> access.
   *
   * <p>If no mask layer was specified in the options, {@code null} is returned and access will not
   * be restricted.
   *
   * <p>If the specified CQL filter matches no geometries or an error occurs, an empty MultiPolygon
   * is returned and access is denied on the entire extent.
   *
   * @param user the user
   * @param resource the restricted resource
   * @return the geometry of the accessible area
   */
  MultiPolygon buildRasterFilter(Authentication user, ResourceInfo resource) {
    Name maskLayerName = getMaskLayerName(options);
    if (maskLayerName == null) {
      // returning null is equivalent to an allow-all filter
      return null;
    }

    List<String> permissions = null;
    try {
      permissions = getPermissions(user);
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Could not retrieve user permissions: denying access to all", e);
      return DENY_ALL_RASTER_FILTER;
    }

    String maksFilterTemplate = getMaskFilterTemplate(options);
    Filter maskFilter = null;
    try {
      maskFilter = buildCqlFilter(maksFilterTemplate, permissions);
    } catch (CQLException e) {
      LOGGER.log(
          Level.SEVERE,
          "Could not build CQL filter using template "
              + maksFilterTemplate
              + " and permissions "
              + permissions
              + ": denying access to all");
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Error parsing CQL filter", e);
      }
      maskFilter = Filter.EXCLUDE;
    }

    MultiPolygon roiArea = null;
    try {
      roiArea = rasterFilterBuilder.buildRasterFilter(user, resource, maskLayerName, maskFilter);
      if (roiArea == null) {
        roiArea = DENY_ALL_RASTER_FILTER;
      } else {
        // reproject area if necessary
        LayerInfo mask = resource.getCatalog().getLayerByName(maskLayerName);
        roiArea = reprojectRoiArea(mask.getResource().getCRS(), resource.getCRS(), roiArea);
      }
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Could not retrieve ROI area: denying access to all", e);
      return DENY_ALL_RASTER_FILTER;
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(
          Level.FINE, "Raster filter for user {0}: {1}", new Object[] {user.getName(), roiArea});
    }

    return roiArea;
  }
Пример #12
0
  @Test
  public void testModifyLayer() throws Exception {
    testAddLayer();

    LayerInfo l = dao.getLayerByName("anvil");
    l.setPath("changed");
    dao.save(l);

    l = dao.getLayerByName("anvil");
    assertEquals("changed", l.getPath());
  }
Пример #13
0
  public MapLayerInfo(LayerInfo layerInfo) {
    this.layerInfo = layerInfo;
    this.remoteFeatureSource = null;
    ResourceInfo resource = layerInfo.getResource();

    // handle InlineFeatureStuff
    this.name = resource.getPrefixedName();
    this.label = resource.getTitle();
    this.description = resource.getAbstract();

    this.type = layerInfo.getType().getCode();
  }
Пример #14
0
  public void testImportCSVIndirect() throws Exception {
    File dir = unpack("csv/locations.zip");
    String wsName = getCatalog().getDefaultWorkspace().getName();

    DataStoreInfo h2DataStore = createH2DataStore(wsName, "csvindirecttest");
    SpatialFile importData = new SpatialFile(new File(dir, "locations.csv"));

    ImportContext context = importer.createContext(importData, h2DataStore);
    assertEquals(1, context.getTasks().size());
    ImportTask task = context.getTasks().get(0);

    TransformChain transformChain = task.getTransform();
    transformChain.add(new AttributesToPointGeometryTransform("LAT", "LON"));
    assertEquals(ImportTask.State.NO_CRS, task.getState());

    LayerInfo layer = task.getLayer();
    ResourceInfo resource = layer.getResource();
    resource.setSRS("EPSG:4326");

    assertTrue("Item not ready", importer.prep(task));
    assertEquals(ImportTask.State.READY, task.getState());

    context.updated();
    assertEquals(ImportContext.State.PENDING, context.getState());
    importer.run(context);

    assertEquals(ImportContext.State.COMPLETE, context.getState());
    FeatureTypeInfo fti = (FeatureTypeInfo) resource;
    SimpleFeatureType featureType = (SimpleFeatureType) fti.getFeatureType();
    GeometryDescriptor geometryDescriptor = featureType.getGeometryDescriptor();
    assertNotNull("Expecting geometry", geometryDescriptor);
    assertEquals("Invalid geometry name", "location", geometryDescriptor.getLocalName());
    assertEquals(3, featureType.getAttributeCount());
    FeatureSource<? extends FeatureType, ? extends Feature> featureSource =
        fti.getFeatureSource(null, null);
    FeatureCollection<? extends FeatureType, ? extends Feature> features =
        featureSource.getFeatures();
    assertEquals(9, features.size());
    FeatureIterator<? extends Feature> featureIterator = features.features();
    assertTrue("Expected features", featureIterator.hasNext());
    SimpleFeature feature = (SimpleFeature) featureIterator.next();
    assertNotNull(feature);
    assertEquals("Invalid city attribute", "Trento", feature.getAttribute("CITY"));
    assertEquals("Invalid number attribute", 140, feature.getAttribute("NUMBER"));
    Object geomAttribute = feature.getAttribute("location");
    assertNotNull("Expected geometry", geomAttribute);
    Point point = (Point) geomAttribute;
    Coordinate coordinate = point.getCoordinate();
    assertEquals("Invalid x coordinate", 11.12, coordinate.x, 0.1);
    assertEquals("Invalid y coordinate", 46.07, coordinate.y, 0.1);
    featureIterator.close();
  }
Пример #15
0
  private static boolean hasGeometry(LayerInfo lyr) {
    if (lyr.getResource() instanceof CoverageInfo) return true;

    if (lyr.getResource() instanceof FeatureTypeInfo) {
      for (AttributeTypeInfo att : ((FeatureTypeInfo) lyr.getResource()).getAttributes()) {
        if (Geometry.class.isAssignableFrom(att.getBinding())) {
          return true;
        }
      }
    }

    return false;
  }
  void addLayerAndStyle(SystemTestData testData, QName name) throws IOException {
    testData.addVectorLayer(
        name, null, name.getLocalPart() + ".properties", getClass(), this.catalog);

    final String styleName = name.getLocalPart();
    testData.addStyle(styleName, getClass(), this.catalog);

    StyleInfo defaultStyle = this.catalog.getStyleByName(styleName);

    String layerId = getLayerId(name);
    LayerInfo layerInfo = this.catalog.getLayerByName(layerId);
    layerInfo.setDefaultStyle(defaultStyle);
    this.catalog.save(layerInfo);
  }
    /**
     * Handles the encoding of the layers elements.
     *
     * <p>This method does a search over the SRS of all the layers to see if there are at least a
     * common one, as needed by the spec: "<i>The root Layer element shall include a sequence of
     * zero or more &lt;SRS&gt; elements listing all SRSes that are common to all subsidiary layers.
     * Use a single SRS element with empty content (like so: "&lt;SRS&gt;&lt;/SRS&gt;") if there is
     * no common SRS."</i>
     *
     * <p>By the other hand, this search is also used to collecto the whole latlon bbox, as stated
     * by the spec: <i>"The bounding box metadata in Capabilities XML specify the minimum enclosing
     * rectangle for the layer as a whole."</i>
     *
     * @task TODO: manage this differently when we have the layer list of the WMS service decoupled
     *     from the feature types configured for the server instance. (This involves nested layers,
     *     gridcoverages, etc)
     */
    private void handleLayers() {
      start("Layer");

      final List<LayerInfo> layers;

      // filter the layers if a namespace filter has been set
      if (request.getNamespace() != null) {
        final List<LayerInfo> allLayers = wmsConfig.getLayers();
        layers = new ArrayList<LayerInfo>();

        String namespace = wmsConfig.getNamespaceByPrefix(request.getNamespace());
        for (LayerInfo layer : allLayers) {
          Name name = layer.getResource().getQualifiedName();
          if (name.getNamespaceURI().equals(namespace)) {
            layers.add(layer);
          }
        }
      } else {
        layers = wmsConfig.getLayers();
      }

      WMSInfo serviceInfo = wmsConfig.getServiceInfo();
      element("Title", serviceInfo.getTitle());
      element("Abstract", serviceInfo.getAbstract());

      List<String> srsList = serviceInfo.getSRS();
      Set<String> srs = new HashSet<String>();
      if (srsList != null) {
        srs.addAll(srsList);
      }
      handleRootCrsList(srs);

      handleRootBbox(layers);

      // now encode each layer individually
      LayerTree featuresLayerTree = new LayerTree(layers);
      handleLayerTree(featuresLayerTree);

      try {
        List<LayerGroupInfo> layerGroups = wmsConfig.getLayerGroups();
        handleLayerGroups(new ArrayList<LayerGroupInfo>(layerGroups));
      } catch (FactoryException e) {
        throw new RuntimeException("Can't obtain Envelope of Layer-Groups: " + e.getMessage(), e);
      } catch (TransformException e) {
        throw new RuntimeException("Can't obtain Envelope of Layer-Groups: " + e.getMessage(), e);
      }

      end("Layer");
    }
  MapLayerInfo createMapLayer(String name, String ns) {
    ResourceInfo r = createMock(ResourceInfo.class);
    expect(r.getName()).andReturn(name);
    expect(r.getPrefixedName()).andReturn(ns + ":" + name);
    expect(r.getTitle()).andReturn(name);
    expect(r.getAbstract()).andReturn(name);
    replay(r);

    LayerInfo l = createMock(LayerInfo.class);
    expect(l.getResource()).andReturn(r);
    expect(l.getType()).andReturn(LayerInfo.Type.VECTOR);
    replay(l);

    return new MapLayerInfo(l);
  }
Пример #19
0
 public Integer getCascadedHopCount(LayerInfo layer) {
   if (!(layer.getResource() instanceof WMSLayerInfo)) {
     return null;
   }
   WMSLayerInfo wmsLayerInfo = (WMSLayerInfo) layer.getResource();
   Layer wmsLayer;
   int cascaded = 1;
   try {
     wmsLayer = wmsLayerInfo.getWMSLayer(null);
     cascaded = 1 + wmsLayer.getCascaded();
   } catch (IOException e) {
     LOGGER.log(Level.INFO, "Unable to determina WMSLayer cascaded hop count", e);
   }
   return cascaded;
 }
Пример #20
0
 /**
  * This value is added the headers of generated maps, marking them as being both "cache-able" and
  * designating the time for which they are to remain valid. The specific header added is
  * "Cache-Control: max-age="
  *
  * @return the number of seconds to be added to the "Cache-Control: max-age=" header, or {@code 0}
  *     if not set
  */
 public int getCacheMaxAge() {
   if (layerInfo == null) {
     return 0;
   }
   ResourceInfo resource = layerInfo.getResource();
   Integer val = resource.getMetadata().get(ResourceInfo.CACHE_AGE_MAX, Integer.class);
   return val == null ? 0 : val;
 }
Пример #21
0
 /**
  * Returns the appropriate icon for the specified layer. This one distinguishes the geometry type
  * inside vector layers.
  *
  * @param info
  * @return
  */
 public ResourceReference getSpecificLayerIcon(LayerInfo info) {
   if (info.getType() == Type.RASTER) {
     return RASTER_ICON;
   } else if (info.getType() == Type.VECTOR) {
     try {
       FeatureTypeInfo fti = (FeatureTypeInfo) info.getResource();
       GeometryDescriptor gd = fti.getFeatureType().getGeometryDescriptor();
       return getVectoryIcon(gd);
     } catch (Exception e) {
       return GEOMETRY_ICON;
     }
   } else if (info.getType() == Type.WMS) {
     return MAP_ICON;
   } else {
     return UNKNOWN_ICON;
   }
 }
Пример #22
0
  public GridCoverageReader getCoverageReader() throws IOException {
    if (type != TYPE_RASTER) {
      throw new IllegalArgumentException("Layer type is not raster");
    }

    CoverageInfo resource = (CoverageInfo) layerInfo.getResource();
    return resource.getGridCoverageReader(null, GeoTools.getDefaultHints());
  }
Пример #23
0
  /**
   * This method is called only the first time the {@link GWCConfig} is initialized and is used to
   * maintain backwards compatibility with the old GWC defaults.
   */
  private void createDefaultTileLayerInfos(final GWCConfig defaultSettings) {
    checkArgument(defaultSettings.isSane());
    for (LayerInfo layer : rawCatalog.getLayers()) {
      if (!CatalogConfiguration.isLayerExposable(layer)) {
        continue;
      }
      try {
        GeoServerTileLayerInfo tileLayerInfo;
        tileLayerInfo = TileLayerInfoUtil.loadOrCreate(layer, defaultSettings);
        tileLayerCatalog.save(tileLayerInfo);
        MetadataMap metadata = layer.getMetadata();
        if (metadata.containsKey(LegacyTileLayerInfoLoader.CONFIG_KEY_ENABLED)) {
          LegacyTileLayerInfoLoader.clear(metadata);
          rawCatalog.save(layer);
        }
      } catch (RuntimeException e) {
        LOGGER.log(
            Level.WARNING,
            "Error occurred saving default GWC Tile Layer settings for Layer '"
                + layer.getName()
                + "'",
            e);
      }
    }

    for (LayerGroupInfo layer : rawCatalog.getLayerGroups()) {
      try {
        GeoServerTileLayerInfo tileLayerInfo;
        tileLayerInfo = TileLayerInfoUtil.loadOrCreate(layer, defaultSettings);
        tileLayerCatalog.save(tileLayerInfo);

        MetadataMap metadata = layer.getMetadata();
        if (metadata.containsKey(LegacyTileLayerInfoLoader.CONFIG_KEY_ENABLED)) {
          LegacyTileLayerInfoLoader.clear(metadata);
          rawCatalog.save(layer);
        }
      } catch (RuntimeException e) {
        LOGGER.log(
            Level.WARNING,
            "Error occurred saving default GWC Tile Layer settings for LayerGroup '"
                + tileLayerName(layer)
                + "'",
            e);
      }
    }
  }
Пример #24
0
  @Test
  public void testAddLayer() throws Exception {
    testAddFeatureType();
    testAddStyle();

    NamespaceInfo ns = dao.getNamespaceByPrefix("acme");
    FeatureTypeInfo ft = dao.getResourceByName(ns, "anvil", FeatureTypeInfo.class);
    StyleInfo s = dao.getStyleByName("blue");

    LayerInfo l = dao.getCatalog().getFactory().createLayer();
    l.setPath("/anvil");
    l.setResource(ft);
    l.setDefaultStyle(s);

    dao.add(l);

    assertEquals(l, dao.getLayerByName("anvil"));
  }
Пример #25
0
  /**
   * Get the bounding box in latitude and longitude for this layer.
   *
   * @return Envelope the feature source bounds.
   * @throws IOException when an error occurs
   */
  public ReferencedEnvelope getLatLongBoundingBox() throws IOException {
    if (layerInfo != null) {
      ResourceInfo resource = layerInfo.getResource();
      return resource.getLatLonBoundingBox();
    }

    throw new UnsupportedOperationException(
        "getLatLongBoundingBox not " + "implemented for remote sources");
  }
Пример #26
0
  @Test
  public void testNonAdvertisedLayer() throws Exception {
    String layerId = getLayerId(MockData.TASMANIA_DEM);
    LayerInfo layer = getCatalog().getLayerByName(layerId);
    try {
      // now you see me
      Document dom = getAsDOM("wcs?request=GetCapabilities");
      assertXpathExists("//wcs:CoverageSummary[ows:Title='DEM']", dom);

      // now you don't!
      layer.setAdvertised(false);
      getCatalog().save(layer);
      dom = getAsDOM("wcs?request=GetCapabilities");
      assertXpathNotExists("//wcs:CoverageSummary[ows:Title='DEM']", dom);
    } finally {
      layer.setAdvertised(true);
      getCatalog().save(layer);
    }
  }
Пример #27
0
 public CoordinateReferenceSystem getCoordinateReferenceSystem() {
   if (layerInfo != null) {
     return layerInfo.getResource().getCRS();
   }
   if (remoteFeatureSource != null) {
     SimpleFeatureType schema = remoteFeatureSource.getSchema();
     return schema.getCoordinateReferenceSystem();
   }
   throw new IllegalStateException();
 }
Пример #28
0
  /**
   * Migrates the configuration of geoserver tile layers from the Layer/GroupInfo metadata maps to
   * the {@link #tileLayerCatalog}
   */
  private void moveTileLayerInfosToTileLayerCatalog() {

    for (LayerInfo layer : rawCatalog.getLayers()) {
      if (!CatalogConfiguration.isLayerExposable(layer)) {
        continue;
      }
      try {
        GeoServerTileLayerInfo tileLayerInfo;
        tileLayerInfo = LegacyTileLayerInfoLoader.load(layer);
        if (tileLayerInfo != null) {
          tileLayerCatalog.save(tileLayerInfo);
          MetadataMap metadata = layer.getMetadata();
          LegacyTileLayerInfoLoader.clear(metadata);
          rawCatalog.save(layer);
        }
      } catch (RuntimeException e) {
        LOGGER.log(
            Level.WARNING,
            "Error migrating GWC Tile Layer settings for Layer '" + layer.getName() + "'",
            e);
      }
    }

    for (LayerGroupInfo layer : rawCatalog.getLayerGroups()) {
      try {
        GeoServerTileLayerInfo tileLayerInfo;
        tileLayerInfo = LegacyTileLayerInfoLoader.load(layer);
        if (tileLayerInfo != null) {
          tileLayerCatalog.save(tileLayerInfo);
          MetadataMap metadata = layer.getMetadata();
          LegacyTileLayerInfoLoader.clear(metadata);
          rawCatalog.save(layer);
        }
      } catch (RuntimeException e) {
        LOGGER.log(
            Level.WARNING,
            "Error occurred saving default GWC Tile Layer settings for LayerGroup '"
                + tileLayerName(layer)
                + "'",
            e);
      }
    }
  }
    /**
     * Called by <code>handleLayers()</code>, iterates over the available featuretypes and coverages
     * to summarize their LatLonBBox'es and write the aggregated bounds for the root layer.
     *
     * @param ftypes the collection of FeatureTypeInfo and CoverageInfo objects to traverse
     */
    private void handleRootBbox(Collection<LayerInfo> layers) {

      Envelope latlonBbox = new Envelope();
      Envelope layerBbox = null;

      LOGGER.finer("Collecting summarized latlonbbox and common SRS...");

      for (LayerInfo layer : layers) {
        ResourceInfo resource = layer.getResource();
        layerBbox = resource.getLatLonBoundingBox();
        latlonBbox.expandToInclude(layerBbox);
      }

      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Summarized LatLonBBox is " + latlonBbox);
      }

      handleLatLonBBox(latlonBbox);
    }
Пример #30
0
  /**
   * Creates a cached tile layer from the given Layer
   *
   * @param info the layer to cache
   * @param defaults default configuration
   */
  public static GeoServerTileLayerInfoImpl loadOrCreate(
      final LayerInfo layerInfo, final GWCConfig defaults) {
    GeoServerTileLayerInfoImpl info = LegacyTileLayerInfoLoader.load(layerInfo);
    if (info == null) {
      info = create(defaults);
      final ResourceInfo resource = layerInfo.getResource();
      if (resource instanceof FeatureTypeInfo) {
        info.getMimeFormats().clear();
        info.getMimeFormats().addAll(defaults.getDefaultVectorCacheFormats());
      } else if (resource instanceof CoverageInfo) {
        info.getMimeFormats().clear();
        info.getMimeFormats().addAll(defaults.getDefaultCoverageCacheFormats());
      }

      checkAutomaticStyles(layerInfo, info);
    }
    info.setName(tileLayerName(layerInfo));
    info.setId(layerInfo.getId());
    return info;
  }