Analyzes the specified JavaScript file.

@param dependency the dependency to analyze.
@param engine the engine that is scanning the dependencies
@throws AnalysisException is thrown if there is an error reading the file
file.
4833
@Override
    public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
        try {
            final byte[] fileContent = IOUtils.toByteArray(new FileInputStream(dependency.getActualFile()));
            final ScannerFacade scanner = new ScannerFacade(jsRepository);
            final List<JsLibraryResult> results = scanner.scanScript(dependency.getActualFile().getAbsolutePath(), fileContent, 0);

            if (results.size() > 0) {
                for (JsLibraryResult libraryResult : results) {

                    final JsLibrary lib = libraryResult.getLibrary();
                    dependency.setName(lib.getName());
                    dependency.setVersion(libraryResult.getDetectedVersion());
                    try {
                        final PackageURL purl = PackageURLBuilder.aPackageURL().withType("javascript")
                                .withName(lib.getName()).withVersion(libraryResult.getDetectedVersion()).build();
                        dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST));
                    } catch (MalformedPackageURLException ex) {
                        LOGGER.debug("Unable to build package url for retireJS", ex);
                        final GenericIdentifier id = new GenericIdentifier("javascript:" + lib.getName() + "@"
                                + libraryResult.getDetectedVersion(), Confidence.HIGHEST);
                        dependency.addSoftwareIdentifier(id);
                    }

                    dependency.addEvidence(EvidenceType.VERSION, "file", "version", libraryResult.getDetectedVersion(), Confidence.HIGH);
                    dependency.addEvidence(EvidenceType.PRODUCT, "file", "name", libraryResult.getLibrary().getName(), Confidence.HIGH);

                    final List<Vulnerability> vulns = new ArrayList<>();
                    final JsVulnerability jsVuln = libraryResult.getVuln();

                    if (jsVuln.getIdentifiers().containsKey("CVE") || jsVuln.getIdentifiers().containsKey("osvdb")) {
                        /* CVEs and OSVDB are an array of Strings - each one a unique vulnerability.
                         * So the JsVulnerability we are operating on may actually be representing
                         * multiple vulnerabilities. */

                        //TODO - can we refactor this to avoid russian doll syndrome (i.e. nesting)?
                        //CSOFF: NestedForDepth
                        for (Map.Entry<String, List<String>> entry : jsVuln.getIdentifiers().entrySet()) {
                            final String key = entry.getKey();
                            final List<String> value = entry.getValue();
                            if ("CVE".equals(key)) {
                                for (String cve : value) {
                                    Vulnerability vuln = engine.getDatabase().getVulnerability(StringUtils.trim(cve));
                                    if (vuln == null) {
                                        /* The CVE does not exist in the database and is likely in a
                                         * reserved state. Create a new one without adding it to the
                                         * database and populate it as best as possible. */
                                        vuln = new Vulnerability();
                                        vuln.setName(cve);
                                        vuln.setUnscoredSeverity(jsVuln.getSeverity());
                                        vuln.setSource(Vulnerability.Source.RETIREJS);
                                    }
                                    for (String info : jsVuln.getInfo()) {
                                        vuln.addReference("info", "info", info);
                                    }
                                    vulns.add(vuln);
                                }
                            } else if ("osvdb".equals(key)) {
                                //todo - convert to map/collect
                                value.stream().forEach((osvdb) -> {
                                    final Vulnerability vuln = new Vulnerability();
                                    vuln.setName(osvdb);
                                    vuln.setSource(Vulnerability.Source.RETIREJS);
                                    vuln.setUnscoredSeverity(jsVuln.getSeverity());
                                    jsVuln.getInfo().forEach((info) -> {
                                        vuln.addReference("info", "info", info);
                                    });
                                    vulns.add(vuln);
                                });
                            }
                            dependency.addVulnerabilities(vulns);
                        }
                        //CSON: NestedForDepth
                    } else {
                        final Vulnerability individualVuln = new Vulnerability();
                        /* ISSUE, BUG, etc are all individual vulnerabilities. The result of this
                         * iteration will be one vulnerability. */
                        for (Map.Entry<String, List<String>> entry : jsVuln.getIdentifiers().entrySet()) {
                            final String key = entry.getKey();
                            final List<String> value = entry.getValue();
                            // CSOFF: NeedBraces
                            if (null != key) {
                                switch (key) {
                                    case "issue":
                                        individualVuln.setName(libraryResult.getLibrary().getName() + " issue: " + value.get(0));
                                        individualVuln.addReference(key, key, value.get(0));
                                        break;
                                    case "bug":
                                        individualVuln.setName(libraryResult.getLibrary().getName() + " bug: " + value.get(0));
                                        individualVuln.addReference(key, key, value.get(0));
                                        break;
                                    case "summary":
                                        if (null == individualVuln.getName()) {
                                            individualVuln.setName(value.get(0));
                                        }
                                        individualVuln.setDescription(value.get(0));
                                        break;
                                    case "release":
                                        individualVuln.addReference(key, key, value.get(0));
                                        break;
                                    default:
                                        break;
                                }
                            }
                            // CSON: NeedBraces
                            individualVuln.setSource(Vulnerability.Source.RETIREJS);
                            individualVuln.setUnscoredSeverity(jsVuln.getSeverity());
                            for (String info : jsVuln.getInfo()) {
                                individualVuln.addReference("info", "info", info);
                            }
                        }
                        dependency.addVulnerability(individualVuln);
                    }
                }
            } else if (getSettings().getBoolean(Settings.KEYS.ANALYZER_RETIREJS_FILTER_NON_VULNERABLE, false)) {
                engine.removeDependency(dependency);
            }
        } catch (IOException | DatabaseException e) {
            throw new AnalysisException(e);
        }
    }
