Java Code Examples for com.google.appengine.api.users.User#getUserId()

The following examples show how to use com.google.appengine.api.users.User#getUserId() . 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: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example 2
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example 3
Source File: RegistryLockGetActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_linkedToContactEmail() {
  // Even though the user is [email protected] the contact is still Marla Singer
  user = new User("[email protected]", "gmail.com", user.getUserId());
  authResult = AuthResult.create(AuthLevel.USER, UserAuthInfo.create(user, false));
  action =
      new RegistryLockGetAction(
          Method.GET, response, accessor, authResult, Optional.of("TheRegistrar"));
  action.run();
  assertThat(GSON.fromJson(response.getPayload(), Map.class).get("results"))
      .isEqualTo(
          ImmutableList.of(
              ImmutableMap.of(
                  "lockEnabledForContact",
                  true,
                  "email",
                  "[email protected]",
                  "clientId",
                  "TheRegistrar",
                  "locks",
                  ImmutableList.of())));
}
 
Example 4
Source File: SkillServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Validate inputs of SkillResponse.
 *
 * @param skill inputs to be validate
 * @param user info about user from google
 *
 * @throws BadRequestException for the validations.
 * @throws InternalServerErrorException in case something goes wrong
 * @throws NotFoundException in case the information are not founded
 */
private void validateInputs(Skill skill, User user)
    throws BadRequestException, NotFoundException, InternalServerErrorException {

  log.info("Validating inputs of skill");

  if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
    throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
  }

  final TechGalleryUser techUser = userService.getUserByGoogleId(user.getUserId());
  if (techUser == null) {
    throw new BadRequestException(ValidationMessageEnums.USER_NOT_EXIST.message());
  }

  if (skill == null) {
    throw new BadRequestException(ValidationMessageEnums.SKILL_CANNOT_BLANK.message());
  }

  if (skill.getValue() == null || skill.getValue() < 0 || skill.getValue() > 5) {
    throw new BadRequestException(ValidationMessageEnums.SKILL_RANGE.message());
  }

  if (skill.getTechnology() == null) {
    throw new BadRequestException(ValidationMessageEnums.TECHNOLOGY_ID_CANNOT_BLANK.message());
  }

}
 
Example 5
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the Profile entity for the current user
 * or creates it if it doesn't exist
 * @param user
 * @return user's Profile
 */
private static Profile getProfileFromUser(User user) {
    // First fetch the user's Profile from the datastore.
    Profile profile = ofy().load().key(
            Key.create(Profile.class, user.getUserId())).now();
    if (profile == null) {
        // Create a new Profile if it doesn't exist.
        // Use default displayName and teeShirtSize
        String email = user.getEmail();
        profile = new Profile(user.getUserId(),
                extractDefaultDisplayNameFromEmail(email), email, TeeShirtSize.NOT_SPECIFIED);
    }
    return profile;
}
 
Example 6
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a Profile object associated with the given user object. The cloud
 * endpoints system automatically inject the User object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @return Profile object.
 * @throws UnauthorizedException
 *             when the User object is null.
 */
@ApiMethod(name = "getProfile", path = "profile", httpMethod = HttpMethod.GET)
public Profile getProfile(final User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO
    // load the Profile Entity
    String userId = user.getUserId();
    Key key = Key.create(Profile.class, userId);

    Profile profile = (Profile) ofy().load().key(key).now();
    return profile;
}
 
Example 7
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This is an ugly workaround for null userId for Android clients.
 *
 * @param user A User object injected by the cloud endpoints.
 * @return the App Engine userId for the user.
 */
private static String getUserId(User user) {
    String userId = user.getUserId();
    if (userId == null) {
        LOG.info("userId is null, so trying to obtain it from the datastore.");
        AppEngineUser appEngineUser = new AppEngineUser(user);
        ofy().save().entity(appEngineUser).now();
        // Begin new session for not using session cache.
        Objectify objectify = ofy().factory().begin();
        AppEngineUser savedUser = objectify.load().key(appEngineUser.getKey()).now();
        userId = savedUser.getUser().getUserId();
        LOG.info("Obtained the userId: " + userId);
    }
    return userId;
}
 
