private JSONObj storeDetails(JSONObj json, StoreInfo store, HttpServletRequest req)
      throws IOException {
    store(json, store);

    JSONObj connection = new JSONObj();
    Map<String, Serializable> params = store.getConnectionParameters();
    for (Entry<String, Serializable> param : params.entrySet()) {
      String key = param.getKey();
      Object value = param.getValue();
      String text = value == null ? null : value.toString();

      connection.put(key, text);
    }
    if (store instanceof CoverageStoreInfo) {
      CoverageStoreInfo info = (CoverageStoreInfo) store;
      connection.put("raster", info.getURL());
    }
    if (store instanceof WMSStoreInfo) {
      WMSStoreInfo info = (WMSStoreInfo) store;
      json.put("wms", info.getCapabilitiesURL());
    }
    json.put("connection", connection);
    json.put("error", IO.error(new JSONObj(), store.getError()));

    if (store.isEnabled()) {
      resources(store, json.putArray("resources"), req);
    }
    json.put("layer-count", layerCount(store));

    return json;
  }
  @SuppressWarnings("unchecked")
  private boolean define(StoreInfo store, JSONObj obj) {
    boolean reconnect = false;
    for (String prop : obj.keys()) {
      if ("description".equals(prop)) {
        store.setDescription(obj.str(prop));
      } else if ("enabled".equals(prop)) {
        store.setEnabled(obj.bool(prop));
        reconnect = true;
      } else if ("name".equals(prop)) {
        store.setName(obj.str(prop));
      } else if ("workspace".equals(prop)) {
        WorkspaceInfo newWorkspace = findWorkspace(obj.str(prop));
        store.setWorkspace(newWorkspace);
      } else if (store instanceof CoverageStoreInfo) {
        CoverageStoreInfo info = (CoverageStoreInfo) store;
        if ("connection".equals(prop)) {
          JSONObj connection = obj.object(prop);
          if (!connection.has("raster") && connection.str("raster") != null) {
            throw new IllegalArgumentException(
                "Property connection.raster required for coverage store");
          }
          for (String param : connection.keys()) {
            if ("raster".equals(param)) {
              String url = connection.str(param);
              reconnect = reconnect || url == null || !url.equals(info.getURL());
              info.setURL(url);
            }
          }
        }
      } else if (store instanceof WMSStoreInfo) {
        WMSStoreInfo info = (WMSStoreInfo) store;
        if ("connection".equals(prop)) {
          JSONObj connection = obj.object(prop);
          if (!connection.has("url") && connection.str("url") != null) {
            throw new IllegalArgumentException("Property connection.url required for wms store");
          }
          for (String param : connection.keys()) {
            if ("url".equals(param)) {
              String url = connection.str(param);
              reconnect = reconnect || url == null || !url.equals(info.getCapabilitiesURL());
              info.setCapabilitiesURL(url);
            }
          }
        }
      }
      if (store instanceof DataStoreInfo) {
        DataStoreInfo info = (DataStoreInfo) store;
        if ("connection".equals(prop)) {
          JSONObj connection = obj.object(prop);
          info.getConnectionParameters().clear();
          info.getConnectionParameters().putAll(connection.raw());
          reconnect = true;
        }
      }
    }

    return reconnect;
  }
Beispiel #3
0
  @Override
  protected void onSetUp(SystemTestData testData) throws Exception {
    super.onSetUp(testData);

    // we need to add a wms store
    CatalogBuilder cb = new CatalogBuilder(catalog);
    cb.setWorkspace(catalog.getWorkspaceByName("sf"));
    WMSStoreInfo wms = cb.buildWMSStore("demo");
    wms.setCapabilitiesURL("http://demo.opengeo.org/geoserver/wms?");
    catalog.add(wms);

    // and a wms layer as well (cannot use the builder, would turn this test into an online one
    addStatesWmsLayer();
  }
  @org.junit.Test
  public void testCascadingWMS() throws Exception {
    Catalog catalog = getCatalog();

    CatalogBuilder builder = new CatalogBuilder(catalog);
    WMSStoreInfo wmsStore = builder.buildWMSStore("cascadeWMS");
    wmsStore.setCapabilitiesURL(
        "http://wms.geonorge.no/skwms1/wms.toporaster2?service=WMS&version=1.1.1");
    catalog.add(wmsStore);

    builder.setStore(wmsStore);
    WMSLayerInfo wmsLayer = builder.buildWMSLayer("toporaster");
    catalog.add(wmsLayer);

    requiredParameters.put("LAYER", "toporaster");
    GetLegendGraphicRequest request =
        requestReader.read(new GetLegendGraphicRequest(), requiredParameters, requiredParameters);
    assertNotNull(request);
  }
  /** 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;
  }
  @SuppressWarnings({"rawtypes", "unchecked"})
  @RequestMapping(value = "/{wsName}/{name}", method = RequestMethod.POST)
  public @ResponseBody JSONObj create(
      @PathVariable String wsName,
      @PathVariable String name,
      @RequestBody JSONObj obj,
      HttpServletRequest req)
      throws IOException {
    Catalog cat = geoServer.getCatalog();
    CatalogFactory factory = cat.getFactory();

    WorkspaceInfo workspace = findWorkspace(wsName);
    StoreInfo store = null;

    JSONObj params = obj.object("connection");
    if (params == null) {
      throw new IllegalArgumentException("connection parameters required");
    }
    if (params.has("raster")) {
      String url = params.str("raster");
      CoverageStoreInfo info = factory.createCoverageStore();
      info.setWorkspace(workspace);
      info.setType(name);

      // connect and defaults
      info.setURL(url);
      info.setType(obj.str("type"));
      try {
        GridCoverageReader reader = info.getGridCoverageReader(null, null);
        Format format = reader.getFormat();
        info.setDescription(format.getDescription());
        info.setEnabled(true);
      } catch (IOException e) {
        info.setError(e);
        info.setEnabled(false);
      }
      store = info;
    } else if (params.has("url")
        && params.str("url").toLowerCase().contains("Service=WMS")
        && params.str("url").startsWith("http")) {
      WMSStoreInfo info = factory.createWebMapServer();
      info.setWorkspace(workspace);
      info.setType(name);

      // connect and defaults
      info.setCapabilitiesURL(params.str("url"));
      try {
        WebMapServer service = info.getWebMapServer(new NullProgressListener());
        info.setDescription(service.getInfo().getDescription());
        info.setEnabled(true);
      } catch (Throwable e) {
        info.setError(e);
        info.setEnabled(false);
      }
      store = info;
    } else {
      HashMap map = new HashMap(params.raw());
      Map resolved = ResourcePool.getParams(map, cat.getResourceLoader());
      DataAccess dataStore = DataAccessFinder.getDataStore(resolved);
      if (dataStore == null) {
        throw new IllegalArgumentException(
            "Connection parameters incomplete (does not match an available data store, coverage store or wms store).");
      }
      DataStoreInfo info = factory.createDataStore();
      info.setWorkspace(workspace);
      info.setType(name);
      info.getConnectionParameters().putAll(map);
      try {
        info.setDescription(dataStore.getInfo().getDescription());
        info.setEnabled(true);
      } catch (Throwable e) {
        info.setError(e);
        info.setEnabled(false);
      }
      store = info;
    }
    boolean refresh = define(store, obj);
    if (refresh) {
      LOG.log(
          Level.FINE, "Inconsistent: default connection used for store creation required refresh");
    }
    cat.add(store);

    return storeDetails(new JSONObj(), store, req);
  }