Exchange server 2013 with Javamail IMAP: Implement the categorize function - jakarta-mail

Background
I start to work with Microsoft Exchange Server 2013 & Javamail 1.5.6
I am making a Java client and currently I am able to connect to mailbox by IMAP protocol and LIST/SEARCH emails.
My question
I want to implement a function that use Java code to categorize mails, the result should be the same as below function in outlook↓
(1) Right click on a mail, click Categorize, then select a target label
(2) The label is on the mail now:
My own research
I go through Javamail API but find nothing about this.
Then, I have a quick look at IMAP: RFC 3501: INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1, but not able to find anything about Categorize, seems it is not standard IMAP capabilities?
Then I found this post: Getting Gmail labels using javamail, the guy did his own extension by using ((IMAPFolder) folder).doCommand():
final MessageSet[] mSets = MessageSet.createMessageSets(mns);
((IMAPFolder) folder).doCommand(new IMAPFolder.ProtocolCommand() {
#Override
public Object doCommand(IMAPProtocol p) throws ProtocolException {
try {
Response[] r = p.fetch(mSets, "X-GM-LABELS X-GM-THRID");
for (int i = 0; i < r.length; i++) {
if (!FetchResponse.class.isInstance(r[i]))
continue;
// Got a FetchResponse.
GmailFetchResponse gfr = new GmailFetchResponse(
((FetchResponse) r[i]).toString());
// Use gfr.getNumber() to get the msg number
for (int j = 0; j < gfr.getItemCount(); j++) {
Item item = gfr.getItem(j);
if (X_GM_LABELS.class.isInstance(item))
// get the labels
((X_GM_LABELS) item).x_gm_labels);
}
}
} catch (ProtocolException e) {
logError(e.getMessage(), e);
}
return null;
}
});
It looks like the guy construct his own commands by extend IMAPProtocol class.
But I couldn't find anything about commands of Microsoft Exchange server, can you help me on this?

Related

How to use WPF UserControls or Windows from inside Visual FoxPro 9

I have a very, very large and complex Visual FoxPro 9 application. I'd like to rewrite portions of this application in WPF with the ultimate goal of completing cutting over a couple of years from now. I've spent a considerable amount of time searching google and stackoverflow for an end to end "hello world" type sample of how to implement this with COM interop. Found bits and pieces but nothing complete that shows both the FoxPro side and the WPF side.
My gut tells me I'm likely to run into issues with XAML resources, third party controls, or other normal functionalities of a WPF app if I try to run it via COM Interop.
So, two questions. Can anyone point me to an small end to end sample that either launches WPF windows from FoxPro or lets me drop WPF user controls on a FoxPro form? Or am I right with my concerns of potential interop issues and should avoid this altogether? If so, is there a recommended way for these two executables to communicate with each other?
I have absolutely no idea whether you can run wpf inside visual FoxPro. I would guess you'd have to write it as an activex.
I recently did some work extending a MS Access app.
My wpf app is completely separate and runs alongside the ms access app.
I communicated between the two using MS Message Queue - which is a com component.
Maybe this sort of approach could work for you.
When I wanted to show a screen in wpf from access I added a piece of xml to the local message queue.
The wpf app listens for these messages, casts them to objects which tells it which screen to show and gives it any parameters.
MS Access subscribes to the received message event on the message queue and that way it can tell when the wpf window closes and the user is done.
This was intended to use the strangler pattern to gradually replace functionality in the old access app.
Here's some code for the queuelistener that drives everything. The various pop classes are deserialised from the message and I build that as a string in access.
internal class QueueListener
{
public const string qFromMadge = #".\private$\XXXXQ";
public static string qToMadge = #".\private$\XXXXReturnQ";
private MessageQueue mq;
internal QueueListener()
{
try
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
SubscribeHandler();
var mqSend = setUpQueue(qToMadge);
mqSend.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException.Message);
}
}
private MessageQueue setUpQueue(string qName)
{
MessageQueue q;
if (MessageQueue.Exists(qName))
{
q = new MessageQueue(qName);
}
else
{
q = MessageQueue.Create(qName);
}
q.ResetPermissions();
q.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Set);
q.Purge();
return q;
}
private void ReceiveMsgCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
m.Formatter = new XmlMessageFormatter(new[] { "XXXX.Popaaaa, XXXX"
, "XXXX.Popbbbb, XXXXX"
, "XXXX.Popcccc, XXXX"
, "XXXX.Popdddd, XXXX"
});
((BasePopView) m.Body).Pop();
mq.BeginReceive();
}
public void UnsubscribeHandler()
{
if (mq == null)
{
return;
}
mq.Close();
mq.ReceiveCompleted -= new ReceiveCompletedEventHandler(ReceiveMsgCompleted);
mq = null;
}
public void SubscribeHandler()
{
if(mq != null)
{
return;
}
mq = setUpQueue(qFromMadge);
mq.ReceiveCompleted += ReceiveMsgCompleted;
mq.BeginReceive();
}

