Java源码示例:com.google.appengine.api.datastore.GeoPt

示例1
/**
 * Builds a new Place document to insert in the Places index.
 * @param placeId      the identifier of the place in the database.
 * @param placeName    the name of the place.
 * @param placeAddress the address of the place.
 * @param location     the GPS location of the place, as a GeoPt.
 * @return the Place document created.
 */
public static Document buildDocument(
        final Long placeId, final String placeName,
        final String placeAddress, final GeoPt location) {
    GeoPoint geoPoint = new GeoPoint(location.getLatitude(),
            location.getLongitude());

    Document.Builder builder = Document.newBuilder()
            .addField(Field.newBuilder().setName("id")
                    .setText(placeId.toString()))
            .addField(Field.newBuilder().setName("name").setText(placeName))
            .addField(Field.newBuilder().setName("address")
                    .setText(placeAddress))
            .addField(Field.newBuilder().setName("place_location")
                    .setGeoPoint(geoPoint));

    // geo-location doesn't work under dev_server, so let's add another
    // field to use for retrieving documents
    if (environment.value() == Development) {
        builder.addField(Field.newBuilder().setName("value").setNumber(1));
    }

    return builder.build();
}
 
示例2
@Before
public void addData() throws InterruptedException {
    Query query = new Query(kindName, rootKey);
    if (service.prepare(query).countEntities(fetchOption) == 0) {
        List<Entity> elist = new ArrayList<Entity>();
        for (int i = 0; i < count; i++) {
            Entity newRec = new Entity(kindName, rootKey);
            newRec.setProperty("stringData", "string test data " + i);
            newRec.setProperty("intData", 10 * i);
            newRec.setProperty("stringList", Arrays.asList("abc" + i, "xyz" + i, "abc" + i));
            newRec.setProperty("intList", Arrays.asList(i, 50 + i, 90 + i));
            newRec.setProperty("timestamp", new Date());
            newRec.setProperty("floatData", new Float(i + 0.1));
            newRec.setProperty("ratingData", new Rating(i + 20));
            newRec.setProperty("booleanData", true);
            newRec.setProperty("geoptData", new GeoPt((float) (i * 20 - 90), new Float(i * 30 - 179.1)));
            newRec.setProperty("byteStrProp", new ShortBlob(("shortblob" + (i * 30)).getBytes()));
            elist.add(newRec);
        }
        service.put(elist);
        sync(waitTime);
    }
}
 
示例3
@Test
public void testWithPropertyProjection() {
    Query query = new Query(kindName, rootKey);
    query.addProjection(new PropertyProjection("geoptData", GeoPt.class));
    Filter filter1 = Query.CompositeFilterOperator.or(
        Query.FilterOperator.LESS_THAN.of("intList", 5),
        Query.FilterOperator.GREATER_THAN.of("intList", 90));
    Filter filter2 = Query.FilterOperator.EQUAL.of("intList", 52);
    query.setFilter(Query.CompositeFilterOperator.and(filter1, filter2));
    // sql statement
    String sql = "SELECT geoptData FROM " + kindName;
    sql += " WHERE ((intList < 5 or intList > 90) AND intList = 52)";
    sql += " AND __ancestor__ is " + rootKey;
    assertEquals(sql.toLowerCase(), query.toString().toLowerCase());
    // check query result
    List<Entity> results = service.prepare(query).asList(fo);
    Assert.assertTrue(results.size() > 0);
    assertEquals(new GeoPt((float) (2.12), (float) (2.98)), results.get(0).getProperty("geoptData"));
    for (Entity e : results) {
        assertEquals(1, e.getProperties().size());
        assertTrue(e.getProperties().containsKey("geoptData"));
    }
}
 
