Performs the analysis.

@param dependency the dependency to analyze
@param engine the engine
@throws AnalysisException when there's an exception during analysis
480465
@Override
    public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
        LOGGER.debug("Checking Nuspec file {}", dependency);
        try {
            final NuspecParser parser = new XPathNuspecParser();
            NugetPackage np = null;
            try (FileInputStream fis = new FileInputStream(dependency.getActualFilePath())) {
                np = parser.parse(fis);
            } catch (NuspecParseException | FileNotFoundException ex) {
                throw new AnalysisException(ex);
            }

            dependency.setEcosystem(DEPENDENCY_ECOSYSTEM);
            if (np.getOwners() != null) {
                dependency.addEvidence(EvidenceType.VENDOR, "nuspec", "owners", np.getOwners(), Confidence.HIGHEST);
            }
            dependency.addEvidence(EvidenceType.VENDOR, "nuspec", "authors", np.getAuthors(), Confidence.HIGH);
            dependency.addEvidence(EvidenceType.VERSION, "nuspec", "version", np.getVersion(), Confidence.HIGHEST);
            dependency.addEvidence(EvidenceType.PRODUCT, "nuspec", "id", np.getId(), Confidence.HIGHEST);
            dependency.setName(np.getId());
            dependency.setVersion(np.getVersion());
            try {
                final PackageURL purl = PackageURLBuilder.aPackageURL().withType("nuget").withName(np.getId()).withVersion(np.getVersion()).build();
                dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST));
            } catch (MalformedPackageURLException ex) {
                LOGGER.debug("Unable to build package url for nuspec", ex);
                final GenericIdentifier gid = new GenericIdentifier("nuspec:" + np.getId() + "@" + np.getVersion(), Confidence.HIGHEST);
                dependency.addSoftwareIdentifier(gid);
            }
            final String packagePath = String.format("%s:%s", np.getId(), np.getVersion());
            dependency.setPackagePath(packagePath);
            dependency.setDisplayFileName(packagePath);
            if (np.getLicenseUrl() != null && !np.getLicenseUrl().isEmpty()) {
                dependency.setLicense(np.getLicenseUrl());
            }
            if (np.getTitle() != null) {
                dependency.addEvidence(EvidenceType.PRODUCT, "nuspec", "title", np.getTitle(), Confidence.MEDIUM);
            }
        } catch (Throwable e) {
            throw new AnalysisException(e);
        }
    }
876537
@Override
	public synchronized void removeEngine(Engine engine) {

        if( log.isDebugEnabled() )
            log.debug("Removing engine (" + engine.getInfo() + ")");

        // Is the specified Engine actually defined?
        int j = -1;
        for (int i = 0; i < engines.length; i++) {
            if (engine == engines[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;

        // Remove any Connector that is using this Engine
        if( log.isDebugEnabled() )
            log.debug(" Removing related Containers");
        while (true) {
            int n = -1;
            Connector[] connectors = service.findConnectors();
            for (int i = 0; i < connectors.length; i++) {
                if (connectors[i].getService().getContainer() == (Container) engine) {
                    n = i;
                    break;
                }
            }
            if (n < 0)
                break;
            service.removeConnector(connectors[n]);
        }

        // Stop this Engine if necessary
        if (engine instanceof Lifecycle) {
            if( log.isDebugEnabled() )
                log.debug(" Stopping this Engine");
            try {
                ((Lifecycle) engine).stop();
            } catch (LifecycleException e) {
                log.error("Engine.stop", e);
            }
        }

        // Remove this Engine from our set of defined Engines
        if( log.isDebugEnabled() )
            log.debug(" Removing this Engine");
        int k = 0;
        Engine results[] = new Engine[engines.length - 1];
        for (int i = 0; i < engines.length; i++) {
            if (i != j)
                results[k++] = engines[i];
        }
        engines = results;

    }
141664
@Override
    public Method analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
        JavaClass jclass = analysisCache.getClassAnalysis(JavaClass.class, descriptor.getClassDescriptor());
        Method[] methodList = jclass.getMethods();

        Method result = null;

        // As a side-effect, cache all of the Methods for this JavaClass
        for (Method method : methodList) {
            MethodDescriptor methodDescriptor = DescriptorFactory.instance().getMethodDescriptor(
                    descriptor.getSlashedClassName(), method.getName(), method.getSignature(), method.isStatic());

            // Put in cache eagerly
            analysisCache.eagerlyPutMethodAnalysis(Method.class, methodDescriptor, method);

            if (methodDescriptor.equals(descriptor)) {
                result = method;
            }
        }

        return result;
    }
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);
        }
    }
