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

The following examples show how to use com.google.android.gcm.server.Message. 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: ProspectiveSearchServlet.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
private void sendGcmAlert(String subId, String regId)
    throws IOException {
  String gcmKey = backendConfigManager.getGcmKey();
  boolean isGcmKeySet = !(gcmKey == null || gcmKey.trim().length() == 0);

  // Only attempt to send GCM if GcmKey is available
  if (isGcmKeySet) {
    Sender sender = new Sender(gcmKey);
    Message message = new Message.Builder().addData(SubscriptionUtility.GCM_KEY_SUBID, subId)
        .build();
    Result r = sender.send(message, regId, GCM_SEND_RETRIES);
    if (r.getMessageId() != null) {
      log.info("ProspectiveSearchServlet: GCM sent: subId: " + subId);
    } else {
      log.warning("ProspectiveSearchServlet: GCM error for subId: " + subId +
          ", senderId: " + gcmKey + ", error: " + r.getErrorCodeName());
      ArrayList<String> deviceIds = new ArrayList<String>();
      deviceIds.add(regId);
      SubscriptionUtility.clearSubscriptionAndDeviceEntity(deviceIds);
    }
  } else {
    // Otherwise, just write a log entry
    log.info(String.format("ProspectiveSearchServlet: GCM is not sent: GcmKey: %s ", 
        isGcmKeySet));
  }
}
 
Example #2
Source File: ProspectiveSearchServlet.java    From solutions-mobile-backend-starter-java with Apache License 2.0 6 votes vote down vote up
private void sendGcmAlert(String subId, String regId)
    throws IOException {
  String gcmKey = backendConfigManager.getGcmKey();
  boolean isGcmKeySet = !(gcmKey == null || gcmKey.trim().length() == 0);

  // Only attempt to send GCM if GcmKey is available
  if (isGcmKeySet) {
    Sender sender = new Sender(gcmKey);
    Message message = new Message.Builder().addData(SubscriptionUtility.GCM_KEY_SUBID, subId)
        .build();
    Result r = sender.send(message, regId, GCM_SEND_RETRIES);
    if (r.getMessageId() != null) {
      log.info("ProspectiveSearchServlet: GCM sent: subId: " + subId);
    } else {
      log.warning("ProspectiveSearchServlet: GCM error for subId: " + subId +
          ", senderId: " + gcmKey + ", error: " + r.getErrorCodeName());
      ArrayList<String> deviceIds = new ArrayList<String>();
      deviceIds.add(regId);
      SubscriptionUtility.clearSubscriptionAndDeviceEntity(deviceIds);
    }
  } else {
    // Otherwise, just write a log entry
    log.info(String.format("ProspectiveSearchServlet: GCM is not sent: GcmKey: %s ", 
        isGcmKeySet));
  }
}
 
Example #3
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 #4
Source File: GCMProvider.java    From tigase-extension with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sendPushNotification(BareJID jid, PushRegistrationInfo info) throws IOException {
    if (gcmSender == null) {
        log.log(Level.WARNING, "GCM provider not configured correctly.");
        return;
    }

    String regId = info.getRegistrationId();
    if (regId != null) {
        com.google.android.gcm.server.Message msg = new com.google.android.gcm.server.Message.Builder()
            .collapseKey("new")
            .addData("action", GCM_DATA_ACTION)
            .priority(Message.Priority.HIGH)
            .build();
        Result result = gcmSender.send(msg, regId, GCM_MAX_RETRIES);
        if (result.getMessageId() != null) {
            log.log(Level.FINE, "GCM message sent: {0}", result.getMessageId());
            String newId = result.getCanonicalRegistrationId();
            if (newId != null) {
                // update registration id
                info.setRegistrationId(newId);
            }
        }
        else {
            log.log(Level.INFO, "GCM error: {0}", result.getErrorCodeName());
        }
    }
    else {
        log.log(Level.INFO, "No registration ID found for {0}", jid);
    }
}
 
Example #5
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 #6
Source File: MessagingEndpoint.java    From MobileShoppingAssistant-sample with Apache License 2.0 4 votes vote down vote up
/**
 * Send to the first NUMBER_OF_DEVICE devices (you can modify this to send
 * to any number of devices or a specific device).
 * @param payload The message to send
 * @throws java.io.IOException if unable to send the message.
 */
