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 first engine created in a JVM 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.getLoopConfiguration()returns the engine’sRiskAssessmentLoopConfiguration(see Risk calculation).dispose()releases the engine.EngineimplementsAutoCloseable, andclose()does the same asdispose(), so you can create an engine in a try-with-resources statement. The threats and their risk values remain usable after the engine is closed.
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.
A catalog pattern that fails to initialize is skipped and logged with java.util.logging (level WARNING, Skipping pattern that failed to initialize: <pattern name>); in a standalone program, this message goes to the standard error output.
If the jar of sparta.queries is missing from the classpath, for example after you repackaged the libraries yourself, runAnalysis(ResourceSet) fails with IllegalStateException: Required VQL library not found on the classpath.
Catalog patterns that bind no data flow (for example the patterns of a STRIDE-per-element catalog) produce threats without a data flow (see Threats).
In 2026.2, runAnalysis still fails with a NullPointerException when a countermeasure with a non-empty scope applies to such a threat (see Which countermeasures apply).
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.getTef(), the threat event frequency, is not shown in the ThreatAnalysis view: it is the sum over all attacker profiles of their threat event frequency.For a threat without a data flow,
getDataFlow(),getDataFlowFrom()andgetDataFlowTo()returnnull, the name getters such asgetDataFlowName()return an empty string, andgetMatchType()only names the threatened element, for exampleP*.getThreatenedElementId()returns the ID of the threatened element in its model file (itsxmi:id, for example_S4cWwMk6EeeheeqXVGLgxA), so it stays the same when you analyze the same saved model again.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().
Changed in version 2026.2: getThreatenedElementId() returns the xmi:id of the element instead of a hash code that changed with every run, getTef() sums over all attacker profiles instead of returning the value of one profile, and threats can have no data flow.
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.
Threat.performRiskCalculationalways uses 1000 samples;SpartaRiskModel.calculateRisk(Threat, RiskAssessmentLoopConfiguration, int)takes another number of samples.The
RiskAssessmentLoopConfigurationholds the attacker profiles, data subject types and personal data types that the risk calculation iterates over. Each engine has its own (Engine.getLoopConfiguration()), so analyses of different models in the same JVM do not influence each other.runAnalysis(ResourceSet)andrunAnalysis(List<...> matchers)fill it with the attacker profiles, data subject types and personal data types in the engine’s scope;runAnalysis(Map<...>)does not. To calculate the risk of a threat yourself, fill the configuration withsetUpLoopParameters(engine)and pass it tothreat.performRiskCalculation(loopConfiguration).IRiskModel.calculateRisk(Threat, RiskAssessmentLoopConfiguration)calculates the risk of one threat.
Changed in version 2026.2: RiskAssessmentLoopConfiguration is no longer a global singleton: RiskAssessmentLoopConfiguration.getInstance() was removed, and Threat.performRiskCalculation, IRiskModel.calculateRisk and SpartaRiskModel.calculateRisk take the loop configuration as an argument (see Migrating from 2026.1).
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 only exports the package sparta.analysis.util with helper classes of its views, and it 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; a double quote inside a value is written twice, andnullbecomes an empty field. 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, with the same columns as the CSV writer. A
nullvalue, such as the data flow of a threat without a data flow, is written as the textnull.Changed in version 2026.2: Its columns are the same as those of the CSV writer: before,
Data Flowcame beforeFlow From,Namewas the raw threat type name, andRisk (potential)was missing.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(thexmi:idof the element),dataFlowName,dataFlowFromName,dataFlowToName.CQThreatJSONWriterUsage:
new CQThreatJSONWriter(Writer);write(Threat...)(Javadoc).Output: a code-quality JSON array with
description,fingerprint,severityandlocationper threat.location.pathis the path of the model relative to the working directory (user.dir) if the model is in that directory or one of its subdirectories, and the full path otherwise (see Command-line tools). Fails with aNullPointerExceptionfor a threat without a data flow.ReportWriterUsage:
new ReportWriter().performExport(File dir, ResourceSet model, List<? extends Threat> threats)(Javadoc).Output: the LaTeX report described in Analysis results and exports, in UTF-8.
performExportthrows anIOExceptionand stops at the first error; it also fails for a threat without a data flow.Changed in version 2026.2:
performExportdeclaresthrows IOException; before, it printed errors and continued with a partial report.
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 writers do not choose a character encoding: pass a Writer with the encoding you need.
Code examples, including one with custom columns, are in Exporting threat results.
Changed in version 2026.2: The CSV and text writers no longer use the default locale of the JVM to format numbers, and the CSV writer escapes double quotes.
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.2.
Changed in version 2026.2: The unused classes DescriptionDiagramTemplate and DescriptionDiagramItemTemplate of the package sparta.io.templates were removed.