@Test public void updateFieldInEntity() throws EntityNotFoundException { Entity person = new Entity("Person"); person.setProperty("firstName", "Ivan"); person.setProperty("age", 22l); Key key = datastore.put(person); // Start transaction Transaction transaction = datastore.beginTransaction(); try { Entity result = datastore.get(key); result.setProperty("age", 30l); datastore.put(result); transaction.commit(); } finally { if (transaction.isActive()) { transaction.rollback(); } } Entity result = datastore.get(key); assertThat("Ivan", is(equalTo(result.getProperty("firstName")))); assertThat(30l, is(equalTo(result.getProperty("age")))); }
@PUT @Consumes(MediaType.APPLICATION_XML) public Response putTaskData(String value) { Response res = null; // add your code here // first check if the Entity exists in the datastore DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); Key entKey = KeyFactory.createKey("TaskData", keyname); Date date = new Date(); try { // if it is, signal that we updated the entity Entity ts = datastore.get(entKey); ts.setProperty("value", value); ts.setProperty("date", date); datastore.put(ts); res = Response.noContent().build(); } catch (EntityNotFoundException e) { // if it is not, create it and // signal that we created the entity in the datastore Entity taskdata = new Entity("TaskData", keyname); taskdata.setProperty("value", value); taskdata.setProperty("date", date); datastore.put(taskdata); res = Response.created(uriInfo.getAbsolutePath()).build(); } TaskData td = new TaskData(keyname, value, date); syncCache.put(keyname, td); return res; }
@Test public void transactionsOnVariusTypesOfEntities() throws EntityNotFoundException { Entity person = new Entity("Person", "tom"); datastore.put(person); // Transaction on root entities Transaction transaction = datastore.beginTransaction(); Entity tom = datastore.get(person.getKey()); tom.setProperty("age", 40); datastore.put(tom); transaction.commit(); // Transaction on child entities transaction = datastore.beginTransaction(); tom = datastore.get(person.getKey()); // Create a Photo entity that is a child of Person entity named "tom" Entity photo = new Entity("Photo", tom.getKey()); photo.setProperty("photoUrl", "images/photo"); datastore.put(photo); transaction.commit(); // Transaction on entities in different entity groups transaction = datastore.beginTransaction(); Entity photoNotChild = new Entity("Photo"); photoNotChild.setProperty("photoUrl", "images/photo"); datastore.put(photoNotChild); transaction.commit(); }
private void doRecordAction(JsonValues values, PrintWriter writer) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Gson gson = new Gson(); // First try to see if we've seen this deck before Filter keyFilter = new FilterPredicate( Entity.KEY_RESERVED_PROPERTY, FilterOperator.EQUAL, KeyFactory.createKey("Record", gson.toJson(values.deck))); Query q = new Query("Record").setFilter(keyFilter); PreparedQuery pq = datastore.prepare(q); int count = pq.countEntities(FetchOptions.Builder.withDefaults()); if (count == 0) { // First time we've seen this deck datastore.put(jsonValuesToEntity(values)); } else if (count == 1) { // We've seen this deck before Entity record = pq.asIterable().iterator().next(); String ratingKey = getRatingKey(values); long ratingValue = 1; if (record.hasProperty(ratingKey)) { ratingValue = (long) record.getProperty(ratingKey) + 1; } record.setProperty(ratingKey, ratingValue); datastore.put(record); } else { throw new RuntimeException("deck present in store multiple times!"); } writer.println("SUCCESS!"); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // super.doPost(req, resp); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Gson gson = new Gson(); Plan pl = gson.fromJson(req.getParameter("PARAM"), Plan.class); Entity plan = new Entity("Plan"); plan.setProperty("title", pl.getTitle()); plan.setProperty("description", pl.getDesc()); plan.setProperty("domain", pl.getDomain()); plan.setProperty("totalLength", pl.getTotalTime()); System.out.println(pl.getTotalTime()); Key planKey = datastore.put(plan); List<Exercise> listEx = pl.getExercises(); Entity exercise; for (Exercise ex : listEx) { exercise = new Entity("Exercise", planKey); exercise.setProperty("title", ex.getTitle()); exercise.setProperty("description", ex.getDesc()); String length = ex.getLength(); String[] splitStr = length.split(":"); Integer seconds = Integer.parseInt(splitStr[0]) * 60 + Integer.parseInt(splitStr[1]); exercise.setProperty("length", seconds); exercise.setProperty("row", ex.getRow()); datastore.put(exercise); } }
public Key store(Key orig, String type, long storeDate) { // long start = System.currentTimeMillis(); final int MAXSIZE = 1000000; Entity ent; Key next = null; this.storeTime = storeDate; this.nanoTime = System.nanoTime(); byte[] data = this.serialize(); Integer length = data.length; int pointer = 0; // int counter = 0; while (length - pointer >= MAXSIZE) { // Expensive, should not be used too much! ent = new Entity(type + "_fragment"); ent.setUnindexedProperty( "payload", new Blob(Arrays.copyOfRange(data, pointer, pointer + MAXSIZE))); if (next != null) ent.setUnindexedProperty("next", next); datastore.put(ent); // counter++; next = ent.getKey(); pointer += MAXSIZE; } if (orig != null) { System.err.println( "Warning, storing storable twice! Strange, should not happen with our immutable structures."); ent = new Entity(orig); } else { ent = new Entity(type); } ent.setUnindexedProperty("payload", new Blob(Arrays.copyOfRange(data, pointer, length))); if (next != null) ent.setUnindexedProperty("next", next); ent.setProperty("timestamp", this.storeTime); ent.setProperty("size", length); ent.setProperty("spread", this.spread); datastore.put(ent); // counter++; myKey = ent.getKey(); // Try to force index writing try { datastore.get(myKey); } catch (EntityNotFoundException e) { } this.storedSize = length; // System.out.println("Just stored shard of "+length+ " bytes in "+counter+" fragments in // "+(System.currentTimeMillis()-start)+" ms"); return myKey; }
@Test public void testInSameEntityGroup() { Entity ancestor = new Entity("foo"); ds.put(ancestor); Entity e1 = new Entity("bar", ancestor.getKey()); ds.put(e1); Entity e2 = new Entity("baz", "Bob", e1.getKey()); Entity e3 = new Entity("foo"); ds.put(Lists.newArrayList(e2, e3)); assertTrue(EntityUtil.inSameEntityGroup(ancestor, e1, e2)); assertFalse(EntityUtil.inSameEntityGroup(ancestor, e1, e2, e3)); }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String userName = req.getParameter("name"); String comment = req.getParameter("comment"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); if (userName != null && comment != null) { Entity commentEntity = new Entity("Comment", guestbookKey); commentEntity.setProperty("name", userName); commentEntity.setProperty("comment", comment); datastore.put(commentEntity); } Query query = new Query("Comment", guestbookKey); List<Entity> comments = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()); // System.out.println(); req.setAttribute("comments", comments); String url = "/guestBook.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(req, resp); }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); String keyStr = "PushInfo"; Key pushKey = KeyFactory.createKey("PushInfo", keyStr); String sellerID = req.getParameter("sellerID"); String ID = req.getParameter("ID"); String title = req.getParameter("sellerTitle"); String number = req.getParameter("number"); Date date = new Date(); Entity entity = new Entity("PushInfo", pushKey); entity.setProperty("sellerID", sellerID); entity.setProperty("ID", ID); entity.setProperty("title", title); entity.setProperty("date", date); entity.setProperty("number", number); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(entity); resp.getWriter().print("succeed save pushInfo"); }
/** * 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 }
@InSequence(10) @Test @OperateOnDeployment("dep1") public void insertIntoBlobstoreOnDep1() throws Exception { BlobstoreService service = BlobstoreServiceFactory.getBlobstoreService(); FileService fileService = FileServiceFactory.getFileService(); AppEngineFile file = fileService.createNewBlobFile("text/plain", "uploadedText.txt"); FileWriteChannel channel = fileService.openWriteChannel(file, true); try { channel.write(ByteBuffer.wrap(TEXT.getBytes())); } finally { channel.closeFinally(); } waitForSync(); BlobKey blobKey = fileService.getBlobKey(file); System.out.println("Blob key: " + blobKey); byte[] bytes = service.fetchData(blobKey, 0, Long.MAX_VALUE); Assert.assertEquals(TEXT, new String(bytes)); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity dsBK = new Entity("blobTestId", 1); dsBK.setProperty("blogId", blobKey.getKeyString()); ds.put(dsBK); waitForSync(); }
public void create(ContactForm cf) { Entity e = Util.contactFormToEntity(cf); txn = ds.beginTransaction(); ds.put(e); txn.commit(); }
public static String verifyToken(String token) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Transaction txn = datastore.beginTransaction(); try { Query searchToken = new Query("Token").addFilter("token", FilterOperator.EQUAL, token); Entity tokenEntity = datastore.prepare(searchToken).asSingleEntity(); if (null == tokenEntity) { log.warn("Token {} not found - error", token); return null; } log.info("Updating token"); tokenEntity.setProperty("accessed", new Date().getTime()); datastore.put(txn, tokenEntity); txn.commit(); log.info("Token OK"); Entity userEntity = datastore.get((Key) tokenEntity.getProperty("user")); return (String) userEntity.getProperty("username"); } catch (Exception e) { log.error("Token error", e); return null; } finally { if (txn.isActive()) { txn.rollback(); } } }
/** * This method is used for updating an existing entity. If the entity does not exist in the * datastore, an exception is thrown. It uses HTTP PUT method. * * @param store the entity to be updated. * @return The updated entity. * @throws UnauthorizedException */ @ApiMethod( name = "modify", scopes = {Config.EMAIL_SCOPE}, clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID}) public ServiceResponse modify( @Named("_name") String _name, @Named("_id") Long _id, ServiceRequest req, User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("UnauthorizedException # User is Null."); } Key key = KeyFactory.createKey(_name, _id); Date currentDate = new Date(); String userEmail = user.getEmail(); DatastoreService dsService = DatastoreServiceFactory.getDatastoreService(); ServiceResponse res = new ServiceResponse(); try { Entity entity = dsService.get(key); entity.setProperty(_updatedAt, currentDate); entity.setProperty(_updatedBy, userEmail); entity.setUnindexedProperty(data, new Text(req.getData())); dsService.put(entity); res.set_id(entity.getKey().getId()); } catch (com.google.appengine.api.datastore.EntityNotFoundException e) { throw new EntityNotFoundException("Object does not exist."); } return res; }
private ServiceResponse updateStatus(String _name, Long _id, String _status, User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("UnauthorizedException # User is Null."); } Key key = KeyFactory.createKey(_name, _id); Date currentDate = new Date(); String userEmail = user.getEmail(); DatastoreService dsService = DatastoreServiceFactory.getDatastoreService(); ServiceResponse res = new ServiceResponse(); try { Entity entity = dsService.get(key); entity.setProperty(_updatedAt, currentDate); entity.setProperty(_updatedBy, userEmail); entity.setProperty(_status, _status); dsService.put(entity); res.set_id(entity.getKey().getId()); } catch (com.google.appengine.api.datastore.EntityNotFoundException e) { throw new EntityNotFoundException("Object does not exist"); } return res; }
/** * This inserts a new entity into App Engine datastore. If the entity already exists in the * datastore, an exception is thrown. It uses HTTP POST method. * * @param req the entity to be inserted. * @return The inserted entity. * @throws UnauthorizedException */ @ApiMethod( name = "add", scopes = {Config.EMAIL_SCOPE}, clientIds = {Config.CHROME_CLIENT_ID, Config.WEB_CLIENT_ID, Config.API_EXPLORER_CLIENT_ID}) public ServiceResponse add(@Named("_name") String _name, ServiceRequest req, User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("UnauthorizedException # User is Null."); } else if (req == null || req.getData() == null) { return null; } String userEmail = user.getEmail(); Date currentDate = new Date(); DatastoreService dsService = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity(_name); entity.setProperty(_createdAt, currentDate); entity.setProperty(_createdBy, userEmail); entity.setProperty(_updatedAt, currentDate); entity.setProperty(_updatedBy, userEmail); entity.setProperty(_status, ACTIVE); entity.setUnindexedProperty(data, new Text(req.getData())); dsService.put(entity); ServiceResponse res = new ServiceResponse(); res.set_id(entity.getKey().getId()); return res; }
public static void employeeLogin(Employee employee) { Entity loginEntity = new Entity("Login", employee.getEmployeeId()); loginEntity.setProperty("EmployeeId", employee.getEmployeeId()); loginEntity.setProperty("UserName", employee.getEmail()); loginEntity.setProperty("Password", employee.getFirstName() + 123); datastore.put(loginEntity); }
public static void employeeAddress(Employee employee) { Entity addressEntity = new Entity("Address", employee.getEmployeeId()); addressEntity.setProperty("EmployeeId", employee.getEmployeeId()); addressEntity.setProperty("Email", employee.getEmail()); addressEntity.setProperty("City", employee.getAddress().getCity()); addressEntity.setProperty("State", employee.getAddress().getState()); datastore.put(addressEntity); }
@Test public void crossGroupTransactions() { TransactionOptions transactionOptions = TransactionOptions.Builder.withXG(true); Transaction transaction = datastore.beginTransaction(transactionOptions); Entity a = new Entity("A"); datastore.put(a); Entity b = new Entity("B", a.getKey()); datastore.put(b); Entity c = new Entity("C", a.getKey()); datastore.put(c); Entity d = new Entity("D"); datastore.put(d); Entity e = new Entity("E"); datastore.put(e); Entity f = new Entity("F"); datastore.put(f); Entity z = new Entity("Z"); datastore.put(z); transaction.commit(); }
public void saveUser(HttpServletRequest req) { Entity e = new Entity("User"); e.setProperty("firstname", req.getParameter("fName")); e.setProperty("lastname", req.getParameter("lName")); e.setProperty("mail", req.getParameter("email")); e.setProperty("pass", req.getParameter("password")); e.setProperty("ph", req.getParameter("phone")); ds.put(e); }
/** * Adds an Entity passed in * * @return boolean indicating success */ public static Key addEntity(Entity entity) { Key key = null; ds.put(entity); key = entity.getKey(); return key; }
public static boolean saveEntity(Entity entity) { try { ds.put(entity); return true; } catch (Exception e) { return false; } }
private static void generateScenery( String mapId, int x, int y, int nx, int ny, DatastoreService store) { if (x != nx && y != ny && x != y) { // Clear the diagonal line for escape Entity obstacle = new Entity(Transport.SCENERY); obstacle.setProperty("x", x); obstacle.setProperty("y", y); obstacle.setProperty("map", mapId); store.put(obstacle); } }
public static Key save(File f, Owner owner) { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity("File", PathHelper.getStorageKey(f.getPath(), owner)); entity = ReflectionHelper.setPropertiesToEntity(File.class, f, entity); Key k = ds.put(entity); return k; }
public static void employeeLeave(Employee employee) { final int LOPDays = 0; Entity leaveEntity = new Entity("Leave", employee.getEmployeeId()); leaveEntity.setProperty("EmployeeId", employee.getEmployeeId()); leaveEntity.setProperty("Email", employee.getEmail()); leaveEntity.setProperty("LeaveBalance", employee.getLeaveBalance()); leaveEntity.setProperty("LOPDays", LOPDays); datastore.put(leaveEntity); }
public static String authorizeUser(String username, String password, String token) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Transaction txn = datastore.beginTransaction(); try { String uName = username.toLowerCase().trim(); String pass = passwordToHash(password); Query existing = new Query("User").addFilter("username", FilterOperator.EQUAL, uName); Entity user = datastore.prepare(existing).asSingleEntity(); if (null == user) { log.info("User {} isn't exists - creating", uName); user = new Entity("User"); user.setProperty("username", uName); user.setProperty("password", pass); user.setProperty("created", new Date().getTime()); datastore.put(txn, user); txn.commit(); txn = datastore.beginTransaction(); } log.info("Checking password for entity: {}", user.getKey()); if (!pass.equals(user.getProperty("password"))) { log.warn("Password in incorrect for user " + uName + ": " + pass); return "Password is incorrect"; } log.info("Storing token"); Entity tokenEntity = new Entity("Token", user.getKey()); tokenEntity.setProperty("token", token); tokenEntity.setProperty("user", user.getKey()); tokenEntity.setProperty("issued", new Date().getTime()); tokenEntity.setProperty("accessed", new Date().getTime()); datastore.put(txn, tokenEntity); txn.commit(); log.info("Token created"); return null; } catch (Exception e) { log.error("Users error", e); return "DB error"; } finally { if (txn.isActive()) { txn.rollback(); } } }
/** * Add an Entity by details * * @return Key - key of the newly added event */ public static Key addEntity(String kind) { Key key = null; Entity event = new Entity(kind); ds.put(event); key = event.getKey(); return key; }
@Override public void save(Company company) { Entity companyEntity = new Entity(CompanyEntity.KIND); companyEntity.setProperty(CompanyEntity.NAME, company.getName()); companyEntity.setProperty(CompanyEntity.ADDRESS, company.getAddress()); companyEntity.setProperty(CompanyEntity.ACTIVITY, company.getActivity()); companyEntity.setProperty(CompanyEntity.LOCATION, company.getLocation()); companyEntity.setProperty(CompanyEntity.EMAIL, company.getEmail()); service.put(companyEntity); }
public static void storeString(String id, String text) { Entity entity = getEntity(id); if (entity == null) entity = new Entity("storedString"); // log.warning("store :"+id+" : "+entity.getKey()); entity.setProperty("id", id); entity.setUnindexedProperty("string", new Text(text)); datastore.put(entity); syncCache.put(id, entity); }
@Override public void addDataObj(DataObj dataObj) { Entity item = new Entity("DataObj"); item.setProperty("deviceId", dataObj.getDeviceId()); item.setProperty("longCord", dataObj.getLongCord()); item.setProperty("latCord", dataObj.getLatCord()); item.setProperty("value", dataObj.getValue()); item.setProperty("time", dataObj.getTime()); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(item); }