private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
      int b, shift = 0, result = 0;
      do {
        b = encoded.charAt(index++) - 63;
        result |= (b & 0x1f) << shift;
        shift += 5;
      } while (b >= 0x20);
      int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
      lat += dlat;

      shift = 0;
      result = 0;
      do {
        b = encoded.charAt(index++) - 63;
        result |= (b & 0x1f) << shift;
        shift += 5;
      } while (b >= 0x20);
      int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
      lng += dlng;

      LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
      poly.add(p);
    }
    return poly;
  }
  public static List<NameValuePair> convertAttributesToNameValuePair(
      Map<String, String> aAttributes) {
    List<NameValuePair> myNameValuePairs = Lists.newArrayList();

    for (Map.Entry<String, String> myEntry : aAttributes.entrySet()) {
      myNameValuePairs.add(new BasicNameValuePair(myEntry.getKey(), myEntry.getValue()));
    }
    return myNameValuePairs;
  }
  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;
  }
Esempio n. 4
0
  private static List<Integer> getFacetsFromString(String facets) throws Exception {
    // Iterate through comma separated string and extract integer and place into list.
    List<Integer> list = new ArrayList<Integer>();

    String[] array = facets.split(",");
    for (int i = 0; i < array.length; i++) {
      int temp = Integer.parseInt(array[i]);
      System.out.println("Facet " + i + 1 + ": " + temp);
      list.add(temp);
    }

    return list;
  }
Esempio n. 5
0
  private static List<String> getDataFromLine(String line, List<Integer> facetList)
      throws Exception {
    List<String> valuesForCase = new ArrayList<String>();
    String[] data = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
    // Facet list has the column numbers you need to get the data out of! Extract data from data[]
    // and put into valuesForCase.
    for (int i = 0; i < facetList.size(); i++) {
      int col = facetList.get(i);
      valuesForCase.add(data[col]);
    }

    return valuesForCase;
  }
Esempio n. 6
0
  private static List<String> facetStringToListOfKeys(String facets) throws Exception {

    List<String> facetList = new ArrayList<String>();

    String array[] = facets.split(",");
    for (int i = 0; i < array.length; i++) {
      int temp = Integer.parseInt(array[i]);
      String key = columnToKey.get(temp);
      if (key != null) {
        facetList.add(key);
      }
    }

    return facetList;
  }
Esempio n. 7
0
  public static List<String> queryMongoForSimilar(String courtId, String facets) throws Exception {
    // Query mongo for other facets with these values.
    System.out.println("Court id is: " + courtId);
    initializeMap();
    List<String> facetList = facetStringToListOfKeys(facets);
    // Facet list has the keys to get. Query mongo for the document with given courtId, then pull
    // the values of these keys.

    MongoConnection mc = new MongoConnection("supremeCourtDataDB.properties");
    MongoCollection<Document> collection = mc.getCollection();

    int courtIdInt = Integer.parseInt(courtId);
    Document d = collection.find(eq("courtId", courtIdInt)).first();
    System.out.println("Doc with this court id: " + d);

    Document queryDoc = new Document();
    // Build query based on given keys and their values in this doc.
    for (int i = 0; i < facetList.size(); i++) {
      String key = facetList.get(i);
      String tempString;
      int tempInt;
      try {
        tempString = d.getString(key);
        // queryJSON.put(key, tempString);
        queryDoc.put(key, tempString);
      } catch (ClassCastException c) {
        tempInt = d.getInteger(key);
        queryDoc.put(key, tempInt);
        // queryJSON.put(key, tempInt);
      }
    }

    List<String> resultList = new ArrayList<String>();

    System.out.println("Querying mongo.");
    FindIterable<Document> result = collection.find(queryDoc);

    for (Document doc : result) {
      String temp = Integer.toString(doc.getInteger("courtId"));
      resultList.add(temp);
    }

    System.out.println("Done!");
    return resultList;
  }
Esempio n. 8
0
  private static List<String> readFileAndGetCourtIds(List<Integer> facetList, String courtId)
      throws Exception {
    // Find the data for the case in request.
    String filepath = "/data/solr-5.4.1/facetData/supremeCourtData.csv";
    BufferedReader br = new BufferedReader(new FileReader(filepath));
    String line;
    while ((line = br.readLine()) != null) {
      String[] data = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
      if (data[53].equals(courtId)) {
        List<String> valuesForCase = getDataFromLine(line, facetList);
        System.out.println("Values for case: " + valuesForCase.toString());
        // Now we look for other lines which match the values for this case for the given facetList.
        List<String> result = lookForOtherCases(valuesForCase, courtId, facetList);
        return result;
      }
    }

    br.close();
    return null;
  }
  public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;

    try {

      jRoutes = jObject.getJSONArray("routes");

      for (int i = 0; i < jRoutes.length(); i++) {
        jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
        List path = new ArrayList<HashMap<String, String>>();

        for (int j = 0; j < jLegs.length(); j++) {
          jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

          for (int k = 0; k < jSteps.length(); k++) {
            String polyline = "";
            polyline =
                (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
            List<LatLng> list = decodePoly(polyline);

            for (int l = 0; l < list.size(); l++) {
              HashMap<String, String> hm = new HashMap<String, String>();
              hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
              hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
              path.add(hm);
            }
          }
          routes.add(path);
        }
      }

    } catch (JSONException e) {
      e.printStackTrace();
    } catch (Exception e) {
    }
    return routes;
  }
  @DontValidate
  public Resolution edit() throws JSONException {
    if (applicationLayer != null) {
      details = new HashMap();
      for (Map.Entry<String, ClobElement> e : applicationLayer.getDetails().entrySet()) {
        details.put(e.getKey(), e.getValue().getValue());
      }

      groupsRead.addAll(applicationLayer.getReaders());
      groupsWrite.addAll(applicationLayer.getWriters());

      // Fill visible checkboxes
      for (ConfiguredAttribute ca : applicationLayer.getAttributes()) {
        if (ca.isVisible()) {
          selectedAttributes.add(ca.getFullName());
        }
      }
    }

    return new ForwardResolution(JSP);
  }
Esempio n. 11
0
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
Esempio n. 12
0
  private static List<String> lookForOtherCases(
      List<String> valuesForCase, String courtIdForGivenCase, List<Integer> facetList)
      throws Exception {
    // Read CSV. Extract line. Split line on comma regex.
    // array[every value in facet list] must match every value in valuesForCase.

    List<String> resultList = new ArrayList<String>();
    String filepath = "/data/solr-5.4.1/facetData/supremeCourtData.csv";
    BufferedReader br = new BufferedReader(new FileReader(filepath));
    String line;

    while ((line = br.readLine()) != null) {
      String[] data = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

      // There is a courtId.
      String courtId = data[53];
      boolean flag = false;
      // Get data from line into list using the method from before.
      List<String> potentialMatchList = getDataFromLine(line, facetList);

      for (int i = 0; i < valuesForCase.size(); i++) {
        String expected = valuesForCase.get(i);
        String actual = potentialMatchList.get(i);
        if (!expected.equals(actual)) {
          flag = false;
          break; // Don't check further.
        }

        flag = true;
      }

      // If we come out of the loop with flag as true, place the courtId in the result list and read
      // another line!
      if (flag) {
        // Match! Place courtId into result.
        if (!courtId.equals(courtIdForGivenCase)) {
          resultList.add(courtId);
        }
      }
    }

    br.close();
    return resultList;
  }
  @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();
  }