com.google.android.gcm.server.Constants Java Examples

The following examples show how to use com.google.android.gcm.server.Constants. 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: TokenLoaderUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts FCM topic names out of a given Criteria object (e.g. /topics/nameOfcategory).
 * If the Criteria is empty, the given variant ID will be returned as topic name (/topics/variantID)
 *
 * @param criteria the push message filter criteria
 * @param variantID variant ID, used as global fallback FCM topic name
 *
 * @return FCM topic names for the given push message criteria filter.
 */
public static Set<String> extractFCMTopics(final Criteria criteria, final String variantID) {
    final Set<String> topics = new TreeSet<>();

    if (isEmptyCriteria(criteria)) {
        // use the variant 'convenience' topic
        topics.add(Constants.TOPIC_PREFIX + variantID);

    } else if (isCategoryOnlyCriteria(criteria)) {
        // use the given categories
        topics.addAll(criteria.getCategories().stream()
                .map(category -> Constants.TOPIC_PREFIX + category)
                .collect(Collectors.toList()));
    }
    return topics;
}
 
Example #2
Source File: FCMPushNotificationSender.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
/**
 * Process the HTTP POST to the FCM infrastructure for the given list of registrationIDs.
 */
private void processFCM(AndroidVariant androidVariant, List<String> pushTargets, Message fcmMessage, ConfigurableFCMSender sender) throws IOException {


    // push targets can be registration IDs OR topics (starting /topic/), but they can't be mixed.
    if (pushTargets.get(0).startsWith(Constants.TOPIC_PREFIX)) {

        // perform the topic delivery

        for (String topic : pushTargets) {
            logger.info(String.format("Sent push notification to FCM topic: %s", topic));
            Result result = sender.sendNoRetry(fcmMessage, topic);

            logger.trace("Response from FCM topic request: {}", result);
        }
    } else {
        logger.info(String.format("Sent push notification to FCM Server for %d registrationIDs", pushTargets.size()));
        MulticastResult multicastResult = sender.sendNoRetry(fcmMessage, pushTargets);

        logger.trace("Response from FCM request: {}", multicastResult);

        // after sending, let's identify the inactive/invalid registrationIDs and trigger their deletion:
        cleanupInvalidRegistrationIDsForVariant(androidVariant.getVariantID(), multicastResult, pushTargets);
    }
}
 
Example #3
Source File: NotificationsServiceIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Test
public void createGoogleNotifierWithBadAPIKey() throws Exception {

    final String badKey = API_KEY + "bad";

    // create notifier with bad API key
    app.clear();
    app.put("name", "gcm_bad_key");
    app.put("provider", PROVIDER);
    app.put("environment", "development");
    app.put("apiKey", badKey);

    try {
        notifier = (Notifier) app
            .testRequest(ServiceAction.POST, 1, "notifiers").getEntity()
            .toTypedEntity();
    } catch (InvalidRequestException e) {
        assertEquals(Constants.ERROR_INVALID_REGISTRATION, e.getDescription());
    }

}
 
Example #4
Source File: TokenLoaderUtilsTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGcmTopicExtractionForEmptyCriteria() {
    final Criteria criteria = new Criteria();

    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).isNotEmpty();
    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).containsOnly(
            Constants.TOPIC_PREFIX+"123"
    );
}
 
Example #5
Source File: TokenLoaderUtilsTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGcmTopicExtractionForCriteriaWithCategories() {
    final Criteria criteria = new Criteria();
    criteria.setCategories(Arrays.asList("football"));

    assertThat(TokenLoaderUtils.isCategoryOnlyCriteria(criteria)).isTrue();

    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).isNotEmpty();
    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).containsOnly(
            Constants.TOPIC_PREFIX+"football"
    );
}
 
Example #6
Source File: TokenLoaderUtilsTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGCMTopic() {
    final Criteria criteria = new Criteria();
    assertThat(TokenLoaderUtils.isFCMTopicRequest(criteria)).isTrue();
    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).containsOnly(
            Constants.TOPIC_PREFIX+"123"
    );
}
 
Example #7
Source File: TokenLoaderUtilsTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGCMTopicForCategory() {
    final Criteria criteria = new Criteria();
    criteria.setCategories(Arrays.asList("football"));
    assertThat(TokenLoaderUtils.isFCMTopicRequest(criteria)).isTrue();
    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).containsOnly(
            Constants.TOPIC_PREFIX+"football"
    );
}
 
