Пример #1
0
  public MockCatalogBuilder layerGroup(
      String name, List<String> layerNames, List<String> styleNames) {

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

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

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

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

      grpLayers.add(l);

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

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

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

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

    callback.onLayerGroup(name, lg, this);
    replay(lg);
    return this;
  }
Пример #2
0
  void createCssTemplate(String name) {
    try {
      Catalog catalog = getCatalog();
      if (catalog.getStyleByName(name) == null) {
        StyleInfo style = catalog.getFactory().createStyle();
        style.setName(name);
        style.setFilename(name + ".sld");
        catalog.add(style);

        File sld = findStyleFile(style.getFilename());
        if (sld == null || !sld.exists()) {
          catalog
              .getResourcePool()
              .writeStyle(
                  style, new ByteArrayInputStream(cssText2sldText(defaultStyle).getBytes()));
        }

        File css = findStyleFile(name + ".css");
        if (!css.exists()) {
          FileWriter writer = new FileWriter(css);
          writer.write(defaultStyle);
          writer.close();
        }
      }
    } catch (IOException ioe) {
      throw new WicketRuntimeException(ioe);
    }
  }
Пример #3
0
 /**
  * Gets a unique fileName for a sample.
  *
  * @param style
  * @return
  */
 private String getSampleFileName(StyleInfo style) {
   String prefix = "";
   if (style.getWorkspace() != null) {
     prefix = style.getWorkspace().getName() + "_";
   }
   String fileName = prefix + style.getName() + "." + DEFAULT_SAMPLE_FORMAT;
   return fileName;
 }
Пример #4
0
  @Test
  public void testAddStyle() throws Exception {
    StyleInfo s = dao.getCatalog().getFactory().createStyle();
    s.setName("blue");

    dao.add(s);

    assertEquals(s, dao.getStyleByName("blue"));
  }
Пример #5
0
 /**
  * Gets an SLD resource for the given style.
  *
  * @param style
  * @return
  */
 private Resource getStyleResource(StyleInfo style) {
   String[] prefix = new String[0];
   if (style.getWorkspace() != null) {
     prefix = new String[] {"workspaces", style.getWorkspace().getName()};
   }
   String fileName = style.getFilename();
   String[] pathParts = (String[]) ArrayUtils.addAll(prefix, new String[] {"styles", fileName});
   String path = Paths.path(pathParts);
   return loader.get(path);
 }
Пример #6
0
 @Test
 public void testPointRenderer() throws Exception {
   StyleInfo pointInfo = getGeoServer().getCatalog().getStyleByName("Buildings");
   assertNotNull(pointInfo);
   Style point = pointInfo.getStyle();
   assertNotNull(point);
   Renderer pointRenderer = StyleEncoder.styleToRenderer((org.geotools.styling.Style) point);
   assertNotNull(point);
   JSONBuilder json = new JSONStringer();
   StyleEncoder.encodeRenderer(json, pointRenderer);
 }
Пример #7
0
 @Test
 public void testLineRenderer() throws Exception {
   StyleInfo lineInfo = getGeoServer().getCatalog().getStyleByName("Streams");
   assertNotNull(lineInfo);
   Style line = lineInfo.getStyle();
   assertNotNull(line);
   Renderer lineRenderer = StyleEncoder.styleToRenderer((org.geotools.styling.Style) line);
   assertNotNull(lineRenderer);
   JSONBuilder json = new JSONStringer();
   StyleEncoder.encodeRenderer(json, lineRenderer);
 }
Пример #8
0
  @Test
  public void testModifyStyle() throws Exception {
    testAddStyle();

    StyleInfo st = dao.getStyleByName("blue");
    st.setName("red");
    dao.save(st);

    assertNull(dao.getStyleByName("blue"));
    assertNotNull(dao.getStyleByName("red"));
  }
Пример #9
0
  /** @return the list of the alternate style names registered for this layer */
  public List<String> getOtherStyleNames() {
    if (layerInfo == null) {
      return Collections.emptyList();
    }
    final List<String> styleNames = new ArrayList<String>();

    for (StyleInfo si : layerInfo.getStyles()) {
      styleNames.add(si.getName());
    }
    return styleNames;
  }