Fetching all Microsoft Active Directory users in Domino Xpages NamePicker via java Agent

I'm working with LDAP Microsoft Active Directory and Domino server and quite new with this.
we've successfully fetched all Microsoft Active Directory users in Domino via java Agent and have printed all the user names in java debug console. For that referred this http://lotus-blogs.blogspot.in/2009/08/ldap-programming-using-domino-java-step.html link.
Now, i want to get all users in Domino Xpages NamePicker, so is this possible to get all users in Xpages NamePicker via java Agent?
As per we see that in Xpages NamePicker, we are able to fetch the Domino Users with the help of java beans.
Any kind of suggestion will be really Appreciated.
My java Agent is like following-
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
LDAPQuery.ldapconnect();
} catch(Exception e) {
e.printStackTrace();
}
}
}
AND
import javax.naming.*;
import javax.naming.directory.*;
import java.util.*;
public class LDAPQuery {
public static void ldapconnect(){
String isFound="0";
try {
System.out.println("inside try 1");
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "PROVIDER_URL");
env.put(Context.SECURITY_PRINCIPAL, "UserName");
env.put(Context.SECURITY_CREDENTIALS, "password");
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Specify the ids of the attributes to return
String[] attrIDs = {"cn","mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectCategory=person)(mail=*abc.com))";
System.out.println("filter defined");
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("", filter,ctls);
System.out.println("get the answer!");
try {
System.out.println("inside try2");
while (answer.hasMore())
{
SearchResult sr = (SearchResult)answer.next();
System.out.println("<<" + sr.getName()+">>");
Attributes attrs = sr.getAttributes();
//System.out.println(sr.getName().matches("/^[0-9]/"));
System.out.println(attrs.get("cn").get());
System.out.println(attrs.get("mail").get());
isFound="1";
}
if ( isFound=="1") {
System.out.println("User found in Active Directory!");
} else {
System.out.println("Opps ! User not found in Active Directory!");
}
answer.close();
}catch(PartialResultException e) {
System.out.println("catch 2");
e.printStackTrace();
}
// Close the context when we're done
ctx.close();
} catch (Exception e) {
System.out.println("catch 1");
e.printStackTrace();
}
}
public LDAPQuery() {
// Don't think I'm doing anything here
}
}
OK, got it.
Any particular reason why you are utilizing an Agent as opposed to using a true bean? Calling an agent everytime someone opens the name picker in my opinion is far from being effective.
Apart from that I don't see a way how the results from your agent could directly be passed into the name picker.
Third: looking at your ldap filter I'm sure that your code will return hundreds or even thousands of names. Using a standard ExtLib NamePicker is no fun for your users, believe me: the list of names displayed per dialog page is way too limited. But that may be a different story.
Sticking to the namePicker approach there are several ways how you could achieve what you appear to accomplish:
refactor your java agent into a javaBean then feed the result to the control
consider going for a directory syncing tool like IBM TDI; thus your AD data can be pushed into a Domino directory of your choice, and then from within your application you can utilize standard name lookup features

App is randomly failing to flag emails 'read' with IMAP, Javamail, Exchange 2010

