Send push notification from springboot - flutter

I have a springboot application which I’m hosting on my own home server. I have sql database setup on the same.
And for front end I’m planning to use android for initial testing phase then shift it to flutter.
I was wonder how do I send notifications from my spring boot to my front end application. I have seen a few articles on how to send it through fire base but I was wondering if there’s another way of achieving the same without using an external service.
I have setup my server running Ubuntu on on 3 pc which loadbalances my app and want to use one of them to send push notifications.

Please follow the below steps
Install Dependency (Gradle/ Maven)
Gradle
implementation 'com.google.firebase:firebase-admin:8.1.0'
Maven
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>8.1.0</version>
</dependency>
Add firebase-service-account.json file
../src/main/resources/firebase-service-account.json
Open MainApplication java class
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
#SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
#Bean
FirebaseMessaging firebaseMessaging() throws IOException {
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new ClassPathResource("firebase-service-account.json").getInputStream());
FirebaseOptions firebaseOptions = FirebaseOptions
.builder()
.setCredentials(googleCredentials)
.build();
FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "YOUR APP NAME");
return FirebaseMessaging.getInstance(app);
}
}
Create Service
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import org.springframework.stereotype.Service;
#Service
public class FirebaseMessagingService {
private final FirebaseMessaging firebaseMessaging;
public FirebaseMessagingService(FirebaseMessaging firebaseMessaging) {
this.firebaseMessaging = firebaseMessaging;
}
public void sendNotification(String title, String body, String token) throws FirebaseMessagingException {
Notification notification = Notification
.builder()
.setTitle(title)
.setBody(body)
.build();
Message message = Message
.builder()
.setToken(token)
.setNotification(notification)
// .putAllData(note.getData())
.build();
firebaseMessaging.send(message);
// For Send to multiple devices use Multicast Message Builder
MulticastMessage message = MulticastMessage
.builder()
.addAllTokens(<List Of Tokens>)
.setNotification(notification)
// .putAllData(note.getData())
.build();
firebaseMessaging.send(message);
}
}
Usage of service inside controller
#Autowired
private FirebaseMessagingService firebaseService;
public void sendPushMessage(){
firebaseService.sendNotification("Notification title", "Notification Text", "Receiver device token");
}

Related

R2DBC cannot create statement for notifications

I am trying to receive asynchronous notifications from postgresql and r2dbc
I use reactivestream and postgres driver but i cannot make statement
I am new to java and reactivestream, i don't to use a framework like spring.
thank you guys
package com.poc.r2dbc_listen;
import io.r2dbc.postgresql.*;
import io.r2dbc.spi.*;
import org.reactivestreams.*;
import reactor.core.publisher.Flux;
public class R2dbc_listen {
public static void main(String[] args) {
PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
.host("127.0.0.1")
.port(5442)
.username("postgres")
.password("psswd")
.database("database")
.build());
Publisher<? extends Connection> connectionPublisher = connectionFactory.create();
Flux<Notification> listen = connectionPublisher.createStatement("LISTEN mymessage")
.execute()
.flatMap(PostgresqlResult::getRowsUpdated)
.thenMany(receiver.getNotifications());
}
}
It works:
private void listen() {
connection = Mono.from(connectionFactory.create())
.cast(PostgresqlConnection.class)
.block(Duration.ofSeconds(10));
connection.createStatement("LISTEN channel")
.execute()
.flatMap(PostgresqlResult::getRowsUpdated)
.subscribe();
connection.getNotifications()
.delayElements(Duration.ofSeconds(1))
.subscribe(System.out::println);
}

How to fix bellow mentioned code into eclipse to scroll mobile application?

I'm writing script to scroll mobile application up and down but Appium studio code with testng framework not working in Eclipse.
I'm new with this kind of script and testing please help to fix it.
I tried Appium studio code.
but it need to fix to run script.
//package <set your test package>;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.TouchAction;
import java.time.Duration;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.logging.Level;
public class scrollandsave {
private String reportDirectory = "reports";
private String reportFormat = "xml";
private String testName = "scrollandsave";
protected AndroidDriver<AndroidElement> driver = null;
DesiredCapabilities dc = new DesiredCapabilities();
#BeforeMethod
public void setUp() throws MalformedURLException {
dc.setCapability("reportDirectory", reportDirectory);
dc.setCapability("reportFormat", reportFormat);
dc.setCapability("testName", testName);
dc.setCapability(MobileCapabilityType.UDID, "330033acecf394bd");
driver = new AndroidDriver<>(new URL("http://localhost:4723/wd/hub"), dc);
driver.setLogLevel(Level.INFO);
}
#Test
public void testscrollandsave() {
new TouchAction(driver).press(480, 1348).waitAction(Duration.ofMillis(624)).moveTo(338, 312).release().perform();
new TouchAction(driver).press(591, 1376).waitAction(Duration.ofMillis(592)).moveTo(421, 138).release().perform();
driver.findElement(By.xpath("(//*[#id='listAllImgByCat']/*/*/*/*[#id='icPlayVideo'])[1]")).click();
new WebDriverWait(driver, 30).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='EDIT']")));
driver.findElement(By.xpath("//*[#text='EDIT']")).click();
new WebDriverWait(driver, 30).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='SAVE']")));
driver.findElement(By.xpath("//*[#text='SAVE']")).click();
driver.findElement(By.xpath("//*[#text='Export as GIF']")).click();
driver.findElement(By.xpath("//*[#id='btnHome']")).click();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
I expect screen should scroll down whenever I execute above code.
you can try this code driver.executeScript("seetest:client.swipe(\"Down\", 1000, 500)");
. This code would swipe from Down, from the offset 1000 for 500ms.
Visit here for more information

