KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opencms > defaults > CmsLinkCheck


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/com/opencms/defaults/CmsLinkCheck.java,v $
3  * Date : $Date: 2005/06/27 23:22:24 $
4  * Version: $Revision: 1.6 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (C) 2002 Alkacon Software (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package com.opencms.defaults;
33
34 import org.opencms.file.CmsFile;
35 import org.opencms.file.CmsObject;
36 import org.opencms.file.CmsResourceFilter;
37 import org.opencms.file.types.CmsResourceTypePointer;
38 import org.opencms.mail.CmsHtmlMail;
39 import org.opencms.mail.CmsMailTransport;
40 import org.opencms.mail.CmsSimpleMail;
41 import org.opencms.main.CmsException;
42 import org.opencms.main.CmsLog;
43 import org.opencms.main.OpenCms;
44 import org.opencms.scheduler.I_CmsScheduledJob;
45 import org.opencms.validation.CmsPointerLinkValidator;
46
47 import com.opencms.legacy.CmsLegacyException;
48 import com.opencms.legacy.CmsRegistry;
49 import com.opencms.template.CmsXmlTemplate;
50 import com.opencms.template.CmsXmlTemplateFile;
51
52 import java.io.ByteArrayInputStream JavaDoc;
53 import java.io.File JavaDoc;
54 import java.io.FileInputStream JavaDoc;
55 import java.io.FileOutputStream JavaDoc;
56 import java.io.FileWriter JavaDoc;
57 import java.io.IOException JavaDoc;
58 import java.io.ObjectInputStream JavaDoc;
59 import java.io.ObjectOutputStream JavaDoc;
60 import java.io.Serializable JavaDoc;
61 import java.net.HttpURLConnection JavaDoc;
62 import java.net.MalformedURLException JavaDoc;
63 import java.net.URL JavaDoc;
64 import java.util.ArrayList JavaDoc;
65 import java.util.Calendar JavaDoc;
66 import java.util.Enumeration JavaDoc;
67 import java.util.GregorianCalendar JavaDoc;
68 import java.util.Hashtable JavaDoc;
69 import java.util.List JavaDoc;
70 import java.util.Map JavaDoc;
71 import java.util.StringTokenizer JavaDoc;
72 import java.util.Vector JavaDoc;
73
74 import javax.mail.MessagingException JavaDoc;
75 import javax.mail.internet.AddressException JavaDoc;
76 import javax.mail.internet.InternetAddress JavaDoc;
77
78 /**
79  * This class contains the functionaility for checking the validity of external links.<p>
80  *
81  * @deprecated Will not be supported past the OpenCms 6 release.
82  */

83 public class CmsLinkCheck extends CmsXmlTemplate implements I_CmsScheduledJob {
84
85     /** The defintion of the filename to store the serialized hashtable in the rfs. */
86     static final String JavaDoc LINKTABLE_FILENAME = OpenCms.getSystemInfo().getPackagesRfsPath() + "linkcheck";
87     /** The key for the date of the last linkcheck in the linkchecktable. */
88     public static final String JavaDoc C_LINKCHECKTABLE_DATE = "linkcheckdate";
89     
90     /**
91      * Constructor, does nothing.<p>
92      */

93     public CmsLinkCheck() {
94         // empty
95
}
96
97     /**
98      * Checks if the given url is valid and returns the response message.<p>
99      *
100      * @param url the url to check
101      * @return the response message
102      */

103     public String JavaDoc checkUrlGetMessage(String JavaDoc url) {
104         try {
105             URL JavaDoc checkedUrl = new URL JavaDoc(url);
106             HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)checkedUrl.openConnection();
107             if (con.getResponseCode() == 200) {
108                 return "";
109             } else {
110                 return con.getResponseMessage();
111             }
112         } catch (MalformedURLException JavaDoc mue) {
113             return "MalformedURLException: " + mue.getMessage();
114         } catch (IOException JavaDoc ioe) {
115             return "IOException: " + ioe.getMessage();
116         }
117     }
118
119     /**
120      * Generates a warning email message.<p>
121      *
122      * @param mailFrom the email adress of the sender
123      * @param mailTo the email adress(es) of the receiver(s)
124      * @param mailCc the email adress(es) of the CC-receiver(s)
125      * @param mailBcc the email adress(es) of the BCC-receiver(s)
126      * @param mailSubject the subject of the mail
127      * @param mailContent the content of the mail
128      * @param mailType the type of the mail
129      * @throws CmsException if something goes wrong
130      */

131     private void generateEmail(
132         String JavaDoc mailFrom,
133         List JavaDoc mailTo,
134         List JavaDoc mailCc,
135         List JavaDoc mailBcc,
136         String JavaDoc mailSubject,
137         String JavaDoc mailContent,
138         String JavaDoc mailType
139     ) throws CmsException {
140         // create a new CmsMail object and start sending the mails
141
if (mailType.toLowerCase().indexOf("html") != -1) {
142             CmsHtmlMail mail = new CmsHtmlMail();
143             try {
144                 mail.setFrom(mailFrom);
145             } catch (MessagingException JavaDoc e) {
146                 throw new CmsLegacyException("[" + this.getClass().getName() + "] " + "Error in sending email, invalid recipient email address.", CmsLegacyException.C_BAD_NAME);
147             }
148             mail.setSubject(mailSubject);
149             mail.setHtmlMsg(mailContent);
150             mail.setTextMsg(mailContent);
151             if (mailTo != null) {
152                 mail.setTo(mailTo);
153             }
154             if (mailCc != null) {
155                 mail.setCc(mailCc);
156             }
157             if (mailBcc != null) {
158                 mail.setCc(mailBcc);
159             }
160             new CmsMailTransport(mail).send();
161         } else {
162             CmsSimpleMail mail = new CmsSimpleMail();
163             try {
164                 mail.setFrom(mailFrom);
165             } catch (MessagingException JavaDoc e) {
166                 throw new CmsLegacyException("[" + this.getClass().getName() + "] " + "Error in sending email, invalid recipient email address.", CmsLegacyException.C_BAD_NAME);
167             }
168             mail.setSubject(mailSubject);
169             mail.setMsg(mailContent);
170             if (mailTo != null) {
171                 mail.setTo(mailTo);
172             }
173             if (mailCc != null) {
174                 mail.setCc(mailCc);
175             }
176             if (mailBcc != null) {
177                 mail.setCc(mailBcc);
178             }
179             new CmsMailTransport(mail).send();
180         }
181     }
182
183     /**
184      * Generates the file.<p>
185      *
186      * @param content the content to store into the file
187      * @param pathname the path where the file should be stored
188      * @param actDate the date and time when the urls were checked
189      * @throws CmsException if something goes wrong
190      */

191     private void generateFile(String JavaDoc content, String JavaDoc pathname, GregorianCalendar JavaDoc actDate) throws CmsException {
192         StringBuffer JavaDoc filename = new StringBuffer JavaDoc("check_");
193         String JavaDoc year = actDate.get(Calendar.YEAR) + "";
194         String JavaDoc month = (actDate.get(Calendar.MONTH) + 1) + "";
195         if (month.length() == 1) {
196             month = "0" + month;
197         }
198         String JavaDoc day = (actDate.get(Calendar.DATE) + "");
199         if (day.length() == 1) {
200             day = "0" + day;
201         }
202         String JavaDoc hour = actDate.get(Calendar.HOUR_OF_DAY) + "";
203         if (hour.length() == 1) {
204             hour = "0" + hour;
205         }
206         String JavaDoc minute = actDate.get(Calendar.MINUTE) + "";
207         if (minute.length() == 1) {
208             minute = "0" + minute;
209         }
210         filename.append(year.substring(2));
211         filename.append(month);
212         filename.append(day);
213         filename.append("_" + hour + "-");
214         filename.append(minute);
215         filename.append(".html");
216         // create a new file in the folder with the pathname and writes the filecontent
217
try {
218             File outputFile = new File(pathname, filename.toString());
219             FileWriter JavaDoc writer = new FileWriter JavaDoc(outputFile);
220             writer.write(content);
221             writer.close();
222         } catch (IOException JavaDoc e) {
223             throw new CmsLegacyException("Cannot write output file.", e);
224         }
225     }
226
227     /**
228      * Returns the current date as formatted String.<p>
229      *
230      * @param actDate the current date
231      * @return the current date as String dd.mm.yyyy hh:min
232      */

233     private String JavaDoc getDateString(GregorianCalendar JavaDoc actDate) {
234         String JavaDoc month = (actDate.get(Calendar.MONTH) + 1) + "";
235         if (month.length() == 1) {
236             month = "0" + month;
237         }
238         String JavaDoc day = (actDate.get(Calendar.DATE) + "");
239         if (day.length() == 1) {
240             day = "0" + day;
241         }
242         String JavaDoc hour = actDate.get(Calendar.HOUR_OF_DAY) + "";
243         if (hour.length() == 1) {
244             hour = "0" + hour;
245         }
246         String JavaDoc minute = actDate.get(Calendar.MINUTE) + "";
247         if (minute.length() == 1) {
248             minute = "0" + minute;
249         }
250         return (day + "." + month + "." + actDate.get(Calendar.YEAR) + " " + hour + ":" + minute);
251     }
252
253     /**
254      * Returns the mail receivers in a string as string array.<p>
255      *
256      * The receivers are separated by a semicolon.<p>
257      *
258      * @param receivers The string that contains the receivers
259      * @return String[] The receivers as elements in an string array
260      */

261     private List JavaDoc getReceiverList(String JavaDoc receivers) {
262         List JavaDoc retArray = new ArrayList JavaDoc();
263         if (receivers != null) {
264             if (!"".equals(receivers.trim())) {
265                 StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(receivers, ";");
266                 retArray = new ArrayList JavaDoc();
267                 while (tokens.hasMoreElements()) {
268                     try {
269                         retArray.add(new InternetAddress JavaDoc((String JavaDoc)tokens.nextElement()));
270                     } catch (AddressException JavaDoc e) {
271                         if (CmsLog.getLog(this).isErrorEnabled()) {
272                             CmsLog.getLog(this).error(e);
273                         }
274                     }
275                 }
276             }
277         }
278         return retArray;
279     }
280
281     /**
282      * This method is called by the cron scheduler.<p>
283      *
284      * @param cms a OpenCms context object
285      * @param parameters link check parameters
286      * @return the String that is written to the OpenCms log
287      * @throws CmsException if something goes wrong
288      */

289     public String JavaDoc launch(CmsObject cms, Map JavaDoc parameters) throws CmsException {
290         String JavaDoc parameter = (String JavaDoc)parameters.get((String JavaDoc)parameters.keySet().iterator().next());
291         if (parameter == null) {
292             parameter = "";
293         }
294         linksUrlCheck(cms, parameter);
295         return "CmsLinkCheck.launch(): Links checked.";
296     }
297
298     /**
299      * Checks all existing external links.<p>
300      *
301      * @param cms a OpenCms context object
302      * @param parameter link check parameters
303      * @throws CmsException if something goes wrong
304      */

305     public void linksUrlCheck(CmsObject cms, String JavaDoc parameter) throws CmsException {
306         // hashtable that contains the urls that are not available and the resourcenames of the links
307
// where this url is referenced
308
Hashtable JavaDoc notAvailable = new Hashtable JavaDoc();
309
310         // vector that contains all external links from the database
311
Vector JavaDoc linkList = new Vector JavaDoc();
312
313         // vector and hashtable that contains the links of an owner that are not available,
314
// so there can be created a mail to the owner with all the broken links
315
Hashtable JavaDoc ownerLinkList = new Hashtable JavaDoc();
316
317         // get the hashtable with the last check result from the system table
318
Hashtable JavaDoc linkckecktable = CmsLinkCheck.readLinkCheckTable();
319
320         Hashtable JavaDoc newLinkchecktable = new Hashtable JavaDoc();
321         // get the values for email from the registry
322
// TODO: check REGISTRY "checklink"
323
int warning = 0;
324         Hashtable JavaDoc emailValues = CmsRegistry.getInstance().getSystemValues("checklink");
325         // Hashtable emailValues = new Hashtable();
326
// get templateFile this way because there is no actual file if
327
// method is called from scheduler ...
328
CmsXmlTemplateFile template = getOwnTemplateFile(cms, (String JavaDoc)emailValues.get("mailtemplate"), "", null, "");
329
330         // set the current date and time
331
GregorianCalendar JavaDoc actDate = new GregorianCalendar JavaDoc();
332         String JavaDoc actDateString = getDateString(actDate);
333         template.setData("actdate", actDateString);
334         newLinkchecktable.put(CmsLinkCheck.C_LINKCHECKTABLE_DATE, actDateString);
335
336         StringBuffer JavaDoc mailContent = new StringBuffer JavaDoc(template.getProcessedDataValue("single_message"));
337
338         // get all links from the database
339
linkList = new Vector JavaDoc(cms.readResources("/", CmsResourceFilter.ONLY_VISIBLE_NO_DELETED
340             .addRequireType(CmsResourceTypePointer.getStaticTypeId())));
341         for (int i = 0; i < linkList.size(); i++) {
342             CmsFile linkElement = (CmsFile)linkList.elementAt(i);
343             String JavaDoc linkName = cms.getSitePath(linkElement);
344             String JavaDoc linkUrl = new String JavaDoc(linkElement.getContents());
345             // do not check internal links
346
if (!linkUrl.startsWith("/")) {
347                 // get the number of failed checks for the link
348
int failedCheck = 0;
349                 String JavaDoc numFromTable = (String JavaDoc)linkckecktable.get(linkName + ", " + linkUrl);
350                 if ((numFromTable != null) && (!"".equals(numFromTable.trim()))) {
351                     failedCheck = Integer.parseInt(numFromTable);
352                 }
353
354                 // check the url,
355
// if the url is not readable add it to the list of not available urls
356
if (!CmsPointerLinkValidator.checkUrl(cms, linkUrl)) {
357                     // get the vector of resourcenames from the hashtable of urls
358
Vector JavaDoc inList = null;
359                     inList = (Vector JavaDoc)notAvailable.get(linkUrl);
360                     if (inList == null) {
361                         inList = new Vector JavaDoc();
362                     }
363                     inList.addElement(linkName);
364                     notAvailable.put(linkUrl, inList);
365
366                     // create the hashtable for the owner mails if requested
367
if ((parameter != null) && ("owneremail".equals(parameter.trim()))) {
368                         // add the failed link to the links of the owner
369
// first try to get the email
370
String JavaDoc ownerEmail = null;
371                         if ((ownerEmail == null) || ("".equals(ownerEmail.trim()))) {
372                             ownerEmail = (String JavaDoc)emailValues.get("mailto");
373                         }
374                         Hashtable JavaDoc ownerLinks = null;
375                         ownerLinks = (Hashtable JavaDoc)ownerLinkList.get(ownerEmail);
376                         if (ownerLinks == null) {
377                             ownerLinks = new Hashtable JavaDoc();
378                         }
379                         ownerLinks.put(linkName, linkUrl);
380                         ownerLinkList.put(ownerEmail, ownerLinks);
381                     }
382
383                     // add the failed link to the new linkchecktable
384
newLinkchecktable.put(linkName + ", " + linkUrl, "" + (failedCheck + 1));
385                 }
386             }
387         }
388         // write the linkchecktable to database
389
CmsLinkCheck.writeLinkCheckTable(newLinkchecktable);
390
391         // get the information for the output
392
if ((parameter != null) && (!"".equals(parameter.trim()))) {
393             // send an email to the owner of the link
394
if ("owneremail".equals(parameter.trim())) {
395                 // get the owners from the owner list
396
if (ownerLinkList.size() > 0) {
397                     Enumeration JavaDoc ownerKeys = ownerLinkList.keys();
398                     while (ownerKeys.hasMoreElements()) {
399                         StringBuffer JavaDoc ownerContent = new StringBuffer JavaDoc();
400                         ownerContent.append(mailContent.toString());
401                         String JavaDoc mailTo = (String JavaDoc)ownerKeys.nextElement();
402                         Hashtable JavaDoc linknames = (Hashtable JavaDoc)ownerLinkList.get(mailTo);
403                         // get all failed links of the owner
404
Enumeration JavaDoc linkKeys = linknames.keys();
405                         String JavaDoc singleLink = "";
406                         while (linkKeys.hasMoreElements()) {
407                             // set the data for the link
408
singleLink = (String JavaDoc)linkKeys.nextElement();
409                             template.setData("ownerlinkname", singleLink);
410                             template.setData("ownerlinkurl", (String JavaDoc)linknames.get(singleLink));
411                             ownerContent.append(template.getProcessedDataValue("ownermail_link"));
412                         }
413                         // get the email data
414
String JavaDoc mailSubject = template.getProcessedDataValue("emailsubject");
415                         String JavaDoc mailFrom = (String JavaDoc)emailValues.get("mailfrom");
416                         List JavaDoc mailCc = getReceiverList(template.getDataValue("emailcc"));
417                         List JavaDoc mailBcc = getReceiverList(template.getDataValue("emailbcc"));
418                         String JavaDoc mailType = template.getDataValue("emailtype");
419                         generateEmail(mailFrom, getReceiverList(mailTo), mailCc, mailBcc, mailSubject, ownerContent.toString(), mailType);
420                     }
421                 }
422             } else {
423                 // if there are not readable urls create the content of the eMail
424
// and send it to the specified user(s)
425
if (notAvailable.size() > 0) {
426                     Enumeration JavaDoc linkKeys = notAvailable.keys();
427                     StringBuffer JavaDoc mailUrls = new StringBuffer JavaDoc();
428                     while (linkKeys.hasMoreElements()) {
429                         String JavaDoc url = (String JavaDoc)linkKeys.nextElement();
430                         template.setData("url", url);
431                         Vector JavaDoc linknames = (Vector JavaDoc)notAvailable.get(url);
432                         StringBuffer JavaDoc mailLinks = new StringBuffer JavaDoc();
433                         for (int j = 0; j < linknames.size(); j++) {
434                             String JavaDoc nextLink = (String JavaDoc)linknames.elementAt(j);
435                             template.setData("linkname", nextLink);
436                             mailLinks.append(template.getProcessedDataValue("single_link"));
437                         }
438                         template.setData("links", mailLinks.toString());
439                         mailUrls.append(template.getProcessedDataValue("single_url"));
440                     }
441                     mailContent.append(mailUrls.toString());
442                     if ("email".equals(parameter.trim())) {
443                         // get the eMail information
444
String JavaDoc mailSubject = template.getProcessedDataValue("emailsubject");
445                         String JavaDoc mailFrom = (String JavaDoc)emailValues.get("mailfrom");
446                         List JavaDoc mailTo = getReceiverList((String JavaDoc)emailValues.get("mailto"));
447                         List JavaDoc mailCc = getReceiverList(template.getDataValue("emailcc"));
448                         List JavaDoc mailBcc = getReceiverList(template.getDataValue("emailbcc"));
449                         String JavaDoc mailType = template.getDataValue("emailtype");
450                         generateEmail(mailFrom, mailTo, mailCc, mailBcc, mailSubject, mailContent.toString(), mailType);
451                     } else {
452                         generateFile(mailContent.toString(), parameter, actDate);
453                     }
454                 }
455             }
456         }
457     }
458    
459     /**
460      * Writes the Linkchecktable.
461      *
462      * @param newLinkchecktable The hashtable that contains the links that were not reachable
463      * @throws CmsException if something goes wrong
464      */

465     public static void writeLinkCheckTable(Hashtable JavaDoc newLinkchecktable) throws CmsException {
466         FileOutputStream JavaDoc fOut = null;
467         try {
468             File tableInRfs = new File(LINKTABLE_FILENAME);
469             if (tableInRfs.exists()) {
470                 tableInRfs.delete();
471                 tableInRfs.createNewFile();
472             }
473             // serialize the object
474
fOut = new FileOutputStream JavaDoc(tableInRfs);
475             ObjectOutputStream JavaDoc oout = new ObjectOutputStream JavaDoc(fOut);
476             oout.writeObject(newLinkchecktable);
477             oout.close();
478             oout.flush();
479         } catch (IOException JavaDoc e) {
480             throw new CmsLegacyException("Error writing serialized hashtable. "+e);
481         } finally {
482             try {
483                 if (fOut != null) {
484                     fOut.close();
485                 }
486             } catch (IOException JavaDoc e) {
487                 // ignore
488
}
489         }
490     }
491     
492     /**
493      * Gets the Linkchecktable.
494      *
495      * @return the linkchecktable
496      *
497      * @throws CmsException if something goes wrong
498      */

499     public static Hashtable JavaDoc readLinkCheckTable() throws CmsException {
500         Hashtable JavaDoc result = new Hashtable JavaDoc();
501         FileInputStream JavaDoc fIn = null;
502         byte[] buffer;
503         int charsRead;
504         int size;
505         try {
506         File tableInRfs = new File(LINKTABLE_FILENAME);
507         if (tableInRfs.exists()) {
508             fIn = new FileInputStream JavaDoc(tableInRfs);
509             charsRead = 0;
510             size = new Long JavaDoc(tableInRfs.length()).intValue();
511             buffer = new byte[size];
512             while (charsRead < size) {
513                 charsRead += fIn.read(buffer, charsRead, size - charsRead);
514             }
515             
516             // now deserialize the object
517
ByteArrayInputStream JavaDoc bin = new ByteArrayInputStream JavaDoc(buffer);
518             ObjectInputStream JavaDoc oin = new ObjectInputStream JavaDoc(bin);
519             Serializable JavaDoc s = (Serializable JavaDoc) oin.readObject();
520             result = (Hashtable JavaDoc) s;
521         }
522         } catch (Exception JavaDoc e) {
523             throw new CmsLegacyException("Error writing serialized hashtable. "+e);
524         } finally {
525         try {
526             if (fIn != null) {
527                 fIn.close();
528             }
529         } catch (IOException JavaDoc e) {
530             // ignore
531
}
532     }
533         return result;
534     }
535 }
Popular Tags