How to encrypt payload in Java Admin SDK - java

I used to use GCM, now I 've passed to FCM.For this reason, right now, I am sending WebPush Message with Firebase Admin SDK. When I sent webpush, clients get notification without data. According to texts which I read, I have to encyrpt payload with JWT. However I could not find a way to encyrpt.
I've clientAuthSecret, clientPublicKey and endpoint. I need your leadership.
#Override
public WebPushResponse sendMessageToMultipleUsers(List<String> registrationTokens) throws IOException {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(new ClassPathResource(firebaseConfigPath).getInputStream())).build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
logger.info("Firebase application has been initialized");
}
MulticastMessage message = MulticastMessage.builder()
.setWebpushConfig(WebpushConfig.builder()
.setNotification(new WebpushNotification("$GOOG up 1.43% on the day",
"$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.", "https://my-server/icon.png"))
.build())
.addAllTokens(registrationTokens).build();
BatchResponse response = null;
try {
response = FirebaseMessaging.getInstance().sendMulticastAsync(message).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (response != null && response.getFailureCount() > 0) {
List<SendResponse> responses = response.getResponses();
List<String> failedTokens = new ArrayList<>();
for (int i = 0; i < responses.size(); i++) {
if (!responses.get(i).isSuccessful()) {
// The order of responses corresponds to the order of the registration tokens.
failedTokens.add(registrationTokens.get(i));
}
}
System.out.println("List of tokens that caused failures: " + failedTokens);
}
return null;
}

Related

Can't send objects using Sockets

