idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
11,500
@ SuppressWarnings ( "ReferenceEquality" ) public synchronized void addRelatedDependency ( Dependency dependency ) { if ( this == dependency ) { LOGGER . warn ( "Attempted to add a circular reference - please post the log file to issue #172 here " + "https://github.com/jeremylong/DependencyCheck/issues/172" ) ; LOGGER . debug ( "this: {}" , this ) ; LOGGER . debug ( "dependency: {}" , dependency ) ; } else if ( ! relatedDependencies . add ( dependency ) ) { LOGGER . debug ( "Failed to add dependency, likely due to referencing the same file as another dependency in the set." ) ; LOGGER . debug ( "this: {}" , this ) ; LOGGER . debug ( "dependency: {}" , dependency ) ; } }
Adds a related dependency .
11,501
protected void analyzeDependency ( Dependency dependency , Engine engine ) throws AnalysisException { final CveDB cveDB = engine . getDatabase ( ) ; try { dependency . getVulnerableSoftwareIdentifiers ( ) . stream ( ) . filter ( ( i ) -> ( i instanceof CpeIdentifier ) ) . map ( i -> ( CpeIdentifier ) i ) . forEach ( i -> { try { final List < Vulnerability > vulns = cveDB . getVulnerabilities ( i . getCpe ( ) ) ; dependency . addVulnerabilities ( vulns ) ; } catch ( DatabaseException ex ) { throw new LambdaExceptionWrapper ( new AnalysisException ( ex ) ) ; } } ) ; dependency . getSuppressedIdentifiers ( ) . stream ( ) . filter ( ( i ) -> ( i instanceof CpeIdentifier ) ) . map ( i -> ( CpeIdentifier ) i ) . forEach ( i -> { try { final List < Vulnerability > vulns = cveDB . getVulnerabilities ( i . getCpe ( ) ) ; dependency . addSuppressedVulnerabilities ( vulns ) ; } catch ( DatabaseException ex ) { throw new LambdaExceptionWrapper ( new AnalysisException ( ex ) ) ; } } ) ; } catch ( LambdaExceptionWrapper ex ) { throw ( AnalysisException ) ex . getCause ( ) ; } }
Analyzes a dependency and attempts to determine if there are any CPE identifiers for this dependency .
11,502
private int runScan ( String reportDirectory , String outputFormat , String applicationName , String [ ] files , String [ ] excludes , int symLinkDepth , int cvssFailScore ) throws DatabaseException , ExceptionCollection , ReportException { Engine engine = null ; try { final List < String > antStylePaths = getPaths ( files ) ; final Set < File > paths = scanAntStylePaths ( antStylePaths , symLinkDepth , excludes ) ; engine = new Engine ( settings ) ; engine . scan ( paths ) ; ExceptionCollection exCol = null ; try { engine . analyzeDependencies ( ) ; } catch ( ExceptionCollection ex ) { if ( ex . isFatal ( ) ) { throw ex ; } exCol = ex ; } try { engine . writeReports ( applicationName , new File ( reportDirectory ) , outputFormat ) ; } catch ( ReportException ex ) { if ( exCol != null ) { exCol . addException ( ex ) ; throw exCol ; } else { throw ex ; } } if ( exCol != null && ! exCol . getExceptions ( ) . isEmpty ( ) ) { throw exCol ; } return determineReturnCode ( engine , cvssFailScore ) ; } finally { if ( engine != null ) { engine . close ( ) ; } } }
Scans the specified directories and writes the dependency reports to the reportDirectory .
11,503
private int determineReturnCode ( Engine engine , int cvssFailScore ) { int retCode = 0 ; for ( Dependency dep : engine . getDependencies ( ) ) { if ( ! dep . getVulnerabilities ( ) . isEmpty ( ) ) { for ( Vulnerability vuln : dep . getVulnerabilities ( ) ) { LOGGER . debug ( "VULNERABILITY FOUND {}" , dep . getDisplayFileName ( ) ) ; if ( ( vuln . getCvssV2 ( ) != null && vuln . getCvssV2 ( ) . getScore ( ) > cvssFailScore ) || ( vuln . getCvssV3 ( ) != null && vuln . getCvssV3 ( ) . getBaseScore ( ) > cvssFailScore ) ) { retCode = 1 ; } } } } return retCode ; }
Determines the return code based on if one of the dependencies scanned has a vulnerability with a CVSS score above the cvssFailScore .
11,504
private Set < File > scanAntStylePaths ( List < String > antStylePaths , int symLinkDepth , String [ ] excludes ) { final Set < File > paths = new HashSet < > ( ) ; for ( String file : antStylePaths ) { LOGGER . debug ( "Scanning {}" , file ) ; final DirectoryScanner scanner = new DirectoryScanner ( ) ; String include = file . replace ( '\\' , '/' ) ; final File baseDir ; final int pos = getLastFileSeparator ( include ) ; final String tmpBase = include . substring ( 0 , pos ) ; final String tmpInclude = include . substring ( pos + 1 ) ; if ( tmpInclude . indexOf ( '*' ) >= 0 || tmpInclude . indexOf ( '?' ) >= 0 || new File ( include ) . isFile ( ) ) { baseDir = new File ( tmpBase ) ; include = tmpInclude ; } else { baseDir = new File ( tmpBase , tmpInclude ) ; include = "**/*" ; } scanner . setBasedir ( baseDir ) ; final String [ ] includes = { include } ; scanner . setIncludes ( includes ) ; scanner . setMaxLevelsOfSymlinks ( symLinkDepth ) ; if ( symLinkDepth <= 0 ) { scanner . setFollowSymlinks ( false ) ; } if ( excludes != null && excludes . length > 0 ) { scanner . addExcludes ( excludes ) ; } scanner . scan ( ) ; if ( scanner . getIncludedFilesCount ( ) > 0 ) { for ( String s : scanner . getIncludedFiles ( ) ) { final File f = new File ( baseDir , s ) ; LOGGER . debug ( "Found file {}" , f . toString ( ) ) ; paths . add ( f ) ; } } } return paths ; }
Scans the give Ant Style paths and collects the actual files .
11,505
private List < String > getPaths ( String [ ] files ) { final List < String > antStylePaths = new ArrayList < > ( ) ; for ( String file : files ) { final String antPath = ensureCanonicalPath ( file ) ; antStylePaths . add ( antPath ) ; } return antStylePaths ; }
Determines the ant style paths from the given array of files .
11,506
private void prepareLogger ( String verboseLog ) { final StaticLoggerBinder loggerBinder = StaticLoggerBinder . getSingleton ( ) ; final LoggerContext context = ( LoggerContext ) loggerBinder . getLoggerFactory ( ) ; final PatternLayoutEncoder encoder = new PatternLayoutEncoder ( ) ; encoder . setPattern ( "%d %C:%L%n%-5level - %msg%n" ) ; encoder . setContext ( context ) ; encoder . start ( ) ; final FileAppender < ILoggingEvent > fa = new FileAppender < > ( ) ; fa . setAppend ( true ) ; fa . setEncoder ( encoder ) ; fa . setContext ( context ) ; fa . setFile ( verboseLog ) ; final File f = new File ( verboseLog ) ; String name = f . getName ( ) ; final int i = name . lastIndexOf ( '.' ) ; if ( i > 1 ) { name = name . substring ( 0 , i ) ; } fa . setName ( name ) ; fa . start ( ) ; final ch . qos . logback . classic . Logger rootLogger = context . getLogger ( ch . qos . logback . classic . Logger . ROOT_LOGGER_NAME ) ; rootLogger . setLevel ( Level . DEBUG ) ; final ThresholdFilter filter = new ThresholdFilter ( ) ; filter . setLevel ( LogLevel . INFO . getValue ( ) ) ; filter . setContext ( context ) ; filter . start ( ) ; rootLogger . iteratorForAppenders ( ) . forEachRemaining ( action -> { action . addFilter ( filter ) ; } ) ; rootLogger . addAppender ( fa ) ; }
Creates a file appender and adds it to logback .
11,507
private int getLastFileSeparator ( String file ) { if ( file . contains ( "*" ) || file . contains ( "?" ) ) { int p1 = file . indexOf ( '*' ) ; int p2 = file . indexOf ( '?' ) ; p1 = p1 > 0 ? p1 : file . length ( ) ; p2 = p2 > 0 ? p2 : file . length ( ) ; int pos = p1 < p2 ? p1 : p2 ; pos = file . lastIndexOf ( '/' , pos ) ; return pos ; } else { return file . lastIndexOf ( '/' ) ; } }
Returns the position of the last file separator .
11,508
public static File createTempDirectory ( final File base ) throws IOException { final File tempDir = new File ( base , "dctemp" + UUID . randomUUID ( ) . toString ( ) ) ; if ( tempDir . exists ( ) ) { return createTempDirectory ( base ) ; } if ( ! tempDir . mkdirs ( ) ) { throw new IOException ( "Could not create temp directory `" + tempDir . getAbsolutePath ( ) + "`" ) ; } LOGGER . debug ( "Temporary directory is `{}`" , tempDir . getAbsolutePath ( ) ) ; return tempDir ; }
Creates a unique temporary directory in the given directory .
11,509
public static File getResourceAsFile ( final String resource ) { final ClassLoader classLoader = FileUtils . class . getClassLoader ( ) ; final String path = classLoader != null ? classLoader . getResource ( resource ) . getFile ( ) : ClassLoader . getSystemResource ( resource ) . getFile ( ) ; if ( path == null ) { return new File ( resource ) ; } return new File ( path ) ; }
Returns a File object for the given resource . The resource is attempted to be loaded from the class loader .
11,510
private void initialize ( final String propertiesFilePath ) { props = new Properties ( ) ; try ( InputStream in = FileUtils . getResourceAsStream ( propertiesFilePath ) ) { props . load ( in ) ; } catch ( NullPointerException ex ) { LOGGER . error ( "Did not find settings file '{}'." , propertiesFilePath ) ; LOGGER . debug ( "" , ex ) ; } catch ( IOException ex ) { LOGGER . error ( "Unable to load settings from '{}'." , propertiesFilePath ) ; LOGGER . debug ( "" , ex ) ; } logProperties ( "Properties loaded" , props ) ; }
Initializes the settings object from the given file .
11,511
public synchronized void cleanup ( boolean deleteTemporary ) { if ( deleteTemporary && tempDirectory != null && tempDirectory . exists ( ) ) { LOGGER . debug ( "Deleting ALL temporary files from `{}`" , tempDirectory . toString ( ) ) ; FileUtils . delete ( tempDirectory ) ; tempDirectory = null ; } }
Cleans up resources to prevent memory leaks .
11,512
private void logProperties ( final String header , final Properties properties ) { if ( LOGGER . isDebugEnabled ( ) ) { final StringWriter sw = new StringWriter ( ) ; try ( final PrintWriter pw = new PrintWriter ( sw ) ) { pw . format ( "%s:%n%n" , header ) ; final Enumeration < ? > e = properties . propertyNames ( ) ; while ( e . hasMoreElements ( ) ) { final String key = ( String ) e . nextElement ( ) ; if ( key . contains ( "password" ) ) { pw . format ( "%s='*****'%n" , key ) ; } else { final String value = properties . getProperty ( key ) ; if ( value != null ) { pw . format ( "%s='%s'%n" , key , value ) ; } } } pw . flush ( ) ; LOGGER . debug ( sw . toString ( ) ) ; } } }
Logs the properties . This will not log any properties that contain password in the key .
11,513
public void setStringIfNotEmpty ( final String key , final String value ) { if ( null != value && ! value . isEmpty ( ) ) { setString ( key , value ) ; } }
Sets a property value only if the value is not null and not empty .
11,514
private File getJarPath ( ) { String decodedPath = "." ; String jarPath = "" ; final ProtectionDomain domain = Settings . class . getProtectionDomain ( ) ; if ( domain != null && domain . getCodeSource ( ) != null && domain . getCodeSource ( ) . getLocation ( ) != null ) { jarPath = Settings . class . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) . getPath ( ) ; } try { decodedPath = URLDecoder . decode ( jarPath , StandardCharsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException ex ) { LOGGER . trace ( "" , ex ) ; } final File path = new File ( decodedPath ) ; if ( path . getName ( ) . toLowerCase ( ) . endsWith ( ".jar" ) ) { return path . getParentFile ( ) ; } else { return new File ( "." ) ; } }
Attempts to retrieve the folder containing the Jar file containing the Settings class .
11,515
public synchronized File getTempDirectory ( ) throws IOException { if ( tempDirectory == null ) { final File baseTemp = new File ( getString ( Settings . KEYS . TEMP_DIRECTORY , System . getProperty ( "java.io.tmpdir" ) ) ) ; tempDirectory = FileUtils . createTempDirectory ( baseTemp ) ; } return tempDirectory ; }
Returns the temporary directory .
11,516
public String [ ] getArray ( final String key ) { final String string = getString ( key ) ; if ( string != null ) { if ( string . charAt ( 0 ) == '{' || string . charAt ( 0 ) == '[' ) { return new Gson ( ) . fromJson ( string , String [ ] . class ) ; } else { return string . split ( ARRAY_SEP ) ; } } return null ; }
Returns a list with the given key .
11,517
public long getLong ( final String key ) throws InvalidSettingException { try { return Long . parseLong ( getString ( key ) ) ; } catch ( NumberFormatException ex ) { throw new InvalidSettingException ( "Could not convert property '" + key + "' to a long." , ex ) ; } }
Returns a long value from the properties file . If the value was specified as a system property or passed in via the - Dprop = value argument - this method will return the value from the system properties before the values in the contained configuration file .
11,518
public String getConnectionString ( String connectionStringKey , String dbFileNameKey ) throws IOException , InvalidSettingException { final String connStr = getString ( connectionStringKey ) ; if ( connStr == null ) { final String msg = String . format ( "Invalid properties file; %s is missing." , connectionStringKey ) ; throw new InvalidSettingException ( msg ) ; } if ( connStr . contains ( "%s" ) ) { final File directory = getH2DataDirectory ( ) ; LOGGER . debug ( "Data directory: {}" , directory ) ; String fileName = null ; if ( dbFileNameKey != null ) { fileName = getString ( dbFileNameKey ) ; } if ( fileName == null ) { final String msg = String . format ( "Invalid properties file to get a file based connection string; '%s' must be defined." , dbFileNameKey ) ; throw new InvalidSettingException ( msg ) ; } if ( connStr . startsWith ( "jdbc:h2:file:" ) && fileName . endsWith ( ".mv.db" ) ) { fileName = fileName . substring ( 0 , fileName . length ( ) - 6 ) ; } final File dbFile = new File ( directory , fileName ) ; final String cString = String . format ( connStr , dbFile . getCanonicalPath ( ) ) ; LOGGER . debug ( "Connection String: '{}'" , cString ) ; return cString ; } return connStr ; }
Returns a connection string from the configured properties . If the connection string contains a %s this method will determine the data directory and replace the %s with the path to the data directory . If the data directory does not exist it will be created .
11,519
public File getDataDirectory ( ) throws IOException { final File path = getDataFile ( Settings . KEYS . DATA_DIRECTORY ) ; if ( path != null && ( path . exists ( ) || path . mkdirs ( ) ) ) { return path ; } throw new IOException ( String . format ( "Unable to create the data directory '%s'" , ( path == null ) ? "unknown" : path . getAbsolutePath ( ) ) ) ; }
Retrieves the primary data directory that is used for caching web content .
11,520
public File getH2DataDirectory ( ) throws IOException { final String h2Test = getString ( Settings . KEYS . H2_DATA_DIRECTORY ) ; final File path ; if ( h2Test != null && ! h2Test . isEmpty ( ) ) { path = getDataFile ( Settings . KEYS . H2_DATA_DIRECTORY ) ; } else { path = getDataFile ( Settings . KEYS . DATA_DIRECTORY ) ; } if ( path != null && ( path . exists ( ) || path . mkdirs ( ) ) ) { return path ; } throw new IOException ( String . format ( "Unable to create the h2 data directory '%s'" , ( path == null ) ? "unknown" : path . getAbsolutePath ( ) ) ) ; }
Retrieves the H2 data directory - if the database has been moved to the temp directory this method will return the temp directory .
11,521
public File getTempFile ( final String prefix , final String extension ) throws IOException { final File dir = getTempDirectory ( ) ; final String tempFileName = String . format ( "%s%s.%s" , prefix , UUID . randomUUID ( ) . toString ( ) , extension ) ; final File tempFile = new File ( dir , tempFileName ) ; if ( tempFile . exists ( ) ) { return getTempFile ( prefix , extension ) ; } return tempFile ; }
Generates a new temporary file name that is guaranteed to be unique .
11,522
protected void analyzeDependency ( Dependency dependency , Engine engine ) throws AnalysisException { final File f = dependency . getActualFile ( ) ; final String fileName = FilenameUtils . removeExtension ( f . getName ( ) ) ; final String ext = FilenameUtils . getExtension ( f . getName ( ) ) ; if ( ! IGNORED_FILES . accept ( f ) && ! "js" . equals ( ext ) ) { final DependencyVersion version = DependencyVersionUtil . parseVersion ( fileName ) ; final String packageName = DependencyVersionUtil . parsePreVersion ( fileName ) ; if ( version != null ) { if ( version . getVersionParts ( ) == null || version . getVersionParts ( ) . size ( ) < 2 ) { dependency . addEvidence ( EvidenceType . VERSION , "file" , "version" , version . toString ( ) , Confidence . MEDIUM ) ; } else { dependency . addEvidence ( EvidenceType . VERSION , "file" , "version" , version . toString ( ) , Confidence . HIGHEST ) ; } dependency . addEvidence ( EvidenceType . VERSION , "file" , "name" , packageName , Confidence . MEDIUM ) ; } dependency . addEvidence ( EvidenceType . PRODUCT , "file" , "name" , packageName , Confidence . HIGH ) ; dependency . addEvidence ( EvidenceType . VENDOR , "file" , "name" , packageName , Confidence . HIGH ) ; } }
Collects information about the file name .
11,523
public boolean supportsParallelProcessing ( ) { try { return getSettings ( ) . getBoolean ( Settings . KEYS . ANALYZER_ARTIFACTORY_PARALLEL_ANALYSIS , true ) ; } catch ( InvalidSettingException ex ) { LOGGER . debug ( "Invalid setting for analyzer.artifactory.parallel.analysis; using true." ) ; } return true ; }
Whether the analyzer is configured to support parallel processing .
11,524
private void processPom ( Dependency dependency , MavenArtifact ma ) throws IOException , AnalysisException { File pomFile = null ; try { final File baseDir = getSettings ( ) . getTempDirectory ( ) ; pomFile = File . createTempFile ( "pom" , ".xml" , baseDir ) ; Files . delete ( pomFile . toPath ( ) ) ; LOGGER . debug ( "Downloading {}" , ma . getPomUrl ( ) ) ; final Downloader downloader = new Downloader ( getSettings ( ) ) ; downloader . fetchFile ( new URL ( ma . getPomUrl ( ) ) , pomFile ) ; PomUtils . analyzePOM ( dependency , pomFile ) ; } catch ( DownloadFailedException ex ) { LOGGER . warn ( "Unable to download pom.xml for {} from Artifactory; " + "this could result in undetected CPE/CVEs." , dependency . getFileName ( ) ) ; } finally { if ( pomFile != null && pomFile . exists ( ) && ! FileUtils . deleteQuietly ( pomFile ) ) { LOGGER . debug ( "Failed to delete temporary pom file {}" , pomFile ) ; pomFile . deleteOnExit ( ) ; } } }
If necessary downloads the pom . xml from Central and adds the evidence to the dependency .
11,525
public String fetchContent ( URL url , boolean useProxy ) throws DownloadFailedException { try ( HttpResourceConnection conn = new HttpResourceConnection ( settings , useProxy ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ) { final InputStream in = conn . fetch ( url ) ; IOUtils . copy ( in , out ) ; return out . toString ( UTF8 ) ; } catch ( IOException ex ) { final String msg = format ( "Download failed, unable to retrieve '%s'" , url . toString ( ) ) ; throw new DownloadFailedException ( msg , ex ) ; } }
Retrieves a file from a given URL and returns the contents .
11,526
private static Map < String , String > readCweData ( String [ ] files ) { try { final SAXParserFactory factory = SAXParserFactory . newInstance ( ) ; final SAXParser saxParser = factory . newSAXParser ( ) ; final CweHandler handler = new CweHandler ( ) ; for ( String f : files ) { final File in = new File ( f ) ; if ( ! in . isFile ( ) ) { System . err . println ( String . format ( "File not found %s" , in ) ) ; } System . out . println ( String . format ( "Parsing %s" , in ) ) ; saxParser . parse ( in , handler ) ; } return handler . getCwe ( ) ; } catch ( SAXException | IOException | ParserConfigurationException ex ) { System . err . println ( String . format ( "Error generating serialized data: %s" , ex . getMessage ( ) ) ) ; } return null ; }
Reads the CWE data from the array of files .
11,527
private static void serializeCweData ( Map < String , String > cwe , File out ) { try ( FileOutputStream fout = new FileOutputStream ( out ) ; ObjectOutputStream objOut = new ObjectOutputStream ( fout ) ; ) { System . out . println ( "Writing " + cwe . size ( ) + " cwe entries." ) ; objOut . writeObject ( cwe ) ; System . out . println ( String . format ( "Serialized CWE data written to %s" , out . getCanonicalPath ( ) ) ) ; System . out . println ( "To update the ODC CWE data copy the serialized file to 'src/main/resources/data/cwe.hashmap.serialized'" ) ; } catch ( IOException ex ) { System . err . println ( String . format ( "Error generating serialized data: %s" , ex . getMessage ( ) ) ) ; } }
Writes the map of CWE data to disk .
11,528
private boolean isUpdateConfiguredFalse ( ) { try { if ( ! settings . getBoolean ( Settings . KEYS . UPDATE_NVDCVE_ENABLED , true ) ) { return true ; } } catch ( InvalidSettingException ex ) { LOGGER . trace ( "invalid setting UPDATE_NVDCVE_ENABLED" , ex ) ; } boolean autoUpdate = true ; try { autoUpdate = settings . getBoolean ( Settings . KEYS . AUTO_UPDATE ) ; } catch ( InvalidSettingException ex ) { LOGGER . debug ( "Invalid setting for auto-update; using true." ) ; } return ! autoUpdate ; }
Checks if the system is configured NOT to update .
11,529
protected void initializeExecutorServices ( ) { final int downloadPoolSize ; final int max = settings . getInt ( Settings . KEYS . MAX_DOWNLOAD_THREAD_POOL_SIZE , 3 ) ; if ( DOWNLOAD_THREAD_POOL_SIZE > max ) { downloadPoolSize = max ; } else { downloadPoolSize = DOWNLOAD_THREAD_POOL_SIZE ; } downloadExecutorService = Executors . newFixedThreadPool ( downloadPoolSize ) ; processingExecutorService = Executors . newFixedThreadPool ( PROCESSING_THREAD_POOL_SIZE ) ; LOGGER . debug ( "#download threads: {}" , downloadPoolSize ) ; LOGGER . debug ( "#processing threads: {}" , PROCESSING_THREAD_POOL_SIZE ) ; }
Initialize the executor services for download and processing of the NVD CVE XML data .
11,530
private boolean checkUpdate ( ) throws UpdateException { boolean proceed = true ; final int validForHours = settings . getInt ( Settings . KEYS . CVE_CHECK_VALID_FOR_HOURS , 0 ) ; if ( dataExists ( ) && 0 < validForHours ) { final long msValid = validForHours * 60L * 60L * 1000L ; final long lastChecked = Long . parseLong ( dbProperties . getProperty ( DatabaseProperties . LAST_CHECKED , "0" ) ) ; final long now = System . currentTimeMillis ( ) ; proceed = ( now - lastChecked ) > msValid ; if ( ! proceed ) { LOGGER . info ( "Skipping NVD check since last check was within {} hours." , validForHours ) ; LOGGER . debug ( "Last NVD was at {}, and now {} is within {} ms." , lastChecked , now , msValid ) ; } } return proceed ; }
Checks if the NVD CVE XML files were last checked recently . As an optimization we can avoid repetitive checks against the NVD . Setting CVE_CHECK_VALID_FOR_HOURS determines the duration since last check before checking again . A database property stores the timestamp of the last check .
11,531
protected final MetaProperties getMetaFile ( String url ) throws UpdateException { try { final String metaUrl = url . substring ( 0 , url . length ( ) - 7 ) + "meta" ; final URL u = new URL ( metaUrl ) ; final Downloader d = new Downloader ( settings ) ; final String content = d . fetchContent ( u , true ) ; return new MetaProperties ( content ) ; } catch ( MalformedURLException ex ) { throw new UpdateException ( "Meta file url is invalid: " + url , ex ) ; } catch ( InvalidDataException ex ) { throw new UpdateException ( "Meta file content is invalid: " + url , ex ) ; } catch ( DownloadFailedException ex ) { throw new UpdateException ( "Unable to download meta file: " + url , ex ) ; } }
Downloads the NVD CVE Meta file properties .
11,532
protected final UpdateableNvdCve getUpdatesNeeded ( ) throws MalformedURLException , DownloadFailedException , UpdateException { LOGGER . debug ( "starting getUpdatesNeeded() ..." ) ; final UpdateableNvdCve updates = new UpdateableNvdCve ( ) ; if ( dbProperties != null && ! dbProperties . isEmpty ( ) ) { try { final int startYear = settings . getInt ( Settings . KEYS . CVE_START_YEAR , 2002 ) ; final int endYear = Calendar . getInstance ( ) . get ( Calendar . YEAR ) ; boolean needsFullUpdate = false ; for ( int y = startYear ; y <= endYear ; y ++ ) { final long val = Long . parseLong ( dbProperties . getProperty ( DatabaseProperties . LAST_UPDATED_BASE + y , "0" ) ) ; if ( val == 0 ) { needsFullUpdate = true ; break ; } } final long lastUpdated = Long . parseLong ( dbProperties . getProperty ( DatabaseProperties . LAST_UPDATED , "0" ) ) ; final long now = System . currentTimeMillis ( ) ; final int days = settings . getInt ( Settings . KEYS . CVE_MODIFIED_VALID_FOR_DAYS , 7 ) ; String url = settings . getString ( Settings . KEYS . CVE_MODIFIED_JSON ) ; MetaProperties modified = getMetaFile ( url ) ; if ( ! needsFullUpdate && lastUpdated == modified . getLastModifiedDate ( ) ) { return updates ; } else { updates . add ( MODIFIED , url , modified . getLastModifiedDate ( ) , true ) ; if ( needsFullUpdate || ! DateUtil . withinDateRange ( lastUpdated , now , days ) ) { final int start = settings . getInt ( Settings . KEYS . CVE_START_YEAR ) ; final int end = Calendar . getInstance ( ) . get ( Calendar . YEAR ) ; final String baseUrl = settings . getString ( Settings . KEYS . CVE_BASE_JSON ) ; for ( int i = start ; i <= end ; i ++ ) { url = String . format ( baseUrl , i ) ; MetaProperties meta = getMetaFile ( url ) ; long currentTimestamp = 0 ; try { currentTimestamp = Long . parseLong ( dbProperties . getProperty ( DatabaseProperties . LAST_UPDATED_BASE + i , "0" ) ) ; } catch ( NumberFormatException ex ) { LOGGER . debug ( "Error parsing '{}' '{}' from nvdcve.lastupdated" , DatabaseProperties . LAST_UPDATED_BASE , i , ex ) ; } if ( currentTimestamp < meta . getLastModifiedDate ( ) ) { updates . add ( Integer . toString ( i ) , url , meta . getLastModifiedDate ( ) , true ) ; } } } } } catch ( NumberFormatException ex ) { LOGGER . warn ( "An invalid schema version or timestamp exists in the data.properties file." ) ; LOGGER . debug ( "" , ex ) ; } catch ( InvalidSettingException ex ) { throw new UpdateException ( "The NVD CVE start year property is set to an invalid value" , ex ) ; } } return updates ; }
Determines if the index needs to be updated . This is done by fetching the NVD CVE meta data and checking the last update date . If the data needs to be refreshed this method will return the NvdCveUrl for the files that need to be updated .
11,533
private void extractConfigureScriptEvidence ( Dependency dependency , final String name , final String contents ) { final Matcher matcher = PACKAGE_VAR . matcher ( contents ) ; while ( matcher . find ( ) ) { final String variable = matcher . group ( 1 ) ; final String value = matcher . group ( 2 ) ; if ( ! value . isEmpty ( ) ) { if ( variable . endsWith ( "NAME" ) ) { dependency . addEvidence ( EvidenceType . PRODUCT , name , variable , value , Confidence . HIGHEST ) ; } else if ( "VERSION" . equals ( variable ) ) { dependency . addEvidence ( EvidenceType . VERSION , name , variable , value , Confidence . HIGHEST ) ; } else if ( "BUGREPORT" . equals ( variable ) ) { dependency . addEvidence ( EvidenceType . VENDOR , name , variable , value , Confidence . HIGH ) ; } else if ( "URL" . equals ( variable ) ) { dependency . addEvidence ( EvidenceType . VENDOR , name , variable , value , Confidence . HIGH ) ; } } } }
Extracts evidence from the configuration .
11,534
private void gatherEvidence ( Dependency dependency , final String name , String contents ) { final Matcher matcher = AC_INIT_PATTERN . matcher ( contents ) ; if ( matcher . find ( ) ) { dependency . addEvidence ( EvidenceType . PRODUCT , name , "Package" , matcher . group ( 1 ) , Confidence . HIGHEST ) ; dependency . addEvidence ( EvidenceType . VERSION , name , "Package Version" , matcher . group ( 2 ) , Confidence . HIGHEST ) ; if ( null != matcher . group ( 3 ) ) { dependency . addEvidence ( EvidenceType . VENDOR , name , "Bug report address" , matcher . group ( 4 ) , Confidence . HIGH ) ; } if ( null != matcher . group ( 5 ) ) { dependency . addEvidence ( EvidenceType . PRODUCT , name , "Tarname" , matcher . group ( 6 ) , Confidence . HIGH ) ; } if ( null != matcher . group ( 7 ) ) { final String url = matcher . group ( 8 ) ; if ( UrlStringUtils . isUrl ( url ) ) { dependency . addEvidence ( EvidenceType . VENDOR , name , "URL" , url , Confidence . HIGH ) ; } } } }
Gathers evidence from a given file
11,535
protected final void prepareAnalyzer ( Engine engine ) throws InitializationException { if ( filesMatched ) { prepareFileTypeAnalyzer ( engine ) ; } else { this . setEnabled ( false ) ; } }
Initializes the analyzer .
11,536
private void analyzePodfileLockDependencies ( Dependency podfileLock , Engine engine ) throws AnalysisException { engine . removeDependency ( podfileLock ) ; final String contents ; try { contents = FileUtils . readFileToString ( podfileLock . getActualFile ( ) , Charset . defaultCharset ( ) ) ; } catch ( IOException e ) { throw new AnalysisException ( "Problem occurred while reading dependency file." , e ) ; } final Matcher matcher = PODFILE_LOCK_DEPENDENCY_PATTERN . matcher ( contents ) ; while ( matcher . find ( ) ) { final String name = matcher . group ( 1 ) ; final String version = matcher . group ( 2 ) ; final Dependency dependency = new Dependency ( podfileLock . getActualFile ( ) , true ) ; dependency . setEcosystem ( DEPENDENCY_ECOSYSTEM ) ; dependency . setName ( name ) ; dependency . setVersion ( version ) ; final String packagePath = String . format ( "%s:%s" , name , version ) ; dependency . setPackagePath ( packagePath ) ; dependency . setDisplayFileName ( packagePath ) ; dependency . setSha1sum ( Checksum . getSHA1Checksum ( packagePath ) ) ; dependency . setSha256sum ( Checksum . getSHA256Checksum ( packagePath ) ) ; dependency . setMd5sum ( Checksum . getMD5Checksum ( packagePath ) ) ; dependency . addEvidence ( EvidenceType . VENDOR , PODFILE_LOCK , "name" , name , Confidence . HIGHEST ) ; dependency . addEvidence ( EvidenceType . PRODUCT , PODFILE_LOCK , "name" , name , Confidence . HIGHEST ) ; dependency . addEvidence ( EvidenceType . VERSION , PODFILE_LOCK , "version" , version , Confidence . HIGHEST ) ; engine . addDependency ( dependency ) ; } }
Analyzes the podfile . lock file to extract evidence for the dependency .
11,537
private String determineEvidence ( String contents , String blockVariable , String fieldPattern ) { String value = "" ; final Matcher arrayMatcher = Pattern . compile ( String . format ( "\\s*?%s\\.%s\\s*?=\\s*?\\{\\s*?(.*?)\\s*?\\}" , blockVariable , fieldPattern ) , Pattern . CASE_INSENSITIVE ) . matcher ( contents ) ; if ( arrayMatcher . find ( ) ) { value = arrayMatcher . group ( 1 ) ; } else { final Matcher matcher = Pattern . compile ( String . format ( "\\s*?%s\\.%s\\s*?=\\s*?(['\"])(.*?)\\1" , blockVariable , fieldPattern ) , Pattern . CASE_INSENSITIVE ) . matcher ( contents ) ; if ( matcher . find ( ) ) { value = matcher . group ( 2 ) ; } } return value ; }
Extracts evidence from the contents and adds it to the given evidence collection .
11,538
private void setPackagePath ( Dependency dep ) { final File file = new File ( dep . getFilePath ( ) ) ; final String parent = file . getParent ( ) ; if ( parent != null ) { dep . setPackagePath ( parent ) ; } }
Sets the package path on the given dependency .
11,539
public Void call ( ) { if ( shouldAnalyze ( ) ) { LOGGER . debug ( "Begin Analysis of '{}' ({})" , dependency . getActualFilePath ( ) , analyzer . getName ( ) ) ; try { analyzer . analyze ( dependency , engine ) ; } catch ( AnalysisException ex ) { LOGGER . warn ( "An error occurred while analyzing '{}' ({})." , dependency . getActualFilePath ( ) , analyzer . getName ( ) ) ; LOGGER . debug ( "" , ex ) ; exceptions . add ( ex ) ; } catch ( Throwable ex ) { LOGGER . warn ( "An unexpected error occurred during analysis of '{}' ({}): {}" , dependency . getActualFilePath ( ) , analyzer . getName ( ) , ex . getMessage ( ) ) ; LOGGER . error ( "" , ex ) ; exceptions . add ( ex ) ; } } return null ; }
Executes the analysis task .
11,540
protected boolean shouldAnalyze ( ) { if ( analyzer instanceof FileTypeAnalyzer ) { final FileTypeAnalyzer fileTypeAnalyzer = ( FileTypeAnalyzer ) analyzer ; return fileTypeAnalyzer . accept ( dependency . getActualFile ( ) ) ; } return true ; }
Determines if the analyzer can analyze the given dependency .
11,541
public static String getMD5Checksum ( File file ) throws IOException , NoSuchAlgorithmException { final byte [ ] b = getChecksum ( MD5 , file ) ; return getHex ( b ) ; }
Calculates the MD5 checksum of a specified file .
11,542
public static String getSHA1Checksum ( File file ) throws IOException , NoSuchAlgorithmException { final byte [ ] b = getChecksum ( SHA1 , file ) ; return getHex ( b ) ; }
Calculates the SHA1 checksum of a specified file .
11,543
public static String getSHA256Checksum ( File file ) throws IOException , NoSuchAlgorithmException { final byte [ ] b = getChecksum ( SHA256 , file ) ; return getHex ( b ) ; }
Calculates the SH256 checksum of a specified file .
11,544
public static String getChecksum ( String algorithm , byte [ ] bytes ) { final MessageDigest digest = getMessageDigest ( algorithm ) ; final byte [ ] b = digest . digest ( bytes ) ; return getHex ( b ) ; }
Calculates the MD5 checksum of a specified bytes .
11,545
public static String getMD5Checksum ( String text ) { final byte [ ] data = stringToBytes ( text ) ; return getChecksum ( MD5 , data ) ; }
Calculates the MD5 checksum of the specified text .
11,546
private static byte [ ] stringToBytes ( String text ) { byte [ ] data ; try { data = text . getBytes ( Charset . forName ( StandardCharsets . UTF_8 . name ( ) ) ) ; } catch ( UnsupportedCharsetException ex ) { data = text . getBytes ( Charset . defaultCharset ( ) ) ; } return data ; }
Converts the given text into bytes .
11,547
private static MessageDigest getMessageDigest ( String algorithm ) { try { return MessageDigest . getInstance ( algorithm ) ; } catch ( NoSuchAlgorithmException e ) { LOGGER . error ( e . getMessage ( ) ) ; final String msg = String . format ( "Failed to obtain the %s message digest." , algorithm ) ; throw new IllegalStateException ( msg , e ) ; } }
Returns the message digest .
11,548
private PropertyType processPropertyType ( ) { final PropertyType pt = new PropertyType ( ) ; pt . setValue ( currentText . toString ( ) ) ; if ( currentAttributes != null && currentAttributes . getLength ( ) > 0 ) { final String regex = currentAttributes . getValue ( "regex" ) ; if ( regex != null ) { pt . setRegex ( Boolean . parseBoolean ( regex ) ) ; } final String caseSensitive = currentAttributes . getValue ( "caseSensitive" ) ; if ( caseSensitive != null ) { pt . setCaseSensitive ( Boolean . parseBoolean ( caseSensitive ) ) ; } } return pt ; }
Processes field members that have been collected during the characters and startElement method to construct a PropertyType object .
11,549
public static JsonObject sanitize ( JsonObject packageJson ) { final JsonObjectBuilder payloadBuilder = Json . createObjectBuilder ( ) ; final String projectName = packageJson . getString ( "name" , "" ) ; final String projectVersion = packageJson . getString ( "version" , "" ) ; if ( ! projectName . isEmpty ( ) ) { payloadBuilder . add ( "name" , projectName ) ; } if ( ! projectVersion . isEmpty ( ) ) { payloadBuilder . add ( "version" , projectVersion ) ; } final JsonValue jsonValue = packageJson . get ( "requires" ) ; if ( jsonValue . getValueType ( ) != JsonValue . ValueType . OBJECT ) { final JsonObjectBuilder requiresBuilder = Json . createObjectBuilder ( ) ; final JsonObject dependencies = packageJson . getJsonObject ( "dependencies" ) ; for ( String moduleName : dependencies . keySet ( ) ) { final JsonObject module = dependencies . getJsonObject ( moduleName ) ; final String version = module . getString ( "version" ) ; requiresBuilder . add ( moduleName , version ) ; } payloadBuilder . add ( "requires" , requiresBuilder . build ( ) ) ; } payloadBuilder . add ( "dependencies" , packageJson . getJsonObject ( "dependencies" ) ) ; payloadBuilder . add ( "install" , Json . createArrayBuilder ( ) . build ( ) ) ; payloadBuilder . add ( "remove" , Json . createArrayBuilder ( ) . build ( ) ) ; payloadBuilder . add ( "metadata" , Json . createObjectBuilder ( ) . add ( "npm_version" , "6.1.0" ) . add ( "node_version" , "v10.5.0" ) . add ( "platform" , "linux" ) ) ; return payloadBuilder . build ( ) ; }
The NPM Audit API only accepts a modified version of package - lock . json . This method will make the necessary modifications in - memory sanitizing non - public dependencies by omitting them and returns a new sanitized version .
11,550
public void cleanup ( ) { if ( file != null && file . exists ( ) && ! file . delete ( ) ) { LOGGER . debug ( "Failed to delete first temporary file {}" , file . toString ( ) ) ; file . deleteOnExit ( ) ; } }
Attempts to delete the files that were downloaded .
11,551
public List < Advisory > submitPackage ( JsonObject packageJson ) throws SearchException , IOException { try { final byte [ ] packageDatabytes = packageJson . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ; final URLConnectionFactory factory = new URLConnectionFactory ( settings ) ; final HttpURLConnection conn = factory . createHttpURLConnection ( nodeAuditUrl , useProxy ) ; conn . setDoOutput ( true ) ; conn . setDoInput ( true ) ; conn . setRequestMethod ( "POST" ) ; conn . setRequestProperty ( "user-agent" , "npm/6.1.0 node/v10.5.0 linux x64" ) ; conn . setRequestProperty ( "npm-in-ci" , "false" ) ; conn . setRequestProperty ( "npm-scope" , "" ) ; conn . setRequestProperty ( "npm-session" , generateRandomSession ( ) ) ; conn . setRequestProperty ( "content-type" , "application/json" ) ; conn . setRequestProperty ( "Content-Length" , Integer . toString ( packageDatabytes . length ) ) ; conn . connect ( ) ; try ( OutputStream os = new BufferedOutputStream ( conn . getOutputStream ( ) ) ) { os . write ( packageDatabytes ) ; os . flush ( ) ; } switch ( conn . getResponseCode ( ) ) { case 200 : try ( InputStream in = new BufferedInputStream ( conn . getInputStream ( ) ) ; JsonReader jsonReader = Json . createReader ( in ) ) { final JSONObject jsonResponse = new JSONObject ( jsonReader . readObject ( ) . toString ( ) ) ; final NpmAuditParser parser = new NpmAuditParser ( ) ; return parser . parse ( jsonResponse ) ; } case 400 : LOGGER . debug ( "Invalid payload submitted to Node Audit API. Received response code: {} {}" , conn . getResponseCode ( ) , conn . getResponseMessage ( ) ) ; throw new SearchException ( "Could not perform Node Audit analysis. Invalid payload submitted to Node Audit API." ) ; default : LOGGER . debug ( "Could not connect to Node Audit API. Received response code: {} {}" , conn . getResponseCode ( ) , conn . getResponseMessage ( ) ) ; throw new IOException ( "Could not connect to Node Audit API" ) ; } } catch ( IOException ex ) { if ( ex instanceof javax . net . ssl . SSLHandshakeException && ex . getMessage ( ) . contains ( "unable to find valid certification path to requested target" ) ) { final String msg = String . format ( "Unable to connect to '%s' - the Java trust store does not contain a trusted root for the cert. " + " Please see https://github.com/jeremylong/InstallCert for one method of updating the trusted certificates." , nodeAuditUrl ) ; throw new URLConnectionFailureException ( msg , ex ) ; } throw ex ; } }
Submits the package . json file to the Node Audit API and returns a list of zero or more Advisories .
11,552
private String generateRandomSession ( ) { final int length = 16 ; final SecureRandom r = new SecureRandom ( ) ; final StringBuilder sb = new StringBuilder ( ) ; while ( sb . length ( ) < length ) { sb . append ( Integer . toHexString ( r . nextInt ( ) ) ) ; } return sb . toString ( ) . substring ( 0 , length ) ; }
Generates a random 16 character lower - case hex string .
11,553
@ SuppressWarnings ( "fallthrough" ) @ SuppressFBWarnings ( justification = "As this is an encoding method the fallthrough is intentional" , value = { "SF_SWITCH_NO_DEFAULT" } ) public static void appendEscapedLuceneQuery ( StringBuilder buf , final CharSequence text ) { if ( text == null || buf == null ) { return ; } for ( int i = 0 ; i < text . length ( ) ; i ++ ) { final char c = text . charAt ( i ) ; switch ( c ) { case '+' : case '-' : case '&' : case '|' : case '!' : case '(' : case ')' : case '{' : case '}' : case '[' : case ']' : case '^' : case '"' : case '~' : case '*' : case '?' : case ':' : case '/' : case '\\' : buf . append ( '\\' ) ; default : buf . append ( c ) ; break ; } } }
Appends the text to the supplied StringBuilder escaping Lucene control characters in the process .
11,554
public static String escapeLuceneQuery ( final CharSequence text ) { if ( text == null ) { return null ; } final int size = text . length ( ) << 1 ; final StringBuilder buf = new StringBuilder ( size ) ; appendEscapedLuceneQuery ( buf , text ) ; return buf . toString ( ) ; }
Escapes the text passed in so that it is treated as data instead of control characters .
11,555
private String addStringEvidence ( Dependency dependency , EvidenceType type , String packageDescription , String field , String fieldPattern , Confidence confidence ) { String value = "" ; final Matcher matcher = Pattern . compile ( String . format ( "%s *:\\s*\"([^\"]*)" , fieldPattern ) , Pattern . DOTALL ) . matcher ( packageDescription ) ; if ( matcher . find ( ) ) { value = matcher . group ( 1 ) ; } if ( value != null ) { value = value . trim ( ) ; if ( value . length ( ) > 0 ) { dependency . addEvidence ( type , SPM_FILE_NAME , field , value , confidence ) ; } } return value ; }
Extracts evidence from the package description and adds it to the given evidence collection .
11,556
public void process ( ) { LOGGER . debug ( "Beginning Composer lock processing" ) ; try { final JsonObject composer = jsonReader . readObject ( ) ; if ( composer . containsKey ( "packages" ) ) { LOGGER . debug ( "Found packages" ) ; final JsonArray packages = composer . getJsonArray ( "packages" ) ; for ( JsonObject pkg : packages . getValuesAs ( JsonObject . class ) ) { if ( pkg . containsKey ( "name" ) ) { final String groupName = pkg . getString ( "name" ) ; if ( groupName . indexOf ( '/' ) >= 0 && groupName . indexOf ( '/' ) <= groupName . length ( ) - 1 ) { if ( pkg . containsKey ( "version" ) ) { final String group = groupName . substring ( 0 , groupName . indexOf ( '/' ) ) ; final String project = groupName . substring ( groupName . indexOf ( '/' ) + 1 ) ; String version = pkg . getString ( "version" ) ; if ( version . startsWith ( "v" ) ) { version = version . substring ( 1 ) ; } LOGGER . debug ( "Got package {}/{}/{}" , group , project , version ) ; composerDependencies . add ( new ComposerDependency ( group , project , version ) ) ; } else { LOGGER . debug ( "Group/package {} does not have a version" , groupName ) ; } } else { LOGGER . debug ( "Got a dependency with no name" ) ; } } } } } catch ( JsonParsingException jsonpe ) { throw new ComposerException ( "Error parsing stream" , jsonpe ) ; } catch ( JsonException jsone ) { throw new ComposerException ( "Error reading stream" , jsone ) ; } catch ( IllegalStateException ise ) { throw new ComposerException ( "Illegal state in composer stream" , ise ) ; } catch ( ClassCastException cce ) { throw new ComposerException ( "Not exactly composer lock" , cce ) ; } }
Process the input stream to create the list of dependencies .
11,557
@ SuppressWarnings ( "unchecked" ) private static Map < String , String > loadData ( ) { final String filePath = "data/cwe.hashmap.serialized" ; try ( InputStream input = FileUtils . getResourceAsStream ( filePath ) ; ObjectInputStream oin = new ObjectInputStream ( input ) ) { return ( HashMap < String , String > ) oin . readObject ( ) ; } catch ( ClassNotFoundException ex ) { LOGGER . warn ( "Unable to load CWE data. This should not be an issue." ) ; LOGGER . debug ( "" , ex ) ; } catch ( IOException ex ) { LOGGER . warn ( "Unable to load CWE data due to an IO Error. This should not be an issue." ) ; LOGGER . debug ( "" , ex ) ; } return null ; }
Loads a HashMap containing the CWE data from a resource found in the jar .
11,558
private void analyzeSetVersionCommand ( Dependency dependency , Engine engine , String contents ) { Dependency currentDep = dependency ; final Matcher m = SET_VERSION . matcher ( contents ) ; int count = 0 ; while ( m . find ( ) ) { count ++ ; LOGGER . debug ( "Found project command match with {} groups: {}" , m . groupCount ( ) , m . group ( 0 ) ) ; String product = m . group ( 1 ) ; final String version = m . group ( 2 ) ; LOGGER . debug ( "Group 1: {}" , product ) ; LOGGER . debug ( "Group 2: {}" , version ) ; final String aliasPrefix = "ALIASOF_" ; if ( product . startsWith ( aliasPrefix ) ) { product = product . replaceFirst ( aliasPrefix , "" ) ; } if ( count > 1 ) { currentDep = new Dependency ( dependency . getActualFile ( ) ) ; currentDep . setEcosystem ( DEPENDENCY_ECOSYSTEM ) ; final String filePath = String . format ( "%s:%s" , dependency . getFilePath ( ) , product ) ; currentDep . setFilePath ( filePath ) ; currentDep . setSha1sum ( Checksum . getSHA1Checksum ( filePath ) ) ; currentDep . setSha256sum ( Checksum . getSHA256Checksum ( filePath ) ) ; currentDep . setMd5sum ( Checksum . getMD5Checksum ( filePath ) ) ; engine . addDependency ( currentDep ) ; } final String source = currentDep . getFileName ( ) ; currentDep . addEvidence ( EvidenceType . PRODUCT , source , "Product" , product , Confidence . MEDIUM ) ; currentDep . addEvidence ( EvidenceType . VENDOR , source , "Vendor" , product , Confidence . MEDIUM ) ; currentDep . addEvidence ( EvidenceType . VERSION , source , "Version" , version , Confidence . MEDIUM ) ; currentDep . setName ( product ) ; currentDep . setVersion ( version ) ; } LOGGER . debug ( "Found {} matches." , count ) ; }
Extracts the version information from the contents . If more then one version is found additional dependencies are added to the dependency list .
11,559
public void parse ( String [ ] args ) throws FileNotFoundException , ParseException { line = parseArgs ( args ) ; if ( line != null ) { validateArgs ( ) ; } }
Parses the arguments passed in and captures the results for later use .
11,560
private void validateArgs ( ) throws FileNotFoundException , ParseException { if ( isUpdateOnly ( ) || isRunScan ( ) ) { final String value = line . getOptionValue ( ARGUMENT . CVE_VALID_FOR_HOURS ) ; if ( value != null ) { try { final int i = Integer . parseInt ( value ) ; if ( i < 0 ) { throw new ParseException ( "Invalid Setting: cveValidForHours must be a number greater than or equal to 0." ) ; } } catch ( NumberFormatException ex ) { throw new ParseException ( "Invalid Setting: cveValidForHours must be a number greater than or equal to 0." ) ; } } } if ( isRunScan ( ) ) { validatePathExists ( getScanFiles ( ) , ARGUMENT . SCAN ) ; validatePathExists ( getReportDirectory ( ) , ARGUMENT . OUT ) ; if ( getPathToCore ( ) != null ) { validatePathExists ( getPathToCore ( ) , ARGUMENT . PATH_TO_CORE ) ; } if ( line . hasOption ( ARGUMENT . OUTPUT_FORMAT ) ) { final String format = line . getOptionValue ( ARGUMENT . OUTPUT_FORMAT ) ; try { Format . valueOf ( format ) ; } catch ( IllegalArgumentException ex ) { final String msg = String . format ( "An invalid 'format' of '%s' was specified. " + "Supported output formats are " + SUPPORTED_FORMATS , format ) ; throw new ParseException ( msg ) ; } } if ( ( getBaseCveUrl ( ) != null && getModifiedCveUrl ( ) == null ) || ( getBaseCveUrl ( ) == null && getModifiedCveUrl ( ) != null ) ) { final String msg = "If one of the CVE URLs is specified they must all be specified; please add the missing CVE URL." ; throw new ParseException ( msg ) ; } if ( line . hasOption ( ARGUMENT . SYM_LINK_DEPTH ) ) { try { final int i = Integer . parseInt ( line . getOptionValue ( ARGUMENT . SYM_LINK_DEPTH ) ) ; if ( i < 0 ) { throw new ParseException ( "Symbolic Link Depth (symLink) must be greater than zero." ) ; } } catch ( NumberFormatException ex ) { throw new ParseException ( "Symbolic Link Depth (symLink) is not a number." ) ; } } } }
Validates that the command line arguments are valid .
11,561
private void validatePathExists ( String path , String argumentName ) throws FileNotFoundException { if ( path == null ) { isValid = false ; final String msg = String . format ( "Invalid '%s' argument: null" , argumentName ) ; throw new FileNotFoundException ( msg ) ; } else if ( ! path . contains ( "*" ) && ! path . contains ( "?" ) ) { File f = new File ( path ) ; if ( "o" . equalsIgnoreCase ( argumentName . substring ( 0 , 1 ) ) && ! "ALL" . equalsIgnoreCase ( this . getReportFormat ( ) ) ) { final String checkPath = path . toLowerCase ( ) ; if ( checkPath . endsWith ( ".html" ) || checkPath . endsWith ( ".xml" ) || checkPath . endsWith ( ".htm" ) ) { if ( f . getParentFile ( ) == null ) { f = new File ( "." , path ) ; } if ( ! f . getParentFile ( ) . isDirectory ( ) ) { isValid = false ; final String msg = String . format ( "Invalid '%s' argument: '%s'" , argumentName , path ) ; throw new FileNotFoundException ( msg ) ; } } } else if ( ! f . exists ( ) ) { isValid = false ; final String msg = String . format ( "Invalid '%s' argument: '%s'" , argumentName , path ) ; throw new FileNotFoundException ( msg ) ; } } else if ( ( path . endsWith ( "/*" ) && ! path . endsWith ( "**/*" ) ) || ( path . endsWith ( "\\*" ) && path . endsWith ( "**\\*" ) ) ) { LOGGER . warn ( "Possibly incorrect path '{}' from argument '{}' because it ends with a slash star; " + "dependency-check uses ant-style paths" , path , argumentName ) ; } }
Validates whether or not the path points at a file that exists ; if the path does not point to an existing file a FileNotFoundException is thrown .
11,562
@ SuppressWarnings ( "static-access" ) private Options createCommandLineOptions ( ) { final Options options = new Options ( ) ; addStandardOptions ( options ) ; addAdvancedOptions ( options ) ; addDeprecatedOptions ( options ) ; return options ; }
Generates an Options collection that is used to parse the command line and to display the help message .
11,563
private boolean hasDisableOption ( String argument , String setting ) { if ( line == null || ! line . hasOption ( argument ) ) { try { return ! settings . getBoolean ( setting ) ; } catch ( InvalidSettingException ise ) { LOGGER . warn ( "Invalid property setting '{}' defaulting to false" , setting ) ; return false ; } } else { return true ; } }
Utility method to determine if one of the disable options has been set . If not set this method will check the currently configured settings for the current value to return .
11,564
public boolean isNodeAuditDisabled ( ) { if ( hasDisableOption ( "disableNSP" , Settings . KEYS . ANALYZER_NODE_AUDIT_ENABLED ) ) { LOGGER . error ( "The disableNSP argument has been deprecated and replaced by disableNodeAudit" ) ; LOGGER . error ( "The disableNSP argument will be removed in the next version" ) ; return true ; } return hasDisableOption ( ARGUMENT . DISABLE_NODE_AUDIT , Settings . KEYS . ANALYZER_NODE_AUDIT_ENABLED ) ; }
Returns true if the disableNodeAudit command line argument was specified .
11,565
public String getNexusUrl ( ) { if ( line == null || ! line . hasOption ( ARGUMENT . NEXUS_URL ) ) { return null ; } else { return line . getOptionValue ( ARGUMENT . NEXUS_URL ) ; } }
Returns the url to the nexus server if one was specified .
11,566
public boolean isNexusUsesProxy ( ) { if ( line == null || ! line . hasOption ( ARGUMENT . NEXUS_USES_PROXY ) ) { try { return settings . getBoolean ( Settings . KEYS . ANALYZER_NEXUS_USES_PROXY ) ; } catch ( InvalidSettingException ise ) { return true ; } } else { return Boolean . parseBoolean ( line . getOptionValue ( ARGUMENT . NEXUS_USES_PROXY ) ) ; } }
Returns true if the Nexus Analyzer should use the configured proxy to connect to Nexus ; otherwise false is returned .
11,567
@ SuppressFBWarnings ( justification = "Accepting that this is a bad practice - used a Boolean as we needed three states" , value = { "NP_BOOLEAN_RETURN_NULL" } ) public Boolean getBooleanArgument ( String argument ) { if ( line != null && line . hasOption ( argument ) ) { final String value = line . getOptionValue ( argument ) ; if ( value != null ) { return Boolean . parseBoolean ( value ) ; } } return null ; }
Returns the argument boolean value .
11,568
public String getStringArgument ( String argument ) { if ( line != null && line . hasOption ( argument ) ) { return line . getOptionValue ( argument ) ; } return null ; }
Returns the argument value .
11,569
public void printHelp ( ) { final HelpFormatter formatter = new HelpFormatter ( ) ; final Options options = new Options ( ) ; addStandardOptions ( options ) ; if ( line != null && line . hasOption ( ARGUMENT . ADVANCED_HELP ) ) { addAdvancedOptions ( options ) ; } final String helpMsg = String . format ( "%n%s" + " can be used to identify if there are any known CVE vulnerabilities in libraries utilized by an application. " + "%s will automatically update required data from the Internet, such as the CVE and CPE data files from nvd.nist.gov.%n%n" , settings . getString ( "application.name" , "DependencyCheck" ) , settings . getString ( "application.name" , "DependencyCheck" ) ) ; formatter . printHelp ( settings . getString ( "application.name" , "DependencyCheck" ) , helpMsg , options , "" , true ) ; }
Displays the command line help message to the standard output .
11,570
@ SuppressFBWarnings ( justification = "Accepting that this is a bad practice - but made more sense in this use case" , value = { "NP_BOOLEAN_RETURN_NULL" } ) public Boolean isRetireJsFilterNonVulnerable ( ) { return ( line != null && line . hasOption ( ARGUMENT . RETIREJS_FILTER_NON_VULNERABLE ) ) ? true : null ; }
Returns whether or not the retireJS analyzer should exclude non - vulnerable JS from the report .
11,571
public String getProjectName ( ) { String name = line . getOptionValue ( ARGUMENT . PROJECT ) ; if ( name == null ) { name = "" ; } return name ; }
Returns the application name specified on the command line .
11,572
public File getPropertiesFile ( ) { final String path = line . getOptionValue ( ARGUMENT . PROP ) ; if ( path != null ) { return new File ( path ) ; } return null ; }
Returns the properties file specified on the command line .
11,573
@ SuppressFBWarnings ( justification = "Accepting that this is a bad practice - but made more sense in this use case" , value = { "NP_BOOLEAN_RETURN_NULL" } ) public Boolean isAutoUpdate ( ) { return ( line != null && line . hasOption ( ARGUMENT . DISABLE_AUTO_UPDATE ) ) ? false : null ; }
Checks if the auto update feature has been disabled . If it has been disabled via the command line this will return false .
11,574
public Integer getCveValidForHours ( ) { final String v = line . getOptionValue ( ARGUMENT . CVE_VALID_FOR_HOURS ) ; if ( v != null ) { return Integer . parseInt ( v ) ; } return null ; }
Get the value of cveValidForHours .
11,575
@ SuppressFBWarnings ( justification = "Accepting that this is a bad practice - but made more sense in this use case" , value = { "NP_BOOLEAN_RETURN_NULL" } ) public Boolean isExperimentalEnabled ( ) { return ( line != null && line . hasOption ( ARGUMENT . EXPERIMENTAL ) ) ? true : null ; }
Returns true if the experimental analyzers are enabled .
11,576
@ SuppressFBWarnings ( justification = "Accepting that this is a bad practice - but made more sense in this use case" , value = { "NP_BOOLEAN_RETURN_NULL" } ) public Boolean isRetiredEnabled ( ) { return ( line != null && line . hasOption ( ARGUMENT . RETIRED ) ) ? true : null ; }
Returns true if the retired analyzers are enabled .
11,577
public int getFailOnCVSS ( ) { if ( line . hasOption ( ARGUMENT . FAIL_ON_CVSS ) ) { final String value = line . getOptionValue ( ARGUMENT . FAIL_ON_CVSS ) ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException nfe ) { return 11 ; } } else { return 11 ; } }
Returns the CVSS value to fail on .
11,578
private void generateExternalReports ( Engine engine , File outDirectory ) throws ScanAgentException { try { engine . writeReports ( applicationName , outDirectory , this . reportFormat . name ( ) ) ; } catch ( ReportException ex ) { LOGGER . debug ( "Unexpected exception occurred during analysis; please see the verbose error log for more details." , ex ) ; throw new ScanAgentException ( "Error generating the report" , ex ) ; } }
Generates the reports for a given dependency - check engine .
11,579
public Engine execute ( ) throws ScanAgentException { Engine engine = null ; try { engine = executeDependencyCheck ( ) ; if ( ! this . updateOnly ) { if ( this . generateReport ) { generateExternalReports ( engine , new File ( this . reportOutputDirectory ) ) ; } if ( this . showSummary ) { showSummary ( engine . getDependencies ( ) ) ; } if ( this . failBuildOnCVSS <= 10 ) { checkForFailure ( engine . getDependencies ( ) ) ; } } } catch ( ExceptionCollection ex ) { if ( ex . isFatal ( ) ) { LOGGER . error ( "A fatal exception occurred during analysis; analysis has stopped. Please see the debug log for more details." ) ; LOGGER . debug ( "" , ex ) ; } throw new ScanAgentException ( "One or more exceptions occurred during analysis; please see the debug log for more details." , ex ) ; } finally { settings . cleanup ( true ) ; if ( engine != null ) { engine . close ( ) ; } } return engine ; }
Executes the dependency - check and generates the report .
11,580
protected boolean addTerm ( ) { final boolean termAdded = ! tokens . isEmpty ( ) ; if ( termAdded ) { final String term = tokens . pop ( ) ; clearAttributes ( ) ; termAtt . append ( term ) ; } return termAdded ; }
Adds a term if one exists from the tokens collection .
11,581
public void add ( String id , String url , long timestamp , boolean needsUpdate ) { final NvdCveInfo item = new NvdCveInfo ( ) ; item . setNeedsUpdate ( needsUpdate ) ; item . setId ( id ) ; item . setUrl ( url ) ; item . setTimestamp ( timestamp ) ; collection . put ( id , item ) ; }
Adds a new entry of updateable information to the contained collection .
11,582
private String addStringEvidence ( Dependency dependency , EvidenceType type , String contents , String blockVariable , String field , String fieldPattern , Confidence confidence ) { String value = "" ; final Matcher arrayMatcher = Pattern . compile ( String . format ( "\\s*?%s\\.%s\\s*?=\\s*?\\[(.*?)\\]" , blockVariable , fieldPattern ) , Pattern . CASE_INSENSITIVE ) . matcher ( contents ) ; if ( arrayMatcher . find ( ) ) { final String arrayValue = arrayMatcher . group ( 1 ) ; value = arrayValue . replaceAll ( "['\"]" , "" ) . trim ( ) ; } else { final Matcher matcher = Pattern . compile ( String . format ( "\\s*?%s\\.%s\\s*?=\\s*?(['\"])(.*?)\\1" , blockVariable , fieldPattern ) , Pattern . CASE_INSENSITIVE ) . matcher ( contents ) ; if ( matcher . find ( ) ) { value = matcher . group ( 2 ) ; } } if ( value . length ( ) > 0 ) { dependency . addEvidence ( type , GEMSPEC , field , value , confidence ) ; } return value ; }
Adds the specified evidence to the given evidence collection .
11,583
private String addEvidenceFromVersionFile ( Dependency dependency , EvidenceType type , File dependencyFile ) { final File parentDir = dependencyFile . getParentFile ( ) ; String version = null ; int versionCount = 0 ; if ( parentDir != null ) { final File [ ] matchingFiles = parentDir . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . contains ( VERSION_FILE_NAME ) ; } } ) ; if ( matchingFiles == null ) { return null ; } for ( File f : matchingFiles ) { try { final List < String > lines = FileUtils . readLines ( f , Charset . defaultCharset ( ) ) ; if ( lines . size ( ) == 1 ) { final String value = lines . get ( 0 ) . trim ( ) ; if ( version == null || ! version . equals ( value ) ) { version = value ; versionCount ++ ; } dependency . addEvidence ( type , GEMSPEC , "version" , value , Confidence . HIGH ) ; } } catch ( IOException e ) { LOGGER . debug ( "Error reading gemspec" , e ) ; } } } if ( versionCount == 1 ) { return version ; } return null ; }
Adds evidence from the version file .
11,584
public FileFilterBuilder addExtensions ( Iterable < String > extensions ) { for ( String extension : extensions ) { this . extensions . add ( extension . startsWith ( "." ) ? extension : "." + extension ) ; } return this ; }
Add to the set of file extensions to accept for analysis . Case - insensitivity is assumed .
11,585
public FileFilter build ( ) { if ( filenames . isEmpty ( ) && extensions . isEmpty ( ) && fileFilters . isEmpty ( ) ) { throw new IllegalStateException ( "May only be invoked after at least one add... method has been invoked." ) ; } final OrFileFilter filter = new OrFileFilter ( ) ; if ( ! filenames . isEmpty ( ) ) { filter . addFileFilter ( new NameFileFilter ( new ArrayList < > ( filenames ) ) ) ; } if ( ! extensions . isEmpty ( ) ) { filter . addFileFilter ( new SuffixFileFilter ( new ArrayList < > ( extensions ) , IOCase . INSENSITIVE ) ) ; } for ( IOFileFilter iof : fileFilters ) { filter . addFileFilter ( iof ) ; } return filter ; }
Builds the filter and returns it .
11,586
public static String fromNamedReference ( CharSequence s ) { if ( s == null ) { return null ; } final Integer code = SPECIALS . get ( s . toString ( ) ) ; if ( code != null ) { return "&#" + code + ";" ; } return null ; }
Converts a named XML entity into its HTML encoded Unicode code point .
11,587
@ SuppressFBWarnings ( justification = "yes, there is a redundant null check in the catch - to suppress warnings we are leaving the null check" , value = { "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE" } ) public HttpURLConnection createHttpURLConnection ( URL url ) throws URLConnectionFailureException { HttpURLConnection conn = null ; final String proxyHost = settings . getString ( Settings . KEYS . PROXY_SERVER ) ; try { if ( proxyHost != null && ! matchNonProxy ( url ) ) { final int proxyPort = settings . getInt ( Settings . KEYS . PROXY_PORT ) ; final SocketAddress address = new InetSocketAddress ( proxyHost , proxyPort ) ; final String username = settings . getString ( Settings . KEYS . PROXY_USERNAME ) ; final String password = settings . getString ( Settings . KEYS . PROXY_PASSWORD ) ; if ( username != null && password != null ) { final Authenticator auth = new Authenticator ( ) { public PasswordAuthentication getPasswordAuthentication ( ) { if ( proxyHost . equals ( getRequestingHost ( ) ) || getRequestorType ( ) . equals ( Authenticator . RequestorType . PROXY ) ) { LOGGER . debug ( "Using the configured proxy username and password" ) ; try { if ( settings . getBoolean ( Settings . KEYS . PROXY_DISABLE_SCHEMAS , true ) ) { System . setProperty ( "jdk.http.auth.tunneling.disabledSchemes" , "" ) ; } } catch ( InvalidSettingException ex ) { LOGGER . trace ( "This exception can be ignored" , ex ) ; } return new PasswordAuthentication ( username , password . toCharArray ( ) ) ; } return super . getPasswordAuthentication ( ) ; } } ; Authenticator . setDefault ( auth ) ; } final Proxy proxy = new Proxy ( Proxy . Type . HTTP , address ) ; conn = ( HttpURLConnection ) url . openConnection ( proxy ) ; } else { conn = ( HttpURLConnection ) url . openConnection ( ) ; } final int connectionTimeout = settings . getInt ( Settings . KEYS . CONNECTION_TIMEOUT , 10000 ) ; conn . setConnectTimeout ( connectionTimeout ) ; conn . setInstanceFollowRedirects ( true ) ; } catch ( IOException ex ) { if ( conn != null ) { try { conn . disconnect ( ) ; } finally { conn = null ; } } throw new URLConnectionFailureException ( "Error getting connection." , ex ) ; } configureTLS ( url , conn ) ; return conn ; }
Utility method to create an HttpURLConnection . If the application is configured to use a proxy this method will retrieve the proxy settings and use them when setting up the connection .
11,588
@ SuppressWarnings ( "StringSplitter" ) private boolean matchNonProxy ( final URL url ) { final String host = url . getHost ( ) ; final String nonProxyHosts = settings . getString ( Settings . KEYS . PROXY_NON_PROXY_HOSTS ) ; if ( null != nonProxyHosts ) { final String [ ] nonProxies = nonProxyHosts . split ( "(,)|(;)|(\\|)" ) ; for ( final String nonProxyHost : nonProxies ) { if ( null != nonProxyHost && nonProxyHost . contains ( "*" ) ) { final int pos = nonProxyHost . indexOf ( '*' ) ; final String nonProxyHostPrefix = nonProxyHost . substring ( 0 , pos ) ; final String nonProxyHostSuffix = nonProxyHost . substring ( pos + 1 ) ; if ( ! StringUtils . isEmpty ( nonProxyHostPrefix ) && host . startsWith ( nonProxyHostPrefix ) && StringUtils . isEmpty ( nonProxyHostSuffix ) ) { return true ; } if ( StringUtils . isEmpty ( nonProxyHostPrefix ) && ! StringUtils . isEmpty ( nonProxyHostSuffix ) && host . endsWith ( nonProxyHostSuffix ) ) { return true ; } if ( ! StringUtils . isEmpty ( nonProxyHostPrefix ) && host . startsWith ( nonProxyHostPrefix ) && ! StringUtils . isEmpty ( nonProxyHostSuffix ) && host . endsWith ( nonProxyHostSuffix ) ) { return true ; } } else if ( host . equals ( nonProxyHost ) ) { return true ; } } } return false ; }
Check if host name matches nonProxy settings
11,589
private void configureTLS ( URL url , URLConnection conn ) { if ( "https" . equals ( url . getProtocol ( ) ) ) { try { final HttpsURLConnection secCon = ( HttpsURLConnection ) conn ; final SSLSocketFactoryEx factory = new SSLSocketFactoryEx ( settings ) ; secCon . setSSLSocketFactory ( factory ) ; } catch ( NoSuchAlgorithmException ex ) { LOGGER . debug ( "Unsupported algorithm in SSLSocketFactoryEx" , ex ) ; } catch ( KeyManagementException ex ) { LOGGER . debug ( "Key management exception in SSLSocketFactoryEx" , ex ) ; } } }
If the protocol is HTTPS this will configure the cipher suites so that connections can be made to the NVD and others using older versions of Java .
11,590
protected synchronized void analyzeDependency ( Dependency ignore , Engine engine ) throws AnalysisException { if ( ! analyzed ) { analyzed = true ; final Set < Dependency > dependenciesToRemove = new HashSet < > ( ) ; final Dependency [ ] dependencies = engine . getDependencies ( ) ; if ( dependencies . length < 2 ) { return ; } for ( int x = 0 ; x < dependencies . length - 1 ; x ++ ) { final Dependency dependency = dependencies [ x ] ; if ( ! dependenciesToRemove . contains ( dependency ) ) { for ( int y = x + 1 ; y < dependencies . length ; y ++ ) { final Dependency nextDependency = dependencies [ y ] ; if ( evaluateDependencies ( dependency , nextDependency , dependenciesToRemove ) ) { break ; } } } } dependenciesToRemove . forEach ( ( d ) -> { engine . removeDependency ( d ) ; } ) ; } }
Analyzes a set of dependencies . If they have been found to have the same base path and the same set of identifiers they are likely related . The related dependencies are bundled into a single reportable item .
11,591
public static H2DBShutdownHook getHook ( Settings settings ) { try { final String className = settings . getString ( Settings . KEYS . H2DB_SHUTDOWN_HOOK , "org.owasp.dependencycheck.utils.H2DBCleanupHook" ) ; final Class < ? > type = Class . forName ( className ) ; return ( H2DBShutdownHook ) type . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex ) { LOGGER . debug ( "Failed to instantiate {}, using default shutdown hook instead" , ex ) ; return new H2DBCleanupHook ( ) ; } }
Creates a new H2DB Shutdown Hook .
11,592
private static Pattern compileAssignPattern ( String name ) { return Pattern . compile ( String . format ( "\\b(__)?%s(__)?\\b *= *(['\"]+)(.*?)\\3" , name ) , REGEX_OPTIONS ) ; }
Utility function to create a regex pattern matcher .
11,593
private boolean addSummaryInfo ( Dependency dependency , Pattern pattern , int group , String contents , String source , String key ) { final Matcher matcher = pattern . matcher ( contents ) ; final boolean found = matcher . find ( ) ; if ( found ) { JarAnalyzer . addDescription ( dependency , matcher . group ( group ) , source , key ) ; } return found ; }
Adds summary information to the dependency
11,594
private boolean gatherHomePageEvidence ( Dependency dependency , EvidenceType type , Pattern pattern , String source , String name , String contents ) { final Matcher matcher = pattern . matcher ( contents ) ; boolean found = false ; if ( matcher . find ( ) ) { final String url = matcher . group ( 4 ) ; if ( UrlStringUtils . isUrl ( url ) ) { found = true ; dependency . addEvidence ( type , source , name , url , Confidence . MEDIUM ) ; } } return found ; }
Collects evidence from the home page URL .
11,595
private boolean gatherEvidence ( Dependency dependency , EvidenceType type , Pattern pattern , String contents , String source , String name , Confidence confidence ) { final Matcher matcher = pattern . matcher ( contents ) ; final boolean found = matcher . find ( ) ; if ( found ) { dependency . addEvidence ( type , source , name , matcher . group ( 4 ) , confidence ) ; if ( type == EvidenceType . VERSION ) { dependency . setVersion ( matcher . group ( 4 ) ) ; final String dispName = String . format ( "%s:%s" , dependency . getName ( ) , dependency . getVersion ( ) ) ; dependency . setDisplayFileName ( dispName ) ; } } return found ; }
Gather evidence from a Python source file using the given string assignment regex pattern .
11,596
public synchronized void cleanup ( ) { if ( driver != null ) { DriverLoader . cleanup ( driver ) ; driver = null ; } connectionString = null ; userName = null ; password = null ; }
Cleans up resources and unloads any registered database drivers . This needs to be called to ensure the driver is unregistered prior to the finalize method being called as during shutdown the class loader used to load the driver may be unloaded prior to the driver being de - registered .
11,597
public synchronized Connection getConnection ( ) throws DatabaseException { initialize ( ) ; Connection conn = null ; try { conn = DriverManager . getConnection ( connectionString , userName , password ) ; } catch ( SQLException ex ) { LOGGER . debug ( "" , ex ) ; throw new DatabaseException ( "Unable to connect to the database" , ex ) ; } return conn ; }
Constructs a new database connection object per the database configuration .
11,598
public static boolean h2DataFileExists ( Settings configuration ) throws IOException { final File file = getH2DataFile ( configuration ) ; return file . exists ( ) ; }
Determines if the H2 database file exists . If it does not exist then the data structure will need to be created .
11,599
public static File getH2DataFile ( Settings configuration ) throws IOException { final File dir = configuration . getH2DataDirectory ( ) ; final String fileName = configuration . getString ( Settings . KEYS . DB_FILE_NAME ) ; final File file = new File ( dir , fileName ) ; return file ; }
Returns a reference to the H2 database file .