com.google.api.server.spi.ServiceException Java Examples

The following examples show how to use com.google.api.server.spi.ServiceException. 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: DeviceRegistrationEndpoint.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a new entity into App Engine datastore or updates existing entity.It uses HTTP POST
 * method.
 *
 * @param device the entity to be inserted/updated.
 * @return The inserted/updated entity.
 * @throws ServiceException when the call is unauthenticated and the backend is configured not to
 *         allow them
 */
public DeviceRegistration registerDevice(DeviceRegistration device, User user)
    throws ServiceException {

  if (user == null && !Configuration.ALLOW_UNAUTHENTICATED_CALLS) {
    throw new UnauthorizedException("Only authenticated calls are allowed");
  }

  EntityManager mgr = getEntityManager();
  try {
    device.setTimestamp(new Date());
    mgr.persist(device);
  } finally {
    mgr.close();
  }
  return device;
}
 
Example #2
Source File: CheckInEndpoint.java    From MobileShoppingAssistant-sample with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts the entity into App Engine datastore. It uses HTTP POST method.
 * @param checkin the entity to be inserted.
 * @param user the user trying to insert the entity.
 * @return The inserted entity.
 * @throws com.google.api.server.spi.ServiceException if user is not
 * authorized
 */
@ApiMethod(httpMethod = "POST")
public final CheckIn insertCheckIn(final CheckIn checkin, final 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();

    ofy().save().entity(checkin).now();

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

    return checkin;
}
 
Example #3
Source File: CheckInEndpoint.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"})
public List<CheckIn> list(User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  List<CheckIn> result = new ArrayList<CheckIn>();
  try {
    Query query = mgr.createQuery("select from CheckIn as CheckIn");
    for (CheckIn checkIn : (List<CheckIn>) query.getResultList()) {
      result.add(checkIn);
    }
  } finally {
    mgr.close();
  }
  return result;
}
 
Example #4
Source File: RestResponseResultWriterTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private void writeError(int exceptionCode, int expectedCode, String reason, String message,
    boolean enableExceptionCompatibility) throws Exception {
  MockHttpServletResponse response = new MockHttpServletResponse();
  RestResponseResultWriter writer = new RestResponseResultWriter(
      response, null, true /* prettyPrint */,
      true /* addContentLength */, enableExceptionCompatibility);
  writer.writeError(new ServiceException(exceptionCode, message));
  ObjectMapper mapper = ObjectMapperUtil.createStandardObjectMapper();
  ObjectNode content = mapper.readValue(response.getContentAsString(), ObjectNode.class);
  JsonNode outerError = content.path("error");
  assertThat(outerError.path("code").asInt()).isEqualTo(expectedCode);
  if (message == null) {
    assertThat(outerError.path("message").isNull()).isTrue();
  } else {
    assertThat(outerError.path("message").asText()).isEqualTo(message);
  }
  JsonNode innerError = outerError.path("errors").path(0);
  assertThat(innerError.path("domain").asText()).isEqualTo("global");
  assertThat(innerError.path("reason").asText()).isEqualTo(reason);
  if (message == null) {
    assertThat(innerError.path("message").isNull()).isTrue();
  } else {
    assertThat(innerError.path("message").asText()).isEqualTo(message);
  }
}
 
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: DeviceInfoEndpoint.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.
 *
 * @param user user object if the caller is authenticated. Set by Cloud Endpoints infrastructure.
 * @return List of all entities persisted.
 * @throws ServiceException if the caller is not authorized to call this method
 */
@SuppressWarnings({"cast", "unchecked"})
public List<DeviceInfo> list(User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  List<DeviceInfo> result = new ArrayList<DeviceInfo>();
  try {
    Query query = mgr.createQuery("select from DeviceInfo as DeviceInfo");
    for (DeviceInfo deviceInfo : (List<DeviceInfo>) query.getResultList()) {
      result.add(deviceInfo);
    }
  } finally {
    mgr.close();
  }
  return result;
}
 
