@SuppressWarnings("VariableDeclarationUsageDistance") @Test public void doGet_repeatedPropertyEntities_writesWidgets() throws Exception { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); // [START exploding_index_example_3] Entity widget = new Entity("Widget"); widget.setProperty("x", Arrays.asList(1, 2, 3, 4)); widget.setProperty("y", Arrays.asList("red", "green", "blue")); widget.setProperty("date", new Date()); datastore.put(widget); // [END exploding_index_example_3] servletUnderTest.doGet(mockRequest, mockResponse); assertThat(responseWriter.toString()) .named("IndexesServlet response") .isEqualTo("Got 1 widgets.\n"); }
/** * Save Full File * * @param inputStream */ private static void saveFile(InputStream inputStream) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Calendar time = Calendar.getInstance(TimeZone.getTimeZone("CET")); time.set(Calendar.HOUR_OF_DAY,0); time.set(Calendar.MINUTE,0); time.set(Calendar.SECOND,0); Date measuredAt = time.getTime(); long millis = time.getTimeInMillis(); // Entity entity = new Entity(ENTITY_TYPE_FICHEROS,millis); entity.setIndexedProperty("Date", measuredAt); entity.setUnindexedProperty("File", GlobalUtils.getString(inputStream)); // Store datastore.put(entity); }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.getWriter().println("<html><body>"); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query query = new Query("SharedList"); query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING); List<Entity> results = datastore.prepare(query).asList( FetchOptions.Builder.withDefaults()); for (Entity entity : results) { String email = (String) entity.getProperty("email"); String productID = (String) entity.getKey().getName(); String productName = (String) entity.getProperty("productName"); Date sharedDate = (Date) entity.getProperty("sharedDate"); resp.getWriter().println( email + " shared <a href=\"http://www.amazon.com/dp/" + productID + "\" target=\"_blank\">" + "<b>" + productName + "</b></a>!<br>"); } resp.getWriter().println("</body></html>"); }
@GET @Produces(MediaType.TEXT_XML) public List<SharedProduct> getEntitiesBrowser() { List<SharedProduct> list = new ArrayList<SharedProduct>(); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query query = new Query("SharedList"); query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING); List<Entity> results = datastore.prepare(query).asList( FetchOptions.Builder.withDefaults()); for (Entity entity : results) { String email = (String) entity.getProperty("email"); String productID = (String) entity.getKey().getName(); String productName = (String) entity.getProperty("productName"); Date sharedDate = (Date) entity.getProperty("sharedDate"); list.add(new SharedProduct(email, productID, productName, sharedDate)); } return list; }
@GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public List<SharedProduct> getEntities() { List<SharedProduct> list = new ArrayList<SharedProduct>(); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query query = new Query("SharedList"); query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING); List<Entity> results = datastore.prepare(query).asList( FetchOptions.Builder.withDefaults()); for (Entity entity : results) { String email = (String) entity.getProperty("email"); String productID = (String) entity.getKey().getName(); String productName = (String) entity.getProperty("productName"); Date sharedDate = (Date) entity.getProperty("sharedDate"); list.add(new SharedProduct(email, productID, productName, sharedDate)); } return list; }
@POST @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void newSharedProduct(@FormParam("productID") String productID, @FormParam("productName") String productName, @Context HttpServletResponse servletResponse) throws Exception { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user == null) { System.out.println("Login first"); return; } DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Entity entity = new Entity("SharedList", productID); entity.setProperty("email", user.getEmail()); entity.setProperty("productName", productName); entity.setProperty("sharedDate", new Date()); datastore.put(entity); servletResponse.getWriter().println(productName + " has been added."); servletResponse.flushBuffer(); }
@POST @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_JSON) public void newSharedProduct(SharedProduct product, @Context HttpServletResponse servletResponse) throws Exception { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user == null) { System.out.println("Login first"); return; } DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Entity entity = new Entity("SharedList", product.getProductID()); entity.setProperty("email", user.getEmail()); entity.setProperty("productName", product.getProductName()); entity.setProperty("sharedDate", product.getSharedDate()); datastore.put(entity); servletResponse.getWriter().println( product.getProductName() + " has been added."); servletResponse.flushBuffer(); }
@GET @Produces(MediaType.TEXT_XML) public WishlistProduct getHTML() { DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); try { Key entKey = KeyFactory.createKey(email, productID); Entity entity = datastore.get(entKey); String productName = (String) entity.getProperty("productName"); double currentPrice = (double) entity.getProperty("currentPrice"); double lowestPrice = (double) entity.getProperty("lowestPrice"); Date lowestDate = (Date) entity.getProperty("lowestDate"); return new WishlistProduct(productID, productName, currentPrice, lowestPrice, lowestDate); } catch (EntityNotFoundException e) { throw new RuntimeException("GET: Wishlist with " + productID + " not found."); } }
@GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public WishlistProduct get() { DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); try { Key entKey = KeyFactory.createKey(email, productID); Entity entity = datastore.get(entKey); String productName = (String) entity.getProperty("productName"); double currentPrice = (double) entity.getProperty("currentPrice"); double lowestPrice = (double) entity.getProperty("lowestPrice"); Date lowestDate = (Date) entity.getProperty("lowestDate"); return new WishlistProduct(productID, productName, currentPrice, lowestPrice, lowestDate); } catch (EntityNotFoundException e) { throw new RuntimeException("GET: Wishlist with " + productID + " not found."); } }
@Test public void testJobIdAndNumJobs_fails() throws Exception { action = new MapreduceEntityCleanupAction( Optional.of("jobid"), Optional.empty(), // jobName Optional.of(1), // numJobsToDelete Optional.empty(), // daysOld Optional.empty(), // force mapreduceEntityCleanupUtil, clock, DatastoreServiceFactory.getDatastoreService(), response); action.run(); assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); assertThat(response.getContentType()).isEqualTo(PLAIN_TEXT_UTF_8); assertThat(response.getPayload()) .isEqualTo("Do not specify both a job ID and a number of jobs to delete"); assertNumMapreducesAndShardedJobs(0, 0); }
@Test public void testDeleteZeroJobs_throwsUsageError() throws Exception { new MapreduceEntityCleanupAction( Optional.empty(), // jobId Optional.empty(), // jobName Optional.of(0), // numJobsToDelete Optional.empty(), // daysOld Optional.empty(), // force mapreduceEntityCleanupUtil, clock, DatastoreServiceFactory.getDatastoreService(), response) .run(); assertThat(response.getStatus()).isEqualTo(SC_BAD_REQUEST); assertThat(response.getPayload()) .isEqualTo("Do not specify a non-positive integer for the number of jobs to delete"); }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String guestbookName = req.getParameter("guestbookName"); Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName); String content = req.getParameter("content"); Date date = new Date(); Entity greeting = new Entity("Greeting", guestbookKey); if (user != null) { greeting.setProperty("author_id", user.getUserId()); greeting.setProperty("author_email", user.getEmail()); } greeting.setProperty("date", date); greeting.setProperty("content", content); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(greeting); resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Error error = Error.NONE; String jsonEnd = HtmlVariable.AVAILABLE.getName(); String userId = req.getParameter(HtmlVariable.USER_ID.getName()); if(userId == null || userId.length() == 0) { error = Error.REQUIRED_USER_ID; jsonEnd = jsonEnd + "\": false }"; } else { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); User user = UserFactory.getByUserId(datastore, null, userId); jsonEnd = (user != null) ? jsonEnd + "\": false }" : jsonEnd + "\": true }"; } String jsonStart = "{ \"" + HtmlVariable.ERROR.getName() + "\": " + error.toString() + ", \""; resp.setContentType("application/json; charset=UTF-8"); resp.getWriter().print(jsonStart + jsonEnd); }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String guestbookName = req.getParameter("guestbookName"); Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName); String content = req.getParameter("content"); Date date = new Date(); Entity greeting = new Entity("Greeting", guestbookKey); greeting.setProperty("user", user); greeting.setProperty("date", date); greeting.setProperty("content", content); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); datastore.put(greeting); resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName); }
@Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch(EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, API_KEY); datastore.put(entity); mLogger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); }
/** * Returns the Account key associated with the specified authorization key. * @param pm reference to the persistence manager * @param authorizationKey authorization key to return the account key for * @return the Account key associated with the specified authorization key; or <code>null</code> if the authorization key is invalid */ public static Key getAccountKeyByAuthKey( final PersistenceManager pm, final String authorizationKey ) { final String memcacheKey = CACHE_KEY_AUTH_KEY_ACCOUNT_KEY_PREFIX + authorizationKey; final String accountKeyString = (String) memcacheService.get( memcacheKey ); if ( accountKeyString != null ) return KeyFactory.stringToKey( accountKeyString ); final Query q = new Query( Account.class.getSimpleName() ); q.setFilter( new FilterPredicate( "authorizationKey", FilterOperator.EQUAL, authorizationKey ) ); q.setKeysOnly(); final List< Entity > entityList = DatastoreServiceFactory.getDatastoreService().prepare( q ).asList( FetchOptions.Builder.withDefaults() ); if ( entityList.isEmpty() ) return null; final Key accountKey = entityList.get( 0 ).getKey(); try { memcacheService.put( memcacheKey, KeyFactory.keyToString( accountKey ) ); } catch ( final MemcacheServiceException mse ) { LOGGER.log( Level.WARNING, "Failed to put key to memcache: " + memcacheKey, mse ); // Ignore memcache errors, do not prevent serving user request } return accountKey; }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); helper.setUp(); ds = DatastoreServiceFactory.getDatastoreService(); // Set up some fake HTTP requests when(mockRequest.getRequestURI()).thenReturn(FAKE_URL); when(mockRequest.getParameter("guestbookName")).thenReturn("default"); when(mockRequest.getParameter("content")).thenReturn(testPhrase); stringWriter = new StringWriter(); when(mockResponse.getWriter()).thenReturn(new PrintWriter(stringWriter)); servletUnderTest = new SignGuestbookServlet(); ObjectifyService.register(Guestbook.class); ObjectifyService.register(Greeting.class); closeable = ObjectifyService.begin(); cleanDatastore(ds, "default"); }
@Test public void doGet_repeatedPropertyEntities_writesWidgets() throws Exception { //CHECKSTYLE.OFF: VariableDeclarationUsageDistance - readability DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); //CHECKSTYLE.ON: VariableDeclarationUsageDistance // [START exploding_index_example_3] Entity widget = new Entity("Widget"); widget.setProperty("x", Arrays.asList(1, 2, 3, 4)); widget.setProperty("y", Arrays.asList("red", "green", "blue")); widget.setProperty("date", new Date()); datastore.put(widget); // [END exploding_index_example_3] servletUnderTest.doGet(mockRequest, mockResponse); assertThat(responseWriter.toString()) .named("IndexesServlet response") .isEqualTo("Got 1 widgets.\n"); }
@Test public void crossGroupTransactions() throws Exception { // [START cross-group_XG_transactions_using_the_Java_low-level_API] DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); TransactionOptions options = TransactionOptions.Builder.withXG(true); Transaction txn = datastore.beginTransaction(options); Entity a = new Entity("A"); a.setProperty("a", 22); datastore.put(txn, a); Entity b = new Entity("B"); b.setProperty("b", 11); datastore.put(txn, b); txn.commit(); // [END cross-group_XG_transactions_using_the_Java_low-level_API] }
@Test public void kindExample_writesEntity() throws Exception { //CHECKSTYLE.OFF: VariableDeclarationUsageDistance - Increased clarity in sample // [START kind_example] DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity employee = new Entity("Employee", "asalieri"); employee.setProperty("firstName", "Antonio"); employee.setProperty("lastName", "Salieri"); employee.setProperty("hireDate", new Date()); employee.setProperty("attendedHrTraining", true); datastore.put(employee); // [END kind_example] //CHECKSTYLE.ON: VariableDeclarationUsageDistance Entity got = datastore.get(employee.getKey()); assertThat((String) got.getProperty("firstName")).named("got.firstName").isEqualTo("Antonio"); assertThat((String) got.getProperty("lastName")).named("got.lastName").isEqualTo("Salieri"); assertThat((Date) got.getProperty("hireDate")).named("got.hireDate").isNotNull(); assertThat((boolean) got.getProperty("attendedHrTraining")) .named("got.attendedHrTraining") .isTrue(); }
/** * A simple API client. * @param args . * @throws IOException . */ public static void main(String[] args) throws IOException { String serverString = args[0]; RemoteApiOptions options; if (serverString.equals("localhost")) { options = new RemoteApiOptions().server(serverString, 8080).useDevelopmentServerCredential(); } else { options = new RemoteApiOptions().server(serverString, 443).useApplicationDefaultCredential(); } RemoteApiInstaller installer = new RemoteApiInstaller(); installer.install(options); try { DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); System.out.println("Key of new entity is " + ds.put(new Entity("Hello Remote API!"))); } finally { installer.uninstall(); } }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); helper.setUp(); datastore = DatastoreServiceFactory.getDatastoreService(); // Add test data. ImmutableList.Builder<Entity> people = ImmutableList.builder(); for (String name : TEST_NAMES) { people.add(createPerson(name)); } datastore.put(people.build()); // Set up a fake HTTP response. responseWriter = new StringWriter(); when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter)); servletUnderTest = new ListPeopleServlet(); }
@Test public void creatingAnEntityInASpecificEntityGroup() throws Exception { String boardName = "my-message-board"; // [START creating_an_entity_in_a_specific_entity_group] DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); String messageTitle = "Some Title"; String messageText = "Some message."; Date postDate = new Date(); Key messageBoardKey = KeyFactory.createKey("MessageBoard", boardName); Entity message = new Entity("Message", messageBoardKey); message.setProperty("message_title", messageTitle); message.setProperty("message_text", messageText); message.setProperty("post_date", postDate); Transaction txn = datastore.beginTransaction(); datastore.put(txn, message); txn.commit(); // [END creating_an_entity_in_a_specific_entity_group] }
@Test public void readPolicy_strong_returnsAllResults() { double deadline = 5.0; ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG); DatastoreServiceConfig datastoreConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy).deadline(deadline); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(datastoreConfig); Entity parent = new Entity("Person", "a"); Entity child = new Entity("Person", "b", parent.getKey()); datastore.put(ImmutableList.<Entity>of(parent, child)); Query q = new Query("Person").setAncestor(parent.getKey()); List<Entity> results = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); assertThat(results).named("query results").hasSize(2); }
@Override public void map(Entity entity) { System.out.println(entity); Long lastModificationDate = (Long) entity.getProperty("lastModificationDate"); if (lastModificationDate == null) { final DatastoreService dss = DatastoreServiceFactory.getDatastoreService(); entity.setProperty("lastModificationDate", System.currentTimeMillis()); dss.put(entity); } // incrementCounter("total entities", 1); // incrementCounter("map calls in shard " + getContext().getShardNumber(), 1); // // String name = entity.getKey().getName(); // if (name != null) { // incrementCounter("total entity key size", name.length()); // emitCharacterCounts(name); // } // // Text property = (Text) entity.getProperty("payload"); // if (property != null) { // incrementCounter("total entity payload size", property.getValue().length()); // emitCharacterCounts(property.getValue()); // } }
private ArrayList<Medicion> getLastStatus(int amountData) { // Poner Key estacion + hora_muestra Calendar calendarTwoAgo = Calendar.getInstance(TimeZone.getTimeZone("CET")); calendarTwoAgo.add(Calendar.DATE, -3); Date dateTwoAgo = calendarTwoAgo.getTime(); // Prepare Query.Filter keyFilter = new Query.FilterPredicate(PROPERTY_MEASURE_DATE, Query.FilterOperator.GREATER_THAN, dateTwoAgo); Query.Filter no2Filter = new Query.FilterPredicate(PROPERTY_COMPUESTO, Query.FilterOperator.EQUAL, NO2.name()); List<Query.Filter> filterList = new ArrayList<>(); filterList.add(keyFilter); filterList.add(no2Filter); Query.Filter filter = new Query.CompositeFilter(Query.CompositeFilterOperator.AND, filterList); Query query = new Query(ENTITY_TYPE_MEDIDAS) .setFilter(filter) .addSort(PROPERTY_MEASURE_DATE , Query.SortDirection.DESCENDING); // Query DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); PreparedQuery pq = datastore.prepare(query); // Get results List<com.google.appengine.api.datastore.Entity> resultList = pq.asList(FetchOptions.Builder.withLimit(amountData)); ArrayList<Medicion> result = new ArrayList<>(); if (resultList.size()!=0) { mLogger.info("Watching " + resultList.size() + " last values of ESTADO"); for (com.google.appengine.api.datastore.Entity item : resultList){ result.add(new Medicion((Date) item.getProperty(PROPERTY_MEASURE_DATE), (String) item.getProperty(PROPERTY_AVISO), (String) item.getProperty(PROPERTY_AVISO_STATE), (String) item.getProperty(PREPERTY_AVISO_MAX_TODAY), (String) item.getProperty(PROPERTY_ESCENARIO_STATE_TODAY), (String) item.getProperty(PROPERTY_ESCENARIO_STATE_TOMORROW), (String) item.getProperty(PROPERTY_ESCENARIO_STATE_TOMORROW_MANUAL) ,isPureMadrid())); } } else { // No hay datos mLogger.info("No previous values for ESTADO"); } return result; }
/** * Gets the access key. */ protected String getKey() { com.google.appengine.api.datastore.DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); String apiKey = ""; try { Entity entity = datastore.get(key); apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD); } catch (EntityNotFoundException e) { mLogger.severe("Exception will retrieving the API Key" + e.toString()); } return apiKey; }
public Iterable<Entity> listRawEntity(Query q, Boolean returnKeysOnly) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); if (returnKeysOnly) { q.setKeysOnly(); } PreparedQuery pq = datastore.prepare(q); return pq.asIterable(); }
public void deleteAllObjects(Query query){ final DatastoreService dss=DatastoreServiceFactory.getDatastoreService(); final ArrayList<Key> keys=new ArrayList<>(); for ( final Entity entity : dss.prepare(query).asIterable(FetchOptions.Builder.withLimit(100000))) { keys.add(entity.getKey()); } dss.delete(keys); }
private static void reboxUnscheduledMessagesForCurrentUserAfterAuth(String userId) throws IOException { final Scheduler scheduler = new Scheduler(userId); final DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); final Iterable<Entity> toBeProcessedScheduledMailsForCurrentUser = EntityHelper.getToBeProcessedScheduledMailsForUser(ds, userId); final List<String> scheduledMailIds = new ArrayList<String>(); for (final Entity scheduledMail : toBeProcessedScheduledMailsForCurrentUser) { scheduledMailIds.add((String) scheduledMail.getProperty(EntityConstants.ScheduledMail.Property.MAIL_ID)); } scheduler.reboxUnscheduledMessagesWithOutboxLabel(scheduledMailIds); }
@Provides DatastoreService provideDatastore(@DatastoreTimeoutMillis long datastoreTimeoutMillis) { return DatastoreServiceFactory.getDatastoreService(DatastoreServiceConfig.Builder .withDeadline(datastoreTimeoutMillis * 1000.0) .implicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.NONE) .readPolicy(new ReadPolicy(ReadPolicy.Consistency.STRONG))); }
@GET @Produces(MediaType.TEXT_XML) public List<WishlistProduct> getEntitiesBrowser() { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user == null) { System.out.println("Login first"); return null; } List<WishlistProduct> list = new ArrayList<WishlistProduct>(); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query query = new Query(user.getEmail()); query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING); List<Entity> results = datastore.prepare(query).asList( FetchOptions.Builder.withDefaults()); for (Entity entity : results) { String productID = (String) entity.getKey().getName(); String productName = (String) entity.getProperty("productName"); double currentPrice = (double) entity.getProperty("currentPrice"); double lowestPrice = (double) entity.getProperty("lowestPrice"); Date lowestDate = (Date) entity.getProperty("lowestDate"); list.add(new WishlistProduct(productID, productName, currentPrice, lowestPrice, lowestDate)); } return list; }
@GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public List<WishlistProduct> getEntities() { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user == null) { System.out.println("Login first"); return null; } List<WishlistProduct> list = new ArrayList<WishlistProduct>(); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query query = new Query(user.getEmail()); query.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.ASCENDING); List<Entity> results = datastore.prepare(query).asList( FetchOptions.Builder.withDefaults()); for (Entity entity : results) { String productID = (String) entity.getKey().getName(); String productName = (String) entity.getProperty("productName"); double currentPrice = (double) entity.getProperty("currentPrice"); double lowestPrice = (double) entity.getProperty("lowestPrice"); Date lowestDate = (Date) entity.getProperty("lowestDate"); list.add(new WishlistProduct(productID, productName, currentPrice, lowestPrice, lowestDate)); } return list; }
@POST @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_JSON) public void newWishlistProductJson(WishlistProduct product, @Context HttpServletResponse servletResponse) throws Exception { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user == null) { System.out.println("Login first"); return; } DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); Entity entity = new Entity(user.getEmail(), product.getProductID()); entity.setProperty("productName", product.getProductName()); entity.setProperty("currentPrice", product.getCurrentPrice()); entity.setProperty("lowestPrice", product.getLowestPrice()); entity.setProperty("lowestDate", new Date()); datastore.put(entity); syncCache.put(product.getProductID(), product.getCurrentPrice()); servletResponse.getWriter().println("<html><head>"); servletResponse .getWriter() .println( "<meta http-equiv=\"refresh\" content=\"3;url=/wishlist.jsp\" />"); servletResponse.getWriter().println("</head><body>"); servletResponse.getWriter() .println( "<h1>" + product.getProductName() + " has been added.</h1><br>"); servletResponse .getWriter() .println( "<h2>Redirecting in 3 seconds...</h2> <a href=\"/wishlist.jsp\">Go back now</a>"); servletResponse.getWriter().println("</body></html>"); servletResponse.flushBuffer(); return; }