示例4
static Document buildDocument(
    String placeId, String placeName, String placeAddress, GeoPt location) {
  GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude());

  Document.Builder builder = Document.newBuilder()
      .addField(Field.newBuilder().setName("id").setText(placeId))
      .addField(Field.newBuilder().setName("name").setText(placeName))
      .addField(Field.newBuilder().setName("address").setText(placeAddress))
      .addField(Field.newBuilder().setName("place_location").setGeoPoint(geoPoint));

  // geo-location doesn't work under dev_server, so let's add another
  // field to use for retrieving documents
  if (environment.value() == Development) {
    builder.addField(Field.newBuilder().setName("value").setNumber(1));
  }

  Document place = builder.build();

  return place;
}
 
示例5
@Test
public void testGets() throws Exception {
    Query query = new Query(kindName, rootKey);
    GeoPt filter = new GeoPt(Float.valueOf(60).floatValue(), Float.valueOf(145).floatValue());
    query.setFilter(new FilterPredicate(propertyName, Query.FilterOperator.EQUAL, filter));
    Entity entity = service.prepare(query).asSingleEntity();
    GeoPt geopt = (GeoPt) entity.getProperty(propertyName);
    assertTrue(geopt.equals(filter));
    assertEquals(Float.valueOf(geopt.getLatitude()).toString(), Float.valueOf(60).toString());
    assertEquals(Float.valueOf(geopt.getLongitude()).toString(), Float.valueOf(145).toString());
}
 
示例6
@Test
public void testGeoptType() {
    List<Entity> elist = doQuery(kindName, propertyName, GeoPt.class, true);
    GeoPt rate = (GeoPt) elist.get(0).getProperty(propertyName);
    GeoPt sameDat = (GeoPt) elist.get(0).getProperty(propertyName);
    GeoPt diffDat = (GeoPt) elist.get(1).getProperty(propertyName);
    assertTrue(rate.equals(sameDat));
    assertFalse(rate.equals(diffDat));
    assertEquals(-12, rate.getLatitude(), 0);
    assertEquals(120, rate.getLongitude(), 0);
    assertEquals(0, rate.compareTo(sameDat));
    assertTrue(rate.compareTo(diffDat) != 0);
    assertEquals(rate.hashCode(), rate.hashCode());
}
 
示例7
@Before
public void createData() throws InterruptedException {
    clearData(kindName);

    List<Entity> elist = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        Entity newRec = new Entity(kindName, rootKey);
        newRec.setProperty("stringData", "string data" + i);
        newRec.setProperty("timestamp", new Date());
        newRec.setProperty("shortBlobData", new ShortBlob(("shortBlobData" + i).getBytes()));
        newRec.setProperty("intData", 20 * i);
        newRec.setProperty("textData", new Text("textData" + i));
        newRec.setProperty("floatData", 1234 + 0.1 * i);
        newRec.setProperty("booleanData", true);
        newRec.setProperty("urlData", new Link("http://www.google.com"));
        newRec.setProperty("emailData", new Email("somebody123" + i + "@google.com"));
        newRec.setProperty("phoneData", new PhoneNumber("408-123-000" + i));
        newRec.setProperty("adressData", new PostalAddress("123 st. CA 12345" + i));
        newRec.setProperty("ratingData", new Rating(10 * i));
        newRec.setProperty("geoptData", new GeoPt((float) (i + 0.12), (float) (i + 0.98)));
        newRec.setProperty("categoryData", new Category("category" + i));
        newRec.setProperty("intList", Arrays.asList(i, 50 + i, 90 + i));
        elist.add(newRec);
    }
    service.put(elist);

    sync(1000);
}
 
