Example project

This page shows a complete standalone project that uses the SPARTA libraries: a small Java program that:

  1. initializes EMF,

  2. creates a DFD model of a web shop,

  3. links a threat type catalog to the model and saves the model,

  4. runs the threat elicitation and risk analysis,

  5. prints the threats and some aggregates, and

  6. exports the threats to a CSV file.

The individual steps are explained in Development scenarios. The project was compiled and run against the SPARTA 2026.2.0 libraries from the SPARTA Maven repository, with Java 21.

Project layout

The project is a regular Maven project with one class, and the threat type catalog next to the pom.xml file:

example-project/
├── pom.xml
├── stride-per-interaction - Shostack.sparta
└── src/main/java/com/example/sparta/ExampleApp.java

The threat type catalog explains where to download the catalog. The program reads the catalog from, and writes webshop.sparta and threats.csv to, the directory it runs in, so run it from the project directory (see Running the example).

The pom.xml file

First create a new Maven project. The following pom.xml file imports the standalone BOM, and adds the SPARTA Maven repository, the Eclipse repository that provides VIATRA, and the SPARTA libraries that the program uses.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.sparta</groupId>
    <artifactId>example-project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SPARTA Example project</name>

    <properties>
        <maven.compiler.release>21</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <sparta.version>2026.2.0</sparta.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- the versions of the third-party libraries that SPARTA is built with -->
            <dependency>
                <groupId>be.kuleuven.cs.distrinet.sparta</groupId>
                <artifactId>standalone</artifactId>
                <version>${sparta.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- meta-model: create, load and save models -->
        <dependency>
            <groupId>be.kuleuven.cs.distrinet.sparta</groupId>
            <artifactId>sparta-model</artifactId>
            <version>${sparta.version}</version>
        </dependency>
        <!-- threat elicitation and risk analysis -->
        <dependency>
            <groupId>be.kuleuven.cs.distrinet.sparta</groupId>
            <artifactId>sparta-core</artifactId>
            <version>${sparta.version}</version>
        </dependency>
        <!-- aggregate analyses -->
        <dependency>
            <groupId>be.kuleuven.cs.distrinet.sparta</groupId>
            <artifactId>sparta-analysis</artifactId>
            <version>${sparta.version}</version>
        </dependency>
        <!-- exporters -->
        <dependency>
            <groupId>be.kuleuven.cs.distrinet.sparta</groupId>
            <artifactId>sparta-io</artifactId>
            <version>${sparta.version}</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>sparta-repository</id>
            <url>https://maven.sparta.distrinet-research.be</url>
        </repository>
        <!-- VIATRA is not available from Maven Central -->
        <repository>
            <id>eclipse</id>
            <url>https://repo.eclipse.org/content/groups/releases/</url>
        </repository>
    </repositories>
</project>

Some remarks:

  • sparta-io already depends on the other three libraries, so it would be enough on its own; the example lists all four because it uses classes from each of them. A program that only creates, loads and saves models only needs sparta-model.

  • The import of the standalone BOM is required: without it, the analysis fails with a SecurityException (see Standalone Prerequisites).

  • The libraries are compiled for Java 21, so the project needs maven.compiler.release 21 or later and a JDK 21 or later.

  • The project does not need the Tycho plug-in. Maven may print warnings that it cannot access repositories “with type p2”; you can ignore these (see Standalone Prerequisites).

  • If your local Maven repository is in a folder whose path contains a space, such as C:\Users\Jane Doe\.m2, the analysis fails (see Standalone Prerequisites).

The threat type catalog

Without a threat type catalog, the analysis finds no threats. The example uses the STRIDE-per-interaction catalog from the catalogs repository (see Installing SPARTA): download STRIDE/STRIDE-per-interaction/Shostack/stride-per-interaction - Shostack.sparta and put it in the project directory. To use another catalog, pass its path as the first program argument.

The ExampleApp class

Create the class com.example.sparta.ExampleApp in src/main/java:

ExampleApp.java
  1package com.example.sparta;
  2
  3import java.io.BufferedWriter;
  4import java.io.File;
  5import java.io.FileWriter;
  6import java.io.IOException;
  7import java.util.Collections;
  8import java.util.List;
  9import java.util.Map;
 10
 11import org.eclipse.emf.common.util.URI;
 12import org.eclipse.emf.ecore.resource.Resource;
 13import org.eclipse.emf.ecore.resource.ResourceSet;
 14import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
 15import org.eclipse.emf.ecore.xmi.XMLResource;
 16
 17import be.kuleuven.cs.distrinet.sparta.analysis.ThreatAggregationAnalysis;
 18import be.kuleuven.cs.distrinet.sparta.core.Engine;
 19import be.kuleuven.cs.distrinet.sparta.core.model.Threat;
 20import be.kuleuven.cs.distrinet.sparta.io.ThreatCSVWriter;
 21import be.kuleuven.cs.distrinet.sparta.spartamodel.DFDModel;
 22import be.kuleuven.cs.distrinet.sparta.spartamodel.DataFlow;
 23import be.kuleuven.cs.distrinet.sparta.spartamodel.DataStore;
 24import be.kuleuven.cs.distrinet.sparta.spartamodel.ExternalEntity;
 25import be.kuleuven.cs.distrinet.sparta.spartamodel.ModelElement;
 26import be.kuleuven.cs.distrinet.sparta.spartamodel.Process;
 27import be.kuleuven.cs.distrinet.sparta.spartamodel.SpartaModelFactory;
 28import be.kuleuven.cs.distrinet.sparta.spartamodel.SpartaModelPackage;
 29import be.kuleuven.cs.distrinet.sparta.spartamodel.ThreatTypeCatalog;
 30import be.kuleuven.cs.distrinet.sparta.spartamodel.TrustBoundaryContainer;
 31import be.kuleuven.cs.distrinet.sparta.spartamodel.util.SpartaModelResourceFactoryImpl;
 32
 33public class ExampleApp {
 34
 35    public static void main(String[] args) throws IOException {
 36        File catalogFile = new File(args.length > 0 ? args[0] : "stride-per-interaction - Shostack.sparta");
 37        File modelFile = new File("webshop.sparta");
 38        File csvFile = new File("threats.csv");
 39
 40        // 1. Initialize EMF (once per JVM)
 41        SpartaModelPackage.eINSTANCE.eClass();
 42        Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap()
 43                .put("sparta", new SpartaModelResourceFactoryImpl());
 44
 45        // 2. Create the model
 46        DFDModel dfd = createModel();
 47
 48        // 3. Load the threat type catalog, link it to the model and save the model
 49        ResourceSet resourceSet = new ResourceSetImpl();
 50        Resource catalogResource = resourceSet.getResource(
 51                URI.createFileURI(catalogFile.getAbsolutePath()), true);
 52        catalogResource.getContents().stream()
 53                .filter(ThreatTypeCatalog.class::isInstance)
 54                .map(ThreatTypeCatalog.class::cast)
 55                .forEach(dfd.getResource()::add);
 56
 57        Resource modelResource = resourceSet.createResource(URI.createFileURI(modelFile.getAbsolutePath()));
 58        modelResource.getContents().add(dfd);
 59        modelResource.save(Collections.singletonMap(XMLResource.OPTION_ENCODING, "UTF-8"));
 60
 61        // 4. Run threat elicitation and risk analysis (the engine is released at the end of the block)
 62        List<Threat> threats;
 63        try (Engine engine = new Engine(resourceSet)) {
 64            threats = engine.runAnalysis(resourceSet);
 65        }
 66
 67        // 5. Print the threats and some aggregates
 68        for (Threat t : threats) {
 69            System.out.printf("%-24s %-40s %-12s %-8s risk %.2f [%.2f, %.2f]%n",
 70                    t.getThreatTypeName(), t.getThreatName(),
 71                    t.getThreatenedElementName(), t.getDataFlowName(),
 72                    t.getRisk(), t.getRisk_lower(), t.getRisk_upper());
 73        }
 74
 75        ThreatAggregationAnalysis taa = new ThreatAggregationAnalysis(threats);
 76        System.out.printf("%d threats, total risk %.2f, total potential risk %.2f%n",
 77                taa.getThreatCount(), taa.getTotalRisk(), taa.getTotalPotentialRisk());
 78        for (Map.Entry<Class<? extends ModelElement>, Long> e : taa.getThreatCountPerModelElementType().entrySet()) {
 79            System.out.printf("  %s: %d threats%n", e.getKey().getSimpleName(), e.getValue());
 80        }
 81
 82        // 6. Export the threats to CSV
 83        try (ThreatCSVWriter writer = new ThreatCSVWriter(new BufferedWriter(new FileWriter(csvFile)))) {
 84            writer.writeHeader();
 85            writer.write(threats.toArray(new Threat[0]));
 86        }
 87        System.out.println("Exported the threats to " + csvFile.getAbsolutePath());
 88    }
 89
 90    private static DFDModel createModel() {
 91        SpartaModelFactory factory = SpartaModelFactory.eINSTANCE;
 92
 93        DFDModel dfd = factory.createDFDModel();
 94        dfd.setName("Webshop");
 95        List<ModelElement> elements = dfd.getContainedElements();
 96
 97        TrustBoundaryContainer backend = factory.createTrustBoundaryContainer();
 98        backend.setName("Backend");
 99        elements.add(backend);
100
101        Process webServer = factory.createProcess();
102        webServer.setName("Web server");
103        backend.getContainedElements().add(webServer);
104
105        DataStore database = factory.createDataStore();
106        database.setName("Database");
107        backend.getContainedElements().add(database);
108
109        ExternalEntity user = factory.createExternalEntity();
110        user.setName("User");
111        elements.add(user);
112
113        DataFlow request = factory.createDataFlow();
114        request.setName("request");
115        request.setSender(user);
116        request.setRecipient(webServer);
117        elements.add(request);
118
119        DataFlow query = factory.createDataFlow();
120        query.setName("query");
121        query.setSender(webServer);
122        query.setRecipient(database);
123        elements.add(query);
124
125        return dfd;
126    }
127}

The numbered comments in main mark the steps of the program:

  1. Initialize EMF, as explained in Setting up a standalone program.

  2. Create the model with the method createModel: a trust boundary Backend with a web server process and a database, an external entity User, and two data flows (see Creating DFD models).

  3. Load the catalog into the resource set, link it to the model, and save the model as webshop.sparta (see Pairing existing threat type catalogs).

  4. Run the threat elicitation and risk analysis (see Performing threat elicitation and risk analysis). The try-with-resources statement closes the engine; you can still read the threats and their risk values afterward, for example to print and export them.

  5. Print each threat and some aggregates (see Reading threat results and Analyzing threat results). getDataFlowName() returns an empty string for a threat without a data flow, where getDataFlow().getName() would fail.

  6. Export the threats to threats.csv (see Exporting threat results).

Running the example

Run ExampleApp from your IDE, with the project directory as working directory. Alternatively, compile the project and let Maven write the classpath to a file:

mvn compile dependency:build-classpath "-Dmdep.outputFile=cp.txt"

Then run the program on Linux or macOS with:

java -cp "target/classes:$(cat cp.txt)" com.example.sparta.ExampleApp

or on Windows (PowerShell) with:

java -cp "target/classes;$(Get-Content cp.txt)" com.example.sparta.ExampleApp

The output looks as follows (shortened):

Repudiation              Web server repudiates action             Web server   query    risk 0.70 [0.00, 5.16]
Tampering                request modified                         request      request  risk 0.74 [0.00, 4.83]
Elevation of Privilege   Web server execution flow altered        Web server   request  risk 0.68 [0.00, 4.62]
Spoofing                 Web server spoofed                       Web server   query    risk 0.68 [0.00, 4.95]
...
Repudiation              User repudiates action                   User         request  risk 0.74 [0.00, 4.69]
Denial of Service        Web server disrupted                     Web server   request  risk 0.74 [0.00, 4.60]
15 threats, total risk 10.91, total potential risk 10.91
  ProcessImpl: 6 threats
  DataStoreImpl: 3 threats
  ExternalEntityImpl: 3 threats
  DataFlowImpl: 3 threats
Exported the threats to /path/to/example-project/threats.csv

The risk values differ between runs, because the risk is calculated with a Monte Carlo simulation, and the order of the threats can differ as well. The program formats the numbers it prints in the default locale of the JVM; the numbers in the CSV file do not depend on the locale. The model contains no countermeasures, so the risk of each threat equals its potential risk. To see the effect of a security solution, apply one before running the analysis, as shown in Creating and applying solutions.

The program also writes the model to webshop.sparta, which refers to the catalog file with a relative path, and the threats to threats.csv, with ; as separator.