com.google.appengine.api.datastore.Text Java Examples

The following examples show how to use com.google.appengine.api.datastore.Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BackendConfigManager.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts data without prefix since data from the front end is based64-encoded and prefixed with
 * "data:application/x-pkcs12;base64,".
 *
 * @param base64String from client
 * @return extracted data without prefix
 */
private Text removeClientHeaderFromData(String base64String) {
  if (StringUtility.isNullOrEmpty(base64String)) {
    return null;
  }

  int index = base64String.indexOf(PKCS12_BASE64_PREFIX);
  if (index < 0) {
    return null;
  }

  String data = base64String.substring(index + PKCS12_BASE64_PREFIX.length());
  if (Base64.isBase64(data)) {
    return new Text(data);
  } else {
    return null;
  }
}
 
Example #2
Source File: BackendConfigManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts data without prefix since data from the front end is based64-encoded and prefixed with
 * "data:application/x-pkcs12;base64,".
 *
 * @param base64String from client
 * @return extracted data without prefix
 */
private Text removeClientHeaderFromData(String base64String) {
  if (StringUtility.isNullOrEmpty(base64String)) {
    return null;
  }

  int index = base64String.indexOf(PKCS12_BASE64_PREFIX);
  if (index < 0) {
    return null;
  }

  String data = base64String.substring(index + PKCS12_BASE64_PREFIX.length());
  if (Base64.isBase64(data)) {
    return new Text(data);
  } else {
    return null;
  }
}
 
Example #3
Source File: UnindexedPropertiesTest.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
@Ignore("CAPEDWARF-66")
@Test
public void testFilterWithUnindexedPropertyType() throws Exception {
    Entity entity = new Entity(UNINDEXED_ENTITY);
    entity.setProperty("prop", "bbb");
    service.put(entity);
    sync(3000);

    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", EQUAL, new Text("bbb")))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", LESS_THAN, new Text("ccc")))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", LESS_THAN_OR_EQUAL, new Text("ccc")))));

    // it's strange that GREATER_THAN actually DOES return a result, whereas LESS_THAN doesn't
    assertEquals(entity, getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", GREATER_THAN, new Text("aaa")))));
    assertEquals(entity, getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("prop", GREATER_THAN_OR_EQUAL, new Text("aaa")))));

    service.delete(entity.getKey());
}
 
Example #4
Source File: BatchTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(11)
public void testStep11Limit() {
    String str1mb = getBigString(1000000);
    Text text = new Text(str1mb);
    List<Entity> elist = new ArrayList<Entity>();
    for (int i = 0; i < 32; i++) {
        Entity newRec = new Entity(kindName, rootKey);
        newRec.setProperty("count", 2000 + i);
        newRec.setProperty("desc", text);
        elist.add(newRec);
    }
    List<Key> eKeys = service.put(elist);
    assertEquals(32, eKeys.size());
}
 
Example #5
Source File: BackendConfigManager.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the push notification certificate as an input stream.
 * 
 * @return the push notification certificate as an input stream or null if the certificate is
 *         not available.
 */
public InputStream getPushNotificationCertificate() {
  Text binary = (Text) getConfiguration().getProperty(PUSH_NOTIFICATION_CERT_BINARY);
  if (StringUtility.isNullOrEmpty(binary)) {
    return null;
  }

  return new ByteArrayInputStream(Base64.decodeBase64(binary.getValue().getBytes()));
}
 
Example #6
Source File: BackendConfigManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the push notification certificate as an input stream.
 * 
 * @return the push notification certificate as an input stream or null if the certificate is
 *         not available.
 */
public InputStream getPushNotificationCertificate() {
  Text binary = (Text) getConfiguration().getProperty(PUSH_NOTIFICATION_CERT_BINARY);
  if (StringUtility.isNullOrEmpty(binary)) {
    return null;
  }

  return new ByteArrayInputStream(Base64.decodeBase64(binary.getValue().getBytes()));
}
 
Example #7
Source File: BackendConfigManager.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the push notification certificates as a byte array.
 *
 * @return the push notification certificate as a byte array or null if the certificate is not
 *         available.
 */
public byte[] getPushNotificationCertificateBytes() {
  Text binary = (Text) getConfiguration().getProperty(PUSH_NOTIFICATION_CERT_BINARY);
  if (StringUtility.isNullOrEmpty(binary)) {
    return null;
  }

  return Base64.decodeBase64(binary.getValue().getBytes());
}
 
Example #8
Source File: TestReport.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
/**
 * Persists {@code this} test report to the given {@link com.google.appengine.api.datastore.DatastoreService}
 * and invalidate the cache.
 *
 * @param reports          the reports entry point
 */
