Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.utn.frba.grupo5303.serverenviolibre.services; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClient; import com.amazonaws.services.sns.model.CreatePlatformApplicationRequest; import com.amazonaws.services.sns.model.CreatePlatformApplicationResult; import com.amazonaws.services.sns.model.CreatePlatformEndpointRequest; import com.amazonaws.services.sns.model.CreatePlatformEndpointResult; import com.amazonaws.services.sns.model.MessageAttributeValue; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.sns.SampleMessageGenerator; import com.amazonaws.sns.SampleMessageGenerator.Platform; import static com.amazonaws.sns.SampleMessageGenerator.jsonify; import com.amazonaws.sns.StringUtils; import edu.utn.frba.grupo5303.serverenviolibre.apis.NotificacionesPushAPI; import edu.utn.frba.grupo5303.serverenviolibre.notificaciones.NotificacionPush; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.stereotype.Service; /** * * @author flpitu88 */ @Service public class NotificacionesPushService implements NotificacionesPushAPI { private final AmazonSNS snsClient; String applicationName = "EnvioLibre"; Platform plataforma = SampleMessageGenerator.Platform.GCM; String serverAPIKey = "AIzaSyDS5knB7Hs_kncf_Hx8Y3503-2oCnn26LA"; private static final Logger logger = Logger.getLogger(NotificacionesPushService.class.getName()); public static final Map<Platform, Map<String, MessageAttributeValue>> attributesMap = new HashMap<>(); static { attributesMap.put(Platform.GCM, null); } public NotificacionesPushService() { snsClient = new AmazonSNSClient(new ProfileCredentialsProvider()); } @Override public void enviarNotificacion(NotificacionPush notificacion) { try { logger.log(Level.INFO, "Enviando notificacion al snsId: {0}", notificacion.getGcmIdDestino()); logger.log(Level.INFO, "Enviando notificacion de tipo: {0}", notificacion.getCodigo()); PublishRequest publishRequest = new PublishRequest(); Map<String, MessageAttributeValue> notificationAttributes = getValidNotificationAttributes( attributesMap.get(plataforma)); if (notificationAttributes != null && !notificationAttributes.isEmpty()) { publishRequest.setMessageAttributes(notificationAttributes); } publishRequest.setMessageStructure("json"); // If the message attributes are not set in the requisite method, // notification is sent with default attributes Map<String, String> messageMap = new HashMap<>(); messageMap.put(plataforma.name(), notificacion.getMensajeDeNotificacion()); String message = SampleMessageGenerator.jsonify(messageMap); // Create Platform Application. This corresponds to an app on a // platform. CreatePlatformApplicationResult platformApplicationResult = createPlatformApplication(); // The Platform Application Arn can be used to uniquely identify the // Platform Application. String platformApplicationArn = platformApplicationResult.getPlatformApplicationArn(); // Create an Endpoint. This corresponds to an app on a device. CreatePlatformEndpointResult platformEndpointResult = createPlatformEndpoint("CustomData", notificacion.getGcmIdDestino(), platformApplicationArn); // For direct publish to mobile end points, topicArn is not relevant. publishRequest.setTargetArn(platformEndpointResult.getEndpointArn()); publishRequest.setMessage(message); snsClient.publish(publishRequest); } catch (AmazonServiceException ase) { logger.log(Level.SEVERE, "Caught an AmazonServiceException, which means your request made it " + "to Amazon SNS, but was rejected with an error response for some reason."); logger.log(Level.SEVERE, "Error Message: {0}", ase.getMessage()); logger.log(Level.SEVERE, "HTTP Status Code: {0}", ase.getStatusCode()); logger.log(Level.SEVERE, "AWS Error Code: {0}", ase.getErrorCode()); logger.log(Level.SEVERE, "Error Type: {0}", ase.getErrorType()); logger.log(Level.SEVERE, "Request ID: {0}", ase.getRequestId()); } catch (AmazonClientException ace) { logger.log(Level.SEVERE, "Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with SNS, such as not " + "being able to access the network."); logger.log(Level.SEVERE, "Error Message: {0}", ace.getMessage()); } } private Map<String, MessageAttributeValue> getValidNotificationAttributes( Map<String, MessageAttributeValue> notificationAttributes) { Map<String, MessageAttributeValue> validAttributes = new HashMap<>(); if (notificationAttributes == null) { return validAttributes; } for (Map.Entry<String, MessageAttributeValue> entry : notificationAttributes.entrySet()) { if (!StringUtils.isBlank(entry.getValue().getStringValue())) { validAttributes.put(entry.getKey(), entry.getValue()); } } return validAttributes; } private CreatePlatformEndpointResult createPlatformEndpoint(String customData, String gcmIdDestino, String applicationArn) { CreatePlatformEndpointRequest platformEndpointRequest = new CreatePlatformEndpointRequest(); platformEndpointRequest.setCustomUserData(customData); String token = gcmIdDestino; platformEndpointRequest.setToken(token); platformEndpointRequest.setPlatformApplicationArn(applicationArn); return snsClient.createPlatformEndpoint(platformEndpointRequest); } private CreatePlatformApplicationResult createPlatformApplication() { CreatePlatformApplicationRequest platformApplicationRequest = new CreatePlatformApplicationRequest(); Map<String, String> attributes = new HashMap<>(); attributes.put("PlatformPrincipal", applicationName); attributes.put("PlatformCredential", serverAPIKey); platformApplicationRequest.setAttributes(attributes); platformApplicationRequest.setName(applicationName); platformApplicationRequest.setPlatform(plataforma.name()); return snsClient.createPlatformApplication(platformApplicationRequest); } }