source: sandbox/expresso-solr/imapCrawler/JCrawlerForIMAP/src/pkg/crawler/data/conn/Crawler.java @ 7576

Revision 7576, 10.5 KB checked in by adir, 11 years ago (diff)

Ticket #000 - Adicionando a integracao de buscas com Solr na base a ser isnerida na comunidade

Line 
1package pkg.crawler.data.conn;
2
3import java.io.IOException;
4import java.util.ArrayList;
5import java.util.Date;
6import java.util.List;
7import java.util.Properties;
8
9import javax.mail.Address;
10import javax.mail.BodyPart;
11import javax.mail.Folder;
12import javax.mail.Message;
13import javax.mail.MessagingException;
14import javax.mail.Multipart;
15import javax.mail.Part;
16import javax.mail.Session;
17import javax.swing.JOptionPane;
18
19import org.apache.solr.client.solrj.SolrServer;
20import org.apache.solr.client.solrj.impl.HttpSolrServer;
21import org.apache.solr.common.SolrInputDocument;
22
23import pkg.crawler.entity.Message2SolrEntity;
24
25import com.sun.mail.imap.ACL;
26import com.sun.mail.imap.IMAPFolder;
27import com.sun.mail.imap.IMAPMessage;
28import com.sun.mail.imap.IMAPStore;
29import com.sun.mail.imap.Rights;
30import com.sun.mail.imap.Rights.Right;
31
32public class Crawler implements Runnable{
33
34        private String host;
35        private String user;
36        private String password;
37        private String mbox;
38        private String hostSolr;
39        private String loginStartsWith;
40        //      private ArrayList<Message2SolrEntity> listIMAPMsgs;
41        private ACL acl;
42
43        public Crawler(String host, String password, String hostSolr, String loginStartsWith)
44        {
45                this.host = host;
46                this.user = "expresso-admin";
47                this.password = password;
48                this.mbox = "user";
49                this.loginStartsWith = loginStartsWith;
50                this.hostSolr = hostSolr;
51
52                //Cria a ACL a ser configurada
53                acl = new ACL("expresso-admin");
54
55                //Define direito de leitura
56                Rights rights = new Rights();
57                rights.add(Right.READ);
58
59                //Configura direito de leitura para a ACL
60                acl.setRights(rights);
61        }
62
63
64        @Override
65        public void run()
66        {
67                while (true)
68                {
69
70
71                        //Inicializando as propriedades default da máquina para conexão
72                        //com o servidor IMAP
73                        Properties props = System.getProperties();
74                        Session session = Session.getInstance(props, null);
75
76                        IMAPStore store = new IMAPStore(session, null);
77
78                        try {
79
80                                //Conectando com o servidor IMAP
81                                store.connect(host, user, password);
82                                //Definindo a pasta base a ser usada
83                                IMAPFolder imapFolder = (IMAPFolder)store.getFolder(mbox);
84
85                                //Faz a iteração entre os usuários/pastas do usuário
86                                for (Folder fINBOXAux : imapFolder.list())
87                                {
88                                        //Verifica se esse usuário começa com a letra definida
89                                        if(fINBOXAux.getName().charAt(0) != loginStartsWith.charAt(0))
90                                        {
91                                                //Caso não seja, pula para o próximo
92                                                continue;
93                                        }
94
95                                        //Cria uma instância de conexão com o servidor Solr
96                                        SolrServer solrServer = new HttpSolrServer(hostSolr);
97
98                                        //Cria
99                                        List<Message2SolrEntity> listIMAPMsgs = new ArrayList<Message2SolrEntity>();
100                                        //INBOX
101                                        IMAPFolder imapFINBOXAux = (IMAPFolder)fINBOXAux;
102
103                                        imapFINBOXAux.addACL(acl);
104
105                                        imapFINBOXAux.open(Folder.READ_ONLY);
106
107                                        Message[] msgsINBOX = imapFINBOXAux.getMessages();
108
109                                        for (Message msgAuxINBOX : msgsINBOX)
110                                        {
111                                                IMAPMessage m = (IMAPMessage)msgAuxINBOX;
112                                                dumpPart(m, listIMAPMsgs);
113                                        }
114                                        imapFINBOXAux.removeACL("expresso-admin");
115                                        for(int i = 0; i < listIMAPMsgs.size(); i++ )
116                                        {
117                                                SolrInputDocument doc = new SolrInputDocument();
118                                                doc.addField("id", listIMAPMsgs.get(i).getId().toString());
119                                                doc.addField("user", listIMAPMsgs.get(i).getUser().toString());
120                                                doc.addField("folder", listIMAPMsgs.get(i).getFolder().toString());
121                                                doc.addField("msg_no", listIMAPMsgs.get(i).getMsgNo());
122                                                doc.addField("from", listIMAPMsgs.get(i).getFrom().toString());
123                                                doc.addField("to", listIMAPMsgs.get(i).getTo().toString());
124                                                doc.addField("subject", listIMAPMsgs.get(i).getSubject().toString());
125                                                doc.addField("content", listIMAPMsgs.get(i).getContent().toString());
126                                                doc.addField("copyto", listIMAPMsgs.get(i).getCopyto().toString());
127                                                doc.addField("sent_date", listIMAPMsgs.get(i).getSent_date());
128                                                doc.addField("hiddencopyto", listIMAPMsgs.get(i).getHiddencopyto().toString());
129
130                                                try {
131                                                        solrServer.add(doc);
132                                                } catch (Exception e) {
133                                                        System.err.println("solr -> " + e.getMessage());
134                                                }
135
136                                        }
137
138                                        listIMAPMsgs = null;
139
140                                        solrServer.commit();
141
142                                        solrServer = null;
143
144                                        for (Folder fAux : imapFINBOXAux.list())
145                                        {
146                                                //Verifica se não é uma pasta compartilhada
147                                                if(fAux.getFullName().split("/").length <= 3 && !fAux.getFullName().split("/")[2].equals("user"))
148                                                {
149                                                        //INBOX
150                                                        IMAPFolder imapFAux = (IMAPFolder)fAux;
151
152                                                        crawIntoUserFolders(imapFAux);
153
154                                                }
155                                        }
156
157                                        System.out.println(imapFINBOXAux.getFullName());
158                                }
159                                store.close();
160
161
162                        } catch (MessagingException e) {
163                                System.out.println(e.getMessage());
164                                e.printStackTrace();
165                        }
166                        catch (Exception e)
167                        {
168                                System.out.println(e.getMessage());
169                                e.printStackTrace();
170                        }
171                }
172        }
173
174        private void crawIntoUserFolders(IMAPFolder imapFAux) throws Exception
175        {
176                SolrServer solrServer = new HttpSolrServer(hostSolr);
177
178                List<Message2SolrEntity> listIMAPMsgs = new ArrayList<Message2SolrEntity>();
179                imapFAux.addACL(acl);
180
181                imapFAux.open(Folder.READ_ONLY);
182
183                Message[] msgs= imapFAux.getMessages();
184
185                for (Message msgAux: msgs)
186                {
187                        IMAPMessage m = (IMAPMessage)msgAux;
188                        dumpPart(m, listIMAPMsgs);
189                }
190                imapFAux.removeACL("expresso-admin");
191                System.out.println(imapFAux.getFullName());
192                for(int i = 0; i < listIMAPMsgs.size(); i++ )
193                {
194                        SolrInputDocument doc = new SolrInputDocument();
195                        doc.addField("id", listIMAPMsgs.get(i).getId());
196                        doc.addField("user", listIMAPMsgs.get(i).getUser());
197                        doc.addField("folder", listIMAPMsgs.get(i).getFolder());
198                        doc.addField("msg_no", listIMAPMsgs.get(i).getMsgNo());
199                        doc.addField("from", listIMAPMsgs.get(i).getFrom());
200                        doc.addField("to", listIMAPMsgs.get(i).getTo());
201                        doc.addField("subject", listIMAPMsgs.get(i).getSubject());
202                        doc.addField("content", listIMAPMsgs.get(i).getContent());
203                        doc.addField("copyto", listIMAPMsgs.get(i).getCopyto());
204                        doc.addField("sent_date", listIMAPMsgs.get(i).getSent_date());
205                        doc.addField("hiddencopyto", listIMAPMsgs.get(i).getHiddencopyto());
206
207                        if(doc.getField("id").toString().trim().equals(""))
208                        {
209                                JOptionPane.showMessageDialog(null, " ¬¬' ");
210                        }
211
212                        try {
213                                solrServer.add(doc);
214                        } catch (Exception e) {
215                                System.err.println("solr -> " + e.getMessage());
216                        }
217                }
218                listIMAPMsgs = null;
219                solrServer.commit();
220                solrServer = null;
221        }
222
223        public void dumpPart(IMAPMessage m, List<Message2SolrEntity> listIMAPMsgs) throws Exception {
224
225                if(m.getMessageID() == null || m.getMessageID().equals("")){
226                        System.out.println("Damn it!");
227                        return;
228                }
229
230                Message2SolrEntity msgEntity = null;
231                msgEntity = new Message2SolrEntity();
232                //              System.out.println(m.getSize());
233
234                msgEntity.setId(new StringBuilder( m.getMessageID()));
235
236                String user = m.getFolder().getFullName().split("/")[1];
237                msgEntity.setUser(new StringBuilder(user));
238
239                String folder = m.getFolder().getFullName().split("/")
240                                [m.getFolder().getFullName().split("/").length-1];
241
242                if(!user.trim().equals(folder.trim()))
243                {
244                        msgEntity.setFolder(new StringBuilder(folder));
245                }
246                else
247                {
248                        msgEntity.setFolder(new StringBuilder("INBOX"));
249                }
250
251                msgEntity.setMsgNo(new StringBuilder(String.valueOf(m.getMessageNumber())));
252
253
254                if(m.getSubject() != null){
255                        msgEntity.setSubject(new StringBuilder( m.getSubject() ));
256                }
257                Address[] a;
258                // FROM
259                if ((a = m.getFrom()) != null) {
260                        for (int j = 0; j < a.length; j++)
261                        {
262                                if(msgEntity.getFrom() == null)
263                                {
264                                        msgEntity.setFrom(new StringBuilder(a[j].toString()));
265                                }
266                                else
267                                {
268                                        msgEntity.setFrom(msgEntity.getFrom().append(", ").append(a[j].toString()));
269                                }
270                                //                                      System.out.println("FROM: " + a[j].toString());
271                        }
272
273                }
274
275                // TO
276                if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
277                        for (int j = 0; j < a.length; j++)
278                        {
279                                if(msgEntity.getTo() == null)
280                                {
281                                        msgEntity.setTo(new StringBuilder(a[j].toString()));
282                                }
283                                else
284                                {
285                                        msgEntity.setTo(msgEntity.getTo().append(", ").append(a[j].toString()));
286                                }
287                        }
288                }
289
290                // CC
291                if ((a = m.getRecipients(Message.RecipientType.CC)) != null) {
292                        for (int j = 0; j < a.length; j++)
293                        {
294                                if(msgEntity.getCopyto() == null)
295                                {
296                                        msgEntity.setCopyto(new StringBuilder(a[j].toString()));
297                                }
298                                else
299                                {
300                                        msgEntity.setCopyto(msgEntity.getCopyto().append(", ").append(a[j].toString()));
301                                }
302                        }
303                }
304                // CC
305                if ((a = m.getRecipients(Message.RecipientType.BCC)) != null) {
306                        for (int j = 0; j < a.length; j++)
307                        {
308                                if(msgEntity.getHiddencopyto() == null)
309                                {
310                                        msgEntity.setHiddencopyto(new StringBuilder(a[j].toString()));
311                                }
312                                else
313                                {
314                                        msgEntity.setHiddencopyto(new StringBuilder(msgEntity.getHiddencopyto() + ","+a[j].toString()));
315                                }
316                        }
317                }
318
319                // DATE
320                Date d = m.getSentDate();
321                if(msgEntity != null)
322                {
323                        if(d != null)
324                        {
325                                msgEntity.setSent_date(new StringBuilder(String.valueOf(d.getTime())));
326                        }
327                        else
328                        {
329                                msgEntity.setSent_date(new StringBuilder(String.valueOf(new Date().getTime())));
330                        }
331                }
332
333                try{
334                        Object o = m.getContent();
335                        if (o instanceof String) {
336                                if( msgEntity != null )
337                                {
338                                        msgEntity.setContent(new StringBuilder( o.toString()));
339                                }
340                        } else if (o instanceof Multipart) {
341                                Multipart multipart = (Multipart)o;
342                                int count = multipart.getCount();
343
344                                for (int i = 0; i < count; i++)
345                                {
346                                        if(msgEntity.getContent() == null || msgEntity.getContent().toString().trim().equals(""))
347                                        {
348                                                msgEntity.setContent(new StringBuilder(""));
349                                        }
350                                        if(multipart.getBodyPart(i).getContentType() != Part.ATTACHMENT)
351                                        {
352                                                msgEntity.setContent(msgEntity.getContent().append(" ").append(getPlainContent(multipart.getBodyPart(i))));
353                                        }
354
355                                }
356
357                        }
358                }catch (Exception e){
359                        System.out.println("Exception ocurred!");
360                        e.printStackTrace();
361                }
362
363                if(msgEntity != null && msgEntity.getId() != null){
364                        listIMAPMsgs.add(msgEntity);
365                }
366
367        }
368
369        private StringBuilder getPlainContent(BodyPart bodyPart) throws IOException, MessagingException
370        {
371                try
372                {
373
374                        if(bodyPart.getContent() instanceof String)
375                        {
376                                //                              ByteArrayOutputStream out = new ByteArrayOutputStream();
377                                //                              InputStream in = bodyPart.getInputStream();
378                                //                             
379                                //                              byte[] buffer = new byte[1024];
380                                //                              byte[] data = null;
381                                //                             
382                                //                              while(in.read(buffer) != -1) {
383                                //                                      out.write(buffer);
384                                //                              }
385                                //                             
386                                //                              data = out.toByteArray();
387
388                                StringBuilder text = new StringBuilder(bodyPart.getContent().toString());
389
390                                //                              out.close();
391                                //                              in.close();
392
393                                return text;
394                        }
395                }catch(Exception e)
396                {
397                        System.out.println(e.getMessage());
398                        e.printStackTrace();
399                        return new StringBuilder("");
400                }
401
402
403                return new StringBuilder("");
404        }
405
406}
Note: See TracBrowser for help on using the repository browser.