WebhookParser { public CallbackRequest handle(String signature, byte[] payload) throws IOException, WebhookParseException { if (signature == null || signature.isEmpty()) { throw new WebhookParseException("Missing 'X-Line-Signature' header"); } if (log.isDebugEnabled()) { log.debug("got: {}", new String(payload, StandardCharsets.UTF_8)); } if (!signatureValidator.validateSignature(payload, signature)) { throw new WebhookParseException("Invalid API signature"); } final CallbackRequest callbackRequest = objectMapper.readValue(payload, CallbackRequest.class); if (callbackRequest == null || callbackRequest.getEvents() == null) { throw new WebhookParseException("Invalid content"); } return callbackRequest; } WebhookParser(@NonNull SignatureValidator signatureValidator); CallbackRequest handle(String signature, byte[] payload); static final String SIGNATURE_HEADER_NAME; }
@Test public void testMissingHeader() { assertThatThrownBy(() -> parser.handle("", "".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(WebhookParseException.class) .hasMessage("Missing 'X-Line-Signature' header"); }
@Test public void testInvalidSignature() { assertThatThrownBy( () -> parser.handle("SSSSIGNATURE", "{}".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(WebhookParseException.class) .hasMessage("Invalid API signature"); }
@Test public void testNullRequest() { final String signature = "SSSSIGNATURE"; final byte[] nullContent = "null".getBytes(StandardCharsets.UTF_8); when(signatureValidator.validateSignature(nullContent, signature)).thenReturn(true); assertThatThrownBy(() -> parser.handle(signature, nullContent)) .isInstanceOf(WebhookParseException.class) .hasMessage("Invalid content"); }
@Test public void testCallRequest() throws Exception { final InputStream resource = getClass().getClassLoader().getResourceAsStream( "callback-request.json"); final byte[] payload = ByteStreams.toByteArray(resource); when(signatureValidator.validateSignature(payload, "SSSSIGNATURE")).thenReturn(true); final CallbackRequest callbackRequest = parser.handle("SSSSIGNATURE", payload); assertThat(callbackRequest).isNotNull(); final List<Event> result = callbackRequest.getEvents(); final MessageEvent messageEvent = (MessageEvent) result.get(0); final TextMessageContent text = (TextMessageContent) messageEvent.getMessage(); assertThat(text.getText()).isEqualTo("Hello, world"); final String followedUserId = messageEvent.getSource().getUserId(); assertThat(followedUserId).isEqualTo("u206d25c2ea6bd87c17655609a1c37cb8"); assertThat(messageEvent.getTimestamp()).isEqualTo( Instant.parse("2016-05-07T13:57:59.859Z")); }