public void save(Reports reports) {
    final Entity entity = new Entity(TEST_REPORT, buildTypeId + buildId);
    entity.setProperty("buildTypeId", buildTypeId);
    entity.setProperty("buildId", buildId);
    entity.setProperty("buildDate", buildDate);
    entity.setProperty("buildDuration", buildDuration);
    entity.setProperty("numberOfPassedTests", numberOfPassedTests);
    entity.setProperty("numberOfIgnoredTests", numberOfIgnoredTests);
    entity.setProperty("numberOfFailedTests", numberOfFailedTests);

    final JSONArray jsonArrayFailedTests = new JSONArray();
    for (Test oneFailingTest : failedTests) {
        jsonArrayFailedTests.put(oneFailingTest.asJson());
    }
    entity.setProperty("failedTests", new Text(jsonArrayFailedTests.toString()));

    final JSONArray jsonArrayIgnoredTests = new JSONArray();
    for (Test oneIgnoredTest : ignoredTests) {
        jsonArrayIgnoredTests.put(oneIgnoredTest.asJson());
    }
    entity.setProperty("ignoredTests", new Text(jsonArrayIgnoredTests.toString()));

    final DatastoreService datastoreService = reports.getDatastoreService();
    datastoreService.put(entity);

    final MemcacheService memcacheService = reports.getMemcacheService();
    memcacheService.delete(buildTypeId); // invalidate cache
}
 
Example #9
Source File: StringDataTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testTextType() {
    String propertyName = "textProp";
    List<Entity> elist = doQuery(kindName, propertyName, null, false);
    Text text = (Text) elist.get(0).getProperty(propertyName);
    Text sameDat = (Text) elist.get(0).getProperty(propertyName);
    Text diffDat = (Text) elist.get(1).getProperty(propertyName);
    assertTrue(text.equals(sameDat));
    assertFalse(text.equals(diffDat));
    String getText = text.getValue();
    assertTrue(getText.equals("english") || getText.equals("chinese")
        || getText.equals("japanese"));
    assertEquals(text.hashCode(), text.hashCode());
}
 
Example #10
Source File: QueryTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #11
Source File: SchemaTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #12
Source File: BackendConfigManager.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the push notification certificates as a byte array.
 *
 * @return the push notification certificate as a byte array or null if the certificate is not
 *         available.
 */
public byte[] getPushNotificationCertificateBytes() {
  Text binary = (Text) getConfiguration().getProperty(PUSH_NOTIFICATION_CERT_BINARY);
  if (StringUtility.isNullOrEmpty(binary)) {
    return null;
  }

  return Base64.decodeBase64(binary.getValue().getBytes());
}
 
Example #13
Source File: UnindexedPropertiesTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnindexedProperties() throws Exception {
    Entity entity = new Entity(UNINDEXED_ENTITY);
    entity.setUnindexedProperty("unindexedString", "unindexedString");
    entity.setUnindexedProperty("unindexedList", new ArrayList<String>(Arrays.asList("listElement1", "listElement2", "listElement3")));
    entity.setUnindexedProperty("unindexedText", new Text("unindexedText"));
    entity.setUnindexedProperty("unindexedBlob", new Blob("unindexedBlob".getBytes()));
    entity.setProperty("text", new Text("text"));
    entity.setProperty("blob", new Blob("blob".getBytes()));

    Key key = service.put(entity);
    sync(3000);  // Not using ancestor queries, so pause before doing queries below.
    Entity entity2 = service.get(key);

    assertTrue(isUnindexed(getRawProperty(entity2, "unindexedString")));
    assertTrue(isUnindexed(getRawProperty(entity2, "unindexedList")));
    assertTrue(isUnindexed(getRawProperty(entity2, "unindexedText")));
    assertTrue(isUnindexed(getRawProperty(entity2, "unindexedBlob")));
    assertTrue(isUnindexed(getRawProperty(entity2, "text")));
    assertTrue(isUnindexed(getRawProperty(entity2, "blob")));

    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("unindexedString", EQUAL, "unindexedString"))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("unindexedList", EQUAL, "listElement1"))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("unindexedText", EQUAL, "unindexedText"))));
    assertNull(getResult(new Query(UNINDEXED_ENTITY).setFilter(new FilterPredicate("text", EQUAL, "text"))));

    service.delete(key);
}
 
Example #14
Source File: MatchTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchOnTextField() throws Exception {
    service.subscribe(TOPIC, "foo", 0, "title:happy", createSchema("title", FieldType.TEXT));

    Entity entity = new Entity("article");
    entity.setProperty("title", new Text("happy feet"));
    service.match(entity, TOPIC);

    assertServletWasInvokedWith(entity);
}
 