how to work with hybrid mobile application using appium?

Can anybody help me,
I have been try to test hybrid application (developed in kony ide) using appiumbut the coding not executed .then using UIautomator viewer I didn't get "resource id " so im using by.name method. is der any possibility to get resource id?? then how to make work with hybrid application .
My coding
package com.appium.testcase;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver
public class AppiumTest
{
WebDriver driver=null;
#BeforeClass
public void setup()
{
File appDir = new File("E:/Automation/adt-bundle-windows-x86_64-20130514/sdk");
File app = new File(appDir, "WatsCooking.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability(CapabilityType.VERSION, "5.1");// motoe
//capabilities.setCapability(CapabilityType.VERSION, "4.2.1");//lava
capabilities.setCapability(CapabilityType.PLATFORM, "WINDOWS");
capabilities.setCapability("app-Package","com.truetech.watcooking");
//Here we mention the activity name, which is invoked initially as app's first page.
capabilities.setCapability("app-Activity","com.truetech.watscooking.SplashActivity");
capabilities.setCapability("deviceName", "ZX1B328HPW");//motoe
//capabilities.setCapability("deviceName", "0123456789ABCDEF");//lava
capabilities.setCapability("app", app.getAbsolutePath());
try {
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
}
#Test
public void loginTest() throws Exception {
try{
System.out.println("call");
List <WebElement> loginbt =driver.findElements(By.id("btnlogin" ));
loginbt.get(1).click();
}
catch(NullPointerException ex1)
{
//System.out.println( "Value not found in Dropdown to Select");
}
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
You need to expose widget IDs. Do the following:
On the File menu, click Settings. The Project Settings dialog box displays.
Click the Native tab.
On the Common sub-tab, click Expose Widget IDs for Test Automation, and then click Finish.
For the Android platform, when you select to expose widget IDs, an xml file is generated during the build containing the widget IDs of the app. This is explained in detail under Android Limitations.
See the docs for more information.

How to get JSON data via http get request

I am new to Vaadin.
As in topic I would like to make http get reaquest in order to retieve some JSON data.
How could I do this ?
I have been trying to make this by com.google.gwt.http.client.RequestBuilder, but I have obtained
java.lang.UnsatisfiedLinkError: com.google.gwt.xhr.client.XMLHttpRequest.create().
I think the error is associated to GWT client - side nature.
So how could I make http get request in Vaadin 7 server - side ?
Here is my code:
package com.example.soaclient;
import javax.servlet.annotation.WebServlet;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("soaclient")
public class SoaclientUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = SoaclientUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
layout.addComponent(new Label("Thank you for clicking"));
String url = "some URL goes here";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
}
});
layout.addComponent(button);
}
}
With Vaadin you should not use anything from com.google.gwt.http.client package. That is only for client side development, e.g. when you make components that need client side counterparts.
Instead of GWT classes you should just stick to generic JDK libraries. E.g. you could simply use java.net.URL.openStream(). But if you are consuming some REST services, you could refer to my recent JAX-RS 2.0 Client article.

How to resolve java.net.SocketException Permission Denied error?

I have already included the Internet Permissions in the andoird manifest page, still the error seems to persist. I am also recieveing an unknown host excption in the similar code. Kindly guide me through! Ty! :)
package name.id;
import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import org.ksoap2.*;
import org.ksoap2.serialization.*;
import org.ksoap2.transport.*;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FirstPage extends Activity implements android.view.View.OnClickListener
{
/** Called when the activity is first created. */
TextView tv;
Button bu;
EditText et;
private static final String SOAP_ACTION="http://lthed.com/GetFullNamefromUserID";
private static final String METHOD_NAME="GetFullNamefromUserID";
private static final String NAMESPACE="http://lthed.com";
private static final String URL="http://vpwdvws09/services/DirectoryService.asmx";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText) findViewById(R.id.editText1);
tv=(TextView) findViewById(R.id.textView2);
bu=(Button) findViewById(R.id.button1);
bu.setOnClickListener((android.view.View.OnClickListener) this);
tv.setText("");
}
public void onClick(View v)
{
// creating the soap request and all its paramaters
SoapObject request= new SoapObject(NAMESPACE, METHOD_NAME);
//request.addProperty("ID","89385815");// hardcoding some random value
//we can also take in a value in a var and pass it there
//set soap envelope,set to dotnet and set output
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet=true;
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE obj = new HttpTransportSE(URL);
//to make call to server
try
{
obj.call(SOAP_ACTION,soapEnvelope);// in out parameter
SoapPrimitive resultString=(SoapPrimitive)soapEnvelope.getResponse();
//soapObject or soapString
tv.setText("Status : " + resultString);
}
catch(Exception e)
{
tv.setText("Error : " + e.toString());
//e.printStackTrace();
}
}
}
Have you added Internet permission to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
The error was being thrown because of an error in the URL. The URL needed my IP address to function properly rather than the URL i was providing because that the webservice was not able to understand.
Depending on what KSOAP2 version you are using error may vary.
Its recommend that use KSOAP2 v3+ lib.
Simply use following code to override...
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
and also use...