Java Examples for com.notnoop.apns.PayloadBuilder
The following java examples will help you to understand the usage of com.notnoop.apns.PayloadBuilder. These source code samples are taken from different open source projects.
Example 1
| Project: java-apns-master File: SimpleApnsNotificationTest.java View source code |
@Theory
public void deviceTokenPart(String deviceToken, PayloadBuilder payload) {
SimpleApnsNotification msg = new SimpleApnsNotification(deviceToken, payload.build());
byte[] bytes = msg.marshall();
byte[] dt = decodeHex(deviceToken);
assertEquals(dt.length, /* found length */
((bytes[1] & 0xff) << 8) + (bytes[2] & 0xff));
// verify the device token part
assertArrayEquals(dt, Utilities.copyOfRange(bytes, 3, 3 + dt.length));
}Example 2
| Project: liferay-portal-master File: ApplePushNotificationsSender.java View source code |
protected String buildPayload(JSONObject payloadJSONObject) {
PayloadBuilder builder = PayloadBuilder.newPayload();
if (payloadJSONObject.has(PushNotificationsConstants.KEY_BADGE)) {
builder.badge(payloadJSONObject.getInt(PushNotificationsConstants.KEY_BADGE));
}
String body = payloadJSONObject.getString(PushNotificationsConstants.KEY_BODY);
if (Validator.isNotNull(body)) {
builder.alertBody(body);
}
String bodyLocalizedKey = payloadJSONObject.getString(PushNotificationsConstants.KEY_BODY_LOCALIZED);
if (Validator.isNotNull(bodyLocalizedKey)) {
builder.localizedKey(bodyLocalizedKey);
}
JSONArray bodyLocalizedArgumentsJSONArray = payloadJSONObject.getJSONArray(PushNotificationsConstants.KEY_BODY_LOCALIZED_ARGUMENTS);
if (bodyLocalizedArgumentsJSONArray != null) {
List<String> localizedArguments = new ArrayList<>();
for (int i = 0; i < bodyLocalizedArgumentsJSONArray.length(); i++) {
localizedArguments.add(bodyLocalizedArgumentsJSONArray.getString(i));
}
builder.localizedArguments(localizedArguments);
}
boolean silent = payloadJSONObject.getBoolean(PushNotificationsConstants.KEY_SILENT);
if (silent) {
builder.instantDeliveryOrSilentNotification();
}
String sound = payloadJSONObject.getString(PushNotificationsConstants.KEY_SOUND);
if (Validator.isNotNull(sound)) {
builder.sound(sound);
}
payloadJSONObject.remove(PushNotificationsConstants.KEY_BADGE);
payloadJSONObject.remove(PushNotificationsConstants.KEY_BODY);
payloadJSONObject.remove(PushNotificationsConstants.KEY_BODY_LOCALIZED);
payloadJSONObject.remove(PushNotificationsConstants.KEY_BODY_LOCALIZED_ARGUMENTS);
payloadJSONObject.remove(PushNotificationsConstants.KEY_SILENT);
payloadJSONObject.remove(PushNotificationsConstants.KEY_SOUND);
builder.customField(PushNotificationsConstants.KEY_PAYLOAD, payloadJSONObject.toString());
return builder.build();
}Example 3
| Project: onebusaway-application-modules-master File: AlarmServiceImpl.java View source code |
private String getDataAsApnsPayload(String alarmId, JSONObject data) {
PayloadBuilder b = PayloadBuilder.newPayload();
b.customField("alarmId", alarmId);
try {
if (data.has("actionKey"))
b.actionKey(data.getString("actionKey"));
if (data.has("alertBody"))
b.alertBody(data.getString("alertBody"));
if (data.has("badge"))
b.badge(data.getInt("badge"));
if (data.has("sound"))
b.sound(data.getString("sound"));
} catch (JSONException e) {
throw new InvalidArgumentServiceException("data", e.getMessage());
}
return b.build();
}Example 4
| Project: pdi-apple-pushnotifications-master File: PushNotification.java View source code |
/**
* Sends the apple push notification.
*
* @param rowMeta the row meta data.
* @param r the row data.
* @return the date of inactive date the registration id provided.
* @throws KettleFileException the kettle file exception.
* @throws KettleValueException the kettle value exception.
*/
private Date sendPush(RowMetaInterface rowMeta, Object[] r) throws KettleFileException, KettleValueException {
if (r == null) {
// Stop: last line or error encountered
if (log.isDetailed()) {
logDetailed("Last line inserted: stop");
}
return null;
}
final InputStream fileInputStream = KettleVFS.getInputStream(environmentSubstitute(data.certificatePath));
ApnsServiceBuilder apnsServiceBuilder = APNS.newService().withCert(fileInputStream, data.certificatePassword).asBatched(data.waitTime, data.maxWaitTime).withAppleDestination(!meta.isUseSandboxField());
if (meta.isNoErrorDetectionField()) {
apnsServiceBuilder = apnsServiceBuilder.withNoErrorDetection();
}
if (meta.isAsQueuedField()) {
apnsServiceBuilder = apnsServiceBuilder.asQueued();
}
final ApnsService service = apnsServiceBuilder.build();
PayloadBuilder payloadBuilder = APNS.newPayload();
if (meta.getBadgeField() != null && !"".equals(meta.getBadgeField())) {
payloadBuilder.badge(rowMeta.getInteger(r, data.indexOfBadgeField).intValue());
}
if (meta.isShrinksBodyField()) {
payloadBuilder = payloadBuilder.shrinkBody(environmentSubstitute(meta.getShrinksPostfixField()));
}
if (meta.getSoundField() != null) {
payloadBuilder = payloadBuilder.sound(rowMeta.getString(r, data.indexOfSoundField));
}
if (meta.getAlertBodyField() != null) {
payloadBuilder = payloadBuilder.alertBody(rowMeta.getString(r, data.indexOfAlertBodyField));
}
if (meta.getActionLocalizedKeyField() != null) {
payloadBuilder = payloadBuilder.actionKey(rowMeta.getString(r, data.indexOfActionLocalizedKeyField));
}
if (meta.getLocalizedKeyField() != null) {
payloadBuilder = payloadBuilder.localizedKey(rowMeta.getString(r, data.indexOfLocalizedKeyField));
}
if (meta.getLocalizedArgumentsDataPush().size() > 0) {
for (int i = 0; i < meta.getLocalizedArgumentsDataPush().size(); i++) {
payloadBuilder = payloadBuilder.localizedArguments(getInputRowMeta().getString(r, data.locArgDataPushValueNrs.get(i)));
}
}
if (meta.getLaunchImageField() != null) {
payloadBuilder = payloadBuilder.launchImage(rowMeta.getString(r, data.indexOfLaunchImageField));
}
int idx = 0;
for (String cFieldStream : meta.getCustomFieldsStream()) {
payloadBuilder = payloadBuilder.customField(cFieldStream, getInputRowMeta().getString(r, data.customFieldsDataPushValueNrs.get(idx)));
idx++;
}
final String payload = payloadBuilder.build();
if (log.isDetailed()) {
logDetailed("Payload: " + payload);
}
service.push(rowMeta.getString(r, data.indexOfDeviceTokenField), payload);
final Map<String, Date> inactiveDevices = service.getInactiveDevices();
return inactiveDevices.get(meta.getDeviceTokenField());
}Example 5
| Project: aerogear-unifiedpush-server-master File: APNsPushNotificationSender.java View source code |
/**
* Sends APNs notifications ({@link UnifiedPushMessage}) to all devices, that are represented by
* the {@link Collection} of tokens for the given {@link iOSVariant}.
*
* @param variant contains details for the underlying push network, e.g. API Keys/Ids
* @param tokens contains the list of tokens that identifies the installation to which the message will be sent
* @param pushMessage payload to be send to the given clients
* @param pushMessageInformationId the id of the PushMessageInformation instance associated with this send.
* @param callback that will be invoked after the sending.
*/
@Override
public void sendPushMessage(final Variant variant, final Collection<String> tokens, final UnifiedPushMessage pushMessage, final String pushMessageInformationId, final NotificationSenderCallback callback) {
// no need to send empty list
if (tokens.isEmpty()) {
return;
}
final iOSVariant iOSVariant = (iOSVariant) variant;
Message message = pushMessage.getMessage();
APNs apns = message.getApns();
PayloadBuilder builder = APNS.newPayload().alertBody(// adding recognized key values
// alert dialog, in iOS or Safari
message.getAlert()).badge(// little badge icon update;
message.getBadge()).sound(// sound to be played by app
message.getSound()).alertTitle(// The title of the notification in Safari and Apple Watch
apns.getTitle()).alertAction(// The label of the action button, if the user sets the notifications to appear as alerts in Safari.
apns.getAction()).urlArgs(apns.getUrlArgs()).category(// iOS8: User Action category
apns.getActionCategory()).localizedTitleKey(//iOS8 : Localized Title Key
apns.getLocalizedTitleKey());
//this kind of check should belong in java-apns
if (apns.getLocalizedTitleArguments() != null) {
//iOS8 : Localized Title Arguments;
builder.localizedArguments(apns.getLocalizedTitleArguments());
}
// apply the 'content-available:1' value:
if (apns.isContentAvailable()) {
// content-available is for 'silent' notifications and Newsstand
builder = builder.instantDeliveryOrSilentNotification();
}
// adding other (submitted) fields
builder = builder.customFields(message.getUserData());
//add aerogear-push-id
builder = builder.customField(InternalUnifiedPushMessage.PUSH_MESSAGE_ID, pushMessageInformationId);
// we are done with adding values here, before building let's check if the msg is too long
if (builder.isTooLong()) {
// invoke the error callback and return, as it is pointless to send something out
callback.onError("Nothing sent to APNs since the payload is too large");
return;
}
// all good, let's build the JSON payload for APNs
final String apnsMessage = builder.build();
final ApnsService service = apnsServiceHolder.dequeueOrCreateNewService(pushMessageInformationId, iOSVariant.getVariantID(), new ServiceConstructor<ApnsService>() {
@Override
public ApnsService construct() {
ApnsService service = buildApnsService(iOSVariant, callback);
if (service == null) {
callback.onError("No certificate was found. Could not send messages to APNs");
throw new IllegalStateException("No certificate was found. Could not send messages to APNs");
} else {
logger.debug("Starting APNs service");
try {
service.start();
} catch (Exception e) {
throw new PushNetworkUnreachableException(e);
}
return service;
}
}
});
if (service == null) {
throw new SenderResourceNotAvailableException("Unable to obtain a ApnsService instance");
}
try {
logger.debug("Sending transformed APNs payload: {}", apnsMessage);
Date expireDate = createFutureDateBasedOnTTL(pushMessage.getConfig().getTimeToLive());
service.push(tokens, apnsMessage, expireDate);
logger.info(String.format("Sent push notification to the Apple APNs Server for %d tokens", tokens.size()));
apnsServiceHolder.queueFreedUpService(pushMessageInformationId, iOSVariant.getVariantID(), service, new ServiceDestroyer<ApnsService>() {
@Override
public void destroy(ApnsService instance) {
service.stop();
}
});
try {
callback.onSuccess();
} catch (Exception e) {
logger.error("Failed to call onSuccess after successful push", e);
}
} catch (Exception e) {
try {
logger.warn("APNs service died in the middle of sending, stopping it");
try {
service.stop();
} catch (Exception ex) {
logger.error("Failed to stop the APNs service after failure", ex);
}
callback.onError("Error sending payload to APNs server: " + e.getMessage());
} finally {
apnsServiceHolder.freeUpSlot(pushMessageInformationId, iOSVariant.getVariantID());
}
}
}Example 6
| Project: baasbox-master File: APNServer.java View source code |
@Override
public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws Exception {
PushLogger pushLogger = PushLogger.getInstance();
pushLogger.addMessage("............ APN Push Message: -%s- to the device(s) %s", message, deviceid);
ApnsService service = null;
try {
if (BaasBoxLogger.isDebugEnabled())
BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid);
if (!isInit) {
pushLogger.addMessage("............ APNS is not initialized!");
return true;
}
String payload = null;
try {
service = getService();
} catch (com.notnoop.exceptions.InvalidSSLConfig e) {
pushLogger.addMessage("Error sending push notification ...");
pushLogger.addMessage(" Exception is: %s ", ExceptionUtils.getStackTrace(e));
BaasBoxLogger.error("Error sending push notification");
throw new PushNotInitializedException("Error decrypting certificate.Verify your password for given certificate");
}
JsonNode contentAvailableNode = bodyJson.findValue("content-available");
Integer contentAvailable = null;
if (!(contentAvailableNode == null)) {
if (!(contentAvailableNode.isInt()))
throw new PushContentAvailableFormatException("Content-available MUST be an Integer (1 for silent notification)");
contentAvailable = contentAvailableNode.asInt();
}
JsonNode categoryNode = bodyJson.findValue("category");
String category = null;
if (!(categoryNode == null)) {
if (!(categoryNode.isTextual()))
throw new PushCategoryFormatException("Category MUST be a String");
category = categoryNode.asText();
}
JsonNode soundNode = bodyJson.findValue("sound");
String sound = null;
if (!(soundNode == null)) {
if (!(soundNode.isTextual()))
throw new PushSoundKeyFormatException("Sound value MUST be a String");
sound = soundNode.asText();
}
JsonNode actionLocKeyNode = bodyJson.findValue("actionLocalizedKey");
String actionLocKey = null;
if (!(actionLocKeyNode == null)) {
if (!(actionLocKeyNode.isTextual()))
throw new PushActionLocalizedKeyFormatException("ActionLocalizedKey MUST be a String");
actionLocKey = actionLocKeyNode.asText();
}
JsonNode locKeyNode = bodyJson.findValue("localizedKey");
String locKey = null;
if (!(locKeyNode == null)) {
if (!(locKeyNode.isTextual()))
throw new PushLocalizedKeyFormatException("LocalizedKey MUST be a String");
locKey = locKeyNode.asText();
}
JsonNode locArgsNode = bodyJson.get("localizedArguments");
List<String> locArgs = new ArrayList<String>();
if (!(locArgsNode == null)) {
if (!(locArgsNode.isArray()))
throw new PushLocalizedArgumentsFormatException("LocalizedArguments MUST be an Array of String");
for (JsonNode locArgNode : locArgsNode) {
if (locArgNode.isNumber())
throw new PushLocalizedArgumentsFormatException("LocalizedArguments MUST be an Array of String");
locArgs.add(locArgNode.toString());
}
}
JsonNode customDataNodes = bodyJson.get("custom");
Map<String, JsonNode> customData = new HashMap<String, JsonNode>();
if (!(customDataNodes == null)) {
customData.put("custom", customDataNodes);
}
JsonNode badgeNode = bodyJson.findValue("badge");
int badge = 0;
if (!(badgeNode == null)) {
if (!(badgeNode.isNumber()))
throw new PushBadgeFormatException("Badge value MUST be a number");
else
badge = badgeNode.asInt();
}
if (BaasBoxLogger.isDebugEnabled())
BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid + " with sound: " + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey + " with Localized-Key: " + locKey);
if (BaasBoxLogger.isDebugEnabled())
BaasBoxLogger.debug("Localized arguments: " + locArgs.toString());
if (BaasBoxLogger.isDebugEnabled())
BaasBoxLogger.debug("Custom Data: " + customData.toString());
pushLogger.addMessage("APN Push message: " + message + " to the device " + deviceid + " with sound: " + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey + " with Localized-Key: " + locKey);
pushLogger.addMessage("Localized arguments: " + locArgs.toString());
pushLogger.addMessage("Custom Data: " + customData.toString());
pushLogger.addMessage("Timeout: " + timeout);
PayloadBuilder payloadBuilder = APNS.newPayload().alertBody(message).sound(sound).actionKey(actionLocKey).localizedKey(locKey).localizedArguments(locArgs).badge(badge).customFields(customData).category(category);
if (contentAvailable != null && contentAvailable.intValue() == 1) {
payloadBuilder.instantDeliveryOrSilentNotification();
}
payload = payloadBuilder.build();
Collection<? extends ApnsNotification> result = null;
if (timeout <= 0) {
try {
result = service.push(deviceid, payload);
} catch (NetworkIOException e) {
pushLogger.addMessage("Error sending push notification ...");
pushLogger.addMessage(" Exception is: %s ", ExceptionUtils.getStackTrace(e));
BaasBoxLogger.error("Error sending push notification");
BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
}
} else {
try {
Date expiry = new Date(Long.MAX_VALUE);
pushLogger.addMessage("Timeout is > 0 (%d), expiration date is set to %s", timeout, expiry.toString());
result = service.push(deviceid, payload, expiry);
} catch (NetworkIOException e) {
pushLogger.addMessage("Error sending push notification ...");
pushLogger.addMessage(" Exception is: %s ", ExceptionUtils.getStackTrace(e));
BaasBoxLogger.error("Error sending enhanced push notification");
BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
}
}
if (result != null) {
Iterator<? extends ApnsNotification> it = result.iterator();
while (it.hasNext()) {
ApnsNotification item = it.next();
//item.
}
}
//icallbackPush.onSuccess();
return false;
} catch (Exception e) {
pushLogger.addMessage("Error sending push notification (APNS)...");
pushLogger.addMessage(ExceptionUtils.getMessage(e));
throw e;
} finally {
if (service != null)
service.stop();
}
}