490658
public static void addDependency(Dependency depend,
                                   ClassLoader loader)
  {
    for (; loader != null; loader = loader.getParent()) {
      if (loader instanceof EnvironmentClassLoader) {
        ((EnvironmentClassLoader) loader).addDependency(depend);
        return;
      }
    }
  }
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);
        }
    }
537651
public void analyzeInstruction(Instruction ins) throws DataflowAnalysisException {
        if (frame.isValid()) {
            try {
                ins.accept(this);
            } catch (InvalidBytecodeException e) {
                String message = "Invalid bytecode: could not analyze instr. " + ins + " at frame " + frame;
                throw new DataflowAnalysisException(message, e);
            }
        }
    }
60869
@Override
    public void execute(DelegateExecution execution) {
        ActionDefinition actionDefinition = findRelatedActionDefinition(execution);

        Connector connector = getConnector(getImplementation(execution));
        IntegrationContext integrationContext = connector.apply(integrationContextBuilder.from(execution,
                                                                                    actionDefinition));

        execution.setVariables(outboundVariablesProvider.calculateVariables(integrationContext,
                                                                            actionDefinition));

        leave(execution);
    }
168441
public void load(ScriptEngine engine) {
        try {
            //module loading
            engine.eval("load('" + getResourceAsURLStirng("/eclairjs/EclairJS_Globals.js") + "');");
            engine.eval("load('" + getResourceAsURLStirng("/eclairjs/ModuleUtils.js") + "');");
            engine.eval("load('" + getResourceAsURLStirng("/eclairjs/jvm-npm/jvm-npm.js") + "');");
            engine.eval("load('" + getResourceAsURLStirng("/eclairjs/Serialize.js") + "');");

            NashornEngineSingleton.setEngine(engine);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
95040
public void addDependency (T dependant, T dependee)
    {
        _orphans.remove(dependant);
        DependencyNode<T> dependantNode = _nodes.get(dependant);
        if (dependantNode == null) {
            throw new IllegalArgumentException("Unknown dependant? " + dependant);
        }
        DependencyNode<T> dependeeNode = _nodes.get(dependee);
        if (dependeeNode == null) {
            throw new IllegalArgumentException("Unknown dependee? " + dependee);
        }
        if (dependee == dependant || dependsOn(dependee, dependant)) {
            throw new IllegalArgumentException("Refusing to create circular dependency.");
        }
        dependantNode.parents.add(dependeeNode);
        dependeeNode.children.add(dependantNode);
    }
488663
protected boolean shouldAnalyze() {
        if (analyzer instanceof FileTypeAnalyzer) {
            final FileTypeAnalyzer fileTypeAnalyzer = (FileTypeAnalyzer) analyzer;
            return fileTypeAnalyzer.accept(dependency.getActualFile());
        }
        return true;
    }
435338
@Override
    public JavaClass analyze(IAnalysisCache analysisCache, ClassDescriptor descriptor) throws CheckedAnalysisException {
        try {
            ClassData classData = analysisCache.getClassAnalysis(ClassData.class, descriptor);
            JavaClass javaClass = new ClassParser(classData.getInputStream(), descriptor.toResourceName()).parse();

            // Make sure that the JavaClass object knows the repository
            // it was loaded from.
            javaClass.setRepository(Repository.getRepository());

            if (DEBUG_MISSING_CLASSES && !(javaClass.getRepository() instanceof AnalysisCacheToRepositoryAdapter)) {
                throw new IllegalStateException("this should not happen");
            }

            return javaClass;
        } catch (RuntimeException e) {
            throw new RuntimeException("Unable to parse classfile for " + descriptor, e);
        } catch (IOException e) {
            throw new ResourceNotFoundException(descriptor.toResourceName(), e);
        }
    }
983041
void analyze(final MethodResult methodResult) {
        lock.lock();
        try {
            buildPackagePrefix(methodResult.getParentResource().getOriginalClass());

            final List<Instruction> visitedInstructions = interpretRelevantInstructions(methodResult.getInstructions());

            // find project defined methods in invoke occurrences
            final Set<ProjectMethod> projectMethods = findProjectMethods(visitedInstructions);

            // add project methods to global method pool
            projectMethods.forEach(MethodPool.getInstance()::addProjectMethod);

            Element returnedElement = new MethodSimulator().simulate(visitedInstructions);
            final String returnType = methodResult.getOriginalMethodSignature().getReturnType();

            // void resource methods are interpreted later; stop analyzing on error
            if (Types.PRIMITIVE_VOID.equals(returnType)) {
                return;
            }

            if (returnedElement == null) {
                // happens for abstract methods or if there is no return
                return;
            }

            final Set<Object> possibleObjects = returnedElement.getPossibleValues().stream().filter(o -> !(o instanceof HttpResponse))
                    .collect(Collectors.toSet());

            // for non-Response methods add a default if there are non-Response objects or none objects at all
            if (!Types.RESPONSE.equals(returnType)) {
                final HttpResponse defaultResponse = new HttpResponse();

                if (Types.OBJECT.equals(returnType))
                    defaultResponse.getEntityTypes().addAll(returnedElement.getTypes());
                else
                    defaultResponse.getEntityTypes().add(returnType);

                possibleObjects.stream().filter(o -> o instanceof JsonValue).map(o -> (JsonValue) o).forEach(defaultResponse.getInlineEntities()::add);

                defaultResponse.getContentTypes().addAll(methodResult.getResponseMediaTypes());

                methodResult.getResponses().add(defaultResponse);
            }

            // add Response results as well
            returnedElement.getPossibleValues().stream().filter(o -> o instanceof HttpResponse).map(o -> (HttpResponse) o).forEach(methodResult.getResponses()::add);
        } finally {
            lock.unlock();
        }
    }
708838
public final void add(ObservableDoubleValue dependency) {
        requireNonNull(dependency, "Parameter 'dependency' is null");

        if (!dependencies.contains(dependency)) {

            dependencies.add(dependency);
            bind(dependency);
            invalidate();

        } else {
            LOGGER.warn("Dependency already included: " + dependency + ", Skipping.");
        }
    }
681722
public void addDependency(Service service) {
        assertDuringInitialization();
        LOG.info("Adding a dependency on {} to {}", service.getName(), getName());
        addDependsOn(service);
        service.addDependedBy(this);
    }
1123658
@Override
    protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
        if (engine.getMode() != Mode.EVIDENCE_COLLECTION) {
            try {
                final Settings settings = engine.getSettings();
                final String[] tmp = settings.getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER);
                if (tmp != null) {
                    final List<String> skipEcosystems = Arrays.asList(tmp);
                    if (skipEcosystems.contains(DEPENDENCY_ECOSYSTEM)
                            && !settings.getBoolean(Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) {
                        LOGGER.debug("NodePackageAnalyzer enabled without a corresponding vulnerability analyzer");
                        final String msg = "Invalid Configuration: enabling the Node Package Analyzer without "
                                + "using the Node Audit Analyzer is not supported.";
                        throw new InitializationException(msg);
                    } else if (!skipEcosystems.contains(DEPENDENCY_ECOSYSTEM)) {
                        LOGGER.warn("Using the CPE Analyzer with Node.js can result in many false positives.");
                    }
                }
            } catch (InvalidSettingException ex) {
                throw new InitializationException("Unable to read configuration settings", ex);
            }
        }
    }
832058
public void setEngine(final ActionEngine engine) {
	if (!Objects.equals(this.engine, engine)) { // Only if changed
	    synchronized (contexts) {
		contexts.clear();
	    }
	}
	this.engine = engine;
    }