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