Example #7
Source File: ServletRequestParamReader.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Override
public Object[] read() throws ServiceException {
  // Assumes input stream to be encoded in UTF-8
  // TODO: Take charset from content-type as encoding
  try {
    String requestBody = IoUtil.readStream(endpointsContext.getRequest().getInputStream());
    logger.atFine().log("requestBody=%s", requestBody);
    if (requestBody == null || requestBody.trim().isEmpty()) {
      return new Object[0];
    }
    JsonNode node = objectReader.readTree(requestBody);
    return deserializeParams(node);
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
      | IOException e) {
    throw new BadRequestException(e);
  }
}
 
Example #8
Source File: Auth.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticate the request and retrieve an {@code com.google.appengine.api.users.User}. Should
 * only run once per request.
 */
com.google.appengine.api.users.User authenticateAppEngineUser() throws ServiceException {
  if (!EnvUtil.isRunningOnAppEngine()) {
    return null;
  }
  attr.set(Attribute.REQUIRE_APPENGINE_USER, true);
  User user = authenticate();
  attr.set(Attribute.REQUIRE_APPENGINE_USER, false);
  if (user == null) {
    return null;
  }
  com.google.appengine.api.users.User appEngineUser =
      attr.get(Attribute.AUTHENTICATED_APPENGINE_USER);
  if (appEngineUser != null) {
    return appEngineUser;
  } else {
    return user.getEmail() == null
        ? null : new com.google.appengine.api.users.User(user.getEmail(), "", user.getId());
  }
}
 
Example #9
Source File: RecommendationEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method removes the entity with primary key id. It uses HTTP DELETE method.
 *
 * @param id the primary key of the entity to be deleted.
 */
public void remove(@Named("id") Long id, User user)
    throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Recommendation recommendation = null;
  try {
    recommendation = mgr.find(Recommendation.class, id);
    mgr.remove(recommendation);
  } finally {
    mgr.close();
  }
}
 
Example #10
Source File: PlaceEndpoint.java    From MobileShoppingAssistant-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts the entity into App Engine datastore. It uses HTTP POST method.
 * @param place the entity to be inserted.
 * @param user the user that requested to insert the entity.
 * @return The inserted entity.
 * @throws com.google.api.server.spi.ServiceException if user is not
 * authorized
 */
@ApiMethod(httpMethod = "POST")
public final Place insertPlace(final Place place, final User user) throws
        ServiceException {
    EndpointUtil.throwIfNotAdmin(user);

    ofy().save().entity(place).now();

    return place;
}
 
Example #11
Source File: PlaceEndpoint.java    From MobileShoppingAssistant-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Updates an entity. It uses HTTP PUT method.
 * @param place the entity to be updated.
 * @param user the user that requested the update to the entity.
 * @return The updated entity.
 * @throws com.google.api.server.spi.ServiceException if user is not
 * authorized
 */
@ApiMethod(httpMethod = "PUT")
public final Place updatePlace(final Place place, final User user) throws
        ServiceException {
    EndpointUtil.throwIfNotAdmin(user);

    ofy().save().entity(place).now();

    return place;
}
 
Example #12
Source File: PlaceEndpoint.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 that requested the deletion of the entity.
 * @throws com.google.api.server.spi.ServiceException if user is not
 * authorized
 */
@ApiMethod(httpMethod = "DELETE")
public final void removePlace(@Named("id") final Long id, final User user)
        throws ServiceException {
    EndpointUtil.throwIfNotAdmin(user);

    Place place = findPlace(id);
    if (place == null) {
        LOG.info(
                "Place " + id + " not found, skipping deletion.");
        return;
    }
    ofy().delete().entity(place).now();
}
 
Example #13
Source File: CheckInEndpoint.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 trying to delete the entity.
 * @throws com.google.api.server.spi.ServiceException if user is not
 * authorized
 */
