initial commit
This commit is contained in:
commit
baaf940750
102 files changed
+11177
No files matched your search
@@ -0,0 +1,305 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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.molnarandrei</groupId>
|
||||
<artifactId>sopa</artifactId>
|
||||
<version>1.0.2</version>
|
||||
<name>sopa</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.release>21</maven.compiler.release>
|
||||
<junit.version>5.12.1</junit.version>
|
||||
|
||||
<!-- Distribution (see <build>). Liberica "Full" JDKs ship JavaFX jmods per platform. -->
|
||||
<dist.name>${project.artifactId}-${project.version}</dist.name>
|
||||
<dist.dir>${project.build.directory}/dist/${dist.name}</dist.dir>
|
||||
<dist.jdks>${project.basedir}/.jdks</dist.jdks>
|
||||
<dist.jdk.version>21.0.13.0.3+5</dist.jdk.version>
|
||||
<dist.jdk.dir>jdk-21.0.13.0.3-full</dist.jdk.dir>
|
||||
<dist.jdk.url>https://github.com/bell-sw/Liberica/releases/download/${dist.jdk.version}/bellsoft-jdk${dist.jdk.version}</dist.jdk.url>
|
||||
<!-- Modules for the bundled runtime. Beyond what jdeps reports: java.desktop/javafx.fxml
|
||||
(module-info), jdk.crypto.ec (HTTPS), jdk.localedata (non-English locales),
|
||||
jdk.unsupported (used reflectively by JavaFX and libraries). -->
|
||||
<dist.modules>java.base,java.desktop,java.logging,java.management,java.naming,java.net.http,java.sql,java.xml,jdk.charsets,jdk.crypto.ec,jdk.httpserver,jdk.localedata,jdk.unsupported,javafx.base,javafx.controls,javafx.fxml,javafx.graphics</dist.modules>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- Align jackson-annotations with Jackson 3.x. Without this, wiremock's
|
||||
transitive jackson-annotations 2.20 wins "nearest wins" mediation and
|
||||
Jackson 3 databind fails at runtime (missing JsonSerializeAs). -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson</groupId>
|
||||
<artifactId>jackson-bom</artifactId>
|
||||
<version>3.2.3</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- javafx -->
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>21.0.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>21.0.6</version>
|
||||
</dependency>
|
||||
|
||||
<!-- javafx theming & apprearence sugar -->
|
||||
<dependency>
|
||||
<groupId>io.github.mkpaz</groupId>
|
||||
<artifactId>atlantafx-base</artifactId>
|
||||
<version>2.1.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.kordamp.ikonli</groupId>
|
||||
<artifactId>ikonli-javafx</artifactId>
|
||||
<version>12.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.kordamp.ikonli</groupId>
|
||||
<artifactId>ikonli-materialdesign2-pack</artifactId>
|
||||
<version>12.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<!-- Google's official Material Icons (filled/outlined/round/sharp). -->
|
||||
<groupId>org.kordamp.ikonli</groupId>
|
||||
<artifactId>ikonli-material2-pack</artifactId>
|
||||
<version>12.4.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- text area with highlighting used for input and output xml -->
|
||||
<dependency>
|
||||
<groupId>org.fxmisc.richtext</groupId>
|
||||
<artifactId>richtextfx</artifactId>
|
||||
<version>0.11.7</version>
|
||||
</dependency>
|
||||
|
||||
<!-- .yml testcase reading -->
|
||||
<dependency>
|
||||
<groupId>tools.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<version>3.2.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>2.7</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.22.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- soap -->
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlbeans</groupId>
|
||||
<artifactId>xmlbeans</artifactId>
|
||||
<version>5.4.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- testing -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<!-- Plugin for junit that creates a SOAP api, or other apis. -->
|
||||
<groupId>org.wiremock</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>3.13.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>5.14.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<!--
|
||||
`mvn package` produces:
|
||||
target/${dist.name}-shaded.jar fat jar (needs a JDK 21; JavaFX natives for the build OS only)
|
||||
target/${dist.name}.zip self-contained distribution, unzipped copy in target/dist/:
|
||||
sopa.sh / sopa.bat launchers (from src/dist; sopa.bat uses javaw)
|
||||
jars/ app + dependencies, shared by both platforms
|
||||
runtime/linux/, runtime/windows/ jlinked JREs with JavaFX, x86_64
|
||||
|
||||
org.openjfx jars are left out of jars/: JavaFX comes from the runtimes, and the Maven
|
||||
jars only carry natives for the build machine. The app runs on the classpath (via
|
||||
Launcher), so non-modular dependencies are fine. The JDKs (~700 MB) download once into
|
||||
.jdks/, outside target/, so `mvn clean` keeps them. Plugins below bound to `package`
|
||||
run in the order declared.
|
||||
-->
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<!-- mvn javafx:run -->
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>0.0.8</version>
|
||||
<configuration>
|
||||
<mainClass>com.molnarandrei.sopa/com.molnarandrei.sopa.ui.SopaApplication</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||
<transformers>
|
||||
<!-- Merge META-INF/services, otherwise only one Ikonli pack registers and icons vanish. -->
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>com.molnarandrei.sopa.Launcher</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includeScope>runtime</includeScope>
|
||||
<excludeGroupIds>org.openjfx</excludeGroupIds>
|
||||
<outputDirectory>${dist.dir}/jars</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.jreleaser</groupId>
|
||||
<artifactId>jdks-maven-plugin</artifactId>
|
||||
<version>1.27.0</version>
|
||||
<dependencies>
|
||||
<!-- Its plexus-utils 4.x lacks Xpp3DomUtils (moved to plexus-xml); unpacking fails without it. -->
|
||||
<dependency>
|
||||
<groupId>org.codehaus.plexus</groupId>
|
||||
<artifactId>plexus-xml</artifactId>
|
||||
<version>3.0.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>setup-jdks</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${dist.jdks}</outputDirectory>
|
||||
<jdks>
|
||||
<jdk>
|
||||
<name>linux</name>
|
||||
<platform>linux-x86_64</platform>
|
||||
<url>${dist.jdk.url}-linux-amd64-full.tar.gz</url>
|
||||
<checksum>SHA-1/451cc597bd5ddbb597fe4dab08d64e88eedeb52b</checksum>
|
||||
</jdk>
|
||||
<jdk>
|
||||
<name>windows</name>
|
||||
<platform>windows-x86_64</platform>
|
||||
<url>${dist.jdk.url}-windows-amd64-full.zip</url>
|
||||
<checksum>SHA-1/17047626c28b30aa4042e555f370703969a627ce</checksum>
|
||||
</jdk>
|
||||
</jdks>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="jlink" value="${dist.jdks}/linux/${dist.jdk.dir}/bin/jlink"/>
|
||||
<property name="jlink.args" value="--add-modules ${dist.modules} --no-header-files --no-man-pages --strip-debug --compress=zip-6"/>
|
||||
<!-- Linux-only executables; Ant's copy and zip both drop the executable bit. -->
|
||||
<property name="executables" value="sopa.sh,runtime/linux/bin/*,runtime/linux/lib/jspawnhelper,runtime/linux/lib/jexec"/>
|
||||
|
||||
<!-- jlink refuses an existing output dir. -->
|
||||
<delete dir="${dist.dir}/runtime"/>
|
||||
<!-- The linux jlink builds both runtimes; the target platform comes from the jmods. -->
|
||||
<exec executable="${jlink}" failonerror="true">
|
||||
<arg line="${jlink.args} --module-path ${dist.jdks}/linux/${dist.jdk.dir}/jmods --output ${dist.dir}/runtime/linux"/>
|
||||
</exec>
|
||||
<exec executable="${jlink}" failonerror="true">
|
||||
<arg line="${jlink.args} --module-path ${dist.jdks}/windows/${dist.jdk.dir}/jmods --output ${dist.dir}/runtime/windows"/>
|
||||
</exec>
|
||||
|
||||
<copy file="${project.build.directory}/${project.build.finalName}.jar" todir="${dist.dir}/jars"/>
|
||||
<copy todir="${dist.dir}">
|
||||
<fileset dir="${project.basedir}/src/dist"/>
|
||||
</copy>
|
||||
<fixcrlf file="${dist.dir}/sopa.sh" eol="lf"/>
|
||||
<fixcrlf file="${dist.dir}/sopa.bat" eol="crlf"/>
|
||||
<chmod perm="755">
|
||||
<fileset dir="${dist.dir}" includes="${executables}"/>
|
||||
</chmod>
|
||||
|
||||
<zip destfile="${project.build.directory}/${dist.name}.zip">
|
||||
<zipfileset dir="${dist.dir}" prefix="${dist.name}" filemode="755" includes="${executables}"/>
|
||||
<zipfileset dir="${dist.dir}" prefix="${dist.name}" excludes="${executables}"/>
|
||||
</zip>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
rem Windows launcher. Uses the bundled runtime in runtime\windows.
|
||||
rem javaw.exe + start: no console window stays open. Set SOPA_CONSOLE=1 to keep
|
||||
rem the console and see log output (runs java.exe in the foreground instead).
|
||||
set "APP_HOME=%~dp0"
|
||||
if defined SOPA_CONSOLE (
|
||||
"%APP_HOME%runtime\windows\bin\java.exe" %JAVA_OPTS% -classpath "%APP_HOME%jars\*" com.molnarandrei.sopa.Launcher %*
|
||||
) else (
|
||||
start "" "%APP_HOME%runtime\windows\bin\javaw.exe" %JAVA_OPTS% -classpath "%APP_HOME%jars\*" com.molnarandrei.sopa.Launcher %*
|
||||
)
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
# Linux launcher. Uses the bundled runtime in runtime/linux; JAVA_OPTS is passed through.
|
||||
APP_HOME=$(cd "$(dirname "$0")" && pwd)
|
||||
exec "$APP_HOME/runtime/linux/bin/java" $JAVA_OPTS \
|
||||
-classpath "$APP_HOME/jars/*" \
|
||||
com.molnarandrei.sopa.Launcher "$@"
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.molnarandrei.sopa;
|
||||
|
||||
import com.molnarandrei.sopa.server.TestServer;
|
||||
import com.molnarandrei.sopa.ui.SopaApplication;
|
||||
import javafx.application.Application;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Launcher {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
LoggerConfig.setup();
|
||||
|
||||
var arguments = List.of(args);
|
||||
if (arguments.contains("testServer")) {
|
||||
TestServer.start(args.length > 1 ? Integer.parseInt(args[1]) : 8080);
|
||||
return;
|
||||
}
|
||||
|
||||
Application.launch(SopaApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.molnarandrei.sopa;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.logging.*;
|
||||
|
||||
public class LoggerConfig {
|
||||
|
||||
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");
|
||||
|
||||
public static void setup() {
|
||||
Logger rootLogger = Logger.getLogger("");
|
||||
for (Handler handler : rootLogger.getHandlers()) {
|
||||
rootLogger.removeHandler(handler);
|
||||
}
|
||||
rootLogger.setLevel(Level.INFO);
|
||||
Logger.getLogger("com.molnarandrei.sopa").setLevel(Level.FINE);
|
||||
|
||||
var formatter = new Formatter() {
|
||||
@Override
|
||||
public String format(LogRecord record) {
|
||||
String time = LocalDateTime.now().format(TIME_FORMAT);
|
||||
|
||||
String fullClass = record.getSourceClassName();
|
||||
String simpleClass = (fullClass != null && fullClass.contains("."))
|
||||
? fullClass.substring(fullClass.lastIndexOf('.') + 1)
|
||||
: (fullClass != null ? fullClass : record.getLoggerName());
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(time).append(" ")
|
||||
.append(record.getLevel()).append(" ")
|
||||
.append(simpleClass).append(": ")
|
||||
.append(formatMessage(record)).append(System.lineSeparator());
|
||||
|
||||
if (record.getThrown() != null) {
|
||||
java.io.StringWriter sw = new java.io.StringWriter();
|
||||
record.getThrown().printStackTrace(new java.io.PrintWriter(sw));
|
||||
sb.append(sw);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
};
|
||||
|
||||
var stdoutHandler = new StreamHandler(System.out, formatter) {
|
||||
@Override
|
||||
public synchronized void publish(LogRecord record) {
|
||||
super.publish(record);
|
||||
flush();
|
||||
}
|
||||
};
|
||||
stdoutHandler.setLevel(Level.FINE);
|
||||
stdoutHandler.setFilter(record -> record.getLevel().intValue() < Level.WARNING.intValue());
|
||||
|
||||
ConsoleHandler stderrHandler = new ConsoleHandler();
|
||||
stderrHandler.setFormatter(formatter);
|
||||
stderrHandler.setLevel(Level.WARNING);
|
||||
|
||||
rootLogger.addHandler(stdoutHandler);
|
||||
rootLogger.addHandler(stderrHandler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.molnarandrei.sopa;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.Alert;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Comparator;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class Utils {
|
||||
private static final Pattern NUMBER_PATTERN = Pattern.compile("^(.*?)(?:-(\\d+))?(\\.[^.]+)?$");
|
||||
|
||||
/**
|
||||
* Order the steps run in, by the index of the folder holding them: step-2 comes before
|
||||
* step-21, which the lexicographic order of the paths gets wrong.
|
||||
*/
|
||||
public static final Comparator<Path> STEP_ORDER = Comparator
|
||||
.comparingInt((Path step) -> extractNumber(step.getParent()))
|
||||
.thenComparing(Path::toString);
|
||||
|
||||
public static Path renameIndexed(Path target) {
|
||||
var fileName = target.getFileName().toString();
|
||||
var matcher = NUMBER_PATTERN.matcher(fileName);
|
||||
|
||||
var baseName = fileName;
|
||||
var index = 0;
|
||||
var extension = "";
|
||||
if (matcher.matches()) {
|
||||
baseName = matcher.group(1) != null ? matcher.group(1) : "";
|
||||
index = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0;
|
||||
extension = matcher.group(3) != null ? matcher.group(3) : "";
|
||||
}
|
||||
|
||||
var destination = target;
|
||||
while (Files.exists(destination)) {
|
||||
index++;
|
||||
destination = target.getParent().resolve(baseName + "-" + index + extension);
|
||||
}
|
||||
|
||||
return destination;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base name an index is attached to: both {@code step} and {@code step-3} give {@code step},
|
||||
* so it can be reused to index a folder somewhere else.
|
||||
*/
|
||||
public static String baseNameOf(Path target) {
|
||||
var fileName = target.getFileName().toString();
|
||||
var matcher = NUMBER_PATTERN.matcher(fileName);
|
||||
if (matcher.matches() && matcher.group(1) != null && ! matcher.group(1).isEmpty())
|
||||
return matcher.group(1);
|
||||
return fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Highest index in use among the {@code baseName} siblings inside {@code directory},
|
||||
* 0 when there is none.
|
||||
*/
|
||||
public static int highestIndexOf(Path directory, String baseName) throws IOException {
|
||||
var highest = 0;
|
||||
try (var entries = Files.list(directory)) {
|
||||
for (var entry : entries.toList()) {
|
||||
var name = entry.getFileName().toString();
|
||||
if (! name.equals(baseName) && ! name.startsWith(baseName + "-")) continue;
|
||||
highest = Math.max(highest, extractNumber(entry));
|
||||
}
|
||||
}
|
||||
return highest;
|
||||
}
|
||||
|
||||
public static Path renameIndexed(Path target, int index) {
|
||||
var fileName = target.getFileName().toString();
|
||||
var matcher = NUMBER_PATTERN.matcher(fileName);
|
||||
|
||||
var baseName = fileName;
|
||||
var extension = "";
|
||||
if (matcher.matches()) {
|
||||
baseName = matcher.group(1) != null ? matcher.group(1) : "";
|
||||
extension = matcher.group(3) != null ? matcher.group(3) : "";
|
||||
}
|
||||
|
||||
return target.getParent().resolve(baseName + "-" + index + extension);
|
||||
}
|
||||
|
||||
public static int extractNumber(Path path) {
|
||||
var matcher = NUMBER_PATTERN.matcher(path.getFileName().toString());
|
||||
if (matcher.matches() && matcher.group(2) != null) {
|
||||
return Integer.parseInt(matcher.group(2));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
public static void copyDirectory(Path source, Path target) throws IOException {
|
||||
copyDirectory(source, target, path -> false);
|
||||
}
|
||||
|
||||
public static void copyDirectory(Path source, Path target, Predicate<Path> skip) throws IOException {
|
||||
try (var stream = Files.walk(source)) {
|
||||
stream.forEach(sourcePath -> {
|
||||
if (skip.test(sourcePath)) return;
|
||||
var targetPath = target.resolve(source.relativize(sourcePath));
|
||||
try {
|
||||
if (Files.isDirectory(sourcePath)) {
|
||||
Files.createDirectories(targetPath);
|
||||
} else {
|
||||
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to copy " + sourcePath, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static void alert(String title, String header, String content) {
|
||||
alert(Alert.AlertType.ERROR, title, header, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a non-blocking dialog on the JavaFX application thread, so it is safe to call
|
||||
* from background threads such as the ones running SOAP jobs.
|
||||
*/
|
||||
public static void alert(Alert.AlertType type, String title, String header, String content) {
|
||||
Platform.runLater(() -> {
|
||||
var alert = new Alert(type);
|
||||
alert.setTitle(title);
|
||||
alert.setHeaderText(header);
|
||||
alert.setContentText(content);
|
||||
alert.show();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.molnarandrei.sopa.calllog;
|
||||
|
||||
import com.molnarandrei.sopa.data.DoesNotExistException;
|
||||
import com.molnarandrei.sopa.data.EmptyException;
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.data.yaml.CallLog;
|
||||
import com.molnarandrei.sopa.data.yaml.Yaml;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.*;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CallLogRepository {
|
||||
public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSS");
|
||||
private static final Logger log = Logger.getLogger(CallLogRepository.class.getName());
|
||||
private static final String prefix = "response-";
|
||||
private static final String suffix = ".yml";
|
||||
private static final String glob = prefix + "*" + suffix;
|
||||
private static final Comparator<Path> NEWEST_FIRST = Comparator.comparing(
|
||||
CallLogRepository::timestampOf,
|
||||
Comparator.nullsLast(Comparator.reverseOrder())
|
||||
);
|
||||
|
||||
public static Map<Path, CallLog> getAll(Path stepPath) throws RepositoryException {
|
||||
if (! Files.isReadable(stepPath)) throw new DoesNotExistException(stepPath, "Unreadable");
|
||||
var stepFolderPath = stepPath.getParent();
|
||||
var responses = new HashMap<Path, CallLog>();
|
||||
|
||||
try (var stream = Files.newDirectoryStream(stepFolderPath, glob)) {
|
||||
for (var responsePath : stream) {
|
||||
try {
|
||||
var response = get(responsePath);
|
||||
responses.put(responsePath, response);
|
||||
} catch (RepositoryException logAndContinue) {
|
||||
log.log(Level.WARNING, "Cannot read response log at %s".formatted(stepFolderPath), logAndContinue);
|
||||
}
|
||||
}
|
||||
} catch (IOException raise) {
|
||||
throw new RepositoryException(stepPath, "IO error", raise);
|
||||
}
|
||||
|
||||
return responses;
|
||||
}
|
||||
|
||||
/** Newest readable log of the step by file name timestamp, or null when the step has none. */
|
||||
public static CallLog getLatest(Path stepPath) throws RepositoryException {
|
||||
var stepFolderPath = stepPath.getParent();
|
||||
var responses = new ArrayList<Path>();
|
||||
try (var stream = Files.newDirectoryStream(stepFolderPath, glob)) {
|
||||
for (var responsePath : stream)
|
||||
if (Files.isRegularFile(responsePath)) responses.add(responsePath);
|
||||
} catch (IOException raise) {
|
||||
throw new RepositoryException(stepPath, "IO error", raise);
|
||||
}
|
||||
|
||||
responses.sort(NEWEST_FIRST);
|
||||
for (var responsePath : responses) {
|
||||
try {
|
||||
return get(responsePath);
|
||||
} catch (RepositoryException logAndContinue) {
|
||||
log.log(Level.WARNING, "Cannot read response log at %s".formatted(responsePath), logAndContinue);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static CallLog get(Path responsePath) throws RepositoryException {
|
||||
if (! Files.isRegularFile(responsePath))
|
||||
throw new DoesNotExistException(responsePath, "Unreadable");
|
||||
String response = "";
|
||||
try {
|
||||
response = Files.readString(responsePath);
|
||||
} catch (IOException raise) {
|
||||
throw new RepositoryException(responsePath, "IO error", raise);
|
||||
}
|
||||
if (response.isBlank())
|
||||
throw new EmptyException(responsePath, "Response file is empty");
|
||||
var obj = Yaml.toResponse(response);
|
||||
if (obj == null)
|
||||
throw new RepositoryException(responsePath, "Not a response");
|
||||
return obj;
|
||||
}
|
||||
|
||||
public static void write(Path stepPath, CallLog callLog) throws RepositoryException {
|
||||
var title = prefix + callLog.getTime().format(formatter) + suffix;
|
||||
var responsePath = stepPath.getParent().resolve(title);
|
||||
try {
|
||||
Files.deleteIfExists(responsePath);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(responsePath, "Cannot delete file for overwriting", io);
|
||||
}
|
||||
var yaml = Yaml.toYaml(callLog);
|
||||
try {
|
||||
Files.writeString(responsePath, yaml);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(responsePath, "Cannot write response history", io);
|
||||
}
|
||||
|
||||
// Delete before triggering, so one check reports the new response and the removed oldest
|
||||
// together, instead of the removal showing up a poll later.
|
||||
deleteOverLimit(stepPath);
|
||||
ProjectMonitors.trigger(stepPath
|
||||
.getParent() // step directory
|
||||
.getParent() // testcase directory
|
||||
.getParent() // project directory
|
||||
);
|
||||
}
|
||||
|
||||
private static void deleteOverLimit(Path stepPath) {
|
||||
var limit = Config.get().getResponseHistory();
|
||||
if (limit == null || limit < 1) {
|
||||
log.warning("Ignoring non-positive response history limit: %s".formatted(limit));
|
||||
return;
|
||||
}
|
||||
|
||||
var stepFolderPath = stepPath.getParent();
|
||||
try (var responsePaths = Files.newDirectoryStream(stepFolderPath, glob)) {
|
||||
var responses = new LinkedList<Path>();
|
||||
for (var responsePath : responsePaths)
|
||||
if (Files.isRegularFile(responsePath)) responses.add(responsePath);
|
||||
|
||||
responses.sort(NEWEST_FIRST);
|
||||
for (int index = limit; index < responses.size(); index++)
|
||||
Files.deleteIfExists(responses.get(index));
|
||||
} catch (IOException io) {
|
||||
log.log(Level.WARNING, "Cannot delete files over limit of %s".formatted(limit), io);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Newest first, by the timestamp written into the file name by {@link #write(Path, CallLog)},
|
||||
* so unparseable names sort last and are deleted first.
|
||||
*/
|
||||
private static LocalDateTime timestampOf(Path responsePath) {
|
||||
var filename = responsePath.getFileName().toString();
|
||||
if (! filename.startsWith(prefix) || ! filename.endsWith(suffix)) return null;
|
||||
try {
|
||||
return LocalDateTime.parse(filename.substring(prefix.length(), filename.length() - suffix.length()));
|
||||
} catch (DateTimeParseException notTimestamped) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void delete(Path responsePath) throws RepositoryException{
|
||||
try {
|
||||
Files.deleteIfExists(responsePath);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(responsePath, "Cannot delete response log.", io);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.molnarandrei.sopa.calllog;
|
||||
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.CallLog;
|
||||
import com.molnarandrei.sopa.calllog.CallLogRepository;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CallLogService {
|
||||
private static final Logger log = Logger.getLogger(CallLogService.class.getName());
|
||||
|
||||
public static Map<Path, CallLog> readAll(Path stepPath) {
|
||||
try {
|
||||
return CallLogRepository.getAll(stepPath);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
log.log(Level.SEVERE, "Cannot read call log for step %s.".formatted(stepPath), readOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido leer las respuestas del paso:\n%s"
|
||||
.formatted(stepPath),
|
||||
readOrParseErr.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** No alert on failure: used for passive UI decoration, a log line is enough. */
|
||||
public static CallLog readLatest(Path stepPath) {
|
||||
try {
|
||||
return CallLogRepository.getLatest(stepPath);
|
||||
} catch (RepositoryException readErr) {
|
||||
log.log(Level.WARNING, "Cannot read latest call log for step %s.".formatted(stepPath), readErr);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static CallLog read(Path callLogPath) {
|
||||
try {
|
||||
return CallLogRepository.get(callLogPath);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
log.log(Level.SEVERE, "Cannot read call logs for step %s.".formatted(callLogPath), readOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido leer las respuesta:\n%s"
|
||||
.formatted(callLogPath),
|
||||
readOrParseErr.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void save(Path stepPath, CallLog callLog) {
|
||||
try {
|
||||
CallLogRepository.write(stepPath, callLog);
|
||||
} catch (RepositoryException writeOrSerializeError) {
|
||||
log.log(Level.SEVERE, "Cannot write call log log for step %s.".formatted(stepPath), writeOrSerializeError);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido guardar la respuestas del paso:\n%s"
|
||||
.formatted(stepPath),
|
||||
writeOrSerializeError.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void delete(Path stepPath) {
|
||||
try {
|
||||
CallLogRepository.delete(stepPath);
|
||||
} catch (RepositoryException readWriteParseError) {
|
||||
log.log(Level.SEVERE, "Cannot delete log %s.".formatted(stepPath), readWriteParseError);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class DoesNotExistException extends RepositoryException {
|
||||
public DoesNotExistException(Path path, String message) {
|
||||
super(path, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class EmptyException extends RepositoryException {
|
||||
public EmptyException(Path path, String message) {
|
||||
super(path, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class FileNames {
|
||||
public static boolean isProjectFile(Path projectFile) {
|
||||
return "project.yml".equals( projectFile.getFileName().toString() );
|
||||
}
|
||||
|
||||
public static boolean hasTestCaseFolderName(Path testCaseFolder) {
|
||||
return testCaseFolder.getFileName().toString().startsWith("testcase-");
|
||||
}
|
||||
|
||||
public static boolean isTestCaseFile(Path testCaseFile) {
|
||||
return "testcase.yml".equals( testCaseFile.getFileName().toString() );
|
||||
}
|
||||
|
||||
public static boolean isStepFolder(Path stepFolder) {
|
||||
return Files.isDirectory(stepFolder)
|
||||
&& stepFolder.getFileName().toString().startsWith("step-");
|
||||
}
|
||||
|
||||
public static boolean isStepResponse(Path responseLog) {
|
||||
var filename = responseLog.getFileName().toString();
|
||||
return isStepFolder(responseLog.getParent())
|
||||
&& filename.startsWith("response-")
|
||||
&& filename.endsWith(".yml");
|
||||
}
|
||||
|
||||
public static boolean isStepFile(Path stepFile) {
|
||||
return "step.yml".equals( stepFile.getFileName().toString() );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import org.apache.commons.io.monitor.FileAlterationListener;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public abstract class PathAlterationListener implements FileAlterationListener {
|
||||
@Override
|
||||
public void onDirectoryChange(File directory) {}
|
||||
|
||||
@Override
|
||||
public void onDirectoryCreate(File directory) {}
|
||||
|
||||
@Override
|
||||
public void onDirectoryDelete(File directory) {}
|
||||
|
||||
@Override
|
||||
public void onFileChange(File file) { onFileChange(file.toPath()); }
|
||||
public void onFileChange(Path file) { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Override
|
||||
public void onFileCreate(File file) { onFileCreate(file.toPath()); }
|
||||
public void onFileCreate(Path file) { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Override
|
||||
public void onFileDelete(File file) { onFileDelete(file.toPath()); }
|
||||
public void onFileDelete(Path file) { throw new UnsupportedOperationException(); }
|
||||
|
||||
@Override
|
||||
public void onStart(FileAlterationObserver observer) {}
|
||||
|
||||
@Override
|
||||
public void onStop(FileAlterationObserver observer) {}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import com.molnarandrei.sopa.events.*;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.logging.Logger;
|
||||
import static com.molnarandrei.sopa.data.FileNames.*;
|
||||
|
||||
public class ProjectMonitor extends PathAlterationListener {
|
||||
private static final Logger log = Logger.getLogger(ProjectMonitor.class.getName());
|
||||
private final Path root;
|
||||
|
||||
protected ProjectMonitor(Path directory) throws IOException {
|
||||
this.root = directory;
|
||||
var projectFile = directory.resolve("project.yml");
|
||||
if (Files.exists(projectFile))
|
||||
onFileCreate(projectFile);
|
||||
|
||||
try (var testCases = Files.newDirectoryStream(directory)) {
|
||||
for (var testCaseDir : testCases) {
|
||||
if (!Files.isDirectory(testCaseDir) || !hasTestCaseFolderName(testCaseDir)) continue;
|
||||
|
||||
var testCaseFile = testCaseDir.resolve("testcase.yml");
|
||||
if (!Files.exists(testCaseFile)) continue;
|
||||
onFileCreate(testCaseFile);
|
||||
|
||||
try (var steps = Files.newDirectoryStream(testCaseDir)) {
|
||||
for (var stepFolder : steps) {
|
||||
if (! isStepFolder(stepFolder)) continue;
|
||||
var stepFile = stepFolder.resolve("step.yml");
|
||||
onFileCreate(stepFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileChange(Path file) {
|
||||
if (isOutsideProjectTree(file)) return;
|
||||
log.info("File changed %s.".formatted(file));
|
||||
if (isProjectFile(file))
|
||||
Events.emit(new ProjectEvent(ProjectEvent.CHANGED, file));
|
||||
else if (isTestCaseFile(file))
|
||||
Events.emit(new TestCaseEvent(TestCaseEvent.CHANGED, testCaseAndProject(file)));
|
||||
else if (isStepResponse(file))
|
||||
Events.emit(new ResponseEvent(ResponseEvent.CHANGED, file));
|
||||
else if (isStepFile(file))
|
||||
Events.emit(new StepEvent(StepEvent.CHANGED, stepAndProject(file)));
|
||||
else
|
||||
log.warning("Unknown change %s.".formatted(file));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileCreate(Path file) {
|
||||
if (isOutsideProjectTree(file)) return;
|
||||
log.info("File created %s.".formatted(file));
|
||||
if (isProjectFile(file))
|
||||
Events.emit(new ProjectEvent(ProjectEvent.ADDED, file));
|
||||
else if (isTestCaseFile(file))
|
||||
Events.emit(new TestCaseEvent(TestCaseEvent.ADDED, testCaseAndProject(file)));
|
||||
else if (isStepResponse(file))
|
||||
Events.emit(new ResponseEvent(ResponseEvent.ADDED, file));
|
||||
else if (isStepFile(file))
|
||||
Events.emit(new StepEvent(StepEvent.ADDED, stepAndProject(file)));
|
||||
else
|
||||
log.warning("Unknown creation %s.".formatted(file));
|
||||
|
||||
if (! isEmpty(file))
|
||||
onFileChange(file);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFileDelete(Path file) {
|
||||
if (isOutsideProjectTree(file)) return;
|
||||
log.info("File deleted: %s.".formatted(file));
|
||||
if (isProjectFile(file))
|
||||
Events.emit(new ProjectEvent(ProjectEvent.REMOVED, file));
|
||||
else if (isTestCaseFile(file))
|
||||
Events.emit(new TestCaseEvent(TestCaseEvent.REMOVED, testCaseAndProject(file)));
|
||||
else if (isStepResponse(file))
|
||||
Events.emit(new ResponseEvent(ResponseEvent.REMOVED, file));
|
||||
else if (isStepFile(file))
|
||||
Events.emit(new StepEvent(StepEvent.REMOVED, stepAndProject(file)));
|
||||
else
|
||||
log.warning("Unknown deletion %s.".formatted(file));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop(FileAlterationObserver observer) {
|
||||
Events.emit(new UiEvent(UiEvent.WATCHER_HEARTBEAT, root));
|
||||
}
|
||||
|
||||
private boolean isOutsideProjectTree(Path file) {
|
||||
var relative = root.relativize(file);
|
||||
if (relative.getNameCount() == 1) return ! isProjectFile(file);
|
||||
return ! hasTestCaseFolderName(relative.getName(0));
|
||||
}
|
||||
|
||||
private static TestCaseEvent.TestCaseAndProject testCaseAndProject(Path testCaseFile) {
|
||||
var project = testCaseFile.getParent().getParent().resolve("project.yml");
|
||||
return new TestCaseEvent.TestCaseAndProject(testCaseFile, project);
|
||||
}
|
||||
|
||||
private static StepEvent.StepAndProject stepAndProject(Path stepFile) {
|
||||
var testCaseFolderPath = stepFile.getParent().getParent();
|
||||
var testCase = testCaseFolderPath.resolve("testcase.yml");
|
||||
var project = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
return new StepEvent.StepAndProject(stepFile, testCase, project);
|
||||
}
|
||||
|
||||
private static boolean isEmpty(Path path) {
|
||||
try {
|
||||
return Files.size(path) == 0;
|
||||
} catch (IOException ignore) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ProjectEvent;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ProjectMonitors {
|
||||
private static final Logger log = Logger.getLogger(ProjectMonitors.class.getName());
|
||||
private static final Map<Path, FileAlterationMonitor> monitors = new HashMap<>();
|
||||
private static final Map<Path, FileAlterationObserver> observers = new HashMap<>();
|
||||
|
||||
public static void start(Path projectDirectory) throws RepositoryException {
|
||||
if (monitors.containsKey(projectDirectory)) return;
|
||||
log.info("Starting monitoring project %s.".formatted(projectDirectory));
|
||||
|
||||
try {
|
||||
var observer = FileAlterationObserver.builder()
|
||||
.setFile(projectDirectory.toFile())
|
||||
.get();
|
||||
observers.put(projectDirectory, observer);
|
||||
|
||||
var listener = new ProjectMonitor(projectDirectory);
|
||||
observer.addListener(listener);
|
||||
|
||||
var monitor = new FileAlterationMonitor(1000, observer);
|
||||
monitor.start();
|
||||
monitors.put(projectDirectory, monitor);
|
||||
|
||||
} catch (IOException initialParsingFailure) {
|
||||
throw new RepositoryException(projectDirectory, "Fallo en la lectura inicial de los directorios", initialParsingFailure);
|
||||
} catch (Exception fileWatcher) {
|
||||
log.log(Level.SEVERE, "Failed starting file monitor for project %s.".formatted(projectDirectory), fileWatcher);
|
||||
throw new RepositoryException(projectDirectory, "Fallo en la inicializacion del monitor en tiempo real del proyecto", fileWatcher);
|
||||
}
|
||||
}
|
||||
|
||||
public static void stop(Path projectDirectory) {
|
||||
var monitor = monitors.remove(projectDirectory);
|
||||
observers.remove(projectDirectory);
|
||||
if (monitor == null) return;
|
||||
log.info("Stopping monitoring project %s.".formatted(projectDirectory));
|
||||
try {
|
||||
monitor.stop();
|
||||
} catch (Exception e) {
|
||||
log.log(Level.SEVERE, "Failed stopping file monitor for project %s.".formatted(projectDirectory), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
monitors.values().forEach(m-> {
|
||||
try {
|
||||
m.stop();
|
||||
} catch (Exception ignore) {}
|
||||
});
|
||||
}
|
||||
|
||||
public static void trigger(Path projectDirectory) {
|
||||
if (!observers.containsKey(projectDirectory)) {
|
||||
log.warning("Triggering observation manually for non-observed project: %s".formatted(projectDirectory));
|
||||
return;
|
||||
}
|
||||
Thread.ofVirtual().start(()->{
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException ignore) {}
|
||||
var observer = observers.get(projectDirectory);
|
||||
if (observer == null) {
|
||||
log.warning("Wrong observer being triggered %s.".formatted(projectDirectory));
|
||||
return;
|
||||
}
|
||||
observer.checkAndNotify();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class RepositoryException extends IOException {
|
||||
public Path path;
|
||||
|
||||
public RepositoryException(Path path, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
public RepositoryException(Path path, String message) {
|
||||
super(message);
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
public Path getPath() {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Folders of deleted projects, testcases and steps, kept for this session so they can be restored.
|
||||
* It is a temporary folder: it is not emptied by the app, the system cleans it.
|
||||
* Only for repositories: services delete and restore through them.
|
||||
*/
|
||||
public class Trash {
|
||||
private static final Logger log = Logger.getLogger(Trash.class.getName());
|
||||
private static Path trash;
|
||||
|
||||
/** Moves {@code folder} into the trash. @return where it is kept. */
|
||||
public static synchronized Path keep(Path folder) throws IOException {
|
||||
var kept = trash().resolve(UUID.randomUUID().toString()).resolve(folder.getFileName().toString());
|
||||
Files.createDirectories(kept.getParent());
|
||||
move(folder, kept);
|
||||
return kept;
|
||||
}
|
||||
|
||||
/** Moves {@code kept} back to {@code folder}, unless its place is taken or its parent is gone. */
|
||||
public static synchronized void restore(Path kept, Path folder) throws IOException {
|
||||
if (Files.exists(folder))
|
||||
throw new IOException("Ya existe %s: muévalo o elimínelo para restaurar.".formatted(folder));
|
||||
if (! Files.isDirectory(folder.getParent()))
|
||||
throw new IOException("No existe la carpeta %s: restaure antes lo que la contenía.".formatted(folder.getParent()));
|
||||
if (! Files.isDirectory(kept))
|
||||
throw new IOException("Ya no está en la papelera: %s.".formatted(kept));
|
||||
move(kept, folder);
|
||||
}
|
||||
|
||||
private static Path trash() throws IOException {
|
||||
if (trash == null) trash = Files.createTempDirectory("sopa-trash-");
|
||||
return trash;
|
||||
}
|
||||
|
||||
/** A rename when both are on the same disk, else a copy and a delete. */
|
||||
private static void move(Path source, Path target) throws IOException {
|
||||
try {
|
||||
Files.move(source, target);
|
||||
return;
|
||||
} catch (IOException otherDisk) {
|
||||
log.fine("Cannot rename %s to %s, copying: %s".formatted(source, target, otherDisk));
|
||||
}
|
||||
try {
|
||||
Utils.copyDirectory(source, target);
|
||||
} catch (RuntimeException cannotCopy) {
|
||||
throw new IOException(cannotCopy.getMessage(), cannotCopy.getCause());
|
||||
}
|
||||
try (var walk = Files.walk(source)) {
|
||||
for (var file : walk.sorted(Comparator.reverseOrder()).toList())
|
||||
Files.delete(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
public class Assertion {
|
||||
public enum Type { httpStatus, contains, xPath, regex, validPerWsdl, notSoapFault, soapFault }
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING)
|
||||
private Type type = Type.contains;
|
||||
private String value = "";
|
||||
private String expression = "";
|
||||
|
||||
public Assertion(){}
|
||||
|
||||
public Assertion(Type type, String value, String expression) {
|
||||
this.type = type;
|
||||
this.value = value;
|
||||
this.expression = expression;
|
||||
}
|
||||
|
||||
public Type getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(Type type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getExpression() {
|
||||
return expression;
|
||||
}
|
||||
|
||||
public void setExpression(String expression) {
|
||||
this.expression = expression;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "%s[%s]=%s".formatted(type, expression, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class CallLog {
|
||||
public static final String HEADER = "# com.molnarandrei.sopa.CallLog";
|
||||
|
||||
public enum Result {
|
||||
success,
|
||||
assertionsFailed,
|
||||
extractionsFailed,
|
||||
exception
|
||||
}
|
||||
|
||||
private Path step;
|
||||
// TODO expand to have endpoint, action, payload sent, etc.
|
||||
|
||||
private int status;
|
||||
private LocalDateTime time;
|
||||
private String body;
|
||||
/** Null on logs written before this field existed. */
|
||||
private Result result;
|
||||
|
||||
public CallLog() {}
|
||||
|
||||
public CallLog(Path step, String body, int status, Result result) {
|
||||
this.step = step;
|
||||
this.body = body;
|
||||
this.status = status;
|
||||
this.result = result;
|
||||
this.time = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public Path getStep() {
|
||||
return step;
|
||||
}
|
||||
|
||||
public void setStep(Path step) {
|
||||
this.step = step;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(LocalDateTime time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public Result getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setResult(Result result) {
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ProjectEvent;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.SplitPane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.SequencedSet;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Config {
|
||||
private static final Logger log = Logger.getLogger(Config.class.getName());
|
||||
|
||||
public static final String HEADER = "# com.molnarandrei.sopa.Settings";
|
||||
private static final Path configs = Path.of(System.getProperty("user.home")).resolve(".config");
|
||||
private static final Path config = configs.resolve("sopa.yml");
|
||||
|
||||
private SequencedSet<Path> projectHistory = new LinkedHashSet<>();
|
||||
private SequencedSet<Path> loadedProjects = new LinkedHashSet<>();
|
||||
|
||||
private Boolean windowMaximized = false;
|
||||
private Double windowPositionX = 0d;
|
||||
private Double windowPositionY = 0d;
|
||||
private Double windowSizeWidth = 800d;
|
||||
private Double windowSizeHeight = 500d;
|
||||
private Double layoutSplitPosition = 0.2d;
|
||||
|
||||
private Double propertiesDialogX = null;
|
||||
private Double propertiesDialogY = null;
|
||||
private Double propertiesDialogWidth = null;
|
||||
private Double propertiesDialogHeight = null;
|
||||
|
||||
private Integer responseHistory = 10;
|
||||
private Double responseHistorySplitPaneDividerPosition = 0.2d;
|
||||
private Double assertionsExtractionsSplitPaneDividerPosition = 0.5d;
|
||||
private Integer callTimeout = 10;
|
||||
|
||||
private static Config INSTANCE = null;
|
||||
|
||||
private final EventHandler<ProjectEvent> projectAddedHandler = this::onProjectAdded;
|
||||
private final EventHandler<ProjectEvent> projectRemovedHandler = this::onProjectRemoved;
|
||||
|
||||
public static Config get() {
|
||||
if (INSTANCE == null) {
|
||||
try {
|
||||
if (Files.exists(config)) {
|
||||
var yaml = Files.readString(config);
|
||||
INSTANCE = Yaml.toConfig(yaml);
|
||||
log.info("Loaded settings: \n%s".formatted(yaml));
|
||||
}
|
||||
} catch (IOException logAndIgnore) {
|
||||
log.log(Level.WARNING, "Cannot load settings.", logAndIgnore);
|
||||
}
|
||||
if (INSTANCE == null)
|
||||
INSTANCE = new Config();
|
||||
INSTANCE.validateHistory();
|
||||
}
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops projects whose directory no longer exists from both the history and the
|
||||
* loaded projects, so they are neither offered nor reloaded. Entries point at the
|
||||
* project.yml file, hence the check on its parent directory.
|
||||
*/
|
||||
private void validateHistory() {
|
||||
projectHistory.removeIf(project -> !Files.isDirectory(project.getParent()));
|
||||
loadedProjects.removeIf(project -> !Files.isDirectory(project.getParent()));
|
||||
}
|
||||
|
||||
public void save() {
|
||||
try {
|
||||
if (!Files.isDirectory(configs))
|
||||
Files.createDirectory(configs);
|
||||
var yaml = Yaml.toYaml(this);
|
||||
log.info("Saving settings: \n%s".formatted(yaml));
|
||||
Files.writeString(config, yaml);
|
||||
} catch (IOException logAndIgnore) {
|
||||
log.log(Level.WARNING, "Cannot save settings.", logAndIgnore);
|
||||
}
|
||||
}
|
||||
|
||||
public Config update(Stage stage, Node root) {
|
||||
try {
|
||||
setWindowMaximized(stage.isMaximized());
|
||||
setWindowSizeHeight(stage.getHeight());
|
||||
setWindowSizeWidth(stage.getWidth());
|
||||
setWindowPositionX(stage.getX());
|
||||
setWindowPositionY(stage.getY());
|
||||
setLayoutSplitPosition(((SplitPane)root.lookup("#splitPane")).getDividerPositions()[0]);
|
||||
} catch (Exception logAndIgnore) {
|
||||
log.log(Level.WARNING, "Cannot update settings.", logAndIgnore);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public Config updatePropertiesDialog(Stage dialog) {
|
||||
try {
|
||||
setPropertiesDialogX(dialog.getX());
|
||||
setPropertiesDialogY(dialog.getY());
|
||||
setPropertiesDialogWidth(dialog.getWidth());
|
||||
setPropertiesDialogHeight(dialog.getHeight());
|
||||
} catch (Exception logAndIgnore) {
|
||||
log.log(Level.WARNING, "Cannot update properties dialog settings.", logAndIgnore);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public void reloadSavedState() {
|
||||
// Starting a monitor emits ProjectEvent.ADDED synchronously on this (FX) thread.
|
||||
// If our handlers were already listening, onProjectAdded would addFirst() into
|
||||
// loadedProjects while we iterate it: a ConcurrentModificationException that stops
|
||||
// every project after the first from loading, and a reshuffled order on each start.
|
||||
// So: iterate a copy, and only start listening once the saved projects are loaded.
|
||||
for (var project : List.copyOf(loadedProjects)) {
|
||||
try {
|
||||
ProjectMonitors.start(project.getParent());
|
||||
} catch (RepositoryException logAndIgnore) {
|
||||
log.log(Level.WARNING, "Cannot load previously loaded project at %s.".formatted(project), logAndIgnore);
|
||||
}
|
||||
}
|
||||
|
||||
Events.addListener(ProjectEvent.ADDED, projectAddedHandler);
|
||||
Events.addListener(ProjectEvent.REMOVED, projectRemovedHandler);
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
Events.removeListener(ProjectEvent.ADDED, projectAddedHandler);
|
||||
Events.removeListener(ProjectEvent.REMOVED, projectRemovedHandler);
|
||||
}
|
||||
|
||||
private void onProjectAdded(ProjectEvent event) {
|
||||
log.info("Will load project %s next session.".formatted(event.get()));
|
||||
loadedProjects.addFirst(event.get());
|
||||
projectHistory.addFirst(event.get());
|
||||
while (projectHistory.size() > 5) projectHistory.removeLast();
|
||||
}
|
||||
|
||||
private void onProjectRemoved(ProjectEvent event) {
|
||||
loadedProjects.remove(event.get());
|
||||
}
|
||||
|
||||
public Boolean isWindowMaximized() {
|
||||
return windowMaximized;
|
||||
}
|
||||
|
||||
public void setWindowMaximized(Boolean maximized) {
|
||||
windowMaximized = maximized;
|
||||
}
|
||||
|
||||
public Double getWindowPositionX() {
|
||||
return windowPositionX;
|
||||
}
|
||||
|
||||
public void setWindowPositionX(Double windowPositionX) {
|
||||
this.windowPositionX = windowPositionX;
|
||||
}
|
||||
|
||||
public Double getWindowPositionY() {
|
||||
return windowPositionY;
|
||||
}
|
||||
|
||||
public void setWindowPositionY(Double windowPositionY) {
|
||||
this.windowPositionY = windowPositionY;
|
||||
}
|
||||
|
||||
public Double getWindowSizeWidth() {
|
||||
return windowSizeWidth;
|
||||
}
|
||||
|
||||
public void setWindowSizeWidth(Double windowSizeWidth) {
|
||||
this.windowSizeWidth = windowSizeWidth;
|
||||
}
|
||||
|
||||
public Double getWindowSizeHeight() {
|
||||
return windowSizeHeight;
|
||||
}
|
||||
|
||||
public void setWindowSizeHeight(Double windowSizeHeight) {
|
||||
this.windowSizeHeight = windowSizeHeight;
|
||||
}
|
||||
|
||||
public Double getLayoutSplitPosition() {
|
||||
return layoutSplitPosition;
|
||||
}
|
||||
|
||||
public void setLayoutSplitPosition(Double layoutSplitPosition) {
|
||||
this.layoutSplitPosition = layoutSplitPosition;
|
||||
}
|
||||
|
||||
public void setProjectHistory(SequencedSet<Path> projectHistory) {
|
||||
this.projectHistory = projectHistory;
|
||||
}
|
||||
|
||||
public Set<Path> getProjectHistory() {
|
||||
return projectHistory;
|
||||
}
|
||||
|
||||
public void setLoadedProjects(SequencedSet<Path> loadedProjects) {
|
||||
this.loadedProjects = loadedProjects;
|
||||
}
|
||||
|
||||
public Set<Path> getLoadedProjects() {
|
||||
return loadedProjects;
|
||||
}
|
||||
|
||||
public Integer getResponseHistory() {
|
||||
return responseHistory;
|
||||
}
|
||||
|
||||
public void setResponseHistory(Integer responseHistory) {
|
||||
this.responseHistory = responseHistory;
|
||||
}
|
||||
|
||||
public Integer getCallTimeout() {
|
||||
return callTimeout;
|
||||
}
|
||||
|
||||
public void setCallTimeout(Integer callTimeout) {
|
||||
this.callTimeout = callTimeout;
|
||||
}
|
||||
|
||||
public Double getAssertionsExtractionsSplitPaneDividerPosition() {
|
||||
return assertionsExtractionsSplitPaneDividerPosition;
|
||||
}
|
||||
|
||||
public void setAssertionsExtractionsSplitPaneDividerPosition(Double assertionsExtractionsSplitPaneDividerPosition) {
|
||||
this.assertionsExtractionsSplitPaneDividerPosition = assertionsExtractionsSplitPaneDividerPosition;
|
||||
}
|
||||
|
||||
public Double getResponseHistorySplitPaneDividerPosition() {
|
||||
return responseHistorySplitPaneDividerPosition;
|
||||
}
|
||||
|
||||
public void setResponseHistorySplitPaneDividerPosition(Double responseHistorySplitPaneDividerPosition) {
|
||||
this.responseHistorySplitPaneDividerPosition = responseHistorySplitPaneDividerPosition;
|
||||
}
|
||||
|
||||
public Double getPropertiesDialogX() {
|
||||
return propertiesDialogX;
|
||||
}
|
||||
|
||||
public void setPropertiesDialogX(Double propertiesDialogX) {
|
||||
this.propertiesDialogX = propertiesDialogX;
|
||||
}
|
||||
|
||||
public Double getPropertiesDialogY() {
|
||||
return propertiesDialogY;
|
||||
}
|
||||
|
||||
public void setPropertiesDialogY(Double propertiesDialogY) {
|
||||
this.propertiesDialogY = propertiesDialogY;
|
||||
}
|
||||
|
||||
public Double getPropertiesDialogWidth() {
|
||||
return propertiesDialogWidth;
|
||||
}
|
||||
|
||||
public void setPropertiesDialogWidth(Double propertiesDialogWidth) {
|
||||
this.propertiesDialogWidth = propertiesDialogWidth;
|
||||
}
|
||||
|
||||
public Double getPropertiesDialogHeight() {
|
||||
return propertiesDialogHeight;
|
||||
}
|
||||
|
||||
public void setPropertiesDialogHeight(Double propertiesDialogHeight) {
|
||||
this.propertiesDialogHeight = propertiesDialogHeight;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
|
||||
/** An endpoint of a project, kept in the project by its url. */
|
||||
public class Endpoint {
|
||||
private SoapVersion version = SoapVersion.ONE_ONE;
|
||||
|
||||
public Endpoint() {}
|
||||
|
||||
public Endpoint(SoapVersion version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public SoapVersion getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(SoapVersion version) {
|
||||
this.version = version;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import org.snakeyaml.engine.v2.api.DumpSettings;
|
||||
import tools.jackson.dataformat.yaml.YAMLFactory;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
import static tools.jackson.dataformat.yaml.YAMLWriteFeature.*;
|
||||
import org.snakeyaml.engine.v2.common.ScalarStyle;
|
||||
import org.snakeyaml.engine.v2.common.FlowStyle;
|
||||
|
||||
public class HumanComfyYamlMapper {
|
||||
|
||||
public static YAMLMapper get() {
|
||||
var dumpSettings = DumpSettings.builder()
|
||||
.setDefaultFlowStyle(FlowStyle.BLOCK)
|
||||
.setDefaultScalarStyle(ScalarStyle.PLAIN)
|
||||
.setIndent(2)
|
||||
.setIndicatorIndent(2)
|
||||
// Required when indicatorIndent == indent: otherwise sequence-of-mapping items
|
||||
// are emitted as a lone "-" followed by keys at the dash column (unparseable).
|
||||
.setIndentWithIndicator(true)
|
||||
.build();
|
||||
|
||||
var yamlFactory = YAMLFactory.builder()
|
||||
.dumperOptions(dumpSettings)
|
||||
.enable(MINIMIZE_QUOTES)
|
||||
.disable(WRITE_DOC_START_MARKER)
|
||||
.enable(INDENT_ARRAYS_WITH_INDICATOR)
|
||||
.disable(ALWAYS_QUOTE_NUMBERS_AS_STRINGS)
|
||||
.build();
|
||||
|
||||
return YAMLMapper.builder(yamlFactory)
|
||||
.changeDefaultPropertyInclusion(incl -> incl.withValueInclusion(JsonInclude.Include.NON_NULL))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
public enum Kind {
|
||||
project,
|
||||
testcase,
|
||||
step
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Project {
|
||||
public static final String HEADER = "# com.molnarandrei.sopa.Project";
|
||||
private String version = "1.0.2";
|
||||
private String name = "";
|
||||
/** By url, in the order they were added. */
|
||||
private Map<String, Endpoint> endpoints = new LinkedHashMap<>();
|
||||
private Map<String, String> headers = new HashMap<>();
|
||||
private Map<String, String> properties = new HashMap<>();
|
||||
|
||||
public Project() {}
|
||||
|
||||
/** Every endpoint is SOAP 1.1. */
|
||||
public Project(String name, List<String> endpoints) {
|
||||
this.name = name;
|
||||
for (var endpoint : endpoints) putEndpoint(endpoint, SoapVersion.ONE_ONE);
|
||||
}
|
||||
|
||||
/** Every endpoint is SOAP 1.1. */
|
||||
public Project(String name, List<String> endpoints, Map<String, String> headers, Map<String, String> properties) {
|
||||
this(name, endpoints);
|
||||
this.headers = headers;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(String version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/** By url. Edited in place by the project editor. */
|
||||
public Map<String, Endpoint> getEndpoints() {
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
/** Adds the endpoint, or changes its version. Blank urls are ignored. */
|
||||
public void putEndpoint(String url, SoapVersion version) {
|
||||
if (url == null || url.isBlank()) return;
|
||||
endpoints.put(url.strip(), new Endpoint(version));
|
||||
}
|
||||
|
||||
/** The version of the project endpoint {@code url}, SOAP 1.1 when it is not a project endpoint. */
|
||||
public SoapVersion versionOf(String url) {
|
||||
if (url == null) return SoapVersion.ONE_ONE;
|
||||
var endpoint = endpoints.get(url.strip());
|
||||
return endpoint == null ? SoapVersion.ONE_ONE : endpoint.getVersion();
|
||||
}
|
||||
|
||||
public void setEndpoints(Map<String, Endpoint> endpoints) {
|
||||
this.endpoints = endpoints == null ? new LinkedHashMap<>() : new LinkedHashMap<>(endpoints);
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
public Map<String, String> getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
public void setProperties(Map<String, String> properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Step {
|
||||
public static final String HEADER = "# com.molnarandrei.sopa.Step";
|
||||
|
||||
private String name = "";
|
||||
private boolean active = true;
|
||||
private String endpoint = "";
|
||||
private String action = "";
|
||||
private final Map<String, String> headers = new HashMap<>();
|
||||
private String payload = "";
|
||||
private final Map<String, String> extractions = new HashMap<>();
|
||||
private final List<Assertion> assertions = new LinkedList<>();
|
||||
|
||||
public Step(){}
|
||||
|
||||
public Step(String name){
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public void setEndpoint(String endpoint) {
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers.clear();
|
||||
if (headers != null) this.headers.putAll(headers);
|
||||
}
|
||||
|
||||
public String getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
public void setPayload(String payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
public Map<String, String> getExtractions() {
|
||||
return extractions;
|
||||
}
|
||||
|
||||
public void setExtractions(Map<String, String> extractions) {
|
||||
this.extractions.clear();
|
||||
if (extractions != null) this.extractions.putAll(extractions);
|
||||
}
|
||||
|
||||
public List<Assertion> getAssertions() {
|
||||
return assertions;
|
||||
}
|
||||
|
||||
public void setAssertions(List<Assertion> assertions) {
|
||||
this.assertions.clear();
|
||||
if (assertions != null) this.assertions.addAll(assertions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class TestCase {
|
||||
public static final String HEADER = "# com.molnarandrei.sopa.TestCase";
|
||||
|
||||
private String name = "";
|
||||
private boolean active = true;
|
||||
private String endpoint = "";
|
||||
private String action = "";
|
||||
private Map<String, String> headers = new HashMap<>();
|
||||
private Map<String, String> properties = new HashMap<>();
|
||||
|
||||
public String filename() {
|
||||
return name.toLowerCase().replaceAll(" ", "-");
|
||||
}
|
||||
|
||||
public TestCase() {}
|
||||
|
||||
public TestCase(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public TestCase(String name, boolean active, String endpoint, String action, Map<String, String> headers, Map<String, String> properties) {
|
||||
this.name = name;
|
||||
this.active = active;
|
||||
this.endpoint = endpoint;
|
||||
this.action = action;
|
||||
this.headers = headers;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public void setActive(boolean active) {
|
||||
this.active = active;
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public void setEndpoint(String endpoint) {
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public String getAction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setAction(String action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
public Map<String, String> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public void setHeaders(Map<String, String> headers) {
|
||||
this.headers = headers;
|
||||
}
|
||||
|
||||
public Map<String, String> getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
public void setProperties(Map<String, String> properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.dataformat.yaml.YAMLMapper;
|
||||
|
||||
public class Yaml {
|
||||
private static final YAMLMapper mapper = HumanComfyYamlMapper.get();
|
||||
|
||||
public static Project toProject(String value) throws JacksonException {
|
||||
if (! value.startsWith(Project.HEADER)) return null;
|
||||
return mapper.readValue(
|
||||
value,
|
||||
Project.class
|
||||
);
|
||||
}
|
||||
|
||||
public static TestCase toTestCase(String value) throws JacksonException {
|
||||
if (! value.startsWith(TestCase.HEADER)) return null;
|
||||
return mapper.readValue(
|
||||
value,
|
||||
TestCase.class
|
||||
);
|
||||
}
|
||||
|
||||
public static Step toStep(String value) throws JacksonException {
|
||||
if (! value.startsWith(Step.HEADER)) return null;
|
||||
return mapper.readValue(
|
||||
value,
|
||||
Step.class
|
||||
);
|
||||
}
|
||||
|
||||
public static Config toConfig(String value) throws JacksonException {
|
||||
if (! value.startsWith(Config.HEADER)) return null;
|
||||
return mapper.readValue(
|
||||
value,
|
||||
Config.class
|
||||
);
|
||||
}
|
||||
|
||||
public static CallLog toResponse(String value) throws JacksonException {
|
||||
if (! value.startsWith(CallLog.HEADER)) return null;
|
||||
return mapper.readValue(
|
||||
value,
|
||||
CallLog.class
|
||||
);
|
||||
}
|
||||
|
||||
public static String toYaml(Project testCase) {
|
||||
return Project.HEADER + '\n' + mapper.writeValueAsString(testCase);
|
||||
}
|
||||
|
||||
public static String toYaml(TestCase testCase) {
|
||||
return TestCase.HEADER + '\n' + mapper.writeValueAsString(testCase);
|
||||
}
|
||||
|
||||
public static String toYaml(Step testCase) {
|
||||
return Step.HEADER + '\n' + mapper.writeValueAsString(testCase);
|
||||
}
|
||||
|
||||
public static String toYaml(Config config) {
|
||||
return Config.HEADER + '\n' + mapper.writeValueAsString(config);
|
||||
}
|
||||
|
||||
public static String toYaml(CallLog callLog) {
|
||||
return CallLog.HEADER + '\n' + mapper.writeValueAsString(callLog);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Maps event types to their handler, so a component can add and remove all of them at once. */
|
||||
public class EventListeners {
|
||||
private final Map<EventType<?>, EventHandler<?>> handlers = new LinkedHashMap<>();
|
||||
|
||||
/** The signature ties the handler to its event type, which the map alone cannot express. */
|
||||
public <T extends SopaEvent<?>> EventListeners on(EventType<T> type, EventHandler<T> handler) {
|
||||
handlers.put(type, handler);
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void addAll() {
|
||||
handlers.forEach((type, handler) -> Events.addListener(
|
||||
(EventType<SopaEvent<?>>) type,
|
||||
(EventHandler<SopaEvent<?>>) handler
|
||||
));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void removeAll() {
|
||||
handlers.forEach((type, handler) -> Events.removeListener(
|
||||
(EventType<SopaEvent<?>>) type,
|
||||
(EventHandler<SopaEvent<?>>) handler
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.event.EventType;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Events {
|
||||
private static final Logger log = Logger.getLogger(Events.class.getName());
|
||||
private static Stage eventNode = null;
|
||||
|
||||
public static void setGlobalEventNode(Stage stage) {
|
||||
eventNode = stage;
|
||||
}
|
||||
|
||||
public static <T extends SopaEvent<?>> void addListener(
|
||||
EventType<T> type,
|
||||
EventHandler<T> handler
|
||||
) {
|
||||
eventNode.addEventHandler(type, handler);
|
||||
}
|
||||
|
||||
public static <T extends SopaEvent<?>> void removeListener(
|
||||
EventType<T> type,
|
||||
EventHandler<T> handler
|
||||
) {
|
||||
eventNode.removeEventHandler(type, handler);
|
||||
}
|
||||
|
||||
public static void emit(SopaEvent<?> event) {
|
||||
if (null == eventNode) return;
|
||||
if (event.getEventType() != UiEvent.WATCHER_HEARTBEAT)
|
||||
log.info("Firing %s.".formatted(event.getEventType().getName()));
|
||||
if (!javafx.application.Platform.isFxApplicationThread()) {
|
||||
javafx.application.Platform.runLater(() -> eventNode.fireEvent(event));
|
||||
} else {
|
||||
eventNode.fireEvent(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class ProjectEvent extends SopaEvent<Path> {
|
||||
public static final EventType<ProjectEvent> ADDED = new EventType<>(Event.ANY, "PROJECT_ADDED");
|
||||
public static final EventType<ProjectEvent> REMOVED = new EventType<>(Event.ANY, "PROJECT_REMOVED");
|
||||
public static final EventType<ProjectEvent> CHANGED = new EventType<>(Event.ANY, "PROJECT_CHANGED");
|
||||
|
||||
public ProjectEvent(EventType<? extends Event> eventType, Path payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import com.molnarandrei.sopa.ui.navpane.TreeIdentity;
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
public class ProjectTreeViewEvent extends SopaEvent<TreeIdentity> {
|
||||
public static final EventType<ProjectTreeViewEvent> SELECTED = new EventType<>(Event.ANY, "PROJECT_PANE_SELECTED");
|
||||
|
||||
public ProjectTreeViewEvent(EventType<? extends Event> eventType, TreeIdentity payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class ResponseEvent extends SopaEvent<Path> {
|
||||
public static final EventType<ResponseEvent> ADDED = new EventType<>(Event.ANY, "RESPONSE_ADDED");
|
||||
public static final EventType<ResponseEvent> REMOVED = new EventType<>(Event.ANY, "RESPONSE_REMOVED");
|
||||
public static final EventType<ResponseEvent> CHANGED = new EventType<>(Event.ANY, "RESPONSE_CHANGED");
|
||||
|
||||
public ResponseEvent(EventType<? extends Event> eventType, Path payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class SoapCallEvent extends SopaEvent<SoapCallEvent.StepAndEndpoint> {
|
||||
public static final EventType<SoapCallEvent> STARTED = new EventType<>(Event.ANY, "SOAP_STARTED");
|
||||
public static final EventType<SoapCallEvent> FINISHED = new EventType<>(Event.ANY, "SOAP_LOGGED");
|
||||
public record StepAndEndpoint(Path step, String endpoint) {}
|
||||
|
||||
public SoapCallEvent(EventType<? extends Event> eventType, StepAndEndpoint payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** Payload: the step paths queued in the job, in execution order. */
|
||||
public class SoapJobEvent extends SopaEvent<List<Path>> {
|
||||
public static final EventType<SoapJobEvent> STARTED = new EventType<>(Event.ANY, "SOAP_JOB_STARTED");
|
||||
public static final EventType<SoapJobEvent> FINISHED = new EventType<>(Event.ANY, "SOAP_JOB_FINISHED");
|
||||
|
||||
public SoapJobEvent(EventType<? extends Event> eventType, List<Path> payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
public abstract class SopaEvent<T> extends Event {
|
||||
private final T payload;
|
||||
|
||||
public SopaEvent(EventType<? extends Event> eventType, T payload) {
|
||||
super(eventType);
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
public T get() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class StepEvent extends SopaEvent<StepEvent.StepAndProject> {
|
||||
public static final EventType<StepEvent> ADDED = new EventType<>(Event.ANY, "STEP_ADDED");
|
||||
public static final EventType<StepEvent> REMOVED = new EventType<>(Event.ANY, "STEP_REMOVED");
|
||||
public static final EventType<StepEvent> CHANGED = new EventType<>(Event.ANY, "STEP_CHANGED");
|
||||
|
||||
public record StepAndProject(Path step, Path testCase, Path project) {}
|
||||
|
||||
public StepEvent(EventType<? extends Event> eventType, StepAndProject payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class TestCaseEvent extends SopaEvent<TestCaseEvent.TestCaseAndProject> {
|
||||
public static final EventType<TestCaseEvent> ADDED = new EventType<>(Event.ANY, "TESTCASE_ADDED");
|
||||
public static final EventType<TestCaseEvent> REMOVED = new EventType<>(Event.ANY, "TESTCASE_REMOVED");
|
||||
public static final EventType<TestCaseEvent> CHANGED = new EventType<>(Event.ANY, "TESTCASE_CHANGED");
|
||||
|
||||
public record TestCaseAndProject(Path testCase, Path project) {}
|
||||
|
||||
public TestCaseEvent(EventType<? extends Event> eventType, TestCaseAndProject payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.molnarandrei.sopa.events;
|
||||
|
||||
import com.molnarandrei.sopa.wsdl.WsdlRemote;
|
||||
import javafx.event.Event;
|
||||
import javafx.event.EventType;
|
||||
|
||||
import javax.xml.namespace.QName;
|
||||
import java.nio.file.Path;
|
||||
|
||||
|
||||
public class UiEvent extends SopaEvent<Object> {
|
||||
public static final EventType<SopaEvent<Object>> WATCHER_HEARTBEAT = new EventType<>(Event.ANY, "UI_WATCHER_HEARTBEAT");
|
||||
public static final EventType<SopaEvent<Object>> ACTION_SELECTED = new EventType<>(Event.ANY, "UI_ACTION_SELECTED");
|
||||
|
||||
/** @param path the step or testcase the action was selected for. */
|
||||
/** @param endpoint the endpoint whose WSDL has the action, as written, before its properties are replaced. */
|
||||
public record ActionSelection(Path path, String endpoint, String soapAction, QName object, WsdlRemote.Download wsdl) {}
|
||||
|
||||
public UiEvent(EventType<? extends Event> eventType, Object payload) {
|
||||
super(eventType, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.molnarandrei.sopa.project;
|
||||
|
||||
import com.molnarandrei.sopa.data.Trash;
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.DoesNotExistException;
|
||||
import com.molnarandrei.sopa.data.EmptyException;
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.*;
|
||||
import com.molnarandrei.sopa.data.yaml.Yaml;
|
||||
import tools.jackson.core.JacksonException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* IO operations belong here.
|
||||
* Assume the filesystem to be the single source of truth.
|
||||
* IDEA filelocks?
|
||||
*/
|
||||
public class ProjectRepository {
|
||||
private static final Logger log = Logger.getLogger(ProjectRepository.class.getName());
|
||||
|
||||
|
||||
public static Project get(Path projectPath) throws RepositoryException {
|
||||
if (! Files.isReadable(projectPath)) throw new DoesNotExistException(projectPath, "Unreadable");
|
||||
try {
|
||||
var project = Files.readString(projectPath);
|
||||
if (project.isBlank())
|
||||
throw new EmptyException(projectPath, "Project file is empty");
|
||||
var obj = Yaml.toProject(project);
|
||||
if (obj == null)
|
||||
throw new RepositoryException(projectPath, "Not a project");
|
||||
return obj;
|
||||
} catch (RepositoryException repo) {
|
||||
throw repo;
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(projectPath, "Could not read file", io);
|
||||
} catch (JacksonException mapping) {
|
||||
throw new RepositoryException(projectPath, "Bad format", mapping);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isProjectFolder(Path projectDir) {
|
||||
return Files.isReadable(projectDir.resolve("project.yml"));
|
||||
}
|
||||
|
||||
public static void update(Path projectPath, Project project) throws RepositoryException{
|
||||
try {
|
||||
var yaml = Yaml.toYaml(project);
|
||||
Files.writeString(projectPath, yaml);
|
||||
ProjectMonitors.trigger(projectPath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(projectPath, "Cannot write project", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean canHoldNewProject(Path projectDir) {
|
||||
var directory = projectDir.toAbsolutePath();
|
||||
if (Files.exists(directory)) return isEmptyFolder(directory);
|
||||
var parent = directory.getParent();
|
||||
return parent != null && Files.isDirectory(parent);
|
||||
}
|
||||
|
||||
private static boolean isEmptyFolder(Path directory) {
|
||||
if (! Files.isDirectory(directory)) return false;
|
||||
try (var entries = Files.list(directory)) {
|
||||
return entries.findAny().isEmpty();
|
||||
} catch (IOException unreadable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void initializeProject(Path projectDir, Project project) throws RepositoryException {
|
||||
var projectFile = projectDir.resolve("project.yml");
|
||||
try {
|
||||
Files.createDirectories(projectDir);
|
||||
if (! Files.exists(projectFile)) {
|
||||
Files.createFile(projectFile);
|
||||
}
|
||||
if (Files.size(projectFile) == 0) {
|
||||
var yaml = Yaml.toYaml(project);
|
||||
Files.writeString(projectFile, yaml);
|
||||
}
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(projectFile, "Could not create project file", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeAgentsFile(Path projectDir) throws RepositoryException {
|
||||
var agentsFile = projectDir.resolve("AGENTS.md");
|
||||
try (var template = ProjectRepository.class.getResourceAsStream("/AGENTS.md")) {
|
||||
if (template == null)
|
||||
throw new IOException("AGENTS.md is not packaged");
|
||||
Files.copy(template, agentsFile);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(agentsFile, "Could not create agents file", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static void copyProjectDirectory(Path fromProjectDirectory, Path toProjectDirectory) throws RepositoryException {
|
||||
try {
|
||||
if (!Files.isDirectory(fromProjectDirectory)) {
|
||||
throw new RepositoryException(toProjectDirectory, "Project to clone does not exist");
|
||||
}
|
||||
if (Files.exists(toProjectDirectory)) {
|
||||
throw new RepositoryException(toProjectDirectory, "Project folder already exists");
|
||||
}
|
||||
|
||||
Files.createDirectory(toProjectDirectory);
|
||||
|
||||
var project = get(fromProjectDirectory.resolve("project.yml"));
|
||||
var rename = toProjectDirectory.getFileName().toString().replaceAll("-", " ").replaceAll("_", " ");
|
||||
rename = Character.toUpperCase(rename.charAt(0)) + rename.substring(1);
|
||||
project.setName(rename);
|
||||
var yaml = Yaml.toYaml(project);
|
||||
Files.writeString(toProjectDirectory.resolve("project.yml"), yaml);
|
||||
|
||||
Utils.copyDirectory(fromProjectDirectory, toProjectDirectory,
|
||||
path -> "project.yml".equals(path.getFileName().toString()));
|
||||
|
||||
} catch (RepositoryException e) {
|
||||
throw e;
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(toProjectDirectory, "Could create step file", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteProject(Path projectPath) throws RepositoryException {
|
||||
if (! Files.exists(projectPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var projectDirectory = projectPath.getParent();
|
||||
try {
|
||||
if (! Files.isDirectory(projectDirectory))
|
||||
return;
|
||||
|
||||
try (var walk = Files.walk(projectDirectory)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> {
|
||||
try {
|
||||
Files.delete(p);
|
||||
} catch (IOException ignore) {}
|
||||
});
|
||||
}
|
||||
|
||||
if (Files.exists(projectDirectory))
|
||||
throw new IOException("Not deleted.");
|
||||
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(projectPath, "Could not delete project", io);
|
||||
|
||||
} finally {
|
||||
ProjectMonitors.trigger(projectDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the folder of a closed project to the {@link Trash}. @return where it is kept. */
|
||||
public static Path trashProject(Path projectPath) throws RepositoryException {
|
||||
try {
|
||||
return Trash.keep(projectPath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(projectPath, "Could not delete project", io);
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the folder of a project back from the {@link Trash}; it is still closed. */
|
||||
public static void restoreProject(Path projectPath, Path kept) throws RepositoryException {
|
||||
try {
|
||||
Trash.restore(kept, projectPath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(projectPath, io.getMessage(), io);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.molnarandrei.sopa.project;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.trash.TrashService;
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.yaml.Project;
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ProjectEvent;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.molnarandrei.sopa.Utils.renameIndexed;
|
||||
import static com.molnarandrei.sopa.data.yaml.Kind.project;
|
||||
|
||||
/**
|
||||
* All operations over projects at the application level belong here.
|
||||
* Including UI operations such as showing a dialog that we cannot read something.
|
||||
*/
|
||||
public class ProjectService {
|
||||
private static final Logger log = Logger.getLogger(ProjectService.class.getName());
|
||||
|
||||
public static Project read(Path projectPath) {
|
||||
try {
|
||||
return ProjectRepository.get(projectPath);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
log.log(Level.SEVERE, "Cannot read project %s.".formatted(projectPath), readOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido abrir el fichero del proyecto:\n%s"
|
||||
.formatted(projectPath),
|
||||
readOrParseErr.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void write(Path projectPath, Project project) {
|
||||
removeBlankHeaders(project);
|
||||
try {
|
||||
ProjectRepository.update(projectPath, project);
|
||||
} catch (RepositoryException cannotWrite) {
|
||||
log.log(Level.SEVERE, "Cannot write project %s.".formatted(projectPath), cannotWrite);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido guardar el proyecto:\n%s"
|
||||
.formatted(projectPath),
|
||||
cannotWrite.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static void removeBlankHeaders(Project project) {
|
||||
project.getHeaders().entrySet().removeIf(entry ->
|
||||
entry.getKey() == null || entry.getKey().isBlank() ||
|
||||
entry.getValue() == null || entry.getValue().isBlank()
|
||||
);
|
||||
}
|
||||
|
||||
public static boolean create(Path projectDirectory, Project project, boolean createAgentsFile) {
|
||||
log.info("Creating project %s.".formatted(projectDirectory));
|
||||
removeBlankHeaders(project);
|
||||
try {
|
||||
ProjectRepository.initializeProject(projectDirectory, project);
|
||||
if (createAgentsFile)
|
||||
ProjectRepository.writeAgentsFile(projectDirectory);
|
||||
ProjectMonitors.start(projectDirectory);
|
||||
return true;
|
||||
} catch (RepositoryException directoryInaccessible) {
|
||||
log.log(Level.WARNING, "Create project error.", directoryInaccessible);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido crear el proyecto:\n%s"
|
||||
.formatted(projectDirectory),
|
||||
directoryInaccessible.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void duplicate(Path projectPath) {
|
||||
log.info("Copying project %s.".formatted(projectPath));
|
||||
Path copiedProjectDirectory = null;
|
||||
Path toProjectDirectory = null;
|
||||
try {
|
||||
copiedProjectDirectory = projectPath.getParent();
|
||||
toProjectDirectory = renameIndexed(copiedProjectDirectory);
|
||||
ProjectRepository.copyProjectDirectory(copiedProjectDirectory, toProjectDirectory);
|
||||
ProjectMonitors.start(toProjectDirectory);
|
||||
|
||||
} catch (RepositoryException readWriteOrParseErr) {
|
||||
log.log(Level.WARNING, "Copy project error.", readWriteOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido copiar el proyecto de orgigen/destino:\n%s\n%s"
|
||||
.formatted(copiedProjectDirectory, toProjectDirectory),
|
||||
readWriteOrParseErr.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void close(Path projectPath) {
|
||||
log.info("Closing project %s.".formatted(projectPath));
|
||||
Events.emit(new ProjectEvent(ProjectEvent.REMOVED, projectPath));
|
||||
ProjectMonitors.stop(projectPath.getParent());
|
||||
}
|
||||
|
||||
/** Closes the project and moves it to the trash: {@link TrashService#undo()} restores and opens it. */
|
||||
public static void delete(Path projectPath) {
|
||||
log.info("Deleting project %s.".formatted(projectPath));
|
||||
close(projectPath);
|
||||
try {
|
||||
TrashService.remember(Kind.project, projectPath, ProjectRepository.trashProject(projectPath));
|
||||
} catch (RepositoryException cannotDeleteAllFiles) {
|
||||
log.log(Level.WARNING, "Delete project error.", cannotDeleteAllFiles);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido eliminar el proyecto:\n%s"
|
||||
.formatted(projectPath),
|
||||
cannotDeleteAllFiles.getMessage()
|
||||
);
|
||||
if (Files.exists(projectPath)) open(projectPath);
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts back and opens a project moved to the trash by {@link #delete(Path)}. */
|
||||
public static boolean restore(Path projectPath, Path kept) {
|
||||
log.info("Restoring project %s.".formatted(projectPath));
|
||||
try {
|
||||
ProjectRepository.restoreProject(projectPath, kept);
|
||||
} catch (RepositoryException cannotRestore) {
|
||||
log.log(Level.WARNING, "Cannot restore project %s.".formatted(projectPath), cannotRestore);
|
||||
Utils.alert(
|
||||
"No se puede deshacer",
|
||||
"No se ha podido restaurar el proyecto:\n%s".formatted(projectPath),
|
||||
cannotRestore.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
open(projectPath);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void open(Path projectPath) {
|
||||
try {
|
||||
ProjectRepository.get(projectPath);
|
||||
ProjectMonitors.start(projectPath.getParent());
|
||||
} catch (RepositoryException repo) {
|
||||
Utils.alert(
|
||||
"Error de lectura",
|
||||
"Error al abrir el proyecto",
|
||||
repo.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.molnarandrei.sopa.server;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* In-memory repository. Not thread-safe on purpose: the test server is single-threaded.
|
||||
*/
|
||||
public class SchoolRepository {
|
||||
private static final Logger LOG = Logger.getLogger(SchoolRepository.class.getName());
|
||||
|
||||
public record Classroom(int id, String name) {}
|
||||
|
||||
public record Alumnus(int id, int classroomId, String name, int age) {}
|
||||
|
||||
private final Map<Integer, Classroom> classrooms = new LinkedHashMap<>();
|
||||
private final Map<Integer, Alumnus> alumni = new LinkedHashMap<>();
|
||||
private int nextClassroomId = 1;
|
||||
private int nextAlumnusId = 1;
|
||||
|
||||
public SchoolRepository() {
|
||||
var a = createClassroom("1A");
|
||||
for (String name : List.of("Ana", "Bogdan", "Carmen", "Dan", "Elena")) {
|
||||
createAlumnus(a.id(), name, 10);
|
||||
}
|
||||
var b = createClassroom("2B");
|
||||
for (String name : List.of("Florin", "Gabriela", "Horia", "Ioana", "Jianu",
|
||||
"Laura", "Mihai", "Nicoleta", "Ovidiu", "Paula")) {
|
||||
createAlumnus(b.id(), name, 11);
|
||||
}
|
||||
LOG.info("Seeded %d classrooms, %d alumni".formatted(classrooms.size(), alumni.size()));
|
||||
}
|
||||
|
||||
// ---- classrooms ----
|
||||
|
||||
public List<Classroom> listClassrooms() {
|
||||
return new ArrayList<>(classrooms.values());
|
||||
}
|
||||
|
||||
public Classroom getClassroom(int id) {
|
||||
var c = classrooms.get(id);
|
||||
if (c == null) throw SoapFault.client("Classroom " + id + " not found");
|
||||
return c;
|
||||
}
|
||||
|
||||
public Classroom createClassroom(String name) {
|
||||
var c = new Classroom(nextClassroomId++, name);
|
||||
classrooms.put(c.id(), c);
|
||||
LOG.info("Created " + c);
|
||||
return c;
|
||||
}
|
||||
|
||||
public Classroom updateClassroom(int id, String name) {
|
||||
getClassroom(id);
|
||||
var c = new Classroom(id, name);
|
||||
classrooms.put(id, c);
|
||||
LOG.info("Updated " + c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Deletes the classroom and all its alumni. */
|
||||
public void deleteClassroom(int id) {
|
||||
getClassroom(id);
|
||||
classrooms.remove(id);
|
||||
alumni.values().removeIf(al -> al.classroomId() == id);
|
||||
LOG.info("Deleted classroom " + id + " and its alumni");
|
||||
}
|
||||
|
||||
public List<Alumnus> getClassroomAlumni(int classroomId) {
|
||||
getClassroom(classroomId);
|
||||
return alumni.values().stream().filter(al -> al.classroomId() == classroomId).toList();
|
||||
}
|
||||
|
||||
// ---- alumni ----
|
||||
|
||||
public Alumnus getAlumnus(int id) {
|
||||
var al = alumni.get(id);
|
||||
if (al == null) throw SoapFault.client("Alumnus " + id + " not found");
|
||||
return al;
|
||||
}
|
||||
|
||||
public Alumnus createAlumnus(int classroomId, String name, int age) {
|
||||
getClassroom(classroomId);
|
||||
var al = new Alumnus(nextAlumnusId++, classroomId, name, age);
|
||||
alumni.put(al.id(), al);
|
||||
LOG.info("Created " + al);
|
||||
return al;
|
||||
}
|
||||
|
||||
public Alumnus updateAlumnus(int id, int classroomId, String name, int age) {
|
||||
getAlumnus(id);
|
||||
getClassroom(classroomId);
|
||||
var al = new Alumnus(id, classroomId, name, age);
|
||||
alumni.put(id, al);
|
||||
LOG.info("Updated " + al);
|
||||
return al;
|
||||
}
|
||||
|
||||
public void deleteAlumnus(int id) {
|
||||
getAlumnus(id);
|
||||
alumni.remove(id);
|
||||
LOG.info("Deleted alumnus " + id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.molnarandrei.sopa.server;
|
||||
|
||||
import com.molnarandrei.sopa.server.SchoolRepository.Alumnus;
|
||||
import com.molnarandrei.sopa.server.SchoolRepository.Classroom;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Maps a SOAP operation (body element name) to a repository call and returns the response body XML.
|
||||
* Request children are matched by local name only, namespace is ignored to keep clients simple.
|
||||
*/
|
||||
public class SchoolService {
|
||||
public static final String NS = "http://sopa.molnarandrei.com/school";
|
||||
|
||||
/** Every operation; the WSDL is generated from this list. */
|
||||
public static final List<String> OPERATIONS = List.of(
|
||||
"ListClassrooms", "GetClassroom", "CreateClassroom", "UpdateClassroom", "DeleteClassroom",
|
||||
"GetClassroomAlumni",
|
||||
"GetAlumnus", "CreateAlumnus", "UpdateAlumnus", "DeleteAlumnus"
|
||||
);
|
||||
|
||||
private static final long WRITE_DELAY_MS = 500;
|
||||
|
||||
private final SchoolRepository repo = new SchoolRepository();
|
||||
|
||||
public String call(String op, Element req) {
|
||||
String inner = switch (op) {
|
||||
case "ListClassrooms" -> classrooms(repo.listClassrooms());
|
||||
case "GetClassroom" -> classroom(repo.getClassroom(intArg(req, "id")));
|
||||
case "CreateClassroom" -> {
|
||||
slow();
|
||||
yield classroom(repo.createClassroom(strArg(req, "name")));
|
||||
}
|
||||
case "UpdateClassroom" -> {
|
||||
slow();
|
||||
yield classroom(repo.updateClassroom(intArg(req, "id"), strArg(req, "name")));
|
||||
}
|
||||
case "DeleteClassroom" -> {
|
||||
repo.deleteClassroom(intArg(req, "id"));
|
||||
yield "<deleted>true</deleted>";
|
||||
}
|
||||
case "GetClassroomAlumni" -> alumni(repo.getClassroomAlumni(intArg(req, "classroomId")));
|
||||
case "GetAlumnus" -> alumnus(repo.getAlumnus(intArg(req, "id")));
|
||||
case "CreateAlumnus" -> {
|
||||
slow();
|
||||
yield alumnus(repo.createAlumnus(
|
||||
intArg(req, "classroomId"), strArg(req, "name"), intArg(req, "age")));
|
||||
}
|
||||
case "UpdateAlumnus" -> {
|
||||
slow();
|
||||
yield alumnus(repo.updateAlumnus(
|
||||
intArg(req, "id"), intArg(req, "classroomId"), strArg(req, "name"), intArg(req, "age")));
|
||||
}
|
||||
case "DeleteAlumnus" -> {
|
||||
repo.deleteAlumnus(intArg(req, "id"));
|
||||
yield "<deleted>true</deleted>";
|
||||
}
|
||||
default -> throw SoapFault.client("Unknown operation: " + op);
|
||||
};
|
||||
return "<" + op + "Response xmlns=\"" + NS + "\">" + inner + "</" + op + "Response>";
|
||||
}
|
||||
|
||||
// ---- request parsing ----
|
||||
|
||||
private static String strArg(Element req, String name) {
|
||||
NodeList nodes = req.getElementsByTagNameNS("*", name);
|
||||
if (nodes.getLength() == 0) throw SoapFault.client("Missing element: " + name);
|
||||
return nodes.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
private static int intArg(Element req, String name) {
|
||||
String value = strArg(req, name);
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw SoapFault.client("Element " + name + " is not an integer: " + value);
|
||||
}
|
||||
}
|
||||
|
||||
private static void slow() {
|
||||
try {
|
||||
Thread.sleep(WRITE_DELAY_MS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
// ---- response writing ----
|
||||
|
||||
private static String classrooms(List<Classroom> list) {
|
||||
var sb = new StringBuilder();
|
||||
list.forEach(c -> sb.append(classroom(c)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String classroom(Classroom c) {
|
||||
return "<classroom><id>" + c.id() + "</id><name>" + esc(c.name()) + "</name></classroom>";
|
||||
}
|
||||
|
||||
private static String alumni(List<Alumnus> list) {
|
||||
var sb = new StringBuilder();
|
||||
list.forEach(a -> sb.append(alumnus(a)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String alumnus(Alumnus a) {
|
||||
return "<alumnus><id>" + a.id() + "</id><classroomId>" + a.classroomId()
|
||||
+ "</classroomId><name>" + esc(a.name()) + "</name><age>" + a.age() + "</age></alumnus>";
|
||||
}
|
||||
|
||||
static String esc(String s) {
|
||||
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.molnarandrei.sopa.server;
|
||||
|
||||
/**
|
||||
* Thrown anywhere in the server to produce a SOAP fault.
|
||||
* CLIENT maps to soap:Client (1.1) / soap:Sender (1.2), SERVER to soap:Server / soap:Receiver.
|
||||
*/
|
||||
public class SoapFault extends RuntimeException {
|
||||
public enum Code { CLIENT, SERVER, VERSION_MISMATCH }
|
||||
|
||||
private final Code code;
|
||||
private final int httpStatus;
|
||||
|
||||
public SoapFault(Code code, String message, int httpStatus) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
public static SoapFault client(String message) {
|
||||
return new SoapFault(Code.CLIENT, message, 0);
|
||||
}
|
||||
|
||||
public Code getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
/** 0 means "let the SOAP version decide". */
|
||||
public int getHttpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package com.molnarandrei.sopa.server;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Test server for our app
|
||||
* POST /v11 SOAP 1.1: Content-Type text/xml, action in the SOAPAction header
|
||||
* POST /v12 SOAP 1.2: Content-Type application/soap+xml; action="..." (no SOAPAction header)
|
||||
* GET /v11?wsdl WSDL with only the SOAP 1.1 binding and port (soap:binding, soap:address)
|
||||
* GET /v12?wsdl WSDL with only the SOAP 1.2 binding and port (soap12:binding, soap12:address)
|
||||
* <p>
|
||||
* Each endpoint shows its SOAP version by the standard means:
|
||||
* its WSDL binding and address, the Content-Type of its responses, and on an envelope of the other version
|
||||
* a VersionMismatch fault with the SOAP 1.2 Upgrade header listing the envelope it supports
|
||||
* (SOAP 1.2 part 1, 5.4.7 and appendix A).
|
||||
*/
|
||||
public class TestServer {
|
||||
private static final Logger LOG = Logger.getLogger(TestServer.class.getName());
|
||||
|
||||
enum Version {
|
||||
V11("1.1", "http://schemas.xmlsoap.org/soap/envelope/", "text/xml"),
|
||||
V12("1.2", "http://www.w3.org/2003/05/soap-envelope", "application/soap+xml");
|
||||
|
||||
final String title;
|
||||
final String envelopeNs;
|
||||
final String contentType;
|
||||
|
||||
Version(String title, String envelopeNs, String contentType) {
|
||||
this.title = title;
|
||||
this.envelopeNs = envelopeNs;
|
||||
this.contentType = contentType;
|
||||
}
|
||||
}
|
||||
|
||||
private final SchoolService service = new SchoolService();
|
||||
|
||||
/** @param port 0 for any free one. */
|
||||
public static HttpServer start(int port) throws IOException {
|
||||
var server = HttpServer.create(new InetSocketAddress(port), 0);
|
||||
var app = new TestServer();
|
||||
server.createContext("/v11", ex -> app.handle(ex, Version.V11));
|
||||
server.createContext("/v12", ex -> app.handle(ex, Version.V12));
|
||||
server.setExecutor(null);
|
||||
server.start();
|
||||
LOG.info("SOAP test server on http://localhost:%d (SOAP 1.1: /v11?wsdl, SOAP 1.2: /v12?wsdl)"
|
||||
.formatted(server.getAddress().getPort()));
|
||||
return server;
|
||||
}
|
||||
|
||||
private void handle(HttpExchange ex, Version v) throws IOException {
|
||||
try (ex) {
|
||||
String method = ex.getRequestMethod();
|
||||
String query = ex.getRequestURI().getQuery();
|
||||
LOG.info("SOAP %s %s %s".formatted(v.title, method, ex.getRequestURI()));
|
||||
|
||||
if (method.equals("GET") && query != null && query.equalsIgnoreCase("wsdl")) {
|
||||
String host = ex.getRequestHeaders().getFirst("Host");
|
||||
send(ex, 200, "text/xml; charset=utf-8", Wsdl.build("http://" + host, v));
|
||||
return;
|
||||
}
|
||||
if (!method.equals("POST")) {
|
||||
send(ex, 405, "text/plain; charset=utf-8", "Use POST for SOAP calls or GET ?wsdl\n");
|
||||
return;
|
||||
}
|
||||
|
||||
String response;
|
||||
int status = 200;
|
||||
try {
|
||||
response = envelope(v, soapCall(ex, v));
|
||||
} catch (SoapFault f) {
|
||||
LOG.warning("Fault: " + f.getMessage());
|
||||
status = faultStatus(v, f);
|
||||
var header = f.getCode() == SoapFault.Code.VERSION_MISMATCH ? upgrade(v) : "";
|
||||
response = envelope(v, header, fault(v, f));
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Server error", e);
|
||||
var f = new SoapFault(SoapFault.Code.SERVER, String.valueOf(e.getMessage()), 0);
|
||||
status = 500;
|
||||
response = envelope(v, fault(v, f));
|
||||
}
|
||||
send(ex, status, v.contentType + "; charset=utf-8", response);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the response body content (without envelope). */
|
||||
private String soapCall(HttpExchange ex, Version v) throws Exception {
|
||||
String contentType = ex.getRequestHeaders().getFirst("Content-Type");
|
||||
if (contentType == null || !contentType.toLowerCase().startsWith(v.contentType)) {
|
||||
throw new SoapFault(SoapFault.Code.CLIENT,
|
||||
"SOAP %s expects Content-Type %s, got %s".formatted(v.title, v.contentType, contentType), 415);
|
||||
}
|
||||
|
||||
String action = v == Version.V11
|
||||
? unquote(ex.getRequestHeaders().getFirst("SOAPAction"))
|
||||
: actionParam(contentType);
|
||||
|
||||
String xml = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
|
||||
LOG.fine("Request:\n" + xml);
|
||||
Element body = parseBody(xml, v);
|
||||
String bodyOp = body.getLocalName();
|
||||
|
||||
String op;
|
||||
if (action == null || action.isEmpty()) {
|
||||
op = bodyOp;
|
||||
LOG.info("No action, using body element: " + op);
|
||||
} else {
|
||||
op = action.substring(action.lastIndexOf('/') + 1);
|
||||
if (!op.equals(bodyOp)) {
|
||||
throw SoapFault.client("Action '%s' does not match body element '%s'".formatted(action, bodyOp));
|
||||
}
|
||||
}
|
||||
|
||||
LOG.info("Operation " + op);
|
||||
String result = service.call(op, body);
|
||||
LOG.fine("Response body: " + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static Element parseBody(String xml, Version v) throws Exception {
|
||||
var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // SOAP forbids DTDs
|
||||
Document doc;
|
||||
try {
|
||||
doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception e) {
|
||||
throw SoapFault.client("Malformed XML: " + e.getMessage());
|
||||
}
|
||||
|
||||
Element envelope = doc.getDocumentElement();
|
||||
if (!"Envelope".equals(envelope.getLocalName())) {
|
||||
throw SoapFault.client("Root element is not Envelope");
|
||||
}
|
||||
if (!v.envelopeNs.equals(envelope.getNamespaceURI())) {
|
||||
throw new SoapFault(SoapFault.Code.VERSION_MISMATCH,
|
||||
"Endpoint is SOAP %s, envelope namespace is %s".formatted(v.title, envelope.getNamespaceURI()), 0);
|
||||
}
|
||||
Element body = firstChild(envelope, "Body");
|
||||
if (body == null) throw SoapFault.client("Missing Body");
|
||||
Element payload = firstChild(body, null);
|
||||
if (payload == null) throw SoapFault.client("Empty Body");
|
||||
return payload;
|
||||
}
|
||||
|
||||
/** First element child, optionally with the given local name. */
|
||||
private static Element firstChild(Element parent, String localName) {
|
||||
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
|
||||
if (n instanceof Element e && (localName == null || localName.equals(e.getLocalName()))) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** SOAP 1.2: action="..." parameter of the Content-Type header. */
|
||||
private static String actionParam(String contentType) {
|
||||
for (String part : contentType.split(";")) {
|
||||
String p = part.trim();
|
||||
if (p.toLowerCase().startsWith("action=")) {
|
||||
return unquote(p.substring("action=".length()));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String unquote(String s) {
|
||||
if (s == null) return null;
|
||||
s = s.trim();
|
||||
if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"")) s = s.substring(1, s.length() - 1);
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---- response writing ----
|
||||
|
||||
private static String envelope(Version v, String bodyContent) {
|
||||
return envelope(v, "", bodyContent);
|
||||
}
|
||||
|
||||
private static String envelope(Version v, String headerContent, String bodyContent) {
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
+ "<soap:Envelope xmlns:soap=\"" + v.envelopeNs + "\">"
|
||||
+ (headerContent.isEmpty() ? "" : "<soap:Header>" + headerContent + "</soap:Header>")
|
||||
+ "<soap:Body>" + bodyContent + "</soap:Body></soap:Envelope>";
|
||||
}
|
||||
|
||||
/**
|
||||
* SOAP 1.2 Upgrade header block naming the only envelope {@code v} supports.
|
||||
* It is in the SOAP 1.2 namespace even in SOAP 1.1 responses, as SOAP 1.2 appendix A says.
|
||||
*/
|
||||
private static String upgrade(Version v) {
|
||||
return "<upg:Upgrade xmlns:upg=\"" + Version.V12.envelopeNs + "\">"
|
||||
+ "<upg:SupportedEnvelope qname=\"env:Envelope\" xmlns:env=\"" + v.envelopeNs + "\"/>"
|
||||
+ "</upg:Upgrade>";
|
||||
}
|
||||
|
||||
private static String fault(Version v, SoapFault f) {
|
||||
String msg = SchoolService.esc(String.valueOf(f.getMessage()));
|
||||
if (v == Version.V11) {
|
||||
String code = switch (f.getCode()) {
|
||||
case CLIENT -> "soap:Client";
|
||||
case SERVER -> "soap:Server";
|
||||
case VERSION_MISMATCH -> "soap:VersionMismatch";
|
||||
};
|
||||
return "<soap:Fault><faultcode>" + code + "</faultcode><faultstring>" + msg + "</faultstring></soap:Fault>";
|
||||
}
|
||||
String code = switch (f.getCode()) {
|
||||
case CLIENT -> "soap:Sender";
|
||||
case SERVER -> "soap:Receiver";
|
||||
case VERSION_MISMATCH -> "soap:VersionMismatch";
|
||||
};
|
||||
return "<soap:Fault><soap:Code><soap:Value>" + code + "</soap:Value></soap:Code>"
|
||||
+ "<soap:Reason><soap:Text xml:lang=\"en\">" + msg + "</soap:Text></soap:Reason></soap:Fault>";
|
||||
}
|
||||
|
||||
/** SOAP 1.1: every fault is 500. SOAP 1.2: Sender faults are 400, the rest 500. */
|
||||
private static int faultStatus(Version v, SoapFault f) {
|
||||
if (f.getHttpStatus() != 0) return f.getHttpStatus();
|
||||
if (v == Version.V12 && f.getCode() == SoapFault.Code.CLIENT) return 400;
|
||||
return 500;
|
||||
}
|
||||
|
||||
private static void send(HttpExchange ex, int status, String contentType, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
ex.getResponseHeaders().set("Content-Type", contentType);
|
||||
ex.sendResponseHeaders(status, bytes.length);
|
||||
ex.getResponseBody().write(bytes);
|
||||
LOG.info("-> HTTP " + status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.molnarandrei.sopa.server;
|
||||
|
||||
import static com.molnarandrei.sopa.server.SchoolService.NS;
|
||||
import static com.molnarandrei.sopa.server.SchoolService.OPERATIONS;
|
||||
|
||||
/**
|
||||
* Builds WSDL 1.1 documents for the endpoints:
|
||||
* a SOAP 1.1 binding/port at {base}/v11 and a SOAP 1.2 binding/port at {base}/v12.
|
||||
* {base}/v11?wsdl has only the SOAP 1.1 binding and port, {base}/v12?wsdl only the SOAP 1.2 ones,
|
||||
* so the WSDL of each endpoint tells which SOAP version it speaks.
|
||||
* {@link #build(String)} describes both, as one service with two ports.
|
||||
* <p>
|
||||
* Style is document/literal wrapped: the body element name equals the operation name,
|
||||
* which is what lets the server dispatch on the body when the action is empty.
|
||||
* soapAction for every operation is NS + "/" + operation.
|
||||
*/
|
||||
public class Wsdl {
|
||||
|
||||
private static final String TYPES = """
|
||||
<wsdl:types>
|
||||
<xs:schema targetNamespace="%1$s" elementFormDefault="qualified">
|
||||
<xs:complexType name="Classroom">
|
||||
<xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
<xs:element name="name" type="xs:string"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
<xs:complexType name="Alumnus">
|
||||
<xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
<xs:element name="classroomId" type="xs:int"/>
|
||||
<xs:element name="name" type="xs:string"/>
|
||||
<xs:element name="age" type="xs:int"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
|
||||
<xs:element name="ListClassrooms"><xs:complexType><xs:sequence/></xs:complexType></xs:element>
|
||||
<xs:element name="ListClassroomsResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="classroom" type="tns:Classroom" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="GetClassroom"><xs:complexType><xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="GetClassroomResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="classroom" type="tns:Classroom"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="CreateClassroom"><xs:complexType><xs:sequence>
|
||||
<xs:element name="name" type="xs:string"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="CreateClassroomResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="classroom" type="tns:Classroom"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="UpdateClassroom"><xs:complexType><xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
<xs:element name="name" type="xs:string"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="UpdateClassroomResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="classroom" type="tns:Classroom"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="DeleteClassroom"><xs:complexType><xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="DeleteClassroomResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="deleted" type="xs:boolean"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="GetClassroomAlumni"><xs:complexType><xs:sequence>
|
||||
<xs:element name="classroomId" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="GetClassroomAlumniResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="alumnus" type="tns:Alumnus" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="GetAlumnus"><xs:complexType><xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="GetAlumnusResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="alumnus" type="tns:Alumnus"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="CreateAlumnus"><xs:complexType><xs:sequence>
|
||||
<xs:element name="classroomId" type="xs:int"/>
|
||||
<xs:element name="name" type="xs:string"/>
|
||||
<xs:element name="age" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="CreateAlumnusResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="alumnus" type="tns:Alumnus"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="UpdateAlumnus"><xs:complexType><xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
<xs:element name="classroomId" type="xs:int"/>
|
||||
<xs:element name="name" type="xs:string"/>
|
||||
<xs:element name="age" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="UpdateAlumnusResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="alumnus" type="tns:Alumnus"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
|
||||
<xs:element name="DeleteAlumnus"><xs:complexType><xs:sequence>
|
||||
<xs:element name="id" type="xs:int"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
<xs:element name="DeleteAlumnusResponse"><xs:complexType><xs:sequence>
|
||||
<xs:element name="deleted" type="xs:boolean"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
</xs:schema>
|
||||
</wsdl:types>
|
||||
""";
|
||||
|
||||
/** Both endpoints. */
|
||||
public static String build(String baseUrl) {
|
||||
return build(baseUrl, true, true);
|
||||
}
|
||||
|
||||
/** Only the endpoint of {@code version}. */
|
||||
static String build(String baseUrl, TestServer.Version version) {
|
||||
return build(baseUrl, version == TestServer.Version.V11, version == TestServer.Version.V12);
|
||||
}
|
||||
|
||||
private static String build(String baseUrl, boolean soap11, boolean soap12) {
|
||||
var sb = new StringBuilder();
|
||||
sb.append("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<wsdl:definitions name="School" targetNamespace="%1$s"
|
||||
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
|
||||
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
|
||||
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
|
||||
xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
xmlns:tns="%1$s">
|
||||
""".formatted(NS));
|
||||
sb.append(TYPES.formatted(NS));
|
||||
|
||||
for (String op : OPERATIONS) {
|
||||
sb.append("""
|
||||
<wsdl:message name="%1$sRequest"><wsdl:part name="parameters" element="tns:%1$s"/></wsdl:message>
|
||||
<wsdl:message name="%1$sResponse"><wsdl:part name="parameters" element="tns:%1$sResponse"/></wsdl:message>
|
||||
""".formatted(op));
|
||||
}
|
||||
|
||||
sb.append(" <wsdl:portType name=\"SchoolPortType\">\n");
|
||||
for (String op : OPERATIONS) {
|
||||
sb.append("""
|
||||
<wsdl:operation name="%1$s">
|
||||
<wsdl:input message="tns:%1$sRequest"/>
|
||||
<wsdl:output message="tns:%1$sResponse"/>
|
||||
</wsdl:operation>
|
||||
""".formatted(op));
|
||||
}
|
||||
sb.append(" </wsdl:portType>\n");
|
||||
|
||||
if (soap11) appendBinding(sb, "soap", "SchoolSoap11Binding", "");
|
||||
if (soap12) appendBinding(sb, "soap12", "SchoolSoap12Binding", " soapActionRequired=\"false\"");
|
||||
|
||||
sb.append(" <wsdl:service name=\"SchoolService\">\n");
|
||||
if (soap11) sb.append("""
|
||||
<wsdl:port name="SchoolSoap11Port" binding="tns:SchoolSoap11Binding">
|
||||
<soap:address location="%1$s/v11"/>
|
||||
</wsdl:port>
|
||||
""".formatted(baseUrl));
|
||||
if (soap12) sb.append("""
|
||||
<wsdl:port name="SchoolSoap12Port" binding="tns:SchoolSoap12Binding">
|
||||
<soap12:address location="%1$s/v12"/>
|
||||
</wsdl:port>
|
||||
""".formatted(baseUrl));
|
||||
sb.append(" </wsdl:service>\n</wsdl:definitions>\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static void appendBinding(StringBuilder sb, String prefix, String name, String extraOpAttrs) {
|
||||
sb.append("""
|
||||
<wsdl:binding name="%2$s" type="tns:SchoolPortType">
|
||||
<%1$s:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
|
||||
""".formatted(prefix, name));
|
||||
for (String op : OPERATIONS) {
|
||||
sb.append("""
|
||||
<wsdl:operation name="%2$s">
|
||||
<%1$s:operation soapAction="%3$s/%2$s"%4$s/>
|
||||
<wsdl:input><%1$s:body use="literal"/></wsdl:input>
|
||||
<wsdl:output><%1$s:body use="literal"/></wsdl:output>
|
||||
</wsdl:operation>
|
||||
""".formatted(prefix, op, NS, extraOpAttrs));
|
||||
}
|
||||
sb.append(" </wsdl:binding>\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
public class CallInitializationException extends Exception {
|
||||
|
||||
public enum MissingField {
|
||||
None("error de programa"), Endpoint("endpoint"), ActionAndBody("accion y cuerpo");
|
||||
|
||||
private final String title;
|
||||
|
||||
MissingField(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
}
|
||||
|
||||
private MissingField missingField;
|
||||
|
||||
public CallInitializationException(
|
||||
String message,
|
||||
MissingField missingField
|
||||
) {
|
||||
super(message);
|
||||
this.missingField = missingField;
|
||||
}
|
||||
|
||||
public MissingField getMissingField() {
|
||||
return missingField;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
public class MalformedEndpointException extends Exception {
|
||||
private final String endpoint;
|
||||
|
||||
public MalformedEndpointException(String message, String endpoint) {
|
||||
super(message);
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
public class PropertyMissingException extends Exception {
|
||||
private String missingKey;
|
||||
public PropertyMissingException(String message, String missingKey) {
|
||||
super(message);
|
||||
this.missingKey = missingKey;
|
||||
}
|
||||
|
||||
public String getMissingKey() {
|
||||
return missingKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
public class RawSoapCall {
|
||||
private static final Logger log = Logger.getLogger(RawSoapCall.class.getName());
|
||||
|
||||
protected SoapVersion version = SoapVersion.ONE_ONE;
|
||||
protected String endpoint = "";
|
||||
protected String action = "";
|
||||
protected Map<String, String> headers = new HashMap<>();
|
||||
protected String payload = "";
|
||||
|
||||
public HttpResponse<String> request()
|
||||
throws IOException, InterruptedException
|
||||
{
|
||||
var timeout = Config.get().getCallTimeout();
|
||||
try (
|
||||
var client = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(timeout))
|
||||
.build()
|
||||
) {
|
||||
var builder = HttpRequest.newBuilder()
|
||||
.uri(URI.create(endpoint.strip()))
|
||||
.timeout(Duration.ofSeconds(timeout))
|
||||
.POST(HttpRequest.BodyPublishers.ofString(payload));
|
||||
for (var header : headers.entrySet())
|
||||
builder.header(header.getKey(), header.getValue());
|
||||
|
||||
switch (version) {
|
||||
case SoapVersion.ONE_ONE:
|
||||
builder.header("SOAPAction", action);
|
||||
builder.header("Content-Type", "text/xml; charset=utf-8");
|
||||
break;
|
||||
case SoapVersion.ONE_TWO:
|
||||
builder.header("Content-Type", "application/soap+xml; charset=utf-8; action=\"%s\"".formatted(action));
|
||||
break;
|
||||
}
|
||||
|
||||
var request = builder.build();
|
||||
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
log.info(">> %s %s: %s".formatted( request.method(), endpoint, payload.replace("\n", "") ));
|
||||
log.info("<< %s: %s".formatted( response.statusCode(), response.body().replace("\n", "") ));
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.Assertion;
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.molnarandrei.sopa.soap.CallInitializationException.MissingField.*;
|
||||
|
||||
public class SoapCall extends RawSoapCall {
|
||||
private static final Logger log = Logger.getLogger(SoapCall.class.getName());
|
||||
|
||||
protected static final Pattern PROP_PATTERN = Pattern.compile("\\{([^}]+)}");
|
||||
private static final Pattern REGEX_QUANTIFIER = Pattern.compile("\\d+(,\\d*)?");
|
||||
|
||||
protected String name;
|
||||
protected Path parentStepPath;
|
||||
protected Path testCasePath;
|
||||
protected Path projectPath;
|
||||
protected boolean active;
|
||||
|
||||
protected Map<String, String> extractions;
|
||||
protected List<Assertion> assertions;
|
||||
protected Map<String, String> properties;
|
||||
|
||||
private final String endpointTemplate;
|
||||
private final String payloadTemplate;
|
||||
private final Map<String, String> headerTemplates;
|
||||
private final List<Assertion> assertionTemplates;
|
||||
|
||||
public SoapCall(
|
||||
Path stepPath
|
||||
) throws
|
||||
RepositoryException,
|
||||
CallInitializationException
|
||||
{
|
||||
log.info("Preparing call for step: %s".formatted(stepPath));
|
||||
|
||||
var step = StepRepository.get(stepPath);
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
testCasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
var testcase = TestCaseRepository.get(testCasePath);
|
||||
var project = ProjectRepository.get(projectPath);
|
||||
|
||||
name = step.getName();
|
||||
parentStepPath = stepPath;
|
||||
active = step.isActive() && testcase.isActive();
|
||||
|
||||
payload = step.getPayload();
|
||||
extractions = step.getExtractions();
|
||||
|
||||
if (! testcase.getEndpoint().isBlank())
|
||||
endpoint = testcase.getEndpoint();
|
||||
if (! step.getEndpoint().isBlank())
|
||||
endpoint = step.getEndpoint();
|
||||
if (endpoint.isBlank())
|
||||
throw new CallInitializationException("No endpoint set.", Endpoint);
|
||||
version = project.versionOf(endpoint);
|
||||
|
||||
if (! testcase.getAction().isBlank())
|
||||
action = testcase.getAction();
|
||||
if (! step.getAction().isBlank())
|
||||
action = step.getAction();
|
||||
|
||||
if (action.isBlank() && endpoint.isBlank())
|
||||
throw new CallInitializationException("No action set and empty body.", ActionAndBody);
|
||||
|
||||
headers = new HashMap<>();
|
||||
headers.putAll(project.getHeaders());
|
||||
headers.putAll(testcase.getHeaders());
|
||||
headers.putAll(step.getHeaders());
|
||||
|
||||
endpointTemplate = endpoint;
|
||||
payloadTemplate = payload;
|
||||
headerTemplates = new HashMap<>(headers);
|
||||
assertionTemplates = new ArrayList<>(step.getAssertions());
|
||||
assertions = assertionTemplates;
|
||||
}
|
||||
|
||||
public void applyProperties() throws RepositoryException, PropertyMissingException, MalformedEndpointException {
|
||||
var testcase = TestCaseRepository.get(testCasePath);
|
||||
var project = ProjectRepository.get(projectPath);
|
||||
properties = new HashMap<>();
|
||||
properties.putAll(project.getProperties());
|
||||
properties.putAll(testcase.getProperties());
|
||||
|
||||
endpoint = applyProperties(endpointTemplate);
|
||||
payload = applyProperties(payloadTemplate);
|
||||
var resolvedHeaders = new HashMap<String, String>();
|
||||
for (var header : headerTemplates.entrySet())
|
||||
resolvedHeaders.put(header.getKey(), applyProperties(header.getValue()));
|
||||
headers = resolvedHeaders;
|
||||
assertions = applyPropertiesToAssertions(assertionTemplates);
|
||||
validateEndpoint(endpoint);
|
||||
}
|
||||
|
||||
public static void validateEndpoint(String endpoint) throws MalformedEndpointException {
|
||||
URI uri;
|
||||
try {
|
||||
uri = new URI(endpoint.strip());
|
||||
} catch (URISyntaxException invalid) {
|
||||
throw new MalformedEndpointException(invalid.getMessage(), endpoint);
|
||||
}
|
||||
var scheme = uri.getScheme();
|
||||
if (scheme == null || !(scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")))
|
||||
throw new MalformedEndpointException("El esquema debe ser http o https.", endpoint);
|
||||
if (uri.getHost() == null || uri.getHost().isBlank())
|
||||
throw new MalformedEndpointException("No se ha indicado el servidor.", endpoint);
|
||||
}
|
||||
|
||||
private List<Assertion> applyPropertiesToAssertions(List<Assertion> stepAssertions) throws PropertyMissingException {
|
||||
var resolved = new ArrayList<Assertion>(stepAssertions.size());
|
||||
for (var assertion : stepAssertions) {
|
||||
var isRegex = assertion.getType() == Assertion.Type.regex;
|
||||
resolved.add(new Assertion(
|
||||
assertion.getType(),
|
||||
applyProperties(assertion.getValue()),
|
||||
applyProperties(assertion.getExpression(), isRegex)
|
||||
));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private String applyProperties(String input) throws PropertyMissingException {
|
||||
return applyProperties(input, false);
|
||||
}
|
||||
|
||||
private String applyProperties(String input, boolean keepQuantifiers) throws PropertyMissingException {
|
||||
return applyProperties(input, properties, keepQuantifiers);
|
||||
}
|
||||
|
||||
/** Replaces each {@code {key}} in {@code input} by its property. */
|
||||
public static String applyProperties(String input, Map<String, String> properties) throws PropertyMissingException {
|
||||
return applyProperties(input, properties, false);
|
||||
}
|
||||
|
||||
private static String applyProperties(
|
||||
String input, Map<String, String> properties, boolean keepQuantifiers
|
||||
) throws PropertyMissingException {
|
||||
var matcher = PROP_PATTERN.matcher(input);
|
||||
var str = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
var key = matcher.group(1);
|
||||
if (keepQuantifiers && REGEX_QUANTIFIER.matcher(key).matches()) {
|
||||
matcher.appendReplacement(str, Matcher.quoteReplacement(matcher.group()));
|
||||
continue;
|
||||
}
|
||||
var value = properties.get(key);
|
||||
if (value == null)
|
||||
throw new PropertyMissingException("Property not set.", key);
|
||||
var replacement = Matcher.quoteReplacement(value);
|
||||
matcher.appendReplacement(str, replacement);
|
||||
}
|
||||
matcher.appendTail(str);
|
||||
return str.toString();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Path getPath() {
|
||||
return parentStepPath;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public Path getTestCasePath() {
|
||||
return testCasePath;
|
||||
}
|
||||
|
||||
public Path getProjectPath() {
|
||||
return projectPath;
|
||||
}
|
||||
|
||||
/** The endpoint as written, before properties: WSDLs are kept by it. */
|
||||
public String getEndpointTemplate() {
|
||||
return endpointTemplate;
|
||||
}
|
||||
|
||||
public Map<String, String> getExtractions() {
|
||||
return extractions;
|
||||
}
|
||||
|
||||
public List<Assertion> getAssertions() {
|
||||
return assertions;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.Assertion;
|
||||
import com.molnarandrei.sopa.data.yaml.CallLog;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.SoapCallEvent;
|
||||
import com.molnarandrei.sopa.events.SoapJobEvent;
|
||||
import com.molnarandrei.sopa.calllog.CallLogService;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlValidations;
|
||||
|
||||
import javafx.scene.control.Alert;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.namespace.NamespaceContext;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import javax.xml.xpath.XPathConstants;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class SoapJob extends LinkedList<SoapCall> implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(SoapJob.class.getName());
|
||||
private static final String REMAINING_SKIPPED = "Los pasos siguientes de la ejecución no se lanzarán.";
|
||||
|
||||
private volatile Thread thread;
|
||||
|
||||
public void start(Runnable doWhenDone) {
|
||||
thread = Thread.ofVirtual().unstarted(() -> {
|
||||
try {
|
||||
run();
|
||||
} finally {
|
||||
doWhenDone.run();
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public void interrupt() {
|
||||
var current = thread;
|
||||
if (current != null) current.interrupt();
|
||||
}
|
||||
|
||||
public boolean isInterruptedOrDone() {
|
||||
var current = thread;
|
||||
return current != null && (current.isInterrupted() || !current.isAlive());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
var id = Thread.currentThread().threadId();
|
||||
var stepPaths = stream().map(SoapCall::getPath).toList();
|
||||
log.info("[%d] Starting queue of %d calls".formatted(id, size()));
|
||||
Events.emit(new SoapJobEvent(SoapJobEvent.STARTED, stepPaths));
|
||||
try {
|
||||
for (var call : this) {
|
||||
if (Thread.currentThread().isInterrupted())
|
||||
break;
|
||||
log.info("[%d] Starting call for step %s".formatted(id, call.getPath()));
|
||||
var success = request(call);
|
||||
if (!success) break;
|
||||
log.info("[%d] Call performed successfully %s".formatted(id, call.getPath()));
|
||||
}
|
||||
} finally {
|
||||
log.info("[%d] Finished all calls".formatted(id));
|
||||
Events.emit(new SoapJobEvent(SoapJobEvent.FINISHED, stepPaths));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean request(SoapCall call) {
|
||||
var stepPath = call.getPath();
|
||||
if (!applyProperties(call)) return false;
|
||||
var endpoint = call.getEndpoint();
|
||||
try {
|
||||
Events.emit(new SoapCallEvent(
|
||||
SoapCallEvent.STARTED,
|
||||
new SoapCallEvent.StepAndEndpoint(stepPath, endpoint)
|
||||
));
|
||||
|
||||
var httpResponse = call.request();
|
||||
var result = CallLog.Result.success;
|
||||
if (!checkAssertions(call, httpResponse))
|
||||
result = CallLog.Result.assertionsFailed;
|
||||
else if (!applyExtractions(call, httpResponse))
|
||||
result = CallLog.Result.extractionsFailed;
|
||||
|
||||
CallLogService.save(stepPath, new CallLog(
|
||||
stepPath,
|
||||
prettyXml(httpResponse.body()),
|
||||
httpResponse.statusCode(),
|
||||
result
|
||||
));
|
||||
return result == CallLog.Result.success;
|
||||
} catch (IOException fail) {
|
||||
log.log(Level.WARNING, "Call to %s failed, stopping job".formatted(endpoint), fail);
|
||||
var errorResponse = new CallLog(
|
||||
stepPath,
|
||||
"%s\n%s".formatted(fail.getClass().getName(), fail.getMessage()),
|
||||
0,
|
||||
CallLog.Result.exception
|
||||
);
|
||||
CallLogService.save(stepPath, errorResponse);
|
||||
Utils.alert(
|
||||
"Fallo de conexión",
|
||||
"No se ha podido completar la llamada a:\n%s".formatted(endpoint),
|
||||
"%s: %s\n\nComprueba que el servidor esté disponible y que el endpoint sea correcto. %s"
|
||||
.formatted(fail.getClass().getSimpleName(), fail.getMessage(), REMAINING_SKIPPED)
|
||||
);
|
||||
return false;
|
||||
|
||||
} catch (InterruptedException interrupted) {
|
||||
log.warning("Interrupted ongoing call to %s".formatted(endpoint));
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
Events.emit(new SoapCallEvent(
|
||||
SoapCallEvent.FINISHED,
|
||||
new SoapCallEvent.StepAndEndpoint(stepPath, endpoint)
|
||||
));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean checkAssertions(SoapCall call, HttpResponse<String> httpResponse) {
|
||||
for (var assertion : call.getAssertions()) {
|
||||
var holds = checkAssertion(call, assertion, httpResponse);
|
||||
log.info("Assertion %s result: %s".formatted(assertion, holds));
|
||||
var couldNotBeEvaluated = holds == null;
|
||||
if (couldNotBeEvaluated) return false;
|
||||
if (!holds) {
|
||||
Utils.alert(
|
||||
Alert.AlertType.WARNING,
|
||||
"Aserción no cumplida",
|
||||
"La respuesta del paso no cumple la aserción %s:\n%s"
|
||||
.formatted(assertion.getType(), call.getPath()),
|
||||
"%s\n\nLa respuesta se ha guardado en el historial del paso para revisarla. %s"
|
||||
.formatted(unmetDetail(call, assertion, httpResponse), REMAINING_SKIPPED)
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean applyProperties(SoapCall call) {
|
||||
try {
|
||||
call.applyProperties();
|
||||
return true;
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
log.log(Level.WARNING, "Cannot read properties for step %s".formatted(call.getPath()), readOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se han podido leer las propiedades del paso:\n%s"
|
||||
.formatted(readOrParseErr.getPath()),
|
||||
readOrParseErr.getMessage()
|
||||
);
|
||||
} catch (PropertyMissingException prop) {
|
||||
log.warning("Property %s missing for step %s".formatted(prop.getMissingKey(), call.getPath()));
|
||||
Utils.alert(
|
||||
Alert.AlertType.WARNING,
|
||||
"Llamada incompleta",
|
||||
"No podemos realizar la llamada SOAP:\n%s".formatted(call.getPath()),
|
||||
"Falta la propiedad: %s".formatted(prop.getMissingKey())
|
||||
);
|
||||
} catch (MalformedEndpointException malformed) {
|
||||
log.warning("Malformed endpoint %s for step %s".formatted(malformed.getEndpoint(), call.getPath()));
|
||||
Utils.alert(
|
||||
Alert.AlertType.WARNING,
|
||||
"Llamada incompleta",
|
||||
"El endpoint no es válido:\n%s"
|
||||
.formatted(malformed.getEndpoint()),
|
||||
malformed.getMessage()
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean applyExtractions(SoapCall call, HttpResponse<String> httpResponse) {
|
||||
var extractions = call.getExtractions();
|
||||
if (extractions.isEmpty()) return true;
|
||||
|
||||
var extracted = new HashMap<String, String>();
|
||||
try {
|
||||
var document = parseXml(httpResponse.body());
|
||||
for (var extraction : extractions.entrySet()) {
|
||||
var value = evaluateXPath(document, extraction.getValue());
|
||||
if (value.isEmpty()) {
|
||||
log.warning("Extraction %s found nothing for step %s".formatted(extraction.getKey(), call.getPath()));
|
||||
Utils.alert(
|
||||
"Fallo de extracción",
|
||||
"La extracción de %s no ha encontrado nada en la respuesta de:\n%s"
|
||||
.formatted(extraction.getKey(), call.getPath()),
|
||||
extraction.getValue()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
extracted.put(extraction.getKey(), value);
|
||||
}
|
||||
} catch (Exception cannotExtract) {
|
||||
log.log(Level.WARNING, "Extraction failed for step %s".formatted(call.getPath()), cannotExtract);
|
||||
Utils.alert(
|
||||
"Fallo de extracción",
|
||||
"No se han podido evaluar las extracciones de:\n%s"
|
||||
.formatted(call.getPath()),
|
||||
String.valueOf(cannotExtract.getMessage())
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info("Extraction result: %s".formatted(extracted));
|
||||
var testCase = TestCaseService.read(call.getTestCasePath());
|
||||
var project = ProjectService.read(call.getProjectPath());
|
||||
if (testCase == null || project == null) return false;
|
||||
|
||||
var testCaseProperties = new HashMap<>(testCase.getProperties());
|
||||
var projectProperties = new HashMap<>(project.getProperties());
|
||||
var testCaseUpdated = false;
|
||||
var projectUpdated = false;
|
||||
for (var entry : extracted.entrySet()) {
|
||||
var key = entry.getKey();
|
||||
if (testCaseProperties.containsKey(key)) {
|
||||
testCaseProperties.put(key, entry.getValue());
|
||||
testCaseUpdated = true;
|
||||
} else if (projectProperties.containsKey(key)) {
|
||||
projectProperties.put(key, entry.getValue());
|
||||
projectUpdated = true;
|
||||
} else {
|
||||
testCaseProperties.put(key, entry.getValue());
|
||||
testCaseUpdated = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (testCaseUpdated) {
|
||||
testCase.setProperties(testCaseProperties);
|
||||
TestCaseService.write(call.getTestCasePath(), testCase);
|
||||
}
|
||||
if (projectUpdated) {
|
||||
project.setProperties(projectProperties);
|
||||
ProjectService.write(call.getProjectPath(), project);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static Boolean checkAssertion(SoapCall call, Assertion assertion, HttpResponse<String> response) {
|
||||
var body = response.body() == null ? "" : response.body();
|
||||
try {
|
||||
return switch (assertion.getType()) {
|
||||
case httpStatus -> response.statusCode() == Integer.parseInt(assertion.getValue().strip());
|
||||
case contains -> body.contains(assertion.getValue());
|
||||
case xPath -> evaluateXPath(parseXml(body), assertion.getExpression())
|
||||
.equals(assertion.getValue());
|
||||
case regex -> Pattern.compile(assertion.getExpression()).matcher(body).find();
|
||||
case validPerWsdl -> wsdlErrors(call, body).isEmpty();
|
||||
case notSoapFault -> faultOf(parseXml(body)) == null;
|
||||
case soapFault -> {
|
||||
var fault = faultOf(parseXml(body));
|
||||
yield fault != null && faultCode(fault).contains(assertion.getValue().strip());
|
||||
}
|
||||
};
|
||||
} catch (Exception invalidAssertionOrBody) {
|
||||
log.log(Level.WARNING, "Assertion %s could not be evaluated".formatted(assertion.getType()), invalidAssertionOrBody);
|
||||
Utils.alert(
|
||||
"Fallo de aserción",
|
||||
"No se ha podido evaluar la aserción %s:\n%s"
|
||||
.formatted(assertion.getType(), assertionDetail(assertion)),
|
||||
String.valueOf(invalidAssertionOrBody.getMessage())
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String unmetDetail(SoapCall call, Assertion assertion, HttpResponse<String> response) {
|
||||
var body = response.body() == null ? "" : response.body();
|
||||
return switch (assertion.getType()) {
|
||||
case httpStatus -> "Se esperaba el estado HTTP %s y se ha recibido %d."
|
||||
.formatted(assertion.getValue().strip(), response.statusCode());
|
||||
case contains -> "La respuesta no contiene el texto:\n%s".formatted(assertion.getValue());
|
||||
case xPath -> {
|
||||
String found;
|
||||
try {
|
||||
found = evaluateXPath(parseXml(body), assertion.getExpression());
|
||||
} catch (Exception alreadyEvaluated) {
|
||||
found = "?";
|
||||
}
|
||||
yield "La expresión %s debía valer \"%s\" pero vale \"%s\"."
|
||||
.formatted(assertion.getExpression(), assertion.getValue(), found);
|
||||
}
|
||||
case regex -> "La expresión regular no encuentra coincidencias:\n%s"
|
||||
.formatted(assertion.getExpression());
|
||||
case validPerWsdl -> {
|
||||
try {
|
||||
yield "La respuesta no es válida según el WSDL:\n%s"
|
||||
.formatted(String.join("\n", wsdlErrors(call, body)));
|
||||
} catch (Exception alreadyEvaluated) {
|
||||
yield "La respuesta no es válida según el WSDL.";
|
||||
}
|
||||
}
|
||||
case notSoapFault, soapFault -> {
|
||||
Element fault;
|
||||
try {
|
||||
fault = faultOf(parseXml(body));
|
||||
} catch (Exception alreadyEvaluated) {
|
||||
fault = null;
|
||||
}
|
||||
if (fault == null) yield "La respuesta no es un SOAP fault.";
|
||||
yield assertion.getType() == Assertion.Type.notSoapFault
|
||||
? "La respuesta es un SOAP fault con código \"%s\".".formatted(faultCode(fault))
|
||||
: "El código del SOAP fault debía contener \"%s\" pero es \"%s\"."
|
||||
.formatted(assertion.getValue().strip(), faultCode(fault));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static String assertionDetail(Assertion assertion) {
|
||||
return switch (assertion.getType()) {
|
||||
case httpStatus, contains, soapFault -> assertion.getValue();
|
||||
case xPath, regex -> assertion.getExpression();
|
||||
case validPerWsdl, notSoapFault -> "";
|
||||
};
|
||||
}
|
||||
|
||||
private static List<String> wsdlErrors(SoapCall call, String body) throws Exception {
|
||||
return WsdlValidations.responseErrors(call.getProjectPath(), call.getEndpointTemplate(), call.version, call.payload, body);
|
||||
}
|
||||
|
||||
public static List<Element> bodyElements(Document document) {
|
||||
var root = document.getDocumentElement();
|
||||
if (! "Envelope".equals(root.getLocalName())) return null;
|
||||
for (var body : childElements(root))
|
||||
if ("Body".equals(body.getLocalName()))
|
||||
return childElements(body);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<Element> childElements(Element parent) {
|
||||
var elements = new ArrayList<Element>();
|
||||
var children = parent.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++)
|
||||
if (children.item(i) instanceof Element child)
|
||||
elements.add(child);
|
||||
return elements;
|
||||
}
|
||||
|
||||
private static Element faultOf(Document document) {
|
||||
var contents = bodyElements(document);
|
||||
if (contents == null) return null;
|
||||
for (var content : contents) {
|
||||
var namespace = content.getNamespaceURI();
|
||||
if ("Fault".equals(content.getLocalName())
|
||||
&& (WsdlValidations.SOAP_11_NS.equals(namespace) || WsdlValidations.SOAP_12_NS.equals(namespace)))
|
||||
return content;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String faultCode(Element fault) {
|
||||
var soap11Code = fault.getElementsByTagNameNS("*", "faultcode");
|
||||
var code = soap11Code.getLength() > 0 ? soap11Code : fault.getElementsByTagNameNS("*", "Value");
|
||||
return code.getLength() == 0 ? "" : code.item(0).getTextContent().strip();
|
||||
}
|
||||
|
||||
public static Document parseXml(String body) throws Exception {
|
||||
var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
var builder = factory.newDocumentBuilder();
|
||||
builder.setErrorHandler(null);
|
||||
return builder.parse(new InputSource(new StringReader(body)));
|
||||
}
|
||||
|
||||
private static String evaluateXPath(Document document, String expression) throws Exception {
|
||||
var namespaces = new HashMap<String, String>();
|
||||
collectNamespaces(document.getDocumentElement(), namespaces);
|
||||
var xpath = XPathFactory.newInstance().newXPath();
|
||||
xpath.setNamespaceContext(new NamespaceContext() {
|
||||
@Override
|
||||
public String getNamespaceURI(String prefix) {
|
||||
return namespaces.getOrDefault(prefix, XMLConstants.NULL_NS_URI);
|
||||
}
|
||||
@Override
|
||||
public String getPrefix(String uri) {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Iterator<String> getPrefixes(String uri) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
return (String) xpath.evaluate(expression, document, XPathConstants.STRING);
|
||||
}
|
||||
|
||||
private static void collectNamespaces(Element element, Map<String, String> namespaces) {
|
||||
var attributes = element.getAttributes();
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
var attribute = attributes.item(i);
|
||||
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI())
|
||||
&& attribute.getPrefix() != null)
|
||||
namespaces.putIfAbsent(attribute.getLocalName(), attribute.getNodeValue());
|
||||
}
|
||||
var children = element.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++)
|
||||
if (children.item(i) instanceof Element child)
|
||||
collectNamespaces(child, namespaces);
|
||||
}
|
||||
|
||||
static String prettyXml(String body) {
|
||||
try {
|
||||
var document = parseXml(body);
|
||||
removeWhitespaceBetweenTags(document);
|
||||
|
||||
var transformerFactory = TransformerFactory.newInstance();
|
||||
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
|
||||
var transformer = transformerFactory.newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
|
||||
|
||||
var out = new StringWriter();
|
||||
transformer.transform(new DOMSource(document), new StreamResult(out));
|
||||
return out.toString().strip();
|
||||
} catch (Exception notXml) {
|
||||
log.fine("Response body is not XML, keeping it as is: %s".formatted(notXml.getMessage()));
|
||||
return body;
|
||||
}
|
||||
}
|
||||
|
||||
private static void removeWhitespaceBetweenTags(Document document) throws XPathExpressionException {
|
||||
var blanks = (NodeList) XPathFactory.newInstance().newXPath()
|
||||
.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET);
|
||||
for (int i = 0; i < blanks.getLength(); i++) {
|
||||
Node blank = blanks.item(i);
|
||||
blank.getParentNode().removeChild(blank);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import javafx.scene.control.Alert;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SoapService {
|
||||
private static final Logger log = Logger.getLogger(SoapService.class.getName());
|
||||
private static final Map<Path, SoapJob> currentlyRunningJobsByPath = new ConcurrentHashMap<>();
|
||||
|
||||
public static void createAndStartStepCalls(Iterable<Path> stepPaths) {
|
||||
var calls = new SoapJob();
|
||||
for (Path stepPath : stepPaths) {
|
||||
try {
|
||||
if (! StepRepository.get(stepPath).isActive()) continue;
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
alert(readOrParseErr);
|
||||
return;
|
||||
}
|
||||
var step = createCall(stepPath);
|
||||
if (step == null) return;
|
||||
if (! step.isActive()) continue;
|
||||
calls.add(step);
|
||||
}
|
||||
if (calls.isEmpty()) return;
|
||||
stopJobsOverlapping(calls);
|
||||
register(calls);
|
||||
calls.start(() -> unregister(calls));
|
||||
}
|
||||
|
||||
public static void createAndStartCallForStep(Path stepPath) {
|
||||
createAndStartStepCalls(List.of(stepPath));
|
||||
}
|
||||
|
||||
public static void createAndStartCallsForTestCaseUntilStep(Path testCasePath, Path stepPath) {
|
||||
try {
|
||||
var allSteps = TestCaseRepository.getPathsOfContainedSteps(testCasePath);
|
||||
var index = allSteps.indexOf(stepPath) + 1;
|
||||
var slice = allSteps.subList(0, index);
|
||||
createAndStartStepCalls(slice);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
alert(readOrParseErr);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createAndStartCallsForTestCaseStartingFromStep(Path testCasePath, Path stepPath) {
|
||||
try {
|
||||
var allSteps = TestCaseRepository.getPathsOfContainedSteps(testCasePath);
|
||||
var index = allSteps.indexOf(stepPath);
|
||||
var slice = allSteps.subList(index, allSteps.size());
|
||||
createAndStartStepCalls(slice);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
alert(readOrParseErr);
|
||||
}
|
||||
}
|
||||
|
||||
public static void createAndStartCallsForTestCase(Path testCasePath) {
|
||||
try {
|
||||
var allSteps = TestCaseRepository.getPathsOfContainedSteps(testCasePath);
|
||||
createAndStartStepCalls(allSteps);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
alert(readOrParseErr);
|
||||
}
|
||||
}
|
||||
|
||||
private static void stopJobsOverlapping(SoapJob job) {
|
||||
for (var call : job) {
|
||||
var running = currentlyRunningJobsByPath.get(call.getPath());
|
||||
if (running == null) continue;
|
||||
if (!running.isInterruptedOrDone()) {
|
||||
log.info("Interrupting running job for step %s".formatted(call.getPath()));
|
||||
running.interrupt();
|
||||
}
|
||||
unregister(running);
|
||||
}
|
||||
}
|
||||
|
||||
private static void register(SoapJob job) {
|
||||
for (var call : job)
|
||||
currentlyRunningJobsByPath.put(call.getPath(), job);
|
||||
}
|
||||
|
||||
/** Only removes keys still owned by this job, so a late cleanup never drops a newer job's entries. */
|
||||
private static void unregister(SoapJob job) {
|
||||
for (var call : job)
|
||||
currentlyRunningJobsByPath.remove(call.getPath(), job);
|
||||
}
|
||||
|
||||
public static SoapCall createCall(Path stepPath) {
|
||||
try {
|
||||
return new SoapCall(stepPath);
|
||||
} catch (RepositoryException readOrParseErr) {
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido abrir alguno de los fciheros del paso:\n%s"
|
||||
.formatted(readOrParseErr.getPath()),
|
||||
readOrParseErr.getMessage()
|
||||
);
|
||||
} catch (CallInitializationException init) {
|
||||
Utils.alert(
|
||||
Alert.AlertType.WARNING,
|
||||
"Llamada incompleta",
|
||||
"No podemos realizar la llamada SOAP",
|
||||
"Falta el campo:%s".formatted(
|
||||
init.getMissingField().getTitle()
|
||||
)
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void alert(RepositoryException err) {
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido abrir alguno de los ficheros:\n%s"
|
||||
.formatted(err.getPath()),
|
||||
err.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
/** Written in YAML by its title: 1.1 or 1.2. */
|
||||
public enum SoapVersion {
|
||||
ONE_ONE("1.1"),
|
||||
ONE_TWO("1.2");
|
||||
|
||||
private final String title;
|
||||
SoapVersion(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static SoapVersion ofTitle(String title) {
|
||||
for (var version : values())
|
||||
if (version.title.equals(title == null ? null : title.strip())) return version;
|
||||
throw new IllegalArgumentException("SOAP version must be 1.1 or 1.2, not %s.".formatted(title));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package com.molnarandrei.sopa.step;
|
||||
|
||||
import com.molnarandrei.sopa.data.Trash;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import com.molnarandrei.sopa.data.DoesNotExistException;
|
||||
import com.molnarandrei.sopa.data.EmptyException;
|
||||
import com.molnarandrei.sopa.data.FileNames;
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.data.yaml.Yaml;
|
||||
import tools.jackson.core.JacksonException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.molnarandrei.sopa.Utils.baseNameOf;
|
||||
import static com.molnarandrei.sopa.Utils.extractNumber;
|
||||
import static com.molnarandrei.sopa.Utils.highestIndexOf;
|
||||
import static com.molnarandrei.sopa.Utils.renameIndexed;
|
||||
|
||||
public class StepRepository {
|
||||
private static final Logger log = Logger.getLogger(StepRepository.class.getName());
|
||||
/** Far above any real index: a free slot to park a step folder on while the others move. */
|
||||
private static final int PARKED_OFFSET = 1_000_000;
|
||||
|
||||
public static Step get(Path stepPath) throws RepositoryException {
|
||||
if (! Files.isReadable(stepPath)) throw new DoesNotExistException(stepPath, "Unreadable");
|
||||
try {
|
||||
var step = Files.readString(stepPath);
|
||||
if (step.isBlank())
|
||||
throw new EmptyException(stepPath, "Step file is empty");
|
||||
var obj = Yaml.toStep(step);
|
||||
if (obj == null)
|
||||
throw new RepositoryException(stepPath, "Not a step");
|
||||
return obj;
|
||||
} catch (RepositoryException repo) {
|
||||
throw repo;
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(stepPath, "Could not read file", io);
|
||||
} catch (JacksonException mapping) {
|
||||
throw new RepositoryException(stepPath, "Bad format", mapping);
|
||||
}
|
||||
}
|
||||
|
||||
public static void update(Path stepPath, Step step) throws RepositoryException{
|
||||
try {
|
||||
var yaml = Yaml.toYaml(step);
|
||||
Files.writeString(stepPath, yaml);
|
||||
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(stepPath, "Cannot write step", io);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the folder of {@code fromStepPath} (its step.yml) into {@code toTestCasePath}
|
||||
* (the target testcase.yml), appended after the last step already there. Dropping a step
|
||||
* on its own testcase moves it to the end of that same testcase.
|
||||
*/
|
||||
public static void move(Path fromStepPath, Path toTestCasePath) throws RepositoryException {
|
||||
if (! FileNames.isStepFile(fromStepPath))
|
||||
throw new RepositoryException(fromStepPath, "Not a step file to move");
|
||||
if (! Files.isDirectory(fromStepPath.getParent()))
|
||||
throw new DoesNotExistException(fromStepPath, "Step folder is missing");
|
||||
|
||||
var fromStepFolderPath = fromStepPath.getParent();
|
||||
var fromTestCaseFolderPath = fromStepFolderPath.getParent();
|
||||
var fromProjectDirectory = fromTestCaseFolderPath.getParent();
|
||||
|
||||
var toTestCaseFolderPath = toTestCasePath.getParent();
|
||||
if (! Files.isDirectory(toTestCaseFolderPath))
|
||||
throw new DoesNotExistException(toTestCasePath, "Target testcase is missing");
|
||||
var toProjectDirectory = toTestCaseFolderPath.getParent();
|
||||
|
||||
var baseName = baseNameOf(fromStepFolderPath);
|
||||
int highestIndex;
|
||||
try {
|
||||
highestIndex = highestIndexOf(toTestCaseFolderPath, baseName);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(toTestCasePath, "Cannot index step into '%s'".formatted(toTestCaseFolderPath), io);
|
||||
}
|
||||
|
||||
if (fromTestCaseFolderPath.equals(toTestCaseFolderPath)) {
|
||||
if (extractNumber(fromStepFolderPath) == highestIndex) {
|
||||
log.info("Step '%s' already is the last one, not moving.".formatted(fromStepPath));
|
||||
return;
|
||||
}
|
||||
log.info("Moving step '%s' to the end of its own testcase.".formatted(fromStepPath));
|
||||
}
|
||||
|
||||
var destination = renameIndexed(toTestCaseFolderPath.resolve(baseName + "-" + (highestIndex + 1)));
|
||||
try {
|
||||
Files.move(fromStepFolderPath, destination);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(fromStepPath, "Cannot move step to '%s'".formatted(destination), io);
|
||||
}
|
||||
|
||||
ProjectMonitors.trigger(toProjectDirectory);
|
||||
if (! fromProjectDirectory.equals(toProjectDirectory))
|
||||
ProjectMonitors.trigger(fromProjectDirectory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the step folder of {@code fromStepPath} at the place of the one of {@code toStepPath}:
|
||||
* in front of it when {@code putBefore}, right behind it otherwise. Every folder taking part
|
||||
* gets the index of its new position, so the numbers in the names keep matching the order of
|
||||
* the steps. A step dropped on a step of another testcase brings its own folder along.
|
||||
*/
|
||||
public static void moveReordering(Path fromStepPath, Path toStepPath, boolean putBefore) throws RepositoryException {
|
||||
if (! FileNames.isStepFile(fromStepPath) || ! FileNames.isStepFile(toStepPath))
|
||||
throw new RepositoryException(fromStepPath, "Reordering takes step files");
|
||||
if (fromStepPath.equals(toStepPath)) {
|
||||
log.info("Step '%s' dropped on itself, not reordering.".formatted(fromStepPath));
|
||||
return;
|
||||
}
|
||||
if (! Files.isDirectory(fromStepPath.getParent()))
|
||||
throw new DoesNotExistException(fromStepPath, "Step folder is missing");
|
||||
|
||||
var fromStepFolderPath = fromStepPath.getParent();
|
||||
var fromTestCaseFolderPath = fromStepFolderPath.getParent();
|
||||
var toStepFolderPath = toStepPath.getParent();
|
||||
var toTestCaseFolderPath = toStepFolderPath.getParent();
|
||||
|
||||
var allSteps = TestCaseRepository.getPathsOfContainedSteps(toTestCaseFolderPath.resolve("testcase.yml"));
|
||||
allSteps.remove(fromStepPath);
|
||||
|
||||
var targetIndex = allSteps.indexOf(toStepPath);
|
||||
if (targetIndex < 0)
|
||||
throw new RepositoryException(toStepPath, "Step is not part of '%s'".formatted(toTestCaseFolderPath));
|
||||
var shiftIndex = targetIndex + (putBefore? 0: 1);
|
||||
|
||||
var orderedSteps = new ArrayList<Path>(allSteps);
|
||||
orderedSteps.add(shiftIndex, fromStepPath);
|
||||
|
||||
var shifting = new LinkedHashMap<Path, Path>();
|
||||
for (int position = 0; position < orderedSteps.size(); position++) {
|
||||
var folder = orderedSteps.get(position).getParent();
|
||||
if (! toTestCaseFolderPath.equals(folder.getParent())) continue;
|
||||
var index = position + 1;
|
||||
if (extractNumber(folder) == index) continue;
|
||||
shifting.put(folder, renameIndexed(folder, index));
|
||||
}
|
||||
|
||||
// Two passes: park on a free index first, take the real one afterwards. In a single pass
|
||||
// the moved step could ask for a slot a folder that has not left it yet still holds,
|
||||
// step-2 sitting on the slot step-1 has to vacate for it.
|
||||
var parked = new LinkedHashMap<Path, Path>();
|
||||
for (var shift : shifting.entrySet()) {
|
||||
var slot = renameIndexed(shift.getKey(), PARKED_OFFSET + extractNumber(shift.getValue()));
|
||||
moveFolder(shift.getKey(), slot, fromStepPath);
|
||||
parked.put(slot, shift.getValue());
|
||||
}
|
||||
for (var park : parked.entrySet())
|
||||
moveFolder(park.getKey(), park.getValue(), fromStepPath);
|
||||
|
||||
if (! toTestCaseFolderPath.equals(fromTestCaseFolderPath)) {
|
||||
var destination = renameIndexed(
|
||||
toTestCaseFolderPath.resolve(baseNameOf(fromStepFolderPath)), shiftIndex + 1
|
||||
);
|
||||
moveFolder(fromStepFolderPath, destination, fromStepPath);
|
||||
}
|
||||
|
||||
var toProjectDirectory = toTestCaseFolderPath.getParent();
|
||||
ProjectMonitors.trigger(toProjectDirectory);
|
||||
if (! toProjectDirectory.equals(fromTestCaseFolderPath.getParent()))
|
||||
ProjectMonitors.trigger(fromTestCaseFolderPath.getParent());
|
||||
}
|
||||
|
||||
private static void moveFolder(Path source, Path destination, Path reportedPath) throws RepositoryException {
|
||||
if (source.equals(destination)) return;
|
||||
try {
|
||||
Files.move(source, destination);
|
||||
} catch (IOException io) {
|
||||
log.log(Level.SEVERE, "While reordering, cannot shift step '%s' to '%s'".formatted(source, destination), io);
|
||||
throw new RepositoryException(reportedPath, "Cannot shift step to '%s'".formatted(destination), io);
|
||||
}
|
||||
}
|
||||
|
||||
public static void delete(Path stepPath) throws RepositoryException{
|
||||
var stepFolderPath = stepPath.getParent();
|
||||
try {
|
||||
if (! Files.isDirectory(stepFolderPath))
|
||||
return;
|
||||
|
||||
try (var walk = Files.walk(stepFolderPath)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> {
|
||||
try {
|
||||
Files.delete(p);
|
||||
} catch (IOException ignore) {}
|
||||
});
|
||||
}
|
||||
|
||||
if (Files.exists(stepFolderPath))
|
||||
throw new IOException("Not deleted.");
|
||||
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(stepPath, "Cannot delete step '%s'".formatted(stepFolderPath), io);
|
||||
} finally {
|
||||
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the folder of the step to the {@link Trash}. @return where it is kept. */
|
||||
public static Path trash(Path stepPath) throws RepositoryException {
|
||||
try {
|
||||
return Trash.keep(stepPath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(stepPath, "Cannot delete step '%s'".formatted(stepPath.getParent()), io);
|
||||
} finally {
|
||||
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the folder of a step back from the {@link Trash}. */
|
||||
public static void restore(Path stepPath, Path kept) throws RepositoryException {
|
||||
try {
|
||||
Trash.restore(kept, stepPath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(stepPath, io.getMessage(), io);
|
||||
} finally {
|
||||
ProjectMonitors.trigger(stepPath.getParent().getParent().getParent());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.molnarandrei.sopa.step;
|
||||
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.trash.TrashService;
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import javafx.scene.control.TextInputDialog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.molnarandrei.sopa.Utils.highestIndexOf;
|
||||
import static com.molnarandrei.sopa.Utils.renameIndexed;
|
||||
|
||||
public class StepService {
|
||||
private static final Logger log = Logger.getLogger(StepService.class.getName());
|
||||
public static final String COPY_SUFFIX = " (copia)";
|
||||
|
||||
public static Step read(Path stepPath) {
|
||||
try {
|
||||
return StepRepository.get(stepPath);
|
||||
} catch (RepositoryException readWriteOrParseErr) {
|
||||
log.log(Level.SEVERE, "Cannot read step %s.".formatted(stepPath), readWriteOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido abrir el paso:\n%s"
|
||||
.formatted(stepPath),
|
||||
readWriteOrParseErr.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void create(Path testCasePath) {
|
||||
var input = new TextInputDialog();
|
||||
input.setTitle("Crear paso en prueba");
|
||||
input.setHeaderText("Nombre del paso");
|
||||
var name = input.showAndWait().orElse("");
|
||||
if (name.isBlank()) return;
|
||||
|
||||
var stepFolderPath = testCasePath.getParent().resolve("step-1");
|
||||
if (Files.exists(stepFolderPath))
|
||||
stepFolderPath = renameIndexed(stepFolderPath);
|
||||
try {
|
||||
Files.createDirectory(stepFolderPath);
|
||||
} catch (IOException cannotCreate) {
|
||||
log.log(Level.SEVERE, "Cannot create step directory %s.".formatted(stepFolderPath), cannotCreate);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido crear el paso:\n%s"
|
||||
.formatted(stepFolderPath),
|
||||
cannotCreate.getMessage()
|
||||
);
|
||||
return;
|
||||
}
|
||||
var step = new Step(name);
|
||||
write(stepFolderPath.resolve("step.yml"), step);
|
||||
}
|
||||
|
||||
/** Writes the step, alerting on failure. Returns whether it was written. */
|
||||
public static boolean write(Path stepPath, Step step) {
|
||||
step.getHeaders().entrySet().removeIf(entry ->
|
||||
entry.getKey() == null || entry.getKey().isBlank() ||
|
||||
entry.getValue() == null || entry.getValue().isBlank()
|
||||
);
|
||||
try {
|
||||
StepRepository.update(stepPath, step);
|
||||
return true;
|
||||
} catch (RepositoryException cannotWrite) {
|
||||
log.log(Level.SEVERE, "Cannot write step %s.".formatted(stepPath), cannotWrite);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido guardar el paso:\n%s"
|
||||
.formatted(stepPath),
|
||||
cannotWrite.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a new step with the contents of {@code stepPath} after the last step of
|
||||
* {@code toTestCasePath}, its name followed by {@code nameSuffix}. Only the step itself is
|
||||
* copied, not its call history: the copy is a different step.
|
||||
* Returns the path of the new step.yml, null when it could not be copied.
|
||||
*/
|
||||
public static Path copyInto(Path stepPath, Path toTestCasePath, String nameSuffix) {
|
||||
log.info("Copying step %s into testcase %s.".formatted(stepPath, toTestCasePath));
|
||||
var step = read(stepPath);
|
||||
if (step == null) return null;
|
||||
|
||||
var toTestCaseFolderPath = toTestCasePath.getParent();
|
||||
Path copiedStepFolderPath = null;
|
||||
try {
|
||||
var highestIndex = highestIndexOf(toTestCaseFolderPath, "step");
|
||||
copiedStepFolderPath = renameIndexed(toTestCaseFolderPath.resolve("step-" + (highestIndex + 1)));
|
||||
Files.createDirectory(copiedStepFolderPath);
|
||||
} catch (IOException cannotCreate) {
|
||||
log.log(Level.SEVERE, "Cannot create step directory in %s.".formatted(toTestCaseFolderPath), cannotCreate);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido crear el paso en:\n%s"
|
||||
.formatted(toTestCaseFolderPath),
|
||||
cannotCreate.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
step.setName(step.getName() + nameSuffix);
|
||||
var copiedStepPath = copiedStepFolderPath.resolve("step.yml");
|
||||
if (write(copiedStepPath, step))
|
||||
return copiedStepPath;
|
||||
|
||||
try {
|
||||
StepRepository.delete(copiedStepPath);
|
||||
} catch (RepositoryException leftover) {
|
||||
log.log(Level.WARNING, "Cannot clean up failed step copy %s.".formatted(copiedStepPath), leftover);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pastes the step at the end of {@code toTestCasePath}. A cut step is erased once its copy
|
||||
* is written, and keeps its name.
|
||||
*/
|
||||
public static void pasteOnTestCase(Path stepPath, Path toTestCasePath, boolean cut) {
|
||||
log.info("Pasting %s step %s onto testcase %s.".formatted(cut? "cut": "copied", stepPath, toTestCasePath));
|
||||
var copiedStepPath = copyInto(stepPath, toTestCasePath, cut? "": COPY_SUFFIX);
|
||||
if (copiedStepPath == null) return;
|
||||
if (cut) erase(stepPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pastes the step right below {@code toStepPath}, in its testcase. A cut step is erased
|
||||
* once its copy is written, and keeps its name. Cutting a step onto itself does nothing.
|
||||
*/
|
||||
public static void pasteBelow(Path stepPath, Path toStepPath, boolean cut) {
|
||||
log.info("Pasting %s step %s below step %s.".formatted(cut? "cut": "copied", stepPath, toStepPath));
|
||||
if (cut && stepPath.equals(toStepPath)) {
|
||||
log.info("Step %s cut onto itself, not pasting.".formatted(stepPath));
|
||||
return;
|
||||
}
|
||||
|
||||
var toTestCasePath = toStepPath.getParent().getParent().resolve("testcase.yml");
|
||||
var copiedStepPath = copyInto(stepPath, toTestCasePath, cut? "": COPY_SUFFIX);
|
||||
if (copiedStepPath == null) return;
|
||||
// Erasing does not rename the other step folders, so toStepPath stays valid; the
|
||||
// reordering below then closes the gap it leaves.
|
||||
if (cut) erase(stepPath);
|
||||
|
||||
try {
|
||||
StepRepository.moveReordering(copiedStepPath, toStepPath, false);
|
||||
} catch (RepositoryException cannotReorder) {
|
||||
log.log(Level.SEVERE, "Cannot place step %s below %s.".formatted(copiedStepPath, toStepPath), cannotReorder);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido colocar el paso pegado tras:\n%s"
|
||||
.formatted(toStepPath),
|
||||
cannotReorder.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void toggleActive(Path stepPath) {
|
||||
log.info("Toggling step %s.".formatted(stepPath));
|
||||
var step = read(stepPath);
|
||||
if (step == null) return;
|
||||
|
||||
step.setActive(! step.isActive());
|
||||
write(stepPath, step);
|
||||
}
|
||||
|
||||
public static void duplicate(Path stepPath) {
|
||||
log.info("Duplicating step %s.".formatted(stepPath));
|
||||
|
||||
var stepFolderPath = stepPath.getParent();
|
||||
var copiedStepFolderPath = Utils.renameIndexed(stepFolderPath);
|
||||
var copiedStepPath = copiedStepFolderPath.resolve("step.yml");
|
||||
try {
|
||||
Utils.copyDirectory(stepFolderPath, copiedStepFolderPath);
|
||||
var step = StepRepository.get(stepPath);
|
||||
step.setName(step.getName() + " (copia)");
|
||||
StepRepository.update(copiedStepPath, step);
|
||||
} catch (IOException readWriteParseError) {
|
||||
log.log(Level.SEVERE, "Cannot copy step %s.".formatted(stepPath), readWriteParseError);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido copiar el paso:\n%s"
|
||||
.formatted(stepPath),
|
||||
readWriteParseError.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the step to the trash: {@link TrashService#undo()} restores it. */
|
||||
public static void delete(Path stepPath) {
|
||||
log.info("Deleting step %s.".formatted(stepPath));
|
||||
try {
|
||||
TrashService.remember(Kind.step, stepPath, StepRepository.trash(stepPath));
|
||||
} catch (RepositoryException readWriteParseError) {
|
||||
log.log(Level.SEVERE, "Cannot delete step %s.".formatted(stepPath), readWriteParseError);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido eliminar el paso:\n%s"
|
||||
.formatted(stepPath),
|
||||
readWriteParseError.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts back a step moved to the trash by {@link #delete(Path)}. */
|
||||
public static boolean restore(Path stepPath, Path kept) {
|
||||
log.info("Restoring step %s.".formatted(stepPath));
|
||||
try {
|
||||
StepRepository.restore(stepPath, kept);
|
||||
return true;
|
||||
} catch (RepositoryException cannotRestore) {
|
||||
log.log(Level.WARNING, "Cannot restore step %s.".formatted(stepPath), cannotRestore);
|
||||
Utils.alert(
|
||||
"No se puede deshacer",
|
||||
"No se ha podido restaurar el paso:\n%s".formatted(stepPath),
|
||||
cannotRestore.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Erases a cut step once pasted: it is not kept in the trash, its copy is where it went. */
|
||||
private static void erase(Path stepPath) {
|
||||
try {
|
||||
StepRepository.delete(stepPath);
|
||||
} catch (RepositoryException readWriteParseError) {
|
||||
log.log(Level.SEVERE, "Cannot erase cut step %s.".formatted(stepPath), readWriteParseError);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido eliminar el paso cortado:\n%s"
|
||||
.formatted(stepPath),
|
||||
readWriteParseError.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.molnarandrei.sopa.testcase;
|
||||
|
||||
import com.molnarandrei.sopa.data.Trash;
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.DoesNotExistException;
|
||||
import com.molnarandrei.sopa.data.EmptyException;
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import com.molnarandrei.sopa.data.yaml.Yaml;
|
||||
import tools.jackson.core.JacksonException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.molnarandrei.sopa.Utils.STEP_ORDER;
|
||||
import static com.molnarandrei.sopa.Utils.renameIndexed;
|
||||
|
||||
public class TestCaseRepository {
|
||||
private static final Logger log = Logger.getLogger(TestCaseRepository.class.getName());
|
||||
|
||||
public static TestCase get(Path testCasePath) throws RepositoryException {
|
||||
if (! Files.isReadable(testCasePath)) throw new DoesNotExistException(testCasePath, "Unreadable");
|
||||
try {
|
||||
var testCase = Files.readString(testCasePath);
|
||||
if (testCase.isBlank())
|
||||
throw new EmptyException(testCasePath, "TestCase file is empty");
|
||||
var obj = Yaml.toTestCase(testCase);
|
||||
if (obj == null)
|
||||
throw new RepositoryException(testCasePath, "Not a testcase");
|
||||
return obj;
|
||||
} catch (RepositoryException repo) {
|
||||
throw repo;
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(testCasePath, "Could not read file", io);
|
||||
} catch (JacksonException mapping) {
|
||||
throw new RepositoryException(testCasePath, "Bad format", mapping);
|
||||
}
|
||||
}
|
||||
|
||||
public static void update(Path testCasePath, TestCase testCase) throws RepositoryException {
|
||||
try {
|
||||
var yaml = Yaml.toYaml(testCase);
|
||||
Files.writeString(testCasePath, yaml);
|
||||
ProjectMonitors.trigger(testCasePath.getParent().getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(testCasePath, "Cannot write testcase", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static void move(Path fromTestCasePath, Path toProjectPath) throws RepositoryException {
|
||||
if (!Files.exists(fromTestCasePath))
|
||||
throw new RepositoryException(fromTestCasePath, "From testcase does not exist.");
|
||||
if (!Files.exists(toProjectPath))
|
||||
throw new RepositoryException(fromTestCasePath, "To project does not exist.");
|
||||
|
||||
log.info("Moving testcase %s onto testcase %s.".formatted(fromTestCasePath, toProjectPath));
|
||||
var fromTestCaseDirectory = fromTestCasePath.getParent();
|
||||
var fromProjectDirectory = fromTestCaseDirectory.getParent();
|
||||
var toProjectDirectory = toProjectPath.getParent();
|
||||
if (fromProjectDirectory.equals(toProjectDirectory)) {
|
||||
log.warning("Haven't implemented reordering yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
var destination = renameIndexed(
|
||||
toProjectDirectory.resolve(fromTestCaseDirectory.getFileName())
|
||||
);
|
||||
try {
|
||||
Files.move(fromTestCaseDirectory, destination);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(fromTestCasePath, "Cannot move testcase to '%s'".formatted(destination), io);
|
||||
}
|
||||
|
||||
ProjectMonitors.trigger(toProjectDirectory);
|
||||
if (! fromProjectDirectory.equals(toProjectDirectory))
|
||||
ProjectMonitors.trigger(fromProjectDirectory);
|
||||
}
|
||||
|
||||
public static void copy(Path fromTestCaseDirectory, Path toTestCaseDirectory) throws RepositoryException {
|
||||
if (!Files.isDirectory(fromTestCaseDirectory)) {
|
||||
throw new RepositoryException(fromTestCaseDirectory, "TestCase to clone does not exist");
|
||||
}
|
||||
if (Files.exists(toTestCaseDirectory)) {
|
||||
throw new RepositoryException(toTestCaseDirectory, "TestCase folder already exists");
|
||||
}
|
||||
|
||||
log.info("Copying testcase %s onto testcase %s.".formatted(fromTestCaseDirectory, toTestCaseDirectory));
|
||||
try {
|
||||
Files.createDirectory(toTestCaseDirectory);
|
||||
|
||||
var testCase = get(fromTestCaseDirectory.resolve("testcase.yml"));
|
||||
var rename = toTestCaseDirectory.getFileName().toString().replaceAll("-", " ").replaceAll("_", " ");
|
||||
rename = Character.toUpperCase(rename.charAt(0)) + rename.substring(1);
|
||||
testCase.setName(rename);
|
||||
var yaml = Yaml.toYaml(testCase);
|
||||
Files.writeString(toTestCaseDirectory.resolve("testcase.yml"), yaml);
|
||||
|
||||
Utils.copyDirectory(fromTestCaseDirectory, toTestCaseDirectory,
|
||||
path -> "testcase.yml".equals(path.getFileName().toString()));
|
||||
|
||||
} catch (RepositoryException e) {
|
||||
throw e;
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(toTestCaseDirectory, "Could create step file", io);
|
||||
}
|
||||
|
||||
var fromProjectDirectory = fromTestCaseDirectory.getParent();
|
||||
var toProjectDirectory = toTestCaseDirectory.getParent();
|
||||
ProjectMonitors.trigger(toProjectDirectory);
|
||||
if (! fromProjectDirectory.equals(toProjectDirectory))
|
||||
ProjectMonitors.trigger(fromProjectDirectory);
|
||||
}
|
||||
|
||||
public static void delete(Path testCasePath) throws RepositoryException {
|
||||
if (! Files.exists(testCasePath))
|
||||
return;
|
||||
|
||||
var testCaseDirectory = testCasePath.getParent();
|
||||
try {
|
||||
if (! Files.isDirectory(testCaseDirectory))
|
||||
return;
|
||||
|
||||
try (var walk = Files.walk(testCaseDirectory)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> {
|
||||
try {
|
||||
Files.delete(p);
|
||||
} catch (IOException ignore) {}
|
||||
});
|
||||
}
|
||||
|
||||
if (! Files.exists(testCaseDirectory))
|
||||
throw new IOException("Not deleted.");
|
||||
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(testCaseDirectory, "Could not delete testcase", io);
|
||||
|
||||
} finally {
|
||||
ProjectMonitors.trigger(testCasePath.getParent().getParent());
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Path> getPathsOfContainedSteps(Path testCasePath) throws RepositoryException {
|
||||
var testCaseDirectory = testCasePath.getParent();
|
||||
if (! Files.isDirectory(testCaseDirectory))
|
||||
throw new RepositoryException(testCaseDirectory, "TestCase does not exist");
|
||||
|
||||
try (var walk = Files.walk(testCaseDirectory)) {
|
||||
return walk.filter(n->"step.yml".equals(n.getFileName().toString())).sorted(STEP_ORDER).collect(Collectors.toList());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(testCaseDirectory, "Cannot walk directory");
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the folder of the testcase, with its steps, to the {@link Trash}. @return where it is kept. */
|
||||
public static Path trash(Path testCasePath) throws RepositoryException {
|
||||
try {
|
||||
return Trash.keep(testCasePath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(testCasePath, "Could not delete testcase", io);
|
||||
} finally {
|
||||
ProjectMonitors.trigger(testCasePath.getParent().getParent());
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves the folder of a testcase back from the {@link Trash}. */
|
||||
public static void restore(Path testCasePath, Path kept) throws RepositoryException {
|
||||
try {
|
||||
Trash.restore(kept, testCasePath.getParent());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(testCasePath, io.getMessage(), io);
|
||||
} finally {
|
||||
ProjectMonitors.trigger(testCasePath.getParent().getParent());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package com.molnarandrei.sopa.testcase;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.trash.TrashService;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import javafx.scene.control.TextInputDialog;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.molnarandrei.sopa.Utils.baseNameOf;
|
||||
import static com.molnarandrei.sopa.Utils.highestIndexOf;
|
||||
import static com.molnarandrei.sopa.Utils.renameIndexed;
|
||||
|
||||
public class TestCaseService {
|
||||
private static final Logger log = Logger.getLogger(TestCaseService.class.getName());
|
||||
|
||||
public static TestCase read(Path testCasePath) {
|
||||
try {
|
||||
return TestCaseRepository.get(testCasePath);
|
||||
} catch (RepositoryException readWriteOrParseErr) {
|
||||
log.log(Level.SEVERE, "Cannot read testcase %s.".formatted(testCasePath), readWriteOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido abrir el caso de prueba:\n%s"
|
||||
.formatted(testCasePath),
|
||||
readWriteOrParseErr.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void create(Path projectPath) {
|
||||
var input = new TextInputDialog();
|
||||
input.setTitle("Crear caso de prueba");
|
||||
input.setHeaderText("Nombre del caso");
|
||||
var name = input.showAndWait().orElse("");
|
||||
if (name.isBlank()) return;
|
||||
|
||||
var testCaseDirectory = projectPath.getParent().resolve("testcase-1");
|
||||
if (Files.exists(testCaseDirectory))
|
||||
testCaseDirectory = renameIndexed(testCaseDirectory);
|
||||
try {
|
||||
Files.createDirectory(testCaseDirectory);
|
||||
} catch (IOException cannotCreate) {
|
||||
log.log(Level.SEVERE, "Cannot create testcase directory %s.".formatted(testCaseDirectory), testCaseDirectory);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido crear el caso:\n%s"
|
||||
.formatted(testCaseDirectory),
|
||||
cannotCreate.getMessage()
|
||||
);
|
||||
return;
|
||||
}
|
||||
var testCase = new TestCase(name);
|
||||
write(testCaseDirectory.resolve("testcase.yml"), testCase);
|
||||
}
|
||||
|
||||
|
||||
/** Writes the testcase, alerting on failure. Returns whether it was written. */
|
||||
public static boolean write(Path testCasePath, TestCase testCase) {
|
||||
testCase.getHeaders().entrySet().removeIf(entry ->
|
||||
entry.getKey() == null || entry.getKey().isBlank() ||
|
||||
entry.getValue() == null || entry.getValue().isBlank()
|
||||
);
|
||||
try {
|
||||
TestCaseRepository.update(testCasePath, testCase);
|
||||
return true;
|
||||
} catch (RepositoryException cannotWrite) {
|
||||
log.log(Level.SEVERE, "Cannot write testcase %s.".formatted(testCasePath), cannotWrite);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido guardar el caso:\n%s"
|
||||
.formatted(testCasePath),
|
||||
cannotWrite.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a new testcase with the contents of {@code testCasePath} into {@code toProjectPath},
|
||||
* followed by a copy of each of its steps in the same order. Only the testcase gets
|
||||
* {@code nameSuffix} after its name, its steps keep theirs. Returns the path of the new testcase.yml, null when
|
||||
* the testcase or any of its steps could not be copied.
|
||||
*/
|
||||
public static Path copyInto(Path testCasePath, Path toProjectPath, String nameSuffix) {
|
||||
log.info("Copying testcase %s into project %s.".formatted(testCasePath, toProjectPath));
|
||||
var testCase = read(testCasePath);
|
||||
if (testCase == null) return null;
|
||||
|
||||
List<Path> stepPaths;
|
||||
try {
|
||||
stepPaths = TestCaseRepository.getPathsOfContainedSteps(testCasePath);
|
||||
} catch (RepositoryException cannotList) {
|
||||
log.log(Level.SEVERE, "Cannot list steps of testcase %s.".formatted(testCasePath), cannotList);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se han podido leer los pasos del caso:\n%s"
|
||||
.formatted(testCasePath),
|
||||
cannotList.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
var toProjectDirectory = toProjectPath.getParent();
|
||||
Path copiedTestCaseDirectory = null;
|
||||
try {
|
||||
var baseName = baseNameOf(testCasePath.getParent());
|
||||
var highestIndex = highestIndexOf(toProjectDirectory, baseName);
|
||||
copiedTestCaseDirectory = renameIndexed(toProjectDirectory.resolve(baseName + "-" + (highestIndex + 1)));
|
||||
Files.createDirectory(copiedTestCaseDirectory);
|
||||
} catch (IOException cannotCreate) {
|
||||
log.log(Level.SEVERE, "Cannot create testcase directory in %s.".formatted(toProjectDirectory), cannotCreate);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido crear el caso en:\n%s"
|
||||
.formatted(toProjectDirectory),
|
||||
cannotCreate.getMessage()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
testCase.setName(testCase.getName() + nameSuffix);
|
||||
var copiedTestCasePath = copiedTestCaseDirectory.resolve("testcase.yml");
|
||||
if (! write(copiedTestCasePath, testCase)) {
|
||||
try {
|
||||
TestCaseRepository.delete(copiedTestCasePath);
|
||||
} catch (RepositoryException leftover) {
|
||||
log.log(Level.WARNING, "Cannot clean up failed testcase copy %s.".formatted(copiedTestCasePath), leftover);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
var allStepsCopied = true;
|
||||
for (var stepPath : stepPaths)
|
||||
if (StepService.copyInto(stepPath, copiedTestCasePath, "") == null)
|
||||
allStepsCopied = false;
|
||||
|
||||
return allStepsCopied? copiedTestCasePath: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pastes the testcase at the end of {@code toProjectPath}. A cut testcase is erased once it
|
||||
* and all its steps are copied, and keeps its name. As testcases have no order, cutting
|
||||
* a testcase onto its own project does nothing.
|
||||
*/
|
||||
public static void pasteOnProject(Path testCasePath, Path toProjectPath, boolean cut) {
|
||||
log.info("Pasting %s testcase %s onto project %s.".formatted(cut? "cut": "copied", testCasePath, toProjectPath));
|
||||
if (cut && testCasePath.getParent().getParent().equals(toProjectPath.getParent())) {
|
||||
log.info("Testcase %s cut onto its own project, not pasting.".formatted(testCasePath));
|
||||
return;
|
||||
}
|
||||
|
||||
var copiedTestCasePath = copyInto(testCasePath, toProjectPath, cut? "": StepService.COPY_SUFFIX);
|
||||
if (copiedTestCasePath == null) return;
|
||||
if (cut) erase(testCasePath);
|
||||
}
|
||||
|
||||
|
||||
public static void toggleActive(Path testCasePath) {
|
||||
log.info("Toggling testcase %s.".formatted(testCasePath));
|
||||
var testCase = read(testCasePath);
|
||||
if (testCase == null) return;
|
||||
|
||||
testCase.setActive( ! testCase.isActive() );
|
||||
write(testCasePath, testCase);
|
||||
}
|
||||
|
||||
|
||||
public static void duplicate(Path testCasePath) {
|
||||
log.info("Copying testcase %s.".formatted(testCasePath));
|
||||
Path copiedTestCaseDirectory = null;
|
||||
Path toTestCaseDirectory = null;
|
||||
try {
|
||||
copiedTestCaseDirectory = testCasePath.getParent();
|
||||
toTestCaseDirectory = renameIndexed(copiedTestCaseDirectory);
|
||||
TestCaseRepository.copy(copiedTestCaseDirectory, toTestCaseDirectory);
|
||||
} catch (RepositoryException readWriteOrParseErr) {
|
||||
log.log(Level.WARNING, "Copy testcase error %s.".formatted(testCasePath), readWriteOrParseErr);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido copiar el case de orgigen/destino:\n%s\n%s"
|
||||
.formatted(copiedTestCaseDirectory, toTestCaseDirectory),
|
||||
readWriteOrParseErr.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Moves the testcase, with its steps, to the trash: {@link TrashService#undo()} restores it. */
|
||||
public static void delete(Path testCasePath) {
|
||||
log.info("Deleting testcase %s.".formatted(testCasePath));
|
||||
try {
|
||||
TrashService.remember(Kind.testcase, testCasePath, TestCaseRepository.trash(testCasePath));
|
||||
} catch (RepositoryException cannotDeleteAllFiles) {
|
||||
log.log(Level.WARNING, "Delete testcase error %s.".formatted(testCasePath), cannotDeleteAllFiles);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido eliminar el caso:\n%s"
|
||||
.formatted(testCasePath),
|
||||
cannotDeleteAllFiles.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts back a testcase moved to the trash by {@link #delete(Path)}. */
|
||||
public static boolean restore(Path testCasePath, Path kept) {
|
||||
log.info("Restoring testcase %s.".formatted(testCasePath));
|
||||
try {
|
||||
TestCaseRepository.restore(testCasePath, kept);
|
||||
return true;
|
||||
} catch (RepositoryException cannotRestore) {
|
||||
log.log(Level.WARNING, "Cannot restore testcase %s.".formatted(testCasePath), cannotRestore);
|
||||
Utils.alert(
|
||||
"No se puede deshacer",
|
||||
"No se ha podido restaurar el caso:\n%s".formatted(testCasePath),
|
||||
cannotRestore.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Erases a cut testcase once pasted: it is not kept in the trash, its copy is where it went. */
|
||||
private static void erase(Path testCasePath) {
|
||||
try {
|
||||
TestCaseRepository.delete(testCasePath);
|
||||
} catch (RepositoryException cannotDeleteAllFiles) {
|
||||
log.log(Level.WARNING, "Erase cut testcase error %s.".formatted(testCasePath), cannotDeleteAllFiles);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido eliminar el caso cortado:\n%s"
|
||||
.formatted(testCasePath),
|
||||
cannotDeleteAllFiles.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.molnarandrei.sopa.trash;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* The deletions of this session, to undo them latest first.
|
||||
* The services of each kind delete into the trash and restore from it.
|
||||
*/
|
||||
public class TrashService {
|
||||
private static final Logger log = Logger.getLogger(TrashService.class.getName());
|
||||
|
||||
/**
|
||||
* @param path the yml of the deleted object, where it is restored.
|
||||
* @param kept the folder of the object inside the trash.
|
||||
*/
|
||||
public record Deleted(Kind kind, Path path, Path kept) {}
|
||||
|
||||
private static final Deque<Deleted> deleted = new ArrayDeque<>();
|
||||
|
||||
/** Called by the services once they moved {@code path} to the trash, kept at {@code kept}. */
|
||||
public static synchronized void remember(Kind kind, Path path, Path kept) {
|
||||
deleted.push(new Deleted(kind, path, kept));
|
||||
}
|
||||
|
||||
public static synchronized boolean canUndo() {
|
||||
return ! deleted.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores the last deletion through the service of its kind. It stays to undo when it cannot be restored,
|
||||
* as when its place is taken or its parent is gone.
|
||||
*
|
||||
* @return the restored deletion, null when there is none or it could not be restored.
|
||||
*/
|
||||
public static synchronized Deleted undo() {
|
||||
var last = deleted.peek();
|
||||
if (last == null) {
|
||||
log.info("Nothing to undo.");
|
||||
return null;
|
||||
}
|
||||
var restored = switch (last.kind()) {
|
||||
case project -> ProjectService.restore(last.path(), last.kept());
|
||||
case testcase -> TestCaseService.restore(last.path(), last.kept());
|
||||
case step -> StepService.restore(last.path(), last.kept());
|
||||
};
|
||||
if (! restored) return null;
|
||||
deleted.pop();
|
||||
return last;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package com.molnarandrei.sopa.ui;
|
||||
|
||||
import atlantafx.base.controls.Spacer;
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.data.yaml.Project;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ProjectTreeViewEvent;
|
||||
import com.molnarandrei.sopa.events.SoapCallEvent;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import com.molnarandrei.sopa.ui.editor.Destroyable;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.geometry.Bounds;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Rectangle2D;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.Modality;
|
||||
import javafx.stage.Screen;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.StageStyle;
|
||||
import javafx.stage.Window;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Always on top, non modal window that shows the merged properties (project, then testcase overriding)
|
||||
* of the selected tree element and lets them be edited and saved back to their files.
|
||||
*/
|
||||
public class PropertiesDialog extends Stage implements Destroyable {
|
||||
private static final Logger log = Logger.getLogger(PropertiesDialog.class.getName());
|
||||
private static final double DEFAULT_WIDTH = 420d;
|
||||
private static final double DEFAULT_HEIGHT = 360d;
|
||||
|
||||
private Path path;
|
||||
private Kind kind;
|
||||
|
||||
private Path projectPath;
|
||||
private Project project;
|
||||
private Path testCasePath;
|
||||
private TestCase testCase;
|
||||
|
||||
private final Label title;
|
||||
private final GridPane grid;
|
||||
private final Button addBtn;
|
||||
private final Button saveBtn;
|
||||
private final List<Row> rows = new ArrayList<>();
|
||||
|
||||
private record Row(TextField key, TextField value, Button remove) {}
|
||||
|
||||
private final EventHandler<ProjectTreeViewEvent> selectionHandler = this::onSelection;
|
||||
private final EventHandler<SoapCallEvent> callFinishedHandler = this::onCallFinished;
|
||||
|
||||
/**
|
||||
* @param owner main window, the dialog floats above it.
|
||||
* @param anchor screen bounds of the button that opened it; its bottom right corner becomes the
|
||||
* dialog's top right corner. May be null, then the dialog is centered on screen.
|
||||
* @param initialPath currently selected path, or null.
|
||||
* @param initialKind currently selected kind, or null.
|
||||
* @param onDestroyed called once the dialog is closed by any mechanism.
|
||||
*/
|
||||
public PropertiesDialog(Window owner, Bounds anchor, Path initialPath, Kind initialKind, Runnable onDestroyed) {
|
||||
initOwner(owner);
|
||||
initModality(Modality.NONE);
|
||||
initStyle(StageStyle.UTILITY);
|
||||
setAlwaysOnTop(true);
|
||||
setTitle("Propiedades");
|
||||
|
||||
title = new Label("Propiedades");
|
||||
Styles.addStyleClass(title, Styles.TITLE_3);
|
||||
|
||||
grid = new GridPane();
|
||||
grid.setHgap(4);
|
||||
grid.setVgap(8);
|
||||
var keyColumn = new ColumnConstraints();
|
||||
keyColumn.setHgrow(Priority.SOMETIMES);
|
||||
keyColumn.setPercentWidth(40);
|
||||
var valueColumn = new ColumnConstraints();
|
||||
valueColumn.setHgrow(Priority.ALWAYS);
|
||||
grid.getColumnConstraints().addAll(keyColumn, valueColumn, new ColumnConstraints());
|
||||
|
||||
var scroll = new ScrollPane(grid);
|
||||
scroll.setFitToWidth(true);
|
||||
scroll.setPadding(new Insets(4));
|
||||
|
||||
addBtn = new Button("Agregar propiedad", FontIcon.of(MaterialDesignP.PLUS));
|
||||
addBtn.setOnAction(e -> addRow("", ""));
|
||||
|
||||
saveBtn = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE));
|
||||
saveBtn.setOnAction(e -> save());
|
||||
|
||||
var actions = new HBox(8, addBtn, new Spacer(), saveBtn);
|
||||
var bottom = new VBox(8, new Separator(), actions);
|
||||
|
||||
var root = new BorderPane();
|
||||
root.setPadding(new Insets(8));
|
||||
root.setTop(title);
|
||||
BorderPane.setMargin(title, new Insets(0, 0, 8, 0));
|
||||
root.setCenter(scroll);
|
||||
root.setBottom(bottom);
|
||||
BorderPane.setMargin(bottom, new Insets(8, 0, 0, 0));
|
||||
|
||||
var config = Config.get();
|
||||
var width = config.getPropertiesDialogWidth() != null ? config.getPropertiesDialogWidth() : DEFAULT_WIDTH;
|
||||
var height = config.getPropertiesDialogHeight() != null ? config.getPropertiesDialogHeight() : DEFAULT_HEIGHT;
|
||||
var scene = new Scene(root, width, height);
|
||||
if (owner != null && owner.getScene() != null)
|
||||
scene.getStylesheets().addAll(owner.getScene().getStylesheets());
|
||||
setScene(scene);
|
||||
setWidth(width);
|
||||
setHeight(height);
|
||||
position(config, anchor, width, height);
|
||||
|
||||
// Hidden covers both the window X and a programmatic close() from the menu button.
|
||||
setOnHidden(e -> {
|
||||
Config.get().updatePropertiesDialog(this).save();
|
||||
destroy();
|
||||
if (onDestroyed != null) onDestroyed.run();
|
||||
});
|
||||
|
||||
Events.addListener(ProjectTreeViewEvent.SELECTED, selectionHandler);
|
||||
Events.addListener(SoapCallEvent.FINISHED, callFinishedHandler);
|
||||
|
||||
reload(initialPath, initialKind);
|
||||
}
|
||||
|
||||
private void position(Config config, Bounds anchor, double width, double height) {
|
||||
if (config.getPropertiesDialogX() != null && config.getPropertiesDialogY() != null) {
|
||||
var x = config.getPropertiesDialogX();
|
||||
var y = config.getPropertiesDialogY();
|
||||
// Only reuse the stored position when it is still on a connected screen.
|
||||
if (!Screen.getScreensForRectangle(x, y, width, height).isEmpty()) {
|
||||
setX(x);
|
||||
setY(y);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (anchor != null) {
|
||||
setX(anchor.getMaxX() - width);
|
||||
setY(anchor.getMaxY());
|
||||
return;
|
||||
}
|
||||
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
|
||||
setX(screen.getMinX() + (screen.getWidth() - width) / 2);
|
||||
setY(screen.getMinY() + (screen.getHeight() - height) / 2);
|
||||
}
|
||||
|
||||
private void onSelection(ProjectTreeViewEvent event) {
|
||||
var identity = event.get();
|
||||
if (identity == null) return;
|
||||
reload(identity.path(), identity.kind());
|
||||
}
|
||||
|
||||
private void onCallFinished(SoapCallEvent event) {
|
||||
reload(null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the active path and kind when given, then loads the properties for the active ones.
|
||||
* Project properties are applied first, testcase properties overwrite them.
|
||||
*/
|
||||
public void reload(Path path, Kind kind) {
|
||||
if (path != null) this.path = path;
|
||||
if (kind != null) this.kind = kind;
|
||||
|
||||
projectPath = null;
|
||||
project = null;
|
||||
testCasePath = null;
|
||||
testCase = null;
|
||||
|
||||
if (this.path == null || this.kind == null) {
|
||||
title.setText("Selecciona un proyecto, caso o paso");
|
||||
showProperties(Map.of());
|
||||
return;
|
||||
}
|
||||
|
||||
switch (this.kind) {
|
||||
case project -> projectPath = this.path;
|
||||
case testcase -> {
|
||||
testCasePath = this.path;
|
||||
projectPath = testCasePath.getParent().getParent().resolve("project.yml");
|
||||
}
|
||||
case step -> {
|
||||
testCasePath = this.path.getParent().getParent().resolve("testcase.yml");
|
||||
projectPath = testCasePath.getParent().getParent().resolve("project.yml");
|
||||
}
|
||||
}
|
||||
|
||||
project = ProjectService.read(projectPath);
|
||||
if (testCasePath != null)
|
||||
testCase = TestCaseService.read(testCasePath);
|
||||
|
||||
var properties = new HashMap<String, String>();
|
||||
if (project != null && project.getProperties() != null)
|
||||
properties.putAll(project.getProperties());
|
||||
if (testCase != null && testCase.getProperties() != null)
|
||||
properties.putAll(testCase.getProperties());
|
||||
|
||||
if (testCase != null)
|
||||
title.setText("Propiedades de %s".formatted(testCase.getName()));
|
||||
else if (project != null)
|
||||
title.setText("Propiedades de %s".formatted(project.getName()));
|
||||
else
|
||||
title.setText("Propiedades");
|
||||
|
||||
showProperties(properties);
|
||||
}
|
||||
|
||||
private void showProperties(Map<String, String> properties) {
|
||||
grid.getChildren().clear();
|
||||
rows.clear();
|
||||
new TreeMap<>(properties).forEach(this::addRow);
|
||||
var editable = project != null;
|
||||
addBtn.setDisable(!editable);
|
||||
saveBtn.setDisable(!editable);
|
||||
}
|
||||
|
||||
private void addRow(String key, String value) {
|
||||
var keyField = new TextField(key);
|
||||
var valueField = new TextField(value);
|
||||
var removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE));
|
||||
keyField.setPromptText("llave");
|
||||
valueField.setPromptText("valor");
|
||||
keyField.setOnAction(e -> save());
|
||||
valueField.setOnAction(e -> save());
|
||||
|
||||
var row = new Row(keyField, valueField, removeBtn);
|
||||
removeBtn.setOnAction(e -> {
|
||||
rows.remove(row);
|
||||
grid.getChildren().removeAll(keyField, valueField, removeBtn);
|
||||
});
|
||||
|
||||
var index = grid.getRowCount();
|
||||
grid.add(keyField, 0, index);
|
||||
grid.add(valueField, 1, index);
|
||||
grid.add(removeBtn, 2, index);
|
||||
rows.add(row);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the edited properties back. An existing key stays where it was defined (testcase first,
|
||||
* then project); new keys go to the testcase when there is one, otherwise to the project.
|
||||
* Removed keys are removed from both.
|
||||
*/
|
||||
private void save() {
|
||||
if (project == null) return;
|
||||
|
||||
var edited = new HashMap<String, String>();
|
||||
for (var row : rows) {
|
||||
var key = row.key().getText();
|
||||
if (key == null || key.isBlank()) continue;
|
||||
edited.put(key.strip(), row.value().getText() == null ? "" : row.value().getText());
|
||||
}
|
||||
|
||||
var projectProperties = project.getProperties();
|
||||
Map<String, String> testCaseProperties = testCase == null ? null : testCase.getProperties();
|
||||
if (testCase != null && testCaseProperties == null) {
|
||||
testCaseProperties = new HashMap<>();
|
||||
testCase.setProperties(testCaseProperties);
|
||||
}
|
||||
|
||||
var newProject = new HashMap<String, String>();
|
||||
var newTestCase = new HashMap<String, String>();
|
||||
for (var entry : edited.entrySet()) {
|
||||
var key = entry.getKey();
|
||||
if (testCaseProperties != null && testCaseProperties.containsKey(key))
|
||||
newTestCase.put(key, entry.getValue());
|
||||
else if (projectProperties.containsKey(key))
|
||||
newProject.put(key, entry.getValue());
|
||||
else if (testCaseProperties != null)
|
||||
newTestCase.put(key, entry.getValue());
|
||||
else
|
||||
newProject.put(key, entry.getValue());
|
||||
}
|
||||
|
||||
// A testcase view only sees project keys it does not shadow; keep shadowed project keys intact.
|
||||
if (testCaseProperties != null)
|
||||
for (var entry : projectProperties.entrySet())
|
||||
if (testCaseProperties.containsKey(entry.getKey()) && !newProject.containsKey(entry.getKey()))
|
||||
newProject.put(entry.getKey(), entry.getValue());
|
||||
|
||||
log.info("Saving properties of %s and %s.".formatted(projectPath, testCasePath));
|
||||
projectProperties.clear();
|
||||
projectProperties.putAll(newProject);
|
||||
ProjectService.write(projectPath, project);
|
||||
|
||||
if (testCase != null) {
|
||||
testCaseProperties.clear();
|
||||
testCaseProperties.putAll(newTestCase);
|
||||
TestCaseService.write(testCasePath, testCase);
|
||||
}
|
||||
|
||||
reload(null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
Events.removeListener(ProjectTreeViewEvent.SELECTED, selectionHandler);
|
||||
Events.removeListener(SoapCallEvent.FINISHED, callFinishedHandler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.molnarandrei.sopa.ui;
|
||||
|
||||
import atlantafx.base.theme.PrimerDark;
|
||||
import com.molnarandrei.sopa.data.ProjectMonitors;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ProjectTreeViewEvent;
|
||||
import com.molnarandrei.sopa.ui.editor.EditorPane;
|
||||
import com.molnarandrei.sopa.ui.menu.TopMenu;
|
||||
import com.molnarandrei.sopa.ui.navpane.ProjectPane;
|
||||
import javafx.application.Application;
|
||||
import javafx.application.Platform;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.geometry.Orientation;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.SplitPane;
|
||||
import javafx.scene.layout.BorderPane;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SopaApplication extends Application {
|
||||
private Stage stage;
|
||||
private static final Logger log = Logger.getLogger(SopaApplication.class.getName());
|
||||
private static final Config config = Config.get();
|
||||
private final EventHandler<ProjectTreeViewEvent> treeSelectionHandler = this::onTreeSelection;
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) {
|
||||
this.stage = stage;
|
||||
log.info("Starting.");
|
||||
|
||||
Events.setGlobalEventNode(stage);
|
||||
Application.setUserAgentStylesheet(new PrimerDark().getUserAgentStylesheet());
|
||||
|
||||
var split = new SplitPane();
|
||||
split.setId("splitPane");
|
||||
split.setOrientation(Orientation.HORIZONTAL);
|
||||
|
||||
var left = new ProjectPane();
|
||||
left.setMinWidth(200d);
|
||||
var right = new EditorPane();
|
||||
left.setMinWidth(300d);
|
||||
split.getItems().addAll(left, right);
|
||||
|
||||
var root = new BorderPane();
|
||||
root.setTop(new TopMenu());
|
||||
root.setCenter(split);
|
||||
|
||||
var scene = new Scene(root, 800, 500);
|
||||
stage.setTitle("Sopa");
|
||||
stage.setScene(scene);
|
||||
|
||||
stage.setMaximized(config.isWindowMaximized());
|
||||
stage.setHeight(config.getWindowSizeHeight());
|
||||
stage.setWidth(config.getWindowSizeWidth());
|
||||
stage.setX(config.getWindowPositionX());
|
||||
stage.setY(config.getWindowPositionY());
|
||||
|
||||
stage.show();
|
||||
Platform.runLater(() -> split.setDividerPosition(0, config.getLayoutSplitPosition()));
|
||||
Platform.runLater(() -> {
|
||||
try { Thread.sleep(1); } catch (Exception ignore) {}
|
||||
config.reloadSavedState();
|
||||
} );
|
||||
|
||||
stage.setOnCloseRequest(windowEvent -> {
|
||||
log.info("Stopping.");
|
||||
config.update(stage, root).save();
|
||||
ProjectMonitors.close();
|
||||
log.info("Stopped.");
|
||||
});
|
||||
|
||||
log.info("Loading custom styles form resources.");
|
||||
try {
|
||||
var globalStyle = getClass().getResource("/style.css").toExternalForm();
|
||||
var xmlStyle = getClass().getResource("/code-area.css").toExternalForm();
|
||||
scene.getStylesheets().addAll(globalStyle, xmlStyle);
|
||||
} catch (Exception e) {
|
||||
log.log(Level.WARNING, "Failed to load style resource files.", e);
|
||||
}
|
||||
log.info("Started.");
|
||||
|
||||
Events.addListener(ProjectTreeViewEvent.SELECTED, treeSelectionHandler);
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
Events.removeListener(ProjectTreeViewEvent.SELECTED, treeSelectionHandler);
|
||||
}
|
||||
|
||||
private void onTreeSelection(ProjectTreeViewEvent event) {
|
||||
var treeIdentity = event.get();
|
||||
stage.setTitle("Sopa - %s".formatted(treeIdentity.path()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.molnarandrei.sopa.ui.create;
|
||||
|
||||
import atlantafx.base.controls.Spacer;
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.data.yaml.Project;
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlRemote;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlService;
|
||||
import com.molnarandrei.sopa.ui.editor.HeadersPane;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.DirectoryChooser;
|
||||
import javafx.stage.Modality;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.Window;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignF;
|
||||
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CreateProjectDialog extends Stage {
|
||||
private static final Logger log = Logger.getLogger(CreateProjectDialog.class.getName());
|
||||
private static final int CREATE_WSDL_TIMEOUT_SECONDS = 1;
|
||||
|
||||
private final BorderPane form = new BorderPane();
|
||||
private final TextField pathField = new TextField();
|
||||
private final Label pathError = new Label("No es una carpeta vacia");
|
||||
private final TextField nameField = new TextField();
|
||||
private final TextField endpointField = new TextField();
|
||||
private final ToggleGroup versionGroup = new ToggleGroup();
|
||||
private final CheckBox agentsFileBox = new CheckBox("Crear fichero AGENTS.md para asistencia IA");
|
||||
private final HashMap<String, String> headers = new HashMap<>();
|
||||
private final Label status = new Label();
|
||||
|
||||
private WsdlRemote.Download wsdlOfCurrentEndpoint = null;
|
||||
private boolean creating = false;
|
||||
|
||||
public CreateProjectDialog(Window owner) {
|
||||
initOwner(owner);
|
||||
initModality(Modality.WINDOW_MODAL);
|
||||
setTitle("Crear proyecto");
|
||||
setOnCloseRequest(e -> { if (creating) e.consume(); });
|
||||
|
||||
var title = new Label("Crear proyecto");
|
||||
Styles.addStyleClass(title, Styles.TITLE_1);
|
||||
|
||||
var fields = new GridPane();
|
||||
fields.setVgap(8);
|
||||
fields.setHgap(16);
|
||||
var fieldColumn = new ColumnConstraints();
|
||||
fieldColumn.setHgrow(Priority.ALWAYS);
|
||||
fields.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn, new ColumnConstraints());
|
||||
var row = 0;
|
||||
|
||||
pathField.setText(Path.of(System.getProperty("user.dir")).toString());
|
||||
pathField.textProperty().addListener((obs, old, value) -> showPathError(false));
|
||||
pathField.focusedProperty().addListener((obs, old, focused) -> {
|
||||
var leftFilled = ! focused && ! pathField.getText().isBlank();
|
||||
if (leftFilled) checkPath();
|
||||
});
|
||||
pathField.setOnAction(e -> create());
|
||||
var choosePath = new Button("", FontIcon.of(MaterialDesignF.FOLDER_OPEN));
|
||||
choosePath.setOnAction(e -> choosePath());
|
||||
fields.add(new Label("Carpeta:"), 0, row);
|
||||
fields.add(pathField, 1, row);
|
||||
fields.add(choosePath, 2, row);
|
||||
row++;
|
||||
|
||||
Styles.addStyleClass(pathError, Styles.DANGER);
|
||||
pathError.managedProperty().bind(pathError.visibleProperty());
|
||||
pathError.setVisible(false);
|
||||
fields.add(pathError, 1, row, 2, 1);
|
||||
row++;
|
||||
|
||||
nameField.setOnAction(e -> create());
|
||||
fields.add(new Label("Nombre:"), 0, row);
|
||||
fields.add(nameField, 1, row, 2, 1);
|
||||
row++;
|
||||
|
||||
endpointField.textProperty().addListener((obs, old, value) -> wsdlOfCurrentEndpoint = null);
|
||||
endpointField.setOnAction(e -> create());
|
||||
fields.add(new Label("Endpoint:"), 0, row);
|
||||
fields.add(endpointField, 1, row, 2, 1);
|
||||
row++;
|
||||
|
||||
var versions = new HBox(16);
|
||||
versions.setAlignment(Pos.CENTER_LEFT);
|
||||
for (var version : SoapVersion.values()) {
|
||||
var option = new RadioButton("v" + version.getTitle());
|
||||
option.setUserData(version);
|
||||
option.setToggleGroup(versionGroup);
|
||||
option.setSelected(version == SoapVersion.ONE_ONE);
|
||||
versions.getChildren().add(option);
|
||||
}
|
||||
fields.add(new Label("Versión SOAP:"), 0, row);
|
||||
fields.add(versions, 1, row, 2, 1);
|
||||
row++;
|
||||
|
||||
agentsFileBox.setSelected(true);
|
||||
fields.add(agentsFileBox, 1, row, 2, 1);
|
||||
|
||||
var headersPane = new HeadersPane(headers, this::create);
|
||||
headersPane.update();
|
||||
BorderPane.setMargin(headersPane, new Insets(8, 0, 8, 0));
|
||||
|
||||
var testDownloadWsdl = new Button("Probar / descargar WSDL", FontIcon.of(MaterialDesignD.DOWNLOAD));
|
||||
testDownloadWsdl.setOnAction(e -> testDownloadWsdl());
|
||||
|
||||
var create = new Button("Crear proyecto", FontIcon.of(MaterialDesignF.FOLDER_PLUS));
|
||||
Styles.addStyleClass(create, Styles.ACCENT);
|
||||
create.disableProperty().bind(nameField.textProperty().isEmpty());
|
||||
create.setOnAction(e -> create());
|
||||
|
||||
status.setWrapText(true);
|
||||
var actions = new HBox(8, new Spacer(), testDownloadWsdl, create);
|
||||
|
||||
form.setPadding(new Insets(16));
|
||||
form.setTop(new VBox(8, title, fields));
|
||||
form.setCenter(headersPane);
|
||||
form.setBottom(new VBox(8, new Separator(), status, actions));
|
||||
|
||||
var scene = new Scene(form, 600, 480);
|
||||
if (owner != null && owner.getScene() != null)
|
||||
scene.getStylesheets().addAll(owner.getScene().getStylesheets());
|
||||
setScene(scene);
|
||||
}
|
||||
|
||||
private void choosePath() {
|
||||
var chooser = new DirectoryChooser();
|
||||
chooser.setTitle("Crear carpeta y abrir como proyecto");
|
||||
var chosen = chooser.showDialog(this);
|
||||
if (chosen == null) return;
|
||||
|
||||
pathField.setText(chosen.toPath().toString());
|
||||
if (checkPath() && nameField.getText().isBlank())
|
||||
nameField.setText(chosen.getName().replaceAll("_", " ").replaceAll("-", " "));
|
||||
}
|
||||
|
||||
private boolean checkPath() {
|
||||
var valid = false;
|
||||
try {
|
||||
valid = ! pathField.getText().isBlank()
|
||||
&& ProjectRepository.canHoldNewProject(Path.of(pathField.getText().strip()));
|
||||
} catch (InvalidPathException notAPath) {
|
||||
log.fine("Not a path: %s".formatted(notAPath.getMessage()));
|
||||
}
|
||||
showPathError(! valid);
|
||||
return valid;
|
||||
}
|
||||
|
||||
private void showPathError(boolean error) {
|
||||
pathField.pseudoClassStateChanged(Styles.STATE_DANGER, error);
|
||||
pathError.setVisible(error);
|
||||
}
|
||||
|
||||
private void testDownloadWsdl() {
|
||||
var endpoint = endpointField.getText();
|
||||
showStatus("Descargando WSDL...", null);
|
||||
form.setDisable(true);
|
||||
Thread.ofVirtual().start(() -> {
|
||||
WsdlRemote.Download downloaded = null;
|
||||
String failure = null;
|
||||
try {
|
||||
downloaded = WsdlRemote.download(endpoint, Config.get().getCallTimeout());
|
||||
} catch (Exception cannotDownload) {
|
||||
failure = cannotDownload.getMessage() != null ? cannotDownload.getMessage() : cannotDownload.toString();
|
||||
}
|
||||
|
||||
var result = downloaded;
|
||||
var error = failure;
|
||||
Platform.runLater(() -> {
|
||||
if (! isShowing()) return;
|
||||
form.setDisable(false);
|
||||
if (result == null) {
|
||||
showStatus("No se ha podido descargar el WSDL: %s".formatted(error), Styles.DANGER);
|
||||
return;
|
||||
}
|
||||
wsdlOfCurrentEndpoint = result;
|
||||
selectVersion(WsdlService.detectVersion(result.wsdl(), endpoint));
|
||||
if (result.failedImports().isEmpty())
|
||||
showStatus("WSDL descargado: %s.".formatted(operations(result)), Styles.SUCCESS);
|
||||
else
|
||||
showStatus(
|
||||
"WSDL descargado: %s, pero faltan esquemas importados: %s"
|
||||
.formatted(operations(result), result.failedImports()),
|
||||
Styles.WARNING
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Selects the version the WSDL declares; leaves the selection when it declares none. */
|
||||
private void selectVersion(SoapVersion version) {
|
||||
if (version == null) return;
|
||||
for (var toggle : versionGroup.getToggles())
|
||||
if (toggle.getUserData() == version) versionGroup.selectToggle(toggle);
|
||||
}
|
||||
|
||||
private static String operations(WsdlRemote.Download download) {
|
||||
var count = WsdlService.operationCount(download);
|
||||
return count == 1 ? "1 operación" : "%d operaciones".formatted(count);
|
||||
}
|
||||
|
||||
private void create() {
|
||||
if (nameField.getText().isBlank() || ! checkPath()) return;
|
||||
|
||||
var directory = Path.of(pathField.getText().strip()).toAbsolutePath();
|
||||
var endpoint = endpointField.getText();
|
||||
var held = wsdlOfCurrentEndpoint;
|
||||
var createAgentsFile = agentsFileBox.isSelected();
|
||||
var project = new Project(nameField.getText(), List.of(), headers, new HashMap<>());
|
||||
project.putEndpoint(endpoint, (SoapVersion) versionGroup.getSelectedToggle().getUserData());
|
||||
|
||||
showLoader();
|
||||
Thread.ofVirtual().start(() -> {
|
||||
var download = held != null ? held : downloadIgnoringFailure(endpoint);
|
||||
// A WSDL tested before creating already selected its version, which may have been changed since.
|
||||
var detected = held == null && download != null ? WsdlService.detectVersion(download.wsdl(), endpoint) : null;
|
||||
if (detected != null) project.putEndpoint(endpoint, detected);
|
||||
var created = ProjectService.create(directory, project, createAgentsFile);
|
||||
if (created && download != null)
|
||||
WsdlService.write(directory.resolve("project.yml"), endpoint, download);
|
||||
|
||||
Platform.runLater(() -> {
|
||||
creating = false;
|
||||
if (created) close();
|
||||
else getScene().setRoot(form);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private static WsdlRemote.Download downloadIgnoringFailure(String endpoint) {
|
||||
try {
|
||||
return WsdlRemote.download(endpoint, CREATE_WSDL_TIMEOUT_SECONDS);
|
||||
} catch (Exception cannotDownload) {
|
||||
log.info("Creating project without WSDL: %s".formatted(cannotDownload));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void showLoader() {
|
||||
creating = true;
|
||||
var loader = new StackPane(new ProgressBar(ProgressIndicator.INDETERMINATE_PROGRESS));
|
||||
loader.setAlignment(Pos.CENTER);
|
||||
getScene().setRoot(loader);
|
||||
}
|
||||
|
||||
private void showStatus(String text, String style) {
|
||||
status.setText(text);
|
||||
status.getStyleClass().removeAll(Styles.SUCCESS, Styles.WARNING, Styles.DANGER);
|
||||
if (style != null) status.getStyleClass().add(style);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
/** Implemented by editors that EditorPane replaces; destroy() releases listeners and other resources. */
|
||||
public interface Destroyable {
|
||||
void destroy();
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.events.*;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import com.molnarandrei.sopa.ui.editor.step.StepEditorPane;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ProgressBar;
|
||||
import javafx.scene.control.ProgressIndicator;
|
||||
import javafx.scene.control.ScrollPane;
|
||||
import javafx.scene.layout.StackPane;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class EditorPane extends StackPane {
|
||||
private static final Logger log = Logger.getLogger(EditorPane.class.getName());
|
||||
|
||||
private Kind activeKind;
|
||||
private Path activePath;
|
||||
|
||||
private final ScrollPane scrollPane;
|
||||
private double lastScrollPosition = 0;
|
||||
private Path lastScrolledPath;
|
||||
/** True while the content is being replaced, so layout changes to the scroll are not remembered. */
|
||||
private boolean restoringScroll = false;
|
||||
|
||||
private final EventListeners listeners = new EventListeners()
|
||||
.on(ProjectTreeViewEvent.SELECTED, this::onSelectionChanged)
|
||||
.on(ProjectEvent.CHANGED, e -> onChanged(e.get()))
|
||||
.on(TestCaseEvent.CHANGED, e -> onChanged(e.get().testCase()))
|
||||
.on(StepEvent.CHANGED, e -> onChanged(e.get().step()));
|
||||
|
||||
public EditorPane() {
|
||||
setMinWidth(100d);
|
||||
|
||||
scrollPane = new ScrollPane();
|
||||
scrollPane.setFitToWidth(true);
|
||||
scrollPane.setFitToHeight(true);
|
||||
scrollPane.setPadding(new Insets(8, 8, 8, 8));
|
||||
scrollPane.vvalueProperty().addListener((obs, old, value)-> {
|
||||
if (!restoringScroll) lastScrollPosition = value.doubleValue();
|
||||
});
|
||||
getChildren().add(scrollPane);
|
||||
|
||||
showCentered(new Label("Carga un proyecto y selecciona un caso!"));
|
||||
|
||||
listeners.addAll();
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
listeners.removeAll();
|
||||
setContent(null);
|
||||
}
|
||||
|
||||
private void onChanged(Path changed) {
|
||||
if (activePath == null) return;
|
||||
var folder = Files.isDirectory(changed) ? changed : changed.getParent();
|
||||
if (activePath.startsWith(folder))
|
||||
load(activeKind, activePath);
|
||||
}
|
||||
|
||||
private void onSelectionChanged(ProjectTreeViewEvent event) {
|
||||
clear();
|
||||
activeKind = event.get().kind();
|
||||
activePath = event.get().path();
|
||||
load(activeKind, activePath);
|
||||
}
|
||||
|
||||
private void load(Kind kind, Path path) {
|
||||
if (!path.equals(lastScrolledPath)) {
|
||||
lastScrollPosition = 0;
|
||||
lastScrolledPath = path;
|
||||
}
|
||||
switch (kind) {
|
||||
case project -> loadProject(path);
|
||||
case testcase -> loadTestCase(path);
|
||||
case step -> loadStep(path);
|
||||
case null -> log.warning("Unknown kind for %s".formatted(path));
|
||||
}
|
||||
restoreScroll();
|
||||
}
|
||||
|
||||
|
||||
private void clear() {
|
||||
showCentered(new ProgressBar(ProgressIndicator.INDETERMINATE_PROGRESS));
|
||||
}
|
||||
|
||||
|
||||
private void showCentered(Node node) {
|
||||
var center = new StackPane(node);
|
||||
center.setAlignment(Pos.CENTER);
|
||||
setContent(center);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Saving rebuilds the editor, so the remembered position of the same path is set back once the
|
||||
* new content has been laid out.
|
||||
*/
|
||||
private void restoreScroll() {
|
||||
Platform.runLater(()-> {
|
||||
scrollPane.setVvalue(lastScrollPosition);
|
||||
restoringScroll = false;
|
||||
});
|
||||
}
|
||||
|
||||
private void setContent(Node content) {
|
||||
restoringScroll = true;
|
||||
if (scrollPane.getContent() instanceof Destroyable previous)
|
||||
previous.destroy();
|
||||
scrollPane.setContent(content);
|
||||
}
|
||||
|
||||
|
||||
private void loadProject(Path projectPath) {
|
||||
var project = ProjectService.read(projectPath);
|
||||
if (project == null) return;
|
||||
var editor = new ProjectEditorPane(projectPath, project);
|
||||
setContent(editor);
|
||||
}
|
||||
|
||||
|
||||
private void loadTestCase(Path testCasePath) {
|
||||
var testCase = TestCaseService.read(testCasePath);
|
||||
if (testCase == null) return;
|
||||
var editor = new TestCaseEditorPane(testCasePath, testCase);
|
||||
setContent(editor);
|
||||
}
|
||||
|
||||
|
||||
private void loadStep(Path stepPath) {
|
||||
var step = StepService.read(stepPath);
|
||||
if (step == null) return;
|
||||
var editor = new StepEditorPane(stepPath, step);
|
||||
setContent(editor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.UiEvent;
|
||||
import com.molnarandrei.sopa.ui.lib.SelectDialog;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlService;
|
||||
import javafx.application.Platform;
|
||||
import javafx.event.ActionEvent;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.TextField;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignF;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignL;
|
||||
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* The WSDL of the endpoint in an endpoint field, or of the endpoint it inherits, shown as its prompt text.
|
||||
* Its buttons follow the field once its editing is done: on enter or when it loses focus.
|
||||
*/
|
||||
public class EndpointWsdl {
|
||||
private static final int WSDL_TIMEOUT_SECONDS = 10;
|
||||
|
||||
private final Path projectPath;
|
||||
private final Path testCasePath;
|
||||
private final TextField endpointField;
|
||||
private final Button downloadButton;
|
||||
private final Button selectEndpointButton;
|
||||
private Button selectActionButton;
|
||||
private Path actionTarget;
|
||||
private boolean downloading = false;
|
||||
private Consumer<SoapVersion> onVersionDetected = version -> {};
|
||||
|
||||
/**
|
||||
* @param testCasePath the testcase whose properties replace those in the endpoint, over those of the
|
||||
* project; null for only those of the project.
|
||||
*/
|
||||
public EndpointWsdl(Path projectPath, Path testCasePath, TextField endpointField) {
|
||||
this.projectPath = projectPath;
|
||||
this.testCasePath = testCasePath;
|
||||
this.endpointField = endpointField;
|
||||
|
||||
downloadButton = new Button("", FontIcon.of(MaterialDesignD.DOWNLOAD));
|
||||
downloadButton.setOnAction(e -> download());
|
||||
|
||||
selectEndpointButton = new Button("Seleccionar", FontIcon.of(MaterialDesignL.LINK_VARIANT));
|
||||
selectEndpointButton.setOnAction(e -> selectEndpoint());
|
||||
|
||||
endpointField.addEventHandler(ActionEvent.ACTION, e -> refresh());
|
||||
endpointField.focusedProperty().addListener((obs, old, focused) -> {
|
||||
if (! focused) refresh();
|
||||
});
|
||||
endpointField.promptTextProperty().addListener((obs, old, value) -> refresh());
|
||||
refresh();
|
||||
}
|
||||
|
||||
/** Downloads or updates the WSDL of the endpoint. */
|
||||
public Button downloadButton() {
|
||||
return downloadButton;
|
||||
}
|
||||
|
||||
/** Called on the FX thread with the version the downloaded WSDL declares for the endpoint, if it does. */
|
||||
public void setOnVersionDetected(Consumer<SoapVersion> onVersionDetected) {
|
||||
this.onVersionDetected = onVersionDetected;
|
||||
}
|
||||
|
||||
/** Sets the field to one of the project endpoints. */
|
||||
public Button selectEndpointButton() {
|
||||
return selectEndpointButton;
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects an action of the WSDL for the step or testcase at {@code target}, emitting
|
||||
* {@link UiEvent#ACTION_SELECTED}. Without an endpoint or its WSDL it is disabled.
|
||||
*/
|
||||
public Button selectActionButton(Path target) {
|
||||
if (selectActionButton == null) {
|
||||
actionTarget = target;
|
||||
selectActionButton = new Button();
|
||||
refresh();
|
||||
}
|
||||
return selectActionButton;
|
||||
}
|
||||
|
||||
/** The endpoint in the field, else the inherited one. */
|
||||
public String endpoint() {
|
||||
var own = endpointField.getText();
|
||||
if (own != null && ! own.isBlank()) return own.strip();
|
||||
var inherited = endpointField.getPromptText();
|
||||
return inherited == null ? "" : inherited.strip();
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
var endpoint = endpoint();
|
||||
var blank = endpoint.isBlank();
|
||||
var exists = WsdlService.exists(projectPath, endpoint);
|
||||
|
||||
downloadButton.setText(exists ? "Actualizar WSDL" : "Descargar WSDL");
|
||||
setAccent(downloadButton, ! blank && ! exists);
|
||||
downloadButton.setDisable(downloading || blank);
|
||||
|
||||
selectEndpointButton.setDisable(WsdlService.endpoints(projectPath).isEmpty());
|
||||
|
||||
if (selectActionButton == null) return;
|
||||
selectActionButton.setText(blank || exists ? "Seleccionar" : "Sin WSDL");
|
||||
selectActionButton.setGraphic(FontIcon.of(MaterialDesignF.FORMAT_LIST_CHECKS));
|
||||
selectActionButton.setOnAction(e -> selectAction());
|
||||
selectActionButton.setDisable(blank || ! exists);
|
||||
}
|
||||
|
||||
private static void setAccent(Button button, boolean accent) {
|
||||
button.getStyleClass().remove(Styles.ACCENT);
|
||||
if (accent) button.getStyleClass().add(Styles.ACCENT);
|
||||
}
|
||||
|
||||
private void download() {
|
||||
var endpoint = endpoint();
|
||||
downloading = true;
|
||||
refresh();
|
||||
Thread.ofVirtual().start(() -> {
|
||||
var done = WsdlService.download(projectPath, testCasePath, endpoint, WSDL_TIMEOUT_SECONDS);
|
||||
var version = done ? WsdlService.detectVersion(projectPath, testCasePath, endpoint) : null;
|
||||
Platform.runLater(() -> {
|
||||
downloading = false;
|
||||
refresh();
|
||||
if (done) downloadButton.setText("Hecho");
|
||||
if (version != null) onVersionDetected.accept(version);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private void selectEndpoint() {
|
||||
new SelectDialog<>(
|
||||
endpointField.getScene().getWindow(),
|
||||
"Seleccionar endpoint",
|
||||
"El proyecto no tiene endpoints.",
|
||||
WsdlService.endpoints(projectPath),
|
||||
endpoint -> endpoint,
|
||||
endpoint -> WsdlService.exists(projectPath, endpoint) ? "" : "Sin WSDL",
|
||||
endpoint -> {
|
||||
endpointField.setText(endpoint);
|
||||
refresh();
|
||||
}
|
||||
).show();
|
||||
}
|
||||
|
||||
private void selectAction() {
|
||||
var endpoint = endpoint();
|
||||
var wsdl = WsdlService.read(projectPath, endpoint);
|
||||
var actions = WsdlService.getActions(projectPath, endpoint);
|
||||
if (wsdl == null || actions == null) return;
|
||||
new SelectDialog<>(
|
||||
selectActionButton.getScene().getWindow(),
|
||||
"Seleccionar accion",
|
||||
"El WSDL no tiene acciones.",
|
||||
actions,
|
||||
WsdlService.Action::name,
|
||||
WsdlService.Action::soapAction,
|
||||
action -> Events.emit(new UiEvent(
|
||||
UiEvent.ACTION_SELECTED,
|
||||
new UiEvent.ActionSelection(actionTarget, endpoint, action.soapAction(), action.object(), wsdl)
|
||||
))
|
||||
).show();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.data.yaml.Endpoint;
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
import javafx.geometry.HPos;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.RadioButton;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.control.ToggleGroup;
|
||||
import javafx.scene.layout.ColumnConstraints;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The endpoints of a project, each with a button for its WSDL, its SOAP version and a button to remove it.
|
||||
* Removing an endpoint keeps its WSDL. Downloading the WSDL selects the version it declares, if it does.
|
||||
*/
|
||||
public class EndpointsPane extends GridPane {
|
||||
private final Path projectPath;
|
||||
private final Map<String, Endpoint> endpoints;
|
||||
private final Runnable onSubmit;
|
||||
private final GridPane endpointsGrid;
|
||||
private final List<Row> rows = new ArrayList<>();
|
||||
|
||||
private record Row(TextField field, ToggleGroup versions) {
|
||||
SoapVersion version() {
|
||||
var selected = versions.getSelectedToggle();
|
||||
return selected == null ? SoapVersion.ONE_ONE : (SoapVersion) selected.getUserData();
|
||||
}
|
||||
|
||||
void select(SoapVersion version) {
|
||||
for (var toggle : versions.getToggles())
|
||||
if (toggle.getUserData() == version) versions.selectToggle(toggle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param endpoints kept equal to the non blank fields, stripped, with the version of their row.
|
||||
* @param onSubmit called when enter is pressed on any endpoint field, and when a version changes.
|
||||
*/
|
||||
public EndpointsPane(Path projectPath, Map<String, Endpoint> endpoints, Runnable onSubmit) {
|
||||
this.projectPath = projectPath;
|
||||
this.endpoints = endpoints;
|
||||
this.onSubmit = onSubmit;
|
||||
setVgap(8);
|
||||
|
||||
var column = new ColumnConstraints();
|
||||
column.setHgrow(Priority.ALWAYS);
|
||||
getColumnConstraints().add(column);
|
||||
|
||||
var title = new Label("Endpoints");
|
||||
Styles.addStyleClass(title, Styles.TITLE_2);
|
||||
add(title, 0, 0);
|
||||
|
||||
endpointsGrid = new GridPane();
|
||||
endpointsGrid.setHgap(4);
|
||||
endpointsGrid.setVgap(8);
|
||||
var fieldColumn = new ColumnConstraints();
|
||||
fieldColumn.setHgrow(Priority.ALWAYS);
|
||||
endpointsGrid.getColumnConstraints().add(fieldColumn);
|
||||
add(endpointsGrid, 0, 1);
|
||||
|
||||
var addButton = new Button("Agregar endpoint", FontIcon.of(MaterialDesignP.PLUS));
|
||||
addButton.setOnAction(e -> addRow("", SoapVersion.ONE_ONE).requestFocus());
|
||||
add(addButton, 0, 2);
|
||||
setHalignment(addButton, HPos.RIGHT);
|
||||
}
|
||||
|
||||
public void update() {
|
||||
endpointsGrid.getChildren().clear();
|
||||
rows.clear();
|
||||
for (var endpoint : List.copyOf(endpoints.entrySet()))
|
||||
addRow(endpoint.getKey(), endpoint.getValue().getVersion());
|
||||
if (endpoints.isEmpty())
|
||||
addRow("", SoapVersion.ONE_ONE);
|
||||
}
|
||||
|
||||
private TextField addRow(String endpoint, SoapVersion version) {
|
||||
var row = endpointsGrid.getRowCount();
|
||||
var field = new TextField(endpoint);
|
||||
field.setPromptText("http://host/servicio");
|
||||
field.setOnAction(e -> onSubmit.run());
|
||||
field.textProperty().addListener((obs, old, value) -> sync());
|
||||
var wsdl = new EndpointWsdl(projectPath, null, field);
|
||||
|
||||
var versionGroup = new ToggleGroup();
|
||||
var versions = new HBox(8);
|
||||
versions.setAlignment(Pos.CENTER_LEFT);
|
||||
for (var option : SoapVersion.values()) {
|
||||
var radio = new RadioButton("v" + option.getTitle());
|
||||
radio.setUserData(option);
|
||||
radio.setToggleGroup(versionGroup);
|
||||
radio.setSelected(option == version);
|
||||
versions.getChildren().add(radio);
|
||||
}
|
||||
var current = new Row(field, versionGroup);
|
||||
versionGroup.selectedToggleProperty().addListener((obs, old, selected) -> {
|
||||
if (selected == null) return;
|
||||
sync();
|
||||
onSubmit.run();
|
||||
});
|
||||
wsdl.setOnVersionDetected(current::select);
|
||||
|
||||
var removeButton = new Button("", FontIcon.of(MaterialDesignD.DELETE));
|
||||
List<Node> cells = List.of(field, wsdl.downloadButton(), versions, removeButton);
|
||||
for (int column = 0; column < cells.size(); column++)
|
||||
endpointsGrid.add(cells.get(column), column, row);
|
||||
rows.add(current);
|
||||
|
||||
removeButton.setOnAction(e -> {
|
||||
endpointsGrid.getChildren().removeAll(cells);
|
||||
rows.remove(current);
|
||||
sync();
|
||||
});
|
||||
return field;
|
||||
}
|
||||
|
||||
private void sync() {
|
||||
endpoints.clear();
|
||||
for (var row : rows) {
|
||||
var text = row.field().getText();
|
||||
if (text != null && ! text.isBlank()) endpoints.put(text.strip(), new Endpoint(row.version()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
import atlantafx.base.theme.Styles;
|
||||
import javafx.geometry.HPos;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.Separator;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.ColumnConstraints;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.layout.Priority;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class HeadersPane extends GridPane {
|
||||
GridPane headersGrid;
|
||||
Map<String, String> headers = Map.of();
|
||||
Map<String, String> inherited = Map.of();
|
||||
private final Runnable onSubmit;
|
||||
|
||||
/**
|
||||
* @param onSubmit called when enter is pressed on any header field.
|
||||
*/
|
||||
public HeadersPane(Map<String, String> headers, Runnable onSubmit) {
|
||||
this.headers = headers;
|
||||
this.onSubmit = onSubmit;
|
||||
setVgap(8);
|
||||
|
||||
setPadding(new Insets(0));
|
||||
getColumnConstraints().addAll(growing(), new ColumnConstraints());
|
||||
|
||||
var title = new Label("HTTP headers");
|
||||
add(title, 0, 0);
|
||||
Styles.addStyleClass(title, Styles.TITLE_2);
|
||||
|
||||
headersGrid = new GridPane();
|
||||
headersGrid.setHgap(4);
|
||||
headersGrid.setVgap(8);
|
||||
// Key and value share the width; the remove button keeps its own.
|
||||
headersGrid.getColumnConstraints().addAll(growing(), growing(), new ColumnConstraints());
|
||||
add(headersGrid, 0, 1);
|
||||
setColumnSpan(headersGrid, 2);
|
||||
|
||||
var addHeaderBtn = new Button("Agregar header", FontIcon.of(MaterialDesignP.PLUS));
|
||||
addHeaderBtn.setOnAction(e->addEmpty());
|
||||
add(addHeaderBtn, 1, 2);
|
||||
addHeaderBtn.setAlignment(Pos.CENTER_RIGHT);
|
||||
setHalignment(addHeaderBtn, HPos.RIGHT);
|
||||
}
|
||||
|
||||
private static ColumnConstraints growing() {
|
||||
var column = new ColumnConstraints();
|
||||
column.setHgrow(Priority.ALWAYS);
|
||||
return column;
|
||||
}
|
||||
|
||||
public void update() {
|
||||
headersGrid.getChildren().clear();
|
||||
if (headers.isEmpty()) {
|
||||
headers.put("", "");
|
||||
}
|
||||
|
||||
var row = 0;
|
||||
for (var inherited: inherited.entrySet()) {
|
||||
var key = inherited.getKey();
|
||||
var value = inherited.getValue();
|
||||
var keyLabel = new Label(key);
|
||||
var valueLabel = new Label(value);
|
||||
headersGrid.add(keyLabel, 0, row);
|
||||
headersGrid.add(valueLabel, 1, row);
|
||||
Styles.addStyleClass(keyLabel, Styles.TEXT_SUBTLE);
|
||||
Styles.addStyleClass(valueLabel, Styles.TEXT_SUBTLE);
|
||||
row++;
|
||||
}
|
||||
|
||||
for (var header: headers.entrySet()) {
|
||||
var key = header.getKey();
|
||||
var value = header.getValue();
|
||||
var keyField = new TextField(key);
|
||||
var valueField = new TextField(value);
|
||||
var removeBtn = new Button("",FontIcon.of(MaterialDesignD.DELETE));
|
||||
|
||||
keyField.setPromptText("llave");
|
||||
valueField.setPromptText("valor");
|
||||
keyField.setOnAction(e -> onSubmit.run());
|
||||
valueField.setOnAction(e -> onSubmit.run());
|
||||
|
||||
headersGrid.add(keyField, 0, row);
|
||||
headersGrid.add(valueField, 1, row);
|
||||
headersGrid.add(removeBtn, 2, row);
|
||||
|
||||
keyField.textProperty().addListener(
|
||||
(obs, oldKey, newKey) -> replaceHeader(oldKey, newKey)
|
||||
);
|
||||
valueField.textProperty().addListener(
|
||||
(a, b, newValue) -> headers.put(keyField.getText(), newValue)
|
||||
);
|
||||
removeBtn.setOnAction(e->{
|
||||
headers.remove(keyField.getText());
|
||||
headersGrid.getChildren().removeAll(keyField, valueField, removeBtn);
|
||||
});
|
||||
|
||||
row++;
|
||||
}
|
||||
}
|
||||
|
||||
private void addEmpty() {
|
||||
var row = headersGrid.getRowCount();
|
||||
var keyField = new TextField();
|
||||
var valueField = new TextField();
|
||||
var removeBtn = new Button("",FontIcon.of(MaterialDesignD.DELETE));
|
||||
|
||||
keyField.setPromptText("llave");
|
||||
valueField.setPromptText("valor");
|
||||
keyField.setOnAction(e -> onSubmit.run());
|
||||
valueField.setOnAction(e -> onSubmit.run());
|
||||
|
||||
headersGrid.add(keyField, 0, row);
|
||||
headersGrid.add(valueField, 1, row);
|
||||
headersGrid.add(removeBtn, 2, row);
|
||||
|
||||
keyField.textProperty().addListener(
|
||||
(obs, oldKey, newKey) -> replaceHeader(oldKey, newKey)
|
||||
);
|
||||
valueField.textProperty().addListener(
|
||||
(a, b, newValue) -> headers.put(keyField.getText(), newValue)
|
||||
);
|
||||
removeBtn.setOnAction(e->{
|
||||
headers.remove(keyField.getText());
|
||||
headersGrid.getChildren().removeAll(keyField, valueField, removeBtn);
|
||||
});
|
||||
}
|
||||
|
||||
private void replaceHeader(String oldKey, String newKey) {
|
||||
String value = "";
|
||||
|
||||
if (! oldKey.isBlank()) {
|
||||
value = headers.remove(oldKey);
|
||||
}
|
||||
|
||||
if (newKey.isBlank())
|
||||
return;
|
||||
|
||||
headers.put(newKey, value);
|
||||
}
|
||||
|
||||
public void updateInherited(Map<String, String> inherited) {
|
||||
this.inherited = inherited;
|
||||
update();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
import atlantafx.base.controls.Spacer;
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.data.yaml.Project;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
|
||||
public class ProjectEditorPane extends BorderPane implements Destroyable {
|
||||
Label title;
|
||||
TextField nameField;
|
||||
EndpointsPane endpointsPane;
|
||||
HeadersPane headersPane;
|
||||
|
||||
public ProjectEditorPane(Path projectPath, Project project) {
|
||||
Runnable submit = ()-> ProjectService.write(projectPath, project);
|
||||
|
||||
var top = new VBox(8);
|
||||
setTop(top);
|
||||
|
||||
title = new Label("Proyecto ?");
|
||||
Styles.addStyleClass(title, Styles.TITLE_1);
|
||||
top.getChildren().add(title);
|
||||
|
||||
var fields = new GridPane();
|
||||
fields.setVgap(8);
|
||||
fields.setHgap(16);
|
||||
var fieldColumn = new ColumnConstraints();
|
||||
fieldColumn.setHgrow(Priority.ALWAYS);
|
||||
fields.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn);
|
||||
top.getChildren().add(fields);
|
||||
var row = 0;
|
||||
|
||||
nameField = new TextField("");
|
||||
nameField.textProperty().addListener((obs, old, value) -> project.setName(value));
|
||||
nameField.setOnAction(e -> submit.run());
|
||||
fields.add(new Label("Nombre:"), 0, row);
|
||||
fields.add(nameField, 1, row);
|
||||
row++;
|
||||
|
||||
endpointsPane = new EndpointsPane(projectPath, project.getEndpoints(), submit);
|
||||
VBox.setMargin(endpointsPane, new Insets(8, 0, 0, 0));
|
||||
top.getChildren().add(endpointsPane);
|
||||
|
||||
headersPane = new HeadersPane(project.getHeaders(), submit);
|
||||
setMargin(headersPane, new Insets(8, 0, 8, 0));
|
||||
setCenter(headersPane);
|
||||
|
||||
var bottom = new VBox(8);
|
||||
setBottom(bottom);
|
||||
bottom.getChildren().add(new Separator());
|
||||
|
||||
var actions = new HBox(8);
|
||||
bottom.getChildren().add(actions);
|
||||
actions.getChildren().add(new Spacer());
|
||||
|
||||
var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE));
|
||||
save.setOnAction(e-> submit.run());
|
||||
actions.getChildren().add(save);
|
||||
|
||||
loadProject(project);
|
||||
}
|
||||
|
||||
private void loadProject(Project project) {
|
||||
title.setText("Proyecto %s".formatted(project.getName()));
|
||||
nameField.setText(project.getName());
|
||||
endpointsPane.update();
|
||||
headersPane.update();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.molnarandrei.sopa.ui.editor;
|
||||
|
||||
import atlantafx.base.controls.Spacer;
|
||||
import atlantafx.base.controls.ToggleSwitch;
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import com.molnarandrei.sopa.events.EventListeners;
|
||||
import com.molnarandrei.sopa.events.SopaEvent;
|
||||
import com.molnarandrei.sopa.events.UiEvent;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
|
||||
public class TestCaseEditorPane extends BorderPane implements Destroyable {
|
||||
|
||||
Label title;
|
||||
TextField nameField;
|
||||
ToggleSwitch activeToggle;
|
||||
TextField endpointField;
|
||||
TextField actionField;
|
||||
HeadersPane headersPane;
|
||||
EndpointWsdl wsdl;
|
||||
private final EventListeners listeners = new EventListeners();
|
||||
|
||||
public TestCaseEditorPane(Path testCasePath, TestCase testCase) {
|
||||
Runnable submit = ()-> TestCaseService.write(testCasePath, testCase);
|
||||
var projectPath = testCasePath.getParent().getParent().resolve("project.yml");
|
||||
|
||||
var top = new VBox(8);
|
||||
setTop(top);
|
||||
|
||||
title = new Label("Caso ?");
|
||||
Styles.addStyleClass(title, Styles.TITLE_1);
|
||||
top.getChildren().add(title);
|
||||
|
||||
var fields = new GridPane();
|
||||
fields.setVgap(8);
|
||||
fields.setHgap(16);
|
||||
var fieldColumn = new ColumnConstraints();
|
||||
fieldColumn.setHgrow(Priority.ALWAYS);
|
||||
fields.getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn);
|
||||
top.getChildren().add(fields);
|
||||
var row = 0;
|
||||
|
||||
fields.add(new Label("Nombre:"), 0, row);
|
||||
nameField = new TextField("");
|
||||
nameField.textProperty().addListener((obs, old, value) -> testCase.setName(value));
|
||||
nameField.setOnAction(e -> submit.run());
|
||||
fields.add(nameField, 1, row);
|
||||
row++;
|
||||
|
||||
fields.add(new Label("Endpoint:"), 0, row);
|
||||
endpointField = new TextField("");
|
||||
endpointField.textProperty().addListener((obs, old, value) -> testCase.setEndpoint(value));
|
||||
endpointField.setOnAction(e -> submit.run());
|
||||
fields.add(endpointField, 1, row);
|
||||
wsdl = new EndpointWsdl(projectPath, testCasePath, endpointField);
|
||||
fields.add(wsdl.selectEndpointButton(), 2, row);
|
||||
row++;
|
||||
|
||||
fields.add(new Label("Accion:"), 0, row);
|
||||
actionField = new TextField("");
|
||||
actionField.textProperty().addListener((obs, old, value) -> testCase.setAction(value));
|
||||
actionField.setOnAction(e -> submit.run());
|
||||
fields.add(actionField, 1, row);
|
||||
fields.add(wsdl.selectActionButton(testCasePath), 2, row);
|
||||
row++;
|
||||
|
||||
headersPane = new HeadersPane(testCase.getHeaders(), submit);
|
||||
setMargin(headersPane, new Insets(8, 0, 8, 0));
|
||||
setCenter(headersPane);
|
||||
|
||||
var bottom = new VBox(8);
|
||||
setBottom(bottom);
|
||||
bottom.getChildren().add(new Separator());
|
||||
|
||||
var actions = new HBox();
|
||||
bottom.getChildren().add(actions);
|
||||
|
||||
activeToggle = new ToggleSwitch("Activo");
|
||||
activeToggle.selectedProperty().addListener((obs, old, value)-> testCase.setActive(value));
|
||||
actions.getChildren().add(activeToggle);
|
||||
|
||||
actions.getChildren().add(new Spacer());
|
||||
|
||||
var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE));
|
||||
save.setOnAction(e-> submit.run());
|
||||
actions.getChildren().add(save);
|
||||
|
||||
loadTestCase(testCase);
|
||||
loadParent(projectPath);
|
||||
|
||||
listeners.on(UiEvent.ACTION_SELECTED, event -> onActionSelected(testCasePath, event));
|
||||
listeners.addAll();
|
||||
}
|
||||
|
||||
private void onActionSelected(Path testCasePath, SopaEvent<Object> event) {
|
||||
if (event.get() instanceof UiEvent.ActionSelection selection && selection.path().equals(testCasePath))
|
||||
actionField.setText(selection.soapAction());
|
||||
}
|
||||
|
||||
private void loadTestCase(TestCase testCase) {
|
||||
title.setText("Caso %s".formatted(testCase.getName()));
|
||||
activeToggle.setSelected(testCase.isActive());
|
||||
nameField.setText(testCase.getName());
|
||||
endpointField.setText(testCase.getEndpoint());
|
||||
actionField.setText(testCase.getAction());
|
||||
headersPane.update();
|
||||
}
|
||||
|
||||
private void loadParent(Path projectPath) {
|
||||
var project = ProjectService.read(projectPath);
|
||||
if (project == null) return;
|
||||
headersPane.updateInherited(project.getHeaders());
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
listeners.removeAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.molnarandrei.sopa.ui.editor.step;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.events.EventListeners;
|
||||
import com.molnarandrei.sopa.events.SopaEvent;
|
||||
import com.molnarandrei.sopa.events.UiEvent;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import com.molnarandrei.sopa.ui.editor.Destroyable;
|
||||
import com.molnarandrei.sopa.ui.editor.EndpointWsdl;
|
||||
import com.molnarandrei.sopa.ui.editor.HeadersPane;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.layout.ColumnConstraints;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.layout.Priority;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class CallDetailsPane extends GridPane implements Destroyable {
|
||||
|
||||
TextField nameField;
|
||||
TextField endpointField;
|
||||
TextField actionField;
|
||||
HeadersPane headersPane;
|
||||
EndpointWsdl wsdl;
|
||||
private final EventListeners listeners = new EventListeners();
|
||||
|
||||
public CallDetailsPane(Path stepPath, Step step, Runnable onSubmit) {
|
||||
setVgap(8);
|
||||
setHgap(16);
|
||||
var fieldColumn = new ColumnConstraints();
|
||||
fieldColumn.setHgrow(Priority.ALWAYS);
|
||||
getColumnConstraints().addAll(new ColumnConstraints(), fieldColumn, new ColumnConstraints());
|
||||
|
||||
var row = 0;
|
||||
add(new Label("Nombre:"), 0, row);
|
||||
nameField = new TextField("");
|
||||
nameField.textProperty().addListener((obs, old, value) -> step.setName(value));
|
||||
nameField.setOnAction(e -> onSubmit.run());
|
||||
add(nameField, 1, row, 2, 1);
|
||||
row++;
|
||||
|
||||
add(new Label("Endpoint:"), 0, row);
|
||||
endpointField = new TextField("");
|
||||
endpointField.textProperty().addListener((obs, old, value) -> step.setEndpoint(value));
|
||||
endpointField.setOnAction(e -> onSubmit.run());
|
||||
add(endpointField, 1, row);
|
||||
var projectPath = stepPath.getParent().getParent().getParent().resolve("project.yml");
|
||||
var testCasePath = stepPath.getParent().getParent().resolve("testcase.yml");
|
||||
wsdl = new EndpointWsdl(projectPath, testCasePath, endpointField);
|
||||
add(wsdl.selectEndpointButton(), 2, row);
|
||||
row++;
|
||||
|
||||
add(new Label("Accion:"), 0, row);
|
||||
actionField = new TextField("");
|
||||
actionField.textProperty().addListener((obs, old, value) -> step.setAction(value));
|
||||
actionField.setOnAction(e -> onSubmit.run());
|
||||
add(actionField, 1, row);
|
||||
add(wsdl.selectActionButton(stepPath), 2, row);
|
||||
row++;
|
||||
|
||||
headersPane = new HeadersPane(step.getHeaders(), onSubmit);
|
||||
add(headersPane, 0, row);
|
||||
GridPane.setColumnSpan(headersPane, 3);
|
||||
row++;
|
||||
|
||||
loadStep(step);
|
||||
loadParent(stepPath);
|
||||
|
||||
listeners.on(UiEvent.ACTION_SELECTED, event -> onActionSelected(stepPath, event));
|
||||
listeners.addAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
listeners.removeAll();
|
||||
}
|
||||
|
||||
private void onActionSelected(Path stepPath, SopaEvent<Object> event) {
|
||||
if (event.get() instanceof UiEvent.ActionSelection selection && selection.path().equals(stepPath))
|
||||
actionField.setText(selection.soapAction());
|
||||
}
|
||||
|
||||
public void loadStep(Step step) {
|
||||
nameField.setText(step.getName());
|
||||
endpointField.setText(step.getEndpoint());
|
||||
actionField.setText(step.getAction());
|
||||
headersPane.update();
|
||||
}
|
||||
|
||||
private void loadParent(Path stepPath) {
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
var project = ProjectService.read(projectPath);
|
||||
var inheritedHeaders = new HashMap<String, String>();
|
||||
if (project != null) {
|
||||
inheritedHeaders.putAll(project.getHeaders());
|
||||
}
|
||||
|
||||
var testCasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
var testCase = TestCaseService.read(testCasePath);
|
||||
if (testCase != null) {
|
||||
var endpoint = testCase.getEndpoint();
|
||||
if (null != endpoint && !endpoint.isBlank()) {
|
||||
endpointField.setPromptText(endpoint);
|
||||
}
|
||||
var action = testCase.getAction();
|
||||
if (null != action && !action.isBlank()) {
|
||||
actionField.setPromptText(action);
|
||||
}
|
||||
inheritedHeaders.putAll(testCase.getHeaders());
|
||||
}
|
||||
|
||||
headersPane.updateInherited(inheritedHeaders);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.molnarandrei.sopa.ui.editor.step;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.CallLog;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ResponseEvent;
|
||||
import com.molnarandrei.sopa.calllog.CallLogService;
|
||||
import com.molnarandrei.sopa.ui.lib.XmlArea;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.Tab;
|
||||
import javafx.scene.control.TabPane;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CallLogPane extends TabPane {
|
||||
public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss.SSS");
|
||||
private static final Comparator<Tab> TAB_ORDER = Comparator.comparing(Tab::getText);
|
||||
private Path stepPath;
|
||||
private Map<Path, Tab> tabsByPath = new HashMap<>();
|
||||
|
||||
// Kept as fields: a method reference creates a new handler on each evaluation, so
|
||||
// the same instance must be passed to removeListener.
|
||||
private final EventHandler<ResponseEvent> responseAddedHandler = this::onResponseAdded;
|
||||
private final EventHandler<ResponseEvent> responseRemovedHandler = this::onResponseRemoved;
|
||||
|
||||
public CallLogPane(Path stepPath) {
|
||||
this.stepPath = stepPath;
|
||||
var responses = CallLogService.readAll(stepPath);
|
||||
if (responses == null) return;
|
||||
|
||||
var tabs = new ArrayList<Tab>();
|
||||
for (var responseByPath : responses.entrySet())
|
||||
tabs.add(toTab(responseByPath.getKey(), responseByPath.getValue()));
|
||||
tabs.sort(TAB_ORDER);
|
||||
getTabs().setAll(tabs);
|
||||
selectRightmost();
|
||||
|
||||
Events.addListener(ResponseEvent.ADDED, responseAddedHandler);
|
||||
Events.addListener(ResponseEvent.REMOVED, responseRemovedHandler);
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
Events.removeListener(ResponseEvent.ADDED, responseAddedHandler);
|
||||
Events.removeListener(ResponseEvent.REMOVED, responseRemovedHandler);
|
||||
}
|
||||
|
||||
private Tab toTab(Path path, CallLog callLog) {
|
||||
var tab = new Tab();
|
||||
tabsByPath.put(path, tab);
|
||||
tab.setText(callLog.getTime().format(formatter));
|
||||
tab.setOnClosed(e->{
|
||||
CallLogService.delete(path);
|
||||
});
|
||||
|
||||
var body = new XmlArea();
|
||||
body.setXml(callLog.getBody());
|
||||
body.setPadding(new Insets(4,4,4,4));
|
||||
body.setMinWidth(100d);
|
||||
tab.setContent(body);
|
||||
|
||||
return tab;
|
||||
}
|
||||
|
||||
private void onResponseAdded(ResponseEvent event) {
|
||||
var responsePath = event.get();
|
||||
if (! responsePath.startsWith( stepPath.getParent() )) return;
|
||||
|
||||
var existing = tabsByPath.get(responsePath);
|
||||
if (existing != null && getTabs().contains(existing)) {
|
||||
getSelectionModel().select(existing);
|
||||
return;
|
||||
}
|
||||
|
||||
var response = CallLogService.read(responsePath);
|
||||
if (response == null) return;
|
||||
|
||||
insertSorted(toTab(responsePath, response));
|
||||
selectRightmost();
|
||||
}
|
||||
|
||||
private void onResponseRemoved(ResponseEvent event) {
|
||||
var removed = tabsByPath.remove(event.get());
|
||||
if (removed == null) return;
|
||||
|
||||
var selected = getSelectionModel().getSelectedItem();
|
||||
getTabs().remove(removed);
|
||||
|
||||
if (selected == null || selected == removed)
|
||||
selectRightmost();
|
||||
else
|
||||
getSelectionModel().select(selected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts at the sorted position instead of sorting the list afterwards: sorting fires a
|
||||
* permutation change, which TabPane's selection model doesn't resync on, leaving a stale
|
||||
* selected index and multiple tabs flagged as selected.
|
||||
*/
|
||||
private void insertSorted(Tab tab) {
|
||||
var tabs = getTabs();
|
||||
int index = Collections.binarySearch(tabs, tab, TAB_ORDER);
|
||||
tabs.add(index < 0 ? -index - 1 : index, tab);
|
||||
}
|
||||
|
||||
private void selectRightmost() {
|
||||
if (!getTabs().isEmpty())
|
||||
getSelectionModel().selectLast();
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package com.molnarandrei.sopa.ui.editor.step;
|
||||
|
||||
import atlantafx.base.controls.Spacer;
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.data.yaml.Assertion;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
public class StepAssertionsExtractionsPane extends SplitPane {
|
||||
private static final Set<Assertion.Type> WITHOUT_EXPRESSION = Set.of(
|
||||
Assertion.Type.httpStatus, Assertion.Type.contains,
|
||||
Assertion.Type.validPerWsdl, Assertion.Type.notSoapFault, Assertion.Type.soapFault
|
||||
);
|
||||
private static final Set<Assertion.Type> WITHOUT_VALUE = Set.of(
|
||||
Assertion.Type.validPerWsdl, Assertion.Type.notSoapFault
|
||||
);
|
||||
|
||||
private final Path stepPath;
|
||||
private final Step step;
|
||||
|
||||
private final GridPane assertionsGrid;
|
||||
private final GridPane extractionsGrid;
|
||||
private final List<ExtractionRow> extractionRows = new ArrayList<>();
|
||||
|
||||
private record ExtractionRow(TextField name, TextField xPath) {}
|
||||
|
||||
public StepAssertionsExtractionsPane(Path stepPath, Step step) {
|
||||
this.stepPath = stepPath;
|
||||
this.step = step;
|
||||
|
||||
assertionsGrid = createGrid(
|
||||
new ColumnConstraints(),
|
||||
growing(45),
|
||||
growing(-1),
|
||||
new ColumnConstraints()
|
||||
);
|
||||
extractionsGrid = createGrid(
|
||||
growing(40),
|
||||
growing(-1),
|
||||
new ColumnConstraints()
|
||||
);
|
||||
|
||||
var addAssertion = new Button("Agregar aserción", FontIcon.of(MaterialDesignP.PLUS));
|
||||
addAssertion.setOnAction(e -> {
|
||||
var assertion = new Assertion();
|
||||
step.getAssertions().add(assertion);
|
||||
addAssertionRow(assertion);
|
||||
});
|
||||
|
||||
var addExtraction = new Button("Agregar extracción", FontIcon.of(MaterialDesignP.PLUS));
|
||||
addExtraction.setOnAction(e -> addExtractionRow("", ""));
|
||||
|
||||
getItems().addAll(
|
||||
section("Aserciones", assertionsGrid, addAssertion),
|
||||
section("Extracciones", extractionsGrid, addExtraction)
|
||||
);
|
||||
setDividerPosition(0, Config.get().getAssertionsExtractionsSplitPaneDividerPosition());
|
||||
getDividers().getFirst().positionProperty().addListener(
|
||||
(obs, old, value) -> Config.get().setAssertionsExtractionsSplitPaneDividerPosition(value.doubleValue())
|
||||
);
|
||||
|
||||
loadStep();
|
||||
}
|
||||
|
||||
private static ColumnConstraints growing(double percentWidth) {
|
||||
var column = new ColumnConstraints();
|
||||
column.setHgrow(Priority.ALWAYS);
|
||||
if (percentWidth > 0) column.setPercentWidth(percentWidth);
|
||||
return column;
|
||||
}
|
||||
|
||||
private static GridPane createGrid(ColumnConstraints... columns) {
|
||||
var grid = new GridPane();
|
||||
grid.setHgap(4);
|
||||
grid.setVgap(8);
|
||||
grid.getColumnConstraints().addAll(columns);
|
||||
return grid;
|
||||
}
|
||||
|
||||
private static VBox section(String title, GridPane grid, Button add) {
|
||||
var label = new Label(title);
|
||||
Styles.addStyleClass(label, Styles.TITLE_4);
|
||||
var header = new HBox(8, label, new Spacer(), add);
|
||||
header.setAlignment(Pos.CENTER_LEFT);
|
||||
var box = new VBox(8, header, grid);
|
||||
box.setPadding(new Insets(4, 8, 4, 8));
|
||||
return box;
|
||||
}
|
||||
|
||||
private void loadStep() {
|
||||
assertionsGrid.getChildren().clear();
|
||||
extractionsGrid.getChildren().clear();
|
||||
extractionRows.clear();
|
||||
step.getAssertions().forEach(this::addAssertionRow);
|
||||
new TreeMap<>(step.getExtractions()).forEach(this::addExtractionRow);
|
||||
}
|
||||
|
||||
private void save() {
|
||||
StepService.write(stepPath, step);
|
||||
}
|
||||
|
||||
private void addAssertionRow(Assertion assertion) {
|
||||
var typeBox = new ComboBox<Assertion.Type>();
|
||||
typeBox.getItems().addAll(Assertion.Type.values());
|
||||
typeBox.setValue(assertion.getType());
|
||||
|
||||
var expressionField = new TextField(assertion.getExpression());
|
||||
expressionField.setPromptText("expresión");
|
||||
expressionField.setDisable(WITHOUT_EXPRESSION.contains(assertion.getType()));
|
||||
expressionField.textProperty().addListener((obs, old, value) -> assertion.setExpression(value));
|
||||
expressionField.setOnAction(e -> save());
|
||||
|
||||
typeBox.valueProperty().addListener((obs, old, value) -> {
|
||||
assertion.setType(value);
|
||||
if (WITHOUT_EXPRESSION.contains(value)) expressionField.setText("");
|
||||
save();
|
||||
});
|
||||
|
||||
var valueField = new TextField(assertion.getValue());
|
||||
valueField.setPromptText(assertion.getType() == Assertion.Type.soapFault ? "código (opcional)" : "valor");
|
||||
valueField.setDisable(WITHOUT_VALUE.contains(assertion.getType()));
|
||||
valueField.textProperty().addListener((obs, old, value) -> assertion.setValue(value));
|
||||
valueField.setOnAction(e -> save());
|
||||
|
||||
var removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE));
|
||||
removeBtn.setOnAction(e -> {
|
||||
step.getAssertions().remove(assertion);
|
||||
assertionsGrid.getChildren().removeAll(typeBox, expressionField, valueField, removeBtn);
|
||||
});
|
||||
|
||||
var index = assertionsGrid.getRowCount();
|
||||
assertionsGrid.add(typeBox, 0, index);
|
||||
assertionsGrid.add(expressionField, 1, index);
|
||||
assertionsGrid.add(valueField, 2, index);
|
||||
assertionsGrid.add(removeBtn, 3, index);
|
||||
}
|
||||
|
||||
private void addExtractionRow(String name, String xPath) {
|
||||
var nameField = new TextField(name);
|
||||
nameField.setPromptText("propiedad");
|
||||
nameField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows());
|
||||
nameField.setOnAction(e -> save());
|
||||
|
||||
var xPathField = new TextField(xPath);
|
||||
xPathField.setPromptText("xpath");
|
||||
xPathField.textProperty().addListener((obs, old, value) -> rebuildExtractionsFromRows());
|
||||
xPathField.setOnAction(e -> save());
|
||||
|
||||
var removeBtn = new Button("", FontIcon.of(MaterialDesignD.DELETE));
|
||||
var row = new ExtractionRow(nameField, xPathField);
|
||||
removeBtn.setOnAction(e -> {
|
||||
extractionRows.remove(row);
|
||||
extractionsGrid.getChildren().removeAll(nameField, xPathField, removeBtn);
|
||||
rebuildExtractionsFromRows();
|
||||
});
|
||||
|
||||
var index = extractionsGrid.getRowCount();
|
||||
extractionsGrid.add(nameField, 0, index);
|
||||
extractionsGrid.add(xPathField, 1, index);
|
||||
extractionsGrid.add(removeBtn, 2, index);
|
||||
extractionRows.add(row);
|
||||
}
|
||||
|
||||
private void rebuildExtractionsFromRows() {
|
||||
var extractions = new LinkedHashMap<String, String>();
|
||||
for (var row : extractionRows) {
|
||||
var name = row.name().getText();
|
||||
if (name == null || name.isBlank()) continue;
|
||||
extractions.put(name.strip(), row.xPath().getText() == null ? "" : row.xPath().getText());
|
||||
}
|
||||
step.setExtractions(extractions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package com.molnarandrei.sopa.ui.editor.step;
|
||||
|
||||
import atlantafx.base.controls.Spacer;
|
||||
import atlantafx.base.controls.ToggleSwitch;
|
||||
import atlantafx.base.theme.Styles;
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.events.EventListeners;
|
||||
import com.molnarandrei.sopa.events.SopaEvent;
|
||||
import com.molnarandrei.sopa.events.UiEvent;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.soap.SoapService;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlService;
|
||||
import com.molnarandrei.sopa.ui.editor.Destroyable;
|
||||
import com.molnarandrei.sopa.ui.lib.XmlArea;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignS;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
public class StepEditorPane extends BorderPane implements Destroyable {
|
||||
private static final Logger log = Logger.getLogger(StepEditorPane.class.getName());
|
||||
private static final Map<Path, Boolean> wasDetailsExpanded = new HashMap<>();
|
||||
private static final Map<Path, Boolean> wasAssertionsExtractionsExpanded = new HashMap<>();
|
||||
|
||||
Label title;
|
||||
ToggleSwitch activeToggle;
|
||||
XmlArea payload;
|
||||
private final CallLogPane responses;
|
||||
private final CallDetailsPane details;
|
||||
private final EventListeners listeners = new EventListeners();
|
||||
|
||||
public StepEditorPane(Path stepPath, Step step) {
|
||||
var top = new VBox();
|
||||
setTop(top);
|
||||
|
||||
title = new Label("Paso ?");
|
||||
Styles.addStyleClass(title, Styles.TITLE_1);
|
||||
top.getChildren().add(title);
|
||||
|
||||
var detailsTitledPane = new TitledPane();
|
||||
detailsTitledPane.setText("Editar llamada");
|
||||
detailsTitledPane.setMaxWidth(Double.MAX_VALUE);
|
||||
detailsTitledPane.setExpanded(wasDetailsExpanded.getOrDefault(stepPath, false));
|
||||
detailsTitledPane.expandedProperty().addListener(
|
||||
(obs, old, value)-> wasDetailsExpanded.put(stepPath, value)
|
||||
);
|
||||
top.getChildren().add(detailsTitledPane);
|
||||
|
||||
details = new CallDetailsPane(stepPath, step, ()-> StepService.write(stepPath, step));
|
||||
detailsTitledPane.setContent(details);
|
||||
|
||||
var assertionsExtractionsTitledPane = new TitledPane();
|
||||
assertionsExtractionsTitledPane.setText("Aserciones y Extracciones");
|
||||
assertionsExtractionsTitledPane.setExpanded(wasAssertionsExtractionsExpanded.getOrDefault(stepPath, false));
|
||||
assertionsExtractionsTitledPane.expandedProperty().addListener(
|
||||
(obs, old, value)-> wasAssertionsExtractionsExpanded.put(stepPath, value)
|
||||
);
|
||||
top.getChildren().add(assertionsExtractionsTitledPane);
|
||||
|
||||
var assertionsExtractionsPane = new StepAssertionsExtractionsPane(stepPath, step);
|
||||
assertionsExtractionsTitledPane.setContent(assertionsExtractionsPane);
|
||||
|
||||
payload = new XmlArea();
|
||||
payload.setPadding(new Insets(4,4,4,4));
|
||||
payload.setMinHeight(300d);
|
||||
payload.setMinWidth(200d);
|
||||
payload.setXml("");
|
||||
payload.textProperty().addListener((obs, old, value)-> step.setPayload(value));
|
||||
|
||||
responses = new CallLogPane(stepPath);
|
||||
|
||||
var payloadAndResponses = new SplitPane();
|
||||
setMargin(payloadAndResponses, new Insets(8,0,8,0));
|
||||
payloadAndResponses.getItems().addAll(payload, responses);
|
||||
payloadAndResponses.setDividerPosition(0, Config.get().getResponseHistorySplitPaneDividerPosition());
|
||||
payloadAndResponses.getDividers().getFirst().positionProperty().addListener(
|
||||
(obs, old, value)-> Config.get().setResponseHistorySplitPaneDividerPosition(value.doubleValue())
|
||||
);
|
||||
setCenter(payloadAndResponses);
|
||||
|
||||
var bottom = new HBox();
|
||||
setBottom(bottom);
|
||||
|
||||
activeToggle = new ToggleSwitch("Activo");
|
||||
activeToggle.selectedProperty().addListener((obs, old, value)-> step.setActive(value));
|
||||
bottom.getChildren().add(activeToggle);
|
||||
|
||||
bottom.getChildren().add(new Spacer());
|
||||
|
||||
var save = new Button("Guardar cambios", FontIcon.of(MaterialDesignC.CONTENT_SAVE));
|
||||
save.setOnAction(e-> StepService.write(stepPath, step));
|
||||
bottom.getChildren().add(save);
|
||||
|
||||
var separation = new Spacer();
|
||||
separation.setMaxWidth(8);
|
||||
bottom.getChildren().add(separation);
|
||||
|
||||
var execute = new Button("Ejecutar", FontIcon.of(MaterialDesignS.SEND));
|
||||
execute.setOnAction(e-> {
|
||||
StepService.write(stepPath, step);
|
||||
SoapService.createAndStartCallForStep(stepPath);
|
||||
});
|
||||
Styles.addStyleClass(execute, Styles.ACCENT);
|
||||
bottom.getChildren().add(execute);
|
||||
|
||||
loadStep(step);
|
||||
|
||||
listeners.on(UiEvent.ACTION_SELECTED, event -> onActionSelected(stepPath, event));
|
||||
listeners.addAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
listeners.removeAll();
|
||||
details.destroy();
|
||||
responses.destroy();
|
||||
}
|
||||
|
||||
private void onActionSelected(Path stepPath, SopaEvent<Object> event) {
|
||||
if (! (event.get() instanceof UiEvent.ActionSelection selection) || ! selection.path().equals(stepPath))
|
||||
return;
|
||||
|
||||
fillPayloadWithExampleInBackground(selection, stepPath.getParent().getParent().getParent().resolve("project.yml"));
|
||||
}
|
||||
|
||||
private void fillPayloadWithExampleInBackground(UiEvent.ActionSelection selection, Path projectPath) {
|
||||
Thread.ofVirtual().start(() -> {
|
||||
var project = ProjectService.read(projectPath);
|
||||
if (project == null) return;
|
||||
try {
|
||||
var example = WsdlService.generateExample(selection.wsdl(), selection.object(), project.versionOf(selection.endpoint()));
|
||||
Platform.runLater(() -> payload.setXml(example));
|
||||
} catch (Exception cannotGenerate) {
|
||||
log.log(Level.WARNING, "Cannot generate example for %s".formatted(selection.object()), cannotGenerate);
|
||||
Utils.alert(
|
||||
"Fallo de WSDL",
|
||||
"No se ha podido generar un ejemplo para:\n%s".formatted(selection.object()),
|
||||
String.valueOf(cannotGenerate.getMessage())
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void loadStep(Step step) {
|
||||
title.setText("Paso %s".formatted(step.getName()));
|
||||
activeToggle.setSelected(step.isActive());
|
||||
payload.setXml(step.getPayload());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.molnarandrei.sopa.ui.lib;
|
||||
|
||||
import atlantafx.base.theme.Styles;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.geometry.Rectangle2D;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ScrollPane;
|
||||
import javafx.scene.control.Tooltip;
|
||||
import javafx.scene.layout.BorderPane;
|
||||
import javafx.scene.layout.Region;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.scene.robot.Robot;
|
||||
import javafx.stage.Modality;
|
||||
import javafx.stage.Screen;
|
||||
import javafx.stage.Stage;
|
||||
import javafx.stage.Window;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* A list of options around the mouse: picking one closes it.
|
||||
* It is as wide as its longest option, so none is cut, up to most of the screen; past that it scrolls.
|
||||
*/
|
||||
public class SelectDialog<T> extends Stage {
|
||||
private static final double MAX_HEIGHT = 500d;
|
||||
private static final double SCROLLBAR_WIDTH = 16d;
|
||||
private static final double MAX_SCREEN_FRACTION = 0.9d;
|
||||
/**
|
||||
* Sizes measured at their preferred value can still be short by rounding, more so on scaled screens:
|
||||
* the text is then cut, or a scrollbar shows that takes the room of the longest option.
|
||||
*/
|
||||
private static final double SLACK = 2d;
|
||||
|
||||
/**
|
||||
* @param tooltipOf the tooltip of an option, blank or null for none.
|
||||
*/
|
||||
public SelectDialog(
|
||||
Window owner, String title, String emptyText, List<T> options,
|
||||
Function<T, String> nameOf, Function<T, String> tooltipOf, Consumer<T> onSelect
|
||||
) {
|
||||
initOwner(owner);
|
||||
initModality(Modality.WINDOW_MODAL);
|
||||
setTitle(title);
|
||||
|
||||
var list = new VBox();
|
||||
list.setPadding(new Insets(4));
|
||||
for (var option : options)
|
||||
list.getChildren().add(createOption(nameOf.apply(option), tooltipOf.apply(option), () -> {
|
||||
onSelect.accept(option);
|
||||
close();
|
||||
}));
|
||||
if (options.isEmpty())
|
||||
list.getChildren().add(new Label(emptyText));
|
||||
|
||||
var scroll = new ScrollPane(list);
|
||||
scroll.setFitToWidth(true);
|
||||
|
||||
// A ScrollPane has no background: as the root of the scene, its white fill would show through.
|
||||
var root = new BorderPane(scroll);
|
||||
setScene(new Scene(root));
|
||||
packAroundMouse(root, scroll);
|
||||
// Sizes are only final once shown, with the stylesheets of the window applied.
|
||||
setOnShown(e -> packAroundMouse(root, scroll));
|
||||
}
|
||||
|
||||
private static Button createOption(String name, String tooltip, Runnable select) {
|
||||
// Never narrower than its text, with slack for rounding: otherwise long endpoints and actions are cut
|
||||
// with an ellipsis, even at their preferred width on scaled screens.
|
||||
var option = new Button(name) {
|
||||
@Override
|
||||
protected double computePrefWidth(double height) {
|
||||
return super.computePrefWidth(height) + SLACK;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected double computeMinWidth(double height) {
|
||||
return computePrefWidth(height);
|
||||
}
|
||||
};
|
||||
Styles.addStyleClass(option, Styles.FLAT);
|
||||
option.setMnemonicParsing(false);
|
||||
option.setMaxWidth(Double.MAX_VALUE);
|
||||
option.setAlignment(Pos.CENTER_LEFT);
|
||||
if (tooltip != null && ! tooltip.isBlank())
|
||||
option.setTooltip(new Tooltip(tooltip));
|
||||
option.setOnAction(e -> select.run());
|
||||
return option;
|
||||
}
|
||||
|
||||
private void packAroundMouse(BorderPane root, ScrollPane scroll) {
|
||||
root.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
|
||||
// Measured without scrollbars: they show only when the options do not fit.
|
||||
scroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
|
||||
scroll.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
|
||||
root.applyCss();
|
||||
root.layout();
|
||||
var bounds = screenOfMouse().getVisualBounds();
|
||||
var maxWidth = bounds.getWidth() * MAX_SCREEN_FRACTION;
|
||||
var maxHeight = Math.min(MAX_HEIGHT, bounds.getHeight() * MAX_SCREEN_FRACTION);
|
||||
|
||||
var contentWidth = root.prefWidth(-1) + SLACK;
|
||||
var contentHeight = root.prefHeight(-1) + SLACK;
|
||||
var scrollsDown = contentHeight > maxHeight;
|
||||
var scrollsAcross = contentWidth + (scrollsDown ? SCROLLBAR_WIDTH : 0) > maxWidth;
|
||||
// A horizontal scrollbar takes height, which can make the options scroll down too.
|
||||
scrollsDown = scrollsDown || (scrollsAcross && contentHeight + SCROLLBAR_WIDTH > maxHeight);
|
||||
|
||||
var width = Math.min(contentWidth + (scrollsDown ? SCROLLBAR_WIDTH : 0), maxWidth);
|
||||
var height = Math.min(contentHeight + (scrollsAcross ? SCROLLBAR_WIDTH : 0), maxHeight);
|
||||
scroll.setHbarPolicy(scrollsAcross ? ScrollPane.ScrollBarPolicy.AS_NEEDED : ScrollPane.ScrollBarPolicy.NEVER);
|
||||
scroll.setVbarPolicy(scrollsDown ? ScrollPane.ScrollBarPolicy.AS_NEEDED : ScrollPane.ScrollBarPolicy.NEVER);
|
||||
root.setPrefSize(width, height);
|
||||
setMaxHeight(maxHeight);
|
||||
sizeToScene();
|
||||
centerOnMouseInsideScreen(width, height, bounds);
|
||||
}
|
||||
|
||||
private static Screen screenOfMouse() {
|
||||
var mouse = new Robot().getMousePosition();
|
||||
var screens = Screen.getScreensForRectangle(new Rectangle2D(mouse.getX(), mouse.getY(), 1, 1));
|
||||
return screens.isEmpty() ? Screen.getPrimary() : screens.getFirst();
|
||||
}
|
||||
|
||||
private void centerOnMouseInsideScreen(double width, double height, Rectangle2D bounds) {
|
||||
var mouse = new Robot().getMousePosition();
|
||||
setX(clamp(mouse.getX() - width / 2, bounds.getMinX(), bounds.getMaxX() - width));
|
||||
setY(clamp(mouse.getY() - height / 2, bounds.getMinY(), bounds.getMaxY() - height));
|
||||
}
|
||||
|
||||
private static double clamp(double value, double min, double max) {
|
||||
return Math.max(min, Math.min(value, max));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package com.molnarandrei.sopa.ui.lib;
|
||||
|
||||
import org.fxmisc.richtext.CodeArea;
|
||||
import org.fxmisc.richtext.model.StyleSpans;
|
||||
import org.fxmisc.richtext.model.StyleSpansBuilder;
|
||||
import org.fxmisc.wellbehaved.event.InputMap;
|
||||
import org.fxmisc.wellbehaved.event.Nodes;
|
||||
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyCombination;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed;
|
||||
|
||||
public class XmlArea extends CodeArea {
|
||||
|
||||
// Regex matching comments, tag/closing names, attribute keys,
|
||||
// quote-delimited attribute values, and element body content.
|
||||
private static final Pattern XML_PATTERN = Pattern.compile(
|
||||
"(?<COMMENT><!--.*?-->)" +
|
||||
"|(?<CLOSINGTAG>(?<=</)[a-zA-Z_:][\\w.\\-:]*)" +
|
||||
"|(?<ELEMENT>(?<=<)[a-zA-Z_:][\\w.\\-:]*)" +
|
||||
"|(?<ATTRIBUTE>[a-zA-Z_:][\\w.\\-:]*)(?=\\s*=)" +
|
||||
"|(?<ATTRVALUE>\"(?<VALUE1>[^\"]*)\"|'(?<VALUE2>[^']*)')" +
|
||||
"|(?<BODYVALUE>(?<=>)[^<]+(?=</))",
|
||||
Pattern.DOTALL
|
||||
);
|
||||
|
||||
private static final String DEFAULT_TAB = " ";
|
||||
|
||||
private String tabString = null;
|
||||
|
||||
public XmlArea() {
|
||||
getStyleClass().add("code-area");
|
||||
Nodes.addInputMap(this, InputMap.sequence(
|
||||
InputMap.consume(keyPressed(KeyCode.TAB), e -> insertTab()),
|
||||
InputMap.consume(keyPressed(KeyCode.TAB, KeyCombination.SHIFT_DOWN), e -> shiftLines(true))
|
||||
));
|
||||
textProperty().addListener(
|
||||
(observable, oldText, newText) -> setStyleSpans(0, computeHighlighting(newText))
|
||||
);
|
||||
}
|
||||
|
||||
private static StyleSpans<Collection<String>> computeHighlighting(String text) {
|
||||
var matcher = XML_PATTERN.matcher(text);
|
||||
var lastKwEnd = 0;
|
||||
var spansBuilder = new StyleSpansBuilder<Collection<String>>();
|
||||
|
||||
while (matcher.find()) {
|
||||
// Unstyled gap prior to this match
|
||||
spansBuilder.add(Collections.emptyList(), matcher.start() - lastKwEnd);
|
||||
|
||||
if (matcher.group("COMMENT") != null) {
|
||||
spansBuilder.add(Collections.singleton("xml-comment"), matcher.end() - matcher.start());
|
||||
|
||||
} else if (matcher.group("CLOSINGTAG") != null) {
|
||||
// Matches "tag" inside </tag>, styled as tag element
|
||||
spansBuilder.add(Collections.singleton("xml-element"), matcher.end() - matcher.start());
|
||||
|
||||
} else if (matcher.group("ELEMENT") != null) {
|
||||
// Matches "tag" inside <tag ...> or <tag/>
|
||||
spansBuilder.add(Collections.singleton("xml-element"), matcher.end() - matcher.start());
|
||||
|
||||
} else if (matcher.group("ATTRIBUTE") != null) {
|
||||
spansBuilder.add(Collections.singleton("xml-attribute"), matcher.end() - matcher.start());
|
||||
|
||||
} else if (matcher.group("ATTRVALUE") != null) {
|
||||
int openingQuoteLen = 1;
|
||||
int closingQuoteLen = 1;
|
||||
int contentLen = (matcher.end() - matcher.start()) - openingQuoteLen - closingQuoteLen;
|
||||
|
||||
spansBuilder.add(Collections.emptyList(), openingQuoteLen);
|
||||
if (contentLen > 0) {
|
||||
spansBuilder.add(Collections.singleton("xml-value"), contentLen);
|
||||
}
|
||||
spansBuilder.add(Collections.emptyList(), closingQuoteLen);
|
||||
|
||||
} else if (matcher.group("BODYVALUE") != null) {
|
||||
// Tag content between > and </
|
||||
spansBuilder.add(Collections.singleton("xml-value"), matcher.end() - matcher.start());
|
||||
}
|
||||
|
||||
lastKwEnd = matcher.end();
|
||||
}
|
||||
|
||||
// Remaining unstyled text at end of file
|
||||
spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd);
|
||||
return spansBuilder.create();
|
||||
}
|
||||
|
||||
private String tab() {
|
||||
return tabString != null ? tabString : DEFAULT_TAB;
|
||||
}
|
||||
|
||||
private void insertTab() {
|
||||
if (getSelection().getLength() == 0)
|
||||
replaceSelection(tab());
|
||||
else
|
||||
shiftLines(false);
|
||||
}
|
||||
|
||||
/** Indents, or deindents once, every line touched by the selection, keeping the selection on the same text. */
|
||||
private void shiftLines(boolean deindent) {
|
||||
var tab = tab();
|
||||
var text = getText();
|
||||
var selection = getSelection();
|
||||
int start = selection.getStart();
|
||||
int end = selection.getEnd();
|
||||
// A selection ending right after a newline does not include the next line
|
||||
int last = end > start && text.charAt(end - 1) == '\n' ? end - 1 : end;
|
||||
int blockStart = text.lastIndexOf('\n', start - 1) + 1;
|
||||
int blockEnd = text.indexOf('\n', last);
|
||||
if (blockEnd < 0) blockEnd = text.length();
|
||||
|
||||
int anchor = getAnchor();
|
||||
int caret = getCaretPosition();
|
||||
int newAnchor = anchor;
|
||||
int newCaret = caret;
|
||||
var result = new StringBuilder();
|
||||
int lineStart = blockStart;
|
||||
for (var line : text.substring(blockStart, blockEnd).split("\n", -1)) {
|
||||
if (lineStart > blockStart) result.append('\n');
|
||||
if (deindent) {
|
||||
int removed = leadingIndent(line, tab.length());
|
||||
newAnchor -= Math.clamp(anchor - lineStart, 0, removed);
|
||||
newCaret -= Math.clamp(caret - lineStart, 0, removed);
|
||||
result.append(line, removed, line.length());
|
||||
} else {
|
||||
if (anchor > lineStart) newAnchor += tab.length();
|
||||
if (caret > lineStart) newCaret += tab.length();
|
||||
result.append(tab).append(line);
|
||||
}
|
||||
lineStart += line.length() + 1;
|
||||
}
|
||||
replaceText(blockStart, blockEnd, result.toString());
|
||||
selectRange(newAnchor, newCaret);
|
||||
}
|
||||
|
||||
/** Number of leading spaces/tabs to remove from line, at most max. */
|
||||
private static int leadingIndent(String line, int max) {
|
||||
int n = 0;
|
||||
while (n < max && n < line.length() && (line.charAt(n) == ' ' || line.charAt(n) == '\t')) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
public void setXml(String xml) {
|
||||
if (tabString == null)
|
||||
tabString = detectIndent(xml);
|
||||
replaceText(xml != null ? xml : "");
|
||||
moveTo(getLength());
|
||||
}
|
||||
|
||||
/** Returns the whitespace between the first newline and the following '<', or two spaces if none. */
|
||||
private static String detectIndent(String xml) {
|
||||
if (xml == null) return DEFAULT_TAB;
|
||||
int newline = xml.indexOf('\n');
|
||||
if (newline < 0) return DEFAULT_TAB;
|
||||
int tag = xml.indexOf('<', newline + 1);
|
||||
if (tag < 0) return DEFAULT_TAB;
|
||||
var indent = xml.substring(newline + 1, tag);
|
||||
return indent.isEmpty() || !indent.isBlank() ? DEFAULT_TAB : indent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package com.molnarandrei.sopa.ui.menu;
|
||||
|
||||
import com.molnarandrei.sopa.data.*;
|
||||
import com.molnarandrei.sopa.data.yaml.Config;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.ProjectTreeViewEvent;
|
||||
import com.molnarandrei.sopa.ui.PropertiesDialog;
|
||||
import com.molnarandrei.sopa.ui.create.CreateProjectDialog;
|
||||
import javafx.event.EventHandler;
|
||||
import javafx.geometry.Bounds;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.Region;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.stage.*;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignF;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class TopMenu extends MenuBar {
|
||||
private static final Logger log = Logger.getLogger(TopMenu.class.getName());
|
||||
|
||||
private Menu projectMenu;
|
||||
private Map<Path, MenuItem> projectHistoryMenuItemsByPath = new HashMap<>();
|
||||
|
||||
private final Menu separatorMenu;
|
||||
private final Menu propertiesMenu;
|
||||
private final Label propertiesLabel;
|
||||
private PropertiesDialog propertiesDialog;
|
||||
private Path selectedPath;
|
||||
private Kind selectedKind;
|
||||
private final EventHandler<ProjectTreeViewEvent> selectionHandler = this::onSelection;
|
||||
|
||||
public TopMenu() {
|
||||
projectMenu = new Menu(
|
||||
"Proyecto",
|
||||
FontIcon.of(MaterialDesignF.FOLDER)
|
||||
);
|
||||
projectMenu.setOnShown(e->updateProjectHistory());
|
||||
|
||||
var openProject = new MenuItem(
|
||||
"Abrir proyecto",
|
||||
FontIcon.of(MaterialDesignF.FOLDER_OPEN)
|
||||
);
|
||||
openProject.setOnAction((e)->openProject());
|
||||
|
||||
var createProject = new MenuItem(
|
||||
"Crear proyecto",
|
||||
FontIcon.of(MaterialDesignF.FOLDER_EDIT)
|
||||
);
|
||||
createProject.setOnAction((e)-> createProject());
|
||||
|
||||
projectMenu.getItems().addAll(
|
||||
openProject,
|
||||
createProject,
|
||||
new SeparatorMenuItem()
|
||||
);
|
||||
|
||||
// A Menu without items does not fire actions, so the clickable part is its graphic.
|
||||
propertiesLabel = new Label("Propiedades", FontIcon.of(MaterialDesignC.CHECKBOX_BLANK_OUTLINE));
|
||||
propertiesLabel.setOnMouseClicked(e -> toggleProperties());
|
||||
propertiesMenu = new Menu();
|
||||
propertiesMenu.setGraphic(propertiesLabel);
|
||||
|
||||
// MenuBar only holds Menus, so the spacer is an empty, disabled Menu whose button grows (see layoutChildren).
|
||||
separatorMenu = new Menu();
|
||||
separatorMenu.setDisable(true);
|
||||
|
||||
getMenus().addAll(
|
||||
projectMenu,
|
||||
separatorMenu,
|
||||
propertiesMenu
|
||||
);
|
||||
|
||||
Events.addListener(ProjectTreeViewEvent.SELECTED, selectionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* MenuBarSkin lays its menu buttons out in an HBox and recreates them when menus change,
|
||||
* so the spacer's button is made to grow on every layout pass. Guarded to avoid relayout loops.
|
||||
*/
|
||||
@Override
|
||||
protected void layoutChildren() {
|
||||
Node spacer = separatorMenu.getStyleableNode();
|
||||
if (spacer instanceof Region region) {
|
||||
if (HBox.getHgrow(region) != Priority.ALWAYS) HBox.setHgrow(region, Priority.ALWAYS);
|
||||
if (region.getMaxWidth() != Double.MAX_VALUE) region.setMaxWidth(Double.MAX_VALUE);
|
||||
}
|
||||
super.layoutChildren();
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
Events.removeListener(ProjectTreeViewEvent.SELECTED, selectionHandler);
|
||||
if (propertiesDialog != null) propertiesDialog.close();
|
||||
}
|
||||
|
||||
private void onSelection(ProjectTreeViewEvent event) {
|
||||
if (event.get() == null) return;
|
||||
selectedPath = event.get().path();
|
||||
selectedKind = event.get().kind();
|
||||
}
|
||||
|
||||
/** Opens the properties dialog, or closes it when already open; only one exists at a time. */
|
||||
private void toggleProperties() {
|
||||
if (propertiesDialog != null) {
|
||||
propertiesDialog.close(); // its hidden handler stores the config and clears the reference
|
||||
return;
|
||||
}
|
||||
propertiesDialog = new PropertiesDialog(
|
||||
getScene().getWindow(),
|
||||
propertiesButtonScreenBounds(),
|
||||
selectedPath,
|
||||
selectedKind,
|
||||
() -> {
|
||||
propertiesDialog = null;
|
||||
propertiesLabel.setGraphic(FontIcon.of(MaterialDesignC.CHECKBOX_BLANK_OUTLINE));
|
||||
}
|
||||
);
|
||||
propertiesLabel.setGraphic(FontIcon.of(MaterialDesignC.CHECKBOX_MARKED));
|
||||
propertiesDialog.show();
|
||||
}
|
||||
|
||||
private Bounds propertiesButtonScreenBounds() {
|
||||
Node button = propertiesMenu.getStyleableNode();
|
||||
if (button == null) button = propertiesLabel;
|
||||
return button.localToScreen(button.getBoundsInLocal());
|
||||
}
|
||||
|
||||
private void updateProjectHistory() {
|
||||
for (MenuItem item : projectHistoryMenuItemsByPath.values())
|
||||
projectMenu.getItems().remove(item);
|
||||
projectHistoryMenuItemsByPath.clear();
|
||||
for (var projectPath: Config.get().getProjectHistory()) {
|
||||
var menuItem = new MenuItem(
|
||||
projectPath.toString(),
|
||||
FontIcon.of(MaterialDesignF.FOLDER_CLOCK)
|
||||
);
|
||||
menuItem.setOnAction(e->{
|
||||
log.info("Loading history project %s".formatted(projectPath));
|
||||
ProjectService.open(projectPath);
|
||||
});
|
||||
projectMenu.getItems().add(menuItem);
|
||||
projectHistoryMenuItemsByPath.put(projectPath, menuItem);
|
||||
}
|
||||
}
|
||||
|
||||
private void openProject() {
|
||||
var chooser = new FileChooser();
|
||||
chooser.setTitle("Crear carpeta y abrir como proyecto");
|
||||
chooser.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("Ficheros de proyecto", "project.yml"));
|
||||
var projectFile = chooser.showOpenDialog(getScene().getWindow());
|
||||
if (projectFile == null) return;
|
||||
var project = projectFile.toPath();
|
||||
log.info("Opening project %s.".formatted(project));
|
||||
|
||||
ProjectService.open(project);
|
||||
}
|
||||
|
||||
private void createProject() {
|
||||
new CreateProjectDialog(getScene().getWindow()).show();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.molnarandrei.sopa.ui.navpane;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Testcase or step held by copy or cut. Nothing is read or erased until paste, so a paste
|
||||
* takes the contents the object has at that moment. Only touched on the FX thread.
|
||||
*/
|
||||
public class Clipboard {
|
||||
private static final Logger log = Logger.getLogger(Clipboard.class.getName());
|
||||
|
||||
private static TreeIdentity held;
|
||||
private static boolean heldIsCut;
|
||||
|
||||
public static void copy(TreeIdentity identity) {
|
||||
hold(identity, false);
|
||||
}
|
||||
|
||||
public static void cut(TreeIdentity identity) {
|
||||
hold(identity, true);
|
||||
}
|
||||
|
||||
private static void hold(TreeIdentity identity, boolean cut) {
|
||||
if (identity.kind() == Kind.project) {
|
||||
log.fine("Projects cannot be copied or cut: %s.".formatted(identity.path()));
|
||||
return;
|
||||
}
|
||||
log.info("%s %s %s.".formatted(cut? "Cut": "Copied", identity.kind(), identity.path()));
|
||||
held = identity;
|
||||
heldIsCut = cut;
|
||||
}
|
||||
|
||||
/** Whether pasting onto {@code target} would do something. */
|
||||
public static boolean canPaste(TreeIdentity target) {
|
||||
if (held == null || target == null) return false;
|
||||
if (! Files.exists(held.path())) return false;
|
||||
|
||||
return switch (held.kind()) {
|
||||
case step -> switch (target.kind()) {
|
||||
case project -> false;
|
||||
case testcase -> true;
|
||||
case step -> ! (heldIsCut && held.path().equals(target.path()));
|
||||
};
|
||||
case testcase -> ! (heldIsCut && projectDirectoryOf(held).equals(projectDirectoryOf(target)));
|
||||
case project -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public static void paste(TreeIdentity target) {
|
||||
if (held == null) return;
|
||||
var source = held;
|
||||
var cut = heldIsCut;
|
||||
if (! Files.exists(source.path())) {
|
||||
log.info("Held %s no longer exists, clearing clipboard: %s.".formatted(source.kind(), source.path()));
|
||||
held = null;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (source.kind()) {
|
||||
case step -> {
|
||||
switch (target.kind()) {
|
||||
case project -> log.fine("Steps cannot be pasted onto a project: %s.".formatted(target.path()));
|
||||
case testcase -> StepService.pasteOnTestCase(source.path(), target.path(), cut);
|
||||
case step -> StepService.pasteBelow(source.path(), target.path(), cut);
|
||||
}
|
||||
}
|
||||
case testcase -> TestCaseService.pasteOnProject(
|
||||
source.path(), projectDirectoryOf(target).resolve("project.yml"), cut
|
||||
);
|
||||
case project -> log.severe("Holding a project, which cannot be pasted: %s.".formatted(source.path()));
|
||||
}
|
||||
|
||||
// A pasted cut is gone from where it was cut, so there is nothing left to paste again.
|
||||
if (cut && ! Files.exists(source.path()))
|
||||
held = null;
|
||||
}
|
||||
|
||||
private static Path projectDirectoryOf(TreeIdentity identity) {
|
||||
return switch (identity.kind()) {
|
||||
case project -> identity.path().getParent();
|
||||
case testcase -> identity.path().getParent().getParent();
|
||||
case step -> identity.path().getParent().getParent().getParent();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.molnarandrei.sopa.ui.navpane;
|
||||
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import javafx.scene.control.Alert;
|
||||
import javafx.scene.control.ButtonBar;
|
||||
import javafx.scene.control.ButtonType;
|
||||
|
||||
/** Asks before deleting a project, testcase or step; the deletion can be undone with ctrl+z in the tree. */
|
||||
public class DeleteDialog {
|
||||
private static final ButtonType DELETE = new ButtonType("Eliminar", ButtonBar.ButtonData.OK_DONE);
|
||||
private static final ButtonType CANCEL = new ButtonType("Cancelar", ButtonBar.ButtonData.CANCEL_CLOSE);
|
||||
|
||||
public static void confirmAndDelete(TreeIdentity identity) {
|
||||
var alert = new Alert(Alert.AlertType.CONFIRMATION, "", DELETE, CANCEL);
|
||||
alert.setTitle("Eliminar");
|
||||
alert.setHeaderText("Seguro que desea eliminar el %s %s?".formatted(kindName(identity), nameOf(identity)));
|
||||
alert.setContentText(identity.path().getParent().toString());
|
||||
// Delete is the default: enter confirms what the delete key started, escape cancels.
|
||||
if (alert.showAndWait().orElse(CANCEL) == DELETE)
|
||||
switch (identity.kind()) {
|
||||
case project -> ProjectService.delete(identity.path());
|
||||
case testcase -> TestCaseService.delete(identity.path());
|
||||
case step -> StepService.delete(identity.path());
|
||||
}
|
||||
}
|
||||
|
||||
private static String kindName(TreeIdentity identity) {
|
||||
return switch (identity.kind()) {
|
||||
case project -> "proyecto";
|
||||
case testcase -> "caso de prueba";
|
||||
case step -> "paso";
|
||||
};
|
||||
}
|
||||
|
||||
private static String nameOf(TreeIdentity identity) {
|
||||
var path = identity.path();
|
||||
try {
|
||||
return switch (identity.kind()) {
|
||||
case project -> ProjectRepository.get(path).getName();
|
||||
case testcase -> TestCaseRepository.get(path).getName();
|
||||
case step -> StepRepository.get(path).getName();
|
||||
};
|
||||
} catch (Exception unreadable) {
|
||||
return path.getParent().getFileName().toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.molnarandrei.sopa.ui.navpane;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.CallLog;
|
||||
import org.kordamp.ikonli.Ikon;
|
||||
import org.kordamp.ikonli.material2.Material2OutlinedAL;
|
||||
import org.kordamp.ikonli.material2.Material2OutlinedMZ;
|
||||
|
||||
/** What the project tree shows next to a step about its SOAP call. */
|
||||
public enum FlightState {
|
||||
idle(Material2OutlinedMZ.RADIO_BUTTON_UNCHECKED, "idle"),
|
||||
inFlight(Material2OutlinedMZ.PLAY_CIRCLE_OUTLINE, "in-flight"),
|
||||
success(Material2OutlinedAL.CHECK_CIRCLE, "success"),
|
||||
failed(Material2OutlinedAL.CANCEL, "failed"),
|
||||
exception(Material2OutlinedAL.ERROR, "exception");
|
||||
|
||||
private final Ikon icon;
|
||||
private final String styleClass;
|
||||
|
||||
FlightState(Ikon icon, String styleClass) {
|
||||
this.icon = icon;
|
||||
this.styleClass = styleClass;
|
||||
}
|
||||
|
||||
public Ikon icon() {
|
||||
return icon;
|
||||
}
|
||||
|
||||
public String styleClass() {
|
||||
return styleClass;
|
||||
}
|
||||
|
||||
/** Logs written before results were recorded have no result and show as idle. */
|
||||
public static FlightState of(CallLog callLog) {
|
||||
if (callLog == null || callLog.getResult() == null) return idle;
|
||||
return switch (callLog.getResult()) {
|
||||
case success -> success;
|
||||
case exception -> exception;
|
||||
case assertionsFailed, extractionsFailed -> failed;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package com.molnarandrei.sopa.ui.navpane;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.events.*;
|
||||
import com.molnarandrei.sopa.calllog.CallLogService;
|
||||
import com.molnarandrei.sopa.trash.TrashService;
|
||||
import javafx.scene.control.Tooltip;
|
||||
import javafx.scene.control.TreeItem;
|
||||
import javafx.scene.control.TreeView;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.KeyCodeCombination;
|
||||
import javafx.scene.input.KeyCombination;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
import javafx.scene.layout.StackPane;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.molnarandrei.sopa.Utils.STEP_ORDER;
|
||||
|
||||
public class ProjectPane extends StackPane {
|
||||
private static final Logger log = Logger.getLogger(ProjectPane.class.getName());
|
||||
private final TreeItem<TreeIdentity> rootItem;
|
||||
private final TreeView<TreeIdentity> treeView;
|
||||
/** Steps without an entry are idle. Only touched on the FX thread. */
|
||||
private final Map<Path, FlightState> flightStates = new HashMap<>();
|
||||
|
||||
private static final KeyCombination COPY = new KeyCodeCombination(KeyCode.C, KeyCombination.SHORTCUT_DOWN);
|
||||
private static final KeyCombination CUT = new KeyCodeCombination(KeyCode.X, KeyCombination.SHORTCUT_DOWN);
|
||||
private static final KeyCombination PASTE = new KeyCodeCombination(KeyCode.V, KeyCombination.SHORTCUT_DOWN);
|
||||
private static final KeyCombination DELETE = new KeyCodeCombination(KeyCode.DELETE);
|
||||
private static final KeyCombination UNDO = new KeyCodeCombination(KeyCode.Z, KeyCombination.SHORTCUT_DOWN);
|
||||
|
||||
private final EventListeners listeners = new EventListeners()
|
||||
.on(ProjectEvent.ADDED, this::onProjectAdded)
|
||||
.on(ProjectEvent.REMOVED, this::onProjectRemoved)
|
||||
.on(ProjectEvent.CHANGED, this::onProjectChanged)
|
||||
.on(TestCaseEvent.ADDED, this::onTestCaseAdded)
|
||||
.on(TestCaseEvent.REMOVED, this::onTestCaseRemoved)
|
||||
.on(TestCaseEvent.CHANGED, this::onTestCaseChanged)
|
||||
.on(StepEvent.ADDED, this::onStepAdded)
|
||||
.on(StepEvent.REMOVED, this::onStepRemoved)
|
||||
.on(StepEvent.CHANGED, this::onStepChanged)
|
||||
.on(SoapJobEvent.STARTED, this::onJobStarted)
|
||||
.on(SoapCallEvent.STARTED, this::onCallStarted)
|
||||
.on(SoapCallEvent.FINISHED, this::onCallFinished);
|
||||
|
||||
public ProjectPane() {
|
||||
log.setLevel(Level.FINE);
|
||||
|
||||
rootItem = new TreeItem<>(null);
|
||||
treeView = new TreeView<>(rootItem);
|
||||
treeView.setShowRoot(false);
|
||||
treeView.setCellFactory(tv -> new SopaTreeCell(
|
||||
path -> flightStates.getOrDefault(path, FlightState.idle)
|
||||
));
|
||||
treeView.setTooltip(new Tooltip("Proyectos"));
|
||||
getChildren().add(treeView);
|
||||
|
||||
treeView.getSelectionModel().selectedItemProperty().addListener(
|
||||
(observable, oldItem, newItem) -> {
|
||||
if (newItem == null) return;
|
||||
var identity = newItem.getValue();
|
||||
log.info("Selected %s %s.".formatted(identity.kind(), identity.path()));
|
||||
Events.emit(new ProjectTreeViewEvent(ProjectTreeViewEvent.SELECTED, identity));
|
||||
});
|
||||
|
||||
treeView.addEventHandler(KeyEvent.KEY_PRESSED, this::onKeyPressed);
|
||||
|
||||
listeners.addAll();
|
||||
|
||||
// TODO when ctrl+n create testcase if project highlighted
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
listeners.removeAll();
|
||||
}
|
||||
|
||||
private void onKeyPressed(KeyEvent event) {
|
||||
if (UNDO.match(event)) {
|
||||
TrashService.undo();
|
||||
event.consume();
|
||||
return;
|
||||
}
|
||||
|
||||
var selectedCell = treeView.getSelectionModel().getSelectedItem();
|
||||
if (selectedCell == null || selectedCell.getValue() == null) return;
|
||||
var selected = selectedCell.getValue();
|
||||
|
||||
if (COPY.match(event)) Clipboard.copy(selected);
|
||||
else if (CUT.match(event)) Clipboard.cut(selected);
|
||||
else if (PASTE.match(event)) Clipboard.paste(selected);
|
||||
else if (DELETE.match(event)) DeleteDialog.confirmAndDelete(selected);
|
||||
else return;
|
||||
event.consume();
|
||||
}
|
||||
|
||||
/** Steps queued in the job lose their previous result until their own call runs. */
|
||||
private void onJobStarted(SoapJobEvent event) {
|
||||
for (var stepPath : event.get())
|
||||
setFlightState(stepPath, FlightState.idle);
|
||||
}
|
||||
|
||||
private void onCallStarted(SoapCallEvent event) {
|
||||
setFlightState(event.get().step(), FlightState.inFlight);
|
||||
}
|
||||
|
||||
private void onCallFinished(SoapCallEvent event) {
|
||||
var stepPath = event.get().step();
|
||||
setFlightState(stepPath, FlightState.of(CallLogService.readLatest(stepPath)));
|
||||
}
|
||||
|
||||
private void setFlightState(Path stepPath, FlightState state) {
|
||||
log.fine("Step %s is now %s.".formatted(stepPath, state));
|
||||
flightStates.put(stepPath, state);
|
||||
var stepCell = findStep(stepPath);
|
||||
if (stepCell == null) return;
|
||||
// A new identity instance makes the cell re-render with the new state.
|
||||
stepCell.setValue(new TreeIdentity(Kind.step, stepPath));
|
||||
}
|
||||
|
||||
private TreeItem<TreeIdentity> findStep(Path stepPath) {
|
||||
for (var projectCell : rootItem.getChildren())
|
||||
for (var testCaseCell : projectCell.getChildren()) {
|
||||
var stepCell = getChildByPath(testCaseCell, stepPath);
|
||||
if (stepCell != null) return stepCell;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void onProjectAdded(ProjectEvent event) {
|
||||
var projectPath = event.get();
|
||||
log.info("Adding project %s.".formatted(projectPath));
|
||||
getOrCreateProject(projectPath);
|
||||
}
|
||||
|
||||
private void onProjectRemoved(ProjectEvent event) {
|
||||
var projectPath = event.get();
|
||||
|
||||
log.info("Removing project %s.".formatted(projectPath));
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.fine("Project already removed: %s.".formatted(projectPath));
|
||||
return;
|
||||
}
|
||||
|
||||
rootItem.getChildren().remove(projectCell);
|
||||
}
|
||||
|
||||
private void onProjectChanged(ProjectEvent event) {
|
||||
var projectPath = event.get();
|
||||
|
||||
log.info("Updating project %s.".formatted(projectPath));
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.severe("Update project but not in tree %s.".formatted(projectPath));
|
||||
return;
|
||||
}
|
||||
|
||||
projectCell.setValue(new TreeIdentity(Kind.project, event.get()));
|
||||
}
|
||||
|
||||
private void onTestCaseAdded(TestCaseEvent event) {
|
||||
var projectPath = event.get().project();
|
||||
var testCasePath = event.get().testCase();
|
||||
|
||||
log.info("Adding testcase %s.".formatted(testCasePath));
|
||||
getOrCreateTestCase(getOrCreateProject(projectPath), testCasePath);
|
||||
}
|
||||
|
||||
private void onTestCaseRemoved(TestCaseEvent event) {
|
||||
var projectPath = event.get().project();
|
||||
var testCasePath = event.get().testCase();
|
||||
|
||||
log.info("Removing testcase %s.".formatted(testCasePath));
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.fine("Testcase already removed: %s.".formatted(testCasePath));
|
||||
return;
|
||||
}
|
||||
var testCaseCell = getChildByPath(projectCell, testCasePath);
|
||||
if (testCaseCell == null) {
|
||||
log.fine("Testcase already removed: %s.".formatted(testCasePath));
|
||||
return;
|
||||
}
|
||||
|
||||
projectCell.getChildren().remove(testCaseCell);
|
||||
}
|
||||
|
||||
private void onTestCaseChanged(TestCaseEvent event) {
|
||||
var projectPath = event.get().project();
|
||||
var testCasePath = event.get().testCase();
|
||||
|
||||
log.info("Updating testcase %s.".formatted(testCasePath));
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.severe("Update testcase for project not in tree %s.".formatted(projectPath));
|
||||
return;
|
||||
}
|
||||
var testCaseCell = getChildByPath(projectCell, testCasePath);
|
||||
if (testCaseCell == null) {
|
||||
log.severe("Update testcase not in tree %s.".formatted(testCasePath));
|
||||
return;
|
||||
}
|
||||
|
||||
testCaseCell.setValue(new TreeIdentity(Kind.testcase, testCasePath));
|
||||
}
|
||||
|
||||
private void onStepAdded(StepEvent event) {
|
||||
var projectPath = event.get().project();
|
||||
var testCasePath = event.get().testCase();
|
||||
var stepPath = event.get().step();
|
||||
|
||||
log.info("Adding step %s.".formatted(stepPath));
|
||||
var testCaseCell = getOrCreateTestCase(getOrCreateProject(projectPath), testCasePath);
|
||||
var stepCell = getChildByPath(testCaseCell, stepPath);
|
||||
if (stepCell != null) {
|
||||
log.fine("Step already present: %s.".formatted(stepPath));
|
||||
return;
|
||||
}
|
||||
|
||||
var treeItem = new TreeItem<>(new TreeIdentity(Kind.step, stepPath));
|
||||
treeItem.setExpanded(true);
|
||||
testCaseCell.getChildren().add(treeItem);
|
||||
|
||||
sortSteps(testCaseCell);
|
||||
}
|
||||
|
||||
private void onStepRemoved(StepEvent event) {
|
||||
var projectPath = event.get().project();
|
||||
var testCasePath = event.get().testCase();
|
||||
var stepPath = event.get().step();
|
||||
|
||||
log.info("Removing step %s.".formatted(stepPath));
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.fine("Step already removed: %s.".formatted(stepPath));
|
||||
return;
|
||||
}
|
||||
var testCaseCell = getChildByPath(projectCell, testCasePath);
|
||||
if (testCaseCell == null) {
|
||||
log.fine("Step already removed: %s.".formatted(stepPath));
|
||||
return;
|
||||
}
|
||||
var stepCell = getChildByPath(testCaseCell, stepPath);
|
||||
if (stepCell == null) {
|
||||
log.fine("Step already removed: %s.".formatted(stepPath));
|
||||
return;
|
||||
}
|
||||
|
||||
testCaseCell.getChildren().remove(stepCell);
|
||||
flightStates.remove(stepPath);
|
||||
if (testCaseCell.getChildren().isEmpty() && !Files.exists(testCasePath)) {
|
||||
log.fine("Removing placeholder testcase with no backing file: %s.".formatted(testCasePath));
|
||||
projectCell.getChildren().remove(testCaseCell);
|
||||
}
|
||||
|
||||
sortSteps(testCaseCell);
|
||||
}
|
||||
|
||||
private void onStepChanged(StepEvent event) {
|
||||
var projectPath = event.get().project();
|
||||
var testCasePath = event.get().testCase();
|
||||
var stepPath = event.get().step();
|
||||
|
||||
log.info("Updating step %s.".formatted(stepPath));
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.severe("Update step for project not in tree %s.".formatted(projectPath));
|
||||
return;
|
||||
}
|
||||
var testcaseCell = getChildByPath(projectCell, testCasePath);
|
||||
if (testcaseCell == null) {
|
||||
log.severe("Update step for testcase not in tree %s.".formatted(testCasePath));
|
||||
return;
|
||||
}
|
||||
var stepCell = getChildByPath(testcaseCell, stepPath);
|
||||
if (stepCell == null) {
|
||||
log.severe("Update step not in tree %s.".formatted(stepPath));
|
||||
return;
|
||||
}
|
||||
|
||||
stepCell.setValue(new TreeIdentity(Kind.step, event.get().step()));
|
||||
}
|
||||
|
||||
private TreeItem<TreeIdentity> getOrCreateProject(Path projectPath) {
|
||||
var projectCell = getChildByPath(rootItem, projectPath);
|
||||
if (projectCell == null) {
|
||||
log.fine("Creating placeholder project: %s.".formatted(projectPath));
|
||||
projectCell = new TreeItem<>(new TreeIdentity(Kind.project, projectPath));
|
||||
projectCell.setExpanded(true);
|
||||
rootItem.getChildren().add(projectCell);
|
||||
}
|
||||
return projectCell;
|
||||
}
|
||||
|
||||
private TreeItem<TreeIdentity> getOrCreateTestCase(TreeItem<TreeIdentity> project, Path testCasePath) {
|
||||
var testCaseCell = getChildByPath(project, testCasePath);
|
||||
if (testCaseCell == null) {
|
||||
log.fine("Creating placeholder testcase: %s.".formatted(testCasePath));
|
||||
testCaseCell = new TreeItem<>(new TreeIdentity(Kind.testcase, testCasePath));
|
||||
testCaseCell.setExpanded(true);
|
||||
project.getChildren().add(testCaseCell);
|
||||
}
|
||||
return testCaseCell;
|
||||
}
|
||||
|
||||
private TreeItem<TreeIdentity> getChildByPath(TreeItem<TreeIdentity> parent, Path seek) {
|
||||
return parent.getChildren().stream()
|
||||
.filter(item->item.getValue().path().equals(seek))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private void sortSteps(TreeItem<TreeIdentity> testCaseCell) {
|
||||
var selectedCell = treeView.getSelectionModel().getSelectedItem();
|
||||
testCaseCell.getChildren().sort((a, b) -> STEP_ORDER.compare(a.getValue().path(), b.getValue().path()));
|
||||
treeView.getSelectionModel().select(selectedCell);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.molnarandrei.sopa.ui.navpane;
|
||||
|
||||
import com.molnarandrei.sopa.data.*;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import com.molnarandrei.sopa.ui.navpane.context.ProjectContextMenu;
|
||||
import com.molnarandrei.sopa.ui.navpane.context.StepContextMenu;
|
||||
import com.molnarandrei.sopa.ui.navpane.context.TestCaseContextMenu;
|
||||
import javafx.scene.control.Tooltip;
|
||||
import javafx.scene.control.TreeCell;
|
||||
import javafx.scene.input.*;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SopaTreeCell extends TreeCell<TreeIdentity> {
|
||||
private static final Logger log = Logger.getLogger(SopaTreeCell.class.getName());
|
||||
public static final DataFormat TREE_IDENTITY_FORMAT = new DataFormat("application/sopa-tree-identity");
|
||||
|
||||
private final Function<Path, FlightState> flightStates;
|
||||
|
||||
public SopaTreeCell(Function<Path, FlightState> flightStates) {
|
||||
this.flightStates = flightStates;
|
||||
setOnDragDetected(this::handleDragDetected);
|
||||
setOnDragOver(this::handleDragOver);
|
||||
setOnDragDropped(this::handleDragDropped);
|
||||
}
|
||||
|
||||
private void handleDragDetected(MouseEvent mouseEvent) {
|
||||
var item = getTreeItem();
|
||||
if (item == null || item.getValue() == null) return;
|
||||
if (item.getValue().kind() == Kind.project) return;
|
||||
|
||||
var dragboard = startDragAndDrop(TransferMode.MOVE);
|
||||
var content = new ClipboardContent();
|
||||
content.put(TREE_IDENTITY_FORMAT, item.getValue().toString());
|
||||
dragboard.setContent(content);
|
||||
mouseEvent.consume();
|
||||
}
|
||||
|
||||
private void handleDragOver(DragEvent dragEvent) {
|
||||
var db = dragEvent.getDragboard();
|
||||
if (!db.hasContent(TREE_IDENTITY_FORMAT)) return;
|
||||
|
||||
var source = TreeIdentity.fromString((String) db.getContent(TREE_IDENTITY_FORMAT));
|
||||
var target = getItem();
|
||||
if (target == null || source.equals(target)) return;
|
||||
|
||||
if (
|
||||
(source.kind() == Kind.testcase && target.kind() == Kind.project) ||
|
||||
(source.kind() == Kind.step && target.kind() == Kind.testcase) ||
|
||||
(source.kind() == target.kind())
|
||||
) {
|
||||
dragEvent.acceptTransferModes(TransferMode.MOVE);
|
||||
}
|
||||
|
||||
dragEvent.consume();
|
||||
}
|
||||
|
||||
private void handleDragDropped(DragEvent dragEvent) {
|
||||
var db = dragEvent.getDragboard();
|
||||
var source = TreeIdentity.fromString((String) db.getContent(TREE_IDENTITY_FORMAT));
|
||||
var target = getItem();
|
||||
|
||||
var success = false;
|
||||
try {
|
||||
if (source.kind() == Kind.testcase && target.kind() == Kind.project) {
|
||||
log.info("Dropped testcase %s onto project %s.".formatted(source.path(), target.path()));
|
||||
TestCaseRepository.move(source.path(), target.path());
|
||||
success = true;
|
||||
} else if (source.kind() == Kind.step && target.kind() == Kind.testcase) {
|
||||
log.info("Dropped step %s onto testcase %s.".formatted(source.path(), target.path()));
|
||||
StepRepository.move(source.path(), target.path());
|
||||
success = true;
|
||||
} else if (source.kind() == target.kind()) {
|
||||
if (source.kind() == Kind.testcase) {
|
||||
log.info("Dropped testcase %s onto testcase %s.".formatted(source.path(), target.path()));
|
||||
var targetProjectPath = target.path().getParent().getParent().resolve("project.yml");
|
||||
TestCaseRepository.move(
|
||||
source.path(),
|
||||
targetProjectPath
|
||||
);
|
||||
success = true;
|
||||
} else if (source.kind() == Kind.step) {
|
||||
log.info("Dropped step %s onto step %s.".formatted(source.path(), target.path()));
|
||||
double mouseY = dragEvent.getY();
|
||||
double cellHeight = this.getHeight();
|
||||
boolean isAboveCenter = mouseY < (cellHeight / 2.0);
|
||||
|
||||
StepRepository.moveReordering(
|
||||
source.path(),
|
||||
target.path(),
|
||||
isAboveCenter
|
||||
);
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
} catch (RepositoryException repo) {
|
||||
log.log(
|
||||
Level.SEVERE,
|
||||
"Cannot move %s -> %s of paths: %s -> %s.".formatted(
|
||||
source.kind(), target.kind(), source.path(), target.path()
|
||||
),
|
||||
repo
|
||||
);
|
||||
}
|
||||
|
||||
dragEvent.setDropCompleted(success);
|
||||
dragEvent.consume();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void updateItem(TreeIdentity item, boolean empty) {
|
||||
super.updateItem(item, empty);
|
||||
setText("");
|
||||
setGraphic(null);
|
||||
setTooltip(null);
|
||||
setContextMenu(null);
|
||||
if (empty || item == null)
|
||||
return;
|
||||
|
||||
getStyleClass().remove("text-bold");
|
||||
var path = item.path();
|
||||
try {
|
||||
switch (item.kind()) {
|
||||
case project:
|
||||
setText(ProjectRepository.get(path).getName());
|
||||
setGraphic(FontIcon.of(MaterialDesignF.FOLDER_OUTLINE));
|
||||
setContextMenu(new ProjectContextMenu(item.path()));
|
||||
getStyleClass().add("text-bold");
|
||||
break;
|
||||
case testcase:
|
||||
setText(TestCaseRepository.get(path).getName());
|
||||
setGraphic(null);
|
||||
setContextMenu(new TestCaseContextMenu(item.path()));
|
||||
break;
|
||||
case step:
|
||||
setText(StepRepository.get(path).getName());
|
||||
setContextMenu(new StepContextMenu(item.path()));
|
||||
setGraphic(flightIcon(flightStates.apply(path)));
|
||||
break;
|
||||
default:
|
||||
log.severe("Calling cell update with unknown kind %s for path %s.".formatted(item.kind().name(), path));
|
||||
setText("error");
|
||||
setGraphic(FontIcon.of(MaterialDesignA.ALERT));
|
||||
}
|
||||
} catch (DoesNotExistException moved) {
|
||||
setText(null);
|
||||
setTooltip(null);
|
||||
setGraphic(FontIcon.of(MaterialDesignL.LOADING));
|
||||
} catch (EmptyException emptyFile) {
|
||||
setText(emptyFile.getMessage());
|
||||
setTooltip(new Tooltip(emptyFile.getPath().toString()));
|
||||
setGraphic(FontIcon.of(MaterialDesignS.SYNC));
|
||||
} catch (RepositoryException badObject) {
|
||||
log.log(Level.SEVERE, "Cannot update cell for %s.".formatted(path), badObject);
|
||||
setText(badObject.getMessage());
|
||||
setTooltip(new Tooltip(badObject.getPath().toString()));
|
||||
setGraphic(FontIcon.of(MaterialDesignH.HELP));
|
||||
}
|
||||
}
|
||||
|
||||
private static FontIcon flightIcon(FlightState state) {
|
||||
var icon = FontIcon.of(state.icon());
|
||||
icon.getStyleClass().addAll("flight-icon", state.styleClass());
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.molnarandrei.sopa.ui.navpane;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public record TreeIdentity(Kind kind, Path path) {
|
||||
@Override
|
||||
public String toString() {
|
||||
return kind.name() + ":" + path.toString();
|
||||
}
|
||||
|
||||
public static TreeIdentity fromString(String string) {
|
||||
var split = string.split(":");
|
||||
return new TreeIdentity(Kind.valueOf(split[0]), Path.of(split[1]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.molnarandrei.sopa.ui.navpane.context;
|
||||
|
||||
import com.molnarandrei.sopa.ui.navpane.DeleteDialog;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.ui.navpane.TreeIdentity;
|
||||
|
||||
import com.molnarandrei.sopa.project.ProjectService;
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import javafx.scene.control.ContextMenu;
|
||||
import javafx.scene.control.MenuItem;
|
||||
import javafx.scene.control.SeparatorMenuItem;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignS;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class ProjectContextMenu extends ContextMenu {
|
||||
public ProjectContextMenu(Path projectPath) {
|
||||
var run = new MenuItem(
|
||||
"ejecutar todos los casos",
|
||||
FontIcon.of(MaterialDesignS.SEND));
|
||||
run.setOnAction(e->{
|
||||
// TODO
|
||||
});
|
||||
|
||||
var createCase = new MenuItem(
|
||||
"crear caso de prueba",
|
||||
FontIcon.of(MaterialDesignP.PLUS));
|
||||
createCase.setOnAction(e->{
|
||||
TestCaseService.create(projectPath);
|
||||
});
|
||||
|
||||
|
||||
var duplicate = new MenuItem(
|
||||
"duplicar proyecto",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_DUPLICATE));
|
||||
duplicate.setOnAction(e->
|
||||
ProjectService.duplicate(projectPath)
|
||||
);
|
||||
|
||||
var close = new MenuItem(
|
||||
"cerrar proyecto",
|
||||
FontIcon.of(MaterialDesignC.CLOSE));
|
||||
close.setOnAction(e->
|
||||
ProjectService.close(projectPath)
|
||||
);
|
||||
|
||||
var delete = new MenuItem(
|
||||
"eliminar proyecto",
|
||||
FontIcon.of(MaterialDesignD.DELETE));
|
||||
delete.setOnAction(e-> DeleteDialog.confirmAndDelete(new TreeIdentity(Kind.project, projectPath)));
|
||||
|
||||
getItems().addAll(
|
||||
run,
|
||||
new SeparatorMenuItem(),
|
||||
createCase, duplicate, close, // TODO rename
|
||||
new TransparentSeparatorMenuItem(),
|
||||
delete
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.molnarandrei.sopa.ui.navpane.context;
|
||||
|
||||
import com.molnarandrei.sopa.ui.navpane.DeleteDialog;
|
||||
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.soap.SoapService;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.ui.navpane.Clipboard;
|
||||
import com.molnarandrei.sopa.ui.navpane.TreeIdentity;
|
||||
import javafx.scene.control.ContextMenu;
|
||||
import javafx.scene.control.MenuItem;
|
||||
import javafx.scene.control.SeparatorMenuItem;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignS;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class StepContextMenu extends ContextMenu {
|
||||
public StepContextMenu(Path stepPath) {
|
||||
var run = new MenuItem(
|
||||
"ejecutar paso",
|
||||
FontIcon.of(MaterialDesignS.SEND));
|
||||
run.setOnAction(e-> SoapService.createAndStartCallForStep(stepPath) );
|
||||
|
||||
var runPreviousSteps = new MenuItem(
|
||||
"ejecutar este y anteriores",
|
||||
FontIcon.of(MaterialDesignC.CHEVRON_UP));
|
||||
runPreviousSteps.setOnAction(e->
|
||||
SoapService.createAndStartCallsForTestCaseUntilStep(
|
||||
stepPath.getParent().getParent().resolve("testcase.yml"),
|
||||
stepPath
|
||||
));
|
||||
|
||||
var runFollowingCases = new MenuItem(
|
||||
"ejecutar a partir de aqui",
|
||||
FontIcon.of(MaterialDesignC.CHEVRON_DOWN));
|
||||
runFollowingCases.setOnAction(e->
|
||||
SoapService.createAndStartCallsForTestCaseStartingFromStep(
|
||||
stepPath.getParent().getParent().resolve("testcase.yml"),
|
||||
stepPath
|
||||
));
|
||||
|
||||
var toggle = new MenuItem(
|
||||
"activar/desactivar paso",
|
||||
FontIcon.of(MaterialDesignC.CHECK_CIRCLE_OUTLINE));
|
||||
toggle.setOnAction(e->{
|
||||
StepService.toggleActive(stepPath);
|
||||
});
|
||||
|
||||
var duplicate = new MenuItem(
|
||||
"duplicar paso",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_DUPLICATE));
|
||||
duplicate.setOnAction(e->{
|
||||
StepService.duplicate(stepPath);
|
||||
});
|
||||
|
||||
var identity = new TreeIdentity(Kind.step, stepPath);
|
||||
|
||||
var copy = new MenuItem(
|
||||
"copiar paso",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_COPY));
|
||||
copy.setOnAction(e-> Clipboard.copy(identity));
|
||||
|
||||
var cut = new MenuItem(
|
||||
"cortar paso",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_CUT));
|
||||
cut.setOnAction(e-> Clipboard.cut(identity));
|
||||
|
||||
var paste = new MenuItem(
|
||||
"pegar",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_PASTE));
|
||||
paste.setOnAction(e-> Clipboard.paste(identity));
|
||||
// The clipboard changes while the menu is hidden, so check again each time it opens.
|
||||
setOnShowing(e-> paste.setDisable(! Clipboard.canPaste(identity)));
|
||||
|
||||
var delete = new MenuItem(
|
||||
"eliminar paso",
|
||||
FontIcon.of(MaterialDesignD.DELETE));
|
||||
delete.setOnAction(e-> DeleteDialog.confirmAndDelete(new TreeIdentity(Kind.step, stepPath)));
|
||||
|
||||
getItems().addAll(
|
||||
run, runPreviousSteps, runFollowingCases,
|
||||
new SeparatorMenuItem(),
|
||||
toggle, duplicate, cut, copy, paste,
|
||||
new TransparentSeparatorMenuItem(),
|
||||
delete
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.molnarandrei.sopa.ui.navpane.context;
|
||||
|
||||
import com.molnarandrei.sopa.ui.navpane.DeleteDialog;
|
||||
|
||||
import com.molnarandrei.sopa.step.StepService;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseService;
|
||||
import com.molnarandrei.sopa.soap.SoapService;
|
||||
import com.molnarandrei.sopa.data.yaml.Kind;
|
||||
import com.molnarandrei.sopa.ui.navpane.Clipboard;
|
||||
import com.molnarandrei.sopa.ui.navpane.TreeIdentity;
|
||||
import javafx.scene.control.ContextMenu;
|
||||
import javafx.scene.control.MenuItem;
|
||||
import javafx.scene.control.SeparatorMenuItem;
|
||||
import org.kordamp.ikonli.javafx.FontIcon;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
|
||||
import org.kordamp.ikonli.materialdesign2.MaterialDesignS;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public class TestCaseContextMenu extends ContextMenu {
|
||||
|
||||
public TestCaseContextMenu(Path testCasePath) {
|
||||
var run = new MenuItem(
|
||||
"ejecutar todos los pasos",
|
||||
FontIcon.of(MaterialDesignS.SEND));
|
||||
run.setOnAction(e->
|
||||
SoapService.createAndStartCallsForTestCase(testCasePath));
|
||||
|
||||
var createStep = new MenuItem(
|
||||
"crear paso",
|
||||
FontIcon.of(MaterialDesignP.PLUS));
|
||||
createStep.setOnAction(e->{
|
||||
StepService.create(testCasePath);
|
||||
});
|
||||
|
||||
var toggle = new MenuItem(
|
||||
"activar/desactivar caso",
|
||||
FontIcon.of(MaterialDesignC.CHECK_CIRCLE_OUTLINE));
|
||||
toggle.setOnAction(e->{
|
||||
TestCaseService.toggleActive(testCasePath);
|
||||
});
|
||||
|
||||
var duplicate = new MenuItem(
|
||||
"duplicar caso",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_DUPLICATE));
|
||||
duplicate.setOnAction(e->{
|
||||
TestCaseService.duplicate(testCasePath);
|
||||
});
|
||||
|
||||
var identity = new TreeIdentity(Kind.testcase, testCasePath);
|
||||
|
||||
var copy = new MenuItem(
|
||||
"copiar caso",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_COPY));
|
||||
copy.setOnAction(e-> Clipboard.copy(identity));
|
||||
|
||||
var cut = new MenuItem(
|
||||
"cortar caso",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_CUT));
|
||||
cut.setOnAction(e-> Clipboard.cut(identity));
|
||||
|
||||
var paste = new MenuItem(
|
||||
"pegar",
|
||||
FontIcon.of(MaterialDesignC.CONTENT_PASTE));
|
||||
paste.setOnAction(e-> Clipboard.paste(identity));
|
||||
// The clipboard changes while the menu is hidden, so check again each time it opens.
|
||||
setOnShowing(e-> paste.setDisable(! Clipboard.canPaste(identity)));
|
||||
|
||||
var delete = new MenuItem(
|
||||
"eliminar caso",
|
||||
FontIcon.of(MaterialDesignD.DELETE));
|
||||
delete.setOnAction(e-> DeleteDialog.confirmAndDelete(new TreeIdentity(Kind.testcase, testCasePath)));
|
||||
|
||||
getItems().addAll(
|
||||
run,
|
||||
new SeparatorMenuItem(),
|
||||
createStep, toggle, duplicate, cut, copy, paste,
|
||||
new TransparentSeparatorMenuItem(),
|
||||
delete
|
||||
);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.molnarandrei.sopa.ui.navpane.context;
|
||||
|
||||
import javafx.scene.control.SeparatorMenuItem;
|
||||
|
||||
/** Separator that keeps its room in the menu but draws no line, to set an item slightly apart. */
|
||||
public class TransparentSeparatorMenuItem extends SeparatorMenuItem {
|
||||
public TransparentSeparatorMenuItem() {
|
||||
getContent().setOpacity(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package com.molnarandrei.sopa.wsdl;
|
||||
|
||||
import com.molnarandrei.sopa.soap.MalformedEndpointException;
|
||||
import com.molnarandrei.sopa.soap.SoapCall;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Logger;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
public class WsdlRemote {
|
||||
private static final Logger log = Logger.getLogger(WsdlRemote.class.getName());
|
||||
private static final int IMPORT_TIMEOUT_SECONDS = 1;
|
||||
|
||||
public record Download(String wsdl, List<String> imports, List<String> failedImports) {}
|
||||
|
||||
public static Download download(String endpoint, int timeoutSeconds) throws IOException, InterruptedException {
|
||||
requireValidEndpoint(endpoint);
|
||||
|
||||
var url = wsdlUrl(endpoint);
|
||||
var wsdl = fetch(url, timeoutSeconds);
|
||||
if (! WsdlValidations.isWsdl(wsdl))
|
||||
throw new IOException("%s no devuelve un WSDL.".formatted(url));
|
||||
|
||||
var imports = new ArrayList<String>();
|
||||
var failed = new ArrayList<String>();
|
||||
var seen = new HashSet<>(Set.of(url));
|
||||
fetchImportsRecursively(url, wsdl, seen, imports, failed);
|
||||
return new Download(wsdl, imports, failed);
|
||||
}
|
||||
|
||||
private static void requireValidEndpoint(String endpoint) throws IOException {
|
||||
try {
|
||||
SoapCall.validateEndpoint(endpoint);
|
||||
} catch (MalformedEndpointException malformed) {
|
||||
throw new IOException("Endpoint no válido: %s".formatted(malformed.getMessage()), malformed);
|
||||
}
|
||||
}
|
||||
|
||||
private static void fetchImportsRecursively(
|
||||
String documentUrl, String document, Set<String> seen, List<String> imports, List<String> failed
|
||||
) throws InterruptedException {
|
||||
for (var location : schemaLocations(document)) {
|
||||
String url;
|
||||
try {
|
||||
url = URI.create(documentUrl).resolve(location.strip()).toString();
|
||||
SoapCall.validateEndpoint(url);
|
||||
} catch (IllegalArgumentException | MalformedEndpointException notFetchable) {
|
||||
log.warning("Cannot fetch import %s of %s.".formatted(location, documentUrl));
|
||||
failed.add(location);
|
||||
continue;
|
||||
}
|
||||
if (! seen.add(url)) continue;
|
||||
|
||||
try {
|
||||
var schema = fetch(url, IMPORT_TIMEOUT_SECONDS);
|
||||
if (! WsdlValidations.isSchema(schema))
|
||||
throw new IOException("%s no devuelve un esquema.".formatted(url));
|
||||
imports.add(schema);
|
||||
fetchImportsRecursively(url, schema, seen, imports, failed);
|
||||
} catch (IOException cannotFetch) {
|
||||
log.warning("Cannot fetch import %s: %s".formatted(url, cannotFetch));
|
||||
failed.add(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> schemaLocations(String document) {
|
||||
var locations = new ArrayList<String>();
|
||||
var root = WsdlValidations.rootOrNull(document);
|
||||
for (var name : List.of("import", "include")) {
|
||||
var references = root.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, name);
|
||||
for (int i = 0; i < references.getLength(); i++) {
|
||||
var location = ((Element) references.item(i)).getAttribute("schemaLocation");
|
||||
if (! location.isBlank()) locations.add(location);
|
||||
}
|
||||
}
|
||||
return locations;
|
||||
}
|
||||
|
||||
private static String fetch(String url, int timeoutSeconds) throws IOException, InterruptedException {
|
||||
log.info("Downloading %s.".formatted(url));
|
||||
var timeout = Duration.ofSeconds(timeoutSeconds);
|
||||
try (
|
||||
var client = HttpClient.newBuilder()
|
||||
.connectTimeout(timeout)
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
) {
|
||||
var request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(timeout)
|
||||
.GET()
|
||||
.build();
|
||||
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() != 200)
|
||||
throw new IOException("%s respondió con estado %d.".formatted(url, response.statusCode()));
|
||||
return response.body();
|
||||
}
|
||||
}
|
||||
|
||||
private static String wsdlUrl(String endpoint) {
|
||||
var url = endpoint.strip();
|
||||
if (url.toLowerCase().endsWith("?wsdl")) return url;
|
||||
return url + (url.contains("?") ? "&wsdl" : "?wsdl");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.molnarandrei.sopa.wsdl;
|
||||
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Each endpoint of a project has its own WSDL, stored in a folder of {@code wsdl/} named after the endpoint:
|
||||
* {@code wsdl/<end of the endpoint, url encoded>/service.wsdl}, its {@code import-<n>.xsd} and
|
||||
* {@code endpoint.txt}, the endpoint itself, as names are cut to their last {@value #MAX_FOLDER_NAME} characters.
|
||||
*/
|
||||
public class WsdlRepository {
|
||||
private static final Logger log = Logger.getLogger(WsdlRepository.class.getName());
|
||||
private static final String WSDL_FILE = "service.wsdl";
|
||||
private static final String ENDPOINT_FILE = "endpoint.txt";
|
||||
static final int MAX_FOLDER_NAME = 50;
|
||||
/** Projects used to keep a single WSDL here, which belongs to the endpoint of the project. */
|
||||
|
||||
public static void update(Path projectPath, String endpoint, WsdlRemote.Download download) throws RepositoryException {
|
||||
var folder = folderOf(projectPath, endpoint);
|
||||
try {
|
||||
Files.createDirectories(folder);
|
||||
deleteImportsIn(folder);
|
||||
|
||||
Files.writeString(folder.resolve(ENDPOINT_FILE), endpoint.strip());
|
||||
Files.writeString(folder.resolve(WSDL_FILE), download.wsdl());
|
||||
var index = 1;
|
||||
for (var schema : download.imports())
|
||||
Files.writeString(folder.resolve("import-%d.xsd".formatted(index++)), schema);
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(folder, "Cannot write wsdl", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static WsdlRemote.Download get(Path projectPath, String endpoint) throws RepositoryException {
|
||||
var wsdlFile = wsdlFileOf(projectPath, endpoint);
|
||||
try {
|
||||
var imports = new ArrayList<String>();
|
||||
for (var file : importsOf(projectPath, endpoint))
|
||||
imports.add(Files.readString(file));
|
||||
return new WsdlRemote.Download(Files.readString(wsdlFile), imports, List.of());
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(wsdlFile, "Cannot read wsdl", io);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean exists(Path projectPath, String endpoint) {
|
||||
if (endpoint == null || endpoint.isBlank()) return false;
|
||||
return Files.isRegularFile(wsdlFileOf(projectPath, endpoint));
|
||||
}
|
||||
|
||||
/** The endpoints that have a WSDL, sorted. */
|
||||
public static List<String> endpoints(Path projectPath) throws RepositoryException {
|
||||
var folder = rootOf(projectPath);
|
||||
var endpoints = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
|
||||
if (! Files.isDirectory(folder)) return List.of();
|
||||
try {
|
||||
for (var endpointFolder : endpointFolders(folder))
|
||||
if (Files.isRegularFile(endpointFolder.resolve(WSDL_FILE)))
|
||||
endpoints.add(endpointOf(endpointFolder));
|
||||
} catch (IOException io) {
|
||||
throw new RepositoryException(folder, "Cannot list wsdl", io);
|
||||
}
|
||||
return List.copyOf(endpoints);
|
||||
}
|
||||
|
||||
static long filesStampOf(Path projectPath, String endpoint) throws IOException {
|
||||
var stamp = stampOf(wsdlFileOf(projectPath, endpoint));
|
||||
for (var file : importsOf(projectPath, endpoint))
|
||||
stamp += stampOf(file);
|
||||
return stamp;
|
||||
}
|
||||
|
||||
private static long stampOf(Path file) {
|
||||
return file.toFile().lastModified() + file.toFile().length();
|
||||
}
|
||||
|
||||
private static Path wsdlFileOf(Path projectPath, String endpoint) {
|
||||
return folderOf(projectPath, endpoint).resolve(WSDL_FILE);
|
||||
}
|
||||
|
||||
private static List<Path> importsOf(Path projectPath, String endpoint) throws IOException {
|
||||
var folder = folderOf(projectPath, endpoint);
|
||||
return Files.isDirectory(folder) ? importsIn(folder) : List.of();
|
||||
}
|
||||
|
||||
private static void deleteImportsIn(Path folder) throws IOException {
|
||||
for (var stale : importsIn(folder))
|
||||
Files.delete(stale);
|
||||
}
|
||||
|
||||
private static List<Path> importsIn(Path folder) throws IOException {
|
||||
var imports = new ArrayList<Path>();
|
||||
try (var stream = Files.newDirectoryStream(folder, "import-*.xsd")) {
|
||||
stream.forEach(imports::add);
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
/** The folder holding the WSDL of the endpoint, or the free one it would go into. */
|
||||
static Path folderOf(Path projectPath, String endpoint) {
|
||||
var root = rootOf(projectPath);
|
||||
var stripped = endpoint.strip();
|
||||
try {
|
||||
for (var folder : endpointFolders(root))
|
||||
if (endpointOf(folder).equals(stripped)) return folder;
|
||||
} catch (IOException unreadable) {
|
||||
log.log(Level.WARNING, "Cannot look for the wsdl of %s.".formatted(stripped), unreadable);
|
||||
}
|
||||
return freeFolder(root, folderName(stripped));
|
||||
}
|
||||
|
||||
/** Ends of different endpoints can be equal: those after the first get a number. */
|
||||
private static Path freeFolder(Path root, String name) {
|
||||
var folder = root.resolve(name);
|
||||
for (var index = 2; Files.exists(folder); index++) {
|
||||
var suffix = "-%d".formatted(index);
|
||||
folder = root.resolve(lastCharacters(name, MAX_FOLDER_NAME - suffix.length()) + suffix);
|
||||
}
|
||||
return folder;
|
||||
}
|
||||
|
||||
static String folderName(String endpoint) {
|
||||
var name = lastCharacters(encode(endpoint), MAX_FOLDER_NAME);
|
||||
// Not "." nor "..", nor hidden.
|
||||
while (name.startsWith(".")) name = name.substring(1);
|
||||
return name.isEmpty() ? "endpoint" : name;
|
||||
}
|
||||
|
||||
private static String lastCharacters(String text, int count) {
|
||||
return text.length() <= count ? text : text.substring(text.length() - count);
|
||||
}
|
||||
|
||||
private static String endpointOf(Path folder) throws IOException {
|
||||
var file = folder.resolve(ENDPOINT_FILE);
|
||||
// Folders made before endpoints were cut were named after the whole endpoint.
|
||||
if (! Files.isRegularFile(file)) return decode(folder.getFileName().toString());
|
||||
return Files.readString(file).strip();
|
||||
}
|
||||
|
||||
private static List<Path> endpointFolders(Path root) throws IOException {
|
||||
if (! Files.isDirectory(root)) return List.of();
|
||||
var folders = new ArrayList<Path>();
|
||||
try (var stream = Files.newDirectoryStream(root, Files::isDirectory)) {
|
||||
stream.forEach(folders::add);
|
||||
}
|
||||
return folders;
|
||||
}
|
||||
|
||||
private static Path rootOf(Path projectPath) {
|
||||
return projectPath.resolveSibling("wsdl");
|
||||
}
|
||||
|
||||
/** Reversible, and safe as a file name: URLEncoder leaves only letters, digits, {@code .-_*} and {@code +}. */
|
||||
static String encode(String endpoint) {
|
||||
return URLEncoder.encode(endpoint, StandardCharsets.UTF_8).replace("*", "%2A");
|
||||
}
|
||||
|
||||
static String decode(String folderName) {
|
||||
return URLDecoder.decode(folderName, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package com.molnarandrei.sopa.wsdl;
|
||||
|
||||
import com.molnarandrei.sopa.Utils;
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.soap.PropertyMissingException;
|
||||
import com.molnarandrei.sopa.soap.SoapCall;
|
||||
import com.molnarandrei.sopa.soap.SoapJob;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
import javafx.scene.control.Alert;
|
||||
import org.apache.xmlbeans.SchemaTypeSystem;
|
||||
import org.apache.xmlbeans.XmlBeans;
|
||||
import org.apache.xmlbeans.XmlObject;
|
||||
import org.apache.xmlbeans.XmlOptions;
|
||||
import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
|
||||
import org.apache.xmlbeans.impl.xsd2inst.SampleXmlUtil;
|
||||
import org.w3c.dom.Attr;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.namespace.QName;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.molnarandrei.sopa.wsdl.WsdlValidations.*;
|
||||
|
||||
/**
|
||||
* All operations over WSDLs at the application level belong here.
|
||||
* Including UI operations such as showing a dialog that we cannot read something.
|
||||
*/
|
||||
public class WsdlService {
|
||||
private static final Logger log = Logger.getLogger(WsdlService.class.getName());
|
||||
private static final String SOAP_11_BINDING_NS = "http://schemas.xmlsoap.org/wsdl/soap/";
|
||||
private static final String SOAP_12_BINDING_NS = "http://schemas.xmlsoap.org/wsdl/soap12/";
|
||||
|
||||
public record Action(String name, String soapAction, QName object) {}
|
||||
|
||||
/**
|
||||
* Downloads the WSDL of {@code endpoint} once its properties are replaced, those of the testcase over
|
||||
* those of the project, and keeps it by {@code endpoint} as written.
|
||||
*
|
||||
* @param testCasePath the testcase whose properties apply, null for only those of the project.
|
||||
*/
|
||||
public static boolean download(Path projectPath, Path testCasePath, String endpoint, int timeoutSeconds) {
|
||||
String url;
|
||||
try {
|
||||
url = SoapCall.applyProperties(endpoint, propertiesOf(projectPath, testCasePath));
|
||||
} catch (RepositoryException cannotRead) {
|
||||
log.log(Level.WARNING, "Cannot read properties for %s.".formatted(endpoint), cannotRead);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se han podido leer las propiedades de:\n%s".formatted(endpoint),
|
||||
cannotRead.getMessage()
|
||||
);
|
||||
return false;
|
||||
} catch (PropertyMissingException missing) {
|
||||
log.warning("Property %s missing for %s.".formatted(missing.getMissingKey(), endpoint));
|
||||
Utils.alert(
|
||||
Alert.AlertType.WARNING,
|
||||
"Endpoint incompleto",
|
||||
"No se puede descargar el WSDL de:\n%s".formatted(endpoint),
|
||||
"Falta la propiedad: %s".formatted(missing.getMissingKey())
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return download(projectPath, endpoint, url, timeoutSeconds);
|
||||
}
|
||||
|
||||
private static Map<String, String> propertiesOf(Path projectPath, Path testCasePath) throws RepositoryException {
|
||||
var properties = new HashMap<>(ProjectRepository.get(projectPath).getProperties());
|
||||
if (testCasePath != null)
|
||||
properties.putAll(TestCaseRepository.get(testCasePath).getProperties());
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static boolean download(Path projectPath, String endpoint, String url, int timeoutSeconds) {
|
||||
try {
|
||||
var wsdl = WsdlRemote.download(url, timeoutSeconds);
|
||||
if (! write(projectPath, endpoint, wsdl)) return false;
|
||||
if (! wsdl.failedImports().isEmpty())
|
||||
Utils.alert(
|
||||
Alert.AlertType.WARNING,
|
||||
"Descarga incompleta",
|
||||
"No se han podido descargar algunos esquemas importados del WSDL",
|
||||
String.join("\n", wsdl.failedImports())
|
||||
);
|
||||
return true;
|
||||
} catch (Exception cannotDownload) {
|
||||
log.log(Level.WARNING, "Cannot download wsdl of %s.".formatted(url), cannotDownload);
|
||||
Utils.alert(
|
||||
"Fallo de descarga",
|
||||
"No se ha podido descargar el WSDL de:\n%s".formatted(url),
|
||||
cannotDownload.getMessage() != null ? cannotDownload.getMessage() : cannotDownload.toString()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean write(Path projectPath, String endpoint, WsdlRemote.Download wsdl) {
|
||||
try {
|
||||
WsdlRepository.update(projectPath, endpoint, wsdl);
|
||||
return true;
|
||||
} catch (RepositoryException cannotWrite) {
|
||||
log.log(Level.SEVERE, "Cannot write wsdl of %s in project %s.".formatted(endpoint, projectPath), cannotWrite);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido guardar el WSDL de:\n%s\nen el proyecto:\n%s"
|
||||
.formatted(endpoint, projectPath),
|
||||
cannotWrite.getMessage()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean exists(Path projectPath, String endpoint) {
|
||||
return WsdlRepository.exists(projectPath, endpoint);
|
||||
}
|
||||
|
||||
public static WsdlRemote.Download read(Path projectPath, String endpoint) {
|
||||
try {
|
||||
return WsdlRepository.get(projectPath, endpoint);
|
||||
} catch (RepositoryException cannotRead) {
|
||||
alertCannotRead(projectPath, endpoint, cannotRead);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The endpoints listed in the project. */
|
||||
public static List<String> endpoints(Path projectPath) {
|
||||
var endpoints = new LinkedHashSet<String>();
|
||||
try {
|
||||
var project = ProjectRepository.get(projectPath);
|
||||
for (var endpoint : project.getEndpoints().keySet())
|
||||
if (endpoint != null && ! endpoint.isBlank()) endpoints.add(endpoint.strip());
|
||||
} catch (RepositoryException cannotRead) {
|
||||
log.log(Level.WARNING, "Cannot list endpoints of project %s.".formatted(projectPath), cannotRead);
|
||||
}
|
||||
return List.copyOf(endpoints);
|
||||
}
|
||||
|
||||
public static List<Action> getActions(Path projectPath, String endpoint) {
|
||||
try {
|
||||
// TODO implement WSDL2.0 when and if it ever becomes relevant.
|
||||
return actionsOf(
|
||||
WsdlRepository.get(projectPath, endpoint).wsdl(),
|
||||
ProjectRepository.get(projectPath).versionOf(endpoint)
|
||||
);
|
||||
} catch (RepositoryException cannotRead) {
|
||||
alertCannotRead(projectPath, endpoint, cannotRead);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The version of the project endpoint {@code endpoint}, SOAP 1.1 when the project cannot be read. */
|
||||
public static SoapVersion versionOf(Path projectPath, String endpoint) {
|
||||
try {
|
||||
return ProjectRepository.get(projectPath).versionOf(endpoint);
|
||||
} catch (RepositoryException cannotRead) {
|
||||
log.log(Level.WARNING, "Cannot read version of %s in project %s.".formatted(endpoint, projectPath), cannotRead);
|
||||
return SoapVersion.ONE_ONE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SOAP version the kept WSDL of {@code endpoint} declares for it, once its properties are replaced,
|
||||
* those of the testcase over those of the project. Null when unknown.
|
||||
*
|
||||
* @param testCasePath the testcase whose properties apply, null for only those of the project.
|
||||
*/
|
||||
public static SoapVersion detectVersion(Path projectPath, Path testCasePath, String endpoint) {
|
||||
try {
|
||||
var url = SoapCall.applyProperties(endpoint, propertiesOf(projectPath, testCasePath));
|
||||
return detectVersion(WsdlRepository.get(projectPath, endpoint).wsdl(), url);
|
||||
} catch (RepositoryException | PropertyMissingException cannotDetect) {
|
||||
log.log(Level.INFO, "Cannot detect SOAP version of %s.".formatted(endpoint), cannotDetect);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SOAP version a WSDL 1.1 declares for {@code url}: that of the port whose address is {@code url}, else
|
||||
* of the only port with its path, else of the bindings when all are of the same version. Null when unknown.
|
||||
*/
|
||||
public static SoapVersion detectVersion(String wsdl, String url) {
|
||||
var root = rootOrNull(wsdl);
|
||||
if (root == null) return null;
|
||||
|
||||
var byAddress = new HashMap<String, SoapVersion>();
|
||||
var byPath = new HashMap<String, List<SoapVersion>>();
|
||||
for (var service : elements(root, WSDL_11_NS, "service"))
|
||||
for (var port : elements(service, WSDL_11_NS, "port"))
|
||||
for (var bindingNs : List.of(SOAP_11_BINDING_NS, SOAP_12_BINDING_NS))
|
||||
for (var address : elements(port, bindingNs, "address")) {
|
||||
var location = address.getAttribute("location");
|
||||
var version = bindingNs.equals(SOAP_12_BINDING_NS) ? SoapVersion.ONE_TWO : SoapVersion.ONE_ONE;
|
||||
byAddress.put(withoutTrailingSlash(location), version);
|
||||
byPath.computeIfAbsent(pathOf(location), k -> new ArrayList<>()).add(version);
|
||||
}
|
||||
|
||||
if (url != null) {
|
||||
var exact = byAddress.get(withoutTrailingSlash(url));
|
||||
if (exact != null) return exact;
|
||||
var samePath = byPath.getOrDefault(pathOf(url), List.of());
|
||||
if (samePath.size() == 1) return samePath.getFirst();
|
||||
}
|
||||
|
||||
var has11 = hasBinding(root, SOAP_11_BINDING_NS);
|
||||
var has12 = hasBinding(root, SOAP_12_BINDING_NS);
|
||||
if (has11 == has12) return null;
|
||||
return has12 ? SoapVersion.ONE_TWO : SoapVersion.ONE_ONE;
|
||||
}
|
||||
|
||||
private static boolean hasBinding(Element root, String bindingNs) {
|
||||
for (var binding : elements(root, WSDL_11_NS, "binding"))
|
||||
if (! elements(binding, bindingNs, "binding").isEmpty()) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String withoutTrailingSlash(String url) {
|
||||
var stripped = url.strip();
|
||||
while (stripped.endsWith("/")) stripped = stripped.substring(0, stripped.length() - 1);
|
||||
return stripped;
|
||||
}
|
||||
|
||||
private static String pathOf(String url) {
|
||||
try {
|
||||
var path = java.net.URI.create(url.strip()).getPath();
|
||||
return path == null ? "" : withoutTrailingSlash(path);
|
||||
} catch (IllegalArgumentException malformed) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static void alertCannotRead(Path projectPath, String endpoint, RepositoryException cannotRead) {
|
||||
log.log(Level.SEVERE, "Cannot read wsdl of %s in project %s.".formatted(endpoint, projectPath), cannotRead);
|
||||
Utils.alert(
|
||||
"Fallo de fichero",
|
||||
"No se ha podido leer el WSDL de:\n%s\nen el proyecto:\n%s".formatted(endpoint, projectPath),
|
||||
cannotRead.getMessage()
|
||||
);
|
||||
}
|
||||
|
||||
private static List<Action> actionsOf(String wsdl, SoapVersion version) {
|
||||
var root = rootOrNull(wsdl);
|
||||
if (root == null) return List.of();
|
||||
|
||||
var soapActions = soapActionsByOperation(root, version);
|
||||
var elementsByMessage = elementsByMessage(root);
|
||||
var actions = new TreeMap<String, Action>(String.CASE_INSENSITIVE_ORDER);
|
||||
for (var portType : elements(root, WSDL_11_NS, "portType")) {
|
||||
for (var operation : elements(portType, WSDL_11_NS, "operation")) {
|
||||
var name = operation.getAttribute("name");
|
||||
var inputs = elementsOf(operation, "input", elementsByMessage);
|
||||
actions.put(name, new Action(
|
||||
name,
|
||||
soapActions.getOrDefault(name, ""),
|
||||
inputs.stream().findFirst().orElse(null)
|
||||
));
|
||||
}
|
||||
}
|
||||
return List.copyOf(actions.values());
|
||||
}
|
||||
|
||||
private static Map<String, String> soapActionsByOperation(Element root, SoapVersion version) {
|
||||
var bindingNamespacesEndingInProjectVersion = version == SoapVersion.ONE_TWO
|
||||
? List.of(SOAP_11_BINDING_NS, SOAP_12_BINDING_NS)
|
||||
: List.of(SOAP_12_BINDING_NS, SOAP_11_BINDING_NS);
|
||||
|
||||
var soapActions = new HashMap<String, String>();
|
||||
for (var bindingNs : bindingNamespacesEndingInProjectVersion)
|
||||
for (var binding : elements(root, WSDL_11_NS, "binding"))
|
||||
for (var operation : elements(binding, WSDL_11_NS, "operation"))
|
||||
for (var soapOperation : elements(operation, bindingNs, "operation"))
|
||||
soapActions.put(operation.getAttribute("name"), soapOperation.getAttribute("soapAction"));
|
||||
return soapActions;
|
||||
}
|
||||
|
||||
public static int operationCount(WsdlRemote.Download download) {
|
||||
var root = rootOrNull(download.wsdl());
|
||||
if (root == null) return 0;
|
||||
return countOperations(root, WSDL_11_NS, "portType") + countOperations(root, WSDL_20_NS, "interface");
|
||||
}
|
||||
|
||||
private static int countOperations(Element root, String namespace, String container) {
|
||||
var count = 0;
|
||||
for (var element : elements(root, namespace, container))
|
||||
count += elements(element, namespace, "operation").size();
|
||||
return count;
|
||||
}
|
||||
|
||||
public static String generateExample(
|
||||
WsdlRemote.Download wsdl, QName object, SoapVersion version
|
||||
) throws Exception {
|
||||
if (object == null)
|
||||
throw new IOException("La acción no declara un elemento de entrada.");
|
||||
var type = compileSchemas(wsdl).findDocumentType(object);
|
||||
if (type == null)
|
||||
throw new IOException("%s no está definido en el WSDL.".formatted(object));
|
||||
|
||||
return wrapInEnvelope(SampleXmlUtil.createSampleForType(type), version);
|
||||
}
|
||||
|
||||
private static String wrapInEnvelope(String body, SoapVersion version) {
|
||||
return """
|
||||
<soapenv:Envelope xmlns:soapenv="%s">
|
||||
<soapenv:Header/>
|
||||
<soapenv:Body>
|
||||
%s
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>""".formatted(envelopeNamespaceOf(version), body.strip().indent(4).stripTrailing());
|
||||
}
|
||||
|
||||
static SchemaTypeSystem compileSchemas(WsdlRemote.Download download) throws Exception {
|
||||
var schemas = inlineAndImportedSchemas(download);
|
||||
var sources = new XmlObject[schemas.size()];
|
||||
for (int i = 0; i < sources.length; i++) {
|
||||
removeExternalReferences(schemas.get(i));
|
||||
// Not XmlObject.Factory: it finds the schema types through the classpath, which modules do not use.
|
||||
sources[i] = SchemaDocument.Factory.parse(schemas.get(i));
|
||||
}
|
||||
return XmlBeans.compileXsd(sources, XmlBeans.getBuiltinTypeSystem(), new XmlOptions());
|
||||
}
|
||||
|
||||
private static List<Element> inlineAndImportedSchemas(WsdlRemote.Download download) throws Exception {
|
||||
var schemas = new ArrayList<Element>();
|
||||
var wsdl = SoapJob.parseXml(download.wsdl());
|
||||
var inline = wsdl.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
|
||||
for (int i = 0; i < inline.getLength(); i++) {
|
||||
var schema = (Element) inline.item(i);
|
||||
copyNamespacesOfAncestors(schema);
|
||||
schemas.add(schema);
|
||||
}
|
||||
for (var schema : download.imports())
|
||||
schemas.add(SoapJob.parseXml(schema).getDocumentElement());
|
||||
return schemas;
|
||||
}
|
||||
|
||||
private static void copyNamespacesOfAncestors(Element schema) {
|
||||
for (var ancestor = schema.getParentNode(); ancestor instanceof Element element; ancestor = element.getParentNode()) {
|
||||
var attributes = element.getAttributes();
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
var attribute = (Attr) attributes.item(i);
|
||||
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI())
|
||||
&& ! schema.hasAttribute(attribute.getName()))
|
||||
schema.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, attribute.getName(), attribute.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void removeExternalReferences(Element schema) {
|
||||
for (var reference : elements(schema, XMLConstants.W3C_XML_SCHEMA_NS_URI, "import"))
|
||||
reference.removeAttribute("schemaLocation");
|
||||
for (var reference : elements(schema, XMLConstants.W3C_XML_SCHEMA_NS_URI, "include"))
|
||||
reference.getParentNode().removeChild(reference);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package com.molnarandrei.sopa.wsdl;
|
||||
|
||||
import com.molnarandrei.sopa.soap.SoapJob;
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
import org.apache.xmlbeans.SchemaTypeLoader;
|
||||
import org.apache.xmlbeans.SchemaTypeSystem;
|
||||
import org.apache.xmlbeans.XmlBeans;
|
||||
import org.apache.xmlbeans.XmlError;
|
||||
import org.apache.xmlbeans.XmlException;
|
||||
import org.apache.xmlbeans.XmlOptions;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.namespace.QName;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class WsdlValidations {
|
||||
private static final Logger log = Logger.getLogger(WsdlValidations.class.getName());
|
||||
|
||||
public static final String SOAP_11_NS = "http://schemas.xmlsoap.org/soap/envelope/";
|
||||
public static final String SOAP_12_NS = "http://www.w3.org/2003/05/soap-envelope";
|
||||
static final String WSDL_11_NS = "http://schemas.xmlsoap.org/wsdl/";
|
||||
static final String WSDL_20_NS = "http://www.w3.org/ns/wsdl";
|
||||
|
||||
private record Contract(
|
||||
long filesStamp, SchemaTypeSystem types, SchemaTypeLoader loader,
|
||||
Map<QName, Set<QName>> outputsByInput, boolean hasMessagesDescribedByType
|
||||
) {}
|
||||
|
||||
private static final Map<Path, Contract> contracts = new ConcurrentHashMap<>();
|
||||
|
||||
static boolean isWsdl(String document) {
|
||||
var root = rootOrNull(document);
|
||||
return root != null && (
|
||||
WSDL_11_NS.equals(root.getNamespaceURI()) && "definitions".equals(root.getLocalName())
|
||||
|| WSDL_20_NS.equals(root.getNamespaceURI()) && "description".equals(root.getLocalName())
|
||||
);
|
||||
}
|
||||
|
||||
static boolean isSchema(String document) {
|
||||
var root = rootOrNull(document);
|
||||
return root != null
|
||||
&& XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI())
|
||||
&& "schema".equals(root.getLocalName());
|
||||
}
|
||||
|
||||
static Element rootOrNull(String document) {
|
||||
try {
|
||||
return SoapJob.parseXml(document).getDocumentElement();
|
||||
} catch (Exception notXml) {
|
||||
log.fine("Not an XML document: %s".formatted(notXml.getMessage()));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String envelopeNamespaceOf(SoapVersion version) {
|
||||
return version == SoapVersion.ONE_TWO ? SOAP_12_NS : SOAP_11_NS;
|
||||
}
|
||||
|
||||
public static List<String> responseErrors(
|
||||
Path projectPath, String endpoint, SoapVersion version, String request, String response
|
||||
) throws Exception {
|
||||
var contract = contractOf(projectPath, endpoint);
|
||||
|
||||
Document document;
|
||||
try {
|
||||
document = SoapJob.parseXml(response);
|
||||
} catch (SAXException notXml) {
|
||||
return List.of("La respuesta no es XML: %s".formatted(notXml.getMessage()));
|
||||
}
|
||||
|
||||
var envelopeNs = envelopeNamespaceOf(version);
|
||||
var root = document.getDocumentElement();
|
||||
if (! envelopeNs.equals(root.getNamespaceURI()) || ! "Envelope".equals(root.getLocalName()))
|
||||
return List.of("La raíz es {%s}%s, se esperaba un Envelope de SOAP %s."
|
||||
.formatted(root.getNamespaceURI(), root.getLocalName(), version.getTitle()));
|
||||
|
||||
var bodyElements = SoapJob.bodyElements(document);
|
||||
if (bodyElements == null)
|
||||
return List.of("El Envelope no tiene Body.");
|
||||
|
||||
var declaredOutputs = declaredOutputsOrEmpty(contract, request);
|
||||
if (bodyElements.isEmpty())
|
||||
return declaredOutputs.isEmpty()
|
||||
? List.of()
|
||||
: List.of("El Body está vacío, se esperaba %s.".formatted(declaredOutputs));
|
||||
|
||||
var errors = new ArrayList<String>();
|
||||
for (var element : bodyElements) {
|
||||
var name = new QName(element.getNamespaceURI(), element.getLocalName());
|
||||
// A fault answers any operation: judging it is up to the notSoapFault and soapFault assertions.
|
||||
if (envelopeNs.equals(name.getNamespaceURI()) && "Fault".equals(name.getLocalPart()))
|
||||
return List.of();
|
||||
errors.addAll(elementErrors(contract, element, name, declaredOutputs));
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
private static List<String> elementErrors(
|
||||
Contract contract, Element element, QName name, Set<QName> declaredOutputs
|
||||
) throws IOException {
|
||||
if (! declaredOutputs.isEmpty() && ! declaredOutputs.contains(name))
|
||||
return List.of("El WSDL declara %s como respuesta, no %s.".formatted(declaredOutputs, name));
|
||||
|
||||
if (contract.types().findDocumentType(name) != null)
|
||||
return schemaErrors(contract, element);
|
||||
|
||||
if (contract.hasMessagesDescribedByType())
|
||||
throw new IOException("El WSDL describe mensajes por tipo (estilo rpc), que no se pueden validar.");
|
||||
return List.of("%s no está definido en el WSDL.".formatted(name));
|
||||
}
|
||||
|
||||
private static List<String> schemaErrors(Contract contract, Element element) {
|
||||
var found = new ArrayList<XmlError>();
|
||||
try {
|
||||
contract.loader().parse(element, null, null).validate(new XmlOptions().setErrorListener(found));
|
||||
} catch (XmlException unparseable) {
|
||||
return List.of(unparseable.getMessage());
|
||||
}
|
||||
return found.stream().map(XmlError::getMessage).toList();
|
||||
}
|
||||
|
||||
private static Set<QName> declaredOutputsOrEmpty(Contract contract, String request) {
|
||||
try {
|
||||
var bodyElements = SoapJob.bodyElements(SoapJob.parseXml(request));
|
||||
if (bodyElements == null || bodyElements.isEmpty()) return Set.of();
|
||||
var input = bodyElements.getFirst();
|
||||
return contract.outputsByInput().getOrDefault(new QName(input.getNamespaceURI(), input.getLocalName()), Set.of());
|
||||
} catch (Exception unreadable) {
|
||||
return Set.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static Contract contractOf(Path projectPath, String endpoint) throws Exception {
|
||||
if (! WsdlRepository.exists(projectPath, endpoint))
|
||||
throw new IOException("No hay WSDL de %s. Descárgalo desde el editor.".formatted(endpoint));
|
||||
|
||||
var folder = WsdlRepository.folderOf(projectPath, endpoint);
|
||||
var filesStamp = WsdlRepository.filesStampOf(projectPath, endpoint);
|
||||
var cached = contracts.get(folder);
|
||||
if (cached != null && cached.filesStamp() == filesStamp) return cached;
|
||||
|
||||
var contract = compile(filesStamp, WsdlRepository.get(projectPath, endpoint));
|
||||
contracts.put(folder, contract);
|
||||
return contract;
|
||||
}
|
||||
|
||||
private static Contract compile(long filesStamp, WsdlRemote.Download download) throws Exception {
|
||||
var types = WsdlService.compileSchemas(download);
|
||||
var root = SoapJob.parseXml(download.wsdl()).getDocumentElement();
|
||||
|
||||
var outputs = new HashMap<QName, Set<QName>>();
|
||||
var elementsByMessage = elementsByMessage(root);
|
||||
for (var portType : elements(root, WSDL_11_NS, "portType")) {
|
||||
for (var operation : elements(portType, WSDL_11_NS, "operation")) {
|
||||
var input = elementsOf(operation, "input", elementsByMessage);
|
||||
var output = elementsOf(operation, "output", elementsByMessage);
|
||||
for (var element : input)
|
||||
outputs.computeIfAbsent(element, ignored -> new HashSet<>()).addAll(output);
|
||||
}
|
||||
}
|
||||
|
||||
var hasMessagesDescribedByType = elements(root, WSDL_11_NS, "part").stream()
|
||||
.anyMatch(part -> ! part.hasAttribute("element"));
|
||||
var loader = XmlBeans.typeLoaderUnion(types, XmlBeans.getBuiltinTypeSystem());
|
||||
return new Contract(filesStamp, types, loader, outputs, hasMessagesDescribedByType);
|
||||
}
|
||||
|
||||
static Map<String, Set<QName>> elementsByMessage(Element root) {
|
||||
var elementsByMessage = new HashMap<String, Set<QName>>();
|
||||
for (var message : elements(root, WSDL_11_NS, "message")) {
|
||||
var parts = new LinkedHashSet<QName>();
|
||||
for (var part : elements(message, WSDL_11_NS, "part"))
|
||||
if (part.hasAttribute("element"))
|
||||
parts.add(resolve(part, part.getAttribute("element")));
|
||||
elementsByMessage.put(message.getAttribute("name"), parts);
|
||||
}
|
||||
return elementsByMessage;
|
||||
}
|
||||
|
||||
static Set<QName> elementsOf(Element operation, String direction, Map<String, Set<QName>> elementsByMessage) {
|
||||
var messages = elements(operation, WSDL_11_NS, direction);
|
||||
if (messages.isEmpty()) return Set.of();
|
||||
var message = messages.getFirst().getAttribute("message");
|
||||
return elementsByMessage.getOrDefault(message.substring(message.indexOf(':') + 1), Set.of());
|
||||
}
|
||||
|
||||
private static QName resolve(Element scope, String prefixedName) {
|
||||
var colon = prefixedName.indexOf(':');
|
||||
var prefix = colon < 0 ? null : prefixedName.substring(0, colon);
|
||||
return new QName(scope.lookupNamespaceURI(prefix), prefixedName.substring(colon + 1));
|
||||
}
|
||||
|
||||
static List<Element> elements(Element parent, String namespace, String name) {
|
||||
var found = parent.getElementsByTagNameNS(namespace, name);
|
||||
var elements = new ArrayList<Element>();
|
||||
for (int i = 0; i < found.getLength(); i++)
|
||||
elements.add((Element) found.item(i));
|
||||
return elements;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
module com.molnarandrei.sopa {
|
||||
requires javafx.controls;
|
||||
requires javafx.fxml;
|
||||
requires atlantafx.base;
|
||||
requires org.kordamp.ikonli.javafx;
|
||||
requires org.kordamp.ikonli.materialdesign2;
|
||||
requires org.kordamp.ikonli.material2;
|
||||
requires tools.jackson.databind;
|
||||
requires tools.jackson.dataformat.yaml;
|
||||
requires java.desktop;
|
||||
requires javafx.graphics;
|
||||
requires javafx.base;
|
||||
requires java.logging;
|
||||
requires tools.jackson.core;
|
||||
requires org.apache.commons.io;
|
||||
requires java.net.http;
|
||||
requires org.yaml.snakeyaml;
|
||||
requires org.snakeyaml.engine;
|
||||
requires org.fxmisc.richtext;
|
||||
requires org.apache.xmlbeans;
|
||||
requires java.xml;
|
||||
requires jdk.httpserver;
|
||||
requires wellbehavedfx;
|
||||
|
||||
opens com.molnarandrei.sopa.data.yaml to tools.jackson.databind;
|
||||
|
||||
opens com.molnarandrei.sopa.ui to javafx.graphics;
|
||||
exports com.molnarandrei.sopa.events;
|
||||
exports com.molnarandrei.sopa.ui.navpane;
|
||||
exports com.molnarandrei.sopa;
|
||||
exports com.molnarandrei.sopa.data;
|
||||
exports com.molnarandrei.sopa.data.yaml;
|
||||
exports com.molnarandrei.sopa.project;
|
||||
exports com.molnarandrei.sopa.step;
|
||||
exports com.molnarandrei.sopa.testcase;
|
||||
exports com.molnarandrei.sopa.calllog;
|
||||
exports com.molnarandrei.sopa.soap;
|
||||
opens com.molnarandrei.sopa.ui.menu to javafx.graphics;
|
||||
opens com.molnarandrei.sopa.ui.editor to javafx.graphics;
|
||||
opens com.molnarandrei.sopa.ui.editor.step to javafx.graphics;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
# Sopa SOAP test project
|
||||
|
||||
Plain YAML files. App watches folder, sees edits live.
|
||||
|
||||
## Tree
|
||||
|
||||
```
|
||||
project.yml
|
||||
wsdl/<name>/service.wsdl, import-<n>.xsd, endpoint.txt READ ONLY
|
||||
testcase-<t>/ t from 1, creation order
|
||||
testcase.yml
|
||||
step-<n>/ n from 1, run order
|
||||
step.yml
|
||||
response-<time>.yml READ ONLY
|
||||
```
|
||||
|
||||
## READ ONLY: never create, edit, delete
|
||||
|
||||
- `wsdl/`: downloaded by app, one folder per endpoint. Pick folder whose endpoint.txt is call endpoint. Read for operations, soapAction, payload shape. Missing: ask user download from
|
||||
project editor endpoint list.
|
||||
- `response-*.yml`: step call log history, written by app. Read for real response shape.
|
||||
|
||||
## Files
|
||||
|
||||
Line 1 header exact, else app reject file. Keep all keys. Empty is `""`, `{}`, `[]`, never null.
|
||||
|
||||
project.yml
|
||||
```yaml
|
||||
# com.molnarandrei.sopa.Project
|
||||
endpoints:
|
||||
http://host/service:
|
||||
version: 1.1 # or 1.2
|
||||
headers: {}
|
||||
name: Test Project
|
||||
properties: {}
|
||||
```
|
||||
|
||||
testcase.yml
|
||||
```yaml
|
||||
# com.molnarandrei.sopa.TestCase
|
||||
action: ""
|
||||
active: true
|
||||
endpoint: ""
|
||||
headers: {}
|
||||
name: Alumni
|
||||
properties: {}
|
||||
```
|
||||
|
||||
step.yml
|
||||
```yaml
|
||||
# com.molnarandrei.sopa.Step
|
||||
action: http://ns/GetAlumnus # WSDL soapAction
|
||||
active: true
|
||||
assertions:
|
||||
- type: httpStatus
|
||||
expression: ""
|
||||
value: "200"
|
||||
- type: xPath
|
||||
expression: "//*[local-name()='alumnus']/*[local-name()='name']"
|
||||
value: "Zoe"
|
||||
endpoint: ""
|
||||
extractions:
|
||||
alumnusId: "//*[local-name()='alumnus']/*[local-name()='id']"
|
||||
headers: {}
|
||||
name: Get alumnus
|
||||
payload: |-
|
||||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://ns">
|
||||
<soapenv:Header/>
|
||||
<soapenv:Body>
|
||||
<sch:GetAlumnus>
|
||||
<sch:id>{alumnusId}</sch:id>
|
||||
</sch:GetAlumnus>
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>
|
||||
```
|
||||
|
||||
## Assertions
|
||||
|
||||
Set unused field to `""`. `assertions: []` allowed.
|
||||
|
||||
| type | expression | value |
|
||||
|---|---|---|
|
||||
| httpStatus | `""` | status code |
|
||||
| contains | `""` | substring of body |
|
||||
| xPath | XPath | exact expected string |
|
||||
| regex | Java regex, found in body | `""` |
|
||||
| validPerWsdl | `""` | `""` |
|
||||
| notSoapFault | `""` | `""` |
|
||||
| soapFault | `""` | faultcode substring, `""` = any fault |
|
||||
|
||||
Expect fault: `httpStatus` 500 plus `soapFault` or xPath on `faultcode`.
|
||||
No fault via xPath: `count(//*[local-name()='Fault'])`, value `"0"`.
|
||||
|
||||
## Rules
|
||||
|
||||
- New testcase: make folder, `testcase.yml`. New step: next `step-<n>` folder, `step.yml`.
|
||||
- Numbers contiguous. Order numeric. Reorder: rename folders. Testcases have no order.
|
||||
- Project `endpoints`: map by url to pick from, never inherited. Testcase or step must set `endpoint`, copy one url exact.
|
||||
- SOAP version per endpoint: call uses `version` of project endpoint equal to call endpoint as written, before `{prop}`. Endpoint not in project: `1.1`.
|
||||
- `1.1`: `text/xml`, `SOAPAction` header. `1.2`: `application/soap+xml; action="..."`. Payload envelope ns must match version.
|
||||
- Version unknown: read endpoint WSDL. Port with `soap12:address` or only `soap12:binding` = `1.2`; `soap:` = `1.1`.
|
||||
- Inherit: blank endpoint step > testcase. Blank action step > testcase. Both blank endpoint stops run.
|
||||
- Merge, lower wins: headers project < testcase < step. properties project < testcase.
|
||||
- `{prop}` substituted in endpoint, payload, header values, assertion expression and value.
|
||||
- Not substituted: action, extraction XPath.
|
||||
- Missing prop stops run. Any `{...}` counts as prop. Only regex expression keeps `{2}`, `{2,3}`.
|
||||
- Extraction: `prop: XPath`. Runs after assertions pass. Empty result fails step.
|
||||
- Extracted value saved to `testcase.yml` properties, or `project.yml` if key only there. No need declare first.
|
||||
- Run: active steps in order. First failed assertion stops rest of steps.
|
||||
- `active: false` skip step. On testcase, skip all its steps.
|
||||
- Prefer `local-name()` XPath: namespace free.
|
||||
- SOAP 1.2 envelope ns: `http://www.w3.org/2003/05/soap-envelope`.
|
||||
@@ -0,0 +1,51 @@
|
||||
/* Base container: Rounded border, background, and clipping */
|
||||
.code-area {
|
||||
-fx-background-color: rgba(0,0,0,0);
|
||||
-fx-border-color: -color-border-default;
|
||||
-fx-border-width: 1px;
|
||||
-fx-border-radius: 4px;
|
||||
-fx-background-radius: 4px;
|
||||
}
|
||||
|
||||
.code-area .caret { -fx-stroke: -color-fg-emphasis; }
|
||||
|
||||
.code-area .viewport {
|
||||
-fx-background-radius: 6px;
|
||||
}
|
||||
|
||||
.code-area .paragraph-box {
|
||||
-fx-background-color: rgba(0,0,0,0);
|
||||
-fx-padding: 0.5em 0.8em;
|
||||
}
|
||||
|
||||
/* Obsidian palette */
|
||||
.code-area {
|
||||
-obsidian-punctuation: #E8E2B7;
|
||||
-obsidian-tag: #93C763;
|
||||
-obsidian-attribute: #678CB1;
|
||||
-obsidian-value: #EC7600;
|
||||
-obsidian-comment: #7D8C93;
|
||||
}
|
||||
|
||||
/* Unstyled punctuation (<, >, =, quotes, slashes) */
|
||||
.code-area .text {
|
||||
-fx-fill: -obsidian-punctuation;
|
||||
}
|
||||
|
||||
/* Syntax Highlighting */
|
||||
.code-area .text.xml-element {
|
||||
-fx-fill: -obsidian-tag;
|
||||
}
|
||||
|
||||
.code-area .text.xml-attribute {
|
||||
-fx-fill: -obsidian-attribute;
|
||||
}
|
||||
|
||||
.code-area .text.xml-value {
|
||||
-fx-fill: -obsidian-value;
|
||||
}
|
||||
|
||||
.code-area .text.xml-comment {
|
||||
-fx-fill: -obsidian-comment;
|
||||
-fx-font-style: italic;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/* Apply bottom spacing to all heading classes globally */
|
||||
.title-1,
|
||||
.title-2,
|
||||
.title-3,
|
||||
.title-4 {
|
||||
/* Top, Right, Bottom, Left insets */
|
||||
-fx-padding: 8px 0 4px 0;
|
||||
}
|
||||
|
||||
.tree-view {
|
||||
-fx-border-width: 0;
|
||||
}
|
||||
|
||||
.split-pane:horizontal > .split-pane-divider {
|
||||
-fx-pref-width: 8px;
|
||||
-fx-padding: 0 4px 0 4px;
|
||||
}
|
||||
|
||||
.menu-item, .tree-cell {
|
||||
-fx-padding: 4px;
|
||||
}
|
||||
|
||||
.tab {
|
||||
-fx-padding: 2px;
|
||||
}
|
||||
|
||||
/* Step flight state icon in the project tree, slightly smaller than the default 18px. */
|
||||
.tree-cell .flight-icon {
|
||||
-fx-icon-size: 14px;
|
||||
}
|
||||
.tree-cell .flight-icon.idle {
|
||||
-fx-icon-color: -color-fg-subtle;
|
||||
}
|
||||
.tree-cell .flight-icon.in-flight {
|
||||
-fx-icon-color: -color-accent-fg;
|
||||
}
|
||||
.tree-cell .flight-icon.success {
|
||||
-fx-icon-color: -color-success-fg;
|
||||
}
|
||||
.tree-cell .flight-icon.failed {
|
||||
-fx-icon-color: -color-warning-fg;
|
||||
}
|
||||
.tree-cell .flight-icon.exception {
|
||||
-fx-icon-color: -color-danger-fg;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import com.molnarandrei.sopa.events.*;
|
||||
import javafx.event.EventType;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
|
||||
/**
|
||||
* Drives a real {@link FileAlterationObserver} over a temporary project with a {@link ProjectMonitor}
|
||||
* attached, and checks that real filesystem changes turn into the expected events.
|
||||
* The observer is polled synchronously on the test thread (rather than through a background
|
||||
* {@code FileAlterationMonitor}) so the static {@link Events} mock, which is thread-local, sees every emit.
|
||||
*/
|
||||
public class FilesystemChangeListenerTest {
|
||||
@TempDir
|
||||
Path project;
|
||||
|
||||
private FileAlterationObserver observer;
|
||||
|
||||
@BeforeEach
|
||||
public void createProject() throws Exception {
|
||||
write("project.yml", "name: demo");
|
||||
write("testcase-one/testcase.yml", "name: one");
|
||||
write("testcase-one/step-1/step.yml", "name: step");
|
||||
Files.createDirectories(project.resolve("wsdl"));
|
||||
|
||||
observer = FileAlterationObserver.builder().setFile(project.toFile()).get();
|
||||
observer.initialize();
|
||||
}
|
||||
|
||||
private Path write(String file, String content) throws IOException {
|
||||
var path = project.resolve(file);
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, content);
|
||||
return path;
|
||||
}
|
||||
|
||||
private record Emitted(EventType<?> type, String payload) {}
|
||||
|
||||
/** Events emitted by one observer poll after {@code change} has been applied to the filesystem. */
|
||||
private List<Emitted> emittedAfter(FilesystemChange change) throws Exception {
|
||||
try (MockedStatic<Events> events = Mockito.mockStatic(Events.class)) {
|
||||
var listener = new ProjectMonitor(project);
|
||||
observer.addListener(listener);
|
||||
events.clearInvocations();
|
||||
|
||||
change.apply();
|
||||
observer.checkAndNotify();
|
||||
observer.removeListener(listener);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(SopaEvent.class);
|
||||
events.verify(() -> Events.emit(captor.capture()), atLeast(0));
|
||||
return captor.getAllValues().stream()
|
||||
.filter(event -> event.getEventType() != UiEvent.WATCHER_HEARTBEAT)
|
||||
.map(event -> new Emitted(event.getEventType(), String.valueOf(event.get())))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private interface FilesystemChange {
|
||||
void apply() throws Exception;
|
||||
}
|
||||
|
||||
private static boolean has(List<Emitted> emitted, EventType<?> type, String pathFragment) {
|
||||
return emitted.stream().anyMatch(e -> e.type() == type && e.payload().contains(pathFragment));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void projectFileChangeEmitsProjectChanged() throws Exception {
|
||||
var emitted = emittedAfter(() -> write("project.yml", "name: a longer demo name"));
|
||||
assertTrue(has(emitted, ProjectEvent.CHANGED, "project.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newTestCaseEmitsTestCaseAdded() throws Exception {
|
||||
var emitted = emittedAfter(() -> write("testcase-two/testcase.yml", "name: two"));
|
||||
assertTrue(has(emitted, TestCaseEvent.ADDED, "testcase-two/testcase.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newNonEmptyFileAlsoEmitsChanged() throws Exception {
|
||||
var emitted = emittedAfter(() -> write("testcase-two/testcase.yml", "name: two"));
|
||||
assertTrue(has(emitted, TestCaseEvent.CHANGED, "testcase-two/testcase.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newEmptyFileDoesNotEmitChanged() throws Exception {
|
||||
var emitted = emittedAfter(() -> write("testcase-two/testcase.yml", ""));
|
||||
assertTrue(has(emitted, TestCaseEvent.ADDED, "testcase-two/testcase.yml"), emitted.toString());
|
||||
assertFalse(has(emitted, TestCaseEvent.CHANGED, "testcase-two/testcase.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newStepEmitsStepAdded() throws Exception {
|
||||
var emitted = emittedAfter(() -> write("testcase-one/step-2/step.yml", "name: second"));
|
||||
assertTrue(has(emitted, StepEvent.ADDED, "testcase-one/step-2/step.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void newResponseEmitsResponseAdded() throws Exception {
|
||||
var emitted = emittedAfter(() -> write("testcase-one/step-1/response-1.yml", "status: 200"));
|
||||
assertTrue(has(emitted, ResponseEvent.ADDED, "step-1/response-1.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deletedStepEmitsStepRemoved() throws Exception {
|
||||
var emitted = emittedAfter(() -> Files.delete(project.resolve("testcase-one/step-1/step.yml")));
|
||||
assertTrue(has(emitted, StepEvent.REMOVED, "testcase-one/step-1/step.yml"), emitted.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filesOutsideTestCaseFoldersAreIgnored() throws Exception {
|
||||
var emitted = emittedAfter(() -> {
|
||||
write("wsdl/http%3A%2F%2Fhost%2Fservice/service.wsdl", "<definitions/>");
|
||||
write("notes.txt", "notes");
|
||||
write("alumni/testcase.yml", "name: alumni");
|
||||
});
|
||||
assertEquals(List.of(), emitted);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noChangeEmitsNothing() throws Exception {
|
||||
assertEquals(List.of(), emittedAfter(() -> {}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.molnarandrei.sopa.data;
|
||||
|
||||
import com.molnarandrei.sopa.events.Events;
|
||||
import com.molnarandrei.sopa.events.SopaEvent;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
|
||||
public class ProjectMonitorTest {
|
||||
@TempDir
|
||||
Path project;
|
||||
|
||||
@BeforeEach
|
||||
public void createProject() throws IOException {
|
||||
write("project.yml");
|
||||
write("testcase-one/testcase.yml");
|
||||
write("testcase-one/step-1/step.yml");
|
||||
write("alumni/testcase.yml");
|
||||
write("alumni/step-1/step.yml");
|
||||
write("wsdl/http%3A%2F%2Fhost%2Fservice/service.wsdl");
|
||||
write("notes.txt");
|
||||
}
|
||||
|
||||
private Path write(String file) throws IOException {
|
||||
var path = project.resolve(file);
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, "content");
|
||||
return path;
|
||||
}
|
||||
|
||||
/** Text of every event emitted while running {@code action}, which holds the paths involved. */
|
||||
private List<String> emittedBy(MonitorAction action) throws Exception {
|
||||
try (MockedStatic<Events> events = Mockito.mockStatic(Events.class)) {
|
||||
var monitor = new ProjectMonitor(project);
|
||||
events.clearInvocations();
|
||||
action.run(monitor);
|
||||
var captor = ArgumentCaptor.forClass(SopaEvent.class);
|
||||
events.verify(() -> Events.emit(captor.capture()), atLeast(0));
|
||||
return captor.getAllValues().stream().map(event -> String.valueOf(event.get())).toList();
|
||||
}
|
||||
}
|
||||
|
||||
private interface MonitorAction {
|
||||
void run(ProjectMonitor monitor) throws Exception;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initialScanOnlyFindsTestCaseFolders() throws Exception {
|
||||
try (MockedStatic<Events> events = Mockito.mockStatic(Events.class)) {
|
||||
new ProjectMonitor(project);
|
||||
var captor = ArgumentCaptor.forClass(SopaEvent.class);
|
||||
events.verify(() -> Events.emit(captor.capture()), atLeast(1));
|
||||
var emitted = captor.getAllValues().stream().map(event -> String.valueOf(event.get())).toList();
|
||||
|
||||
assertTrue(emitted.stream().anyMatch(e -> e.contains("testcase-one" + "/testcase.yml")));
|
||||
assertTrue(emitted.stream().anyMatch(e -> e.contains("testcase-one/step-1/step.yml")));
|
||||
assertTrue(emitted.stream().noneMatch(e -> e.contains("alumni")));
|
||||
assertTrue(emitted.stream().noneMatch(e -> e.contains("wsdl")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void liveEventsOutsideTestCaseFoldersAreIgnored() throws Exception {
|
||||
var emitted = emittedBy(monitor -> {
|
||||
monitor.onFileChange(project.resolve("alumni/testcase.yml"));
|
||||
monitor.onFileCreate(project.resolve("alumni/step-1/step.yml"));
|
||||
monitor.onFileDelete(project.resolve("alumni/testcase.yml"));
|
||||
monitor.onFileCreate(project.resolve("wsdl/http%3A%2F%2Fhost%2Fservice/service.wsdl"));
|
||||
monitor.onFileChange(project.resolve("notes.txt"));
|
||||
});
|
||||
assertEquals(List.of(), emitted);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void liveEventsInTestCaseFoldersAreEmitted() throws Exception {
|
||||
var testCase = project.resolve("testcase-one/testcase.yml");
|
||||
var emitted = emittedBy(monitor -> {
|
||||
monitor.onFileChange(testCase);
|
||||
Files.delete(testCase);
|
||||
monitor.onFileDelete(testCase);
|
||||
});
|
||||
assertEquals(2, emitted.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void projectFileIsNotIgnored() throws Exception {
|
||||
var emitted = emittedBy(monitor -> monitor.onFileChange(project.resolve("project.yml")));
|
||||
assertEquals(1, emitted.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.molnarandrei.sopa.data.yaml;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class YamlRoundTripTest {
|
||||
|
||||
@Test
|
||||
public void stepWithAssertionsRoundTrips() {
|
||||
var step = new Step("Create classroom");
|
||||
step.setAssertions(List.of(
|
||||
new Assertion(Assertion.Type.httpStatus, "200", ""),
|
||||
new Assertion(Assertion.Type.xPath, "0", "count(//*[local-name()='Fault'])")
|
||||
));
|
||||
|
||||
var yaml = Yaml.toYaml(step);
|
||||
var read = Yaml.toStep(yaml);
|
||||
|
||||
assertEquals(2, read.getAssertions().size(), yaml);
|
||||
assertEquals(Assertion.Type.httpStatus, read.getAssertions().get(0).getType());
|
||||
assertEquals("count(//*[local-name()='Fault'])", read.getAssertions().get(1).getExpression());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.molnarandrei.sopa.project;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Project;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class ProjectFolderTest {
|
||||
@TempDir
|
||||
Path folder;
|
||||
|
||||
@Test
|
||||
public void emptyFolderCanHoldAProject() {
|
||||
assertTrue(ProjectRepository.canHoldNewProject(folder));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingFolderNeedsItsParent() {
|
||||
assertTrue(ProjectRepository.canHoldNewProject(folder.resolve("new")));
|
||||
assertFalse(ProjectRepository.canHoldNewProject(folder.resolve("missing/new")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void folderWithContentsCannot() throws Exception {
|
||||
Files.writeString(folder.resolve("file.txt"), "x");
|
||||
assertFalse(ProjectRepository.canHoldNewProject(folder));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fileCannot() throws Exception {
|
||||
assertFalse(ProjectRepository.canHoldNewProject(Files.writeString(folder.resolve("file.txt"), "x")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void initializingCreatesTheMissingFolder() throws Exception {
|
||||
var directory = folder.resolve("new");
|
||||
ProjectRepository.initializeProject(directory, new Project("P", java.util.List.of()));
|
||||
assertEquals("P", ProjectRepository.get(directory.resolve("project.yml")).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void agentsFileIsWrittenIntoTheProject() throws Exception {
|
||||
ProjectRepository.writeAgentsFile(folder);
|
||||
assertTrue(Files.readString(folder.resolve("AGENTS.md")).startsWith("# Sopa"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.molnarandrei.sopa.server;
|
||||
|
||||
import com.molnarandrei.sopa.soap.SoapVersion;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlService;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class TestServerTest {
|
||||
private static final String SOAP_11_ENVELOPE = """
|
||||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>
|
||||
<GetClassroom xmlns="%s"><id>1</id></GetClassroom>
|
||||
</soap:Body></soap:Envelope>""".formatted(SchoolService.NS);
|
||||
|
||||
private HttpServer server;
|
||||
private String base;
|
||||
|
||||
@BeforeEach
|
||||
public void start() throws Exception {
|
||||
server = TestServer.start(0);
|
||||
base = "http://localhost:%d".formatted(server.getAddress().getPort());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void stop() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
private HttpResponse<String> get(String path) throws Exception {
|
||||
try (var client = HttpClient.newHttpClient()) {
|
||||
return client.send(HttpRequest.newBuilder(URI.create(base + path)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wsdlOfEachEndpointHasOnlyItsVersion() throws Exception {
|
||||
var v11 = get("/v11?wsdl").body();
|
||||
var v12 = get("/v12?wsdl").body();
|
||||
assertTrue(v11.contains("soap:address") && ! v11.contains("soap12:"), v11);
|
||||
assertTrue(v12.contains("soap12:address") && ! v12.contains("<soap:"), v12);
|
||||
assertEquals(SoapVersion.ONE_ONE, WsdlService.detectVersion(v11, base + "/v11"));
|
||||
assertEquals(SoapVersion.ONE_TWO, WsdlService.detectVersion(v12, base + "/v12"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void otherVersionGetsVersionMismatchWithUpgrade() throws Exception {
|
||||
try (var client = HttpClient.newHttpClient()) {
|
||||
var response = client.send(
|
||||
HttpRequest.newBuilder(URI.create(base + "/v12"))
|
||||
.header("Content-Type", "application/soap+xml; charset=utf-8")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(SOAP_11_ENVELOPE))
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.ofString()
|
||||
);
|
||||
assertEquals(500, response.statusCode());
|
||||
assertTrue(response.headers().firstValue("Content-Type").orElse("").startsWith("application/soap+xml"));
|
||||
var body = response.body();
|
||||
assertTrue(body.contains("VersionMismatch"), body);
|
||||
assertTrue(body.contains("Upgrade") && body.contains("SupportedEnvelope"), body);
|
||||
assertTrue(body.contains("xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\""), body);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Assertion;
|
||||
import com.molnarandrei.sopa.data.yaml.Assertion.Type;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlRemote;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlRepository;
|
||||
import com.molnarandrei.sopa.wsdl.WsdlValidations;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Against the WSDL of the bundled test server. */
|
||||
public class SoapAssertionsTest {
|
||||
private static final String SCHOOL = "http://sopa.molnarandrei.com/school";
|
||||
private static final String GET_CLASSROOM = envelope(WsdlValidations.SOAP_11_NS,
|
||||
"<GetClassroom xmlns='%s'><id>1</id></GetClassroom>".formatted(SCHOOL));
|
||||
private static final String VALID_RESPONSE = classroomResponse("<id>1</id><name>A</name>");
|
||||
|
||||
private static final String ENDPOINT = "http://localhost:8080/school";
|
||||
|
||||
@TempDir
|
||||
Path folder;
|
||||
Path projectPath;
|
||||
|
||||
@BeforeEach
|
||||
public void storeWsdl() throws Exception {
|
||||
projectPath = folder.resolve("project.yml");
|
||||
var wsdl = com.molnarandrei.sopa.server.Wsdl.build("http://localhost:8080");
|
||||
WsdlRepository.update(projectPath, ENDPOINT, new WsdlRemote.Download(wsdl, List.of(), List.of()));
|
||||
}
|
||||
|
||||
private static String envelope(String namespace, String content) {
|
||||
return "<s:Envelope xmlns:s='%s'><s:Body>%s</s:Body></s:Envelope>".formatted(namespace, content);
|
||||
}
|
||||
|
||||
private static String classroomResponse(String classroom) {
|
||||
return envelope(WsdlValidations.SOAP_11_NS,
|
||||
"<GetClassroomResponse xmlns='%s'><classroom>%s</classroom></GetClassroomResponse>".formatted(SCHOOL, classroom));
|
||||
}
|
||||
|
||||
private List<String> validate(String response) throws Exception {
|
||||
return WsdlValidations.responseErrors(projectPath, ENDPOINT, SoapVersion.ONE_ONE, GET_CLASSROOM, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptsTheDeclaredResponse() throws Exception {
|
||||
assertEquals(List.of(), validate(VALID_RESPONSE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsWrongTypesAndMissingElements() throws Exception {
|
||||
assertFalse(validate(classroomResponse("<id>abc</id><name>A</name>")).isEmpty());
|
||||
assertFalse(validate(classroomResponse("<id>1</id>")).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsTheResponseOfAnotherOperation() throws Exception {
|
||||
var other = envelope(WsdlValidations.SOAP_11_NS,
|
||||
"<DeleteAlumnusResponse xmlns='%s'><deleted>true</deleted></DeleteAlumnusResponse>".formatted(SCHOOL));
|
||||
assertEquals(1, validate(other).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsWhatIsNotAnEnvelopeOfTheVersion() throws Exception {
|
||||
assertFalse(validate("plain text").isEmpty());
|
||||
assertFalse(validate("<other/>").isEmpty());
|
||||
assertFalse(validate("<s:Envelope xmlns:s='%s'/>".formatted(WsdlValidations.SOAP_11_NS)).isEmpty());
|
||||
assertFalse(WsdlValidations.responseErrors(projectPath, ENDPOINT, SoapVersion.ONE_TWO, GET_CLASSROOM, VALID_RESPONSE).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unknownElementsAreRejectedWhenTheRequestIsNotInTheWsdl() throws Exception {
|
||||
var unknown = envelope(WsdlValidations.SOAP_11_NS, "<Nope xmlns='urn:nope'/>");
|
||||
assertEquals(1, WsdlValidations.responseErrors(projectPath, ENDPOINT, SoapVersion.ONE_ONE, "<not-soap/>", unknown).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aFaultIsValid() throws Exception {
|
||||
assertEquals(List.of(), validate(fault11("soap:Client")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validatesAgainstImportedSchemas() throws Exception {
|
||||
var wsdl = """
|
||||
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
xmlns:a="urn:a" xmlns:b="urn:b" targetNamespace="urn:a">
|
||||
<wsdl:types>
|
||||
<xs:schema targetNamespace="urn:a" elementFormDefault="qualified">
|
||||
<xs:import namespace="urn:b" schemaLocation="http://elsewhere.invalid/b.xsd"/>
|
||||
<xs:element name="Out"><xs:complexType><xs:sequence>
|
||||
<xs:element name="n" type="b:Age"/>
|
||||
</xs:sequence></xs:complexType></xs:element>
|
||||
</xs:schema>
|
||||
</wsdl:types>
|
||||
</wsdl:definitions>""";
|
||||
var imported = """
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:b">
|
||||
<xs:simpleType name="Age"><xs:restriction base="xs:int"/></xs:simpleType>
|
||||
</xs:schema>""";
|
||||
WsdlRepository.update(projectPath, ENDPOINT, new WsdlRemote.Download(wsdl, List.of(imported), List.of()));
|
||||
|
||||
assertEquals(List.of(), validate(envelope(WsdlValidations.SOAP_11_NS, "<Out xmlns='urn:a'><n>3</n></Out>")));
|
||||
assertFalse(validate(envelope(WsdlValidations.SOAP_11_NS, "<Out xmlns='urn:a'><n>x</n></Out>")).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aRefreshedWsdlIsUsed() throws Exception {
|
||||
assertEquals(List.of(), validate(VALID_RESPONSE));
|
||||
var wsdl = WsdlRepository.get(projectPath, ENDPOINT).wsdl();
|
||||
WsdlRepository.update(projectPath, ENDPOINT, new WsdlRemote.Download(wsdl.replace("name=\"GetClassroomResponse\"", "name=\"Renamed\""), List.of(), List.of()));
|
||||
assertFalse(validate(VALID_RESPONSE).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noWsdlCannotBeEvaluated() {
|
||||
assertThrows(Exception.class, () ->
|
||||
WsdlValidations.responseErrors(folder.resolve("none/project.yml"), ENDPOINT, SoapVersion.ONE_ONE, GET_CLASSROOM, VALID_RESPONSE));
|
||||
}
|
||||
|
||||
private static String fault11(String code) {
|
||||
return envelope(WsdlValidations.SOAP_11_NS,
|
||||
"<s:Fault><faultcode>%s</faultcode><faultstring>nope</faultstring></s:Fault>".formatted(code));
|
||||
}
|
||||
|
||||
private static String fault12(String code) {
|
||||
return envelope(WsdlValidations.SOAP_12_NS, "<s:Fault><s:Code><s:Value>%s</s:Value></s:Code></s:Fault>".formatted(code));
|
||||
}
|
||||
|
||||
private Boolean check(Type type, String value, String body) {
|
||||
var call = Mockito.mock(SoapCall.class);
|
||||
call.version = SoapVersion.ONE_ONE;
|
||||
call.payload = GET_CLASSROOM;
|
||||
Mockito.when(call.getProjectPath()).thenReturn(projectPath);
|
||||
Mockito.when(call.getEndpointTemplate()).thenReturn(ENDPOINT);
|
||||
@SuppressWarnings("unchecked")
|
||||
HttpResponse<String> response = Mockito.mock(HttpResponse.class);
|
||||
Mockito.when(response.body()).thenReturn(body);
|
||||
return SoapJob.checkAssertion(call, new Assertion(type, value, ""), response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checksEachAssertionType() {
|
||||
assertTrue(check(Type.validPerWsdl, "", VALID_RESPONSE));
|
||||
assertFalse(check(Type.validPerWsdl, "", classroomResponse("<id>x</id><name>A</name>")));
|
||||
|
||||
assertTrue(check(Type.notSoapFault, "", VALID_RESPONSE));
|
||||
assertFalse(check(Type.notSoapFault, "", fault11("soap:Client")));
|
||||
assertFalse(check(Type.notSoapFault, "", fault12("env:Sender")));
|
||||
|
||||
assertFalse(check(Type.soapFault, "", VALID_RESPONSE));
|
||||
assertTrue(check(Type.soapFault, "", fault11("soap:Client")));
|
||||
assertTrue(check(Type.soapFault, "Client", fault11("soap:Client")));
|
||||
assertFalse(check(Type.soapFault, "Server", fault11("soap:Client")));
|
||||
assertTrue(check(Type.soapFault, "Sender", fault12("env:Sender")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package com.molnarandrei.sopa.soap;
|
||||
|
||||
import com.molnarandrei.sopa.data.yaml.Assertion;
|
||||
import com.molnarandrei.sopa.data.yaml.Project;
|
||||
import com.molnarandrei.sopa.data.yaml.Step;
|
||||
import com.molnarandrei.sopa.data.yaml.TestCase;
|
||||
import com.molnarandrei.sopa.project.ProjectRepository;
|
||||
import com.molnarandrei.sopa.step.StepRepository;
|
||||
import com.molnarandrei.sopa.testcase.TestCaseRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
|
||||
public class SoapCallTest {
|
||||
|
||||
@Test
|
||||
public void simpleCallWithoutOverwrites() throws Exception {
|
||||
var stepPath = Path.of("/proj/case/step-1/step.yml");
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
var testcasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
|
||||
var project = new Project(
|
||||
"Demo Project",
|
||||
List.of("http://project.example/soap"),
|
||||
Map.of("X-Project", "p"),
|
||||
Map.of("user", "alice")
|
||||
);
|
||||
var testcase = new TestCase(
|
||||
"Demo Case", true, "http://example.com/soap", "urn:simpleAction",
|
||||
Map.of("X-Case", "c"),
|
||||
Map.of()
|
||||
);
|
||||
var step = new Step("Demo Step");
|
||||
step.setEndpoint("");
|
||||
step.setAction("");
|
||||
step.setPayload("<request>{user}</request>");
|
||||
step.getHeaders().put("X-Step", "s");
|
||||
|
||||
try (
|
||||
var stepMock = Mockito.mockStatic(StepRepository.class);
|
||||
var caseMock = Mockito.mockStatic(TestCaseRepository.class);
|
||||
var projectMock = Mockito.mockStatic(ProjectRepository.class)
|
||||
) {
|
||||
stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
|
||||
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
|
||||
projectMock.when(() -> ProjectRepository.get(eq(projectPath))).thenReturn(project);
|
||||
|
||||
var call = new SoapCall(stepPath);
|
||||
call.applyProperties();
|
||||
|
||||
assertEquals("http://example.com/soap", call.endpoint);
|
||||
assertEquals("<request>alice</request>", call.payload);
|
||||
assertEquals("alice", call.properties.get("user"));
|
||||
assertEquals("urn:simpleAction", call.action);
|
||||
|
||||
// Headers from all levels are present when there is no conflict.
|
||||
assertEquals("p", call.headers.get("X-Project"));
|
||||
assertEquals("c", call.headers.get("X-Case"));
|
||||
assertEquals("s", call.headers.get("X-Step"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void complexCallWithOverwrites() throws Exception {
|
||||
var stepPath = Path.of("/proj/case/step-1/step.yml");
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
var testcasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
|
||||
var project = new Project(
|
||||
"P",
|
||||
List.of("http://project.example/soap"),
|
||||
Map.of(
|
||||
"X-Shared", "project-header",
|
||||
"X-Project", "project-header"
|
||||
),
|
||||
Map.of(
|
||||
"shared", "project-value",
|
||||
"projectOnly", "project-value"
|
||||
)
|
||||
);
|
||||
var testcase = new TestCase(
|
||||
"C", true,
|
||||
"http://case.example/soap",
|
||||
"urn:caseAction",
|
||||
Map.of(
|
||||
"X-Shared", "case-header",
|
||||
"X-Case", "case-header"
|
||||
),
|
||||
Map.of(
|
||||
"shared", "case-value",
|
||||
"caseOnly", "case-value"
|
||||
)
|
||||
);
|
||||
var step = new Step("S");
|
||||
step.setEndpoint("http://step.example/soap");
|
||||
step.setAction("");
|
||||
step.setPayload("<request>{shared}|{caseOnly}|{projectOnly}</request>");
|
||||
step.getHeaders().put("X-Shared", "step-header");
|
||||
step.getHeaders().put("X-Step", "step-header");
|
||||
|
||||
try (
|
||||
var stepMock = Mockito.mockStatic(StepRepository.class);
|
||||
var caseMock = Mockito.mockStatic(TestCaseRepository.class);
|
||||
var projectMock = Mockito.mockStatic(ProjectRepository.class)
|
||||
) {
|
||||
stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
|
||||
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
|
||||
projectMock.when(() -> ProjectRepository.get(eq(projectPath))).thenReturn(project);
|
||||
|
||||
var call = new SoapCall(stepPath);
|
||||
call.applyProperties();
|
||||
|
||||
// Properties required from case are present when provided.
|
||||
assertEquals("case-value", call.properties.get("caseOnly"));
|
||||
assertTrue(call.payload.contains("case-value"));
|
||||
|
||||
// Shared property resolves to testcase value, not project value.
|
||||
assertEquals("case-value", call.properties.get("shared"));
|
||||
assertNotEquals("project-value", call.properties.get("shared"));
|
||||
|
||||
// Full payload substitution proves both cases above.
|
||||
assertEquals(
|
||||
"<request>case-value|case-value|project-value</request>",
|
||||
call.payload
|
||||
);
|
||||
|
||||
// Endpoint defaults to most specific object present:
|
||||
// project -> testcase -> step, so step wins.
|
||||
assertEquals("http://step.example/soap", call.endpoint);
|
||||
assertNotEquals("http://project.example/soap", call.endpoint);
|
||||
assertNotEquals("http://case.example/soap", call.endpoint);
|
||||
|
||||
// Headers follow the same project -> testcase -> step precedence.
|
||||
assertEquals("step-header", call.headers.get("X-Shared"));
|
||||
assertEquals("project-header", call.headers.get("X-Project"));
|
||||
assertEquals("case-header", call.headers.get("X-Case"));
|
||||
assertEquals("step-header", call.headers.get("X-Step"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertionsUsePropertiesWithoutChangingTheStep() throws Exception {
|
||||
var stepPath = Path.of("/proj/case/step-1/step.yml");
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
var testcasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
|
||||
var project = new Project("P", List.of("http://example.com/soap"), Map.of(), Map.of("element", "id"));
|
||||
var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of(), Map.of("alumnusId", "17"));
|
||||
var step = new Step("S");
|
||||
step.setPayload("<request/>");
|
||||
step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{alumnusId}", "//*[local-name()='{element}']"));
|
||||
step.getAssertions().add(new Assertion(Assertion.Type.contains, "Alumnus {alumnusId} not found", ""));
|
||||
step.getAssertions().add(new Assertion(Assertion.Type.regex, "", "<id>{alumnusId}</id>\\d{2}x{1,}y{2,5}"));
|
||||
|
||||
try (
|
||||
var stepMock = Mockito.mockStatic(StepRepository.class);
|
||||
var caseMock = Mockito.mockStatic(TestCaseRepository.class);
|
||||
var projectMock = Mockito.mockStatic(ProjectRepository.class)
|
||||
) {
|
||||
stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
|
||||
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
|
||||
projectMock.when(() -> ProjectRepository.get(eq(projectPath))).thenReturn(project);
|
||||
|
||||
var call = new SoapCall(stepPath);
|
||||
call.applyProperties();
|
||||
var assertions = call.getAssertions();
|
||||
|
||||
assertEquals("17", assertions.get(0).getValue());
|
||||
assertEquals("//*[local-name()='id']", assertions.get(0).getExpression());
|
||||
assertEquals("Alumnus 17 not found", assertions.get(1).getValue());
|
||||
// Regex quantifiers are kept, properties are still applied.
|
||||
assertEquals("<id>17</id>\\d{2}x{1,}y{2,5}", assertions.get(2).getExpression());
|
||||
|
||||
// The step keeps its placeholders for the next run.
|
||||
assertEquals("{alumnusId}", step.getAssertions().get(0).getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assertionWithMissingPropertyFails() throws Exception {
|
||||
var stepPath = Path.of("/proj/case/step-1/step.yml");
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
var testcasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
|
||||
var project = new Project("P", List.of("http://example.com/soap"), Map.of(), Map.of());
|
||||
var testcase = new TestCase("C", true, "http://example.com/soap", "urn:a", Map.of(), Map.of());
|
||||
var step = new Step("S");
|
||||
step.setPayload("<request/>");
|
||||
step.getAssertions().add(new Assertion(Assertion.Type.xPath, "{nope}", "//id"));
|
||||
|
||||
try (
|
||||
var stepMock = Mockito.mockStatic(StepRepository.class);
|
||||
var caseMock = Mockito.mockStatic(TestCaseRepository.class);
|
||||
var projectMock = Mockito.mockStatic(ProjectRepository.class)
|
||||
) {
|
||||
stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
|
||||
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
|
||||
projectMock.when(() -> ProjectRepository.get(eq(projectPath))).thenReturn(project);
|
||||
|
||||
var missing = assertThrows(PropertyMissingException.class, new SoapCall(stepPath)::applyProperties);
|
||||
assertEquals("nope", missing.getMissingKey());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void versionIsThatOfTheProjectEndpointOfTheCall() throws Exception {
|
||||
var stepPath = Path.of("/proj/case/step-1/step.yml");
|
||||
var testCaseFolderPath = stepPath.getParent().getParent();
|
||||
var testcasePath = testCaseFolderPath.resolve("testcase.yml");
|
||||
var projectPath = testCaseFolderPath.getParent().resolve("project.yml");
|
||||
|
||||
var project = new Project("P", List.of());
|
||||
project.putEndpoint("http://{host}/v11", SoapVersion.ONE_ONE);
|
||||
project.putEndpoint("http://{host}/v12", SoapVersion.ONE_TWO);
|
||||
var testcase = new TestCase("C", true, "http://{host}/v12", "urn:a", Map.of(), Map.of());
|
||||
var step = new Step("S");
|
||||
step.setPayload("<request/>");
|
||||
|
||||
try (
|
||||
var stepMock = Mockito.mockStatic(StepRepository.class);
|
||||
var caseMock = Mockito.mockStatic(TestCaseRepository.class);
|
||||
var projectMock = Mockito.mockStatic(ProjectRepository.class)
|
||||
) {
|
||||
stepMock.when(() -> StepRepository.get(eq(stepPath))).thenReturn(step);
|
||||
caseMock.when(() -> TestCaseRepository.get(eq(testcasePath))).thenReturn(testcase);
|
||||
projectMock.when(() -> ProjectRepository.get(eq(projectPath))).thenReturn(project);
|
||||
|
||||
assertEquals(SoapVersion.ONE_TWO, new SoapCall(stepPath).version);
|
||||
step.setEndpoint("http://{host}/v11");
|
||||
assertEquals(SoapVersion.ONE_ONE, new SoapCall(stepPath).version);
|
||||
step.setEndpoint("http://elsewhere/soap");
|
||||
assertEquals(SoapVersion.ONE_ONE, new SoapCall(stepPath).version);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.molnarandrei.sopa.step;
|
||||
|
||||
import com.molnarandrei.sopa.data.RepositoryException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class StepRepositoryMoveTest {
|
||||
|
||||
@TempDir
|
||||
Path project;
|
||||
|
||||
@Test
|
||||
public void movesStepFolderBehindTheStepsOfTheTargetTestcase() throws Exception {
|
||||
var from = testcase("test-case-a");
|
||||
var to = testcase("test-case-b");
|
||||
step(from, "step-1", "the moved one");
|
||||
step(from, "step-2", "stays behind");
|
||||
step(to, "step-1", "b one");
|
||||
step(to, "step-3", "b three");
|
||||
|
||||
StepRepository.move(from.resolve("step-1/step.yml"), to.resolve("testcase.yml"));
|
||||
|
||||
// The source index must not decide where it lands: step-2 was free and would have
|
||||
// dropped it in the middle of the target steps.
|
||||
assertEquals(List.of("step-1", "step-3", "step-4"), stepFolders(to));
|
||||
assertEquals(List.of("step-2"), stepFolders(from));
|
||||
assertEquals("the moved one", Files.readString(to.resolve("step-4/step.yml")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void movesResponsesAlongWithTheStepFolder() throws Exception {
|
||||
var from = testcase("test-case-a");
|
||||
var to = testcase("test-case-b");
|
||||
var moved = step(from, "step-1", "body");
|
||||
Files.writeString(moved.getParent().resolve("response-2026-10-23T10:00:00.00000.yml"), "response");
|
||||
|
||||
StepRepository.move(moved, to.resolve("testcase.yml"));
|
||||
|
||||
assertEquals(
|
||||
List.of("response-2026-10-23T10:00:00.00000.yml", "step.yml"),
|
||||
filesOf(to.resolve("step-1"))
|
||||
);
|
||||
assertFalse(Files.exists(from.resolve("step-1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void appendsToTheEndOfItsOwnTestcase() throws Exception {
|
||||
var testCase = testcase("test-case-a");
|
||||
step(testCase, "step-1", "one");
|
||||
step(testCase, "step-2", "two");
|
||||
step(testCase, "step-3", "three");
|
||||
|
||||
StepRepository.move(testCase.resolve("step-1/step.yml"), testCase.resolve("testcase.yml"));
|
||||
|
||||
assertEquals(List.of("step-2", "step-3", "step-4"), stepFolders(testCase));
|
||||
assertEquals("one", Files.readString(testCase.resolve("step-4/step.yml")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keepsTheLastStepOfItsOwnTestcaseInPlace() throws Exception {
|
||||
var testCase = testcase("test-case-a");
|
||||
step(testCase, "step-1", "one");
|
||||
step(testCase, "step-2", "two");
|
||||
|
||||
StepRepository.move(testCase.resolve("step-2/step.yml"), testCase.resolve("testcase.yml"));
|
||||
|
||||
assertEquals(List.of("step-1", "step-2"), stepFolders(testCase));
|
||||
assertEquals("two", Files.readString(testCase.resolve("step-2/step.yml")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void movesIntoAnEmptyTestcase() throws Exception {
|
||||
var from = testcase("test-case-a");
|
||||
var to = testcase("test-case-b");
|
||||
step(from, "step-1", "only");
|
||||
|
||||
StepRepository.move(from.resolve("step-1/step.yml"), to.resolve("testcase.yml"));
|
||||
|
||||
assertEquals(List.of("step-1"), stepFolders(to));
|
||||
assertEquals(List.of(), stepFolders(from));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refusesToMoveAnythingButAStepFile() throws Exception {
|
||||
var from = testcase("test-case-a");
|
||||
var to = testcase("test-case-b");
|
||||
step(from, "step-1", "one");
|
||||
|
||||
assertThrows(RepositoryException.class, () ->
|
||||
StepRepository.move(from.resolve("testcase.yml"), to.resolve("testcase.yml")));
|
||||
|
||||
// The old code took the parent of whatever it was given and would have moved the
|
||||
// whole testcase directory into the target testcase.
|
||||
assertEquals(List.of("test-case-a", "test-case-b"), directoryNames());
|
||||
assertEquals(List.of("step-1"), stepFolders(from));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refusesToMoveIntoAMissingTestcase() throws Exception {
|
||||
var from = testcase("test-case-a");
|
||||
step(from, "step-1", "one");
|
||||
|
||||
assertThrows(RepositoryException.class, () ->
|
||||
StepRepository.move(from.resolve("step-1/step.yml"), project.resolve("gone/testcase.yml")));
|
||||
|
||||
assertEquals(List.of("step-1"), stepFolders(from));
|
||||
}
|
||||
|
||||
private Path testcase(String name) throws IOException {
|
||||
var directory = project.resolve(name);
|
||||
Files.createDirectories(directory);
|
||||
Files.writeString(directory.resolve("testcase.yml"), "name: %s".formatted(name));
|
||||
return directory;
|
||||
}
|
||||
|
||||
private Path step(Path testcase, String folder, String content) throws IOException {
|
||||
var directory = testcase.resolve(folder);
|
||||
Files.createDirectories(directory);
|
||||
var stepFile = directory.resolve("step.yml");
|
||||
Files.writeString(stepFile, content);
|
||||
return stepFile;
|
||||
}
|
||||
|
||||
private List<String> stepFolders(Path testcase) throws IOException {
|
||||
return filesOf(testcase).stream()
|
||||
.filter(name -> Files.isDirectory(testcase.resolve(name)))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<String> filesOf(Path directory) throws IOException {
|
||||
try (var entries = Files.list(directory)) {
|
||||
return entries
|
||||
.map(entry -> entry.getFileName().toString())
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> directoryNames() throws IOException {
|
||||
return stepFolders(project);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user