How do i setup BroadcastReceiver to only display sms received from specific numbers? - broadcastreceiver

I need help modifying a broadcastReceiver I wrote so that it only displays incoming sms message from numbers that I can specify. right now the following code displays ALL received sms, it would be nice if the app only displayed sms from 1 specific number. can anyone provide any specifics on how I could accomplish this?
code is as follows:
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
thanks a bunch for any help guys.

Just put one if there :)
public class IncomingSms extends BroadcastReceiver {
private static final String MY_PHONE_NUMBER = "your number here";
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
if(!MY_PHONE_NUMBER.equals(phoneNumber)) {
return;
}
...

Related

Curator ServiceCacheListener is triggered three times when a service is added

I am learning zookeeper and trying out the Curator framework for service discoveries. However, I am facing a weird issue that I have difficulties to figure out. The problem is when I tried to register an instance via serviceDiscovery, the cacheChanged event of the serviceCache gets triggered three times. When I removed an instance, it is only triggered once, which is the expected behavior. Please see the code below:
public class DiscoveryExample {
private static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
// this is the ip address of my VM
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
.client(client)
.basePath(PATH)
.serializer(serializer)
.build();
serviceDiscovery.start();
ServiceCache<InstanceDetails> serviceCache = serviceDiscovery.serviceCacheBuilder()
.name("product")
.build();
serviceCache.addListener(new ServiceCacheListener() {
#Override
public void stateChanged(CuratorFramework curator, ConnectionState state) {
// TODO Auto-generated method stub
System.out.println("State Changed to " + state.name());
}
// THIS IS THE PART GETS TRIGGERED MULTIPLE TIMES
#Override
public void cacheChanged() {
System.out.println("Cached Changed ");
List<ServiceInstance<InstanceDetails>> list = serviceCache.getInstances();
Iterator<ServiceInstance<InstanceDetails>> it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next().getAddress());
}
}
});
serviceCache.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
String line = in.readLine();
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
}
AND
public class RegisterApplicationServer {
final static String PATH = "/base";
static ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
public static void main(String[] args) throws Exception {
CuratorFramework client = null;
try {
client = CuratorFrameworkFactory.newClient("192.168.149.129:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(
InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH)
.serializer(serializer).build();
serviceDiscovery.start();
// SOME OTHER CODE THAT TAKES CARES OF USER INPUT...
} finally {
CloseableUtils.closeQuietly(serviceDiscovery);
CloseableUtils.closeQuietly(client);
}
}
private static void addInstance(String[] args, CuratorFramework client, String command,
ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// simulate a new instance coming up
// in a real application, this would be a separate process
if (args.length < 2) {
System.err.println("syntax error (expected add <name> <description>): " + command);
return;
}
StringBuilder description = new StringBuilder();
for (int i = 1; i < args.length; ++i) {
if (i > 1) {
description.append(' ');
}
description.append(args[i]);
}
String serviceName = args[0];
ApplicationServer server = new ApplicationServer(client, PATH, serviceName, description.toString());
server.start();
serviceDiscovery.registerService(server.getThisInstance());
System.out.println(serviceName + " added");
}
private static void deleteInstance(String[] args, String command, ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// in a real application, this would occur due to normal operation, a
// crash, maintenance, etc.
if (args.length != 2) {
System.err.println("syntax error (expected delete <name>): " + command);
return;
}
final String serviceName = args[0];
Collection<ServiceInstance<InstanceDetails>> set = serviceDiscovery.queryForInstances(serviceName);
Iterator<ServiceInstance<InstanceDetails>> it = set.iterator();
while (it.hasNext()) {
ServiceInstance<InstanceDetails> si = it.next();
if (si.getPayload().getDescription().indexOf(args[1]) != -1) {
serviceDiscovery.unregisterService(si);
}
}
System.out.println("Removed an instance of: " + serviceName);
}
}
I appriciate if anyone can please point out where I am doing wrong and maybe can share some good materials/examples so I can refer to. The official website and the examples on github does not help a lot.

How to fetch unread email using javax.mail pop3 from outlook