@ApiMethod(httpMethod = "DELETE")
public final void removeCheckIn(@Named("id") final Long id, final User user)
        throws ServiceException {
    EndpointUtil.throwIfNotAdmin(user);

    CheckIn checkIn = findCheckIn(id);
    if (checkIn == null) {
        LOG.info(
                "CheckIn " + id + " not found, skipping deletion.");
        return;
    }
    ofy().delete().entity(checkIn).now();
}
 
Example #14
Source File: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets the entity having primary key id. It uses HTTP GET method.
 *
 * @param id the primary key of the java bean.
 * @return The entity with primary key id.
 */
public Offer get(@Named("id") String id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Offer offer = null;
  try {
    offer = mgr.find(Offer.class, id);
  } finally {
    mgr.close();
  }
  return offer;
}
 
Example #15
Source File: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This inserts the entity into App Engine datastore. It uses HTTP POST method.
 *
 * @param offer the entity to be inserted.
 * @return The inserted entity.
 */
public Offer insert(Offer offer, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);


  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(offer);
  } finally {
    mgr.close();
  }
  return offer;
}
 
Example #16
Source File: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used for updating a entity. It uses HTTP PUT method.
 *
 * @param offer the entity to be updated.
 * @return The updated entity.
 */
public Offer update(Offer offer, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);


  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(offer);
  } finally {
    mgr.close();
  }
  return offer;
}
 
Example #17
Source File: OfferEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method removes the entity with primary key id. It uses HTTP DELETE method.
 *
 * @param id the primary key of the entity to be deleted.
 */
public void remove(@Named("id") String id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Offer offer = null;
  try {
    offer = mgr.find(Offer.class, id);
    mgr.remove(offer);
  } finally {
    mgr.close();
  }
}
 
Example #18
Source File: RecommendationEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets the entity having primary key id. It uses HTTP GET method.
 *
 * @param id the primary key of the java bean.
 * @return The entity with primary key id.
 */
public Recommendation get(@Named("id") Long id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Recommendation recommendation = null;
  try {
    recommendation = mgr.find(Recommendation.class, id);
  } finally {
    mgr.close();
  }
  return recommendation;
}
 
Example #19
Source File: RecommendationEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This inserts the entity into App Engine datastore. It uses HTTP POST method.
 *
 * @param recommendation the entity to be inserted.
 * @return The inserted entity.
 */
public Recommendation insert(Recommendation recommendation, User user)
    throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(recommendation);
  } finally {
    mgr.close();
  }
  return recommendation;
}
 
Example #20
Source File: RecommendationEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used for updating a entity. It uses HTTP PUT method.
 *
 * @param recommendation the entity to be updated.
 * @return The updated entity.
 */
public Recommendation update(Recommendation recommendation, User user)
    throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(recommendation);
  } finally {
    mgr.close();
  }
  return recommendation;
}
 
Example #21
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets the entity having primary key id. It uses HTTP GET method.
 *
 * @param id the primary key of the java bean.
 * @return The entity with primary key id.
 */
public Place get(@Named("id") Long id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Place place = null;
  try {
    place = mgr.find(Place.class, id);
  } finally {
    mgr.close();
  }
  return place;
}
 
Example #22
Source File: DummyGameEndpoint.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Called when the player unlocked an achievement.
 *
 * @param achievement the achievement unlocked by the player.
 * @throws ServiceException
 */
public void achievementUnlocked(@Named("message") String achievement, User user)
    throws ServiceException {

  if (user == null && !Configuration.ALLOW_UNAUTHENTICATED_CALLS) {
    throw new UnauthorizedException("Only authenticated calls are allowed");
  }

  // The actual game backend would probably validate the achievement first
  // and then store it in Datastore. Then it might send push notification
  // to user's friends.
  // In this sample only the send part is implemented and instead of
  // retrieving the list of user's friends, the code just retrieves
  // a few most recently registered devices and sends an alert to them

  String playerName =
      (user == null || user.getEmail() == null) ? "Anonymous User" : user.getEmail();

  String alert = String.format("%1$s unlocked achievement '%2$s'", playerName, achievement);

  EntityManager mgr = null;
  try {
    mgr = getEntityManager();
    Query query =
        mgr.createQuery("select deviceToken from DeviceRegistration d order by timestamp");

    query.setFirstResult(0);
    query.setMaxResults(5);

    @SuppressWarnings("unchecked")
    List<String> deviceTokensOfFriends = query.getResultList();

    log.info("Sent achievement unlocked push notification to " + deviceTokensOfFriends.size()
        + " friend(s) of " + playerName);
    PushNotificationUtility.enqueuePushAlert(alert, deviceTokensOfFriends);
  } finally {
    mgr.close();
  }
}
 
