public Resolution getMinMaxValue() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("success", Boolean.FALSE);

    try {
      Layer layer =
          applicationLayer
              .getService()
              .getSingleLayer(applicationLayer.getLayerName(), Stripersist.getEntityManager());
      if (layer != null && layer.getFeatureType() != null) {
        SimpleFeatureType sft = layer.getFeatureType();
        Object value;
        if (operator.equals("#MAX#")) {
          value = sft.getMaxValue(attribute);
        } else {
          value = sft.getMinValue(attribute);
        }

        json.put("value", value.toString());
        json.put("success", Boolean.TRUE);
      }
    } catch (Exception e) {
      log.error("getMinMaxValue() failed", e);
      json.put(
          "msg",
          "Minmax waardes bepalen mislukt voor attribuut " + attribute + ": " + e.toString());
    }
    return new StreamingResolution("application/json", new StringReader(json.toString()));
  }
  public Resolution getUniqueValues() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("success", Boolean.FALSE);

    try {
      Layer layer = applicationLayer.getService().getSingleLayer(applicationLayer.getLayerName());
      if (layer != null && layer.getFeatureType() != null) {
        SimpleFeatureType sft = layer.getFeatureType();
        List<String> beh = sft.calculateUniqueValues(attribute);
        json.put("uniqueValues", new JSONArray(beh));
        json.put("success", Boolean.TRUE);
      }
    } catch (Exception e) {
      json.put("msg", e.toString());
    }
    return new StreamingResolution("application/json", new StringReader(json.toString()));
  }
  private void makeAttributeJSONArray(final SimpleFeatureType layerSft) throws JSONException {
    List<ConfiguredAttribute> cas = applicationLayer.getAttributes();
    // Sort the attributes, by featuretype and the featuretyp
    Collections.sort(
        cas,
        new Comparator<ConfiguredAttribute>() {
          @Override
          public int compare(ConfiguredAttribute o1, ConfiguredAttribute o2) {
            if (o1.getFeatureType() == null) {
              return -1;
            }
            if (o2.getFeatureType() == null) {
              return 1;
            }
            if (o1.getFeatureType().getId().equals(layerSft.getId())) {
              return -1;
            }
            if (o2.getFeatureType().getId().equals(layerSft.getId())) {
              return 1;
            }
            return o1.getFeatureType().getId().compareTo(o2.getFeatureType().getId());
          }
        });
    for (ConfiguredAttribute ca : cas) {
      JSONObject j = ca.toJSONObject();

      // Copy alias over from feature type
      SimpleFeatureType sft = ca.getFeatureType();
      if (sft == null) {
        sft = layerSft;
      }
      AttributeDescriptor ad = sft.getAttribute(ca.getAttributeName());
      j.put("alias", ad.getAlias());
      j.put("featureTypeAttribute", ad.toJSONObject());

      attributesJSON.put(j);
    }
  }
  private List<String> rebuildAttributes(SimpleFeatureType sft) {
    Layer layer = applicationLayer.getService().getSingleLayer(applicationLayer.getLayerName());
    List<String> attributesToRetain = new ArrayList<String>();
    for (AttributeDescriptor ad : sft.getAttributes()) {
      String name = ad.getName();

      String fullName = sft.getId() + ":" + name;
      // if attribute already added return.
      if (attributesToRetain.contains(fullName)) {
        return attributesToRetain;
      }
      attributesToRetain.add(fullName);

      // Used for display in JSP
      if (StringUtils.isNotBlank(ad.getAlias())) {
        attributeAliases.put(fullName, ad.getAlias());
      }

      if (applicationLayer.getAttribute(sft, name) == null) {
        ConfiguredAttribute ca = new ConfiguredAttribute();
        // default visible if not geometry type
        // and not a attribute of a related featuretype
        boolean defaultVisible = true;
        if (layer.getFeatureType().getId() != sft.getId()
            || AttributeDescriptor.GEOMETRY_TYPES.contains(ad.getType())) {
          defaultVisible = false;
        }
        ca.setVisible(defaultVisible);
        ca.setAttributeName(name);
        ca.setFeatureType(sft);
        applicationLayer.getAttributes().add(ca);
        Stripersist.getEntityManager().persist(ca);

        if (!"save".equals(getContext().getEventName())) {
          String message = "Nieuw attribuut \"{0}\" gevonden in ";
          if (layer.getFeatureType().getId() != sft.getId()) {
            message += "gekoppelde ";
          }
          message += "attribuutbron";
          if (layer.getFeatureType().getId() == sft.getId()) {
            message += ": wordt zichtbaar na opslaan";
          }
          getContext().getMessages().add(new SimpleMessage(message, name));
        }
      }
    }
    if (sft.getRelations() != null) {
      for (FeatureTypeRelation rel : sft.getRelations()) {
        attributesToRetain.addAll(rebuildAttributes(rel.getForeignFeatureType()));
      }
    }
    return attributesToRetain;
  }
