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;
  }
  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;
  }
 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;
 }
    /** @param layerTree */
    private void handleLayerTree(final LayerTree layerTree) {
      final List<LayerInfo> data = new ArrayList<LayerInfo>(layerTree.getData());
      final Collection<LayerTree> children = layerTree.getChildrens();

      Collections.sort(
          data,
          new Comparator<LayerInfo>() {
            public int compare(LayerInfo o1, LayerInfo o2) {
              return o1.getName().compareTo(o2.getName());
            }
          });

      for (LayerInfo layer : data) {
        // no sense in exposing a geometryless layer through wms...
        boolean wmsExposable = false;
        if (layer.getType() == Type.RASTER || layer.getType() == Type.WMS) {
          wmsExposable = true;
        } else {
          try {
            wmsExposable =
                layer.getType() == Type.VECTOR
                    && ((FeatureTypeInfo) layer.getResource())
                            .getFeatureType()
                            .getGeometryDescriptor()
                        != null;
          } catch (Exception e) {
            LOGGER.log(
                Level.SEVERE,
                "An error occurred trying to determine if" + " the layer is geometryless",
                e);
          }
        }

        // ask for enabled() instead of isEnabled() to account for disabled resource/store
        if (layer.enabled() && wmsExposable) {
          try {
            handleLayer(layer);
          } catch (Exception e) {
            // report what layer we failed on to help the admin locate and fix it
            throw new ServiceException(
                "Error occurred trying to write out metadata for layer: " + layer.getName(), e);
          }
        }
      }

      for (LayerTree childLayerTree : children) {
        start("Layer");
        element("Name", childLayerTree.getName());
        element("Title", childLayerTree.getName());
        handleLayerTree(childLayerTree);
        end("Layer");
      }
    }
Exemple #5
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);
      }
    }
  }
