data7-master/graph/greycat/src/main/java/data7/greycat/actions/ActionCreateVulnerabilityNode.java
package data7.greycat.actions;

import data7.greycatmodel.CVENode;
import data7.greycatmodel.Cwes;
import data7.greycatmodel.YearNode;
import data7.model.vulnerability.Vulnerability;
import greycat.Action;
import greycat.TaskContext;
import greycat.struct.Buffer;
import greycat.struct.StringArray;

import static data7.greycat.Utils.handleTraverseOneResult;

public class ActionCreateVulnerabilityNode implements Action {
    public static final String NAME = "createVulnerabilityNode";
    private final Vulnerability _vulnerability;

    public ActionCreateVulnerabilityNode(Vulnerability p_vulnerability) {
        this._vulnerability = p_vulnerability;
    }

    @Override
    public void eval(TaskContext ctx) {
        if (ctx.result().size() > 0 && ctx.result().get(0) instanceof YearNode) {
            ctx.setTime(_vulnerability.getCreationTime());
            CVENode node = CVENode.create(ctx.world(), ctx.time(), ctx.graph());
            node.setIdentifier(_vulnerability.getCve());
            node.setDescription(_vulnerability.getDescription());
            node.setScore(_vulnerability.getScore());
            StringArray bugs = node.getOrCreateBugIds();
            bugs.addAll(_vulnerability.getBugIds().toArray(new String[_vulnerability.getBugIds().size()]));
            YearNode yearNode = (YearNode) ctx.result().get(0);
            yearNode.indexCves(node);
            if (_vulnerability.getCwe() != null) {
                Cwes.find(ctx.graph(), ctx.world(), ctx.time(), _vulnerability.getCwe(),
                        cweNodes ->
                                handleTraverseOneResult(ctx, cweNodes,
                                        () -> ctx.continueWith(ctx.wrap(node)),
                                        () -> cweNodes[0].indexCves(node,
                                                cweNode -> {
                                                    cweNode.free();
                                                    ctx.continueWith(ctx.wrap(node));
                                                })
                                )
                );
            } else {
                ctx.continueWith(ctx.wrap(node));
            }
        } else {
            ctx.endTask(ctx.result(), new IllegalArgumentException("Invalid current result to call this action"));
        }
    }

    @Override
    public void serialize(Buffer builder) {
        throw new RuntimeException("Remote injection not supported.");
    }

    @Override
    public String name() {
        return NAME;
    }
}
