Coverage Report - org.owasp.dependencycheck.data.cpe.CpeMemoryIndex
 
Classes in this File Line Coverage Branch Coverage Complexity
CpeMemoryIndex
72%
70/96
50%
13/26
3.071
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Dependency-check-core is free software: you can redistribute it and/or modify it
 5  
  * under the terms of the GNU General Public License as published by the Free
 6  
  * Software Foundation, either version 3 of the License, or (at your option) any
 7  
  * later version.
 8  
  *
 9  
  * Dependency-check-core is distributed in the hope that it will be useful, but
 10  
  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  
  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 12  
  * details.
 13  
  *
 14  
  * You should have received a copy of the GNU General Public License along with
 15  
  * dependency-check-core. If not, see http://www.gnu.org/licenses/.
 16  
  *
 17  
  * Copyright (c) 2013 Jeremy Long. All Rights Reserved.
 18  
  */
 19  
 package org.owasp.dependencycheck.data.cpe;
 20  
 
 21  
 import java.io.IOException;
 22  
 import java.sql.ResultSet;
 23  
 import java.sql.SQLException;
 24  
 import java.util.HashMap;
 25  
 import java.util.Map;
 26  
 import java.util.logging.Level;
 27  
 import java.util.logging.Logger;
 28  
 import org.apache.lucene.analysis.Analyzer;
 29  
 import org.apache.lucene.analysis.core.KeywordAnalyzer;
 30  
 import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
 31  
 import org.apache.lucene.document.Document;
 32  
 import org.apache.lucene.document.Field;
 33  
 import org.apache.lucene.document.TextField;
 34  
 import org.apache.lucene.index.CorruptIndexException;
 35  
 import org.apache.lucene.index.DirectoryReader;
 36  
 import org.apache.lucene.index.IndexReader;
 37  
 import org.apache.lucene.index.IndexWriter;
 38  
 import org.apache.lucene.index.IndexWriterConfig;
 39  
 import org.apache.lucene.queryparser.classic.ParseException;
 40  
 import org.apache.lucene.queryparser.classic.QueryParser;
 41  
 import org.apache.lucene.search.IndexSearcher;
 42  
 import org.apache.lucene.search.Query;
 43  
 import org.apache.lucene.search.TopDocs;
 44  
 import org.owasp.dependencycheck.data.lucene.FieldAnalyzer;
 45  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 46  
 import org.apache.lucene.store.RAMDirectory;
 47  
 import org.owasp.dependencycheck.data.lucene.LuceneUtils;
 48  
 import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
 49  
 
 50  
 /**
 51  
  * An in memory lucene index that contains the vendor/product combinations from
 52  
  * the CPE (application) identifiers within the NVD CVE data.
 53  
  *
 54  
  * @author Jeremy Long <jeremy.long@owasp.org>
 55  
  */
 56  
 public final class CpeMemoryIndex {
 57  
 
 58  
     /**
 59  
      * singleton instance.
 60  
      */
 61  1
     private static CpeMemoryIndex instance = new CpeMemoryIndex();
 62  
 
 63  
     /**
 64  
      * private constructor for singleton.
 65  
      */
 66  1
     private CpeMemoryIndex() {
 67  1
     }
 68  
 
 69  
     /**
 70  
      * Gets the singleton instance of the CpeMemoryIndex.
 71  
      *
 72  
      * @return the instance of the CpeMemoryIndex
 73  
      */
 74  
     public static CpeMemoryIndex getInstance() {
 75  14
         return instance;
 76  
     }
 77  
     /**
 78  
      * The in memory Lucene index.
 79  
      */
 80  
     private RAMDirectory index;
 81  
     /**
 82  
      * The Lucene IndexReader.
 83  
      */
 84  
     private IndexReader indexReader;
 85  
     /**
 86  
      * The Lucene IndexSearcher.
 87  
      */
 88  
     private IndexSearcher indexSearcher;
 89  
     /**
 90  
      * The Lucene Analyzer used for Searching.
 91  
      */
 92  
     private Analyzer searchingAnalyzer;
 93  
     /**
 94  
      * The Lucene QueryParser used for Searching.
 95  
      */
 96  
     private QueryParser queryParser;
 97  
     /**
 98  
      * The search field analyzer for the product field.
 99  
      */
 100  
     private SearchFieldAnalyzer productSearchFieldAnalyzer;
 101  
     /**
 102  
      * The search field analyzer for the vendor field.
 103  
      */
 104  
     private SearchFieldAnalyzer vendorSearchFieldAnalyzer;
 105  
 
 106  
     /**
 107  
      * Creates and loads data into an in memory index.
 108  
      *
 109  
      * @param cve the data source to retrieve the cpe data
 110  
      * @throws IndexException thrown if there is an error creating the index
 111  
      */
 112  
     public void open(CveDB cve) throws IndexException {
 113  14
         if (!openState) {
 114  11
             index = new RAMDirectory();
 115  11
             buildIndex(cve);
 116  
             try {
 117  11
                 indexReader = DirectoryReader.open(index);
 118  0
             } catch (IOException ex) {
 119  0
                 throw new IndexException(ex);
 120  11
             }
 121  11
             indexSearcher = new IndexSearcher(indexReader);
 122  11
             searchingAnalyzer = createSearchingAnalyzer();
 123  11
             queryParser = new QueryParser(LuceneUtils.CURRENT_VERSION, Fields.DOCUMENT_KEY, searchingAnalyzer);
 124  11
             openState = true;
 125  
         }
 126  14
     }
 127  
     /**
 128  
      * A flag indicating whether or not the index is open.
 129  
      */
 130  1
     private boolean openState = false;
 131  
 
 132  
     /**
 133  
      * returns whether or not the index is open.
 134  
      *
 135  
      * @return whether or not the index is open
 136  
      */
 137  
     public boolean isOpen() {
 138  0
         return openState;
 139  
     }
 140  
 
 141  
     /**
 142  
      * Creates the indexing analyzer for the CPE Index.
 143  
      *
 144  
      * @return the CPE Analyzer.
 145  
      */
 146  
     @SuppressWarnings("unchecked")
 147  
     private Analyzer createIndexingAnalyzer() {
 148  11
         final Map fieldAnalyzers = new HashMap();
 149  11
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 150  11
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 151  
     }
 152  
 
 153  
     /**
 154  
      * Creates an Analyzer for searching the CPE Index.
 155  
      *
 156  
      * @return the CPE Analyzer.
 157  
      */
 158  
     @SuppressWarnings("unchecked")
 159  
     private Analyzer createSearchingAnalyzer() {
 160  11
         final Map fieldAnalyzers = new HashMap();
 161  11
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 162  11
         productSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 163  11
         vendorSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 164  11
         fieldAnalyzers.put(Fields.PRODUCT, productSearchFieldAnalyzer);
 165  11
         fieldAnalyzers.put(Fields.VENDOR, vendorSearchFieldAnalyzer);
 166  
 
 167  11
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 168  
     }
 169  
 
 170  
     /**
 171  
      * Saves a CPE IndexEntry into the Lucene index.
 172  
      *
 173  
      * @param vendor the vendor to index
 174  
      * @param product the product to index
 175  
      * @param indexWriter the index writer to write the entry into
 176  
      * @throws CorruptIndexException is thrown if the index is corrupt
 177  
      * @throws IOException is thrown if an IOException occurs
 178  
      */
 179  
     public void saveEntry(String vendor, String product, IndexWriter indexWriter) throws CorruptIndexException, IOException {
 180  236203
         final Document doc = new Document();
 181  236203
         final Field v = new TextField(Fields.VENDOR, vendor, Field.Store.YES);
 182  236203
         final Field p = new TextField(Fields.PRODUCT, product, Field.Store.YES);
 183  236203
         doc.add(v);
 184  236203
         doc.add(p);
 185  236203
         indexWriter.addDocument(doc);
 186  236203
     }
 187  
 
 188  
     /**
 189  
      * Closes the CPE Index.
 190  
      */
 191  
     public void close() {
 192  11
         if (searchingAnalyzer != null) {
 193  11
             searchingAnalyzer.close();
 194  11
             searchingAnalyzer = null;
 195  
         }
 196  11
         if (indexReader != null) {
 197  
             try {
 198  11
                 indexReader.close();
 199  0
             } catch (IOException ex) {
 200  0
                 Logger.getLogger(CpeMemoryIndex.class.getName()).log(Level.FINEST, null, ex);
 201  11
             }
 202  11
             indexReader = null;
 203  
         }
 204  11
         queryParser = null;
 205  11
         indexSearcher = null;
 206  11
         if (index != null) {
 207  11
             index.close();
 208  11
             index = null;
 209  
         }
 210  11
         openState = false;
 211  11
     }
 212  
 
 213  
     /**
 214  
      * Builds the lucene index based off of the data within the CveDB.
 215  
      *
 216  
      * @param cve the data base containing the CPE data
 217  
      * @throws IndexException thrown if there is an issue creating the index
 218  
      */
 219  
     private void buildIndex(CveDB cve) throws IndexException {
 220  11
         Analyzer analyzer = null;
 221  11
         IndexWriter indexWriter = null;
 222  
         try {
 223  11
             analyzer = createIndexingAnalyzer();
 224  11
             final IndexWriterConfig conf = new IndexWriterConfig(LuceneUtils.CURRENT_VERSION, analyzer);
 225  11
             indexWriter = new IndexWriter(index, conf);
 226  11
             final ResultSet rs = cve.getVendorProductList();
 227  11
             if (rs == null) {
 228  0
                 throw new IndexException("No data exists");
 229  
             }
 230  
             try {
 231  236214
                 while (rs.next()) {
 232  236203
                     saveEntry(rs.getString(1), rs.getString(2), indexWriter);
 233  
                 }
 234  0
             } catch (SQLException ex) {
 235  0
                 Logger.getLogger(CpeMemoryIndex.class.getName()).log(Level.FINE, null, ex);
 236  0
                 throw new IndexException("Error reading CPE data", ex);
 237  11
             }
 238  0
         } catch (CorruptIndexException ex) {
 239  0
             throw new IndexException("Unable to close an in-memory index", ex);
 240  0
         } catch (IOException ex) {
 241  0
             throw new IndexException("Unable to close an in-memory index", ex);
 242  
         } finally {
 243  11
             if (indexWriter != null) {
 244  
                 try {
 245  
                     try {
 246  11
                         indexWriter.commit();
 247  
                     } finally {
 248  11
                         indexWriter.close(true);
 249  11
                     }
 250  0
                 } catch (CorruptIndexException ex) {
 251  0
                     throw new IndexException("Unable to close an in-memory index", ex);
 252  0
                 } catch (IOException ex) {
 253  0
                     throw new IndexException("Unable to close an in-memory index", ex);
 254  11
                 }
 255  11
                 if (analyzer != null) {
 256  11
                     analyzer.close();
 257  
                 }
 258  
             }
 259  
         }
 260  11
     }
 261  
 
 262  
     /**
 263  
      * Resets the searching analyzers
 264  
      */
 265  
     private void resetSearchingAnalyzer() {
 266  0
         if (productSearchFieldAnalyzer != null) {
 267  0
             productSearchFieldAnalyzer.clear();
 268  
         }
 269  0
         if (vendorSearchFieldAnalyzer != null) {
 270  0
             vendorSearchFieldAnalyzer.clear();
 271  
         }
 272  0
     }
 273  
 
 274  
     /**
 275  
      * Searches the index using the given search string.
 276  
      *
 277  
      * @param searchString the query text
 278  
      * @param maxQueryResults the maximum number of documents to return
 279  
      * @return the TopDocs found by the search
 280  
      * @throws ParseException thrown when the searchString is invalid
 281  
      * @throws IOException is thrown if there is an issue with the underlying
 282  
      * Index
 283  
      */
 284  
     public TopDocs search(String searchString, int maxQueryResults) throws ParseException, IOException {
 285  73
         if (searchString == null || searchString.trim().isEmpty()) {
 286  0
             throw new ParseException("Query is null or empty");
 287  
         }
 288  73
         final Query query = queryParser.parse(searchString);
 289  73
         return indexSearcher.search(query, maxQueryResults);
 290  
     }
 291  
 
 292  
     /**
 293  
      * Searches the index using the given query.
 294  
      *
 295  
      * @param query the query used to search the index
 296  
      * @param maxQueryResults the max number of results to return
 297  
      * @return the TopDocs found be the query
 298  
      * @throws CorruptIndexException thrown if the Index is corrupt
 299  
      * @throws IOException thrown if there is an IOException
 300  
      */
 301  
     public TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException {
 302  0
         resetSearchingAnalyzer();
 303  0
         return indexSearcher.search(query, maxQueryResults);
 304  
     }
 305  
 
 306  
     /**
 307  
      * Retrieves a document from the Index.
 308  
      *
 309  
      * @param documentId the id of the document to retrieve
 310  
      * @return the Document
 311  
      * @throws IOException thrown if there is an IOException
 312  
      */
 313  
     public Document getDocument(int documentId) throws IOException {
 314  750
         return indexSearcher.doc(documentId);
 315  
     }
 316  
 
 317  
     /**
 318  
      * Returns the number of CPE entries stored in the index.
 319  
      *
 320  
      * @return the number of CPE entries stored in the index
 321  
      */
 322  
     public int numDocs() {
 323  3
         if (indexReader == null) {
 324  0
             return -1;
 325  
         }
 326  3
         return indexReader.numDocs();
 327  
     }
 328  
 }