I'm using a code to recover passwords. when a user requested to reset password, it send a SMS to user's phone. my problem is that it gives me this output in the middle of the runtime.
===============================================================================
Now Sleeping - Hit enter to terminate.
but I want to send the enter signal automatically so the job will be terminated automatically.how can I do this?
My code is below:
if (rs3.next()) {
String port = "COM3"; //Modem Port.
int bitRate = 460800; //this is also optional. leave as it is.
String modemName = "Huawei E165G"; //this is optional.
String modemPin = ""; //Pin code if any have assigned to the modem.
String SMSC = "+947100003"; //Message Center Number ex. Mobitel
GsmModem gsmModem = new GsmModem();
GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);
gsmModem.Sender(mobileno, "Your new password is "+rs3.getString("password")+" Please change your password in your next login. >>Fast Inventory<<"); // (tp, msg)
System.out.println("Code came here");
Statement s2=Db.connectDb().createStatement();
s2.executeUpdate("UPDATE user SET lockstatus='0' WHERE uid='"+username.getText()+"'");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
I'm using SMSlib.
Related
I am using the code from this tutorial with minimal modifications. Here is my code: `
public static void receiveEmail(String hst, String stype, String user, String password) {
try {
Properties props = new Properties();
props.put("mail.store.protocol", "pop3");
props.put("mail.pop3s.host", hst);
props.put("mail.pop3s.port", "995");
props.put("mail.pop3.starttls.enable", "true");
Session sess = Session.getDefaultInstance(props);
Store st = sess.getStore("pop3s");
st.connect(hst, user, password);
Folder emailFolder = st.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
Message message = messages[229];
System.out.println("Welcome To Email");
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
String body = "body";
Multipart part = (Multipart) message.getContent();
MimeBodyPart mimePart = null;
for (int i = 0; i < part.getCount(); i++) {
mimePart = (MimeBodyPart) part.getBodyPart(i);
System.out.println(mimePart.getContent());
System.out.println("========");
}
emailFolder.close(false);
st.close();
}// catch (NoSuchProviderException e) {e.printStackTrace();}
catch (MessagingException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
`
I am calling receive email from a driver class. This is literally the only method being called.
I will run the code and it will work fine, printing the contents of the 229th email. Then, if i run it again, with not changes whatsoever, I get an array index out of bounds exception saying index 229 is out of bounds for length 229. As I understand it, when i run it, the code works fine, but somehow the email I want to access is no longer accessible. I have been trying to access the last email for testing purposes and I knew which number it is. What I think is happening is that the code is making the email I just accessed unavailable. I just added a print line and confirmed that when i first run it, the length is such that the message being accessed is the last element in the array, upon running the program again, the array is mysteriously one element smaller. I have verified that the emails are actually not disappearing from my account. I think i started at email 250 or something and have been gradually losing access. Another interesting thing to note is that yesterday, I was working with a different email account that only had 19 emails in it, after a short period of time, I was suddenly unable to list out the emails in that account with code. The emails were there, I could send emails with code, but not access the emails stored on that account.
I have built a Spring CLI app which communicates with a server in an async fashion. The server was given, I did not create it, basically my app is required to open a TCP socket and send a JSON through it, then it sends back a JSON. It is mandatory not to use CLI parameters, but instead in the callback of the request I want to show the user a set of options for which he needs to select by inserting the corresponding number on the CLI. Most probably I'm not doing right something, because after entering the command, I see spring> on the console (this is an expected behavior) and it will block the async callback unless I press something (nothing is printed to the CLI when I receive the callback unless I press a bunch of enters - this is unexpected). To read from the console so far I used JLine's command line, what I would like to achieve is that when I get the response from the server and the callback is served, the console is given to the thread on which the callback is running (I instantly print the contents of the callback to the console, and I'm able to read the input without any tricks).
Some code:
public void runReceiver(){
receiverThread = new Thread(() -> {
byte[] digit = null;
int nb;
Iterator<CommandListener> it;
CommandListener listener;
String message;
List<CommandListener> listenersToRemove = new ArrayList<>();
while (true) {
try {
nb = communicatorInput.readInt();
digit = new byte[nb];
communicatorInput.readFully(digit);
} catch (IOException e) {
e.printStackTrace();
}
it = listeners.iterator();
while (it.hasNext()){
listener = it.next();
if (digit != null && digit.length > 0) {
message = new String(digit);
// the message was not acknowledged
if(message.contains("NACK")){
try {
listener.onError(message);
if (listener.isDone()) {
listenersToRemove.add(listener);
}
} catch (Exception e){
e.printStackTrace();
}
} else try {
listener.onCompleted(message);
} catch (InvalidObjectException e){
Main.logger.debug(String.format("Response could not be parsed as %s", listener.getCommandType()));
} catch (Exception e){
e.printStackTrace();
}
if (listener.isDone()) {
listenersToRemove.add(listener);
}
}
}
listeners.removeAll(listenersToRemove);
}
}, "receiverThread");
receiverThread.setDaemon(true);
receiverThread.start();
Then a CLI command (it expects no input here):
#CliCommand(value="start", help = "Starts stuff")
public void start() throws IOException, InterruptedException {
// this method is passed to the thread with the listener
getAvailabilities().updateAvailabilities("all", "all", "all", someListener);
}
And the callback for that listener:
someListener = new CommandListener() {
private String source = "Start some listener";
#Override
public void onCompleted(String r) throws IOException {
System.out.println("Which would you like to start?");
getAvailabilities().printAvailableBrands();
String brandNumber = "";
while(Objects.equals(brandNumber, "")){
System.out.println("Please enter the number of the Brand: ");
//when the callback arrives here I still only see ">spring:" and I get nothing printed on the console
brandNumber = cr.readLine();
if(!isInputAllowed(brandNumber, getAvailabilities().AvailableBrands.size())){
brandNumber = "";
}
}
BrandName = getAvailabilities().AvailableBrands.get(Integer.parseInt(brandNumber) - 1);
//updating the availabilities narrows down the things I list to the console, so I send an update after every selection
getAvailabilities().updateAvailabilities("all", BrandName, "all", getInterfaceListener);
done = true;
}
This might slightly connect to the issue that sometimes while debugging the CLI in Idea, it gets whacky inputs, eg. when I insert start it says No such command as ar, and if I press enter again, it'll say (some of) the rest: No such command as stt.
The problem is here:
if (listener.isDone()) {
listenersToRemove.add(listener);
}
If you want your listeners to be executed asynchronously you should not check their completion right away on the same thread as it will most likely return false.
The issue you might be having is that your listeners schedule some task but have no time to finish it as you immediately remove them after the loop:
listeners.removeAll(listenersToRemove);
It is very hard to tell what your logic is but I guess in the next while iteration your list is empty.
I've been making a instant chat program, and wanted to make it possible for users to "whisper" or private message one another. The way I implemented that is the user would type:
/w [username] [message]
I then send it to the server which sends it to all the users. The users then have to check to see if its sent to them, this is that method:
if (message.startsWith("/msg/")) {
message = message.trim();
message = message.substring(5);
String[] words = message.split("//s");
String UserName = null;
try {
String username = words[2];
UserName = username;
System.out.println(UserName);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error reading the whisper command!");
}
if (UserName == client.getName()) {
List<String> list = new ArrayList<String>(Arrays.asList(words));
list.removeAll(Arrays.asList(2));
words = list.toArray(words);
String text = words.toString();
text = "You've been whispered! " + message;
console(text);
}
Everytime I send a /w when I'm testing it always give the ArrayIndexOutOfBoundsException. I also modify the message in the sending. Heres that method:
else if (message.toLowerCase().startsWith("/w")) {
message = "/msg/" + client.getName() + message;
message = "/m/" + message + "/e/";
txtMessage.setText("");
}
I also added a whole bunch more options for the actual code for the users, I made it /whisper, /m, /msg, and /message, but those are all just copies of this with a different input. Why is it giving me an ArrayIndextOutOfBoundsException, when the 3rd place in the words array SHOULD be the username that the sender is trying to send it to. Obviously this probably isn't the best way to send private messages, and if any of you guys have a simpler way I can implement to my server, please go ahead and let me know! Just know that I am a young, new programmer and so I will probably have a lot of questions.
The slashes in your split() regex are backwards. You need
String[] words = message.split("\\s");
You can also just use a space
String[] words = message.split(" ");
I'm working on an mailing app. The app can receive multiple recipient addresses. Once the "Send" button is pressed, a single message is sent containing multiple recipient addresses. Of course, by having this kind of system, there would be an SendFailedException if at least one of the addresses is invalid. Naturally, I would catch this and exception and try to work around with it. Here's my code so far:
catch (SendFailedException e)
{ try
{
System.out.println(e.getValidUnsentAddresses()!=null);
if (e.getValidUnsentAddresses()!=null) //with valid unsent addresses
{
String invalid = new String();
String valid = new String();
for (int i=0; i<e.getInvalidAddresses().length; i++)
{
invalid = invalid + e.getInvalidAddresses()[i].toString();
if (i+1<e.getInvalidAddresses().length)
{
invalid = invalid + ", ";
}
}
for (int i=0; i<e.getValidUnsentAddresses().length; i++)
{
valid = valid + e.getValidUnsentAddresses()[i].toString();
if (i+1<e.getValidUnsentAddresses().length)
{
valid = valid + ", ";
}
}
int choice = JOptionPane.showOptionDialog(null, invalid + " are invalid addresses. Send mail to valid addresses?", "Information", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, "No");
if (choice==0)
{
transport.sendMessage(message, e.getValidUnsentAddresses());
JOptionPane.showMessageDialog(null, "Sent message to " + valid + ".", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
else //no valid unsent addresses
{
JOptionPane.showMessageDialog(null, "All email addresses are invalid.", "Information", JOptionPane.ERROR_MESSAGE);
}
}
catch(MessagingException e2)
{ e2.printStackTrace(); }
}
Loop to add recipient addresses to message:
for (int i=0; i<listModel.getSize(); i++) //listModel is of DefaultListModel Class
{
message.addRecipient(Message.RecipientType.TO, new InternetAddress((String)listModel.getElementAt(i)));
}
Then at the end:
properties = System.getProperties();
session = Session.getDefaultInstance(properties);
transport = session.getTransport("smtp");
transport.connect(host, textEmail.getText(), new String(pwdPassword.getPassword()));
transport.sendMessage(message, message.getAllRecipients()); // <----this part throws the SendFailedException
transport.close();
Now onto the problem. You could see that there's an if-else statement immediately inside the catch block. I wanted to check whether there were any valid unsent addresses in the recipients. This way I can know if there are only invalid addresses in the recipients (as there are no valid sent addresses since the message fails to send because of the exception).
I've run some tests on the system. It works fine if all addresses are valid, however, when a single invalid address is included, a minor problem appears. If I were to put only invalid addresses in the recipients, it is supposed to go to the "else" part, but instead it always ends up in the "if" part of the statement.
While it is only a minor problem (it's only about prompts), I would still like to know why my condition doesn't work. I might be missing something about the SendFailedException
Try putting all invalid addresses and it should work
If is executed everytime because even if one valid address is there
e.getValidUnsentAddresses();
will not return null
I've been searching for four hours and this is driving me nuts. I'm going to try keeping this short, if you need more information/code ask and I'll edit.
So I have an Android client that connects to a server using PrintWriter and BufferedReader. The way it works is it starts a new ASyncTask() to load the connection. When the connection is made, it sends a "Join" message to the server, and then loads a listen thread that has a while loop waiting for UserInput.readLine() != null, and once broken it returns a string that runs a process function that takes the string and does it's action, and reloads the listen task.
//Listener thread
class listen extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
//Disconnect variable that's only turned true on backpress
if (!disconnect) {
try {
message = Connection.listen(); //socket object
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// async task finished
if (!disconnect) {
say("INCOMMING"); //easy-made function for Toast
input(message);
}
}
}
and in that Connection:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
}
return userInput;
}
Now in my server java app, I have a thread that loads up other connection threads into an ArrayList and acts as a headquarters to dispatch messages to all child clients
In my connection:
while ((inputLine = in.readLine()) != null) {
//Tells HQ to process string, with id being who it's coming from
hq.Process(id, inputLine);
if (!connected)
break;
}
in HQ object:
public void Process(int id, String str) {
String[] msg = str.split(","); //split message
String send = " "; //string I print to console
if (msg[0].equals("join")) {
send = msg[1] + " has joined!";
parent.seats[cnew.get(id).seat] = id;
cnew.get(id).sendData();
System.out.println(id);
}
And after join, the HQ tells that connection to send that player's information to the phone
public void sendData() {
out.println("chips," + chips); // Update chip count
//give player his cards
out.println("card," + hq.parent.gameCards.getCard(10) + ","
+ hq.parent.gameCards.getCard(11));
//a cry for help to get some output on the phone
out.println("error,SAY THIS");
// out.flush(); //commented out because it didn't help at all
System.out.println("sending id " + id); //debug checker (ignore this)
}
My problem is, it worked when I connected four phones and they all sent toasts to each other.
But as soon as I changed it to send back data as soon as the player joins, I'm not getting a response in Android at all.
I can't figure out why it's not working. On server side, it's going through everything (Checked with system.prints). The connection IS made, and when I click buttons on the phone the Server is outputting it's responses. But the phone is not receiving anything -- I still don't know if the server is failing to send or the phone is failing to read. Can you see anything in the code that may be causing this? Need to see more? Or have any tips on how to debug the connection status? The listen() task is never finishing it's execution anymore.
UPDATE: So I figured out it's probably to do with my while() loop on android side, doh, probably never breaking. Stupid mistake. But I tried to add this as a tester, and still nothing:
public String listen() throws IOException {
String userInput;
while ((userInput = in.readLine()) != null) {
if (userInput.length() > 2)
break;
}
return userInput;
}
UPDATE: Next desperate update -
When I hit "back" (which sends quit msg to server that closes connection, and calls out.close and the rest.close) then I get a never ending loop of "MSG" Toast's -- The Toast that I put when an input is recognized. Is a out.close causing a block?
So it turns out, println on the server's side wasn't printing a new line -- adding + "\n" at the end of the server's messages made it go through. Why? I don't know..