Hello Im writing an app in which client sends name of room to server, server creates it and then sends back whole list of rooms. I have problem with receiving this object from server also whats interesting when I close clients' app and open again I have list of rooms just like it should be. I refresh room list in client app but its always empty only reopening helps that's pretty weird and I don't know an issue of this.
On client side:
getIs() method is returning is object
getOs() method returning os object
this.os = new ObjectOutputStream(clientSocket.getOutputStream());
this.is = new ObjectInputStream(clientSocket.getInputStream());
private void createRoom(ActionEvent event) {
String roomName = "CreateRoom ";
roomName += setRoomName();
String response = null;
try {
client.getOs().writeObject(roomName);
response = (String) client.getIs().readObject();
System.out.println(response);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void refreshRooms() {
String response = null;
try {
client.getOs().writeObject("RefreshRooms");
response = (String) client.getIs().readObject();
System.out.println(response);
rooms = (Rooms) client.getIs().readObject();
System.out.println("Print in client: ");
rooms.printAllRooms();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server:
this.os = new ObjectOutputStream(connection.getOutputStream());
this.is = new ObjectInputStream(connection.getInputStream());
public void run() {
String inputRequest = null;
try {
while((inputRequest = (String) ois.readObject()) != null) {
System.out.println(inputRequest);
handleRequest(inputRequest);
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("Client has disconnected.");
e.printStackTrace();
}
}
private void handleRequest(String request) {
String response = null;
String[] msg = request.split(" ");
if(msg[0].equals("CreateRoom")) {
try {
oos.writeObject("You want create a room.");
Room newRoom = new Room(msg[1]);
rooms.addRoom(newRoom);
System.out.println("Created room: " + newRoom.getName());
System.out.println("\n Print after creation: ");
rooms.printAllRooms();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if (msg[0].equals("RefreshRooms")) {
try {
oos.writeObject("You want list of rooms.");
System.out.println("Print before send.");
rooms.printAllRooms();
oos.writeObject(rooms);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
///EDIT:
So I removed PrintWriter and BufferedReader objects and now Im using only Object Streams. What doesn't work now is:
I create some rooms one after another and then refresh rooms list on clients app - in that case I get all rooms
But when I create one room refresh then create another and refresh I get only 1 room after 2nd refresh, so basically when I refresh server sends me always the same object from 1st send and I don't know how to change it.
Also Im printing these rooms on server side and always get all rooms so room creation is OK.
You could try to flush the buffered streams:
os.flush()
This will force the stream to actually send the bytes of the serialized object. Without that, the BufferedOutputStream might just wait around and buffer data, as the name says. This is done so that the size of the sent packets does not become too small, which would result in a lot of overhead if you want to send multiple objects.
If you are done, you should close the stream anyway.

ListenableFuture - how to wait before return

I have a Spring Cloud microservice that posts message on a Kafka broker, this microservice is accessible thru a REST api.
I want to return the submit status back to the caller but seems like Java does not await. How to make this to wait either success or failure before my code returns?
Heres the code:
kafkaProduc.send("topictest", msg).addCallback(
new ListenableFutureCallback<SendResult<String, ExecutionDataMessage>>() {
#Override
public void onSuccess(SendResult<String, ExecutionDataMessage> result) {
eresp.status = "ok";
eresp.msg = "message submitted successfully";
}
#Override
public void onFailure(Throwable ex) {
eresp.status = "error";
eresp.msg = "failure while sending data to kafka. exception: " + ex.getMessage();
}
});
HttpStatus erespStatus = eresp.status == "ok" ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST;
return new ResponseEntity<ExecutionResponse>(eresp, erespStatus);
The callback is for when you want an asynchronous result. If you want to block the calling thread, use future.get()...
ListenableFuture<SendResult<String, String>> future = template.send("foo", "bar");
try {
SendResult<String, String> sendResult = future.get(10, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Thread.currentThread.interrupt();
}
catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kafkaproducer.send returns a future. If you want to wait then perhaps you would prefer the following:
kafkaProduc.send("topictest", msg).get(1L, TimeUnit.SECONDS);
Then failures are likely to raise an exception rather than invoking your on error callback.

Get Tweets from Twitter hbc API

public class TwitterStreamImpl implements TwitterStream {
public void setUpStream() throws InterruptedException {
final String consumerKey = getTwitterCredentials().get(0).toString();
final String consumerSecret = getTwitterCredentials().get(1).toString();
final String token = getTwitterCredentials().get(2).toString();
final String secret = getTwitterCredentials().get(3).toString();
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
StatusesFilterEndpoint endpoint = new StatusesFilterEndpoint();
// add some track terms
endpoint.trackTerms(Lists.newArrayList("twitterapi", "#yolo", "trump", "donald", "lol"));
Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
// Authentication auth = new BasicAuth(username, password);
// Create a new BasicClient. By default gzip is enabled.
BasicClient client = new ClientBuilder()
.hosts(Constants.STREAM_HOST)
.endpoint(endpoint)
.authentication(auth)
.processor(new StringDelimitedProcessor(queue))
.build();
// Establish a connection
client.connect();
// Do whatever needs to be done with messages
for (int msgRead = 0; msgRead < 1000; msgRead++) {
if (client.isDone()) {
System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
break;
}
String msg = queue.poll(5, TimeUnit.SECONDS);
if (msg == null) {
System.out.println("Did not receive a message in 5 seconds");
} else {
System.out.println(msg);
}
}
client.stop();
}
/**
* Reads twitterStup.txt from C:/Users/"user"/documents/ and returns them as
* an array
*
* #return Twitter Api Credentials
*/
private ArrayList getTwitterCredentials() {
BufferedReader in;
String str;
ArrayList<String> list = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("*******"));
while ((str = in.readLine()) != null) {
list.add(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
The console log says:
Did not receive a message in 5 seconds
And it says that every five seconds.
I want to "sysout" (live) every tweet, that has one of the endpoint trackTerms in it. But there is no error or something similar.
Is there a problem with the proxy perhaps?
The code is working, as it is at the time. The problem was the proxy. Because I've been in the office-network, the connection to the stream wasn't possible. So i tried it with my own notebook, guess what, it worked.

Why same notification is pushed many times to android and iphone devices

I have used javapns for pushing notifications to ios and android.gcm.server to push notification for android devices. But when I sent one notifications to many devices each device get multiple number of copies of the notification sent. Sometimes this number is 2 and sometimes 3. Hardly it delivers only one which I expect always. Any Ideas ?
My code is as below
public void pushNotificationsToAndroid(String pushMessage,
String contentType, String content, String notification_id,
List<String> devices) {
try {
Sender sender = new Sender(
properties
.getProperty("notification.android.senderIdDemo"));
com.google.android.gcm.server.Message message = new com.google.android.gcm.server.Message.Builder()
.collapseKey("1").timeToLive(3).delayWhileIdle(true)
.addData("message", pushMessage)
.addData("content_type", contentType)
.addData("content", content)
.addData("notification_id", notification_id).build();
MulticastResult result = sender.send(message, devices, 1);
if (result.getResults() == null) {
System.out.println(result.getFailure());
logger.debug("getFailure() of sender.send() method :",
result.getFailure());
}
} catch (Exception exception) {
logger.error("erorr push notification ");
}
System.out.println("sent not at " + new Date());
logger.debug(
"exit pushNotificationsToAndroid() method : current time is ",
new Date());
}
public void pushNotificationsToIOS(String pushMessage, String contentType,
String content, String notification_id, List<String> devices)
{
boolean production = true;
String password = properties
.getProperty("notification.ios.password");
String keyStroke = properties
.getProperty("notification.ios.certFileName");
AppleNotificationServer jksServer = null;
try {
jksServer = new AppleNotificationServerBasicImpl(keyStroke,
password, ConnectionToAppleServer.KEYSTORE_TYPE_JKS,
production);
} catch (KeystoreException keystoreException) {
logger.error("erorr creating jksServer");
}
PushNotificationPayload payload = PushNotificationPayload.complex();
try {
payload.addAlert(pushMessage);
} catch (JSONException e2) {
logger.error("erorr creating payload alert");
}
try {
payload.addCustomDictionary("content_type", contentType);
} catch (JSONException e1) {
logger.error("erorr creating payload content_type");
}
try {
payload.addCustomDictionary("content", content);
} catch (JSONException e1) {
logger.error("erorr creating payload content");
}
try {
payload.addCustomDictionary("notification_id", notification_id);
} catch (JSONException e1) {
logger.error("erorr creating payload notification_id");
}
PushNotificationManager pushManager = new PushNotificationManager();
try {
pushManager.initializeConnection(jksServer);
} catch (CommunicationException | KeystoreException e) {
logger.error("erorr connecting Server");
}
try {
List<PushedNotification> notifications = pushManager
.sendNotifications(payload, Devices.asDevices(devices));
} catch (CommunicationException | KeystoreException e) {
logger.error("erorr push notifications");
}
}
In android official site says about some reasons for duplicate message conditions .

How to append listview items from the Internet

I'm still struggling to find an answer to my question. I want to download 3 strings for each item in the listview to the phone. I know how to get all the data from the server, just not how to append the data to the litview, I'm really annoyed and this problem is dragging me down.
My Code:
public class ChatService extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
try {
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CheckLogin();
private void CheckLogin() {
// TODO Auto-generated method stub
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//put intent here(21/3/12);
} else {
Log.w("HttpPost", "FALSE");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
//now we'll return the data that the PHP set from the MySQL Database.
if (in.equals("True")); {
Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
}
}
// end bracket for "ContactsandIm"
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Use an ArrayAdapter on your list, and add items to this adapter, then call notifyDatasetChanged on it, and zou
First of all when we connect to Server using the Network Threads, then you should go for AsyncTask or Handlers. Which is specially used for handling such Threads.
ListView can be created by using default Listview ans also the Custom Listview where we can design our own Row design in the Row.xml and the same design will be used for all the rows.
If you want move forward or go for some advanced Listview then even we can use 'n' number of designs for different rows.
Here in your case, You should use a AsyncTask for fetching the data and use the Listview for displaying rows.
You can get more information from the below link.
https://docs.google.com/leaf?id=0B2qCFbmeiTFxN2ViZjVlOTUtNmY3ZS00NThhLTg3N2UtYjVkYjgyM2Y4MWUy&hl=en&authkey=COeP8JYN

Categories