1346061
public static void analyzePOM(Dependency dependency, File pomFile) throws AnalysisException {
        final Model pom = PomUtils.readPom(pomFile);
        JarAnalyzer.setPomEvidence(dependency, pom, null, true);
    }
674019
public void addDependency(String notation, String scope ) {
        Map<String, String> notationMap = Notation.parse(notation);
        Dependency dependency = new Dependency();
        dependency.setGroupId(notationMap.get("groupId"));
        dependency.setArtifactId(notationMap.get("artifactId"));
        dependency.setType(notationMap.get("type"));
        dependency.setVersion(notationMap.get("version"));
        dependency.setScope( scope );
        addDependency(dependency);
    }
1051907
protected void runCheck() throws MojoExecutionException, MojoFailureException {
        try (Engine engine = initializeEngine()) {
            ExceptionCollection exCol = scanDependencies(engine);
            try {
                engine.analyzeDependencies();
            } catch (ExceptionCollection ex) {
                exCol = handleAnalysisExceptions(exCol, ex);
            }
            if (exCol == null || !exCol.isFatal()) {

                File outputDir = getCorrectOutputDirectory(this.getProject());
                if (outputDir == null) {
                    //in some regards we shouldn't be writing this, but we are anyway.
                    //we shouldn't write this because nothing is configured to generate this report.
                    outputDir = new File(this.getProject().getBuild().getDirectory());
                }
                try {
                    final MavenProject p = this.getProject();
                    engine.writeReports(p.getName(), p.getGroupId(), p.getArtifactId(), p.getVersion(), outputDir, getFormat());
                } catch (ReportException ex) {
                    if (exCol == null) {
                        exCol = new ExceptionCollection(ex);
                    } else {
                        exCol.addException(ex);
                    }
                    if (this.isFailOnError()) {
                        throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
                    } else {
                        getLog().debug("Error writing the report", ex);
                    }
                }
                showSummary(this.getProject(), engine.getDependencies());
                checkForFailure(engine.getDependencies());
                if (exCol != null && this.isFailOnError()) {
                    throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
                }
            }
        } catch (DatabaseException ex) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Database connection error", ex);
            }
            final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
            if (this.isFailOnError()) {
                throw new MojoExecutionException(msg, ex);
            }
            getLog().error(msg, ex);
        } finally {
            getSettings().cleanup();
        }
    }
341487
@Override
    public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
        LOGGER.debug("Initializing Artifactory analyzer");
        final boolean enabled = isEnabled();
        LOGGER.debug("Artifactory analyzer enabled: {}", enabled);
        if (enabled) {
            searcher = new ArtifactorySearch(getSettings());
            final boolean preflightRequest = searcher.preflightRequest();
            if (!preflightRequest) {
                setEnabled(false);
                throw new InitializationException("There was an issue connecting to Artifactory . Disabling analyzer.");
            }
        }
    }
1318456
public static void loadScriptDependencies(final JsArrayString dependencies, final JavaScriptObject callback) {

        if (dependencies.length() == 0) {
            return;
        }
        final Set<String> absoluteUris = new HashSet<String>();
        for (int i = 0; i < dependencies.length(); i++) {
            absoluteUris.add(WidgetUtil.getAbsoluteUrl(dependencies.get(i)));
        }
        // Listener that loads the next when one is completed
        ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {

            @Override
            public void onError(ResourceLoadEvent event) {

                CmsDebugLog.consoleLog(event.getResourceUrl() + " could not be loaded.");
                // The show must go on
                absoluteUris.remove(event.getResourceUrl());
                if (absoluteUris.isEmpty()) {
                    Scheduler.get().scheduleDeferred(new ScheduledCommand() {

                        public void execute() {

                            callNativeFunction(callback);
                        }
                    });
                }

            }

            @Override
            public void onLoad(ResourceLoadEvent event) {

                absoluteUris.remove(event.getResourceUrl());
                if (absoluteUris.isEmpty()) {
                    Scheduler.get().scheduleDeferred(new ScheduledCommand() {

                        public void execute() {

                            callNativeFunction(callback);
                        }
                    });

                }
            }
        };

        ResourceLoader loader = ResourceLoader.get();
        for (int i = 0; i < dependencies.length(); i++) {
            String preloadUrl = dependencies.get(i);
            loader.loadScript(preloadUrl, resourceLoadListener);
        }
    }