Example #15
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@Override
protected void toProperties(DatastoreService ds, Map<String, Object> map) {
    map.put("subject", subject);
    map.put("sender", from);
    map.put("to", to);
    map.put("from", from);
    map.put("cc", cc);
    map.put("bcc", bcc);
    map.put("replyTo", replyTo);
    map.put("body", new Text(body));
    map.put("multiPartsList", toTextList(multiPartsList));
    map.put("headers", new Text(headers));
}
 
Example #16
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void fromPropertiesInternal(Map<String, Object> properties) {
    subject = (String) properties.get("subject");
    from = (String) properties.get("from");
    to = (String) properties.get("to");
    cc = (String) properties.get("cc");
    bcc = (String) properties.get("bcc");
    replyTo = (String) properties.get("replyTo");
    body = fromText(properties.get("body"));
    multiPartsList = fromTextList((List<Text>) properties.get("multiPartsList"));
    headers = fromText(properties.get("headers"));
}
 
Example #17
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private static List<String> fromTextList(List<Text> textList) {
    if (textList == null || textList.isEmpty()) {
        return Collections.emptyList();
    }

    List<String> stringList = new ArrayList<>(textList.size());
    for (Text text : textList) {
        stringList.add(text.getValue());
    }
    return stringList;
}
 
Example #18
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private static List<Text> toTextList(List<String> stringList) {
    if (stringList == null || stringList.isEmpty()) {
        return Collections.emptyList();
    }

    List<Text> textList = new ArrayList<>(stringList.size());
    for (String string : stringList) {
        textList.add(new Text(string));
    }
    return textList;
}
 
Example #19
Source File: CountMapper.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
public void map(Entity entity) {
    emit1("total entities");
    emit1("map calls in shard " + getContext().getShardNumber());
    String name = entity.getKey().getName();
    String payload = ((Text) entity.getProperty("payload")).getValue();
    emit("total entity payload size", payload.length());
    emit("total entity key size", name.length());
    for (char c = 'a'; c <= 'z'; c++) {
        emit(toKey(c), countChar(payload, c));
    }
    for (char c = '0'; c <= '9'; c++) {
        emit("occurrences of digit " + c + " in key", countChar(name, c));
    }
}
 
Example #20
Source File: StudentProfile.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
public void setMoreInfo(String moreInfo) {
    this.moreInfo = moreInfo == null ? null : new Text(moreInfo);
}
 
Example #21
Source File: RemoveWhitespaceTextAdapter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
public String marshal(Text t) {
  return (t == null) ? null : t.getValue();
}
 
Example #22
Source File: EntityCreator.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
public void map(Long index) {
    String name = String.valueOf(random.nextLong() & Long.MAX_VALUE);
    Entity e = new Entity(kind, name);
    e.setProperty("payload", new Text(payloads.get((int) (index % payloads.size()))));
    pool.put(e);
}
 
Example #23
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private static String fromText(Object value) {
    return Text.class.cast(value).getValue();
}
 
Example #24
Source File: EncodedSignedMark.java    From nomulus with Apache License 2.0 4 votes vote down vote up
public static EncodedSignedMark create(String encoding, String encodedData) {
  EncodedSignedMark instance = new EncodedSignedMark();
  instance.encoding = encoding;
  instance.encodedData = new Text(encodedData);
  return instance;
}
 
Example #25
Source File: RepComment.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
public void setComment( Text comment ) {
	this.comment = comment;
}
 
Example #26
Source File: RepComment.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
public Text getComment() {
	return comment;
}
 
Example #27
Source File: InfoServlet.java    From sc2gears with Apache License 2.0 4 votes vote down vote up
/**
 * Saves public replay comment for a replay.
 * Sends back a plain text response: 1 line exactly, true if comment saved successfully; false otherwise.
 */
