Пример #1
0
  public static void main(String args[]) {
    Sender sender = new Sender("AIzaSyAvibNcQ9OwiB_h-glX4SD4ZQjJGgWiJ9k");
    Message message = new Message.Builder().build();

    Result result = null;
    try {
      result =
          sender.send(
              message,
              "APA91bHttEIg49kyyJtbA0tQT-6Na6V5moCqqN6QJrT_hjMHZkSB85KOR6N5_rINEXpqsTJzoQtNQ-fKY52kwidhGDayyO8iqJuz9exMan2aUUklRqJ0K0Ar4f0_lvqOzYoZ4qH8SoX5FUfs-cUbqhWoz_cgt8GKMg",
              1);
    } catch (IOException e) {
      System.out.println("Error occured.");
      e.printStackTrace();
    }
    if (result.getMessageId() != null) {
      String canonicalRegId = result.getCanonicalRegistrationId();
      if (canonicalRegId != null) {
        // same device has more than on registration ID: update database
        System.out.println("same device has more than on registration ID: update database");
      }
    } else {
      String error = result.getErrorCodeName();
      if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
        // application has been removed from device - unregister
        // database
        System.out.println("application has been removed from device - unregister database");
      }
    }
    System.out.println("Inforr:" + result.toString());
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    Result result = null;

    String share = request.getParameter("shareRegId");

    // GCM RedgId of Android device to send push notification
    String regId = "";
    if (share != null && !share.isEmpty()) {
      regId = request.getParameter("regId");
      System.out.println("regId111: " + regId);
      PrintWriter writer = new PrintWriter("GCMRegId.txt");
      writer.println(regId);
      writer.close();
      request.setAttribute("pushStatus", "GCM RegId Received.");
      Sender sender = new Sender(GOOGLE_SERVER_KEY);
      Message message =
          new Message.Builder()
              .timeToLive(30)
              .delayWhileIdle(true)
              .addData(MESSAGE_KEY, "loopback connector")
              .build();
      result = sender.send(message, regId, 1);
      request.getRequestDispatcher("index.jsp").forward(request, response);
    } else {

      try {
        BufferedReader br = new BufferedReader(new FileReader("GCMRegId.txt"));
        regId = br.readLine();
        br.close();
        String userMessage = request.getParameter("message");
        Sender sender = new Sender(GOOGLE_SERVER_KEY);
        Message message =
            new Message.Builder()
                .timeToLive(30)
                .delayWhileIdle(true)
                .addData(MESSAGE_KEY, userMessage)
                .build();
        System.out.println("regId: " + regId);
        result = sender.send(message, regId, 1);
        request.setAttribute("pushStatus", result.toString());
      } catch (IOException ioe) {
        ioe.printStackTrace();
        request.setAttribute("pushStatus", "RegId required: " + ioe.toString());
      } catch (Exception e) {
        e.printStackTrace();
        request.setAttribute("pushStatus", e.toString());
      }
      request.getRequestDispatcher("index.jsp").forward(request, response);
    }
  }
Пример #3
0
  /**
   * 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;
  }
Пример #4
0
 <T> T send(GoogleMessage gmsg, PushResponseHandler<T> handler) {
   try {
     Result result = sender.sendNoRetry(gmsg.toPayload(), gmsg.token());
     return result.getMessageId() != null
         ? handler.onGoogleSuccess(gmsg, result)
         : handler.onGoogleFail(gmsg, result);
   } catch (IOException ex) {
     return handler.onGoogleThrow(gmsg, ex);
   }
 }
Пример #5
0
  @Override
  public void onNewDataComplete() {
    // gather data
    Map<String, String> payload = new HashMap<>();
    payload.put(DATA_KEY_SOURCE, source.getId());
    payload.put(DATA_KEY_DEBUG, Boolean.TRUE.toString());

    String collapseKey = source.getId();

    final List<String> devices = new ArrayList<>();
    devices.add(client.getGcmClientId());

    // send
    Message.Builder builder = new Message.Builder().collapseKey(collapseKey);
    for (Map.Entry<String, String> e : payload.entrySet()) {
      builder.addData(e.getKey(), e.getValue());
    }

    MulticastResult multicastResult;
    try {
      multicastResult = gcmSender.send(builder.build(), devices, 5);
    } catch (IOException io) {
      setErrorResult(io);
      return;
    }

    // analyze the results
    List<Result> results = multicastResult.getResults();
    for (int i = 0; i < devices.size(); i++) {
      String regId = devices.get(i);
      Result result = results.get(i);
      String messageId = result.getMessageId();
      if (messageId != null) {
        Log.info("Succesfully sent message to device: " + regId + "; messageId = " + messageId);
        String canonicalRegId = result.getCanonicalRegistrationId();
        if (canonicalRegId != null) {
          // same device has more than on registration id: update it
          setUpdateClientResult(client, new GcmClient(client.getId(), canonicalRegId));
          return;
        }
      } else {
        String error = result.getErrorCodeName();
        if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
          // application has been removed from device - unregister it
          setRemoveClientResult(client);
          return;
        } else {
          setErrorResult(error);
          return;
        }
      }
    }

    setSuccessResult();
  }
Пример #6
0
 /**
  * Send to the first 10 devices (You can modify this to send to any number of devices or a
  * specific device)
  *
  * @param message The message to send
  */
 public void sendMessage(@Named("message") String message) throws IOException {
   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().addData("message", message).build();
   List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list();
   for (RegistrationRecord record : records) {
     Result result = sender.send(msg, record.getRegId(), 5);
     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(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);
       }
     }
   }
 }