@ApiMethod(httpMethod = "POST")
public final void sendMessage(final ImmutableMap<String, String> payload)
        throws IOException {
    if (payload == null || payload.size() == 0) {
        LOG.warning("Not sending message because payload is empty");
        return;
    }

    Sender sender = new Sender(Constants.GCM_API_KEY);
    Message msg = new Message.Builder()
            .setData(payload)
            .build();
    List<Registration> records = ofy().load()
            .type(Registration.class).limit(NUMBER_OF_DEVICES)
            .list();
    for (Registration record : records) {
        Result result = sender.send(msg, record.getRegId(),
                MAXIMUM_RETRIES);
        if (result.getMessageId() != null) {
            LOG.info("Message sent to " + record.getRegId());
            String canonicalRegId = result.getCanonicalRegistrationId();
            if (canonicalRegId != null) {
                // if the regId changed, we have to update the datastore
                LOG.info("Registration Id changed for " + record.getRegId()
                        + " updating to "
                        + canonicalRegId);
                record.setRegId(canonicalRegId);
                ofy().save().entity(record).now();
            }
        } else {
            String error = result.getErrorCodeName();
            if (error.equals(com.google.android.gcm.server.
                    Constants.ERROR_NOT_REGISTERED)) {
                LOG.warning("Registration Id " + record.getRegId()
                        + " no longer registered with GCM, "
                        + "removing from datastore");
                // if the device is no longer registered with Gcm, remove it
                // from the datastore
                ofy().delete().entity(record).now();
            } else {
                LOG.warning("Error when sending message : " + error);
            }
        }
    }
}
 
Example #7
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 + "'");
    }
}
 
Example #8
Source File: FCMPushNotificationSender.java    From aerogear-unifiedpush-server with Apache License 2.0 4 votes vote down vote up
/**
 * Sends FCM notifications ({@link UnifiedPushMessage}) to all devices, that are represented by
 * the {@link List} of tokens for the given {@link AndroidVariant}.
 */
@Override
public void sendPushMessage(Variant variant, Collection<String> tokens, UnifiedPushMessage pushMessage, String pushMessageInformationId, NotificationSenderCallback callback) {

    // no need to send empty list
    if (tokens.isEmpty()) {
        return;
    }

    final List<String> pushTargets = new ArrayList<>(tokens);
    final AndroidVariant androidVariant = (AndroidVariant) variant;

    // payload builder:
    Builder fcmBuilder = new Message.Builder();

    org.jboss.aerogear.unifiedpush.message.Message message = pushMessage.getMessage();
    // add the "recognized" keys...
    fcmBuilder.addData("alert", message.getAlert());
    fcmBuilder.addData("sound", message.getSound());
    fcmBuilder.addData("badge", String.valueOf(message.getBadge()));

    /*
    The Message defaults to a Normal priority.  High priority is used
    by FCM to wake up devices in Doze mode as well as apps in AppStandby
    mode.  This has no effect on devices older than Android 6.0
    */
    fcmBuilder.priority(
            message.getPriority() ==  Priority.HIGH ?
                                      Message.Priority.HIGH :
                                      Message.Priority.NORMAL
                       );

    // if present, apply the time-to-live metadata:
    int ttl = pushMessage.getConfig().getTimeToLive();
    if (ttl != -1) {
        fcmBuilder.timeToLive(ttl);
    }

    // iterate over the missing keys:
    message.getUserData().keySet()
            .forEach(key -> fcmBuilder.addData(key, String.valueOf(message.getUserData().get(key))));

    //add the aerogear-push-id
    fcmBuilder.addData(InternalUnifiedPushMessage.PUSH_MESSAGE_ID, pushMessageInformationId);

    Message fcmMessage = fcmBuilder.build();

    // send it out.....
    try {
        logger.debug("Sending transformed FCM payload: {}", fcmMessage);

        final ConfigurableFCMSender sender = new ConfigurableFCMSender(androidVariant.getGoogleKey());

        // we are about to send HTTP requests for all tokens of topics of this batch
        PrometheusExporter.instance().increasetotalPushAndroidRequests();

        // send out a message to a batch of devices...
        processFCM(androidVariant, pushTargets, fcmMessage , sender);

        logger.debug("Message batch to FCM has been submitted");
        callback.onSuccess();

    } catch (Exception e) {
        // FCM exceptions:
        callback.onError(String.format("Error sending payload to FCM server: %s", e.getMessage()));
    }
}
 
Example #9
Source File: PushEndpoint.java    From divide with Apache License 2.0 3 votes vote down vote up
private String sendMessageToDevice(String email, String input) throws ServerDAO.DAOException, IOException {

        Credentials user = getUserByEmail(dao,email);

        Sender sender = new Sender(keyManager.getPushKey());
        Message message = new Message.Builder().addData("body", input).build();

        MulticastResult result = sender.send(message, Arrays.asList(user.getPushMessagingKey()), 5);

        System.out.println("Result = " + result);
        return result.toString();
    }