Пример #10
0
  /** Copies a well known style out to the data directory and adds a catalog entry for it. */
  void initializeStyle(Catalog catalog, String styleName, String sld) throws IOException {

    // copy the file out to the data directory if necessary
    if (resourceLoader.find("styles", sld) == null) {
      FileUtils.copyURLToFile(
          GeoServerLoader.class.getResource(sld),
          new File(resourceLoader.findOrCreateDirectory("styles"), sld));
    }

    // create a style for it
    StyleInfo s = catalog.getFactory().createStyle();
    s.setName(styleName);
    s.setFilename(sld);
    catalog.add(s);
  }
Пример #11
0
  /**
   * Creates a new sample file for the given style and stores it on disk. The sample dimensions
   * (width x height) are returned.
   *
   * @param style
   * @param pngOutputFormat
   * @return
   * @throws Exception
   */
  private Dimension createNewSample(StyleInfo style, GetLegendGraphicOutputFormat pngOutputFormat)
      throws Exception {
    GetLegendGraphicRequest legendGraphicRequest = new GetLegendGraphicRequest();
    File sampleLegendFolder = getSamplesFolder();

    legendGraphicRequest.setLayers(Arrays.asList((FeatureType) null));
    legendGraphicRequest.setStyles(Arrays.asList(style.getStyle()));
    legendGraphicRequest.setFormat(pngOutputFormat.getContentType());
    Object legendGraphic = pngOutputFormat.produceLegendGraphic(legendGraphicRequest);
    if (legendGraphic instanceof BufferedImageLegendGraphic) {
      BufferedImage image = ((BufferedImageLegendGraphic) legendGraphic).getLegend();

      PNGWriter writer = new PNGWriter();
      FileOutputStream outStream = null;
      try {
        File sampleFile =
            new File(
                sampleLegendFolder.getAbsolutePath() + File.separator + getSampleFileName(style));
        if (!sampleFile.getParentFile().exists()) {
          sampleFile.getParentFile().mkdirs();
        }
        outStream = new FileOutputStream(sampleFile);
        writer.writePNG(image, outStream, 0.0f, FilterType.FILTER_NONE);
        removeStyleSampleInvalidation(style);
        return new Dimension(image.getWidth(), image.getHeight());
      } finally {
        if (outStream != null) {
          outStream.close();
        }
      }
    }

    return null;
  }
Пример #12
0
  void loadStyles(File styles, Catalog catalog, XStreamPersister xp) {
    for (File sf : list(styles, new SuffixFileFilter(".xml"))) {
      try {
        // handle the .xml.xml case
        if (new File(styles, sf.getName() + ".xml").exists()) {
          continue;
        }

        StyleInfo s = depersist(xp, sf, StyleInfo.class);
        catalog.add(s);

        LOGGER.info("Loaded style '" + s.getName() + "'");
      } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Failed to load style from file '" + sf.getName() + "'", e);
      }
    }
  }
Пример #13
0
  /**
   * Adds a style to the test setup.
   *
   * <p>To set up the style a file named <tt>filename</tt> is copied from the classpath relative to
   * the <tt>scope</tt> parameter.
   *
   * @param name The name of the style.
   * @param filename The filename to copy from classpath.
   * @param scope Class from which to load sld resource from.
   */
  public void addStyle(String name, String filename, Class scope, Catalog catalog)
      throws IOException {
    File styles = catalog.getResourceLoader().findOrCreateDirectory(data, "styles");

    catalog.getResourceLoader().copyFromClassPath(filename, new File(styles, filename), scope);

    StyleInfo style = catalog.getStyleByName(name);
    if (style == null) {
      style = catalog.getFactory().createStyle();
      style.setName(name);
    }
    style.setFilename(filename);
    if (style.getId() == null) {
      catalog.add(style);
    } else {
      catalog.save(style);
    }
  }