Example #5
0
 public static Filter reformatFilter(Filter filter, SimpleFeatureType ft) throws Exception {
   FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
   if (Filter.INCLUDE.equals(filter) || Filter.EXCLUDE.equals(filter)) {
     return filter;
   }
   for (FeatureTypeRelation rel : ft.getRelations()) {
     if (FeatureTypeRelation.JOIN.equals(rel.getType())) {
       filter = reformatFilter(filter, rel.getForeignFeatureType());
       filter = (Filter) filter.accept(new ValidFilterExtractor(rel), filter);
     }
   }
   filter = (Filter) filter.accept(new SimplifyingFilterVisitor(), null);
   return filter;
 }
Example #6
0
 private JSONObject toJSONFeature(
     JSONObject j,
     SimpleFeature f,
     SimpleFeatureType ft,
     ApplicationLayer al,
     List<String> propertyNames,
     Map<String, String> attributeAliases,
     int index)
     throws JSONException, Exception {
   if (arrays) {
     for (String name : propertyNames) {
       Object value = f.getAttribute(name);
       j.put("c" + index++, formatValue(value));
     }
   } else {
     for (String name : propertyNames) {
       String alias = null;
       if (attributeAliases != null) {
         alias = attributeAliases.get(name);
       }
       j.put(alias != null ? alias : name, formatValue(f.getAttribute(name)));
     }
   }
   // if edit and not yet set
   // removed check for edit variable here because we need to compare features in edit component
   // and feature info attributes
   // was if(edit && j.optString(FID,null)==null) {
   if (j.optString(FID, null) == null) {
     String id = f.getID();
     j.put(FID, id);
   }
   if (ft.hasRelations()) {
     j = populateWithRelatedFeatures(j, f, ft, al, index);
   }
   return j;
 }
  @Before
  public void synchronizeFeatureTypeAndLoadInfo() throws JSONException {

    Layer layer = applicationLayer.getService().getSingleLayer(applicationLayer.getLayerName());
    if (layer == null) {
      getContext()
          .getValidationErrors()
          .addGlobalError(
              new SimpleError(
                  "Laag niet gevonden bij originele service - verwijder deze laag uit niveau"));
      return;
    }

    for (StyleLibrary sld : layer.getService().getStyleLibraries()) {
      Map style = new HashMap();
      JSONObject styleTitleJson = new JSONObject();

      style.put("id", "sld:" + sld.getId());
      style.put(
          "title", "SLD stijl: " + sld.getTitle() + (sld.isDefaultStyle() ? " (standaard)" : ""));

      // Find stuff for layerName
      if (sld.getNamedLayerUserStylesJson() != null) {
        JSONObject sldNamedLayerJson = new JSONObject(sld.getNamedLayerUserStylesJson());
        if (sldNamedLayerJson.has(layer.getName())) {
          JSONObject namedLayer = sldNamedLayerJson.getJSONObject(layer.getName());
          if (namedLayer.has("title")) {
            styleTitleJson.put("namedLayerTitle", namedLayer.get("title"));
          }
          JSONArray userStyles = namedLayer.getJSONArray("styles");
          if (userStyles.length() > 0) {
            JSONObject userStyle = userStyles.getJSONObject(0);
            if (userStyle.has("title")) {
              styleTitleJson.put("styleTitle", userStyle.get("title"));
            }
          }
        }
      }
      styles.add(style);
      stylesTitleJson.put((String) style.get("id"), styleTitleJson);
    }
    if (layer.getDetails().containsKey(Layer.DETAIL_WMS_STYLES)) {
      JSONArray wmsStyles =
          new JSONArray(layer.getDetails().get(Layer.DETAIL_WMS_STYLES).getValue());
      for (int i = 0; i < wmsStyles.length(); i++) {
        JSONObject wmsStyle = wmsStyles.getJSONObject(i);
        Map style = new HashMap();
        style.put("id", "wms:" + wmsStyle.getString("name"));
        style.put(
            "title",
            "WMS server stijl: "
                + wmsStyle.getString("name")
                + " ("
                + wmsStyle.getString("title")
                + ")");
        JSONObject styleTitleJson = new JSONObject();
        styleTitleJson.put("styleTitle", wmsStyle.getString("title"));
        styles.add(style);
        stylesTitleJson.put((String) style.get("id"), styleTitleJson);
      }
    }
    if (!styles.isEmpty()) {
      List<Map> temp = new ArrayList();
      Map s = new HashMap();
      s.put("id", "registry_default");
      s.put("title", "In gegevensregister als standaard ingestelde SLD");
      temp.add(s);
      s = new HashMap();
      s.put("id", "none");
      s.put("title", "Geen: standaard stijl van WMS service zelf");
      temp.add(s);
      temp.addAll(styles);
      styles = temp;
    }

    // Synchronize configured attributes with layer feature type

    if (layer.getFeatureType() == null || layer.getFeatureType().getAttributes().isEmpty()) {
      applicationLayer.getAttributes().clear();
    } else {
      List<String> attributesToRetain = new ArrayList();

      SimpleFeatureType sft = layer.getFeatureType();
      editable = sft.isWriteable();
      // Rebuild ApplicationLayer.attributes according to Layer FeatureType
      // New attributes are added at the end of the list; the original
      // order is only used when the Application.attributes list is empty
      // So a feature for reordering attributes per applicationLayer is
      // possible.
      // New Attributes from a join or related featureType are added at the
      // end of the list.
      attributesToRetain = rebuildAttributes(sft);

      // JSON info about attributed required for editing
      makeAttributeJSONArray(layer.getFeatureType());
      // Remove ConfiguredAttributes which are no longer present
      List<ConfiguredAttribute> attributesToRemove = new ArrayList();
      for (ConfiguredAttribute ca : applicationLayer.getAttributes()) {
        if (ca.getFeatureType() == null) {
          ca.setFeatureType(layer.getFeatureType());
        }
        if (!attributesToRetain.contains(ca.getFullName())) {
          // Do not modify list we are iterating over
          attributesToRemove.add(ca);
          if (!"save".equals(getContext().getEventName())) {
            getContext()
                .getMessages()
                .add(
                    new SimpleMessage(
                        "Attribuut \"{0}\" niet meer beschikbaar in attribuutbron: wordt verwijderd na opslaan",
                        ca.getAttributeName()));
          }
        }
      }
      for (ConfiguredAttribute ca : attributesToRemove) {
        applicationLayer.getAttributes().remove(ca);
        Stripersist.getEntityManager().remove(ca);
      }
    }
  }
