@Test @Ignore public void testActions() { // setAttributes try { subscription.setAttributes("RawMessageDelivery", "false"); refreshSubscription(); Assert.assertEquals("false", subscription.getAttributes().get("RawMessageDelivery")); } catch (InvalidParameterException ipe) { Assert.assertTrue(ipe.getMessage().contains( "delivery protocol [application] does not support raw message delivery.")); } }
@Override public SubscribeResult subscribe(SubscribeRequest subscribeRequest) throws AmazonClientException { final String protocol = subscribeRequest.getProtocol().toLowerCase(); if (!protocol.equals("sqs")) { throw new InvalidParameterException("endpoint protocol " + protocol + " not supported"); } final String topicArn = subscribeRequest.getTopicArn(); if (!_subscriptionsForTopic.containsKey(topicArn)) { throw new InvalidParameterException("no such topic " + topicArn); } String subscriptionArn = topicArn + ":" + RandomStringUtils.randomNumeric(7); if (!_subscriptionsByArn.containsKey(subscriptionArn)) { _subscriptionsByArn.put(subscriptionArn, new Subscription(). withTopicArn(topicArn). withProtocol(protocol). withSubscriptionArn(subscriptionArn). withEndpoint(subscribeRequest.getEndpoint())); _subscriptionsForTopic.get(topicArn).add(subscriptionArn); } return new SubscribeResult().withSubscriptionArn(subscriptionArn); }
@Test(expected = AmazonSNSException.class) public void testAddPermission_withInvalidParameterMock_shouldThrowException() { mockSns(new MockParameters(InvalidParameterException.class)); AddPermissionRequest addPermissionRequest = new AddPermissionRequest() .withActionNames(ImmutableList.of("READ", "WRITE")) .withAWSAccountIds(ImmutableList.of("1", "2")).withLabel("unsecure-topic").withTopicArn( "arn:aws:sns:us-east-1:123456789012:my_corporate_topic:02034b43-fefa-4e07-a5eb-3be56f8c54ce"); sns.addPermission(addPermissionRequest); }
@Test public void createTopicWithInvalidName() { assertSNSThrownBy(() -> sns.createTopic("test topic")) .isInstanceOf(InvalidParameterException.class) .hasErrorCode("InvalidParameter") .hasErrorMessage("Invalid parameter: test topic") .hasStatusCode(400); }
public void verifyPlatformApplication(AmazonSNS client) { try { if (!BatchCreatePlatformEndpointSample.listOfRegions .contains(this.region = this.applicationArn.split(":")[3])) { System.err.println("[ERROR] The region " + region + " is invalid"); System.exit(BatchCreatePlatformEndpointSample.MALFORMED_PROPERTIES_ERROR_CODE); } } catch (ArrayIndexOutOfBoundsException aioobe) { System.err.println("[ERROR] The ARN " + this.applicationArn + " is malformed"); System.exit(BatchCreatePlatformEndpointSample.MALFORMED_PROPERTIES_ERROR_CODE); } client.setEndpoint("https://sns." + this.region + ".amazonaws.com/"); try { GetPlatformApplicationAttributesRequest applicationAttributesRequest = new GetPlatformApplicationAttributesRequest(); applicationAttributesRequest .setPlatformApplicationArn(this.applicationArn); @SuppressWarnings("unused") GetPlatformApplicationAttributesResult getAttributesResult = client .getPlatformApplicationAttributes(applicationAttributesRequest); } catch (NotFoundException nfe) { System.err .println("[ERROR: APP NOT FOUND] The application ARN provided: " + this.applicationArn + " does not correspond to any existing platform applications. " + nfe.getMessage()); System.exit(BatchCreatePlatformEndpointSample.NOT_FOUND_ERROR_CODE); } catch (InvalidParameterException ipe) { System.err .println("[ERROR: APP ARN INVALID] The application ARN provided: " + this.applicationArn + " is malformed" + ipe.getMessage()); System.exit(BatchCreatePlatformEndpointSample.NOT_FOUND_ERROR_CODE); } }
private void publishNotification( final String arn, final SNSMessage<?> message, final QualifiedName name, final String errorMessage, final String counterKey, final boolean retryOnLongMessage ) { this.notificationMetric.recordTime(message, Metrics.TimerNotificationsBeforePublishDelay.getMetricName()); try { final AsyncHandler<PublishRequest, PublishResult> handler = new AsyncHandler<PublishRequest, PublishResult>() { @Override public void onError(final Exception exception) { if (retryOnLongMessage && (exception instanceof InvalidParameterException || exception instanceof InvalidParameterValueException)) { log.error("SNS Publish message exceeded the size threshold", exception); notificationMetric.counterIncrement( Metrics.CounterSNSNotificationPublishMessageSizeExceeded.getMetricName()); final SNSMessage<Void> voidMessage = new SNSMessage<>(message.getId(), message.getTimestamp(), message.getRequestId(), message.getType(), message.getName(), null); publishNotification(arn, voidMessage, name, errorMessage, counterKey, false); } else { notificationMetric.handleException(name, errorMessage, counterKey, message, exception); } } @Override public void onSuccess(final PublishRequest request, final PublishResult publishResult) { log.info("Successfully published message to topic {} with id {}", arn, publishResult.getMessageId()); log.debug("Successfully published message {} to topic {} with id {}", message, arn, publishResult.getMessageId()); notificationMetric.counterIncrement(counterKey); notificationMetric.recordTime(message, Metrics.TimerNotificationsPublishDelay.getMetricName()); } }; client.publishAsync(arn, mapper.writeValueAsString(message), handler); } catch (final Exception e) { notificationMetric.handleException(name, errorMessage, counterKey, message, e); } }
static SNSExceptionBuilder newInvalidParameterException(String reason) { return new SNSExceptionBuilder( new InvalidParameterException("Invalid parameter: " + reason), "InvalidParameter", 400); }
private static AWSThrowableAssert assertSNSParamThrownBy(ThrowableAssert.ThrowingCallable shouldRaiseThrowable) { return assertSNSThrownBy(shouldRaiseThrowable) .isInstanceOf(InvalidParameterException.class) .hasErrorCode("InvalidParameter") .hasStatusCode(400); }
String createApplicationEndpoint(String backendId, String appId, PushService service, String token) { Optional<PlatformApplication> application = getApplication(appId, service); if (!application.isPresent()) throw Exceptions.illegalArgument(// "push service [%s] of mobile application [%s] not registered in AWS", // appId, service); String applicationArn = application.get().getPlatformApplicationArn(); String endpointArn = null; try { endpointArn = getSnsClient() .createPlatformEndpoint(// new CreatePlatformEndpointRequest()// .withPlatformApplicationArn(applicationArn)// .withToken(token))// .getEndpointArn(); } catch (InvalidParameterException e) { String message = e.getErrorMessage(); Utils.info("Exception message: %s", message); Pattern p = Pattern.compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + "with the same token.*"); Matcher m = p.matcher(message); if (m.matches()) { // The platform endpoint already exists for this token, but with // additional custom data that // createEndpoint doesn't want to overwrite. Just use the // existing platform endpoint. endpointArn = m.group(1); } else { throw e; } } if (endpointArn == null) throw new RuntimeException("failed to create device notification endpoint: try again later"); boolean updateNeeded = false; try { GetEndpointAttributesResult endpointAttributes = getSnsClient() .getEndpointAttributes(new GetEndpointAttributesRequest().withEndpointArn(endpointArn)); updateNeeded = !endpointAttributes.getAttributes().get("Token").equals(token) || !endpointAttributes.getAttributes().get("Enabled").equalsIgnoreCase("true"); } catch (NotFoundException nfe) { // We had a stored ARN, but the platform endpoint associated with it // disappeared. Recreate it. endpointArn = null; } if (endpointArn == null) throw new RuntimeException("failed to create device notification endpoint: try again later"); if (updateNeeded) { // The platform endpoint is out of sync with the current data; // update the token and enable it. Map<String, String> attribs = new HashMap<>(); attribs.put("Token", token); attribs.put("Enabled", "true"); getSnsClient().setEndpointAttributes(// new SetEndpointAttributesRequest()// .withEndpointArn(endpointArn)// .withAttributes(attribs)); } return endpointArn; }
String createApplicationEndpoint(String backendId, String appId, PushServices service, String token) { PlatformApplication application = getApplication(backendId, appId, service)// .orElseThrow(// () -> Exceptions.illegalArgument(// "push service [%s] not registered for mobile application [%s]", // appId, service)); String endpointArn = null; String applicationArn = application.getPlatformApplicationArn(); try { endpointArn = getSnsClient() .createPlatformEndpoint(// new CreatePlatformEndpointRequest()// .withPlatformApplicationArn(applicationArn)// .withToken(token))// .getEndpointArn(); } catch (InvalidParameterException e) { String message = e.getErrorMessage(); Utils.info("Exception message: %s", message); Pattern p = Pattern.compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + "with the same token.*"); Matcher m = p.matcher(message); if (m.matches()) { // The platform endpoint already exists for this token, but with // additional custom data that // createEndpoint doesn't want to overwrite. Just use the // existing platform endpoint. endpointArn = m.group(1); } else { throw e; } } if (endpointArn == null) throw new RuntimeException("failed to create device notification endpoint: try again later"); boolean updateNeeded = false; try { GetEndpointAttributesResult endpointAttributes = getSnsClient() .getEndpointAttributes(new GetEndpointAttributesRequest().withEndpointArn(endpointArn)); updateNeeded = !endpointAttributes.getAttributes().get("Token").equals(token) || !endpointAttributes.getAttributes().get("Enabled").equalsIgnoreCase("true"); } catch (NotFoundException nfe) { // We had a stored ARN, but the platform endpoint associated with it // disappeared. Recreate it. endpointArn = null; } if (endpointArn == null) throw new RuntimeException("failed to create device notification endpoint: try again later"); if (updateNeeded) { // The platform endpoint is out of sync with the current data; // update the token and enable it. Map<String, String> attribs = new HashMap<String, String>(); attribs.put("Token", token); attribs.put("Enabled", "true"); getSnsClient().setEndpointAttributes(// new SetEndpointAttributesRequest()// .withEndpointArn(endpointArn)// .withAttributes(attribs)); } return endpointArn; }