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

import data7.greycatmodel.Years;
import greycat.Action;
import greycat.Constants;
import greycat.TaskContext;
import greycat.internal.task.TaskHelper;
import greycat.struct.Buffer;

import java.text.ParseException;
import java.util.regex.Matcher;

import static data7.greycat.Utils.handleTraverseOneResult;
import static data7.greycat.Utils.vulnerabilityMatch;

public class ActionGetVulnerability implements Action {

    //Name declared for the Plugin
    public static final String NAME = "getVulnerabilityNode";

    private final String _vulnIdentifier;

    public ActionGetVulnerability(String vulnIdentifier) {
        _vulnIdentifier = vulnIdentifier;
    }

    @Override
    public void eval(TaskContext ctx) {
        String cve = ctx.template(_vulnIdentifier);
        Matcher m = vulnerabilityMatch(cve);
        if (m.find()) {
            String year = m.group(1);
            Years.find(ctx.graph(), ctx.world(), ctx.time(), year,
                    yearNodes ->
                            handleTraverseOneResult(ctx,
                                    yearNodes,
                                    () -> ctx.continueWith(ctx.newResult()),
                                    () -> yearNodes[0].findCves(cve, cveNodes -> {
                                                ctx.graph().freeNodes(yearNodes);
                                                handleTraverseOneResult(ctx, cveNodes,
                                                        () -> ctx.continueWith(ctx.newResult()),
                                                        () -> ctx.continueWith(ctx.wrap(cveNodes[0])));
                                            }
                                    )
                            ));
        } else {
            ctx.endTask(ctx.newResult(), new ParseException(_vulnIdentifier + " is not a cve", 0));
        }
    }

    @Override
    public void serialize(Buffer builder) {
        builder.writeString(NAME);
        builder.writeChar(Constants.TASK_PARAM_OPEN);
        TaskHelper.serializeString(_vulnIdentifier, builder, false);
        builder.writeChar(Constants.TASK_PARAM_CLOSE);
    }

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


}