Пример #7
0
  /** Processes the request to add a new message. */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    List<String> devices = Datastore.getDevices();

    String status;
    if (devices.isEmpty()) {
      status = "Message ignored as there is no device registered!";
    } else {
      // NOTE: check below is for demonstration purposes; a real application
      // could always send a multicast, even for just one recipient
      if (devices.size() == 1) {
        // send a single message using plain post

        String registrationId = devices.get(0);

        Message message = new Message.Builder().build();
        Result result = sender.send(message, registrationId, 5);

        status = "Sent message to one device: " + result;
      } else {
        // send a multicast message using JSON
        // must split in chunks of 1000 devices (GCM limit)
        int total = devices.size();
        List<String> partialDevices = new ArrayList<String>(total);
        int counter = 0;
        int tasks = 0;
        for (String device : devices) {
          counter++;
          partialDevices.add(device);
          int partialSize = partialDevices.size();
          if (partialSize == MULTICAST_SIZE || counter == total) {
            asyncSend(partialDevices);
            partialDevices.clear();
            tasks++;
          }
        }
        status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices";
      }
    }
    req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
    getServletContext().getRequestDispatcher("/home").forward(req, resp);
  }
  /**
   * 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.
   * @throws IOException
   */
  private static Result sendViaGcm(Message msg, Sender sender, DeviceInfo deviceInfo)
      throws IOException {
    Result result = sender.send(msg, deviceInfo.getDeviceRegistrationId(), 5);
    LOG.info("Sent ping to device of user: " + deviceInfo.getUserHandle());
    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;
  }
  @Override
  public <T> void send(T message) {
    // meh:
    sender = new Sender(googleAPIKey);

    List<MobileApplicationInstance> instances = this.getInstances();
    // String token = instances.get(0).getDeviceToken();

    String token = "123";
    Message msg =
        new Message.Builder()
            .addData("text", message.toString())
            .addData("title", "FOOOOO")
            .build();

    // send it out.....
    try {
      sender.send(msg, token, 0);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #10
0
  /** @param params */
  @ApiMethod(name = "sendone", path = "sendone", httpMethod = ApiMethod.HttpMethod.POST)

  // public void sendOneMessage(@Named("message") String message,@Named("regid")String regid,
  //  @Named("from") String from, @Named("to") String to) throws IOException {

  public void sendOneMessage(@Named("params") ArrayList<String> params) throws IOException {

    logger.warning(" params size " + params.size());
    logger.warning(" zero is msg " + params.get(0));
    logger.warning(" one is regid " + params.get(1));
    logger.warning(" two is from " + params.get(2));
    logger.warning(" three is to " + params.get(3));

    // logger.warning("sendOneMessage called");
    // logger.warning(" send() from " + from + " to " + to + " message " + message + " reg id "
    // +regid);

    /// logger.warning(message+" / "+regid+" / "+from+" / "+to);

    String message = params.get(0);
    String regid = params.get(1);
    String from = params.get(2);
    String to = params.get(3);

    logger.warning(
        " send() from " + from + " to " + to + " message " + message + " reg id " + regid);

    if (message == null || message.trim().length() == 0) {
      logger.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()
            //			.delayWhileIdle(true)
            .addData(com.ramogi.xbox.backend.Constants.TO, to)
            .addData(com.ramogi.xbox.backend.Constants.FROM, from)
            .addData(com.ramogi.xbox.backend.Constants.MSG, message)
            .build();

    try {

      Result result = sender.send(msg, regid, 5);

      Contactplus contactplus = new Contactplus();
      contactplus.setRegId(regid);
      contactplus.setEmail(from);
      if (result.getMessageId() != null) {
        logger.info("Message sent to " + regid);
        String canonicalRegId = result.getCanonicalRegistrationId();
        if (canonicalRegId != null) {
          // if the regId changed, we have to update the datastore
          // logger.info("Registration Id changed for " + regid + " updating to " + canonicalRegId);
          // record.setRegId(canonicalRegId);
          // ofy().save().entity(record).now();
          contactplus.setRegId(canonicalRegId);
          ofy().save().entity(contactplus).now();
        }
      } else {
        String error = result.getErrorCodeName();
        if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
          logger.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
          // ofy().delete().entity(record).now();
          ofy().delete().entity(contactplus).now();
        } else {
          logger.warning("Error when sending message : " + error);
        }
      }

      logger.info("Result: " + result.toString());
    } catch (IOException e) {
      logger.warning(e.getMessage());
    }
  }