Example 8
Source File: AppEngineServletUtils.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Return the user id for the currently logged in user.
 */
static final String getUserId() {
  UserService userService = UserServiceFactory.getUserService();
  User loggedIn = userService.getCurrentUser();
  Preconditions.checkState(loggedIn != null, "This servlet requires the user to be logged in.");
  return loggedIn.getUserId();
}
 
Example 9
Source File: UserServiceTGImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
@Override
public TechGalleryUser validateUser(User user)
    throws BadRequestException, NotFoundException, InternalServerErrorException {

  if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
    throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
  }

  final TechGalleryUser techUser = getUserByGoogleId(user.getUserId());
  if (techUser == null) {
    throw new NotFoundException(ValidationMessageEnums.USER_NOT_EXIST.message());
  }
  return techUser;
}
 
Example 10
Source File: TechnologyServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the user logged in.
 *
 * @param user info about user from google
 * @throws InternalServerErrorException in case something goes wrong
 * @throws NotFoundException            in case the information are not founded
 * @throws BadRequestException          in case a request with problem were made.
 */
private void validateUser(User user) throws BadRequestException, NotFoundException, InternalServerErrorException {

    if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
        throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
    }

    TechGalleryUser techUser = userService.getUserByGoogleId(user.getUserId());
    if (techUser == null) {
        throw new NotFoundException(ValidationMessageEnums.USER_NOT_EXIST.message());
    }
}
 
Example 11
Source File: TechnologyLinkServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the user logged in.
 *
 * @param user info about user from google
 *
 * @throws BadRequestException in case a request with problem were made.
 * @throws InternalServerErrorException in case something goes wrong
 * @throws NotFoundException in case the information are not founded
 */
private void validateUser(User user)
    throws BadRequestException, NotFoundException, InternalServerErrorException {

  log.info("Validating user to link");

  if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
    throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
  }

  final TechGalleryUser techUser = userService.getUserByGoogleId(user.getUserId());
  if (techUser == null) {
    throw new NotFoundException(ValidationMessageEnums.USER_NOT_EXIST.message());
  }
}
 
Example 12
Source File: RecommendationServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the user logged in.
 *
 * @param user info about user from google
 * @throws InternalServerErrorException in case something goes wrong
 * @throws NotFoundException in case the information are not founded
 * @throws BadRequestException in case a request with problem were made.
 */
private void validateUser(User user)
    throws BadRequestException, NotFoundException, InternalServerErrorException {

  if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
    throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
  }

  final TechGalleryUser techUser = userService.getUserByGoogleId(user.getUserId());
  if (techUser == null) {
    throw new NotFoundException(ValidationMessageEnums.USER_NOT_EXIST.message());
  }
}
 
Example 13
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a Profile object associated with the given user object. The cloud
 * endpoints system automatically inject the User object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @return Profile object.
 * @throws UnauthorizedException
 *             when the User object is null.
 */
@ApiMethod(name = "getProfile", path = "profile", httpMethod = HttpMethod.GET)
public Profile getProfile(final User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO
    // load the Profile Entity
    String userId = user.getUserId();
    Key key = Key.create(Profile.class, userId);

    Profile profile = (Profile) ofy().load().key(key).now();
    return profile;
}
 
Example 14
Source File: TechnologyRecommendationServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Validation for User.
 *
 * @author <a href="mailto:[email protected]"> João Felipe de Medeiros Moreira </a>
 * @since 28/09/2015
 *
 * @param user to be validated
 * @param techUser to be validated
 *
 * @throws BadRequestException in case the params are not correct
 * @throws InternalServerErrorException in case of internal error
 */
private void validateUser(User user, TechGalleryUser techUser)
    throws BadRequestException, InternalServerErrorException {
  log.info("Validating user to recommend");

  if (user == null || user.getUserId() == null || user.getUserId().isEmpty()) {
    throw new BadRequestException(ValidationMessageEnums.USER_GOOGLE_ENDPOINT_NULL.message());
  }

  if (techUser == null) {
    throw new BadRequestException(ValidationMessageEnums.USER_NOT_EXIST.message());
  }
}
 