I'm using Javamail with an implementation of MessageCountListener to read incoming emails on an Exchange 2010 server, using IMAP over an SSL connection.
We are currently testing the app.
Most days, the app processes the incoming emails and extracts their attachment files and then marks the emails as 'read':
try {
email.setFlag(Flag.ANSWERED, true);
email.setFlag(Flag.SEEN, true);
} catch (final MessagingException e) {
log.warn("Can't set msg to read - fail transaction...", ex);
// etc
}
But on some days, this doesn't work. I can see in the Outlook inbox folder that approximately 30% of the emails are left 'unread'. However there is no exception logged and the app otherwise works perfectly, so it seems.
This of course leads to problems since the app will re-process the emails and their file attachments when it is re-started, since it sees them as unread.
This is only on our test server and I haven't been able to reproduce it on my local dev box.
Can anyone advise how to approach this problem or say if they have seen it too?
My MessageCountListener implementation:
#Override
public void messagesAdded(final MessageCountEvent event) {
Message[] newEmails = event.getMessages();
if (newEmails != null) {
log.debug(String.format("%d message(s) added", newEmails.length));
for (Message email : newEmails) {
Folder folder = email.getFolder();
Store store = folder.getStore();
statusOK = processor.runTransaction(email);
if (statusOK) {
messageCount++;
} else {
log.trace("shutting down listener due to error");
store.removeConnectionListener((ConnectionListener) this);
break;
}
}
} else {
log.debug("Added null new emails array");
}
}

Can't use SearchTerm term = new MessageIDTerm(ID) to search mail by message-ID

Iam developing an Email application on Android and I got stuck at here. If I use Gmail server I can search Email by ID
SearchTerm term = new MessageIDTerm(ID);
message_s = folder.search(term);
But with this code, I can't search email with some Other server like yahoo,hotmail. And I try solve this bug by override this code
SearchTerm messageIDTerm= new SearchTerm() {
#Override
public boolean match(Message message) {
try {
String messageID="";
Enumeration headers = message.getAllHeaders();
while (headers.hasMoreElements()) {
eader h = (Header) headers.nextElement();
String mID = h.getName();
if(mID.contains("Message-ID") || mID.contains("Message-Id")){
messageID= h.getValue();
}
}
if (messageID.contains(ID)) {
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
};
message_s = folder.search(messageIDTerm);
It's success to search mail. But the problem is this code check every Message-ID by client search(download messeage-ID and compare) and it take a lot of time to find the result.
The first way, server make a seach for my request and its very fast.
So how do I make the search as fast as the first way if I use the second way?
Some servers are broken. You can't fix them.
If you have to do the search in the client, the best you can do is use the Folder.fetch method to prefetch the headers you're going to need to do the search. Then use the standard MessageIDTerm with the Message.match method as you iterate over all the messages you need to check.

How do I make a call to the Yahoo hourly weather forecast API?

I have found yahoo weather forcast most helpful.
I'm able to get an hourly weather request here from Yahoo.
How can I make an API request for the above hourly weather report using an Yahoo API call to http://weather.yahooapis.com/forecastrss?w=2502265?
This is the documentation I found.
Yahoo Weather Api does not seem to support hourly forecasts, there are just a few parameters you have control over like the location in (woeid) or (lat, long) and the temperature-unit (u or f), refer here for yahoo query language.
You can use other api's AccuWeather for hourly details.
You can do using the REST API's of the programming language you want to use.. I will give Java example. (Similar thing applies to other languages too.. )'
package tests;
import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* A simple Java REST GET example using the Apache HTTP library.
* This executes a call against the Yahoo Weather API service, which is
* actually an RSS service (http://developer.yahoo.com/weather/).
*
* Try this Twitter API URL for another example (it returns JSON results):
* http://search.twitter.com/search.json?q=%40apple
* (see this url for more twitter info: https://dev.twitter.com/docs/using-search)
*
* Apache HttpClient: http://hc.apache.org/httpclient-3.x/
*
*/
public class ApacheHttpRestClient1 {
public static void main(String[] args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
// specify the host, protocol, and port
HttpHost target = new HttpHost("weather.yahooapis.com", 80, "http");
// specify the get request
HttpGet getRequest = new HttpGet("/forecastrss?p=80020&u=f");
System.out.println("executing request to " + target);
HttpResponse httpResponse = httpclient.execute(target, getRequest);
HttpEntity entity = httpResponse.getEntity();
System.out.println("----------------------------------------");
System.out.println(httpResponse.getStatusLine());
Header[] headers = httpResponse.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
There are more ways to do the same... you can find many other alternate ways at http://alvinalexander.com/java/java-apache-httpclient-restful-client-examples

Resources