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 page has the following sections; each starts with a note that names the plug-ins, standalone libraries and packages of its classes:

Meta-model

The classes of SPARTA models.

Threat elicitation and risk analysis

Eliciting the threats of a model, calculating their risk, and reading the results.

Aggregated risk analyses

Figures over a collection of threats, such as the total risk and the risk reduction.

Exporting results

Writing threats to CSV, text files, XLSX, JSON and a LaTeX report.

Creating models from YAML descriptions

Converting a simple text description of a data flow diagram into a SPARTA model.

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

Note

Plug-in sparta.spartamodel, standalone library sparta-model; packages sparta.spartamodel, sparta.spartamodel.impl and sparta.spartamodel.util.

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, it is registered through an extension of the plug-in; 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

Note

Plug-ins sparta.core and sparta.queries, standalone library sparta-core; packages sparta.core and its subpackages, and sparta.queries. StandaloneRuntime is in the standalone library sparta-cli (package sparta.cli.runtime) and has no plug-in.

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). A countermeasure with a non-empty scope never applies to such a threat, because its scope is checked against the roles bound to the data flow of the threat (see Which countermeasures apply).

Running the analysis outside Eclipse

In a standalone program, the static methods of StandaloneRuntime set up EMF and VIATRA, load a model with the catalogs it references, and run the analysis with an Engine. They are described in Using sparta-cli as a library.

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. It also contains DfdStructure (see Model structure).

  • 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().

  • getMitigations() returns the countermeasures taken into account for calculating the risk of the threat (see Risk calculation).

Check isRiskCalculated() before you read the risk values of a threat: the risk getters, such as getRisk() and getVulnerability(), and getMitigations() throw an IllegalStateException when the risk of the threat was not calculated. This is the case for the threats that runAnalysis(Map<...>) returns, and for a threat without a threatened element, for which the risk calculation is skipped. For such a threat, toString() ends with (risk not calculated).

Changed in version 2026.3: The risk getters throw an IllegalStateException instead of a NullPointerException when the risk was not calculated, and Threat has the new methods isRiskCalculated() and getMitigations(). The protected method Threat.getElementName(String) was removed.

Model structure

sparta.core.model.DfdStructure has static methods that derive the position of elements and threats in the trust boundaries of a DFD model from the containment of the model elements:

  • parent(EObject) returns the direct DFD parent of an element (a trust boundary, or the process of a decomposed process), or null at the top level of the model.

  • trustBoundaries(EObject) returns the trust boundaries that enclose an element, outermost first, and trustBoundaryDepth(EObject) their number.

  • crossesTrustBoundary(EObject, EObject) tells whether a data flow between two elements crosses a trust boundary, that is, whether the two elements are not enclosed by the same trust boundaries. crossesTrustBoundary(Threat) applies it to the sender and recipient of the data flow of a threat, and returns null for a threat without such a data flow.

  • involvedElements(Threat) returns the sender and recipient of the data flow of a threat, or the threatened element for a threat without a data flow.

  • minTrustBoundaryDepth(Threat) and maxTrustBoundaryDepth(Threat) return the lowest and highest trustBoundaryDepth of the elements that involvedElements(Threat) returns.

All methods of DfdStructure accept null elements and threats without a data flow. crossesTrustBoundary only compares the elements themselves; the built-in query flowContainerDiff of DFDQueries.vql (see Built-in queries) also considers the elements that a data flow reaches through sender and recipient specifications.

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, and IRiskModel.isCalculated() tells whether it has done so. The getters of SpartaRiskModel throw an IllegalStateException until the risk is calculated.

  • Each threat has its own risk model. IRiskModel.getMitigations() returns the countermeasures that the risk calculation of that threat took into account, as a list of Mitigation records (package sparta.core.analysis); Threat.getMitigations() returns the same list. A Mitigation holds the countermeasure (counterMeasure()) and the role binding of the threatened element through which it applies (binding()); solution() returns the solution that contains the role binding, or null. RiskCalculation.mitigations(DataFlow, ThreatType, List<RoleBinding>) selects these countermeasures, with RiskCalculation.mitigates(CounterMeasure, ThreatType) and RiskCalculation.isInScope(CounterMeasure, DataFlow); which countermeasures apply is explained in Which countermeasures apply.

Changed in version 2026.3: IRiskModel has the new methods isCalculated() and getMitigations(), which your own implementations must provide.

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

Note

Plug-in sparta.threatanalysis, standalone library sparta-analysis; package sparta.analysis. Despite its name, the package sparta.analysis 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.

The plug-in sparta.threatanalysis provides aggregated risk analyses over collections of threats, based on the risk values that are calculated for the individual threats (see Risk calculation).

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. If the collection contains a threat whose risk was not calculated (see Threats), the methods that sum risk values, and categorize, throw an IllegalStateException.

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.

Exporting results

Note

Plug-in sparta.io, standalone library sparta-io; packages sparta.io, sparta.io.diagram and sparta.io.templates.

