com.google.appengine.api.users.User Java Examples

The following examples show how to use com.google.appengine.api.users.User. 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: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * This method lists all the entities inserted in datastore. It uses HTTP GET method.
 *
 * @return List of all entities persisted.
 */
@SuppressWarnings({"cast", "unchecked"})
@ApiMethod(httpMethod = "GET", path = "offer")
public List<Offer> list(@Named("placeId") String placeId, User user) {

  // TODO(user): Retrieve only offers applicable to given place and user
  EntityManager mgr = getEntityManager();
  List<Offer> result = new ArrayList<Offer>();
  try {
    Query query = mgr.createQuery("select from Offer as Offer");
    for (Offer offer : (List<Offer>) query.getResultList()) {
      result.add(offer);
    }
  } finally {
    mgr.close();
  }
  return result;
}
 
Example #2
Source File: EndorsementServiceImpl.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * GET for getting one endorsement.
 *
 * @throws InternalServerErrorException in case something goes wrong
 * @throws OAuthRequestException in case of authentication problem
 * @throws NotFoundException in case the information are not founded
 * @throws BadRequestException in case a request with problem were made.
 */
@Override
public Response getEndorsementsByTech(String techId, User user)
    throws InternalServerErrorException, BadRequestException, NotFoundException,
    OAuthRequestException {
  final List<Endorsement> endorsementsByTech = endorsementDao.findAllActivesByTechnology(techId);
  final List<EndorsementsGroupedByEndorsedTransient> grouped =
      groupEndorsementByEndorsed(endorsementsByTech, techId);
  final Technology technology = techService.getTechnologyById(techId, user);

  techService.updateEdorsedsCounter(technology, grouped.size());

  groupUsersWithSkill(grouped, technology);

  Collections.sort(grouped, new EndorsementsGroupedByEndorsedTransient());
  final ShowEndorsementsResponse response = new ShowEndorsementsResponse();
  response.setEndorsements(grouped);
  return response;
}
 
Example #3
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a signed URL that can be used to upload a blob.
 *
 * @param bucketName  Google Cloud Storage bucket to use for upload.
 * @param objectPath  path to the object in the bucket.
 * @param accessMode  controls how the uploaded blob can be accessed.
 * @param contentType the MIME type of the object of be uploaded. Can be null.
 * @param user        the user making the request.
 * @throws com.google.api.server.spi.response.UnauthorizedException if the user is not authorized.
 * @throws com.google.api.server.spi.response.BadRequestException   if the bucketName or objectPath are not valid.
 */
@ApiMethod(httpMethod = HttpMethod.GET, path = "blobs/uploads/{bucketName}/{objectPath}")
public BlobAccess getUploadUrl(@Named("bucketName") String bucketName,
                               @Named("objectPath") String objectPath, @Named("accessMode") BlobAccessMode accessMode,
                               @Nullable @Named("contentType") String contentType, User user)
  throws UnauthorizedException, BadRequestException {
  validateUser(user);

  validateBucketAndObjectPath(bucketName, objectPath);

  if (!reserveNameIfAvailable(bucketName, objectPath, accessMode, user)) {
    throw new UnauthorizedException("You don't have permissions to upload this object");
  }

  return getBlobUrlForUpload(
    bucketName, objectPath, accessMode, contentType != null ? contentType : "");
}
 
Example #4
Source File: SignGuestbookServlet.java    From appengine-java-guestbook-multiphase with Apache License 2.0 6 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  Greeting greeting;

  UserService userService = UserServiceFactory.getUserService();
  User user = userService.getCurrentUser();  // Find out who the user is.

  String guestbookName = req.getParameter("guestbookName");
  String content = req.getParameter("content");
  if (user != null) {
    greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());
  } else {
    greeting = new Greeting(guestbookName, content);
  }

  // Use Objectify to save the greeting and now() is used to make the call synchronously as we
  // will immediately get a new page using redirect and we want the data to be present.
  ObjectifyService.ofy().save().entity(greeting).now();

  resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #5
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * This inserts the entity into App Engine datastore. It uses HTTP POST method.
 *
 * @param checkin the entity to be inserted.
 * @return The inserted entity.
 */
public CheckIn insert(CheckIn checkin, User user) throws ServiceException {
  EndpointUtil.throwIfNotAuthenticated(user);

  checkin.setUserEmail(user.getEmail());
  checkin.setCheckinDate(new Date());

  // Do not use the key provided by the caller; use a generated key.
  checkin.clearKey();

  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(checkin);
  } finally {
    mgr.close();
  }

  // generate personalized offers when user checks into a place and send them
  // to the user using push notification
  pushPersonalizedOffers(checkin.getPlaceId(), user);

  return checkin;
}
 
Example #6
Source File: GaeUserIdConverter.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an email address to a GAE user id.
 *
 * @return Numeric GAE user id (in String form), or null if email address has no GAE id
 */
