Coverage Report - org.owasp.dependencycheck.data.cpe.CpeMemoryIndex
 
Classes in this File Line Coverage Branch Coverage Complexity
CpeMemoryIndex
79%
79/99
50%
12/24
3.077
 
 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 org.apache.lucene.analysis.Analyzer;
 25  
 import org.apache.lucene.analysis.core.KeywordAnalyzer;
 26  
 import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
 27  
 import org.apache.lucene.document.Document;
 28  
 import org.apache.lucene.document.Field;
 29  
 import org.apache.lucene.document.TextField;
 30  
 import org.apache.lucene.index.CorruptIndexException;
 31  
 import org.apache.lucene.index.DirectoryReader;
 32  
 import org.apache.lucene.index.IndexReader;
 33  
 import org.apache.lucene.index.IndexWriter;
 34  
 import org.apache.lucene.index.IndexWriterConfig;
 35  
 import org.apache.lucene.queryparser.classic.ParseException;
 36  
 import org.apache.lucene.queryparser.classic.QueryParser;
 37  
 import org.apache.lucene.search.IndexSearcher;
 38  
 import org.apache.lucene.search.Query;
 39  
 import org.apache.lucene.search.TopDocs;
 40  
 import org.apache.lucene.store.RAMDirectory;
 41  
 import org.owasp.dependencycheck.data.lucene.FieldAnalyzer;
 42  
 import org.owasp.dependencycheck.data.lucene.LuceneUtils;
 43  
 import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
 44  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 45  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 46  
 import org.owasp.dependencycheck.utils.Pair;
 47  
 import org.slf4j.Logger;
 48  
 import org.slf4j.LoggerFactory;
 49  
 
 50  
 /**
 51  
  * An in memory lucene index that contains the vendor/product combinations from the CPE (application) identifiers within the NVD
 52  
  * CVE data.
 53  
  *
 54  
  * @author Jeremy Long
 55  
  */
 56  
 public final class CpeMemoryIndex {
 57  
 
 58  
     /**
 59  
      * The logger.
 60  
      */
 61  1
     private static final Logger LOGGER = LoggerFactory.getLogger(CpeMemoryIndex.class);
 62  
     /**
 63  
      * singleton instance.
 64  
      */
 65  1
     private static final CpeMemoryIndex INSTANCE = new CpeMemoryIndex();
 66  
 
 67  
     /**
 68  
      * private constructor for singleton.
 69  
      */
 70  1
     private CpeMemoryIndex() {
 71  1
     }
 72  
 
 73  
     /**
 74  
      * Gets the singleton instance of the CpeMemoryIndex.
 75  
      *
 76  
      * @return the instance of the CpeMemoryIndex
 77  
      */
 78  
     public static CpeMemoryIndex getInstance() {
 79  1
         return INSTANCE;
 80  
     }
 81  
     /**
 82  
      * The in memory Lucene index.
 83  
      */
 84  
     private RAMDirectory index;
 85  
     /**
 86  
      * The Lucene IndexReader.
 87  
      */
 88  
     private IndexReader indexReader;
 89  
     /**
 90  
      * The Lucene IndexSearcher.
 91  
      */
 92  
     private IndexSearcher indexSearcher;
 93  
     /**
 94  
      * The Lucene Analyzer used for Searching.
 95  
      */
 96  
     private Analyzer searchingAnalyzer;
 97  
     /**
 98  
      * The Lucene QueryParser used for Searching.
 99  
      */
 100  
     private QueryParser queryParser;
 101  
     /**
 102  
      * The search field analyzer for the product field.
 103  
      */
 104  
     private SearchFieldAnalyzer productSearchFieldAnalyzer;
 105  
     /**
 106  
      * The search field analyzer for the vendor field.
 107  
      */
 108  
     private SearchFieldAnalyzer vendorSearchFieldAnalyzer;
 109  
 
 110  
     /**
 111  
      * Creates and loads data into an in memory index.
 112  
      *
 113  
      * @param cve the data source to retrieve the cpe data
 114  
      * @throws IndexException thrown if there is an error creating the index
 115  
      */
 116  
     public void open(CveDB cve) throws IndexException {
 117  1
         synchronized (INSTANCE) {
 118  1
             if (!openState) {
 119  1
                 index = new RAMDirectory();
 120  1
                 buildIndex(cve);
 121  
                 try {
 122  1
                     indexReader = DirectoryReader.open(index);
 123  0
                 } catch (IOException ex) {
 124  0
                     throw new IndexException(ex);
 125  1
                 }
 126  1
                 indexSearcher = new IndexSearcher(indexReader);
 127  1
                 searchingAnalyzer = createSearchingAnalyzer();
 128  1
                 queryParser = new QueryParser(LuceneUtils.CURRENT_VERSION, Fields.DOCUMENT_KEY, searchingAnalyzer);
 129  1
                 openState = true;
 130  
             }
 131  1
         }
 132  1
     }
 133  
     /**
 134  
      * A flag indicating whether or not the index is open.
 135  
      */
 136  1
     private boolean openState = false;
 137  
 
 138  
     /**
 139  
      * returns whether or not the index is open.
 140  
      *
 141  
      * @return whether or not the index is open
 142  
      */
 143  
     public boolean isOpen() {
 144  0
         return openState;
 145  
     }
 146  
 
 147  
     /**
 148  
      * Creates the indexing analyzer for the CPE Index.
 149  
      *
 150  
      * @return the CPE Analyzer.
 151  
      */
 152  
     private Analyzer createIndexingAnalyzer() {
 153  1
         final Map<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>();
 154  1
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 155  1
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 156  
     }
 157  
 
 158  
     /**
 159  
      * Creates an Analyzer for searching the CPE Index.
 160  
      *
 161  
      * @return the CPE Analyzer.
 162  
      */
 163  
     private Analyzer createSearchingAnalyzer() {
 164  1
         final Map<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>();
 165  1
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 166  1
         productSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 167  1
         vendorSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 168  1
         fieldAnalyzers.put(Fields.PRODUCT, productSearchFieldAnalyzer);
 169  1
         fieldAnalyzers.put(Fields.VENDOR, vendorSearchFieldAnalyzer);
 170  
 
 171  1
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 172  
     }
 173  
 
 174  
     /**
 175  
      * Closes the CPE Index.
 176  
      */
 177  
     public void close() {
 178  1
         if (searchingAnalyzer != null) {
 179  1
             searchingAnalyzer.close();
 180  1
             searchingAnalyzer = null;
 181  
         }
 182  1
         if (indexReader != null) {
 183  
             try {
 184  1
                 indexReader.close();
 185  0
             } catch (IOException ex) {
 186  0
                 LOGGER.trace("", ex);
 187  1
             }
 188  1
             indexReader = null;
 189  
         }
 190  1
         queryParser = null;
 191  1
         indexSearcher = null;
 192  1
         if (index != null) {
 193  1
             index.close();
 194  1
             index = null;
 195  
         }
 196  1
         openState = false;
 197  1
     }
 198  
 
 199  
     /**
 200  
      * Builds the CPE Lucene Index based off of the data within the CveDB.
 201  
      *
 202  
      * @param cve the data base containing the CPE data
 203  
      * @throws IndexException thrown if there is an issue creating the index
 204  
      */
 205  
     private void buildIndex(CveDB cve) throws IndexException {
 206  1
         Analyzer analyzer = null;
 207  1
         IndexWriter indexWriter = null;
 208  
         try {
 209  1
             analyzer = createIndexingAnalyzer();
 210  1
             final IndexWriterConfig conf = new IndexWriterConfig(LuceneUtils.CURRENT_VERSION, analyzer);
 211  1
             indexWriter = new IndexWriter(index, conf);
 212  
             try {
 213  
                 // Tip: reuse the Document and Fields for performance...
 214  
                 // See "Re-use Document and Field instances" from
 215  
                 // http://wiki.apache.org/lucene-java/ImproveIndexingSpeed
 216  1
                 final Document doc = new Document();
 217  1
                 final Field v = new TextField(Fields.VENDOR, Fields.VENDOR, Field.Store.YES);
 218  1
                 final Field p = new TextField(Fields.PRODUCT, Fields.PRODUCT, Field.Store.YES);
 219  1
                 doc.add(v);
 220  1
                 doc.add(p);
 221  
 
 222  1
                 final Set<Pair<String, String>> data = cve.getVendorProductList();
 223  1
                 for (Pair<String, String> pair : data) {
 224  22136
                     v.setStringValue(pair.getLeft());
 225  22136
                     p.setStringValue(pair.getRight());
 226  22136
                     indexWriter.addDocument(doc);
 227  22136
                 }
 228  0
             } catch (DatabaseException ex) {
 229  0
                 LOGGER.debug("", ex);
 230  0
                 throw new IndexException("Error reading CPE data", ex);
 231  1
             }
 232  0
         } catch (CorruptIndexException ex) {
 233  0
             throw new IndexException("Unable to close an in-memory index", ex);
 234  0
         } catch (IOException ex) {
 235  0
             throw new IndexException("Unable to close an in-memory index", ex);
 236  
         } finally {
 237  1
             if (indexWriter != null) {
 238  
                 try {
 239  
                     try {
 240  1
                         indexWriter.commit();
 241  
                     } finally {
 242  1
                         indexWriter.close(true);
 243  1
                     }
 244  0
                 } catch (CorruptIndexException ex) {
 245  0
                     throw new IndexException("Unable to close an in-memory index", ex);
 246  0
                 } catch (IOException ex) {
 247  0
                     throw new IndexException("Unable to close an in-memory index", ex);
 248  1
                 }
 249  1
                 if (analyzer != null) {
 250  1
                     analyzer.close();
 251  
                 }
 252  
             }
 253  
         }
 254  1
     }
 255  
 
 256  
     /**
 257  
      * Resets the searching analyzers
 258  
      */
 259  
     private void resetSearchingAnalyzer() {
 260  6
         if (productSearchFieldAnalyzer != null) {
 261  6
             productSearchFieldAnalyzer.clear();
 262  
         }
 263  6
         if (vendorSearchFieldAnalyzer != null) {
 264  6
             vendorSearchFieldAnalyzer.clear();
 265  
         }
 266  6
     }
 267  
 
 268  
     /**
 269  
      * Searches the index using the given search string.
 270  
      *
 271  
      * @param searchString the query text
 272  
      * @param maxQueryResults the maximum number of documents to return
 273  
      * @return the TopDocs found by the search
 274  
      * @throws ParseException thrown when the searchString is invalid
 275  
      * @throws IOException is thrown if there is an issue with the underlying Index
 276  
      */
 277  
     public TopDocs search(String searchString, int maxQueryResults) throws ParseException, IOException {
 278  6
         if (searchString == null || searchString.trim().isEmpty()) {
 279  0
             throw new ParseException("Query is null or empty");
 280  
         }
 281  6
         LOGGER.debug(searchString);
 282  6
         final Query query = queryParser.parse(searchString);
 283  6
         return search(query, maxQueryResults);
 284  
     }
 285  
 
 286  
     /**
 287  
      * Searches the index using the given query.
 288  
      *
 289  
      * @param query the query used to search the index
 290  
      * @param maxQueryResults the max number of results to return
 291  
      * @return the TopDocs found be the query
 292  
      * @throws CorruptIndexException thrown if the Index is corrupt
 293  
      * @throws IOException thrown if there is an IOException
 294  
      */
 295  
     public TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException {
 296  6
         resetSearchingAnalyzer();
 297  6
         return indexSearcher.search(query, maxQueryResults);
 298  
     }
 299  
 
 300  
     /**
 301  
      * Retrieves a document from the Index.
 302  
      *
 303  
      * @param documentId the id of the document to retrieve
 304  
      * @return the Document
 305  
      * @throws IOException thrown if there is an IOException
 306  
      */
 307  
     public Document getDocument(int documentId) throws IOException {
 308  23
         return indexSearcher.doc(documentId);
 309  
     }
 310  
 
 311  
     /**
 312  
      * Returns the number of CPE entries stored in the index.
 313  
      *
 314  
      * @return the number of CPE entries stored in the index
 315  
      */
 316  
     public int numDocs() {
 317  0
         if (indexReader == null) {
 318  0
             return -1;
 319  
         }
 320  0
         return indexReader.numDocs();
 321  
     }
 322  
 }