Read incoming sms without spaces - blackberry

The following code reads an incoming sms then prints the body of the message. How do I get the app to print out the message without any spaces inbetween?
For example: The incoming sms reads "Here I am", so "Here I am" is printed out, but I want the app to print out "HereIam".
How can I do this? Any help would be most appreciated.
Here is my code:
public void run() {
try {
DatagramConnection _dc = (DatagramConnection)Connector.open("sms://");
for(;;) {
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
byte[] bytes = d.getData();
String address = d.getAddress();
String msg = new String(bytes);
System.out.println(address);
System.out.println(msg);
}
}catch (Exception me) {
}
}
Thanks

try this
add this line to code
System.out.println(replaceAll(msg," ",""));
Add this method as well
public static String replaceAll(String source, String pattern,
String replacement) {
if (source == null)
return "";
StringBuffer sb = new StringBuffer();
int idx = -1;
int patIdx = 0;
while ((idx = source.indexOf(pattern, patIdx)) != -1) {
sb.append(source.substring(patIdx, idx));
sb.append(replacement);
patIdx = idx + pattern.length();
}
sb.append(source.substring(patIdx));
return sb.toString();
}
It replaces all the spaces with empty string, which is what you want.

Use the String.replace() method:
msg = msg.replace("\s+", "");

Related

JavaMail MIME attachment link by cid

Background
I have banged my head against this for a while and not made much progress. I am generating MPEG_4 / AAC files in Android and sending them by email as .mp3 files. I know they aren't actually .mp3 files, but that allows Hotmail and Gmail to play them in Preview. They don't work on iPhone though, unless they are sent as .m4a files instead which breaks the Outlook / Gmail Preview.
So I have thought of a different approach which is to attach as a .mp3 file but have an HTML link in the email body which allows the attached file to be downloaded and specifies a .m4a file name. Gmail / Outlook users can click the attachment directly whereas iPhone users can use the HTML link.
Issue
I can send an email using JavaMail with HTML in it including a link which should be pointing at the attached file to allow download of that file by the link. Clicking on the link in Gmail (Chrome on PC) gives a 404 page and iPhone just ignores my clicking on the link.
Below is the code in which I generate a multipart message and assign a CID to the attachment which I then try to access using the link in the html part. It feels like I am close, but maybe that is an illusion. I'd be massively grateful if someone could help me fix it or save me the pain if it isn't possible.
private int send_email_temp(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtp_host_setting);
//props.put("mail.debug", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", smtp_port_setting);
session = Session.getInstance(props);
ActuallySendAsync_temp asy = new ActuallySendAsync_temp(true);
asy.execute();
return 0;
}
class ActuallySendAsync_temp extends AsyncTask<String, String, Void> {
public ActuallySendAsync_temp(boolean boo) {
// something to do before sending email
}
#Override
protected Void doInBackground(String... params) {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient_email_address));
message.setSubject(email_subject);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
String file = mFileName;
/**/
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
/* /
File ff = new File(file);
try {
messageBodyPart.attachFile(ff);
} catch(IOException eio) {
Log.e("Message Error", "Old Macdonald");
}
/* /
messageBodyPart = new PreencodedMimeBodyPart("base64");
byte[] file_bytes = null;
File ff = new File(file);
try {
int length = (int) ff.length();
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(ff));
file_bytes = new byte[length];
reader.read(file_bytes, 0, length);
reader.close();
} catch (IOException eio) {
Log.e("Message Error", "Old Macdonald");
}
messageBodyPart.setText(Base64.encodeToString(file_bytes, Base64.DEFAULT));
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
/**/
messageBodyPart.setFileName( DEFAULT_AUDIO_FILENAME );//"AudioClip.mp3");
//messageBodyPart.setContentID("<audio_clip>");
String content_id = UUID.randomUUID().toString();
messageBodyPart.setContentID("<" + content_id + ">");
messageBodyPart.setDisposition(Part.ATTACHMENT);//INLINE);
messageBodyPart.setHeader("Content-Type", "audio/mp4");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart messageBodyText = new MimeBodyPart();
//final String MY_HTML_MESSAGE = "<h1>My HTML</h1><a download=\"AudioClip.m4a\" href=\"cid:audio_clip\">iPhone Download</a>";
final String MY_HTML_MESSAGE = "<h1>My HTML</h1><a download=\"AudioClip.m4a\" href=\"cid:" + content_id + "\">iPhone Download</a>";
messageBodyText.setContent( MY_HTML_MESSAGE, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Print_Message_To_Console(message);
Transport transport = session.getTransport("smtp");
transport.connect(smtp_host_setting, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// something to do after sending email
}
}
int Print_Message_To_Console(Message msg) {
int ret_val = 0;
int line_num = 0;
InputStream in = null;
InputStreamReader inputStreamReader = null;
BufferedReader buff_reader = null;
try {
in = msg.getInputStream();
inputStreamReader = new InputStreamReader(in);
buff_reader = new BufferedReader(inputStreamReader);
String temp = "";
while ((temp = buff_reader.readLine()) != null) {
Log.d("Message Line " + Integer.toString(line_num++), temp);
}
} catch(Exception e) {
Log.d("Message Lines", "------------ OOPS! ------------");
ret_val = 1;
} finally {
try {
if (buff_reader != null) buff_reader.close();
if (inputStreamReader != null) inputStreamReader.close();
if (in != null) in.close();
} catch(Exception e2) {
Log.d("Message Lines", "----------- OOPS! 2 -----------");
ret_val = 2;
}
}
return ret_val;
}
You need to create a multipart/related and set the main text part as the first body part.

tryparse a value form a file