public static String convertEmailAddressToGaeUserId(String emailAddress) {
  final GaeUserIdConverter gaeUserIdConverter = new GaeUserIdConverter();
  gaeUserIdConverter.id = allocateId();
  List<String> emailParts = Splitter.on('@').splitToList(emailAddress);
  checkState(emailParts.size() == 2, "'%s' is not a valid email address", emailAddress);
  gaeUserIdConverter.user = new User(emailAddress, emailParts.get(1));

  try {
    // Perform these operations in a transactionless context to avoid enlisting in some outer
    // transaction (if any).
    tm().doTransactionless(() -> ofy().saveWithoutBackup().entity(gaeUserIdConverter).now());

    // The read must be done in its own transaction to avoid reading from the session cache.
    return tm()
        .transactNew(() -> ofy().load().entity(gaeUserIdConverter).safe().user.getUserId());
  } finally {
    tm().doTransactionless(() -> ofy().deleteWithoutBackup().entity(gaeUserIdConverter).now());
  }
}
 
Example #7
Source File: TechnologyServiceImpl.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
/**
 * GET for getting all technologies.
 *
 * @throws NotFoundException .
 */
@Override
public Response getTechnologies(User user)
        throws InternalServerErrorException, NotFoundException, BadRequestException {
    List<Technology> techEntities = technologyDAO.findAllActives();
    // if list is null, return a not found exception
    if (techEntities == null || techEntities.isEmpty()) {
        return new TechnologiesResponse();
    } else {
        verifyTechnologyFollowedByUser(user, techEntities);
        TechnologiesResponse response = new TechnologiesResponse();
        Technology.sortTechnologiesDefault(techEntities);
        response.setTechnologies(techEntities);
        return response;
    }
}
 
Example #8
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 #9
Source File: GuestbookServlet.java    From appengine-java-guestbook-multiphase with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  if (req.getParameter("testing") != null) {
    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, this is a testing servlet. \n\n");
    Properties p = System.getProperties();
    p.list(resp.getWriter());

  } else {
    UserService userService = UserServiceFactory.getUserService();
    User currentUser = userService.getCurrentUser();

    if (currentUser != null) {
      resp.setContentType("text/plain");
      resp.getWriter().println("Hello, " + currentUser.getNickname());
    } else {
      resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
    }
  }
}
 
Example #10
Source File: TodoEndpoint.java    From appstart with Apache License 2.0 6 votes vote down vote up
@ApiMethod(
	name = "todos.delete",
	path = "todos/{id}"
)
public Todo delete(@Named("id") Long id, @Named("auth") boolean auth, User user) {
	if(auth) {
		this.authenticate(user);
	}
	
	Todo todo = null;
	try {
		todo = service.delete(id);
		
	} catch(Exception e) {
		log.log(Level.SEVERE, "Something went wrong", e);
		throw e;
	}
	return todo;
}
 
Example #11
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a collection of Conference Object that the user is going to attend.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @return a Collection of Conferences that the user is going to attend.
 * @throws UnauthorizedException when the User object is null.
 */
@ApiMethod(
        name = "getConferencesToAttend",
        path = "getConferencesToAttend",
        httpMethod = HttpMethod.GET
)
public Collection<Conference> getConferencesToAttend(final User user)
        throws UnauthorizedException, NotFoundException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
    if (profile == null) {
        throw new NotFoundException("Profile doesn't exist.");
    }
    List<String> keyStringsToAttend = profile.getConferenceKeysToAttend();
    List<Key<Conference>> keysToAttend = new ArrayList<>();
    for (String keyString : keyStringsToAttend) {
        keysToAttend.add(Key.<Conference>create(keyString));
    }
    return ofy().load().keys(keysToAttend).values();
}
 
Example #12
Source File: TechnologyServiceImpl.java    From tech-gallery with Apache License 2.0 6 votes vote down vote up
@Override
public Technology addOrUpdateTechnology(Technology technology, User user)
        throws BadRequestException, IOException, GeneralSecurityException {

    Technology foundTechnology = validateInformations(technology);
    Boolean isUpdate = foundTechnology != null && foundTechnology.getId().equals(technology.getId())
            && foundTechnology.getActive().equals(Boolean.TRUE);

    String imageLink = saveImage(technology);

    if (isUpdate) {
        updateTechnology(foundTechnology, technology, user, imageLink);
    } else {
        addTechnology(technology, user, imageLink);
    }

    return technology;
}
 
Example #13
Source File: BlobEndpoint.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Checks user's permissions to delete a blob and throws an exception if user doesn't have
 * permissions.
 *
 * @param bucketName Google Cloud Storage bucket where the object was uploaded.
 * @param objectPath path to the object in the bucket.
 * @param user       the user making the request.
 * @return true if the object may exist and delete operation should proceed; false otherwise.
 * @throws com.google.api.server.spi.response.UnauthorizedException if the user is not authorized.
 */
