protected void setLiveIconStyle(
        Style style,
        org.geotools.styling.Style sld,
        IconProperties properties,
        KmlEncodingContext context) {
      final Double opacity = properties.getOpacity();
      final Double scale = properties.getScale();
      final Double heading = properties.getHeading();

      IconStyle is = style.createAndSetIconStyle();

      if (opacity != null) {
        is.setColor(colorToHex(Color.WHITE, opacity));
      }

      if (scale != null) {
        is.setScale(scale);
      }

      if (heading != null) {
        is.setHeading(heading);
      }

      // Get the name of the workspace

      WorkspaceInfo ws = context.getWms().getCatalog().getStyleByName(sld.getName()).getWorkspace();
      String wsName = null;
      if (ws != null) wsName = ws.getName();

      Icon icon = is.createAndSetIcon();
      icon.setHref(
          properties.href(
              context.getMapContent().getRequest().getBaseUrl(), wsName, sld.getName()));
    }
  private void configureGeogigDataStore() throws Exception {

    helper.insertAndAdd(helper.lines1);
    helper.getGeogig().command(CommitOp.class).call();

    Catalog catalog = getCatalog();
    CatalogFactory factory = catalog.getFactory();
    NamespaceInfo ns = factory.createNamespace();
    ns.setPrefix(WORKSPACE);
    ns.setURI(NAMESPACE);
    catalog.add(ns);
    WorkspaceInfo ws = factory.createWorkspace();
    ws.setName(ns.getName());
    catalog.add(ws);

    DataStoreInfo ds = factory.createDataStore();
    ds.setEnabled(true);
    ds.setDescription("Test Geogig DataStore");
    ds.setName(STORE);
    ds.setType(GeoGigDataStoreFactory.DISPLAY_NAME);
    ds.setWorkspace(ws);
    Map<String, Serializable> connParams = ds.getConnectionParameters();

    Optional<URI> geogigDir = helper.getGeogig().command(ResolveGeogigURI.class).call();
    File repositoryUrl = new File(geogigDir.get()).getParentFile();
    assertTrue(repositoryUrl.exists() && repositoryUrl.isDirectory());

    connParams.put(GeoGigDataStoreFactory.REPOSITORY.key, repositoryUrl);
    connParams.put(GeoGigDataStoreFactory.DEFAULT_NAMESPACE.key, ns.getURI());
    catalog.add(ds);

    DataStoreInfo dsInfo = catalog.getDataStoreByName(WORKSPACE, STORE);
    assertNotNull(dsInfo);
    assertEquals(GeoGigDataStoreFactory.DISPLAY_NAME, dsInfo.getType());
    DataAccess<? extends FeatureType, ? extends Feature> dataStore = dsInfo.getDataStore(null);
    assertNotNull(dataStore);
    assertTrue(dataStore instanceof GeoGigDataStore);

    FeatureTypeInfo fti = factory.createFeatureType();
    fti.setNamespace(ns);
    fti.setCatalog(catalog);
    fti.setStore(dsInfo);
    fti.setSRS("EPSG:4326");
    fti.setName("Lines");
    fti.setAdvertised(true);
    fti.setEnabled(true);
    fti.setCqlFilter("INCLUDE");
    fti.setProjectionPolicy(ProjectionPolicy.FORCE_DECLARED);
    ReferencedEnvelope bounds = new ReferencedEnvelope(-180, 180, -90, 90, CRS.decode("EPSG:4326"));
    fti.setNativeBoundingBox(bounds);
    fti.setLatLonBoundingBox(bounds);
    catalog.add(fti);

    fti = catalog.getFeatureType(fti.getId());

    FeatureSource<? extends FeatureType, ? extends Feature> featureSource;
    featureSource = fti.getFeatureSource(null, null);
    assertNotNull(featureSource);
  }
  public void testLoad() {
    tester.assertRenderedPage(WorkspacePage.class);
    tester.assertNoErrorMessage();

    DataView dv = (DataView) tester.getComponentFromLastRenderedPage("table:listContainer:items");
    assertEquals(dv.size(), getCatalog().getWorkspaces().size());
    WorkspaceInfo ws = (WorkspaceInfo) dv.getDataProvider().iterator(0, 1).next();
    assertEquals("cdf", ws.getName());
  }
  public MockCatalogBuilder coverageStore(String name, String filename, String format) {
    String csId = newId();
    WorkspaceInfo ws = workspaces.peekLast();
    NamespaceInfo ns = namespaces.peekLast();

    final CoverageStoreInfo cs = createNiceMock(CoverageStoreInfo.class);
    coverageStores.add(cs);

    initStore(cs, CoverageStoreInfo.class, csId, name, ws);

    File covDir = new File(dataDirRoot, name);
    final File covFile = new File(covDir, filename);
    expect(cs.getURL()).andReturn(DataUtilities.fileToURL(covFile).toString()).anyTimes();
    expect(cs.getType())
        .andAnswer(
            new IAnswer<String>() {
              @Override
              public String answer() throws Throwable {
                return lookupGridFormat(covFile).getName();
              }
            })
        .anyTimes();
    expect(cs.getFormat())
        .andAnswer(
            new IAnswer<AbstractGridFormat>() {
              @Override
              public AbstractGridFormat answer() throws Throwable {
                return lookupGridFormat(covFile);
              }
            })
        .anyTimes();
    expect(cs.getConnectionParameters()).andReturn(new HashMap()).anyTimes();

    expect(catalog.getCoverageStore(csId)).andReturn(cs).anyTimes();
    expect(catalog.getCoverageStoreByName(name)).andReturn(cs).anyTimes();
    expect(catalog.getCoverageStoreByName(ws.getName(), name)).andReturn(cs).anyTimes();
    expect(catalog.getCoverageStoreByName(ws, name)).andReturn(cs).anyTimes();

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

    callback.onStore(name, cs, ws, this);
    replay(cs);
    return this;
  }
  public MockCatalogBuilder workspace(String name, String uri) {
    String wsId = newId();
    String nsId = newId();

    final WorkspaceInfo ws = createNiceMock(WorkspaceInfo.class);
    workspaces.add(ws);
    expect(ws.getId()).andReturn(wsId).anyTimes();
    expect(ws.getName()).andReturn(name).anyTimes();
    expect(ws.getMetadata()).andReturn(new MetadataMap()).anyTimes();

    expect(catalog.getWorkspace(wsId)).andReturn(ws).anyTimes();
    expect(catalog.getWorkspaceByName(name)).andReturn(ws).anyTimes();

    final NamespaceInfo ns = createNiceMock(NamespaceInfo.class);
    namespaces.add(ns);

    expect(ns.getId()).andReturn(nsId).anyTimes();
    expect(ns.getName()).andReturn(name).anyTimes();
    expect(ns.getPrefix()).andReturn(name).anyTimes();
    expect(ns.getMetadata()).andReturn(new MetadataMap()).anyTimes();

    expect(catalog.getNamespace(nsId)).andReturn(ns).anyTimes();
    expect(catalog.getNamespaceByPrefix(name)).andReturn(ns).anyTimes();
    expect(catalog.getNamespaceByURI(uri)).andReturn(ns).anyTimes();

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

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

    callback.onWorkspace(name, ws, this);

    replay(ws, ns);
    return this;
  }
  public MockCatalogBuilder dataStore(String name) {
    String dsId = newId();
    final WorkspaceInfo ws = workspaces.peekLast();
    final NamespaceInfo ns = namespaces.peekLast();

    final DataStoreInfo ds = createNiceMock(DataStoreInfo.class);
    dataStores.add(ds);

    initStore(ds, DataStoreInfo.class, dsId, name, ws);

    // setup the property data store
    final File propDir = new File(dataDirRoot, name);

    HashMap cxParams = new HashMap();
    cxParams.put(PropertyDataStoreFactory.DIRECTORY.key, propDir);
    cxParams.put(PropertyDataStoreFactory.NAMESPACE.key, ns.getURI());
    expect(ds.getConnectionParameters()).andReturn(cxParams).anyTimes();

    try {
      expect(ds.getDataStore(null))
          .andAnswer(
              (IAnswer)
                  new IAnswer<DataAccess>() {
                    @Override
                    public DataAccess answer() throws Throwable {
                      return new PropertyDataStore(propDir, ns.getURI());
                    }
                  })
          .anyTimes();
    } catch (IOException e) {
    }

    expect(catalog.getDataStore(dsId)).andReturn(ds).anyTimes();
    expect(catalog.getDataStoreByName(name)).andReturn(ds).anyTimes();
    expect(catalog.getDataStoreByName(ws.getName(), name)).andReturn(ds).anyTimes();
    expect(catalog.getDataStoreByName(ws, name)).andReturn(ds).anyTimes();

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

    callback.onStore(name, ds, ws, this);
    replay(ds);
    return this;
  }
  @Test
  public void testRemoveWorkspace() throws Exception {
    WorkspaceInfo ws = dao.getCatalog().getFactory().createWorkspace();
    ws.setName("baz");
    dao.add(ws);

    assertNotNull(dao.getWorkspaceByName("baz"));
    int n = dao.getWorkspaces().size();

    dao.remove(ws);
    assertNull(dao.getWorkspaceByName("baz"));
    assertEquals(n - 1, dao.getWorkspaces().size());
  }
  @Test
  public void testCascadeWorkspace() {
    Catalog catalog = getCatalog();
    CascadeRemovalReporter visitor = new CascadeRemovalReporter(catalog);

    WorkspaceInfo ws = catalog.getWorkspaceByName(MockData.CITE_PREFIX);
    assertNotNull(ws);
    List<StoreInfo> stores = getCatalog().getStoresByWorkspace(ws, StoreInfo.class);

    ws.accept(visitor);

    assertTrue(stores.containsAll(visitor.getObjects(StoreInfo.class, ModificationType.DELETE)));
  }
  @Test
  public void testModifyWorkspace() throws Exception {
    WorkspaceInfo ws = dao.getCatalog().getFactory().createWorkspace();
    ws.setName("foo");
    dao.add(ws);

    ws = dao.getWorkspaceByName("foo");
    ws.setName("bar");
    dao.save(ws);

    assertNull(dao.getWorkspaceByName("foo"));
    assertNotNull(dao.getWorkspaceByName("bar"));
  }
  @Test
  public void testRemoveWorkspaceLocalService() throws Exception {
    testAddWorkspaceLocalService();

    File dataDirRoot = getTestData().getDataDirectoryRoot();
    WorkspaceInfo ws = getCatalog().getDefaultWorkspace();

    File f = new File(dataDirRoot, "workspaces" + "/" + ws.getName() + "/service.xml");
    assertTrue(f.exists());

    ServiceInfo s = geoServer.getServiceByName(ws, "foo", ServiceInfo.class);
    geoServer.remove(s);
    assertFalse(f.exists());
  }
  @Test
  public void testAddWorkspace() throws Exception {
    assertEquals(0, dao.getWorkspaces().size());

    WorkspaceInfo ws = dao.getCatalog().getFactory().createWorkspace();
    ws.setName("acme");
    assertNull(ws.getId());

    dao.add(ws);
    assertNotNull(ws.getId());

    assertEquals(1, dao.getWorkspaces().size());
    assertEquals(ws, dao.getWorkspace(ws.getId()));
  }
  @Test
  public void testAddWorkspaceLocalService() throws Exception {
    File dataDirRoot = getTestData().getDataDirectoryRoot();
    WorkspaceInfo ws = getCatalog().getDefaultWorkspace();

    ServiceInfo s = geoServer.getFactory().createService();
    s.setName("foo");
    s.setWorkspace(ws);

    File f = new File(dataDirRoot, "workspaces" + "/" + ws.getName() + "/service.xml");
    assertFalse(f.exists());

    geoServer.add(s);
    assertTrue(f.exists());
  }
  @Override
  protected String handleObjectPost(Object object) throws Exception {
    String workspace = getAttribute("workspace");

    DataStoreInfo ds = (DataStoreInfo) object;
    if (ds.getWorkspace() != null) {
      // ensure the specifried workspace matches the one dictated by the uri
      WorkspaceInfo ws = (WorkspaceInfo) ds.getWorkspace();
      if (!workspace.equals(ws.getName())) {
        throw new RestletException(
            "Expected workspace " + workspace + " but client specified " + ws.getName(),
            Status.CLIENT_ERROR_FORBIDDEN);
      }
    } else {
      ds.setWorkspace(catalog.getWorkspaceByName(workspace));
    }
    ds.setEnabled(true);

    // if no namespace parameter set, set it
    // TODO: we should really move this sort of thing to be something central
    if (!ds.getConnectionParameters().containsKey("namespace")) {
      WorkspaceInfo ws = ds.getWorkspace();
      NamespaceInfo ns = catalog.getNamespaceByPrefix(ws.getName());
      if (ns == null) {
        ns = catalog.getDefaultNamespace();
      }
      if (ns != null) {
        ds.getConnectionParameters().put("namespace", ns.getURI());
      }
    }

    // attempt to set the datastore type
    try {
      DataAccessFactory factory = DataStoreUtils.aquireFactory(ds.getConnectionParameters());
      ds.setType(factory.getDisplayName());
    } catch (Exception e) {
      LOGGER.warning("Unable to determine datastore type from connection parameters");
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "", e);
      }
    }

    catalog.validate((DataStoreInfo) object, false).throwIfInvalid();
    catalog.add((DataStoreInfo) object);

    LOGGER.info("POST data store " + ds.getName());
    return ds.getName();
  }
  private JSONArr layers(StoreInfo store, JSONArr list) throws IOException {
    Catalog cat = geoServer.getCatalog();
    WorkspaceInfo ws = store.getWorkspace();

    Filter filter = and(equal("store", store), equal("namespace.prefix", ws.getName()));
    try (CloseableIterator<ResourceInfo> layers = cat.list(ResourceInfo.class, filter); ) {
      while (layers.hasNext()) {
        ResourceInfo r = layers.next();
        for (LayerInfo l : cat.getLayers(r)) {
          layer(list.addObject(), l, true);
        }
      }
    }

    return list;
  }
  int layerCount(StoreInfo store) throws IOException {
    Catalog cat = geoServer.getCatalog();
    WorkspaceInfo ws = store.getWorkspace();

    Filter filter = and(equal("store", store), equal("namespace.prefix", ws.getName()));
    int count = 0;
    try (CloseableIterator<ResourceInfo> layers = cat.list(ResourceInfo.class, filter); ) {
      while (layers.hasNext()) {
        ResourceInfo r = layers.next();
        for (LayerInfo l : cat.getLayers(r)) {
          if (l != null) {
            count++;
          }
        }
      }
    }
    return count;
  }
