この Javaからウェブプッシュを簡単に送信する方法 という記事をもとに、VAPID用に書き換えてみました。
lombokなしにしています。
package sample;
import java.security.GeneralSecurityException;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import nl.martijndwars.webpush.PushService;
@Configuration
public class WebPushConfig {
WebPushProperties webPushProperties;
public WebPushConfig(WebPushProperties webPushProperties) {
this.webPushProperties = webPushProperties;
}
@ConfigurationProperties(prefix = "sample")
public record WebPushProperties(String vapidPublicKey, String vapidPrivateKey) {}
@Bean
public PushService pushService() throws GeneralSecurityException {
Security.addProvider(new BouncyCastleProvider());
return new PushService(webPushProperties.vapidPublicKey(), webPushProperties.vapidPrivateKey, "mailto:foo@example.com");
}
}
application.yml
sample:
vapid-public-key: xxxxxxxxxxxxxxxxxxx
vapid-private-key: yyyyyyyyyyyyyyyyyyyyyyyy
これらは、ツールを使ってあらかじめ作成しておきます。
package sample;
import java.nio.charset.StandardCharsets;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.martijndwars.webpush.Encoding;
import nl.martijndwars.webpush.Notification;
import nl.martijndwars.webpush.PushService;
public class Push {
private static Logger logger = LoggerFactory.getLogger(Push.class);
private PushService pushService;
public Push(PushService pushService) {
this.pushService = pushService;
}
public int sendPush(String endpoint, String publicKey, String authenticationSecret, byte[] payload) {
try {
Notification notification = new Notification(endpoint, publicKey, authenticationSecret, payload);
HttpResponse response = pushService.send(notification, Encoding.AES128GCM);
logger.info(endpoint);
logger.info(authenticationSecret);
logger.info("" + response.getStatusLine());
logger.info("" + response.getEntity());
logger.info(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
for (Header h: response.getAllHeaders()) {
logger.info("" + h);
}
return response.getStatusLine().getStatusCode();
} catch (Exception exception) {
logger.error(exception.getMessage());
return -1;
}
}
}
publicKeyは、Pushサービスサーバーから返ってきた、p256dhです。同じくauthenticationSecretは、authです。
他に必要な部分の短いサンプルができたら、追記します。
追記 サンプルつくりました。Web Push Notification Sample