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 librarysparta-model.- Threat elicitation and risk analysis
Plug-ins
sparta.coreandsparta.queries, standalone librarysparta-core.- Aggregated risk analyses
Plug-in
sparta.threatanalysis, standalone librarysparta-analysis.- Exporters
Plug-in
sparta.io, standalone librarysparta-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.
SpartaModelPackageis the generated EMF package class, with the namespace URIhttp://distrinet.cs.kuleuven.be/spartamodel.Use
SpartaModelFactory.eINSTANCEto create model elements (Javadoc).SpartaModelResourceFactoryImplreads and writes models in files with the extension.spartaand 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)andEngine(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 aList<Threat>. Use this method unless you need one of the variants below.runAnalysis(List<...> matchers)runs only the given VIATRA matchers, for example those ofgetPatternMatchers()or of patterns that you compiled yourself, converts their matches into threats, and calculates their risk.runAnalysis(Map<ThreatPatternMatchMetadata, PatternParsingResults>)runs patterns parsed byPatternProcessorand createsPatternThreatobjects, without calculating their risk.getPatternMatchers()returns the built-in matchers of the legacy key-based threat types.getMatcherOnEngine(...)andgetVQMatcherOnEngine(...)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.1, 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(), andgetMatchType(), the interaction signature such asEE*-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 andgetThreatName()the name of the matched threat type, both with placeholders replaced by element names, andgetDescription()is the catalog description with its placeholders filled in (getFullDescription()adds the long description and the risk values).For a plain
Threatfrom a legacy key-based threat type,getThreatTypeName()andgetThreatName()are both the name of the threat type, andgetDescription()returns the same text astoString().
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 ofThreatcan pass another risk model to the protected constructorThreat(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.1.
The risk configuration is global (
RiskAssessmentLoopConfigurationis a singleton thatrunAnalysisre-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.vqlThe 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.vqlQueries on data types, personal data types, data subjects and their assignment to DFD elements.
AttackerProfileQueries.vqlQueries on attacker profiles.
PatternSupport.vqlQueries 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()andgetThreatCountPerModelElement(), and the shares (0..1)getThreatCountPctPerThreatType()andgetThreatCountPctPerModelElementType(). Averages are given bygetAverageThreatCounterPerElement()andgetAverageThreatCountPerModelElementType().- Element counts
getModelElementTypeCount(),getDFDElementTypeCount(),getModelElementTypes(),getThreatTypeCount()andgetThreatTypes(). 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()andgetPotentialRiskPerModelElementType().- Residual or actual risk
getTotalRisk(),getRiskPerThreatType()andgetRiskPerModelElementType().- Risk reduction
getTotalRiskReductionPct(),getRiskReductionPctPerThreatType()andgetRiskReductionPctPerModelElementType(): (potential risk - risk) / potential risk, as a fraction between 0 and 1 (NaNwhen 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 andclasses.
Map keys are as follows:
ThreatTypekeys 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 exampleProcessImpl.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:
ThreatCSVWriterUsage:
new ThreatCSVWriter(Writer); callwriteHeader()and thenwrite(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).ThreatTextWriterUsage:
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.
ThreatXlsxOutputStreamUsage:
new ThreatXlsxOutputStream(OutputStream);write(Threat...); the workbook is written onclose()(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 ofsparta-io2026.1.0, this class fails; see Known limitation: XLSX export.ThreatJsonWriter<T extends IThreat>Usage:
new ThreatJsonWriter<>(Writer, Class<T>);write(List<T>)orwritePretty(List<T>)(Javadoc).Output: a JSON array with the properties of the getters of
T. WithIInteractionThreat:threatTypeName,threatName,description,vulnerability,risk,potentialRisk,threatenedElementName,threatenedElementTypeName,threatenedElementId,dataFlowName,dataFlowFromName,dataFlowToName.CQThreatJSONWriterUsage:
new CQThreatJSONWriter(Writer);write(Threat...)(Javadoc).Output: a code-quality JSON array with
description,fingerprint,severityandlocationper threat (see Command-line tools).location.pathis the model path relative to the working directory (user.dir); the model must be below it.ReportWriterUsage:
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.1.