907293
function lookForExternalDependenciesJS( _def, javascriptSources ) {
  if ( !_def ) return;
  try {
    const def = convertExternalDependencyDefinition( _def );
    Object.keys( def ).forEach( function ( js ) {
      const
      filename = `mod/${js}`,
      src = new Source( Project, filename ),
      code = src.read();
      pushUnique( javascriptSources, code );
    } );
  } catch ( ex ) {
    Fatal.fire(
      `Unable to parse JS dependencies: ${JSON.stringify(_def)}!\n${ex}`,
      javascriptSources
    );
  }
}
698657
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);
        }
    }
765086
function analyzeDependencies(component) {
  const checkList = ['base'];

  search(
    dependencyTree({
      directory: dir,
      filename: path.join(dir, component, 'index.js'),
      filter: path => !~path.indexOf('node_modules')
    }),
    component,
    checkList
  );

  if (!whiteList.includes(component)) {
    checkList.push(component);
  }

  return checkList.filter(item => checkComponentHasStyle(item));
}
905903
public void addDependency(final Dependency dependency) {
        if(dependency != null && !dependencies.contains(dependency)){
            this.dependencies.add(dependency);
        }
    }
423835
@Override
    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;
    }
629883
public static CompiledScript compile(ScriptEngine engine, String script) throws ScriptException {
		if (engine instanceof Compilable) {
			Compilable compEngine = (Compilable) engine;
			return compEngine.compile(script);
		}
		return null;
	}
817273
@Override
    public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
        LOGGER.debug("Initializing {}", getName());
        try {
            searcher = new NodeAuditSearch(getSettings());
        } catch (MalformedURLException ex) {
            setEnabled(false);
            throw new InitializationException("The configured URL to NPM Audit API is malformed", ex);
        }
        try {
            final Settings settings = engine.getSettings();
            final boolean nodeEnabled = settings.getBoolean(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED);
            if (!nodeEnabled) {
                LOGGER.warn("The Node Package Analyzer has been disabled; the resulting report will only "
                        + " contain the known vulnerable dependency - not a bill of materials for the node project.");
            }
        } catch (InvalidSettingException ex) {
            throw new InitializationException("Unable to read configuration settings", ex);
        }
    }
573984
public static void registerPluginAnalysisEngines(DetectorFactoryCollection detectorFactoryCollection,
            IAnalysisCache analysisCache) throws IOException {
        for (Iterator<Plugin> i = detectorFactoryCollection.pluginIterator(); i.hasNext();) {
            Plugin plugin = i.next();

            Class<? extends IAnalysisEngineRegistrar> engineRegistrarClass = plugin.getEngineRegistrarClass();
            if (engineRegistrarClass != null) {
                try {
                    IAnalysisEngineRegistrar engineRegistrar = engineRegistrarClass.newInstance();
                    engineRegistrar.registerAnalysisEngines(analysisCache);
                } catch (InstantiationException e) {
                    IOException ioe = new IOException("Could not create analysis engine registrar for plugin "
                            + plugin.getPluginId());
                    ioe.initCause(e);
                    throw ioe;
                } catch (IllegalAccessException e) {
                    IOException ioe = new IOException("Could not create analysis engine registrar for plugin "
                            + plugin.getPluginId());
                    ioe.initCause(e);
                    throw ioe;
                }
            }
        }
    }
376855
@Override
    public final void prepare(Engine engine) throws InitializationException {
        if (isEnabled()) {
            prepareAnalyzer(engine);
        } else {
            LOGGER.debug("{} has been disabled", getName());
        }
    }
1347593
private void handleAnalyzeFromFile(String filePath) throws IOException {
        try (BufferedReader in = new BufferedReader(UTF8.fileReader(filePath))) {
            while (true) {
                String s = in.readLine();
                if (s == null) {
                    break;
                }
                project.addFile(s);
            }
        }
    }
558730
@Override
    public synchronized void prepareAnalyzer(Engine engine) throws InitializationException {
        if (rules.isEmpty()) {
            try {
                loadSuppressionBaseData();
            } catch (SuppressionParseException ex) {
                throw new InitializationException("Error initializing the suppression analyzer: " + ex.getLocalizedMessage(), ex, true);
            }

            try {
                loadSuppressionData();
            } catch (SuppressionParseException ex) {
                throw new InitializationException("Warn initializing the suppression analyzer: " + ex.getLocalizedMessage(), ex, false);
            }
        }
    }