SPARTA Java API

This page describes the Java classes that you use to work with SPARTA models, to run the threat elicitation and risk analysis, and to process the results. The classes are the same in Eclipse and outside Eclipse, because the standalone libraries contain the jars of the Eclipse plug-ins. Only the way you add them to your project differs: as plug-in dependencies in Eclipse (see SPARTA in Eclipse), or as Maven dependencies in a standalone program (see SPARTA Standalone libraries).

Note

All plug-in and package names on this page are abbreviated: they all start with be.kuleuven.cs.distrinet.. For example, sparta.core stands for be.kuleuven.cs.distrinet.sparta.core.

The API consists of the following components:

Meta-model

Plug-in sparta.spartamodel, standalone library sparta-model.

Threat elicitation and risk analysis

Plug-ins sparta.core and sparta.queries, standalone library sparta-core.

Aggregated risk analyses

Plug-in sparta.threatanalysis, standalone library sparta-analysis.

Exporters

Plug-in sparta.io, standalone library sparta-io.

Code for common tasks, such as creating a model or running the analysis, is in Development scenarios. The Javadoc is described in API documentation.

Meta-model

The package sparta.spartamodel contains the EMF interfaces of the SPARTA meta-model (DFDModel, Process, DataFlow, ThreatTypeCatalog, …), sparta.spartamodel.impl their implementations, and sparta.spartamodel.util the resource factory. The meta-model itself is described in Advanced concepts in SPARTA.

  • SpartaModelPackage is the generated EMF package class, with the namespace URI http://distrinet.cs.kuleuven.be/spartamodel.

  • Use SpartaModelFactory.eINSTANCE to create model elements (Javadoc).

  • SpartaModelResourceFactoryImpl reads and writes models in files with the extension .sparta and the older extension .securitydfd. In Eclipse, the plug-in registers it; in a standalone program, you register it yourself (see Setting up a standalone program).

Tip

Import be.kuleuven.cs.distrinet.sparta.spartamodel.Process explicitly. With a wildcard import of the spartamodel package, the name Process is ambiguous with java.lang.Process and the code does not compile.

Threat elicitation and risk analysis

The engine

The class sparta.core.Engine elicits the threats of a model and calculates their risk (Javadoc). It has the following main public methods:

  • Engine(ResourceSet) and Engine(EMFScope) create an engine on a model. The constructor also initializes the VIATRA pattern language for standalone use (EMFPatternLanguageStandaloneSetup.doSetup()); the code warns not to use it when the VIATRA Query tooling is loaded, for example in an Eclipse IDE with the VIATRA Query SDK installed.

  • runAnalysis(ResourceSet) runs the patterns of the threat type catalogs and the built-in matchers of the legacy key-based threat types, calculates the risk of the resulting threats, and returns them as a List<Threat>. Use this method unless you need one of the variants below.

  • runAnalysis(List<...> matchers) runs only the given VIATRA matchers, for example those of getPatternMatchers() or of patterns that you compiled yourself, converts their matches into threats, and calculates their risk.

  • runAnalysis(Map<ThreatPatternMatchMetadata, PatternParsingResults>) runs patterns parsed by PatternProcessor and creates PatternThreat objects, without calculating their risk.

  • getPatternMatchers() returns the built-in matchers of the legacy key-based threat types.

  • getMatcherOnEngine(...) and getVQMatcherOnEngine(...) return a matcher on the engine’s VIATRA query engine.

  • dispose() releases the engine. Call it when you no longer need the engine.

The engine considers every threat type catalog in its scope, that is, in the ResourceSet (or EMFScope) passed to the constructor, whether or not the model links to it. The ResourceSet argument of runAnalysis is not used for this. Without a catalog, the analysis finds no threats. Loading a model with resourceSet.getResource(uri, true) followed by EcoreUtil.resolveAll(resourceSet) also loads the catalogs that the model references; see Pairing existing threat type catalogs.

The package sparta.core.patterns processes the VQL patterns of the catalogs: PatternProcessor finds the threat type catalogs in the scope of the engine and parses their patterns. How to write these patterns is described in Writing threat type patterns.

Note

In 2026.0, every threat must have a data flow. A catalog pattern that binds no data flow (for example the patterns of a STRIDE-per-element catalog) makes runAnalysis fail with a NullPointerException. In Eclipse, the ThreatAnalysis view shows such threats, but the CSV and report exports fail (see Analysis results and exports).