示例8
@Before
public void createData() throws InterruptedException {
    List<Entity> eList = new ArrayList<Entity>();
    for (int i = 0; i < namespaceDat.length; i++) {
        NamespaceManager.set(namespaceDat[i]);
        for (int k = 0; k < kindDat.length; k++) {
            Query q = new Query(kindDat[k]);
            if (service.prepare(q).countEntities(fo) == 0) {
                for (int c = 0; c < count; c++) {
                    Entity newRec = new Entity(kindDat[k]);
                    newRec.setProperty("name", kindDat[k] + c);
                    newRec.setProperty("timestamp", new Date());
                    newRec.setProperty("shortBlobData", new ShortBlob("shortBlobData".getBytes()));
                    newRec.setProperty("intData", 12345);
                    newRec.setProperty("textData", new Text("textData"));
                    newRec.setProperty("floatData", new Double(12345.12345));
                    newRec.setProperty("booleanData", true);
                    newRec.setProperty("urlData", new Link("http://www.google.com"));
                    newRec.setProperty("emailData", new Email("[email protected]"));
                    newRec.setProperty("phoneData", new PhoneNumber("408-123-4567"));
                    newRec.setProperty("adressData", new PostalAddress("123 st. CA 12345"));
                    newRec.setProperty("ratingData", new Rating(55));
                    newRec.setProperty("geoptData", new GeoPt((float) 12.12, (float) 98.98));
                    newRec.setProperty("categoryData", new Category("abc"));
                    eList.add(newRec);
                }
            }
        }
    }
    if (eList.size() > 0) {
        service.put(eList);
        sync(waitTime);
    }
}
 
示例9
@Before
public void createData() throws InterruptedException {
    Query query = new Query(kindName, rootKey);
    if (service.prepare(query).countEntities(fo) == 0) {
        int props = 15;
        List<Entity> elist = new ArrayList<Entity>();
        elist.clear();
        for (int i = 0; i < count; i++) {
            Entity newRec = new Entity(kindName, rootKey);
            if (i == 0) {
                newRec.setProperty("stringData", null);
            } else if (i == 15) {
                newRec.setProperty("stringData", "");
            } else {
                newRec.setProperty("stringData", "string" + i / (props));
            }
            newRec.setProperty("timestamp", new Date());
            newRec.setProperty("intData", i / (props - 2));
            if (i == 4) {
                newRec.setProperty("floatData", null);
            } else {
                newRec.setProperty("floatData", new Double(12 + i / (props - 4) * 0.1));
            }
            if ((count % 2) == 0) {
                newRec.setProperty("booleanData", true);
            } else {
                newRec.setProperty("booleanData", false);
            }
            newRec.setProperty("geoptData",
                new GeoPt((float) (i / (props - 9) + 12.0), (float) (i / (props - 9) + 90.0)));
            newRec.setProperty("intList",
                Arrays.asList(i / (props - 11), 50 + i / (props - 11), 90 + i / (props - 11)));
            elist.add(newRec);
        }
        service.put(elist);
        sync(waitTime);
    }
}
 
示例10
/**
 * Returns the nearest places to the location of the user.
 * @param location the location of the user.
 * @param distanceInMeters the maximum distance to the user.
 * @param resultCount the maximum number of places returned.
 * @return List of up to resultCount places in the datastore ordered by
 *      the distance to the location parameter and less than
 *      distanceInMeters meters to the location parameter.
 */