I am trying to fetch unread email from Inbox(Outlook.office365.com) and also copy the read message to another folder. But I am getting some of the following issues.
Email is being re-read again, even if we mark the email as being
read programmatically.
Unable to copy an email to another folder even when we open the Inbox is RW(Read&Write) mode.
Attached my code as well.
package com.xyz.mail;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
public class ReadEmail {
private static final String TRUE = "true";
private static final String MAIL_POP3_HOST = "mail.pop3.host";
private static final String MAIL_POP3_PORT = "mail.pop3.port";
private static final String MAIL_POP3_STARTTLS_ENABLE = "mail.pop3.starttls.enable";
private static final String MAIL_FOLDER_INBOX = "INBOX";
public static void check(String host, String storeType, String user, String password) throws Exception {
Store store = null;
Folder emailFolder = null;
try {
Properties properties = new Properties();
properties.put(MAIL_POP3_HOST, host);
properties.put(MAIL_POP3_PORT, "995");
properties.put(MAIL_POP3_STARTTLS_ENABLE, TRUE);
Session emailSession = Session.getDefaultInstance(properties);
// create the POP3 store object and connect with the pop server
store = emailSession.getStore(storeType);
store.connect(host, user, password);
emailFolder = store.getFolder(MAIL_FOLDER_INBOX);
emailFolder.open(Folder.READ_WRITE);
Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println("messages.length---" + messages.length);
if (messages.length == 0) {
System.out.println("No new messages found.");
} else {
for (int i = 0, len = messages.length; i < len; i++) {
Message message = messages[i];
boolean hasAttachments = hasAttachments(message);
if (hasAttachments) {
System.out.println(
"Email #" + (i + 1) + " with subject " + message.getSubject() + " has attachments.");
readAttachment(message);
} else {
System.out.println("Email #" + (i + 1) + " with subject " + message.getSubject()
+ " does not have any attachments.");
continue;
}
Folder copyFolder = store.getFolder("copyData");
if (copyFolder.exists()) {
System.out.println("copy messages...");
copyFolder.copyMessages(messages, emailFolder);
message.setFlag(Flags.Flag.DELETED, true);
}
}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
emailFolder.close(false);
store.close();
}
}
public static void main(String[] args) throws Exception {
String host = "outlook.office365.com";
String username = "emailtest#xyz.com";
String password = "passw0rd{}";
String mailStoreType = "pop3s";
check(host, mailStoreType, username, password);
}
private static boolean hasAttachments(Message msg) throws Exception {
if (msg.isMimeType("multipart/mixed")) {
Multipart mp = (Multipart) msg.getContent();
if (mp.getCount() > 1) {
return true;
}
}
return false;
}
public static void readAttachment(Message message) throws Exception {
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String destFilePath = "/home/user/Documents/" + part.getFileName();
System.out.println("Email attachement ---- " + destFilePath);
FileOutputStream output = new FileOutputStream(destFilePath);
InputStream input = part.getInputStream();
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
output.close();
}
}
}
}
How to I fetch only unread email and copy the email to another folder.
change the protocal to imap and change the prot respecitvely ..using pop3 we can access only inbox that is the reason why you are unable to copy the mail to another folder

Spring MVC bulk message using MimeMessagePreparator