Пример #14
0
 /** Clean up no more valid samples: SLD updated from latest sample creation. */
 private void clean() {
   for (StyleInfo style : catalog.getStyles()) {
     synchronized (style) {
       Resource styleResource = getStyleResource(style);
       File sampleFile;
       try {
         // remove old samples
         sampleFile = getSampleFile(style);
         if (isStyleNewerThanSample(styleResource, sampleFile)) {
           sampleFile.delete();
         }
       } catch (IOException e) {
         LOGGER.log(
             Level.SEVERE, "Error cleaning invalid legend sample for " + style.getName(), e);
       }
     }
   }
   invalidated = new HashSet<String>();
 }
Пример #15
0
  public MockCatalogBuilder style(String name) {
    String filename = name + ".sld";
    if (getClass().getResourceAsStream(filename) == null) {
      return this;
    }

    String sId = newId();
    Version version = Styles.Handler.SLD_10.getVersion();

    final StyleInfo s = createNiceMock(StyleInfo.class);
    styles.add(s);

    expect(s.getId()).andReturn(sId);
    expect(s.getName()).andReturn(name).anyTimes();
    expect(s.getFilename()).andReturn(filename).anyTimes();
    expect(s.getSLDVersion()).andReturn(version).anyTimes();
    try {
      expect(s.getStyle())
          .andReturn(
              Styles.style(Styles.parse(getClass().getResourceAsStream(filename), null, version)))
          .anyTimes();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    expect(catalog.getStyle(sId)).andReturn(s).anyTimes();
    expect(catalog.getStyleByName(name)).andReturn(s).anyTimes();

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

    callback.onStyle(name, s, this);
    replay(s);
    return this;
  }
Пример #16
0
 public Style getStyleByName(String styleName) throws IOException {
   StyleInfo styleInfo = getCatalog().getStyleByName(styleName);
   return styleInfo == null ? null : styleInfo.getStyle();
 }
Пример #17
0
  protected void initUI(StyleInfo style) {
    IModel<StyleInfo> styleModel =
        new CompoundPropertyModel(
            style != null
                ? new StyleDetachableModel(style)
                : getCatalog().getFactory().createStyle());

    styleForm =
        new Form("form", styleModel) {
          @Override
          protected void onSubmit() {
            super.onSubmit();
            onStyleFormSubmit();
          }
        };
    styleForm.setMarkupId("mainForm");
    add(styleForm);

    styleForm.add(nameTextField = new TextField("name"));
    nameTextField.setRequired(true);

    DropDownChoice<WorkspaceInfo> wsChoice =
        new DropDownChoice("workspace", new WorkspacesModel(), new WorkspaceChoiceRenderer());
    wsChoice.setNullValid(true);
    if (!isAuthenticatedAsAdmin()) {
      wsChoice.setNullValid(false);
      wsChoice.setRequired(true);
    }

    styleForm.add(wsChoice);
    styleForm.add(editor = new CodeMirrorEditor("SLD", new PropertyModel(this, "rawSLD")));
    // force the id otherwise this blasted thing won't be usable from other forms
    editor.setTextAreaMarkupId("editor");
    editor.setOutputMarkupId(true);
    editor.setRequired(true);
    styleForm.add(editor);

    if (style != null) {
      try {
        setRawSLD(readFile(style));
      } catch (IOException e) {
        // ouch, the style file is gone! Register a generic error message
        Session.get()
            .error(new ParamResourceModel("sldNotFound", this, style.getFilename()).getString());
      }
    }

    // style copy functionality
    styles =
        new DropDownChoice(
            "existingStyles", new Model(), new StylesModel(), new StyleChoiceRenderer());
    styles.setOutputMarkupId(true);
    styles.add(
        new AjaxFormComponentUpdatingBehavior("onchange") {

          @Override
          protected void onUpdate(AjaxRequestTarget target) {
            styles.validate();
            copyLink.setEnabled(styles.getConvertedInput() != null);
            target.addComponent(copyLink);
          }
        });
    styleForm.add(styles);
    copyLink = copyLink();
    copyLink.setEnabled(false);
    styleForm.add(copyLink);

    uploadForm = uploadForm(styleForm);
    uploadForm.setMultiPart(true);
    uploadForm.setMaxSize(Bytes.megabytes(1));
    uploadForm.setMarkupId("uploadForm");
    add(uploadForm);

    uploadForm.add(fileUploadField = new FileUploadField("filename"));

    add(validateLink());
    Link cancelLink =
        new Link("cancel") {
          @Override
          public void onClick() {
            setResponsePage(StylePage.class);
          }
        };
    add(cancelLink);
  }
  /**
   * Handles changes of interest to GWC on a {@link LayerInfo}.
   *
   * <ul>
   *   <li>If the name of the default style changed, then the layer's cache for the default style is
   *       truncated. This method doesn't check if the contents of the styles are equal. That is
   *       handled by {@link CatalogStyleChangeListener} whenever a style is modified.
   *   <li>If the tile layer is {@link GeoServerTileLayerInfo#isAutoCacheStyles() auto caching
   *       styles} and the layerinfo's "styles" list changed, the tile layer's STYLE parameter
   *       filter is updated to match the actual list of layer styles and any removed style is
   *       truncated.
   * </ul>
   *
   * @param changedProperties
   * @param oldValues
   * @param newValues
   * @param li
   * @param tileLayerInfo
   */
  private void handleLayerInfoChange(
      final List<String> changedProperties,
      final List<Object> oldValues,
      final List<Object> newValues,
      final LayerInfo li,
      final GeoServerTileLayerInfo tileLayerInfo) {

    checkNotNull(tileLayerInfo);

    final String layerName = tileLayerName(li);

    boolean save = false;

    final String defaultStyle;

    /*
     * If default style name changed
     */
    if (changedProperties.contains("defaultStyle")) {
      final int propIndex = changedProperties.indexOf("defaultStyle");
      final StyleInfo oldStyle = (StyleInfo) oldValues.get(propIndex);
      final StyleInfo newStyle = (StyleInfo) newValues.get(propIndex);

      final String oldStyleName = oldStyle.getName();
      defaultStyle = newStyle.getName();
      if (!Objects.equal(oldStyleName, defaultStyle)) {
        save = true;
        log.info(
            "Truncating default style for layer "
                + layerName
                + ", as it changed from "
                + oldStyleName
                + " to "
                + defaultStyle);
        mediator.truncateByLayerAndStyle(layerName, oldStyleName);
      }
    } else {
      StyleInfo styleInfo = li.getDefaultStyle();
      defaultStyle = styleInfo == null ? null : styleInfo.getName();
    }

    if (tileLayerInfo.isAutoCacheStyles()) {
      Set<String> styles = new HashSet<String>();
      for (StyleInfo s : li.getStyles()) {
        styles.add(s.getName());
      }
      ImmutableSet<String> cachedStyles = tileLayerInfo.cachedStyles();
      if (!styles.equals(cachedStyles)) {
        // truncate no longer existing cached styles
        Set<String> notCachedAnyMore = Sets.difference(cachedStyles, styles);
        for (String oldCachedStyle : notCachedAnyMore) {
          log.info(
              "Truncating cached style "
                  + oldCachedStyle
                  + " of layer "
                  + layerName
                  + " as it's no longer one of the layer's styles");
          mediator.truncateByLayerAndStyle(layerName, oldCachedStyle);
        }
        // reset STYLES parameter filter
        final boolean createParamIfNotExists = true;
        TileLayerInfoUtil.updateStringParameterFilter(
            tileLayerInfo, "STYLES", createParamIfNotExists, defaultStyle, styles);
        save = true;
      }
    }

    if (save) {
      GridSetBroker gridSetBroker = mediator.getGridSetBroker();
      GeoServerTileLayer tileLayer = new GeoServerTileLayer(li, gridSetBroker, tileLayerInfo);
      mediator.save(tileLayer);
    }
  }
Пример #19
0
  private void doMainLayout() {
    Fragment mainContent = new Fragment("main-content", "normal", this);
    final ModalWindow popup = new ModalWindow("popup");
    mainContent.add(popup);
    mainContent.add(new Label("style.name", new PropertyModel(style, "name")));
    mainContent.add(new Label("layer.name", new PropertyModel(layer, "name")));
    mainContent.add(
        new AjaxLink("change.style", new ParamResourceModel("CssDemoPage.changeStyle", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(400);
            popup.setInitialWidth(600);
            popup.setTitle(new Model("Choose style to edit"));
            popup.setContent(new StyleChooser(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });
    mainContent.add(
        new AjaxLink("change.layer", new ParamResourceModel("CssDemoPage.changeLayer", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(400);
            popup.setInitialWidth(600);
            popup.setTitle(new Model("Choose layer to edit"));
            popup.setContent(new LayerChooser(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });
    mainContent.add(
        new AjaxLink("create.style", new ParamResourceModel("CssDemoPage.createStyle", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(200);
            popup.setInitialWidth(300);
            popup.setTitle(new Model("Choose name for new style"));
            popup.setContent(new LayerNameInput(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });
    mainContent.add(
        new AjaxLink(
            "associate.styles", new ParamResourceModel("CssDemoPage.associateStyles", this)) {
          public void onClick(AjaxRequestTarget target) {
            target.appendJavascript("Wicket.Window.unloadConfirmation = false;");
            popup.setInitialHeight(400);
            popup.setInitialWidth(600);
            popup.setTitle(new Model("Choose layers to associate"));
            popup.setContent(new MultipleLayerChooser(popup.getContentId(), CssDemoPage.this));
            popup.show(target);
          }
        });

    final IModel<String> sldModel =
        new AbstractReadOnlyModel<String>() {
          public String getObject() {
            File file = findStyleFile(style.getFilename());
            if (file != null && file.isFile()) {
              BufferedReader reader = null;
              try {
                reader = new BufferedReader(new FileReader(file));
                StringBuilder builder = new StringBuilder();
                char[] line = new char[4096];
                int len = 0;
                while ((len = reader.read(line, 0, 4096)) >= 0) builder.append(line, 0, len);
                return builder.toString();
              } catch (IOException e) {
                throw new WicketRuntimeException(e);
              } finally {
                try {
                  if (reader != null) reader.close();
                } catch (IOException e) {
                  throw new WicketRuntimeException(e);
                }
              }
            } else {
              return "No SLD file found for this style. One will be generated automatically if you save the CSS.";
            }
          }
        };

    final CompoundPropertyModel model = new CompoundPropertyModel<CssDemoPage>(CssDemoPage.this);
    List<ITab> tabs = new ArrayList<ITab>();
    tabs.add(
        new PanelCachingTab(
            new AbstractTab(new Model("Generated SLD")) {
              public Panel getPanel(String id) {
                SLDPreviewPanel panel = new SLDPreviewPanel(id, sldModel);
                sldPreview = panel.getLabel();
                return panel;
              }
            }));
    tabs.add(
        new PanelCachingTab(
            new AbstractTab(new Model("Map")) {
              public Panel getPanel(String id) {
                return map = new OpenLayersMapPanel(id, layer, style);
              }
            }));
    if (layer.getResource() instanceof FeatureTypeInfo) {
      tabs.add(
          new PanelCachingTab(
              new AbstractTab(new Model("Data")) {
                public Panel getPanel(String id) {
                  try {
                    return new DataPanel(id, model, (FeatureTypeInfo) layer.getResource());
                  } catch (IOException e) {
                    throw new WicketRuntimeException(e);
                  }
                };
              }));
    } else if (layer.getResource() instanceof CoverageInfo) {
      tabs.add(
          new PanelCachingTab(
              new AbstractTab(new Model("Data")) {
                public Panel getPanel(String id) {
                  return new BandsPanel(id, (CoverageInfo) layer.getResource());
                };
              }));
    }
    tabs.add(
        new AbstractTab(new Model("CSS Reference")) {
          public Panel getPanel(String id) {
            return new DocsPanel(id);
          }
        });

    FeedbackPanel feedback2 = new FeedbackPanel("feedback-low");
    feedback2.setOutputMarkupId(true);
    mainContent.add(feedback2);

    String cssSource = style.getFilename().replaceFirst("(\\.sld)?$", ".css");

    mainContent.add(
        new StylePanel("style.editing", model, CssDemoPage.this, getFeedbackPanel(), cssSource));

    mainContent.add(new AjaxTabbedPanel("context", tabs));

    add(mainContent);
  }
    /**
     * Writes layer LegendURL pointing to the user supplied icon URL, if any, or to the proper
     * GetLegendGraphic operation if an URL was not supplied by configuration file.
     *
     * <p>It is common practice to supply a URL to a WMS accesible legend graphic when it is
     * difficult to create a dynamic legend for a layer.
     *
     * @param ft The FeatureTypeInfo that holds the legendURL to write out, or<code>null</code> if
     *     dynamically generated.
     * @task TODO: figure out how to unhack legend parameters such as WIDTH, HEIGHT and FORMAT
     */
    protected void handleLegendURL(String layerName, LegendInfo legend, StyleInfo style) {
      if (legend != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.fine("using user supplied legend URL");
        }

        AttributesImpl attrs = new AttributesImpl();
        attrs.addAttribute("", "width", "width", "", String.valueOf(legend.getWidth()));
        attrs.addAttribute("", "height", "height", "", String.valueOf(legend.getHeight()));

        start("LegendURL", attrs);

        element("Format", legend.getFormat());
        attrs.clear();
        attrs.addAttribute("", "xmlns:xlink", "xmlns:xlink", "", XLINK_NS);
        attrs.addAttribute(XLINK_NS, "type", "xlink:type", "", "simple");
        attrs.addAttribute(XLINK_NS, "href", "xlink:href", "", legend.getOnlineResource());

        element("OnlineResource", null, attrs);

        end("LegendURL");
      } else {
        String defaultFormat = GetLegendGraphicRequest.DEFAULT_FORMAT;

        if (null == wmsConfig.getLegendGraphicOutputFormat(defaultFormat)) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.warning(
                new StringBuffer("Default legend format (")
                    .append(defaultFormat)
                    .append(")is not supported (jai not available?), can't add LegendURL element")
                    .toString());
          }

          return;
        }

        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.fine("Adding GetLegendGraphic call as LegendURL");
        }

        AttributesImpl attrs = new AttributesImpl();
        attrs.addAttribute(
            "", "width", "width", "", String.valueOf(GetLegendGraphicRequest.DEFAULT_WIDTH));

        // DJB: problem here is that we do not know the size of the
        // legend apriori - we need
        // to make one and find its height. Not the best way, but it
        // would work quite well.
        // This was advertising a 20*20 icon, but actually producing
        // ones of a different size.
        // An alternative is to just scale the resulting icon to what
        // the server requested, but this isnt
        // the nicest thing since warped images dont look nice. The
        // client should do the warping.

        // however, to actually estimate the size is a bit difficult.
        // I'm going to do the scaling
        // so it obeys the what the request says. For people with a
        // problem with that should consider
        // changing the default size here so that the request is for the
        // correct size.
        attrs.addAttribute(
            "", "height", "height", "", String.valueOf(GetLegendGraphicRequest.DEFAULT_HEIGHT));

        start("LegendURL", attrs);

        element("Format", defaultFormat);
        attrs.clear();

        Map<String, String> params =
            params(
                "request",
                "GetLegendGraphic",
                "format",
                defaultFormat,
                "width",
                String.valueOf(GetLegendGraphicRequest.DEFAULT_WIDTH),
                "height",
                String.valueOf(GetLegendGraphicRequest.DEFAULT_HEIGHT),
                "layer",
                layerName);
        if (style != null) {
          params.put("style", style.getName());
        }
        String legendURL = buildURL(request.getBaseUrl(), "wms", params, URLType.SERVICE);

        attrs.addAttribute("", "xmlns:xlink", "xmlns:xlink", "", XLINK_NS);
        attrs.addAttribute(XLINK_NS, "type", "xlink:type", "", "simple");
        attrs.addAttribute(XLINK_NS, "href", "xlink:href", "", legendURL);
        element("OnlineResource", null, attrs);

        end("LegendURL");
      }
    }
Пример #21
0
 /**
  * Gets a unique name for a style, considering the workspace definition, in the form
  * worspacename:stylename (or stylename if the style is global).
  *
  * @param styleInfo
  * @return
  */
 private String getStyleName(StyleInfo styleInfo) {
   return styleInfo.getWorkspace() != null
       ? (styleInfo.getWorkspace().getName() + ":" + styleInfo.getName())
       : styleInfo.getName();
 }
    /**
     * 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");
    }