1 /* 2 * Copyright (c) 2017 Google Inc. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you 5 * may not use this file except in compliance with the License. You may 6 * obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 * implied. See the License for the specific language governing 14 * permissions and limitations under the License. 15 */ 16 17 package com.android.vts.entity; 18 19 import com.google.appengine.api.datastore.Entity; 20 import com.google.appengine.api.datastore.Key; 21 import com.google.appengine.api.users.User; 22 import java.util.logging.Level; 23 import java.util.logging.Logger; 24 25 /** Entity describing subscriptions between a user and a test. */ 26 public class UserFavoriteEntity implements DashboardEntity { 27 protected static final Logger logger = Logger.getLogger(UserFavoriteEntity.class.getName()); 28 29 public static final String KIND = "UserFavorite"; 30 31 // Property keys 32 public static final String USER = "user"; 33 public static final String TEST_KEY = "testKey"; 34 35 public final User user; 36 public final Key testKey; 37 38 /** 39 * Create a user favorite relationship. 40 * 41 * @param user The User object for the subscribing user. 42 * @param testKey The key of the TestEntity object describing the test. 43 */ 44 public UserFavoriteEntity(User user, Key testKey) { 45 this.user = user; 46 this.testKey = testKey; 47 } 48 49 @Override 50 public Entity toEntity() { 51 Entity favoriteEntity = new Entity(KIND); 52 favoriteEntity.setProperty(USER, this.user); 53 favoriteEntity.setProperty(TEST_KEY, this.testKey); 54 return favoriteEntity; 55 } 56 57 /** 58 * Convert an Entity object to a UserFavoriteEntity. 59 * 60 * @param e The entity to process. 61 * @return UserFavoriteEntity object with the properties from e, or null if incompatible. 62 */ 63 public static UserFavoriteEntity fromEntity(Entity e) { 64 if (!e.getKind().equals(KIND) || !e.hasProperty(USER) || !e.hasProperty(TEST_KEY)) { 65 logger.log( 66 Level.WARNING, "Missing user favorite attributes in entity: " + e.toString()); 67 return null; 68 } 69 try { 70 User user = (User) e.getProperty(USER); 71 Key testKey = (Key) e.getProperty(TEST_KEY); 72 return new UserFavoriteEntity(user, testKey); 73 } catch (ClassCastException exception) { 74 // Invalid cast 75 logger.log(Level.WARNING, "Error parsing user favorite entity.", exception); 76 } 77 return null; 78 } 79 } 80