public static List<PlaceInfo> getPlaces(final GeoPt location,
        final long distanceInMeters, final int resultCount) {

    // Optional: use memcache

    String geoPoint = "geopoint(" + location.getLatitude() + ", " + location
            .getLongitude()
            + ")";
    String locExpr = "distance(place_location, " + geoPoint + ")";

    // Build the SortOptions with 2 sort keys
    SortOptions sortOptions = SortOptions.newBuilder()
            .addSortExpression(SortExpression.newBuilder()
                    .setExpression(locExpr)
                    .setDirection(SortExpression.SortDirection.ASCENDING)
                    .setDefaultValueNumeric(distanceInMeters + 1))
            .setLimit(resultCount)
            .build();
    // Build the QueryOptions
    QueryOptions options = QueryOptions.newBuilder()
            .setSortOptions(sortOptions)
            .build();
    // Query string
    String searchQuery = "distance(place_location, " + geoPoint + ") < "
            + distanceInMeters;

    Query query = Query.newBuilder().setOptions(options).build(searchQuery);

    Results<ScoredDocument> results = getIndex().search(query);

    if (results.getNumberFound() == 0) {
        // geo-location doesn't work under dev_server
        if (environment.value() == Development) {
            // return all documents
            results = getIndex().search("value > 0");
        }
    }

    List<PlaceInfo> places = new ArrayList<>();

    for (ScoredDocument document : results) {
        if (places.size() >= resultCount) {
            break;
        }

        GeoPoint p = document.getOnlyField("place_location").getGeoPoint();

        PlaceInfo place = new PlaceInfo();
        place.setPlaceId(Long.valueOf(document.getOnlyField("id")
                .getText()));
        place.setName(document.getOnlyField("name").getText());
        place.setAddress(document.getOnlyField("address").getText());

        place.setLocation(new GeoPt((float) p.getLatitude(),
                (float) p.getLongitude()));

        // GeoPoints are not implemented on dev server and latitude and
        // longitude are set to zero
        // But since those are doubles let's play safe
        // and use double comparison with epsilon set to EPSILON
        if (Math.abs(p.getLatitude()) <= EPSILON
                && Math.abs(p.getLongitude()) <= EPSILON) {
            // set a fake distance of 5+ km
            place.setDistanceInKilometers(FAKE_DISTANCE_FOR_DEV + places
                    .size());
        } else {
            double distance = distanceInMeters / METERS_IN_KILOMETER;
            try {
                distance = getDistanceInKm(
                        p.getLatitude(), p.getLongitude(),
                        location.getLatitude(),
                        location.getLongitude());
            } catch (Exception e) {
                LOG.warning("Exception when calculating a distance: " + e
                        .getMessage());
            }

            place.setDistanceInKilometers(distance);
        }

        places.add(place);
    }
    return places;
}
 
示例11
@Test
public void testQueryGeoPtType() {
    checkQueryType("geoptData", GeoPt.class);
}
 
示例12
@Before
public void setUp() {
    super.setUp();

    values = asList(
        asSet((Object) null),
        asSet((short) -10, -10, -10L),
        asSet((short) 10, 10, 10L, new Rating(10)),
        asSet((short) 20, 20, 20L, new Rating(20)),
        asSet(createDate(2013, 1, 1)),
        asSet(createDate(2013, 5, 5)),
        asSet(1381363199999999L),   // 1 microsecond before 2013-10-10
        asSet(new Date(1381363200000L), 1381363200000000L), // 2013-10-10
        asSet(1381363200000001L),   // 1 microsecond after 2013-10-10
        asSet(false),
        asSet(true),
        asSet(
            "sip sip",
            new ShortBlob("sip sip".getBytes()),
            new PostalAddress("sip sip"),
            new PhoneNumber("sip sip"),
            new Email("sip sip"),
            new IMHandle(IMHandle.Scheme.sip, "sip"),   // this is stored as "sip sip"
            new Link("sip sip"),
            new Category("sip sip"),
            new BlobKey("sip sip")
        ),
        asSet(
            "xmpp xmpp",
            new ShortBlob("xmpp xmpp".getBytes()),
            new PostalAddress("xmpp xmpp"),
            new PhoneNumber("xmpp xmpp"),
            new Email("xmpp xmpp"),
            new IMHandle(IMHandle.Scheme.xmpp, "xmpp"), // this is stored as "xmpp xmpp"
            new Link("xmpp xmpp"),
            new Category("xmpp xmpp"),
            new BlobKey("xmpp xmpp")
        ),
        asSet(-10f, -10d),
        asSet(10f, 10d),
        asSet(20f, 20d),
        asSet(new GeoPt(10f, 10f)),
        asSet(new GeoPt(20f, 20f)),
        asSet(new User("aaa", "aaa"), new User("aaa", "otherAuthDomain")),  // ordering must depend only on the email
        asSet(new User("bbb", "bbb")),
        asSet(KeyFactory.createKey("kind", "aaa")),
        asSet(KeyFactory.createKey("kind", "bbb"))
    );

    entities = new ArrayList<Set<Entity>>();
    for (Set<?> values2 : values) {
        Set<Entity> entities2 = new HashSet<Entity>();
        entities.add(entities2);
        for (Object value : values2) {
            entities2.add(storeTestEntityWithSingleProperty(value));
        }
    }
}
 