Example #8
0
 /**
  * Get the features as JSONArray with the given params
  *
  * @param al The application layer(if there is a application layer)
  * @param ft The featuretype that must be used to get the features
  * @param fs The featureSource
  * @param q The query
  * @param sort The attribute name that is used to sort
  * @param dir Sort direction (DESC or ASC)
  * @return JSONArray with features.
  * @throws IOException if any
  * @throws JSONException if transforming to json fails
  * @throws Exception if any
  */
 public JSONArray getJSONFeatures(
     ApplicationLayer al, SimpleFeatureType ft, FeatureSource fs, Query q, String sort, String dir)
     throws IOException, JSONException, Exception {
   Map<String, String> attributeAliases = new HashMap<String, String>();
   if (!edit) {
     for (AttributeDescriptor ad : ft.getAttributes()) {
       if (ad.getAlias() != null) {
         attributeAliases.put(ad.getName(), ad.getAlias());
       }
     }
   }
   List<String> propertyNames;
   if (al != null) {
     propertyNames = this.setPropertyNames(al, q, ft, edit);
   } else {
     propertyNames = new ArrayList<String>();
     for (AttributeDescriptor ad : ft.getAttributes()) {
       propertyNames.add(ad.getName());
     }
   }
   if (sort != null) {
     setSortBy(q, propertyNames, sort, dir);
   }
   /* Use the first property as sort field, otherwise geotools while give a error when quering
    * a JDBC featureType without a primary key.
    */
   else if (fs instanceof org.geotools.jdbc.JDBCFeatureSource && !propertyNames.isEmpty()) {
     setSortBy(q, propertyNames.get(0), dir);
   }
   Integer start = q.getStartIndex();
   if (start == null) {
     start = 0;
   }
   boolean offsetSupported = fs.getQueryCapabilities().isOffsetSupported();
   // if offSet is not supported, get more features (start + the wanted features)
   if (!offsetSupported && q.getMaxFeatures() < MAX_FEATURES) {
     q.setMaxFeatures(q.getMaxFeatures() + start);
   }
   FeatureIterator<SimpleFeature> it = null;
   JSONArray features = new JSONArray();
   try {
     it = fs.getFeatures(q).features();
     int featureIndex = 0;
     while (it.hasNext()) {
       SimpleFeature feature = it.next();
       /* if offset not supported and there are more features returned then
        * only get the features after index >= start*/
       if (offsetSupported || featureIndex >= start) {
         JSONObject j =
             this.toJSONFeature(
                 new JSONObject(), feature, ft, al, propertyNames, attributeAliases, 0);
         features.put(j);
       }
       featureIndex++;
     }
   } finally {
     if (it != null) {
       it.close();
     }
     fs.getDataStore().dispose();
   }
   return features;
 }