Example 15
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Register to attend the specified Conference.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @param websafeConferenceKey The String representation of the Conference Key.
 * @return Boolean true when success, otherwise false
 * @throws UnauthorizedException when the user is not signed in.
 * @throws NotFoundException when there is no Conference with the given conferenceId.
 */
@ApiMethod(
        name = "registerForConference",
        path = "conference/{websafeConferenceKey}/registration",
        httpMethod = HttpMethod.POST
)

public WrappedBoolean registerForConference(final User user,
        @Named("websafeConferenceKey") final String websafeConferenceKey)
        throws UnauthorizedException, NotFoundException,
        ForbiddenException, ConflictException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // Get the userId
    final String userId = user.getUserId();

    WrappedBoolean result = ofy().transact(new Work<WrappedBoolean>() {
        @Override
        public WrappedBoolean run() {
            try {

            // Get the conference key
            // Will throw ForbiddenException if the key cannot be created
            Key<Conference> conferenceKey = Key.create(websafeConferenceKey);

            // Get the Conference entity from the datastore
            Conference conference = ofy().load().key(conferenceKey).now();

            // 404 when there is no Conference with the given conferenceId.
            if (conference == null) {
                return new WrappedBoolean (false,
                        "No Conference found with key: "
                                + websafeConferenceKey);
            }

            // Get the user's Profile entity
            Profile profile = getProfileFromUser(user);

            // Has the user already registered to attend this conference?
            if (profile.getConferenceKeysToAttend().contains(
                    websafeConferenceKey)) {
                return new WrappedBoolean (false, "Already registered");
            } else if (conference.getSeatsAvailable() <= 0) {
                return new WrappedBoolean (false, "No seats available");
            } else {
                // All looks good, go ahead and book the seat
                profile.addToConferenceKeysToAttend(websafeConferenceKey);
                conference.bookSeats(1);

                // Save the Conference and Profile entities
                ofy().save().entities(profile, conference).now();
                // We are booked!
                return new WrappedBoolean(true, "Registration successful");
            }

            }
            catch (Exception e) {
                return new WrappedBoolean(false, "Unknown exception");

            }
        }
    });
    // if result is false
    if (!result.getResult()) {
        if (result.getReason().contains("No Conference found with key")) {
            throw new NotFoundException (result.getReason());
        }
        else if (result.getReason() == "Already registered") {
            throw new ConflictException("You have already registered");
        }
        else if (result.getReason() == "No seats available") {
            throw new ConflictException("There are no seats available");
        }
        else {
            throw new ForbiddenException("Unknown exception");
        }
    }
    return result;
}
 
Example 16
Source File: EndorsementServiceImpl.java    From tech-gallery with Apache License 2.0 4 votes vote down vote up
/**
 * POST for adding a endorsement. TODO: Refactor - Extract Method. Same in
 * {@link #addOrUpdateEndorsement(EndorsementResponse, User)}
 *
 * @throws InternalServerErrorException in case something goes wrong
 * @throws NotFoundException in case the information are not founded
 * @throws BadRequestException in case a request with problem were made.
 * @throws OAuthRequestException in case of authentication problem
 */