示例13
@Test
public void testGeoPtProperty() {
    testEqualityQueries(new GeoPt(45f, 15f), new GeoPt(50f, 20f));
    testInequalityQueries(new GeoPt(20f, 10f), new GeoPt(30f, 10f), new GeoPt(40f, 10f));
    testInequalityQueries(new GeoPt(0f, 10f), new GeoPt(0f, 20f), new GeoPt(0f, 30f));
}
 
示例14
@Test
public void testFilter() throws Exception {
    doAllFilters(kindName, propertyName, new GeoPt(Float.valueOf(24).floatValue(), Float.valueOf(-90).floatValue()));
}
 
示例15
public GeoPt getLocation() {
  return location;
}
 
示例16
public void setLocation(GeoPt location) {
  this.location = location;
}
 
示例17
public GeoPt getLocation() {
  return location;
}
 
示例18
public void setLocation(GeoPt location) {
  this.location = location;
}
 
示例19
public GeoPt getLocation() {
  return location;
}
 
示例20
public void setLocation(GeoPt location) {
  this.location = location;
}
 
示例21
static List<PlaceInfo> getPlaces(GeoPt location, long distanceInMeters, int resultCount) {

    // TODO(user): Use memcache

    String geoPoint = "geopoint(" + location.getLatitude() + ", " + location.getLongitude() + ")";

    String query = "distance(place_location, " + geoPoint + ") < " + distanceInMeters;
    String locExpr = "distance(place_location, " + geoPoint + ")";

    SortExpression sortExpr = SortExpression.newBuilder()
        .setExpression(locExpr)
        .setDirection(SortExpression.SortDirection.ASCENDING)
        .setDefaultValueNumeric(distanceInMeters + 1)
        .build();
    Query searchQuery = Query.newBuilder().setOptions(QueryOptions.newBuilder()
        .setSortOptions(SortOptions.newBuilder().addSortExpression(sortExpr))).build(query);
    Results<ScoredDocument> results = getIndex().search(searchQuery);

    if (results.getNumberFound() == 0) {
      // geo-location doesn't work under dev_server
      if (environment.value() == Development) {
        // return all documents
        results = getIndex().search("value > 0");
      }
    }

    List<PlaceInfo> places = new ArrayList<PlaceInfo>();

    for (ScoredDocument document : results) {
      if (places.size() >= resultCount) {
        break;
      }

      GeoPoint p = document.getOnlyField("place_location").getGeoPoint();

      PlaceInfo place = new PlaceInfo();
      place.setplaceID(document.getOnlyField("id").getText());
      place.setName(document.getOnlyField("name").getText());
      place.setAddress(document.getOnlyField("address").getText());

      place.setLocation(new GeoPt((float) p.getLatitude(), (float) p.getLongitude()));

      // GeoPoints are not implemented on dev server and latitude and longitude are set to zero
      // But since those are doubles let's play safe
      // and use double comparison with epsilon set to 0.0001
      if (Math.abs(p.getLatitude()) <= 0.0001 && Math.abs(p.getLongitude()) <= 0.0001) {
        // set a fake distance of 5+ km
        place.setDistanceInKilometers(5 + places.size());
      } else {
        double distance = distanceInMeters / 1000;
        try {
          distance = getDistanceInKm(
              p.getLatitude(), p.getLongitude(), location.getLatitude(), location.getLongitude());
        } catch (Exception e) {
          log.warning("Exception when calculating a distance: " + e.getMessage());
        }

        place.setDistanceInKilometers(distance);
      }

      places.add(place);
    }

    return places;
  }
 
示例22
/**
 * Returns the location of the place.
 * @return the GPS location of this place, as a GeoPt.
 */
public final GeoPt getLocation() {
    return location;
}
 
示例23
/**
 * Sets the location of the place.
 * @param pLocation the GPS location to set for this place, as a GeoPt.
 */
public final void setLocation(final GeoPt pLocation) {
    this.location = pLocation;
}