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()));
  }
 @After(stages = LifecycleStage.BindingAndValidation)
 public void loadLayer() {
   this.layer =
       appLayer
           .getService()
           .getSingleLayer(appLayer.getLayerName(), Stripersist.getEntityManager());
 }
Ejemplo n.º 3
0
 public Resolution retrieveCache() throws JSONException, IOException {
   Resolution view = view();
   EntityManager em = Stripersist.getEntityManager();
   SelectedContentCache cache = new SelectedContentCache();
   ClobElement el = application.getDetails().get("selected_content_cache");
   appConfigJSON = el.getValue();
   return view;
 }
 @Before(stages = LifecycleStage.EventHandling)
 public void checkAuthorization() {
   if (application == null
       || appLayer == null
       || !Authorizations.isLayerGeomWriteAuthorized(
           layer, context.getRequest(), Stripersist.getEntityManager())) {
     unauthorized = true;
   }
 }
Ejemplo n.º 5
0
  public Resolution saveCache() throws JSONException, IOException {
    Resolution view = view();

    EntityManager em = Stripersist.getEntityManager();
    SelectedContentCache cache = new SelectedContentCache();
    JSONObject sc = cache.createSelectedContent(application, false);
    application.getDetails().put("selected_content_cache", new ClobElement(sc.toString()));
    em.getTransaction().commit();
    return view;
  }
  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;
  }
Ejemplo n.º 7
0
 static Application findApplication(String name, String version) {
   EntityManager em = Stripersist.getEntityManager();
   if (name != null) {
     CriteriaBuilder cb = em.getCriteriaBuilder();
     CriteriaQuery q = cb.createQuery(Application.class);
     Root<Application> root = q.from(Application.class);
     Predicate namePredicate = cb.equal(root.get("name"), name);
     Predicate versionPredicate =
         version != null ? cb.equal(root.get("version"), version) : cb.isNull(root.get("version"));
     q.where(cb.and(namePredicate, versionPredicate));
     try {
       return (Application) em.createQuery(q).getSingleResult();
     } catch (NoResultException nre) {
     }
   }
   return null;
 }
  @DefaultHandler
  public Resolution getUniqueValues() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("success", Boolean.FALSE);

    try {
      if (this.featureType == null) {
        Layer layer =
            applicationLayer
                .getService()
                .getSingleLayer(applicationLayer.getLayerName(), Stripersist.getEntityManager());
        if (layer != null && layer.getFeatureType() != null) {
          this.featureType = layer.getFeatureType();
        }
      }
      // SimpleFeatureType sft = layer.getFeatureType();
      JSONObject uniqueValues = new JSONObject();
      for (int i = 0; i < attributes.length; i++) {
        String attribute = attributes[i];
        List<String> beh = this.featureType.calculateUniqueValues(attribute, maxFeatures);

        uniqueValues.put(attribute, new JSONArray(beh));
        json.put("success", Boolean.TRUE);
      }
      json.put("uniqueValues", uniqueValues);

    } catch (Exception e) {
      log.error("getUniqueValues() failed", e);
      json.put(
          "msg",
          "Unieke waardes ophalen mislukt voor laag "
              + applicationLayer.getLayerName()
              + ": "
              + e.toString());
    }
    return new StreamingResolution("application/json", new StringReader(json.toString()));
  }
  /**
   * Get a list of key/value pairs to use in picklists.
   *
   * @return json containing a list of id/label objects
   * @throws JSONException if any
   */
  public Resolution getKeyValuePairs() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("success", Boolean.FALSE);
    try {
      if (attributes.length != 2) {
        throw new IllegalArgumentException(
            "Aantal attributen moet 2 zijn voor deze functie, een sleutel en een label veld.");
      }

      if (this.featureType == null) {
        Layer layer =
            applicationLayer
                .getService()
                .getSingleLayer(applicationLayer.getLayerName(), Stripersist.getEntityManager());
        if (layer != null && layer.getFeatureType() != null) {
          this.featureType = layer.getFeatureType();
        }
      }
      Map<String, String> pairs =
          this.featureType.getKeysValues(attributes[0], attributes[1], maxFeatures);
      json.put("valuePairs", pairs);
      json.put("success", Boolean.TRUE);
    } catch (IllegalArgumentException e) {
      log.error("getKeyValuePairs() failed", e);
      json.put("msg", e.toString());
    } catch (Exception e) {
      log.error("getKeyValuePairs() failed", e);
      json.put(
          "msg",
          "Waarde paren ophalen mislukt voor laag "
              + applicationLayer.getLayerName()
              + ": "
              + e.toString());
    }
    return new StreamingResolution("application/json", new StringReader(json.toString()));
  }
  @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);
      }
    }
  }
  public Resolution save() throws JSONException {
    // Only remove details which are editable and re-added layer if not empty,
    // retain other details possibly used in other parts than this page
    // See JSP for which keys are edited
    applicationLayer
        .getDetails()
        .keySet()
        .removeAll(
            Arrays.asList(
                "titleAlias",
                "legendImageUrl",
                "transparency",
                "influenceradius",
                "summary.title",
                "summary.image",
                "summary.description",
                "summary.link",
                "editfunction.title",
                "style",
                "summary.noHtmlEncode",
                "summary.nl2br"));
    for (Map.Entry<String, String> e : details.entrySet()) {
      if (e.getValue() != null) { // Don't insert null value ClobElement
        applicationLayer.getDetails().put(e.getKey(), new ClobElement(e.getValue()));
      }
    }

    applicationLayer.getReaders().clear();
    for (String groupName : groupsRead) {
      applicationLayer.getReaders().add(groupName);
    }

    applicationLayer.getWriters().clear();
    for (String groupName : groupsWrite) {
      applicationLayer.getWriters().add(groupName);
    }

    if (applicationLayer.getAttributes() != null && applicationLayer.getAttributes().size() > 0) {
      List<ConfiguredAttribute> appAttributes = applicationLayer.getAttributes();
      int i = 0;

      for (Iterator it = appAttributes.iterator(); it.hasNext(); ) {
        ConfiguredAttribute appAttribute = (ConfiguredAttribute) it.next();
        // save visible
        if (selectedAttributes.contains(appAttribute.getFullName())) {
          appAttribute.setVisible(true);
        } else {
          appAttribute.setVisible(false);
        }

        // save editable
        if (attributesJSON.length() > i) {
          JSONObject attribute = attributesJSON.getJSONObject(i);

          if (attribute.has("editable")) {
            appAttribute.setEditable(new Boolean(attribute.get("editable").toString()));
          }
          if (attribute.has("editalias")) {
            appAttribute.setEditAlias(attribute.get("editalias").toString());
          }
          if (attribute.has("editvalues")) {
            appAttribute.setEditValues(attribute.get("editvalues").toString());
          }
          if (attribute.has("editHeight")) {
            appAttribute.setEditHeight(attribute.get("editHeight").toString());
          }

          // save selectable
          if (attribute.has("selectable")) {
            appAttribute.setSelectable(new Boolean(attribute.get("selectable").toString()));
          }
          if (attribute.has("filterable")) {
            appAttribute.setFilterable(new Boolean(attribute.get("filterable").toString()));
          }

          if (attribute.has("defaultValue")) {
            appAttribute.setDefaultValue(attribute.get("defaultValue").toString());
          }
        }
        i++;
      }
    }

    Stripersist.getEntityManager().persist(applicationLayer);
    application.authorizationsModified();

    displayName = applicationLayer.getDisplayName();

    Stripersist.getEntityManager().getTransaction().commit();

    getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen"));
    return edit();
  }
 @Before(stages = LifecycleStage.BindingAndValidation)
 @SuppressWarnings("unchecked")
 public void load() {
   allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList();
 }
