Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have configured a client android Google Cloud Messaging (GCM) to receive push notifications, but I can not configure a server in java to send notifications to devices. How could I?
You can use gcm-server.jar which contains helper methods for GCM messaging.
To get this jar you can install "[Deprecated]Google Cloud Messaging for Android Library" through Android SDK Manager. Don't let the deprecated name confuse you. Only the client part is deprecated, not server side.
After install you can find it at "ADT_SDKROOT\sdk\extras\google\gcm". The sample folder contains a demo server which is very easy to understand.
Sending a GCM message involves only few lines of code:
final String GCM_API_KEY = "yourKey";
final int retries = 3;
final String notificationToken = "deviceNotificationToken";
Sender sender = new Sender(GCM_API_KEY);
Message msg = new Message.Builder().build();
try {
Result result = sender.send(msg, notificationToken, retries);
if (StringUtils.isEmpty(result.getErrorCodeName())) {
logger.debug("GCM Notification is sent successfully");
return true;
}
logger.error("Error occurred while sending push notification :" + result.getErrorCodeName());
} catch (InvalidRequestException e) {
logger.error("Invalid Request", e);
} catch (IOException e) {
logger.error("IO Exception", e);
}
return false;
For """test""" create java console app, add gcm jar file.
try{
Sender sender = new Sender("<senderId>");
ArrayList<String> devicesList = new ArrayList<String>();
devicesList.add(<deviceId>);
String data = "<data>";
Message message = new Message.Builder()
.collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("message",
data)
.build();
MulticastResult result = sender.send(message, devicesList, 1);
sender.send(message, devicesList, 1);
System.out.println(result.toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println(error);
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i built by using java
a telegram bot
which basically get users's name
it can be 1 or 10 or even 40 (i limited it to 50) depends on how much you want to put
now the purpose of this bot is later on when you finish with your specific users
you write a message to send them
now everything is work perfect the id names getting save as well the message
although
how do i send it to all the users i just insert as a private message
if it even possible... by command
i hope i was understandable enough
thats my code:
class Bot extends TelegramLongPollingBot {
public int counter = 0;
public ArrayList names = new ArrayList(50);
public SendMessage mainMessage = new SendMessage();
public String sgMsg = "";
public StringBuilder stringBuilder = new StringBuilder();
public String msg;
public void onUpdateReceived(Update update) {
String command = update.getMessage().getText();
SendMessage sysMsg = new SendMessage();
sysMsg.setChatId(update.getMessage().getChatId());
String firstCdletter;
firstCdletter = Character.toString(command.charAt(0));
if (command.equals("/start")) {
sysMsg.setText("Enter the user's id, to finish send: Ok");
try {
execute(sysMsg);
} catch (TelegramApiException e) {
e.printStackTrace();
}
counter = 0;
names.clear();
sgMsg = "";
}else if (firstCdletter.equals("#")) {
String user = command;
names.add(counter);
counter++;
}else if(command.equals("/ok")){
sysMsg.setText("Good, now write your message you want to deliver");
try {
execute(sysMsg);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}else if(command.equals("/done")){
msg = stringBuilder.toString();
}else{
sgMsg = update.getMessage().getText();
stringBuilder.append(sgMsg + " ");
}
}
thank you all for your time and help
Unfortunately, you cannot send message via #username, the only identify you can use is UID (looks like 109780439).
And by the way, bot have to chat with that user before, or you will got an 400 Error.
Trying to get the weight from the weighing scale through a port connected to a USB that's connected to my android phone. The data is coming through but I don't know how to convert it properly. This is the code I'm currently using to convert the data:
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
This is what I'm currently getting:
The number 14700t was supposed to show on the textview.
This question already has answers here:
Sending the same but modifed object over ObjectOutputStream
(2 answers)
Closed 6 years ago.
So, I am trying to make simple java socket chat. Before any chat would be possible, simple login with only a username is required. I send "Message" ("Poruka" in code) objects over ObjectOutputStream, and "Message" objects contain "Sender, Receiver, Content, bool Login, bool Logout".
The sequence is:
Client sends Message (Poruka) with Login set to true and Sender set to username (works fine)
Server Thread successfuly receives the Message, and adds new user to list if similar username doesn't exist in list already (works fine)
Upon receiving information of adding user to the list on server side, Server Thread sends appropriate answer to the Client (here comes the issue).
The Server Thread code:
try {
Poruka poruka = null;
Poruka odgovor = new Poruka();
while (true) {
poruka = (Poruka) in.readObject();
System.out.println("salje prije ifLogin "+poruka.getSalje()+" "+ poruka.isLogin());
if (poruka.isLogin()) {
System.out.println("salje "+poruka.getSalje());
boolean success = Server.dodajKorisnika(poruka.getSalje());
System.out.println("Uspjeh? "+success);
//System.out.println("Jeste LOGIN poruka "+odgovor.getSadrzaj()+" "+odgovor.isLogout());
if (success) {
System.out.println("USLO U TRUE BLOK");
odgovor.setSadrzaj("ACCEPTED");
out.writeObject(odgovor);
// out.flush();
}
else{
odgovor.setSadrzaj("DENIED");
out.writeObject(odgovor);
// out.flush();
System.out.println(odgovor.getSadrzaj()+ " IZ BLOKA NEUSPJEH");
}
}
System.out.println("PORUKA " + poruka.isLogin() + " " + poruka.getSalje());
}
} catch (Exception ex) {
ex.printStackTrace();
}
Here, Server Thread does good job at setting return Message with appropriate login information. If login is successful, Message.Content is set to "ACCEPTED", else it's set to "DENIED". I double checked that.
Now, the problem: Client always receives Message object with "ACCEPTED" for some reason?
Here is the Client Thread code:
public boolean prijaviSe(String ime) {
boolean ret = false;
Poruka prijava = new Poruka();
prijava.setSalje(ime);
prijava.setLogin(true);
try {
System.out.println("PRIJAVA " + prijava.getSalje());
out.writeObject(prijava);
out.flush();
while (true) {
Poruka odgovor = (Poruka) in.readObject();
System.out.println("ODGOVOR "+odgovor.getSadrzaj());
if (odgovor.getSadrzaj().equals("ACCEPTED")) {
prijavljen = true;
System.out.println("accepted");
gui.setLabelaPrijavljen("Korisnik uspješno prijavljen");
break;
} else if (odgovor.getSadrzaj().equals("DENIED")) {
prijavljen = false;
System.out.println("denied");
gui.setLabelaPrijavljen("Promijenite korisničko ime!");
}
}//while
} catch (Exception ex) {
ex.printStackTrace();
}
return ret;
}
I am not sure even what to look for here? Is it a threading issue? Some kind of OutputStream / InputStream conflict? Or is it just my logic? Don't have a clue.
Java serialization is designed to serialize a graph of objects. If an object appears more than once it is only sent once and both references point to the same object. E.g. You can have two objects A and B where each has a reference to each other. But using references and only passing each object once, this all works
Where this doesn't work as expected is with mutable objects. If you pass an object more than once you get a reference to the same object. It does/can't check whether you changed it.
Note this means you are retaining every object ever written or read which can be a subtle memory leak.
The solution is to call reset() which clears the cached objects and sends any object again including updates.
This question already has an answer here:
Java networking, really strange error
(1 answer)
Closed 8 years ago.
Im working on a little chat program and now i have a huge problem and i can not solve it.
I dont know where the mistake could be, for me the code is right. So i really really need help. I have 2 threads in my server, 1 thread for accepting clients and the other for the streams. And the thread for the streams is not working right. It sends only 1 time a message back to the client and multiple clients are also not working. And there is another strange problem. I can only send 1 message back, if i put the JOptionPane-message called "Sockets empty" in the else statement, without it doesnt work.
Here is the stream thread code:
private static Runnable streamThread = new Runnable()
{
public void run()
{
while(true)
{
if(!(socketList.isEmpty()))
{
for(int i = 0; i < socketList.size(); i++)
{
try
{
String key = socketList.get(i);
if(socketHashMap.containsKey(key))
{
Socket connection = socketHashMap.get(key);
ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());
String response = (String) ois.readObject();
ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());
oos.writeObject(key + ": " + response);
oos.flush();
}
if(connection.isClosed())
{
JOptionPane.showMessageDialog(null, "Client closed connection", "Info", JOptionPane.INFORMATION_MESSAGE);
}
}
catch (IOException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "ERROR: " + e.getMessage(), "ALARM", JOptionPane.ERROR_MESSAGE);
try {
connection.close();
connection.shutdownInput();
connection.shutdownOutput();
listClientsModel.remove(i);
} catch (IOException e1) {
}
}
}
}
else
{
JOptionPane.showMessageDialog(null, "SOCKETS LEER", "Info", JOptionPane.INFORMATION_MESSAGE);
}
}
}
};
And if you want to see the complete servercode :
http://pastebin.com/sxGGRnJv
The documentation for getOutputStream says:
Closing the returned OutputStream will close the associated socket.
And that is the problem. You create an ObjectOutputStream, but don't keep a reference to that object around. As this object gets garbage collected, it will call close() which will close the socket's output stream.
Same problem with the InputStream.
You could, for example, create a class that contains your socket and input and output stream and store that in your map instead of just the socket. That way you can re-use the streams.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am developing a java web application and I want to know how to take a certain field (table and/or output-text) value from a certain website. Assuming that this component has always the same ID does anyone know how can I retrieve this information?
I don't know if anyone has ever faced this issue but if anyone has any idea please share.
Thank you.
In general:
1.) Retrieve the pages markup by reading it through an HTTPConnection to the URL in your application
2.) Parse the Markup using a framework like jsoup and retrieve the value you need.
More specifically, here is some example code for jsoup:
HttpClient http = new DefaultHttpClient();
String htmlcode = "";
HttpGet request = new HttpGet("http://www.example.com");
HttpResponse response = null;
try {
response = http.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(response != null){
BufferedReader read = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while((line = read.readLine()) != null){
htmlcode += line;
}
}
// at this point we have the pages markup
Document doc = Jsoup.parse(htmlcode);
Elements lis = doc.getElementsByTag("li"); // get all entries in lists
for(Element el : lis){
String val = el.text().trim();
// do something for each list entry
}
You are talking about web scraping, check this library for php:
http://simplehtmldom.sourceforge.net/