Skip to content
This repository has been archived by the owner on Nov 21, 2023. It is now read-only.

svenkubiak/WebPush4J

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

71 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Maven Central

WebPush4J

Refactored and improved version of WebPush

  • Switch from Gradle to Maven
  • Updated dependencies
  • OkHttp instead of httpcomponents
  • Reduced code, cleanups and refactorings
  • Fluent API
  • Requires Java 21

Usage

  1. Add the WebPush4J dependency to your pom.xml:
<dependency>
    <groupId>de.svenkubiak</groupId>
    <artifactId>webpush4j</artifactId>
    <version>x.x.x</version>
</dependency>
  1. Create a Subscriber or load from e.g. database
String json = ... //Json from initial subscription
Subscriber subscriber = Subscriber.from(json);
  1. Create a notification
Notification notification = Notification.create()
    .withTitle("Hello!!")
    .withBody("New Message from your favorite Server.");
  1. Send the notification to the subscriber
try {
    WebPush.crerate()
		.withPublicKey("PUBLIC KEY") //Vapid public key
 		.withPrivateKey("PRIVATE KEY") //Vapid private key
  		.withSubject("SUBJECT");
        	.withSubscriber(subscriber)
        	.withNotification(notification)
        	.send();
} catch (WebPushException e) {
    e.printStackTrace();
}

Full example

import de.svenkubiak.webpush4j.Notification;
import de.svenkubiak.webpush4j.Subscriber;
import de.svenkubiak.webpush4j.WebPush;
import de.svenkubiak.webpush4j.exceptions.WebPushException;

public class Main {
    public static void main(String... args) {
        Subscriber subscriber = Subscriber.from(json);
                
        Notification notification = Notification.create()
            .withTitle("Hello!!")
            .withBody("New Message from your favorite Server.");
        
        try {
	    WebPush.crerate()
			.withPublicKey("PUBLIC KEY") //Vapid public key
	 		.withPrivateKey("PRIVATE KEY") //Vapid private key
	  		.withSubject("SUBJECT");
	        	.withSubscriber(subscriber)
	        	.withNotification(notification)
	        	.send();
        } catch (WebPushException e) {
            e.printStackTrace();
        }
    }
}