Threats

The package sparta.core.model contains the classes that represent elicited threats: Threat and its subclass PatternThreat (for threats found by catalog patterns), the interfaces IThreat and IInteractionThreat, and the classes Attacker and CustomEstimate.

  • Threat (Javadoc) gives access to the threat type (getThreatType(), getThreatTypeName(), getThreatName()), the description (getDescription()), the location (getThreatenedElement(), getDataFlow(), getDataFlowFrom(), getDataFlowTo(), and getMatchType(), the interaction signature such as EE*-DF->P, where * marks the threatened element) and the risk values (getRisk(), getRisk_lower(), getRisk_upper(), getPotentialRisk(), getVulnerability(), getVulnerability_lower(), getVulnerability_upper(), getSle(), getTef(), getLef()). The meaning of these values is explained in How SPARTA computes risk.

  • For a PatternThreat (Javadoc), getThreatTypeName() is the name of the top-level threat type group and getThreatName() the name of the matched threat type, both with placeholders replaced by element names, and getDescription() is the catalog description with its placeholders filled in (getFullDescription() adds the long description and the risk values).

  • For a plain Threat from a legacy key-based threat type, getThreatTypeName() and getThreatName() are both the name of the threat type, and getDescription() returns the same text as toString().

Risk calculation

The packages sparta.core.analysis and sparta.core.analysis.risk contain the Monte Carlo risk calculation: RiskCalculation, RiskAssessmentLoopConfiguration, the BetaPERT distribution (BetaPERT), Clopper-Pearson confidence intervals (BinomialConfidence), and the risk model interface IRiskModel with its implementation SpartaRiskModel. How the risk is computed is explained in How SPARTA computes risk.

  • The engine always uses SpartaRiskModel. A subclass of Threat can pass another risk model to the protected constructor Threat(IPatternMatch, IRiskModel).

  • The risk calculation is a Monte Carlo simulation with 1000 samples per estimate and no fixed seed, so the risk values differ slightly between runs. The number of samples is fixed in 2026.0.

  • The risk configuration is global (RiskAssessmentLoopConfiguration is a singleton that runAnalysis re-initializes), so do not run several analyses concurrently in the same JVM.

Built-in queries

The plug-in sparta.queries contains the built-in VIATRA queries that SPARTA runs on a model, in the package sparta.queries. They are defined in four files:

DFDQueries.vql

The interactions between DFD elements over data flows (for example processToDataStoreComm), which the engine uses for the legacy key-based threat types, and helper patterns.

DataQueries.vql

Queries on data types, personal data types, data subjects and their assignment to DFD elements.

AttackerProfileQueries.vql

Queries on attacker profiles.

PatternSupport.vql

Queries on threat type catalogs and their threat types, used to find the catalog patterns.

The Java code of these queries is generated during the build (see Building SPARTA from source). You can use the generated query classes in your own code, and import their patterns in your own VQL files. The patterns of threat type catalogs can also use the patterns of DFDQueries.vql.

Aggregated risk analyses

The plug-in sparta.threatanalysis provides support for aggregated risk analyses over collections of threats, based on the risk values that sparta.core calculates for individual threats.

Note

The classes are in the package sparta.analysis, which belongs to the plug-in sparta.threatanalysis. The plug-in sparta.analysis is the Eclipse user interface; it exports no packages and is not available as a standalone library.

sparta.analysis.ThreatAggregationAnalysis (Javadoc) takes a Collection<Threat> in its constructor (null counts as empty). Its risk aggregates sum the scalar risk values of the threats: “risk” is each threat’s getRisk() (the expected residual risk) and “potential risk” is its getPotentialRisk(). The lower and upper bounds of the risk are not used.

Examples of supported analyses are:

Threat counts

getThreatCount(), getThreatCountPerThreatType(), getThreatCountPerModelElementType() and getThreatCountPerModelElement(), and the shares (0..1) getThreatCountPctPerThreatType() and getThreatCountPctPerModelElementType(). Averages are given by getAverageThreatCounterPerElement() and getAverageThreatCountPerModelElementType().

Element counts