private boolean checkDeletePermissions(String bucketName, String objectPath, User user)
  throws UnauthorizedException {
  BlobMetadata metadata = BlobManager.getBlobMetadata(bucketName, objectPath);
  if (metadata == null) {
    return false;
  }

  if (getUserId(user).equals(metadata.getOwnerId())) {
    // User is the owner.
    return true;
  }

  throw new UnauthorizedException("You don't have permissions to delete this object");
}
 
Example #14
Source File: ProjectServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
/**
 * Validate inputs of SkillResponse.
 *
 * @param project 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(Project project, 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());
    }

    if (project == null || project.getName() == null) {
        throw new BadRequestException(ValidationMessageEnums.NAME_CANNOT_BLANK.message());
    }
}
 
Example #15
Source File: TechnologyCommentServiceImpl.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 comment");

  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 #16
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 #17
Source File: SignGuestbookServlet.java    From appengine-java-vm-guestbook-extras with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    String code = (String) req.getParameter("ccode");
    String captcha = (String) req.getSession().getAttribute("captcha");
    if (captcha != null && code != null) {
        if (!captcha.trim().equalsIgnoreCase(code)) {
            resp.getWriter().println("<html><head><title>error</title></head><body>error in captcha." +
                "<br/><a href='/guestbook.jsp'>Try again</a>.</body></html>");
            return;
        }
    }
    else {
        resp.getWriter().println("error in captcha");
        return;
    }

    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);
    content = content.substring(0, Math.min(content.length(), 490));
    greeting.setProperty("content", content);

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(greeting);

    resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);
}
 
Example #18
Source File: TodoEndpoint.java    From appstart with Apache License 2.0 5 votes vote down vote up
private void authenticate(User user) {
	if(user == null) {
		log.warning("User is not authenticated");
		throw new RuntimeException("Authentication required!");
	} else {
		// further validation such as domain checking, etc...
		log.info(user.getEmail());
	}
}
 
Example #19
Source File: GuestbookServlet.java    From appengine-modules-sample-java with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {

  final UserService userService = UserServiceFactory.getUserService();
  final User currentUser = userService.getCurrentUser();

  if (currentUser != null) {
    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, " + currentUser.getNickname());
  } else {
    resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
  }
}
 
Example #20
Source File: AdminServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< Void > recalculateFileInfoStats( final String googleAccount ) {
	LOGGER.fine( "For Google account: " + googleAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	if ( !userService.isUserAdmin() )
		return RpcResult.createNoPermissionErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final Key accountKey = CachingService.getAccountKeyByUser( pm, new User( googleAccount, "gmail.com" ) );
		if ( accountKey == null )
			return RpcResult.createErrorResult( "Invalid Google account!" );
		
		TaskServlet.register_recalcFileStatsTask( accountKey );
		
		pm.makePersistent( new Event( accountKey, Type.FILE_STATS_RECALC_TRIGGERED, "By admin: " + user.getEmail() ) );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
	
	return RpcResult.createInfoResult( "File stats recalculation has been kicked-off..." );
}
 
Example #21
Source File: RegistrarSettingsActionTestCase.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Registrar "TheRegistrar" has access to TLD "currenttld" but not to "newtld".
  createTlds("currenttld", "newtld");
  disallowRegistrarAccess(CLIENT_ID, "newtld");

  // Add a technical contact to the registrar (in addition to the default admin contact created by
  // AppEngineRule).
  techContact =
      getOnlyElement(loadRegistrar(CLIENT_ID).getContactsOfType(RegistrarContact.Type.TECH));

  action.registrarAccessor = null;
  action.appEngineServiceUtils = appEngineServiceUtils;
  when(appEngineServiceUtils.getCurrentVersionHostname("backend")).thenReturn("backend.hostname");
  action.jsonActionRunner =
      new JsonActionRunner(ImmutableMap.of(), new JsonResponse(new ResponseImpl(rsp)));
  action.sendEmailUtils =
      new SendEmailUtils(
          getGSuiteOutgoingEmailAddress(),
          getGSuiteOutgoingEmailDisplayName(),
          ImmutableList.of("[email protected]", "[email protected]"),
          emailService);
  action.registrarConsoleMetrics = new RegistrarConsoleMetrics();
  action.authResult =
      AuthResult.create(
          AuthLevel.USER,
          UserAuthInfo.create(new User("[email protected]", "email.com", "12345"), false));
  inject.setStaticField(Ofy.class, "clock", clock);
  when(req.getMethod()).thenReturn("POST");
  when(rsp.getWriter()).thenReturn(new PrintWriter(writer));
  when(req.getContentType()).thenReturn("application/json");
  when(req.getReader()).thenReturn(createJsonPayload(ImmutableMap.of("op", "read")));
  // We set the default to a user with access, as that's the most common test case. When we want
  // to specifically check a user without access, we can switch user for that specific test.
  setUserWithAccess();
  RegistrarConsoleMetrics.settingsRequestMetric.reset();
}
 
Example #22
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 #23
Source File: CrudOperations.java    From solutions-mobile-backend-starter-java with Apache License 2.0 5 votes vote down vote up
protected EntityListDto getAllEntities(EntityListDto cdl, User user) {

    // get all entities by CbIdList
    Map<String, Entity> entities = getAllEntitiesByKeyList(cdl.readKeyList(user));

    // convert to CbDtos
    EntityListDto resultCdl = new EntityListDto();
    for (Entity e : entities.values()) {
      EntityDto cd = EntityDto.createFromEntity(e);
      resultCdl.getEntries().add(cd);
    }
    return resultCdl;
  }
 
Example #24
Source File: UserTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
/**
 * Tests hashCode.
 * <p>Given user1.equals(user2) returns true,
 * expect hashCode of user1 == hashCode of user2.
 */