The plug-in sparta.io provides writers with which you export threat analysis results to CSV, text files, XLSX, JSON and a LaTeX report. Code examples, including one with custom columns, are in Exporting threat results.

Writers

The writers 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. A value that starts with =, +, -, @, a tab or a carriage return gets a ' in front, so that spreadsheet applications do not run it as a formula; this does not apply to the column headers. One row per threat, with the default columns unless you choose others (see Columns).

ThreatTextWriter

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

Output: one line per column, with the column header, a colon, a tab character and the value (see Columns).

ThreatXlsxOutputStream

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

Output: one sheet with one row per threat, with the same columns as the CSV writer (see Columns). Numbers and booleans are written as numeric and boolean cells, other values as text, and a null value, such as the data flow of a threat without a data flow, leaves the cell empty.

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.

ReportWriter

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

Output: the LaTeX report described in Analysis results and exports, in UTF-8. For a threat whose risk was not calculated, the report shows -- as the risk. performExport throws an IOException and stops at the first error.

The text of the report comes from the templates in the package sparta.io.templates. The report also contains the data flow diagram of the model as a TikZ picture, which ReportWriter creates with the classes of the package sparta.io.diagram: AirdLayout reads the positions of the elements from the Sirius representations file (.aird) that you pass to setAird, and DfdTikzGenerator draws the diagram with these positions. Without an .aird file, or when it cannot be read, DfdTikzGenerator computes a layout itself, which is the same on every export.

Columns

The CSV, text and XLSX writers write the same information for every threat, divided into columns that each represent a different type of information, such as the threat type or the risk. Each column has a header and a function that computes its value from the threat. In a CSV file or an XLSX sheet, the columns form a table with one row per threat and the headers in the first row; a text file lists them as one line per column, with the header and the value. ThreatJsonWriter and ReportWriter do not use columns.

The default columns are Type, Name, Location, Flow From, Data Flow, Flow To, Vulnerability, Risk, Risk (lower), Risk (upper) and Risk (potential). To write other columns, pass a Map<String, Function<Threat, ? extends Object>> as second constructor argument: the keys become the column headers, and the functions compute the values. Use a LinkedHashMap to control the column order. Model elements are written as their name.

The class ThreatExportColumns provides ready-made column maps, which you can extend:

ThreatExportColumns.defaults()

Returns the default columns as a new LinkedHashMap.

ThreatExportColumns.withMetadata()

Returns the default columns followed by the columns Crosses Trust Boundary, Trust Boundary Depth (min), Trust Boundary Depth (max), Flow From Parent, Flow To Parent, Flow From Trust Boundaries, Flow To Trust Boundaries and Mitigating Solutions, the columns of the CSV and XLSX exports of the ThreatAnalysis view and of sparta-cli:

  • The first five come from DfdStructure (see Model structure).

  • The trust boundaries of an element are written as their names, outermost first, separated by >, for example Backend > Payments for an element in the trust boundary Payments inside Backend.

  • Mitigating Solutions lists, separated by commas, the solutions whose countermeasures the risk calculation of the threat took into account (Threat.getMitigations()), by the name of their solution type, or by their own name if they have no solution type.

The class ThreatMetadata provides the values of the trust boundary and Mitigating Solutions columns for your own columns.

Output format

  • The CSV and text writers write a number with a period as decimal separator, at most four decimals and no grouping separator.

  • The writers do not choose a character encoding: pass a Writer with the encoding you need.

Caution

The CSV, text and XLSX writers fail for a threat whose risk was not calculated (see Threats), because the default columns contain risk values; ThreatJsonWriter fails as well, because it reads the risk getters of the threat.

Changed in version 2026.3: The GitLab Code Quality export (CQThreatJSONWriter and the package sparta.io.json) was removed. The CSV writer puts a ' in front of values that a spreadsheet would run as a formula, the CSV and text writers no longer write grouping separators in numbers, and the XLSX writer leaves the cell of a null value empty instead of writing null. ReportWriter adds the data flow diagram to the report.

Creating models from YAML descriptions

Note

Plug-in sparta.io, standalone library sparta-io; package sparta.io.convert.

The class YmlToEmfConverter creates a SPARTA model from a YAML file with the keys processes, dataStores, externalEntities and dataFlows; each data flow is written as Sender->Recipient. sparta-ci uses it for models in the .txt format (see Command-line tools).

  • YmlToEmfConverter.convert(File workingDir, String file) reads the file (relative to workingDir unless it is absolute), saves the model as dfd.sparta in workingDir, and returns that file.

  • convert(String file) does the same in the working directory of the JVM (user.dir).

The model refers to the threat specification catalog in ThreatSpecification.sparta, which must be in workingDir as well. The converter throws an IOException that names the file when the file is empty or is not valid YAML, and an IllegalArgumentException when a data flow refers to an element that the file does not declare.

Changed in version 2026.3: YmlToEmfConverter works: its constructor and saveToModel were replaced by the static convert methods.