1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.search.lucene;
24  
25  import com.liferay.portal.kernel.dao.jdbc.DataAccess;
26  import com.liferay.portal.kernel.log.Log;
27  import com.liferay.portal.kernel.log.LogFactoryUtil;
28  import com.liferay.portal.kernel.search.SearchEngineUtil;
29  import com.liferay.portal.kernel.util.FileUtil;
30  import com.liferay.portal.kernel.util.InfrastructureUtil;
31  import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.StringUtil;
34  import com.liferay.portal.kernel.util.Validator;
35  import com.liferay.portal.util.PropsKeys;
36  import com.liferay.portal.util.PropsUtil;
37  import com.liferay.portal.util.PropsValues;
38  import com.liferay.util.lucene.KeywordsUtil;
39  
40  import java.io.IOException;
41  
42  import java.sql.Connection;
43  import java.sql.DatabaseMetaData;
44  import java.sql.ResultSet;
45  import java.sql.Statement;
46  
47  import java.util.Date;
48  import java.util.Map;
49  import java.util.concurrent.ConcurrentHashMap;
50  
51  import javax.sql.DataSource;
52  
53  import org.apache.lucene.analysis.Analyzer;
54  import org.apache.lucene.analysis.WhitespaceAnalyzer;
55  import org.apache.lucene.document.Document;
56  import org.apache.lucene.index.IndexReader;
57  import org.apache.lucene.index.IndexWriter;
58  import org.apache.lucene.index.Term;
59  import org.apache.lucene.queryParser.ParseException;
60  import org.apache.lucene.queryParser.QueryParser;
61  import org.apache.lucene.search.BooleanClause;
62  import org.apache.lucene.search.BooleanQuery;
63  import org.apache.lucene.search.IndexSearcher;
64  import org.apache.lucene.search.Query;
65  import org.apache.lucene.search.TermQuery;
66  import org.apache.lucene.search.WildcardQuery;
67  import org.apache.lucene.store.Directory;
68  import org.apache.lucene.store.FSDirectory;
69  import org.apache.lucene.store.RAMDirectory;
70  import org.apache.lucene.store.jdbc.JdbcDirectory;
71  import org.apache.lucene.store.jdbc.JdbcStoreException;
72  import org.apache.lucene.store.jdbc.dialect.Dialect;
73  import org.apache.lucene.store.jdbc.lock.JdbcLock;
74  import org.apache.lucene.store.jdbc.support.JdbcTemplate;
75  
76  /**
77   * <a href="LuceneUtil.java.html"><b><i>View Source</i></b></a>
78   *
79   * @author Brian Wing Shun Chan
80   * @author Harry Mark
81   *
82   */
83  public class LuceneUtil {
84  
85      public static void acquireLock(long companyId) {
86          try {
87              _instance._sharedWriter.acquireLock(companyId, true);
88          }
89          catch (InterruptedException ie) {
90              _log.error(ie);
91          }
92      }
93  
94      public static void addDate(Document doc, String field, Date value) {
95          doc.add(LuceneFields.getDate(field, value));
96      }
97  
98      public static void addExactTerm(
99          BooleanQuery booleanQuery, String field, boolean value) {
100 
101         addExactTerm(booleanQuery, field, String.valueOf(value));
102     }
103 
104     public static void addExactTerm(
105         BooleanQuery booleanQuery, String field, Boolean value) {
106 
107         addExactTerm(booleanQuery, field, String.valueOf(value));
108     }
109 
110     public static void addExactTerm(
111         BooleanQuery booleanQuery, String field, double value) {
112 
113         addExactTerm(booleanQuery, field, String.valueOf(value));
114     }
115 
116     public static void addExactTerm(
117         BooleanQuery booleanQuery, String field, Double value) {
118 
119         addExactTerm(booleanQuery, field, String.valueOf(value));
120     }
121 
122     public static void addExactTerm(
123         BooleanQuery booleanQuery, String field, int value) {
124 
125         addExactTerm(booleanQuery, field, String.valueOf(value));
126     }
127 
128     public static void addExactTerm(
129         BooleanQuery booleanQuery, String field, Integer value) {
130 
131         addExactTerm(booleanQuery, field, String.valueOf(value));
132     }
133 
134     public static void addExactTerm(
135         BooleanQuery booleanQuery, String field, long value) {
136 
137         addExactTerm(booleanQuery, field, String.valueOf(value));
138     }
139 
140     public static void addExactTerm(
141         BooleanQuery booleanQuery, String field, Long value) {
142 
143         addExactTerm(booleanQuery, field, String.valueOf(value));
144     }
145 
146     public static void addExactTerm(
147         BooleanQuery booleanQuery, String field, short value) {
148 
149         addExactTerm(booleanQuery, field, String.valueOf(value));
150     }
151 
152     public static void addExactTerm(
153         BooleanQuery booleanQuery, String field, Short value) {
154 
155         addExactTerm(booleanQuery, field, String.valueOf(value));
156     }
157 
158     public static void addExactTerm(
159         BooleanQuery booleanQuery, String field, String value) {
160 
161         //text = KeywordsUtil.escape(value);
162 
163         Query query = new TermQuery(new Term(field, value));
164 
165         booleanQuery.add(query, BooleanClause.Occur.SHOULD);
166     }
167 
168     public static void addRequiredTerm(
169         BooleanQuery booleanQuery, String field, boolean value) {
170 
171         addRequiredTerm(booleanQuery, field, String.valueOf(value));
172     }
173 
174     public static void addRequiredTerm(
175         BooleanQuery booleanQuery, String field, Boolean value) {
176 
177         addRequiredTerm(booleanQuery, field, String.valueOf(value));
178     }
179 
180     public static void addRequiredTerm(
181         BooleanQuery booleanQuery, String field, double value) {
182 
183         addRequiredTerm(booleanQuery, field, String.valueOf(value));
184     }
185 
186     public static void addRequiredTerm(
187         BooleanQuery booleanQuery, String field, Double value) {
188 
189         addRequiredTerm(booleanQuery, field, String.valueOf(value));
190     }
191 
192     public static void addRequiredTerm(
193         BooleanQuery booleanQuery, String field, int value) {
194 
195         addRequiredTerm(booleanQuery, field, String.valueOf(value));
196     }
197 
198     public static void addRequiredTerm(
199         BooleanQuery booleanQuery, String field, Integer value) {
200 
201         addRequiredTerm(booleanQuery, field, String.valueOf(value));
202     }
203 
204     public static void addRequiredTerm(
205         BooleanQuery booleanQuery, String field, long value) {
206 
207         addRequiredTerm(booleanQuery, field, String.valueOf(value));
208     }
209 
210     public static void addRequiredTerm(
211         BooleanQuery booleanQuery, String field, Long value) {
212 
213         addRequiredTerm(booleanQuery, field, String.valueOf(value));
214     }
215 
216     public static void addRequiredTerm(
217         BooleanQuery booleanQuery, String field, short value) {
218 
219         addRequiredTerm(booleanQuery, field, String.valueOf(value));
220     }
221 
222     public static void addRequiredTerm(
223         BooleanQuery booleanQuery, String field, Short value) {
224 
225         addRequiredTerm(booleanQuery, field, String.valueOf(value));
226     }
227 
228     public static void addRequiredTerm(
229         BooleanQuery booleanQuery, String field, String value) {
230 
231         addRequiredTerm(booleanQuery, field, value, false);
232     }
233 
234     public static void addRequiredTerm(
235         BooleanQuery booleanQuery, String field, String value, boolean like) {
236 
237         if (like) {
238             value = StringUtil.replace(
239                 value, StringPool.PERCENT, StringPool.STAR);
240 
241             value = value.toLowerCase();
242 
243             WildcardQuery wildcardQuery = new WildcardQuery(
244                 new Term(field, value));
245 
246             booleanQuery.add(wildcardQuery, BooleanClause.Occur.MUST);
247         }
248         else {
249             //text = KeywordsUtil.escape(value);
250 
251             Term term = new Term(field, value);
252             TermQuery termQuery = new TermQuery(term);
253 
254             booleanQuery.add(termQuery, BooleanClause.Occur.MUST);
255         }
256     }
257 
258     public static void addTerm(
259             BooleanQuery booleanQuery, String field, long value)
260         throws ParseException {
261 
262         addTerm(booleanQuery, field, String.valueOf(value));
263     }
264 
265     public static void addTerm(
266             BooleanQuery booleanQuery, String field, String value)
267         throws ParseException {
268 
269         addTerm(booleanQuery, field, value, false);
270     }
271 
272     public static void addTerm(
273             BooleanQuery booleanQuery, String field, String value,
274             boolean like)
275         throws ParseException {
276 
277         if (Validator.isNull(value)) {
278             return;
279         }
280 
281         if (like) {
282             value = value.toLowerCase();
283 
284             StringBuilder sb = new StringBuilder();
285 
286             sb.append(StringPool.STAR);
287             sb.append(value);
288             sb.append(StringPool.STAR);
289 
290             WildcardQuery wildcardQuery = new WildcardQuery(
291                 new Term(field, sb.toString()));
292 
293             booleanQuery.add(wildcardQuery, BooleanClause.Occur.SHOULD);
294         }
295         else {
296             QueryParser queryParser = new QueryParser(
297                 field, LuceneUtil.getAnalyzer());
298 
299             try {
300                 Query query = queryParser.parse(value);
301 
302                 booleanQuery.add(query, BooleanClause.Occur.SHOULD);
303             }
304             catch (ParseException pe) {
305                 if (_log.isDebugEnabled()) {
306                     _log.debug(
307                         "ParseException thrown, reverting to literal search",
308                         pe);
309                 }
310 
311                 value = KeywordsUtil.escape(value);
312 
313                 Query query = queryParser.parse(value);
314 
315                 booleanQuery.add(query, BooleanClause.Occur.SHOULD);
316             }
317         }
318     }
319 
320     public static void checkLuceneDir(long companyId) {
321         if (SearchEngineUtil.isIndexReadOnly()) {
322             return;
323         }
324 
325         Directory luceneDir = LuceneUtil.getLuceneDir(companyId);
326 
327         try {
328 
329             // LEP-6078
330 
331             if (luceneDir.fileExists("write.lock")) {
332                 luceneDir.deleteFile("write.lock");
333             }
334         }
335         catch (IOException ioe) {
336             _log.error("Unable to clear write lock", ioe);
337         }
338 
339         IndexWriter writer = null;
340 
341         // Lucene does not properly release its lock on the index when
342         // IndexWriter throws an exception
343 
344         try {
345             if (luceneDir.fileExists("segments.gen")) {
346                 writer = new IndexWriter(
347                     luceneDir, LuceneUtil.getAnalyzer(), false);
348             }
349             else {
350                 writer = new IndexWriter(
351                     luceneDir, LuceneUtil.getAnalyzer(), true);
352             }
353         }
354         catch (IOException ioe) {
355             _log.error("Check Lucene directory failed for " + companyId, ioe);
356         }
357         finally {
358             if (writer != null) {
359                 try {
360                     writer.close();
361                 }
362                 catch (IOException ioe) {
363                     _log.error(ioe);
364                 }
365             }
366         }
367     }
368 
369     public static void delete(long companyId) {
370         _instance._delete(companyId);
371     }
372 
373     public static void deleteDocuments(long companyId, Term term)
374         throws IOException {
375 
376         try {
377             _instance._sharedWriter.deleteDocuments(companyId, term);
378         }
379         catch (InterruptedException ie) {
380             _log.error(ie);
381         }
382     }
383 
384     public static Analyzer getAnalyzer() {
385         return _instance._getAnalyzer();
386     }
387 
388     public static Directory getLuceneDir(long companyId) {
389         return _instance._getLuceneDir(companyId);
390     }
391 
392     public static IndexReader getReader(long companyId) throws IOException {
393         return IndexReader.open(getLuceneDir(companyId));
394     }
395 
396     public static IndexSearcher getSearcher(long companyId)
397         throws IOException {
398 
399         return new IndexSearcher(getLuceneDir(companyId));
400     }
401 
402     public static IndexWriter getWriter(long companyId) throws IOException {
403         return getWriter(companyId, false);
404     }
405 
406     public static IndexWriter getWriter(long companyId, boolean create)
407         throws IOException {
408 
409         return _instance._sharedWriter.getWriter(companyId, create);
410     }
411 
412     public static void releaseLock(long companyId) {
413         _instance._sharedWriter.releaseLock(companyId);
414     }
415 
416     public static void write(long companyId) {
417         _instance._sharedWriter.write(companyId);
418     }
419 
420     public static void write(IndexWriter writer) throws IOException {
421         _instance._sharedWriter.write(writer);
422     }
423 
424     private LuceneUtil() {
425         String analyzerName = PropsUtil.get(PropsKeys.LUCENE_ANALYZER);
426 
427         if (Validator.isNotNull(analyzerName)) {
428             try {
429                 _analyzerClass = Class.forName(analyzerName);
430             }
431             catch (Exception e) {
432                 _log.error(e);
433             }
434         }
435 
436         // Dialect
437 
438         if (PropsValues.LUCENE_STORE_TYPE.equals(_LUCENE_STORE_TYPE_JDBC)) {
439             Connection con = null;
440 
441             try {
442                 con = DataAccess.getConnection();
443 
444                 String url = con.getMetaData().getURL();
445 
446                 int x = url.indexOf(":");
447                 int y = url.indexOf(":", x + 1);
448 
449                 String urlPrefix = url.substring(x + 1, y);
450 
451                 String dialectClass = PropsUtil.get(
452                     PropsKeys.LUCENE_STORE_JDBC_DIALECT + urlPrefix);
453 
454                 if (dialectClass != null) {
455                     if (_log.isDebugEnabled()) {
456                         _log.debug("JDBC class implementation " + dialectClass);
457                     }
458                 }
459                 else {
460                     if (_log.isDebugEnabled()) {
461                         _log.debug("JDBC class implementation is null");
462                     }
463                 }
464 
465                 if (dialectClass != null) {
466                     _dialect =
467                         (Dialect)Class.forName(dialectClass).newInstance();
468                 }
469             }
470             catch (Exception e) {
471                 _log.error(e);
472             }
473             finally{
474                 DataAccess.cleanUp(con);
475             }
476 
477             if (_dialect == null) {
478                 _log.error("No JDBC dialect found");
479             }
480         }
481     }
482 
483     public void _delete(long companyId) {
484         if (SearchEngineUtil.isIndexReadOnly()) {
485             return;
486         }
487 
488         if (_log.isDebugEnabled()) {
489             _log.debug("Lucene store type " + PropsValues.LUCENE_STORE_TYPE);
490         }
491 
492         if (PropsValues.LUCENE_STORE_TYPE.equals(_LUCENE_STORE_TYPE_FILE)) {
493             _deleteFile(companyId);
494         }
495         else if (PropsValues.LUCENE_STORE_TYPE.equals(
496                     _LUCENE_STORE_TYPE_JDBC)) {
497 
498             _deleteJdbc(companyId);
499         }
500         else if (PropsValues.LUCENE_STORE_TYPE.equals(_LUCENE_STORE_TYPE_RAM)) {
501             _deleteRam(companyId);
502         }
503         else {
504             throw new RuntimeException(
505                 "Invalid store type " + PropsValues.LUCENE_STORE_TYPE);
506         }
507     }
508 
509     private void _deleteFile(long companyId) {
510         String path = _getPath(companyId);
511 
512         try {
513             Directory directory = FSDirectory.getDirectory(path, false);
514 
515             directory.close();
516         }
517         catch (Exception e) {
518             if (_log.isWarnEnabled()) {
519                 _log.warn("Could not close directory " + path);
520             }
521         }
522 
523         FileUtil.deltree(path);
524     }
525 
526     private void _deleteJdbc(long companyId) {
527         String tableName = _getTableName(companyId);
528 
529         try {
530             Directory directory = _jdbcDirectories.remove(tableName);
531 
532             if (directory != null) {
533                 directory.close();
534             }
535         }
536         catch (Exception e) {
537             if (_log.isWarnEnabled()) {
538                 _log.warn("Could not close directory " + tableName);
539             }
540         }
541 
542         Connection con = null;
543         Statement s = null;
544 
545         try {
546             con = DataAccess.getConnection();
547 
548             s = con.createStatement();
549 
550             s.executeUpdate("DELETE FROM " + tableName);
551         }
552         catch (Exception e) {
553             if (_log.isWarnEnabled()) {
554                 _log.warn("Could not truncate " + tableName);
555             }
556         }
557         finally {
558             DataAccess.cleanUp(con, s);
559         }
560     }
561 
562     private void _deleteRam(long companyId) {
563     }
564 
565     private Analyzer _getAnalyzer() {
566         try {
567             return (Analyzer)_analyzerClass.newInstance();
568         }
569         catch (Exception e) {
570             throw new RuntimeException(e);
571         }
572     }
573 
574     private Directory _getLuceneDir(long companyId) {
575         if (_log.isDebugEnabled()) {
576             _log.debug("Lucene store type " + PropsValues.LUCENE_STORE_TYPE);
577         }
578 
579         if (PropsValues.LUCENE_STORE_TYPE.equals(_LUCENE_STORE_TYPE_FILE)) {
580             return _getLuceneDirFile(companyId);
581         }
582         else if (PropsValues.LUCENE_STORE_TYPE.equals(
583                     _LUCENE_STORE_TYPE_JDBC)) {
584 
585             return _getLuceneDirJdbc(companyId);
586         }
587         else if (PropsValues.LUCENE_STORE_TYPE.equals(_LUCENE_STORE_TYPE_RAM)) {
588             return _getLuceneDirRam(companyId);
589         }
590         else {
591             throw new RuntimeException(
592                 "Invalid store type " + PropsValues.LUCENE_STORE_TYPE);
593         }
594     }
595 
596     private Directory _getLuceneDirFile(long companyId) {
597         Directory directory = null;
598 
599         String path = _getPath(companyId);
600 
601         try {
602             directory = FSDirectory.getDirectory(path, false);
603         }
604         catch (IOException ioe1) {
605             try {
606                 if (directory != null) {
607                     directory.close();
608                 }
609 
610                 directory = FSDirectory.getDirectory(path, true);
611             }
612             catch (IOException ioe2) {
613                 throw new RuntimeException(ioe2);
614             }
615         }
616 
617         return directory;
618     }
619 
620     private Directory _getLuceneDirJdbc(long companyId) {
621         JdbcDirectory directory = null;
622 
623         Thread currentThread = Thread.currentThread();
624 
625         ClassLoader contextClassLoader = currentThread.getContextClassLoader();
626 
627         try {
628             currentThread.setContextClassLoader(
629                 PortalClassLoaderUtil.getClassLoader());
630 
631             String tableName = _getTableName(companyId);
632 
633             directory = (JdbcDirectory)_jdbcDirectories.get(tableName);
634 
635             if (directory != null) {
636                 return directory;
637             }
638 
639             try {
640                 DataSource ds = InfrastructureUtil.getDataSource();
641 
642                 directory = new JdbcDirectory(ds, _dialect, tableName);
643 
644                 _jdbcDirectories.put(tableName, directory);
645 
646                 if (!directory.tableExists()) {
647                     directory.create();
648                 }
649             }
650             catch (IOException ioe) {
651                 throw new RuntimeException(ioe);
652             }
653             catch (UnsupportedOperationException uoe) {
654                 if (_log.isWarnEnabled()) {
655                     _log.warn(
656                         "Database doesn't support the ability to check " +
657                             "whether a table exists");
658                 }
659 
660                 _manuallyCreateJdbcDirectory(directory, tableName);
661             }
662         }
663         finally {
664             currentThread.setContextClassLoader(contextClassLoader);
665         }
666 
667         return directory;
668     }
669 
670     private Directory _getLuceneDirRam(long companyId) {
671         String path = _getPath(companyId);
672 
673         Directory directory = _ramDirectories.get(path);
674 
675         if (directory == null) {
676             directory = new RAMDirectory();
677 
678             _ramDirectories.put(path, directory);
679         }
680 
681         return directory;
682     }
683 
684     private String _getPath(long companyId) {
685         StringBuilder sb = new StringBuilder();
686 
687         sb.append(PropsValues.LUCENE_DIR);
688         sb.append(companyId);
689         sb.append(StringPool.SLASH);
690 
691         return sb.toString();
692     }
693 
694     private String _getTableName(long companyId) {
695         return _LUCENE_TABLE_PREFIX + companyId;
696     }
697 
698     private void _manuallyCreateJdbcDirectory(
699         JdbcDirectory directory, String tableName) {
700 
701         // LEP-2181
702 
703         Connection con = null;
704         ResultSet rs = null;
705 
706         try {
707             con = DataAccess.getConnection();
708 
709             // Check if table exists
710 
711             DatabaseMetaData metaData = con.getMetaData();
712 
713             rs = metaData.getTables(null, null, tableName, null);
714 
715             if (!rs.next()) {
716                 JdbcTemplate jdbcTemplate = directory.getJdbcTemplate();
717 
718                 jdbcTemplate.executeUpdate(directory.getTable().sqlCreate());
719 
720                 Class<?> lockClass = directory.getSettings().getLockClass();
721 
722                 JdbcLock jdbcLock = null;
723 
724                 try {
725                     jdbcLock = (JdbcLock)lockClass.newInstance();
726                 }
727                 catch (Exception e) {
728                     throw new JdbcStoreException(
729                         "Failed to create lock class " + lockClass);
730                 }
731 
732                 jdbcLock.initializeDatabase(directory);
733             }
734         }
735         catch (Exception e) {
736             if (_log.isWarnEnabled()) {
737                 _log.warn("Could not create " + tableName);
738             }
739         }
740         finally {
741             DataAccess.cleanUp(con, null, rs);
742         }
743     }
744 
745     private static final String _LUCENE_STORE_TYPE_FILE = "file";
746 
747     private static final String _LUCENE_STORE_TYPE_JDBC = "jdbc";
748 
749     private static final String _LUCENE_STORE_TYPE_RAM = "ram";
750 
751     private static final String _LUCENE_TABLE_PREFIX = "LUCENE_";
752 
753     private static Log _log = LogFactoryUtil.getLog(LuceneUtil.class);
754 
755     private static LuceneUtil _instance = new LuceneUtil();
756 
757     private IndexWriterFactory _sharedWriter = new IndexWriterFactory();
758     private Class<?> _analyzerClass = WhitespaceAnalyzer.class;
759     private Dialect _dialect;
760     private Map<String, Directory> _jdbcDirectories =
761         new ConcurrentHashMap<String, Directory>();
762     private Map<String, Directory> _ramDirectories =
763         new ConcurrentHashMap<String, Directory>();
764 
765 }