private static void savePublicRepComment( final HttpServletRequest request, final HttpServletResponse response ) throws IOException {
	final String sha1     = request.getParameter( PARAM_SHA1      );
	String       userName = request.getParameter( PARAM_USER_NAME );
	final String rateGg   = request.getParameter( PARAM_RATE_GG   );
	final String rateBg   = request.getParameter( PARAM_RATE_BG   );
	String       comment  = request.getParameter( PARAM_COMMENT   );
	// Optional parameter:
	final String authorizationKey = request.getParameter( PARAM_AUTHORIZATION_KEY );
	
	LOGGER.fine( "Authorization key: " + authorizationKey + ", sha1: " + sha1 + ", user name: " + userName );
	
	if ( sha1 == null || sha1.isEmpty() || userName == null || userName.isEmpty() ) {
		LOGGER.warning( "Missing parameters!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing parameters!" );
		return;
	}
	if ( comment == null && rateGg == null && rateBg == null ) {
		LOGGER.warning( "Missing parameters!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing parameters!" );
		return;
	}
	
	userName = InfoServletApi.trimUserName( userName );
	comment  = InfoServletApi.trimPublicRepComment( comment );
	if ( userName.isEmpty() || comment != null && comment.isEmpty() ) {
		LOGGER.warning( "Missing parameters!" );
		response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Missing parameters!" );
		return;
	}
	
	PersistenceManager pm = null;
	try {
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = authorizationKey == null ? null : CachingService.getAccountKeyByAuthKey( pm, authorizationKey );
		
		// First register the updater task because if it fails, we do not want comment and rate to be saved!
		// Update replay profile
		TaskServlet.register_updateRepProfileTask( sha1, comment != null, rateGg != null, rateBg != null );
		
		if ( rateGg != null || rateBg != null ) {
			// Save rate
			final RepRate repRate = new RepRate( sha1 );
			if ( accountKey != null )
				repRate.setAccountKey( accountKey );
			repRate.setUserName( userName );
			repRate.fillTracking( request );
			repRate.setBg( rateBg != null );
			repRate.setGg( rateGg != null );
			pm.makePersistent( repRate );
		}
		
		if ( comment != null ) {
			// Save comment
			final RepComment repComment = new RepComment( sha1 );
			if ( accountKey != null )
				repComment.setAccountKey( accountKey );
			repComment.setUserName( userName );
			repComment.fillTracking( request );
			repComment.setComment( new Text( comment ) );
			pm.makePersistent( repComment );
		}
		
		response.setContentType( "text/plain" );
		// Set no-cache
		setNoCache( response );
		
		response.getWriter().println( Boolean.TRUE );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #28
Source File: GeoFencingAPI.java    From google-geoEngine with Apache License 2.0 4 votes vote down vote up
/**
 * Endpoint for adding fences to the DataStore collection.
 */@ApiMethod(name = "add", httpMethod = "post", path = "add")
public MyFence addFence(@Named("group") String group, @Named("index") boolean buildIndex, MyFence fence) {
    //Get the last fences' id.
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key fenceKey = KeyFactory.createKey("Geofence", group);

    long nextId;
    if (fence.getId() != -1) {
        nextId = fence.getId();
    } else {
        long lastId;
        Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING);
        List < Entity > lastFence = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));

        if (lastFence.isEmpty()) {
            lastId = -1;
        } else {
            lastId = (long) lastFence.get(0).getProperty("id");
        }
        nextId = lastId + 1;
    }

    //Create new Entity with nextId.
    Entity fenceEntity = new Entity("Fence", fenceKey);
    fenceEntity.setProperty("id", nextId);
    fenceEntity.setProperty("name", fence.getName());
    fenceEntity.setProperty("description", fence.getDescription());

    Gson gson = new Gson();
    String jsonString = gson.toJson(fence.getVertices());
    //Convert to DataStore-Text-Object to store the vertices.
    Text jsonText = new Text(jsonString);
    fenceEntity.setProperty("vertices", jsonText);
    //Write to DataStore.
    datastore.put(fenceEntity);

    MyFence newFence = new MyFence();
    newFence.setId(nextId);

    //Rebuild the Index.
    if (buildIndex) {
        try {
            MyIndex.buildIndex(group);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return newFence;
}
 
Example #29
Source File: MyIndex.java    From google-geoEngine with Apache License 2.0 4 votes vote down vote up
public static int buildIndex(String group) throws IOException{
    //Get all fences of group from DataStore.
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key fenceKey = KeyFactory.createKey("Geofence", group);

    Query query = new Query("Fence", fenceKey).addSort("id", Query.SortDirection.DESCENDING);
    List<Entity> fencesFromStore = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    if (!fencesFromStore.isEmpty()) {
    	//Create STRTree-Index.
        STRtree index = new STRtree();
        //Loop through the fences from DataStore.
        for (Entity fenceFromStore : fencesFromStore) {
            long id = (long) fenceFromStore.getProperty("id");
            Gson gson = new Gson();
            Text vText = (Text) fenceFromStore.getProperty("vertices");
            String vString = vText.getValue();
            double[][] vertices = gson.fromJson(vString, double[][].class);

            //Store coordinates in an array.
            Coordinate[] coordinates = new Coordinate[vertices.length];
            int i = 0;
            for(double[] point : vertices){
                Coordinate coordinate = new Coordinate(point[0],point[1]);
                coordinates[i++] = coordinate;
            }
            //Create polygon from the coordinates.
            GeometryFactory fact = new GeometryFactory();
            LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
            MyPolygon polygon = new MyPolygon(linear, null, fact, id);
            //Add polygon to index.
            index.insert(polygon.getEnvelopeInternal(), polygon);
        }
        //Build the index.
        index.build();
        //Write the index to Memcache.
        MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
        //Last param is expiration date. Set to null to keep it in Memcache forever.
        syncCache.put(group, index, null); 
    }
    return fencesFromStore.size();
}
 
Example #30
Source File: JobRecord.java    From appengine-pipelines with Apache License 2.0 4 votes vote down vote up
/**
 * Re-constitutes an instance of this class from a Data Store entity.
 *
 * @param entity
 */
public JobRecord(Entity entity) {
  super(entity);
  jobInstanceKey = (Key) entity.getProperty(JOB_INSTANCE_PROPERTY);
  finalizeBarrierKey = (Key) entity.getProperty(FINALIZE_BARRIER_PROPERTY);
  runBarrierKey = (Key) entity.getProperty(RUN_BARRIER_PROPERTY);
  outputSlotKey = (Key) entity.getProperty(OUTPUT_SLOT_PROPERTY);
  state = State.valueOf((String) entity.getProperty(STATE_PROPERTY));
  exceptionHandlingAncestorKey =
      (Key) entity.getProperty(EXCEPTION_HANDLING_ANCESTOR_KEY_PROPERTY);
  Object exceptionHandlerSpecifiedProperty =
      entity.getProperty(EXCEPTION_HANDLER_SPECIFIED_PROPERTY);
  if (null != exceptionHandlerSpecifiedProperty) {
    exceptionHandlerSpecified = (Boolean) exceptionHandlerSpecifiedProperty;
  }
  exceptionHandlerJobKey = (Key) entity.getProperty(EXCEPTION_HANDLER_JOB_KEY_PROPERTY);
  Text exceptionHandlerGraphGuidText =
      (Text) entity.getProperty(EXCEPTION_HANDLER_JOB_GRAPH_GUID_PROPERTY);
  if (null != exceptionHandlerGraphGuidText) {
    exceptionHandlerJobGraphGuid = exceptionHandlerGraphGuidText.getValue();
  }
  Object callExceptionHandlerProperty = entity.getProperty(CALL_EXCEPTION_HANDLER_PROPERTY);
  if (null != callExceptionHandlerProperty) {
    callExceptionHandler = (Boolean) callExceptionHandlerProperty;
  }
  Object ignoreExceptionProperty = entity.getProperty(IGNORE_EXCEPTION_PROPERTY);
  if (null != ignoreExceptionProperty) {
    ignoreException = (Boolean) ignoreExceptionProperty;
  }
  Text childGraphGuidText = (Text) entity.getProperty(CHILD_GRAPH_GUID_PROPERTY);
  if (null != childGraphGuidText) {
    childGraphGuid = childGraphGuidText.getValue();
  }
  exceptionKey = (Key) entity.getProperty(EXCEPTION_KEY_PROPERTY);
  startTime = (Date) entity.getProperty(START_TIME_PROPERTY);
  endTime = (Date) entity.getProperty(END_TIME_PROPERTY);
  childKeys = (List<Key>) entity.getProperty(CHILD_KEYS_PROPERTY);
  if (null == childKeys) {
    childKeys = new LinkedList<>();
  }
  attemptNumber = (Long) entity.getProperty(ATTEMPT_NUM_PROPERTY);
  maxAttempts = (Long) entity.getProperty(MAX_ATTEMPTS_PROPERTY);
  backoffSeconds = (Long) entity.getProperty(BACKOFF_SECONDS_PROPERTY);
  backoffFactor = (Long) entity.getProperty(BACKOFF_FACTOR_PROPERTY);
  queueSettings.setOnBackend((String) entity.getProperty(ON_BACKEND_PROPERTY));
  queueSettings.setOnModule((String) entity.getProperty(ON_MODULE_PROPERTY));
  queueSettings.setModuleVersion((String) entity.getProperty(MODULE_VERSION_PROPERTY));
  queueSettings.setOnQueue((String) entity.getProperty(ON_QUEUE_PROPERTY));
  statusConsoleUrl = (String) entity.getProperty(STATUS_CONSOLE_URL);
  rootJobDisplayName = (String) entity.getProperty(ROOT_JOB_DISPLAY_NAME);
}