Example #9
0
 /** Get the propertynames and add the needed propertynames to the query. */
 private List<String> setPropertyNames(
     ApplicationLayer appLayer, Query q, SimpleFeatureType sft, boolean edit) {
   List<String> propertyNames = new ArrayList<String>();
   boolean haveInvisibleProperties = false;
   if (propertyNamesQueryCache.containsKey(sft.getId())) {
     haveInvisibleProperties = haveInvisiblePropertiesCache.get(sft.getId());
     if (haveInvisibleProperties) {
       q.setPropertyNames(propertyNamesQueryCache.get(sft.getId()));
     }
     return propertyNamesReturnCache.get(sft.getId());
   } else {
     for (ConfiguredAttribute ca : appLayer.getAttributes(sft)) {
       if ((!edit && !graph && ca.isVisible())
           || (edit && ca.isEditable())
           || (graph && attributesToInclude.contains(ca.getId()))) {
         propertyNames.add(ca.getAttributeName());
       } else {
         haveInvisibleProperties = true;
       }
     }
     haveInvisiblePropertiesCache.put(sft.getId(), haveInvisibleProperties);
     propertyNamesReturnCache.put(sft.getId(), propertyNames);
     propertyNamesQueryCache.put(sft.getId(), propertyNames);
     if (haveInvisibleProperties) {
       // By default Query retrieves Query.ALL_NAMES
       // Query.NO_NAMES is an empty String array
       q.setPropertyNames(propertyNames);
       // If any related featuretypes are set, add the leftside names in the query
       // don't add them to propertynames, maybe they are not visible
       if (sft.getRelations() != null) {
         List<String> withRelations = new ArrayList<String>();
         withRelations.addAll(propertyNames);
         for (FeatureTypeRelation ftr : sft.getRelations()) {
           if (ftr.getRelationKeys() != null) {
             for (FeatureTypeRelationKey key : ftr.getRelationKeys()) {
               if (!withRelations.contains(key.getLeftSide().getName())) {
                 withRelations.add(key.getLeftSide().getName());
               }
             }
           }
         }
         propertyNamesQueryCache.put(sft.getId(), withRelations);
         q.setPropertyNames(withRelations);
       }
     }
     propertyNamesReturnCache.put(sft.getId(), propertyNames);
     return propertyNames;
   }
 }