@Override
public Endorsement addOrUpdateEndorsementPlusOne(EndorsementResponse endorsement, User user)
    throws InternalServerErrorException, BadRequestException, NotFoundException,
    OAuthRequestException {
  // endorser user google id
  String googleId;
  // endorser user from techgallery datastore
  TechGalleryUser tgEndorserUser;
  // endorsed user from techgallery datastore
  TechGalleryUser tgEndorsedUser;
  // endorsed email
  String endorsedEmail;
  // technology from techgallery datastore
  Technology technology;

  // User from endpoint (endorser) can't be null
  if (user == null) {
    throw new OAuthRequestException(i18n.t("OAuth error, null user reference!"));
  } else {
    googleId = user.getUserId();
  }

  // TechGalleryUser can't be null and must exists on datastore
  if (googleId == null || googleId.equals("")) {
    throw new NotFoundException(i18n.t("Current user was not found!"));
  } else {
    // get the TechGalleryUser from datastore
    tgEndorserUser = userDao.findByGoogleId(googleId);
    if (tgEndorserUser == null) {
      throw new BadRequestException(i18n.t("Endorser user do not exists on datastore!"));
    }
    tgEndorserUser.setGoogleId(googleId);
  }

  // endorsed email can't be null.
  endorsedEmail = endorsement.getEndorsed();
  if (endorsedEmail == null || endorsedEmail.equals("")) {
    throw new BadRequestException(i18n.t("Endorsed email was not especified!"));
  } else {
    // get user from PEOPLE
    tgEndorsedUser = userService.getUserSyncedWithProvider(endorsedEmail);
    if (tgEndorsedUser == null) {
      throw new BadRequestException(i18n.t("Endorsed email was not found on PEOPLE!"));
    }
  }

  // technology id can't be null and must exists on datastore
  final String technologyId = endorsement.getTechnology();
  if (technologyId == null || technologyId.equals("")) {
    throw new BadRequestException(i18n.t("Technology was not especified!"));
  } else {
    technology = techDao.findById(technologyId);
    if (technology == null) {
      throw new BadRequestException(i18n.t("Technology do not exists!"));
    }
  }

  // final checks and persist
  // user cannot endorse itself
  if (tgEndorserUser.getId().equals(tgEndorsedUser.getId())) {
    throw new BadRequestException(i18n.t("You cannot endorse yourself!"));
  }

  // should exist only one active endorsement per endorser/endorsed/technology. the others are
  // saved for history purpose. if already exist one active endorsement, set to inactive.
  // if not, add a new one as active
  final List<Endorsement> endorsements =
      endorsementDao.findActivesByUsers(tgEndorserUser, tgEndorsedUser, technology);
  if (endorsements.size() == 1) {
    endorsements.get(0).setInactivatedDate(new Date());
    endorsements.get(0).setActive(false);
    endorsementDao.update(endorsements.get(0));

    UserProfileServiceImpl.getInstance().handleEndorsement(endorsements.get(0));
    return getEndorsement(endorsements.get(0).getId());
  } else if (endorsements.size() > 1) {
    throw new BadRequestException(
        i18n.t("More than one active endorserment for the same endorser/endorsed/technology!"));
  }

  // create endorsement and save it
  final Endorsement entity = new Endorsement();
  entity.setEndorser(Ref.create(tgEndorserUser));
  entity.setEndorsed(Ref.create(tgEndorsedUser));
  entity.setTimestamp(new Date());
  entity.setTechnology(Ref.create(technology));
  entity.setActive(true);
  endorsementDao.add(entity);
  UserProfileServiceImpl.getInstance().handleEndorsement(entity);
  return getEndorsement(entity.getId());
}
 
Example 17
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Register to attend the specified Conference.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @param websafeConferenceKey The String representation of the Conference Key.
 * @return Boolean true when success, otherwise false
 * @throws UnauthorizedException when the user is not signed in.
 * @throws NotFoundException when there is no Conference with the given conferenceId.
 */
@ApiMethod(
        name = "registerForConference",
        path = "conference/{websafeConferenceKey}/registration",
        httpMethod = HttpMethod.POST
)

public WrappedBoolean registerForConference(final User user,
        @Named("websafeConferenceKey") final String websafeConferenceKey)
        throws UnauthorizedException, NotFoundException,
        ForbiddenException, ConflictException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // Get the userId
    final String userId = user.getUserId();

    WrappedBoolean result = ofy().transact(new Work<WrappedBoolean>() {
        @Override
        public WrappedBoolean run() {
            try {

            // Get the conference key
            // Will throw ForbiddenException if the key cannot be created
            Key<Conference> conferenceKey = Key.create(websafeConferenceKey);

            // Get the Conference entity from the datastore
            Conference conference = ofy().load().key(conferenceKey).now();

            // 404 when there is no Conference with the given conferenceId.
            if (conference == null) {
                return new WrappedBoolean (false,
                        "No Conference found with key: "
                                + websafeConferenceKey);
            }

            // Get the user's Profile entity
            Profile profile = getProfileFromUser(user);

            // Has the user already registered to attend this conference?
            if (profile.getConferenceKeysToAttend().contains(
                    websafeConferenceKey)) {
                return new WrappedBoolean (false, "Already registered");
            } else if (conference.getSeatsAvailable() <= 0) {
                return new WrappedBoolean (false, "No seats available");
            } else {
                // All looks good, go ahead and book the seat
                profile.addToConferenceKeysToAttend(websafeConferenceKey);
                conference.bookSeats(1);

                // Save the Conference and Profile entities
                ofy().save().entities(profile, conference).now();
                // We are booked!
                return new WrappedBoolean(true, "Registration successful");
            }

            }
            catch (Exception e) {
                return new WrappedBoolean(false, "Unknown exception");

            }
        }
    });
    // if result is false
    if (!result.getResult()) {
        if (result.getReason().contains("No Conference found with key")) {
            throw new NotFoundException (result.getReason());
        }
        else if (result.getReason() == "Already registered") {
            throw new ConflictException("You have already registered");
        }
        else if (result.getReason() == "No seats available") {
            throw new ConflictException("There are no seats available");
        }
        else {
            throw new ForbiddenException("Unknown exception");
        }
    }
    return result;
}
 