Example #8
Source File: TokenLoaderUtilsTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGCMTopicForVariantAndCategory() {
    final Criteria criteria = new Criteria();
    criteria.setVariants(Arrays.asList("variant1", "variant2"));
    criteria.setCategories(Arrays.asList("football"));

    assertThat(TokenLoaderUtils.isFCMTopicRequest(criteria)).isTrue();
    assertThat(TokenLoaderUtils.extractFCMTopics(criteria, "123")).containsOnly(
            Constants.TOPIC_PREFIX+"football"
    );

}
 
Example #9
Source File: MessageEndpoint.java    From solutions-mobile-shopping-assistant-backend-java with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the message using the Sender object to the registered device.
 * 
 * @param message
 *            the message to be sent in the GCM ping to the device.
 * @param sender
 *            the Sender object to be used for ping,
 * @param deviceInfo
 *            the registration id of the device.
 * @return Result the result of the ping.
 */
private static Result doSendViaGcm(String message, Sender sender,
    DeviceInfo deviceInfo) throws IOException {
  // Trim message if needed.
  if (message.length() > 1000) {
    message = message.substring(0, 1000) + "[...]";
  }

  // This message object is a Google Cloud Messaging object, it is NOT 
  // related to the MessageData class
  Message msg = new Message.Builder().addData("message", message).build();
  Result result = sender.send(msg, deviceInfo.getDeviceRegistrationID(),
      5);
  if (result.getMessageId() != null) {
    String canonicalRegId = result.getCanonicalRegistrationId();
    if (canonicalRegId != null) {
      endpoint.removeDeviceInfo(deviceInfo.getDeviceRegistrationID());
      deviceInfo.setDeviceRegistrationID(canonicalRegId);
      endpoint.insertDeviceInfo(deviceInfo);
    }
  } else {
    String error = result.getErrorCodeName();
    if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
      endpoint.removeDeviceInfo(deviceInfo.getDeviceRegistrationID());
    }
  }

  return result;
}
 
Example #10
Source File: MessagingEndpoint.java    From watchpresenter with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param message The message to send
 */
@ApiMethod(name = "sendMessage")
public void sendMessage(@Named("message") String message, User user) throws IOException, OAuthRequestException {
    if(user == null){
        throw new OAuthRequestException("Not authorized");
    }
    final String userId = PresenterRecord.getUserId(user.getEmail());
    if(com.zuluindia.watchpresenter.backend.Constants.KEEP_ALIVE_MESSAGE.equals(
            message)){
        log.fine("Keep alive from userId: " + userId);
        //This is just a keep-alive. Nothing to do here...
        return;
    }
    log.info("UserId: " + userId);
    if (message == null || message.trim().length() == 0) {
        log.warning("Not sending message because it is empty");
        return;
    }
    // crop longer messages
    if (message.length() > 1000) {
        message = message.substring(0, 1000) + "[...]";
    }
    Sender sender = new Sender(API_KEY);
    Message msg = new Message.Builder().collapseKey("WatchPresenter").timeToLive(0).
            addData("message", message).build();
    PresenterRecord presenterRecord =
            ofy().load().key(Key.create(PresenterRecord.class,userId)).now();
    if(presenterRecord != null) {
        Iterator<String> regIdsIterator = presenterRecord.getRegIds().iterator();
        while (regIdsIterator.hasNext()) {
            String regId = regIdsIterator.next();
            Result result = sender.send(msg, regId, 5);
            if (result.getMessageId() != null) {
                log.info("Message sent to " + regId);
                String canonicalRegId = result.getCanonicalRegistrationId();
                if (canonicalRegId != null) {
                    // if the regId changed, we have to update the datastore
                    log.info("Registration Id changed for " + regId + ". Updating to " + canonicalRegId);
                    regIdsIterator.remove();
                    HashSet<String> newSet = new HashSet<String>(presenterRecord.getRegIds());
                    newSet.add(canonicalRegId);
                    presenterRecord.setRegIds(newSet);
                    ofy().save().entity(presenterRecord).now();
                }
            } else {
                String error = result.getErrorCodeName();
                if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
                    log.warning("Registration Id " + regId + " no longer registered with GCM, removing from datastore");
                    // if the device is no longer registered with Gcm, remove it from the datastore
                    regIdsIterator.remove();
                    ofy().save().entity(presenterRecord).now();
                } else {
                    log.warning("Error when sending message : " + error);
                }
            }
        }
    }
    else{
        log.info("No presenters found for userId: '" + userId + "'");
    }
}