Coverage Report - org.owasp.dependencycheck.data.cpe.CpeMemoryIndex
 
Classes in this File Line Coverage Branch Coverage Complexity
CpeMemoryIndex
73%
68/92
42%
12/28
2.929
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2013 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.cpe;
 19  
 
 20  
 import java.io.IOException;
 21  
 import java.util.HashMap;
 22  
 import java.util.Map;
 23  
 import java.util.Set;
 24  
 import java.util.logging.Level;
 25  
 import java.util.logging.Logger;
 26  
 import org.apache.lucene.analysis.Analyzer;
 27  
 import org.apache.lucene.analysis.core.KeywordAnalyzer;
 28  
 import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
 29  
 import org.apache.lucene.document.Document;
 30  
 import org.apache.lucene.document.Field;
 31  
 import org.apache.lucene.document.TextField;
 32  
 import org.apache.lucene.index.CorruptIndexException;
 33  
 import org.apache.lucene.index.DirectoryReader;
 34  
 import org.apache.lucene.index.IndexReader;
 35  
 import org.apache.lucene.index.IndexWriter;
 36  
 import org.apache.lucene.index.IndexWriterConfig;
 37  
 import org.apache.lucene.queryparser.classic.ParseException;
 38  
 import org.apache.lucene.queryparser.classic.QueryParser;
 39  
 import org.apache.lucene.search.IndexSearcher;
 40  
 import org.apache.lucene.search.Query;
 41  
 import org.apache.lucene.search.TopDocs;
 42  
 import org.apache.lucene.store.RAMDirectory;
 43  
 import org.owasp.dependencycheck.data.lucene.FieldAnalyzer;
 44  
 import org.owasp.dependencycheck.data.lucene.LuceneUtils;
 45  
 import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
 46  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 47  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 48  
 import org.owasp.dependencycheck.utils.Pair;
 49  
 
 50  
 /**
 51  
  * An in memory lucene index that contains the vendor/product combinations from the CPE (application) identifiers within
 52  
  * the NVD CVE data.
 53  
  *
 54  
  * @author Jeremy Long <jeremy.long@owasp.org>
 55  
  */
 56  
 public final class CpeMemoryIndex {
 57  
     /**
 58  
      * The logger.
 59  
      */
 60  4
     private static final Logger LOGGER = Logger.getLogger(CpeMemoryIndex.class.getName());
 61  
     /**
 62  
      * singleton instance.
 63  
      */
 64  4
     private static CpeMemoryIndex instance = new CpeMemoryIndex();
 65  
 
 66  
     /**
 67  
      * private constructor for singleton.
 68  
      */
 69  
     private CpeMemoryIndex() {
 70  
     }
 71  
 
 72  
     /**
 73  
      * Gets the singleton instance of the CpeMemoryIndex.
 74  
      *
 75  
      * @return the instance of the CpeMemoryIndex
 76  
      */
 77  
     public static CpeMemoryIndex getInstance() {
 78  8
         return instance;
 79  
     }
 80  
     /**
 81  
      * The in memory Lucene index.
 82  
      */
 83  
     private RAMDirectory index;
 84  
     /**
 85  
      * The Lucene IndexReader.
 86  
      */
 87  
     private IndexReader indexReader;
 88  
     /**
 89  
      * The Lucene IndexSearcher.
 90  
      */
 91  
     private IndexSearcher indexSearcher;
 92  
     /**
 93  
      * The Lucene Analyzer used for Searching.
 94  
      */
 95  
     private Analyzer searchingAnalyzer;
 96  
     /**
 97  
      * The Lucene QueryParser used for Searching.
 98  
      */
 99  
     private QueryParser queryParser;
 100  
     /**
 101  
      * The search field analyzer for the product field.
 102  
      */
 103  
     private SearchFieldAnalyzer productSearchFieldAnalyzer;
 104  
     /**
 105  
      * The search field analyzer for the vendor field.
 106  
      */
 107  
     private SearchFieldAnalyzer vendorSearchFieldAnalyzer;
 108  
 
 109  
     /**
 110  
      * Creates and loads data into an in memory index.
 111  
      *
 112  
      * @param cve the data source to retrieve the cpe data
 113  
      * @throws IndexException thrown if there is an error creating the index
 114  
      */
 115  
     public void open(CveDB cve) throws IndexException {
 116  8
         if (!openState) {
 117  4
             index = new RAMDirectory();
 118  4
             buildIndex(cve);
 119  
             try {
 120  4
                 indexReader = DirectoryReader.open(index);
 121  0
             } catch (IOException ex) {
 122  0
                 throw new IndexException(ex);
 123  4
             }
 124  4
             indexSearcher = new IndexSearcher(indexReader);
 125  4
             searchingAnalyzer = createSearchingAnalyzer();
 126  4
             queryParser = new QueryParser(LuceneUtils.CURRENT_VERSION, Fields.DOCUMENT_KEY, searchingAnalyzer);
 127  4
             openState = true;
 128  
         }
 129  8
     }
 130  
     /**
 131  
      * A flag indicating whether or not the index is open.
 132  
      */
 133  
     private boolean openState = false;
 134  
 
 135  
     /**
 136  
      * returns whether or not the index is open.
 137  
      *
 138  
      * @return whether or not the index is open
 139  
      */
 140  
     public boolean isOpen() {
 141  
         return openState;
 142  
     }
 143  
 
 144  
     /**
 145  
      * Creates the indexing analyzer for the CPE Index.
 146  
      *
 147  
      * @return the CPE Analyzer.
 148  
      */
 149  
     @SuppressWarnings("unchecked")
 150  
     private Analyzer createIndexingAnalyzer() {
 151  4
         final Map fieldAnalyzers = new HashMap();
 152  4
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 153  4
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 154  
     }
 155  
 
 156  
     /**
 157  
      * Creates an Analyzer for searching the CPE Index.
 158  
      *
 159  
      * @return the CPE Analyzer.
 160  
      */
 161  
     @SuppressWarnings("unchecked")
 162  
     private Analyzer createSearchingAnalyzer() {
 163  4
         final Map fieldAnalyzers = new HashMap();
 164  4
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 165  4
         productSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 166  4
         vendorSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 167  4
         fieldAnalyzers.put(Fields.PRODUCT, productSearchFieldAnalyzer);
 168  4
         fieldAnalyzers.put(Fields.VENDOR, vendorSearchFieldAnalyzer);
 169  
 
 170  4
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 171  
     }
 172  
 
 173  
     /**
 174  
      * Saves a CPE IndexEntry into the Lucene index.
 175  
      *
 176  
      * @param vendor the vendor to index
 177  
      * @param product the product to index
 178  
      * @param indexWriter the index writer to write the entry into
 179  
      * @throws CorruptIndexException is thrown if the index is corrupt
 180  
      * @throws IOException is thrown if an IOException occurs
 181  
      */
 182  
     public void saveEntry(String vendor, String product, IndexWriter indexWriter) throws CorruptIndexException, IOException {
 183  88708
         final Document doc = new Document();
 184  88708
         final Field v = new TextField(Fields.VENDOR, vendor, Field.Store.YES);
 185  88708
         final Field p = new TextField(Fields.PRODUCT, product, Field.Store.YES);
 186  88708
         doc.add(v);
 187  88708
         doc.add(p);
 188  88708
         indexWriter.addDocument(doc);
 189  88708
     }
 190  
 
 191  
     /**
 192  
      * Closes the CPE Index.
 193  
      */
 194  
     public void close() {
 195  4
         if (searchingAnalyzer != null) {
 196  4
             searchingAnalyzer.close();
 197  4
             searchingAnalyzer = null;
 198  
         }
 199  4
         if (indexReader != null) {
 200  
             try {
 201  4
                 indexReader.close();
 202  0
             } catch (IOException ex) {
 203  0
                 LOGGER.log(Level.FINEST, null, ex);
 204  4
             }
 205  4
             indexReader = null;
 206  
         }
 207  4
         queryParser = null;
 208  4
         indexSearcher = null;
 209  4
         if (index != null) {
 210  4
             index.close();
 211  4
             index = null;
 212  
         }
 213  4
         openState = false;
 214  4
     }
 215  
 
 216  
     /**
 217  
      * Builds the CPE Lucene Index based off of the data within the CveDB.
 218  
      *
 219  
      * @param cve the data base containing the CPE data
 220  
      * @throws IndexException thrown if there is an issue creating the index
 221  
      */
 222  
     private void buildIndex(CveDB cve) throws IndexException {
 223  4
         Analyzer analyzer = null;
 224  4
         IndexWriter indexWriter = null;
 225  
         try {
 226  4
             analyzer = createIndexingAnalyzer();
 227  4
             final IndexWriterConfig conf = new IndexWriterConfig(LuceneUtils.CURRENT_VERSION, analyzer);
 228  4
             indexWriter = new IndexWriter(index, conf);
 229  
             try {
 230  4
                 final Set<Pair<String, String>> data = cve.getVendorProductList();
 231  4
                 for (Pair<String, String> pair : data) {
 232  88708
                     saveEntry(pair.getLeft(), pair.getRight(), indexWriter);
 233  88708
                 }
 234  0
             } catch (DatabaseException ex) {
 235  0
                 LOGGER.log(Level.FINE, null, ex);
 236  0
                 throw new IndexException("Error reading CPE data", ex);
 237  4
             }
 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  4
             if (indexWriter != null) {
 244  
                 try {
 245  
                     try {
 246  4
                         indexWriter.commit();
 247  
                     } finally {
 248  4
                         indexWriter.close(true);
 249  4
                     }
 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  4
                 }
 255  4
                 if (analyzer != null) {
 256  4
                     analyzer.close();
 257  
                 }
 258  
             }
 259  
         }
 260  4
     }
 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 Index
 282  
      */
 283  
     public TopDocs search(String searchString, int maxQueryResults) throws ParseException, IOException {
 284  32
         if (searchString == null || searchString.trim().isEmpty()) {
 285  0
             throw new ParseException("Query is null or empty");
 286  
         }
 287  32
         final Query query = queryParser.parse(searchString);
 288  32
         return indexSearcher.search(query, maxQueryResults);
 289  
     }
 290  
 
 291  
     /**
 292  
      * Searches the index using the given query.
 293  
      *
 294  
      * @param query the query used to search the index
 295  
      * @param maxQueryResults the max number of results to return
 296  
      * @return the TopDocs found be the query
 297  
      * @throws CorruptIndexException thrown if the Index is corrupt
 298  
      * @throws IOException thrown if there is an IOException
 299  
      */
 300  
     public TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException {
 301  0
         resetSearchingAnalyzer();
 302  0
         return indexSearcher.search(query, maxQueryResults);
 303  
     }
 304  
 
 305  
     /**
 306  
      * Retrieves a document from the Index.
 307  
      *
 308  
      * @param documentId the id of the document to retrieve
 309  
      * @return the Document
 310  
      * @throws IOException thrown if there is an IOException
 311  
      */
 312  
     public Document getDocument(int documentId) throws IOException {
 313  216
         return indexSearcher.doc(documentId);
 314  
     }
 315  
 
 316  
     /**
 317  
      * Returns the number of CPE entries stored in the index.
 318  
      *
 319  
      * @return the number of CPE entries stored in the index
 320  
      */
 321  
     public int numDocs() {
 322  4
         if (indexReader == null) {
 323  0
             return -1;
 324  
         }
 325  4
         return indexReader.numDocs();
 326  
     }
 327  
 }