Ejemplo n.º 13
0
 public static Category getRootCategory() {
   return Stripersist.getEntityManager().find(Category.class, ROOT_CATEGORY_ID);
 }
Ejemplo n.º 14
0
  public void execute(JobExecutionContext jec) throws JobExecutionException {

    try {
      Stripersist.requestInit();
      EntityManager em = Stripersist.getEntityManager();

      StringBuilder monitoringFailures = new StringBuilder();

      int online = 0, offline = 0;

      // TODO: where monitoringEnabled = true...
      for (GeoService gs : (List<GeoService>) em.createQuery("from GeoService").getResultList()) {

        String debugMsg =
            String.format(
                "%s service %s (#%d) with URL: %s",
                gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl());
        try {

          if (isInterrupted()) {
            log.info("Interrupted, ending monitoring job");
            return;
          }

          gs.checkOnline();
          online++;
          gs.setMonitoringStatusOK(true);
          log.debug("ONLINE: " + debugMsg);
        } catch (Exception e) {
          gs.setMonitoringStatusOK(false);
          offline++;
          log.debug("OFFLINE: " + debugMsg);
          if (log.isTraceEnabled()) {
            log.trace("Exception", e);
          }
          String message = e.toString();
          Throwable cause = e.getCause();
          while (cause != null) {
            message += "; " + cause.toString();
            cause = cause.getCause();
          }
          monitoringFailures.append(
              String.format(
                  "%s service %s (#%d)\nURL: %s\nFout: %s\n\n",
                  gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl(), message));
        }
      }

      em.getTransaction().commit();

      log.info(
          String.format(
              "Total services %d, online: %d, offline: %d, runtime: %d s",
              online + offline, online, offline, jec.getJobRunTime() / 1000));

      if (offline > 0) {

        Set emails = new HashSet();
        for (User admin :
            (List<User>)
                em.createQuery(
                        "select u from User u "
                            + "join u.groups g "
                            + "where g.name = '"
                            + Group.SERVICE_ADMIN
                            + "' ")
                    .getResultList()) {
          emails.add(admin.getDetails().get(User.DETAIL_EMAIL));
        }
        emails.remove(null);

        if (!emails.isEmpty()) {
          StringBuilder mail = new StringBuilder();

          SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
          mail.append(
              String.format(
                  "Bij een controle op %s zijn in het gegevensregister %d services gevonden waarbij fouten zijn geconstateerd.\n"
                      + "\nDe volgende controle zal worden uitgevoerd op %s.\nHieronder staat de lijst met probleemservices:\n\n",
                  f.format(jec.getFireTime()), offline, f.format(jec.getNextFireTime())));
          mail.append(monitoringFailures);

          mail(jec, emails, offline + " services zijn offline bij controle", mail.toString());
        }
      }
    } catch (Exception e) {
      log.error("Error", e);
    } finally {
      Stripersist.requestComplete();
    }
  }