what i am trying to do is take the variable from the file but throw an exception if input is not a number. i just want an error message to show when the entered amount is a word or negative number. i want to use a try catch but am not sure how to structure it. thanks you guys.
StreamReader read = new StreamReader("../../data.dat");
Stopwatch st = new Stopwatch();
bool ok;
int num;
string input=(read.ReadLine());
ok = int.TryParse(input, out num);
if (ok ==false)
{
throw new Exception("Input in incorrect format");
}
int sum = 0;
Scanner scan = new Scanner("../../data.dat");
int num = Integer.MIN_VALUE;
try {
num = Integer.parseInt(scan.next());
} catch (Exception e) {
System.out.println("Input in incorrect format.");
e.printStackTrace();
}
scan.close();

Incoming sms listener on blackberry

i've used below code for notify the sms .
Its working on two blackberry simulator.
I've install the app on my device and send sms from android device.
The sms listener not working on device.
Incoming message received on device. but my app not notify the listener .
What is the problem how to resolve it.
What port number need to give for device?
class BackgroundApplication extends Application implements MessageListener
{
int i=0;
static String suffix;
MessageConnection _mc ;
public BackgroundApplication()
{
try {
_mc = (MessageConnection)Connector.open("sms://:0");
_mc.setMessageListener(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void notifyIncomingMessage(MessageConnection conn) {
try {
Message m = _mc.receive();
String address = m.getAddress();
String msg = null;
if ( m instanceof TextMessage )
{
TextMessage tm = (TextMessage)m;
msg = tm.getPayloadText();
}
else if (m instanceof BinaryMessage) {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) m).getPayloadData();
// convert Binary Data to Text
msg = new String(data, "UTF-8");
}
else
System.out.println("Invalid Message Format");
System.out.println("Received SMS text from " + address + " : " + msg);
showDialog("Msg: "+msg);
} catch (Exception e) {
// TODO: handle exception
}
}
private void showDialog(String string) {
synchronized (UiApplication.getEventLock())
{
Status.show(""+string,Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), 5000,
Status.GLOBAL_STATUS, true, false, 1);
}
}
}
Check this
http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-listen-for-SMS-messages/ta-p/445062
DatagramConnection _dc =
(DatagramConnection)Connector.open("sms://");
for(;;)
{
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
byte[] bytes = d.getData();
String address = d.getAddress();
String msg = new String(bytes);
System.out.println( "Received SMS text from " + address + " : " + msg);
}

BlackBerry java.io.IOException: null

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

TCP client stream

I'm comunicationg with a email gateway. That gateway has an specific ip and port.
The requests the gateway are JSON formated and the gateway normally responds first whith an proceeding state and then with a confirmation or error state, represented also in JSON.
The code to make the requests and receive the response is:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Win32;
public class TcpClientSample
{
public static void SendMessage(TcpClient client, string msg)
{
Console.WriteLine("REQUEST:" + msg);
NetworkStream stream = client.GetStream();
byte[] myWriteBuffer = Encoding.ASCII.GetBytes(msg);
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
byte[] myWriteBuffer2 = Encoding.ASCII.GetBytes("\r\n");
stream.Write(myWriteBuffer2, 0, myWriteBuffer2.Length);
string gResponse = "";
BinaryReader r = new BinaryReader(stream);
int receivedMessages = 0;
while (true)
{
while (true)
{
char currentChar = r.ReadChar();
if (currentChar == '\n')
break;
else
gResponse = gResponse + currentChar;
}
if (gResponse != "")
{
Console.WriteLine("RESPONSE:" + gResponse);
receivedMessages = receivedMessages + 1;
}
if (receivedMessages == 2)
{
break;
}
}
}
public static void Main()
{
List<string> messages = new List<string>();
for (int i = 0; i < 1; i++)
{
String msg = "{ \"user\" : \"James\", \"email\" : \"james#domain.pt\" }";
messages.Add(msg);
}
TcpClient client = new TcpClient();
client.Connect("someIp", somePort);
int sentMessages = 0;
int receivedMessages = 0;
foreach (string msg in messages)
{
Thread newThread = new Thread(() =>
{
sentMessages = sentMessages + 1;
Console.WriteLine("SENT MESSAGES: " + sentMessages);
SendMessage(client, msg);
receivedMessages = receivedMessages + 1;
Console.WriteLine("RECEIVED MESSAGES: " + receivedMessages);
});
newThread.Start();
}
Console.ReadLine();
}
}
If I send few emails (up to 10) the network stream is OK.
But if I send thousands of emails I get messed chars lie
:{iyo"asn ooyes" "ncd" 0,"s_d:"4379" nme" 92729,"er_u" ,"ed_t_i" 2#" p cin_d:"921891010-11:11.725,"s" 4663175D0105E6912ADAAFFF6FDA393367" rpy:"rcein"
Why is this?
Don't worry I'm not a spammer :D
When you write a message to a TCP socket, it'll respond with the sent data. When the buffer is full, I expect it's 0, but you advance your send buffer anyway. You should advance it by the return value :)
Edit: it looks like you're using a stream abstraction which writes the internal buffer. The situation is the same. You are saying "the message has been completely sent" when the internal buffer state is not saying this, i.e. position does not equal limit. You need to keep sending until the remaining amount of buffer is 0 before moving on.
I solved this issue by having a single method just to read from the stream like this:
private TcpClient client;
private NetworkStream stream;
public void ListenFromGateway()
{
...
while (true)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
//BLOCKS UNTIL AT LEAST ONE BYTE IS READ
stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
//RETURNS THE DATA RECEIVED
string returndata = Encoding.UTF8.GetString(bytes);
//REMOVE THE EXCEDING CHARACTERS STARTING ON \r
string returndata = returndata.Remove(returndata.IndexOf('\r'));
...
}
Thanks for the help

Resources