Example #23
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets the entity having primary key id. It uses HTTP GET method.
 *
 * @param id the primary key of the java bean.
 * @return The entity with primary key id.
 */
public CheckIn get(@Named("id") Long id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  CheckIn checkin = null;
  try {
    checkin = mgr.find(CheckIn.class, id);
  } finally {
    mgr.close();
  }
  return checkin;
}
 
Example #24
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method removes the entity with primary key id. It uses HTTP DELETE method.
 *
 * @param id the primary key of the entity to be deleted.
 */
public void remove(@Named("id") Long id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  Place place = null;
  try {
    place = mgr.find(Place.class, id);
    mgr.remove(place);
  } finally {
    mgr.close();
  }
}
 
Example #25
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used for updating a entity. It uses HTTP PUT method.
 *
 * @param checkin the entity to be updated.
 * @return The updated entity.
 */
public CheckIn update(CheckIn checkin, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(checkin);
  } finally {
    mgr.close();
  }
  return checkin;
}
 
Example #26
Source File: CheckInEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method removes the entity with primary key id. It uses HTTP DELETE method.
 *
 * @param id the primary key of the entity to be deleted.
 */
public void remove(@Named("id") Long id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  CheckIn checkin = null;
  try {
    checkin = mgr.find(CheckIn.class, id);
    mgr.remove(checkin);
  } finally {
    mgr.close();
  }
}
 
Example #27
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used for updating a entity. It uses HTTP PUT method.
 *
 * @param place the entity to be updated.
 * @return The updated entity.
 */
public Place update(Place place, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  try {
    mgr.persist(place);
  } finally {
    mgr.close();
  }
  return place;
}
 
Example #28
Source File: DeviceInfoEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets the entity having primary key id. It uses HTTP GET method.
 *
 * @param id the primary key of the java bean.
 * @param user user object if the caller is authenticated. Set by Cloud Endpoints infrastructure.
 * @return The entity with primary key id.
 * @throws ServiceException if the caller is not authorized to call this method
 */
public DeviceInfo get(@Named("id") String id, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

  EntityManager mgr = getEntityManager();
  DeviceInfo deviceinfo = null;
  try {
    deviceinfo = mgr.find(DeviceInfo.class, id);
  } finally {
    mgr.close();
  }
  return deviceinfo;
}
 
Example #29
Source File: DeviceInfoEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This inserts the entity into App Engine datastore. It uses HTTP POST method.
 *
 * @param deviceinfo the entity to be inserted.
 * @param user user object if the caller is authenticated. Set by Cloud Endpoints infrastructure.
 * @return The inserted entity.
 * @throws ServiceException if the caller is unauthenticated
 */
public DeviceInfo insert(DeviceInfo deviceinfo, User user) throws ServiceException {
  EndpointUtil.throwIfNotAuthenticated(user);

  // TODO(user): associate user information (user id / email) with
  // deviceInfo

  log.info("Inserting device info");
  return insertDeviceInfo(deviceinfo);
}
 
Example #30
Source File: PlaceEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * This inserts the entity into App Engine datastore. It uses HTTP POST method.
 *
 * @param place the entity to be inserted.
 * @return The inserted entity.
 */
public Place insert(Place place, User user) throws ServiceException {
  EndpointUtil.throwIfNotAdmin(user);

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