Example #10
0
 /** Populate the json object with related featues */
 private JSONObject populateWithRelatedFeatures(
     JSONObject j, SimpleFeature feature, SimpleFeatureType ft, ApplicationLayer al, int index)
     throws Exception {
   if (ft.hasRelations()) {
     JSONArray related_featuretypes = new JSONArray();
     for (FeatureTypeRelation rel : ft.getRelations()) {
       boolean isJoin = rel.getType().equals(FeatureTypeRelation.JOIN);
       if (isJoin) {
         FeatureSource foreignFs = rel.getForeignFeatureType().openGeoToolsFeatureSource(TIMEOUT);
         FeatureIterator<SimpleFeature> foreignIt = null;
         try {
           Query foreignQ = new Query(foreignFs.getName().toString());
           // create filter
           Filter filter = createFilter(feature, rel);
           if (filter == null) {
             continue;
           }
           // if join only get 1 feature
           foreignQ.setMaxFeatures(1);
           foreignQ.setFilter(filter);
           // set propertynames
           List<String> propertyNames;
           if (al != null) {
             propertyNames = setPropertyNames(al, foreignQ, rel.getForeignFeatureType(), edit);
           } else {
             propertyNames = new ArrayList<String>();
             for (AttributeDescriptor ad : rel.getForeignFeatureType().getAttributes()) {
               propertyNames.add(ad.getName());
             }
           }
           if (propertyNames.isEmpty()) {
             // if there are no properties to retrieve just get out
             continue;
           }
           // get aliases
           Map<String, String> attributeAliases = new HashMap<String, String>();
           if (!edit) {
             for (AttributeDescriptor ad : rel.getForeignFeatureType().getAttributes()) {
               if (ad.getAlias() != null) {
                 attributeAliases.put(ad.getName(), ad.getAlias());
               }
             }
           }
           // Get Feature and populate JSON object with the values.
           foreignIt = foreignFs.getFeatures(foreignQ).features();
           while (foreignIt.hasNext()) {
             SimpleFeature foreignFeature = foreignIt.next();
             // join it in the same json
             j =
                 toJSONFeature(
                     j,
                     foreignFeature,
                     rel.getForeignFeatureType(),
                     al,
                     propertyNames,
                     attributeAliases,
                     index);
           }
         } finally {
           if (foreignIt != null) {
             foreignIt.close();
           }
           foreignFs.getDataStore().dispose();
         }
       } else {
         Filter filter = createFilter(feature, rel);
         if (filter == null) {
           continue;
         }
         JSONObject related_ft = new JSONObject();
         related_ft.put("filter", CQL.toCQL(filter));
         related_ft.put("id", rel.getForeignFeatureType().getId());
         related_ft.put("foreignFeatureTypeName", rel.getForeignFeatureType().getTypeName());
         related_featuretypes.put(related_ft);
       }
     }
     if (related_featuretypes.length() > 0) {
       j.put("related_featuretypes", related_featuretypes);
     }
   }
   return j;
 }