Exemple #16
0
  /**
   * Adds a workspace to the test setup.
   *
   * @param name The name of the workspace.
   * @param uri The namespace uri associated with the workspace.
   */
  public void addWorkspace(String name, String uri, Catalog catalog) {

    WorkspaceInfo ws = catalog.getWorkspaceByName(name);
    if (ws == null) {
      ws = catalog.getFactory().createWorkspace();
      ws.setName(name);
      catalog.add(ws);
    }

    NamespaceInfo ns = catalog.getNamespaceByPrefix(name);
    if (ns == null) {
      ns = catalog.getFactory().createNamespace();
      ns.setPrefix(name);
      ns.setURI(uri);
      catalog.add(ns);
    } else {
      ns.setURI(uri);
      catalog.save(ns);
    }
  }
  @Test
  public void testDefaultWorkspace() throws Exception {
    testAddWorkspace();

    assertNull(dao.getDefaultWorkspace());
    WorkspaceInfo ws = dao.getWorkspaceByName("acme");
    dao.setDefaultWorkspace(ws);

    assertNotNull(dao.getDefaultWorkspace());
    assertEquals("acme", dao.getDefaultWorkspace().getName());

    ws = dao.getCatalog().getFactory().createWorkspace();
    ws.setName("bam");
    dao.add(ws);
    dao.setDefaultWorkspace(ws);

    assertEquals("bam", dao.getDefaultWorkspace().getName());

    dao.setDefaultWorkspace(null);
    assertNull(dao.getDefaultWorkspace());
  }
  /**
   * Test that changing a datastore's workspace updates the datastore's "namespace" parameter as
   * well as the namespace of its previously configured resources
   */
  public void testWorkspaceSyncsUpWithNamespace() {
    final Catalog catalog = getCatalog();

    final FormTester formTester = tester.newFormTester("rasterStoreForm");

    final String wsDropdownPath = "rasterStoreForm:workspacePanel:border:paramValue";

    tester.assertModelValue(wsDropdownPath, catalog.getWorkspaceByName(MockData.WCS_PREFIX));

    // select the fifth item in the drop down, which is the cdf workspace
    formTester.select("workspacePanel:border:paramValue", 2);

    // weird on this test I need to both call form.submit() and also simulate clicking on the
    // ajax "save" link for the model to be updated. On a running geoserver instance it works ok
    // though
    formTester.submit();

    final boolean isAjax = true;
    tester.clickLink("rasterStoreForm:save", isAjax);

    // did the save finish normally?
    tester.assertRenderedPage(StorePage.class);

    CoverageStoreInfo store = catalog.getCoverageStore(coverageStore.getId());
    WorkspaceInfo workspace = store.getWorkspace();
    assertFalse(MockData.WCS_PREFIX.equals(workspace.getName()));

    // was the namespace for the datastore resources updated?
    List<CoverageInfo> resourcesByStore;
    resourcesByStore = catalog.getResourcesByStore(store, CoverageInfo.class);

    assertTrue(resourcesByStore.size() > 0);

    for (CoverageInfo cv : resourcesByStore) {
      assertEquals(
          "Namespace for " + cv.getName() + " was not updated",
          workspace.getName(),
          cv.getNamespace().getPrefix());
    }
  }
  <T extends StoreInfo> void initStore(
      T s, Class<T> clazz, String sId, String name, WorkspaceInfo ws) {
    expect(s.getId()).andReturn(sId).anyTimes();
    expect(s.getName()).andReturn(name).anyTimes();
    expect(s.getWorkspace()).andReturn(ws).anyTimes();
    expect(s.getCatalog()).andReturn(catalog).anyTimes();
    expect(s.isEnabled()).andReturn(true).anyTimes();

    expect(catalog.getStore(sId, clazz)).andReturn(s).anyTimes();
    expect(catalog.getStore(sId, StoreInfo.class)).andReturn(s).anyTimes();

    expect(catalog.getStoreByName(name, clazz)).andReturn(s).anyTimes();
    expect(catalog.getStoreByName(name, StoreInfo.class)).andReturn(s).anyTimes();

    expect(catalog.getStoreByName(ws.getName(), name, clazz)).andReturn(s).anyTimes();
    expect(catalog.getStoreByName(ws.getName(), name, StoreInfo.class)).andReturn(s).anyTimes();

    expect(catalog.getStoreByName(ws, name, clazz)).andReturn(s).anyTimes();
    expect(catalog.getStoreByName(ws, name, StoreInfo.class)).andReturn(s).anyTimes();
  }
  /** 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;
  }
  @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace")
  public String execute(
      @DescribeParameter(name = "features", min = 0, description = "Input feature collection")
          SimpleFeatureCollection features,
      @DescribeParameter(name = "coverage", min = 0, description = "Input raster")
          GridCoverage2D coverage,
      @DescribeParameter(
              name = "workspace",
              min = 0,
              description = "Target workspace (default is the system default)")
          String workspace,
      @DescribeParameter(
              name = "store",
              min = 0,
              description = "Target store (default is the workspace default)")
          String store,
      @DescribeParameter(
              name = "name",
              min = 0,
              description =
                  "Name of the new featuretype/coverage (default is the name of the features in the collection)")
          String name,
      @DescribeParameter(
              name = "srs",
              min = 0,
              description =
                  "Target coordinate reference system (default is based on source when possible)")
          CoordinateReferenceSystem srs,
      @DescribeParameter(
              name = "srsHandling",
              min = 0,
              description =
                  "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)")
          ProjectionPolicy srsHandling,
      @DescribeParameter(
              name = "styleName",
              min = 0,
              description =
                  "Name of the style to be associated with the layer (default is a standard geometry-specific style)")
          String styleName)
      throws ProcessException {

    // first off, decide what is the target store
    WorkspaceInfo ws;
    if (workspace != null) {
      ws = catalog.getWorkspaceByName(workspace);
      if (ws == null) {
        throw new ProcessException("Could not find workspace " + workspace);
      }
    } else {
      ws = catalog.getDefaultWorkspace();
      if (ws == null) {
        throw new ProcessException("The catalog is empty, could not find a default workspace");
      }
    }

    // create a builder to help build catalog objects
    CatalogBuilder cb = new CatalogBuilder(catalog);
    cb.setWorkspace(ws);

    // ok, find the target store
    StoreInfo storeInfo = null;
    boolean add = false;
    if (store != null) {
      if (features != null) {
        storeInfo = catalog.getDataStoreByName(ws.getName(), store);
      } else if (coverage != null) {
        storeInfo = catalog.getCoverageStoreByName(ws.getName(), store);
      }
      if (storeInfo == null) {
        throw new ProcessException("Could not find store " + store + " in workspace " + workspace);
        // TODO: support store creation
      }
    } else if (features != null) {
      storeInfo = catalog.getDefaultDataStore(ws);
      if (storeInfo == null) {
        throw new ProcessException("Could not find a default store in workspace " + ws.getName());
      }
    } else if (coverage != null) {
      // create a new coverage store
      LOGGER.info(
          "Auto-configuring coverage store: "
              + (name != null ? name : coverage.getName().toString()));

      storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString()));
      add = true;
      store = (name != null ? name : coverage.getName().toString());

      if (storeInfo == null) {
        throw new ProcessException("Could not find a default store in workspace " + ws.getName());
      }
    }

    // check the target style if any
    StyleInfo targetStyle = null;
    if (styleName != null) {
      targetStyle = catalog.getStyleByName(styleName);
      if (targetStyle == null) {
        throw new ProcessException("Could not find style " + styleName);
      }
    }

    if (features != null) {
      // check if the target layer and the target feature type are not
      // already there (this is a half-assed attempt as we don't have
      // an API telling us how the feature type name will be changed
      // by DataStore.createSchema(...), but better than fully importing
      // the data into the target store to find out we cannot create the layer...)
      String tentativeTargetName = null;
      if (name != null) {
        tentativeTargetName = ws.getName() + ":" + name;
      } else {
        tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName();
      }
      if (catalog.getLayer(tentativeTargetName) != null) {
        throw new ProcessException("Target layer " + tentativeTargetName + " already exists");
      }

      // check the target crs
      String targetSRSCode = null;
      if (srs != null) {
        try {
          Integer code = CRS.lookupEpsgCode(srs, true);
          if (code == null) {
            throw new WPSException("Could not find a EPSG code for " + srs);
          }
          targetSRSCode = "EPSG:" + code;
        } catch (Exception e) {
          throw new ProcessException("Could not lookup the EPSG code for the provided srs", e);
        }
      } else {
        // check we can extract a code from the original data
        GeometryDescriptor gd = features.getSchema().getGeometryDescriptor();
        if (gd == null) {
          // data is geometryless, we need a fake SRS
          targetSRSCode = "EPSG:4326";
          srsHandling = ProjectionPolicy.FORCE_DECLARED;
        } else {
          CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem();
          if (nativeCrs == null) {
            throw new ProcessException(
                "The original data has no native CRS, " + "you need to specify the srs parameter");
          } else {
            try {
              Integer code = CRS.lookupEpsgCode(nativeCrs, true);
              if (code == null) {
                throw new ProcessException(
                    "Could not find an EPSG code for data "
                        + "native spatial reference system: "
                        + nativeCrs);
              } else {
                targetSRSCode = "EPSG:" + code;
              }
            } catch (Exception e) {
              throw new ProcessException(
                  "Failed to loookup an official EPSG code for "
                      + "the source data native "
                      + "spatial reference system",
                  e);
            }
          }
        }
      }

      // import the data into the target store
      SimpleFeatureType targetType;
      try {
        targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo);
      } catch (IOException e) {
        throw new ProcessException("Failed to import data into the target store", e);
      }

      // now import the newly created layer into GeoServer
      try {
        cb.setStore(storeInfo);

        // build the typeInfo and set CRS if necessary
        FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName());
        if (targetSRSCode != null) {
          typeInfo.setSRS(targetSRSCode);
        }
        if (srsHandling != null) {
          typeInfo.setProjectionPolicy(srsHandling);
        }
        // compute the bounds
        cb.setupBounds(typeInfo);

        // build the layer and set a style
        LayerInfo layerInfo = cb.buildLayer(typeInfo);
        if (targetStyle != null) {
          layerInfo.setDefaultStyle(targetStyle);
        }

        catalog.add(typeInfo);
        catalog.add(layerInfo);

        return layerInfo.prefixedName();
      } catch (Exception e) {
        throw new ProcessException("Failed to complete the import inside the GeoServer catalog", e);
      }
    } else if (coverage != null) {
      try {
        final File directory =
            catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store);
        final File file = File.createTempFile(store, ".tif", directory);
        ((CoverageStoreInfo) storeInfo).setURL(file.toURL().toExternalForm());
        ((CoverageStoreInfo) storeInfo).setType("GeoTIFF");

        // check the target crs
        CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem();
        String targetSRSCode = null;
        if (srs != null) {
          try {
            Integer code = CRS.lookupEpsgCode(srs, true);
            if (code == null) {
              throw new WPSException("Could not find a EPSG code for " + srs);
            }
            targetSRSCode = "EPSG:" + code;
          } catch (Exception e) {
            throw new ProcessException("Could not lookup the EPSG code for the provided srs", e);
          }
        } else {
          // check we can extract a code from the original data
          if (cvCrs == null) {
            // data is geometryless, we need a fake SRS
            targetSRSCode = "EPSG:4326";
            srsHandling = ProjectionPolicy.FORCE_DECLARED;
            srs = DefaultGeographicCRS.WGS84;
          } else {
            CoordinateReferenceSystem nativeCrs = cvCrs;
            if (nativeCrs == null) {
              throw new ProcessException(
                  "The original data has no native CRS, "
                      + "you need to specify the srs parameter");
            } else {
              try {
                Integer code = CRS.lookupEpsgCode(nativeCrs, true);
                if (code == null) {
                  throw new ProcessException(
                      "Could not find an EPSG code for data "
                          + "native spatial reference system: "
                          + nativeCrs);
                } else {
                  targetSRSCode = "EPSG:" + code;
                  srs = CRS.decode(targetSRSCode, true);
                }
              } catch (Exception e) {
                throw new ProcessException(
                    "Failed to loookup an official EPSG code for "
                        + "the source data native "
                        + "spatial reference system",
                    e);
              }
            }
          }
        }

        MathTransform tx = CRS.findMathTransform(cvCrs, srs);

        if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) {
          coverage =
              WCSUtils.resample(
                  coverage,
                  cvCrs,
                  srs,
                  null,
                  Interpolation.getInstance(Interpolation.INTERP_NEAREST));
        }

        GeoTiffWriter writer = new GeoTiffWriter(file);

        // setting the write parameters for this geotiff
        final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters();
        params
            .parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString())
            .setValue(DEFAULT_WRITE_PARAMS);
        final GeneralParameterValue[] wps =
            (GeneralParameterValue[]) params.values().toArray(new GeneralParameterValue[1]);

        try {
          writer.write(coverage, wps);
        } finally {
          try {
            writer.dispose();
          } catch (Exception e) {
            // we tried, no need to fuss around this one
          }
        }

        // add or update the datastore info
        if (add) {
          catalog.add((CoverageStoreInfo) storeInfo);
        } else {
          catalog.save((CoverageStoreInfo) storeInfo);
        }

        cb.setStore((CoverageStoreInfo) storeInfo);

        AbstractGridCoverage2DReader reader = new GeoTiffReader(file);
        if (reader == null) {
          throw new ProcessException("Could not aquire reader for coverage.");
        }

        // coverage read params
        final Map customParameters = new HashMap();
        /*String useJAIImageReadParam = "USE_JAI_IMAGEREAD";
        if (useJAIImageReadParam != null) {
        	customParameters.put(AbstractGridFormat.USE_JAI_IMAGEREAD.getName().toString(), Boolean.valueOf(useJAIImageReadParam));
        }*/

        CoverageInfo cinfo = cb.buildCoverage(reader, customParameters);

        // check if the name of the coverage was specified
        if (name != null) {
          cinfo.setName(name);
        }

        if (!add) {
          // update the existing
          CoverageInfo existing =
              catalog.getCoverageByCoverageStore(
                  (CoverageStoreInfo) storeInfo,
                  name != null ? name : coverage.getName().toString());
          if (existing == null) {
            // grab the first if there is only one
            List<CoverageInfo> coverages =
                catalog.getCoveragesByCoverageStore((CoverageStoreInfo) storeInfo);
            if (coverages.size() == 1) {
              existing = coverages.get(0);
            }
            if (coverages.size() == 0) {
              // no coverages yet configured, change add flag and continue on
              add = true;
            } else {
              // multiple coverages, and one to configure not specified
              throw new ProcessException("Unable to determine coverage to configure.");
            }
          }

          if (existing != null) {
            cb.updateCoverage(existing, cinfo);
            catalog.save(existing);
            cinfo = existing;
          }
        }

        // do some post configuration, if srs is not known or unset, transform to 4326
        if ("UNKNOWN".equals(cinfo.getSRS())) {
          // CoordinateReferenceSystem sourceCRS =
          // cinfo.getBoundingBox().getCoordinateReferenceSystem();
          // CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326", true);
          // ReferencedEnvelope re = cinfo.getBoundingBox().transform(targetCRS, true);
          cinfo.setSRS("EPSG:4326");
          // cinfo.setCRS( targetCRS );
          // cinfo.setBoundingBox( re );
        }

        // add/save
        if (add) {
          catalog.add(cinfo);

          LayerInfo layerInfo = cb.buildLayer(cinfo);
          if (styleName != null && targetStyle != null) {
            layerInfo.setDefaultStyle(targetStyle);
          }
          // JD: commenting this out, these sorts of edits should be handled
          // with a second PUT request on the created coverage
          /*
          String styleName = form.getFirstValue("style");
          if ( styleName != null ) {
              StyleInfo style = catalog.getStyleByName( styleName );
              if ( style != null ) {
                  layerInfo.setDefaultStyle( style );
                  if ( !layerInfo.getStyles().contains( style ) ) {
                      layerInfo.getStyles().add( style );
                  }
              }
              else {
                  LOGGER.warning( "Client specified style '" + styleName + "'but no such style exists.");
              }
          }

          String path = form.getFirstValue( "path");
          if ( path != null ) {
              layerInfo.setPath( path );
          }
          */

          boolean valid = true;
          try {
            if (!catalog.validate(layerInfo, true).isEmpty()) {
              valid = false;
            }
          } catch (Exception e) {
            valid = false;
          }

          layerInfo.setEnabled(valid);
          catalog.add(layerInfo);

          return layerInfo.prefixedName();
        } else {
          catalog.save(cinfo);

          LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName());
          if (styleName != null && targetStyle != null) {
            layerInfo.setDefaultStyle(targetStyle);
          }

          return layerInfo.prefixedName();
        }

      } catch (MalformedURLException e) {
        throw new ProcessException("URL Error", e);
      } catch (IOException e) {
        throw new ProcessException("I/O Exception", e);
      } catch (Exception e) {
        e.printStackTrace();
        throw new ProcessException("Exception", e);
      }
    }

    return null;
  }
  // Would have put this on GeoServerImplTest, but it depends on WMS and WFS InfoImpl classes
  // which would lead to circular dependencies.
  @SuppressWarnings("unchecked")
  @Test
  public void testTypedServicesWithWorkspace() throws Exception {
    // Make a workspace
    WorkspaceInfo ws1 = geoServer.getCatalog().getFactory().createWorkspace();
    ws1.setName("TEST-WORKSPACE-1");
    geoServer.getCatalog().add(ws1);

    // Make a service for that workspace
    ServiceInfo ws1wms = new org.geoserver.wms.WMSInfoImpl();
    ws1wms.setWorkspace(ws1);
    ws1wms.setName("WMS1");
    ws1wms.setTitle("WMS for WS1");
    geoServer.add(ws1wms);

    // Make a second for that workspace
    ServiceInfo ws1wfs = new org.geoserver.wfs.WFSInfoImpl();
    ws1wfs.setWorkspace(ws1);
    ws1wfs.setName("WFS1");
    ws1wfs.setTitle("WFS for WS1");
    geoServer.add(ws1wfs);

    // Make a global service
    ServiceInfo gwms = new org.geoserver.wms.WMSInfoImpl();
    gwms.setName("WMSG");
    gwms.setTitle("Global WMS");
    geoServer.add(gwms);

    // Make a second global service
    ServiceInfo gwfs = new org.geoserver.wfs.WFSInfoImpl();
    gwfs.setName("WFSG");
    gwfs.setTitle("Global WFS");
    geoServer.add(gwfs);

    // Make a workspace
    WorkspaceInfo ws2 = geoServer.getCatalog().getFactory().createWorkspace();
    ws2.setName("TEST-WORKSPACE-2");
    geoServer.getCatalog().add(ws2);

    // Make a service for that workspace
    ServiceInfo ws2wms = new org.geoserver.wms.WMSInfoImpl();
    ws2wms.setWorkspace(ws2);
    ws2wms.setName("WMS2");
    ws2wms.setTitle("WMS for WS2");
    geoServer.add(ws2wms);

    // Make a second for that workspace
    ServiceInfo ws2wfs = new org.geoserver.wfs.WFSInfoImpl();
    ws2wfs.setWorkspace(ws2);
    ws2wfs.setName("WFS2");
    ws2wfs.setTitle("WFS for WS2");
    geoServer.add(ws2wfs);

    // Check that we get the services we expect to
    assertThat(geoServer.getService(org.geoserver.wms.WMSInfo.class), equalTo(gwms));
    assertThat(geoServer.getService(org.geoserver.wfs.WFSInfo.class), equalTo(gwfs));
    assertThat(
        (Collection<ServiceInfo>) geoServer.getServices(),
        allOf(hasItems(gwms, gwfs), not(hasItems(ws1wms, ws1wfs, ws2wms, ws2wfs))));
    assertThat(geoServer.getService(ws1, org.geoserver.wms.WMSInfo.class), equalTo(ws1wms));
    assertThat(geoServer.getService(ws1, org.geoserver.wfs.WFSInfo.class), equalTo(ws1wfs));
    assertThat(
        (Collection<ServiceInfo>) geoServer.getServices(ws1),
        allOf(hasItems(ws1wms, ws1wfs), not(hasItems(gwms, gwfs, ws2wms, ws2wfs))));
    assertThat(geoServer.getService(ws2, org.geoserver.wms.WMSInfo.class), equalTo(ws2wms));
    assertThat(geoServer.getService(ws2, org.geoserver.wfs.WFSInfo.class), equalTo(ws2wfs));
    assertThat(
        (Collection<ServiceInfo>) geoServer.getServices(ws2),
        allOf(hasItems(ws2wms, ws2wfs), not(hasItems(gwms, gwfs, ws1wms, ws1wfs))));
  }
 public WorkspaceRequestCtxBuilder(XACMLRole role, WorkspaceInfo workspace, AccessMode mode) {
   super(role, mode.toString());
   this.workspaceName = workspace.getName();
 }
  public MockCatalogBuilder commit() {
    if (!featureTypes.isEmpty() || !coverages.isEmpty()) {
      if (!featureTypes.isEmpty()) {
        DataStoreInfo ds = dataStores.peekLast();

        expect(catalog.getResourcesByStore(ds, FeatureTypeInfo.class))
            .andReturn(featureTypes)
            .anyTimes();
        expect(catalog.getResourcesByStore(ds, ResourceInfo.class))
            .andReturn((List) featureTypes)
            .anyTimes();
        expect(catalog.getFeatureTypesByDataStore(ds)).andReturn(featureTypes).anyTimes();
      }

      if (!coverages.isEmpty()) {
        CoverageStoreInfo cs = coverageStores.peekLast();

        expect(catalog.getResourcesByStore(cs, CoverageInfo.class)).andReturn(coverages).anyTimes();
        expect(catalog.getResourcesByStore(cs, ResourceInfo.class))
            .andReturn((List) coverages)
            .anyTimes();
        expect(catalog.getCoveragesByCoverageStore(cs)).andReturn(coverages).anyTimes();
      }

      // clear out local lists but push up to be included when this workspace is complete
      featureTypesByNamespace.addAll(featureTypes);
      featureTypes = new LinkedList<FeatureTypeInfo>();

      coveragesByNamespace.addAll(coverages);
      coverages = new LinkedList<CoverageInfo>();

    } else if (!dataStores.isEmpty() || !coverageStores.isEmpty()) {
      WorkspaceInfo ws = workspaces.peekLast();
      NamespaceInfo ns = namespaces.peekLast();

      expect(catalog.getStoresByWorkspace(ws.getName(), DataStoreInfo.class))
          .andReturn(dataStores)
          .anyTimes();
      expect(catalog.getStoresByWorkspace(ws, DataStoreInfo.class))
          .andReturn(dataStores)
          .anyTimes();
      expect(catalog.getDataStoresByWorkspace(ws.getName())).andReturn(dataStores).anyTimes();
      expect(catalog.getDataStoresByWorkspace(ws)).andReturn(dataStores).anyTimes();

      expect(catalog.getStoresByWorkspace(ws.getName(), CoverageStoreInfo.class))
          .andReturn(coverageStores)
          .anyTimes();
      expect(catalog.getStoresByWorkspace(ws, CoverageStoreInfo.class))
          .andReturn(coverageStores)
          .anyTimes();
      expect(catalog.getCoverageStoresByWorkspace(ws.getName()))
          .andReturn(coverageStores)
          .anyTimes();
      expect(catalog.getCoverageStoresByWorkspace(ws)).andReturn(coverageStores).anyTimes();

      List<StoreInfo> l = new LinkedList<StoreInfo>(dataStores);
      l.addAll(coverageStores);

      expect(catalog.getStoresByWorkspace(ws.getName(), StoreInfo.class)).andReturn(l).anyTimes();
      expect(catalog.getStoresByWorkspace(ws, StoreInfo.class)).andReturn(l).anyTimes();

      // add all the resources for this workspace
      List<ResourceInfo> m = new LinkedList(featureTypesByNamespace);
      m.addAll(coveragesByNamespace);
      expect(catalog.getResourcesByNamespace(ns, ResourceInfo.class)).andReturn(m).anyTimes();
      // expect(catalog.getResourcesByNamespace(ns.getPrefix(),
      // ResourceInfo.class)).andReturn(m).anyTimes();
      expect(catalog.getResourcesByNamespace(ns, FeatureTypeInfo.class))
          .andReturn(featureTypesByNamespace)
          .anyTimes();
      // expect(catalog.getResourcesByNamespace(ns.getPrefix(), FeatureTypeInfo.class))
      //    .andReturn(featureTypesByNamespace).anyTimes();
      expect(catalog.getResourcesByNamespace(ns, CoverageInfo.class))
          .andReturn(coveragesByNamespace)
          .anyTimes();
      // expect(catalog.getResourcesByNamespace(ns.getPrefix(), CoverageInfo.class))
      //    .andReturn(coveragesByNamespace).anyTimes();

      dataStoresAll.addAll(dataStores);
      dataStores = new LinkedList();

      coverageStoresAll.addAll(coverageStores);
      coverageStores = new LinkedList();

      featureTypesAll.addAll(featureTypesByNamespace);
      featureTypesByNamespace = new LinkedList();

      coveragesAll.addAll(coveragesByNamespace);
      coveragesByNamespace = new LinkedList();
    } else if (!workspaces.isEmpty()) {

      // all the resources
      List<ResourceInfo> l = new LinkedList<ResourceInfo>(featureTypesAll);
      l.addAll(coveragesAll);
      expect(catalog.getResources(ResourceInfo.class)).andReturn(l).anyTimes();
      expect(catalog.getResources(FeatureTypeInfo.class)).andReturn(featureTypesAll).anyTimes();
      expect(catalog.getResources(CoverageInfo.class)).andReturn(coverages).anyTimes();
      expect(catalog.getFeatureTypes()).andReturn(featureTypesAll).anyTimes();
      expect(catalog.getCoverages()).andReturn(coveragesAll).anyTimes();

      // add all the stores
      List<StoreInfo> m = new LinkedList<StoreInfo>(dataStoresAll);
      m.addAll(coverageStoresAll);
      expect(catalog.getStores(StoreInfo.class)).andReturn(m).anyTimes();
      expect(catalog.getStores(DataStoreInfo.class)).andReturn(dataStoresAll).anyTimes();
      expect(catalog.getStores(CoverageStoreInfo.class)).andReturn(coverageStoresAll).anyTimes();

      // add all the styles
      expect(catalog.getStyles()).andReturn(styles).anyTimes();

      // add all the layer groups
      expect(catalog.getLayerGroups()).andReturn(layerGroups).anyTimes();

      // add all the workspaces/namespaces
      expect(catalog.getWorkspaces()).andReturn(workspaces).anyTimes();
      expect(catalog.getNamespaces()).andReturn(namespaces).anyTimes();

      // default workspace/namespace
      expect(catalog.getDefaultWorkspace()).andReturn(workspaces.peekFirst()).anyTimes();
      expect(catalog.getDefaultNamespace()).andReturn(namespaces.peekFirst()).anyTimes();

      replay(catalog);

      featureTypesAll = new LinkedList();
      coveragesAll = new LinkedList();
      dataStoresAll = new LinkedList();
      coverageStoresAll = new LinkedList();
      styles = new LinkedList();
      workspaces = new LinkedList();
      namespaces = new LinkedList();
    }

    return this;
  }