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 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 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.

  • getLoopConfiguration() returns the engine’s RiskAssessmentLoopConfiguration (see Risk calculation).

  • dispose() releases the engine. Engine implements AutoCloseable, and close() does the same as dispose(), 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(), 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. 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() and getDataFlowTo() return null, the name getters such as getDataFlowName() return an empty string, and getMatchType() only names the threatened element, for example P*.

  • getThreatenedElementId() returns the ID of the threatened element in its model file (its xmi: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 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().

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 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. Threat.performRiskCalculation always uses 1000 samples; SpartaRiskModel.calculateRisk(Threat, RiskAssessmentLoopConfiguration, int) takes another number of samples.

  • The RiskAssessmentLoopConfiguration holds 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) and runAnalysis(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 with setUpLoopParameters(engine) and pass it to threat.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.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 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() 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; a double quote inside a value is written twice, and null becomes an empty field. 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, with the same columns as the CSV writer. A null value, such as the data flow of a threat without a data flow, is written as the text null.

Changed in version 2026.2: Its columns are the same as those of the CSV writer: before, Data Flow came before Flow From, Name was the raw threat type name, and Risk (potential) was missing.

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 (the xmi:id of the element), 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. location.path is 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 a NullPointerException for a threat without a data flow.

ReportWriter

Usage: 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. performExport throws an IOException and stops at the first error; it also fails for a threat without a data flow.

Changed in version 2026.2: performExport declares throws 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.