@Test
public void testHashCode() {
    User user1 = new User("[email protected]", "gmail.com");
    User user2 = new User("[email protected]", "gmail.com");
    assertTrue(user1.equals(user2));
    assertEquals(user1.hashCode(), user2.hashCode());
}
 
Example #25
Source File: UserTest.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
/**
 * Tests compareTo email1 less than email2.
 */
@Test
public void testCompareTo_less() {
    User user1 = new User("aa", "dd");
    User user2 = new User("bb", "cc");
    assertTrue(user1.compareTo(user2) < 0);
}
 
Example #26
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 #27
Source File: ApiUserServiceImpl.java    From sc2gears with Apache License 2.0 5 votes vote down vote up
@Override
public RpcResult< SettingsInfo > getSettings( final String sharedApiAccount ) {
	LOGGER.fine( "sharedApiAccount: " + sharedApiAccount );
	
	final UserService userService = UserServiceFactory.getUserService();
	final User user = userService.getCurrentUser();
	if ( user == null )
		return RpcResult.createNotLoggedInErrorResult();
	
	PersistenceManager pm = null;
	try {
		
		pm = PMF.get().getPersistenceManager();
		
		final ApiAccount apiAccount = getApiAccount( pm, sharedApiAccount, user );
		if ( apiAccount == null )
			return RpcResult.createNoPermissionErrorResult();
		
		final SettingsInfo settingsInfo = new SettingsInfo();
		settingsInfo.setGoogleAccount       ( apiAccount.getUser                ().getEmail() );
		settingsInfo.setContactEmail        ( apiAccount.getContactEmail        ()            );
		settingsInfo.setUserName            ( apiAccount.getName                ()            );
		settingsInfo.setNotificationAvailOps( apiAccount.getNotificationAvailOps()            );
		return new RpcResult< SettingsInfo >( settingsInfo );
		
	} finally {
		if ( pm != null )
			pm.close();
	}
}
 
Example #28
Source File: OfferEndpoint.java    From MobileShoppingAssistant-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the entity with primary key id. It uses HTTP DELETE method.
 * @param id the primary key of the entity to be deleted.
 * @param user the user deleting the entity.
 * @throws com.google.api.server.spi.ServiceException if user is not
 * authorized
 */
@ApiMethod(httpMethod = "DELETE")
public final void removeOffer(@Named("id") final Long id, final User user)
        throws ServiceException {
    EndpointUtil.throwIfNotAdmin(user);

    Offer offer = findOffer(id);
    if (offer == null) {
        LOG.info(
                "Offer " + id + " not found, skipping deletion.");
        return;
    }
    ofy().delete().entity(offer).now();
}
 
Example #29
Source File: RegistrationEndpoint.java    From MobileShoppingAssistant-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Unregisters a device from the backend.
 * @param regId The Google Cloud Messaging registration Id to remove     *
 * @param user the user unregistering a device.
 * @throws com.google.api.server.spi.response.UnauthorizedException if
 * user is unauthorized
 */
@ApiMethod(httpMethod = "DELETE")
public final void unregisterDevice(@Named("regId") final String regId,
        final User user) throws UnauthorizedException {
    EndpointUtil.throwIfNotAdmin(user);
    Registration record = findRecord(regId);
    if (record == null) {
        LOG.info(
                "Device " + regId + " not registered, skipping unregister");
        return;
    }
    ofy().delete().entity(record).now();
}
 
Example #30
Source File: TechnologyServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getOrderOptions(User user) {
    List<String> orderOptions = new ArrayList<String>();
    for (TechnologyOrderOptionEnum item : TechnologyOrderOptionEnum.values()) {
        orderOptions.add(item.option());
    }
    return orderOptions;
}