Example 18
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
        throws UnauthorizedException {

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO 2
    // Get the userId and mainEmail
    String mainEmail = user.getEmail();
    String userId = user.getUserId();

    // TODO 1
    // Get the displayName and teeShirtSize sent by the request.

    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    // Get the Profile from the datastore if it exists
    // otherwise create a new one
    Profile profile = ofy().load().key(Key.create(Profile.class, userId))
            .now();

    if (profile == null) {
        // Populate the displayName and teeShirtSize with default values
        // if not sent in the request
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user
                    .getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        // Now create a new Profile entity
        profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
    } else {
        // The Profile entity already exists
        // Update the Profile entity
        profile.update(displayName, teeShirtSize);
    }

    // TODO 3
    // Save the entity in the datastore
    ofy().save().entity(profile).now();

    // Return the profile
    return profile;
}
 
Example 19
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new Conference object and stores it to the datastore.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @param conferenceForm A ConferenceForm object representing user's inputs.
 * @return A newly created Conference Object.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(name = "createConference", path = "conference", httpMethod = HttpMethod.POST)
public Conference createConference(final User user, final ConferenceForm conferenceForm)
    throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO (Lesson 4)
    // Get the userId of the logged in User
    String userId = user.getUserId();

    // TODO (Lesson 4)
    // Get the key for the User's Profile
    Key<Profile> profileKey = Key.create(Profile.class, userId);

    // TODO (Lesson 4)
    // Allocate a key for the conference -- let App Engine allocate the ID
    // Don't forget to include the parent Profile in the allocated ID
    final Key<Conference> conferenceKey = factory().allocateId(profileKey, Conference.class);

    // TODO (Lesson 4)
    // Get the Conference Id from the Key
    final long conferenceId = conferenceKey.getId();

    // TODO (Lesson 4)
    // Get the existing Profile entity for the current user if there is one
    // Otherwise create a new Profile entity with default values
    Profile profile = getProfileFromUser(user);

    // TODO (Lesson 4)
    // Create a new Conference Entity, specifying the user's Profile entity
    // as the parent of the conference
    Conference conference = new Conference(conferenceId, userId, conferenceForm);

    // TODO (Lesson 4)
    // Save Conference and Profile Entities
     ofy().save().entities(conference, profile).now();

     return conference;
     }
 
Example 20
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
        throws UnauthorizedException {

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO 2
    // Get the userId and mainEmail
    String mainEmail = user.getEmail();
    String userId = user.getUserId();

    // TODO 1
    // Get the displayName and teeShirtSize sent by the request.

    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    // Get the Profile from the datastore if it exists
    // otherwise create a new one
    Profile profile = ofy().load().key(Key.create(Profile.class, userId))
            .now();

    if (profile == null) {
        // Populate the displayName and teeShirtSize with default values
        // if not sent in the request
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user
                    .getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        // Now create a new Profile entity
        profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
    } else {
        // The Profile entity already exists
        // Update the Profile entity
        profile.update(displayName, teeShirtSize);
    }

    // TODO 3
    // Save the entity in the datastore
    ofy().save().entity(profile).now();

    // Return the profile
    return profile;
}