Exemple #6
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);
      }
    }
  }
  /** Reads the catalog from disk. */
  Catalog readCatalog(XStreamPersister xp) throws Exception {
    CatalogImpl catalog = new CatalogImpl();
    catalog.setResourceLoader(resourceLoader);
    xp.setCatalog(catalog);
    xp.setUnwrapNulls(false);

    CatalogFactory factory = catalog.getFactory();

    // global styles
    loadStyles(resourceLoader.find("styles"), catalog, xp);

    // workspaces, stores, and resources
    File workspaces = resourceLoader.find("workspaces");
    if (workspaces != null) {
      // do a first quick scan over all workspaces, setting the default
      File dws = new File(workspaces, "default.xml");
      WorkspaceInfo defaultWorkspace = null;
      if (dws.exists()) {
        try {
          defaultWorkspace = depersist(xp, dws, WorkspaceInfo.class);
          LOGGER.info("Loaded default workspace " + defaultWorkspace.getName());
        } catch (Exception e) {
          LOGGER.log(Level.WARNING, "Failed to load default workspace", e);
        }
      } else {
        LOGGER.warning("No default workspace was found.");
      }

      for (File wsd : list(workspaces, DirectoryFileFilter.INSTANCE)) {
        File f = new File(wsd, "workspace.xml");
        if (!f.exists()) {
          continue;
        }

        WorkspaceInfo ws = null;
        try {
          ws = depersist(xp, f, WorkspaceInfo.class);
          catalog.add(ws);
        } catch (Exception e) {
          LOGGER.log(Level.WARNING, "Failed to load workspace '" + wsd.getName() + "'", e);
          continue;
        }

        LOGGER.info("Loaded workspace '" + ws.getName() + "'");

        // load the namespace
        File nsf = new File(wsd, "namespace.xml");
        NamespaceInfo ns = null;
        if (nsf.exists()) {
          try {
            ns = depersist(xp, nsf, NamespaceInfo.class);
            catalog.add(ns);
          } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to load namespace for '" + wsd.getName() + "'", e);
          }
        }

        // set the default workspace, this value might be null in the case of coming from a
        // 2.0.0 data directory. See http://jira.codehaus.org/browse/GEOS-3440
        if (defaultWorkspace != null) {
          if (ws.getName().equals(defaultWorkspace.getName())) {
            catalog.setDefaultWorkspace(ws);
            if (ns != null) {
              catalog.setDefaultNamespace(ns);
            }
          }
        } else {
          // create the default.xml file
          defaultWorkspace = catalog.getDefaultWorkspace();
          if (defaultWorkspace != null) {
            try {
              persist(xp, defaultWorkspace, dws);
            } catch (Exception e) {
              LOGGER.log(
                  Level.WARNING, "Failed to persist default workspace '" + wsd.getName() + "'", e);
            }
          }
        }

        // load the styles for the workspace
        File styles = resourceLoader.find(wsd, "styles");
        if (styles != null) {
          loadStyles(styles, catalog, xp);
        }
      }

      for (File wsd : list(workspaces, DirectoryFileFilter.INSTANCE)) {

        // load the stores for this workspace
        for (File sd : list(wsd, DirectoryFileFilter.INSTANCE)) {
          File f = new File(sd, "datastore.xml");
          if (f.exists()) {
            // load as a datastore
            DataStoreInfo ds = null;
            try {
              ds = depersist(xp, f, DataStoreInfo.class);
              catalog.add(ds);

              LOGGER.info("Loaded data store '" + ds.getName() + "'");

              if (ds.isEnabled()) {
                // connect to the datastore to determine if we should disable it
                try {
                  ds.getDataStore(null);
                } catch (Throwable t) {
                  LOGGER.warning("Error connecting to '" + ds.getName() + "'. Disabling.");
                  LOGGER.log(Level.INFO, "", t);

                  ds.setError(t);
                  ds.setEnabled(false);
                }
              }
            } catch (Exception e) {
              LOGGER.log(Level.WARNING, "Failed to load data store '" + sd.getName() + "'", e);
              continue;
            }

            // load feature types
            for (File ftd : list(sd, DirectoryFileFilter.INSTANCE)) {
              f = new File(ftd, "featuretype.xml");
              if (f.exists()) {
                FeatureTypeInfo ft = null;
                try {
                  ft = depersist(xp, f, FeatureTypeInfo.class);
                } catch (Exception e) {
                  LOGGER.log(
                      Level.WARNING, "Failed to load feature type '" + ftd.getName() + "'", e);
                  continue;
                }

                catalog.add(ft);

                LOGGER.info("Loaded feature type '" + ds.getName() + "'");

                f = new File(ftd, "layer.xml");
                if (f.exists()) {
                  try {
                    LayerInfo l = depersist(xp, f, LayerInfo.class);
                    catalog.add(l);

                    LOGGER.info("Loaded layer '" + l.getName() + "'");
                  } catch (Exception e) {
                    LOGGER.log(
                        Level.WARNING,
                        "Failed to load layer for feature type '" + ft.getName() + "'",
                        e);
                  }
                }
              } else {
                LOGGER.warning("Ignoring feature type directory " + ftd.getAbsolutePath());
              }
            }
          } else {
            // look for a coverage store
            f = new File(sd, "coveragestore.xml");
            if (f.exists()) {
              CoverageStoreInfo cs = null;
              try {
                cs = depersist(xp, f, CoverageStoreInfo.class);
                catalog.add(cs);

                LOGGER.info("Loaded coverage store '" + cs.getName() + "'");
              } catch (Exception e) {
                LOGGER.log(
                    Level.WARNING, "Failed to load coverage store '" + sd.getName() + "'", e);
                continue;
              }

              // load coverages
              for (File cd : list(sd, DirectoryFileFilter.INSTANCE)) {
                f = new File(cd, "coverage.xml");
                if (f.exists()) {
                  CoverageInfo c = null;
                  try {
                    c = depersist(xp, f, CoverageInfo.class);
                    catalog.add(c);

                    LOGGER.info("Loaded coverage '" + cs.getName() + "'");
                  } catch (Exception e) {
                    LOGGER.log(Level.WARNING, "Failed to load coverage '" + cd.getName() + "'", e);
                    continue;
                  }

                  f = new File(cd, "layer.xml");
                  if (f.exists()) {
                    try {
                      LayerInfo l = depersist(xp, f, LayerInfo.class);
                      catalog.add(l);

                      LOGGER.info("Loaded layer '" + l.getName() + "'");
                    } catch (Exception e) {
                      LOGGER.log(
                          Level.WARNING, "Failed to load layer coverage '" + c.getName() + "'", e);
                    }
                  }
                } else {
                  LOGGER.warning("Ignoring coverage directory " + cd.getAbsolutePath());
                }
              }
            } else {
              f = new File(sd, "wmsstore.xml");
              if (f.exists()) {
                WMSStoreInfo wms = null;
                try {
                  wms = depersist(xp, f, WMSStoreInfo.class);
                  catalog.add(wms);

                  LOGGER.info("Loaded wmsstore '" + wms.getName() + "'");
                } catch (Exception e) {
                  LOGGER.log(Level.WARNING, "Failed to load wms store '" + sd.getName() + "'", e);
                  continue;
                }

                // load wms layers
                for (File cd : list(sd, DirectoryFileFilter.INSTANCE)) {
                  f = new File(cd, "wmslayer.xml");
                  if (f.exists()) {
                    WMSLayerInfo wl = null;
                    try {
                      wl = depersist(xp, f, WMSLayerInfo.class);
                      catalog.add(wl);

                      LOGGER.info("Loaded wms layer'" + wl.getName() + "'");
                    } catch (Exception e) {
                      LOGGER.log(
                          Level.WARNING, "Failed to load wms layer '" + cd.getName() + "'", e);
                      continue;
                    }

                    f = new File(cd, "layer.xml");
                    if (f.exists()) {
                      try {
                        LayerInfo l = depersist(xp, f, LayerInfo.class);
                        catalog.add(l);

                        LOGGER.info("Loaded layer '" + l.getName() + "'");
                      } catch (Exception e) {
                        LOGGER.log(
                            Level.WARNING,
                            "Failed to load cascaded wms layer '" + wl.getName() + "'",
                            e);
                      }
                    }
                  } else {
                    LOGGER.warning("Ignoring coverage directory " + cd.getAbsolutePath());
                  }
                }
              } else if (!isConfigDirectory(sd)) {
                LOGGER.warning("Ignoring store directory '" + sd.getName() + "'");
                continue;
              }
            }
          }
        }

        // load hte layer groups for this workspace
        File layergroups = resourceLoader.find(wsd, "layergroups");
        if (layergroups != null) {
          loadLayerGroups(layergroups, catalog, xp);
        }
      }
    } else {
      LOGGER.warning("No 'workspaces' directory found, unable to load any stores.");
    }

    // namespaces

    // layergroups
    File layergroups = resourceLoader.find("layergroups");
    if (layergroups != null) {
      loadLayerGroups(layergroups, catalog, xp);
    }
    xp.setUnwrapNulls(true);
    catalog.resolve();
    return catalog;
  }
    /**
     * Calls super.handleFeatureType to add common FeatureType content such as Name, Title and
     * LatLonBoundingBox, and then writes WMS specific layer properties as Styles, Scale Hint, etc.
     *
     * @throws IOException
     * @task TODO: write wms specific elements.
     */
    @SuppressWarnings("deprecation")
    protected void handleLayer(final LayerInfo layer) {
      // HACK: by now all our layers are queryable, since they reference
      // only featuretypes managed by this server
      AttributesImpl qatts = new AttributesImpl();
      boolean queryable = wmsConfig.isQueryable(layer);
      qatts.addAttribute("", "queryable", "queryable", "", queryable ? "1" : "0");
      start("Layer", qatts);
      element("Name", layer.getResource().getNamespace().getPrefix() + ":" + layer.getName());
      // REVISIT: this is bad, layer should have title and anbstract by itself
      element("Title", layer.getResource().getTitle());
      element("Abstract", layer.getResource().getAbstract());
      handleKeywordList(layer.getResource().getKeywords());

      /**
       * @task REVISIT: should getSRS() return the full URL? no - the spec says it should be a set
       *     of <SRS>EPSG:#</SRS>...
       */
      final String srs = layer.getResource().getSRS();
      element("SRS", srs);

      // DJB: I want to be nice to the people reading the capabilities
      // file - I'm going to get the
      // human readable name and stick it in the capabilities file
      // NOTE: this isnt well done because "comment()" isnt in the
      // ContentHandler interface...
      try {
        CoordinateReferenceSystem crs = layer.getResource().getCRS();
        String desc = "WKT definition of this CRS:\n" + crs;
        comment(desc);
      } catch (Exception e) {
        if (LOGGER.isLoggable(Level.WARNING)) {
          LOGGER.log(Level.WARNING, e.getLocalizedMessage(), e);
        }
      }

      Envelope bbox;
      try {
        bbox = layer.getResource().boundingBox();
      } catch (Exception e) {
        throw new RuntimeException(
            "Unexpected error obtaining bounding box for layer " + layer.getName(), e);
      }
      Envelope llbbox = layer.getResource().getLatLonBoundingBox();

      handleLatLonBBox(llbbox);
      // the native bbox might be null
      if (bbox != null) {
        handleBBox(bbox, srs);
      }

      // handle dimensions
      String timeMetadata = null;
      String elevationMetadata = null;

      if (layer.getType() == Type.VECTOR) {
        dimensionHelper.handleVectorLayerDimensions(layer);
      } else if (layer.getType() == Type.RASTER) {
        dimensionHelper.handleRasterLayerDimensions(layer);
      }

      // handle data attribution
      handleAttribution(layer);

      // handle metadata URLs
      handleMetadataList(layer.getResource().getMetadataLinks());

      if (layer.getResource() instanceof WMSLayerInfo) {
        // do nothing for the moment, we may want to list the set of cascaded named styles
        // in the future (when we add support for that)
      } else {
        // add the layer style
        start("Style");

        StyleInfo defaultStyle = layer.getDefaultStyle();
        if (defaultStyle == null) {
          throw new NullPointerException("Layer " + layer.getName() + " has no default style");
        }
        Style ftStyle;
        try {
          ftStyle = defaultStyle.getStyle();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
        element("Name", defaultStyle.getName());
        element("Title", ftStyle.getTitle());
        element("Abstract", ftStyle.getAbstract());
        handleLegendURL(layer.getName(), layer.getLegend(), null);
        end("Style");

        Set<StyleInfo> styles = layer.getStyles();

        for (StyleInfo styleInfo : styles) {
          try {
            ftStyle = styleInfo.getStyle();
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
          start("Style");
          element("Name", styleInfo.getName());
          element("Title", ftStyle.getTitle());
          element("Abstract", ftStyle.getAbstract());
          handleLegendURL(layer.getName(), null, styleInfo);
          end("Style");
        }
      }

      end("Layer");
    }