getModelElementTypeCount(), getDFDElementTypeCount(), getModelElementTypes(), getThreatTypeCount() and getThreatTypes(). The threat list can also be used to get an indication of the size of the original DFD model. This cannot take into account elements that are not involved in any threat whatsoever.

Potential risk

getTotalPotentialRisk(), getPotentialRiskPerThreatType() and getPotentialRiskPerModelElementType().

Residual or actual risk

getTotalRisk(), getRiskPerThreatType() and getRiskPerModelElementType().

Risk reduction

getTotalRiskReductionPct(), getRiskReductionPctPerThreatType() and getRiskReductionPctPerModelElementType(): (potential risk - risk) / potential risk, as a fraction between 0 and 1 (NaN when the potential risk is 0).

Risk classes

categorize(Threat, int classes) returns the risk of a threat relative to the highest potential risk in the collection, rounded to a class between 0 and classes.

Map keys are as follows:

  • ThreatType keys are the matched threat types (Threat.getThreatType()), not the top-level groups. For catalog patterns, their raw names can contain placeholders such as <$location$> spoofed.

  • Element type keys (Map<Class<? extends ModelElement>, ...>) are the EMF implementation classes, for example ProcessImpl.class.

The deprecated static method analyze(Collection<Threat>) computes some values but produces no output. The class IThreatAggregationAnalysis (a class, despite its name) offers similar methods with String keys for collections of IThreat; SPARTA itself does not use it.

Exporters

The plug-in sparta.io exports threat analysis results to various output formats. The classes are in the package sparta.io:

ThreatCSVWriter

Usage: new ThreatCSVWriter(Writer); call writeHeader() and then write(Threat...) (Javadoc).

Output: CSV with ; as separator and every field in double quotes. Default columns: Type, Name, Location, Flow From, Data Flow, Flow To, Vulnerability, Risk, Risk (lower), Risk (upper), Risk (potential).

ThreatTextWriter

Usage: new ThreatTextWriter(Writer); write(Threat); static fileNameSuggestion(Threat) (Javadoc).

Output: one line per column, with the column name, a colon, a tab character and the value; the columns are the same as those of the CSV writer.

ThreatXlsxOutputStream

Usage: new ThreatXlsxOutputStream(OutputStream); write(Threat...); the workbook is written on close() (Javadoc).

Output: one sheet with numeric cells. Columns: Type, Name (the raw threat type name), Location, Data Flow, Flow From, Flow To, Vulnerability, Risk, Risk (lower), Risk (upper). With the Maven dependencies of sparta-io 2026.0.0, this class fails; see Known limitation: XLSX export.

ThreatJsonWriter<T extends IThreat>

Usage: new ThreatJsonWriter<>(Writer, Class<T>); write(List<T>) or writePretty(List<T>) (Javadoc).

Output: a JSON array with the properties of the getters of T. With IInteractionThreat: threatTypeName, threatName, description, vulnerability, risk, potentialRisk, threatenedElementName, threatenedElementTypeName, threatenedElementId, dataFlowName, dataFlowFromName, dataFlowToName.

CQThreatJSONWriter

Usage: new CQThreatJSONWriter(Writer); write(Threat...) (Javadoc).

Output: a code-quality JSON array with description, fingerprint, severity and location per threat (see Command-line tools). location.path is the model path relative to the working directory (user.dir); the model must be below it.

ReportWriter

Usage: new ReportWriter().performExport(File dir, ResourceSet model, List<? extends Threat> threats) (Javadoc).

Output: the LaTeX report described in Analysis results and exports.

ThreatCSVWriter, ThreatTextWriter and ThreatXlsxOutputStream also accept a Map<String, Function<Threat, ? extends Object>> as second constructor argument to define your own columns: the keys become the column headers. Use a LinkedHashMap to control the column order. Model elements are written as their name. The CSV and text writers format numbers with the default locale of the JVM and at most 4 decimals (for example 12,345.6789 in en-US and 12.345,6789 in nl-BE). Code examples, including one with custom columns, are in Exporting threat results.

The package sparta.io.convert contains YmlToEmfConverter, which is meant to create a SPARTA model from a YAML description of processes, data stores, external entities and data flows. The converter fails with a NullPointerException (it creates a SnakeYAML Representer without options), so do not rely on it; this is a known limitation of 2026.0.