I'm trying to send bulk emails using Spring MVC. Here is my code:
if(customerClients != null){
int count = 0;
boolean sent = false;
List<MimeMessagePreparator> preparators = new ArrayList<MimeMessagePreparator>();
for (BulkEmail client : customerClients) {
if(customerID==-1)
customerID = client.getCustomerID();
CustomerAccount customerAccount = service.getCustomerAccount(client.getCustomerID());
if (instantMessage.isEmailChecked() && customerAccount.getBalance()>0) {
try{
final String receiverID = client.getEmail();
instantMessage.setIpersonOrGroupValue(receiverID);
preparators.add(new MimeMessagePreparator()
{
public void prepare(MimeMessage mimeMessage) throws Exception
{
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setSubject(instantMessage.getSubject());
message.setTo(receiverID);
message.setFrom(from);
message.setText(instantMessage.getMessage(), true);
}
});
sent = false;
}
catch(Exception ex){
ex.printStackTrace();
}
}
++count;
if(count%100==0){
springMail.send(preparators);
preparators = new ArrayList<MimeMessagePreparator>();
sent = true;
}
}
if(!sent)
springMail.send(preparators);
Here is the code that uses JavaMailSender for sending the preparators:
public void send(List<MimeMessagePreparator> preparatorsList) {
MimeMessagePreparator[] preparators = preparatorsList.toArray(new MimeMessagePreparator[preparatorsList.size()]);
mailSender.send(preparators);
}
The problem with this code is it takes around 1 second per email address. This means 300 emails in 5 minutes.
I want to know if this is normal or there is something I can do to improve.
Thanks

Creating custom plugin for chinese tokenization

I'm working towards properly integrating the stanford segmenter within SOLR for chinese tokenization.
This plugin involves loading other jar files and model files. I've got it working in a crude manner by hardcoding the complete path for the files.
I'm looking for methods to create the plugin where the paths need not be hardcoded and also to have the plugin in conformance with the SOLR plugin architecture. Please let me know if there are any recommended sites or tutorials for this.
I've added my code below :
public class ChineseTokenizerFactory extends TokenizerFactory {
/** Creates a new WhitespaceTokenizerFactory */
public ChineseTokenizerFactory(Map<String,String> args) {
super(args);
assureMatchVersion();
if (!args.isEmpty()) {
throw new IllegalArgumentException("Unknown parameters: " + args);
}
}
#Override
public ChineseTokenizer create(AttributeFactory factory, Reader input) {
Reader processedStringReader = new ProcessedStringReader(input);
return new ChineseTokenizer(luceneMatchVersion, factory, processedStringReader);
}
}
public class ProcessedStringReader extends java.io.Reader {
private static final int BUFFER_SIZE = 1024 * 8;
//private static TextProcess m_textProcess = null;
private static final String basedir = "/home/praveen/PDS_Meetup/solr-4.9.0/custom_plugins/";
static Properties props = null;
static CRFClassifier<CoreLabel> segmenter = null;
private char[] m_inputData = null;
private int m_offset = 0;
private int m_length = 0;
public ProcessedStringReader(Reader input){
char[] arr = new char[BUFFER_SIZE];
StringBuffer buf = new StringBuffer();
int numChars;
if(segmenter == null)
{
segmenter = new CRFClassifier<CoreLabel>(getProperties());
segmenter.loadClassifierNoExceptions(basedir + "ctb.gz", getProperties());
}
try {
while ((numChars = input.read(arr, 0, arr.length)) > 0) {
buf.append(arr, 0, numChars);
}
} catch (IOException e) {
e.printStackTrace();
}
m_inputData = processText(buf.toString()).toCharArray();
m_offset = 0;
m_length = m_inputData.length;
}
#Override
public int read(char[] cbuf, int off, int len) throws IOException {
int charNumber = 0;
for(int i = m_offset + off;i<m_length && charNumber< len; i++){
cbuf[charNumber] = m_inputData[i];
m_offset ++;
charNumber++;
}
if(charNumber == 0){
return -1;
}
return charNumber;
}
#Override
public void close() throws IOException {
m_inputData = null;
m_offset = 0;
m_length = 0;
}
public String processText(String inputText)
{
List<String> segmented = segmenter.segmentString(inputText);
String output = "";
if(segmented.size() > 0)
{
output = segmented.get(0);
for(int i=1;i<segmented.size();i++)
{
output = output + " " +segmented.get(i);
}
}
System.out.println(output);
return output;
}
static Properties getProperties()
{
if (props == null) {
props = new Properties();
props.setProperty("sighanCorporaDict", basedir);
// props.setProperty("NormalizationTable", "data/norm.simp.utf8");
// props.setProperty("normTableEncoding", "UTF-8");
// below is needed because CTBSegDocumentIteratorFactory accesses it
props.setProperty("serDictionary",basedir+"dict-chris6.ser.gz");
props.setProperty("inputEncoding", "UTF-8");
props.setProperty("sighanPostProcessing", "true");
}
return props;
}
}
public final class ChineseTokenizer extends CharTokenizer {
public ChineseTokenizer(Version matchVersion, Reader in) {
super(matchVersion, in);
}
public ChineseTokenizer(Version matchVersion, AttributeFactory factory, Reader in) {
super(matchVersion, factory, in);
}
/** Collects only characters which do not satisfy
* {#link Character#isWhitespace(int)}.*/
#Override
protected boolean isTokenChar(int c) {
return !Character.isWhitespace(c);
}
}
You can pass the argument through the Factory's args parameter.

I get the following error: "message": "Malformed access token

I have an app in facebook and I am trying to obtain long term token,
for that I call the following link:
https://graph.facebook.com/oauth/authorize?client_id=xxxxxx&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Faccesstokforfacebook%2Ffbaccess&scope=read_stream,read_insights,user_religion_politics,user_relationship_details,user_hometown,user_location,user_likes,user_activities,user_interests,user_education_history,user_work_history,user_website,user_groups,user_events,user_photos,user_videos,user_about_me,user_status,user_games_activity,user_tagged_places,user_actions.books,user_actions.video,user_actions.news
and the return url is a servlet with following codes:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String accessCode = request.getParameter("code");
System.out.println("dddd "+accessCode);
//print SUCCESS if code is found
/*if (accessCode!=null){*/
out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\"><html><head><title>Facebook Access Granted</title></head><body>");
out.print("<p>SUCCESS!</p><p>"+accessCode+"</p></body></html>");
and this servlet receives the very long code like this:
AQCY244eMOhxEVu3e6UEIl-qK974wTh-p0Il1ZdG9VEAYl5GdrjxxxxxxxxxxxxxxxxxxxxxxxxxxxxxQcJeUmeXFU56cbWbmXJdLQvEyIT7JWCxxu6tChkr9oCL1DVYxxv4v-j4Y_vaWGD7dYcxxxxxxxxxxxxxxxxxxTvZPHLU-tU5ySHrQrVgpo_i8minM73cyWxxxxxxxxxxxxxxdZvnrIhQXQ-B_3LAFzDcWe2NbCW7WSgmQ-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxMkJ55M0wHHbLmL4D-g_wLIwhpz4W_8Hz0h7v_ZL
Now when I use this token to get the all info for a page I get an error:
this is a link that I use:
https://graph.facebook.com/v2.0/khalatbari.hooman/feed?access_token=THE ABOVE CODE
and the error is:
Now I think the code that I get is not access token but I have no idea how to use this code to get access token!!!
can anyone help
Finally found solution for Facebook SDK 4.6.0 to getting limited comment's list for feed :
1> Calling commentInfo() firstly Inside Activity's oncreate()
:
private boolean isLoadMoreCalled;
commentInfo("", "true");
2> Putting load more method also there like:
listViewCommentList.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.d("scrollState", ""+scrollState);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int last_visible_in_screen = firstVisibleItem + visibleItemCount;
if(last_visible_in_screen == totalItemCount && isLoadMoreCalled) {
Toast.makeText(getApplicationContext(), "Loading more Items 10", Toast.LENGTH_SHORT).show();
commentInfo(nextFeedUrl, "false");
isLoadMoreCalled = false;
}
}
});
3> create commentInfo() of outside onCreate() :
public void commentInfo (String fields, final String isFirst) {
/** Festival Feed Comments Details #Facebook */
Bundle params = new Bundle();
params.putString("fields", "message,created_time,from");
params.putString("limit", "10");
if(isFirst.equals("false")) {
params.putString("after", fields);
}
showProgressBar();
/* make the API call */
//refreshCurrentAccessTokenAsync();
System.out.println("Acees Token Comment>>>"+ AccessToken.getCurrentAccessToken());
new GraphRequest(AccessToken.getCurrentAccessToken(), "/"+ feedId +"/comments", params, HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
System.out.println("Festival feed Comments response::" + String.valueOf(response.getJSONObject()));
try {
JSONObject jObjResponse = new JSONObject(String.valueOf(response.getJSONObject()));
JSONObject jObjPaging = jObjResponse.getJSONObject("paging");
JSONObject jObjCursor = jObjPaging.getJSONObject("cursors");
nextFeedUrl = "";
nextFeedUrl = jObjCursor.getString("after");
System.out.println("nextFeedUrl>>"+ nextFeedUrl);
JSONArray jArrayData = jObjResponse.getJSONArray("data");
for(int i = 0; i< jArrayData.length(); i++) {
Getting comments info & store into Data-Structure(Array-List)
}
if(isFirst.equals("true")) {
fbFeedCommentAdapter = new FbFeedCommentAdapter();
listViewCommentList.setAdapter(fbFeedCommentAdapter);
}
else {
fbFeedCommentAdapter.notifyDataSetChanged();
}
if(!jObjPaging.has("next")) {
isLoadMoreCalled = false;
}
else {
isLoadMoreCalled = true;
}
dismissProgressBar();
}
catch (Exception e) {
e.printStackTrace();
dismissProgressBar();
}
}
}
).executeAsync();
}
Here,
fbFeedCommentAdapter -> BaseAdapter
listViewCommentList -> Listview
Also refer How to use the Facebook Graph Api Cursor-based Pagination