list) {
+ var sb = new StringBuilder();
+ list.forEach(a -> sb.append(alumnus(a)));
+ return sb.toString();
+ }
+
+ private static String alumnus(Alumnus a) {
+ return "" + a.id() + "" + a.classroomId()
+ + "" + esc(a.name()) + "" + a.age() + "";
+ }
+
+ static String esc(String s) {
+ return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """);
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/server/SoapFault.java b/src/main/java/com/molnarandrei/sopa/server/SoapFault.java
new file mode 100644
index 0000000..0067970
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/server/SoapFault.java
@@ -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;
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/server/TestServer.java b/src/main/java/com/molnarandrei/sopa/server/TestServer.java
new file mode 100644
index 0000000..ae606b7
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/server/TestServer.java
@@ -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)
+ *
+ * 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 ""
+ + ""
+ + (headerContent.isEmpty() ? "" : "" + headerContent + "")
+ + "" + bodyContent + "";
+ }
+
+ /**
+ * 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 ""
+ + ""
+ + "";
+ }
+
+ 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 "" + code + "" + msg + "";
+ }
+ String code = switch (f.getCode()) {
+ case CLIENT -> "soap:Sender";
+ case SERVER -> "soap:Receiver";
+ case VERSION_MISMATCH -> "soap:VersionMismatch";
+ };
+ return "" + code + ""
+ + "" + msg + "";
+ }
+
+ /** 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);
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/server/Wsdl.java b/src/main/java/com/molnarandrei/sopa/server/Wsdl.java
new file mode 100644
index 0000000..82ba513
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/server/Wsdl.java
@@ -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.
+ *
+ * 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 = """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """;
+
+ /** 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("""
+
+
+ """.formatted(NS));
+ sb.append(TYPES.formatted(NS));
+
+ for (String op : OPERATIONS) {
+ sb.append("""
+
+
+ """.formatted(op));
+ }
+
+ sb.append(" \n");
+ for (String op : OPERATIONS) {
+ sb.append("""
+
+
+
+
+ """.formatted(op));
+ }
+ sb.append(" \n");
+
+ if (soap11) appendBinding(sb, "soap", "SchoolSoap11Binding", "");
+ if (soap12) appendBinding(sb, "soap12", "SchoolSoap12Binding", " soapActionRequired=\"false\"");
+
+ sb.append(" \n");
+ if (soap11) sb.append("""
+
+
+
+ """.formatted(baseUrl));
+ if (soap12) sb.append("""
+
+
+
+ """.formatted(baseUrl));
+ sb.append(" \n\n");
+ return sb.toString();
+ }
+
+ private static void appendBinding(StringBuilder sb, String prefix, String name, String extraOpAttrs) {
+ sb.append("""
+
+ <%1$s:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
+ """.formatted(prefix, name));
+ for (String op : OPERATIONS) {
+ sb.append("""
+
+ <%1$s:operation soapAction="%3$s/%2$s"%4$s/>
+ <%1$s:body use="literal"/>
+ <%1$s:body use="literal"/>
+
+ """.formatted(prefix, op, NS, extraOpAttrs));
+ }
+ sb.append(" \n");
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/CallInitializationException.java b/src/main/java/com/molnarandrei/sopa/soap/CallInitializationException.java
new file mode 100644
index 0000000..1d74e58
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/CallInitializationException.java
@@ -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;
+ }
+
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/MalformedEndpointException.java b/src/main/java/com/molnarandrei/sopa/soap/MalformedEndpointException.java
new file mode 100644
index 0000000..5c7ec10
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/MalformedEndpointException.java
@@ -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;
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/PropertyMissingException.java b/src/main/java/com/molnarandrei/sopa/soap/PropertyMissingException.java
new file mode 100644
index 0000000..07d9afa
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/PropertyMissingException.java
@@ -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;
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/RawSoapCall.java b/src/main/java/com/molnarandrei/sopa/soap/RawSoapCall.java
new file mode 100644
index 0000000..65bff08
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/RawSoapCall.java
@@ -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 headers = new HashMap<>();
+ protected String payload = "";
+
+ public HttpResponse 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;
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java b/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java
new file mode 100644
index 0000000..3ccb743
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/SoapCall.java
@@ -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 extractions;
+ protected List assertions;
+ protected Map properties;
+
+ private final String endpointTemplate;
+ private final String payloadTemplate;
+ private final Map headerTemplates;
+ private final List 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();
+ 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 applyPropertiesToAssertions(List stepAssertions) throws PropertyMissingException {
+ var resolved = new ArrayList(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 properties) throws PropertyMissingException {
+ return applyProperties(input, properties, false);
+ }
+
+ private static String applyProperties(
+ String input, Map 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 getExtractions() {
+ return extractions;
+ }
+
+ public List getAssertions() {
+ return assertions;
+ }
+
+
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java b/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java
new file mode 100644
index 0000000..e806d95
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/SoapJob.java
@@ -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 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 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 httpResponse) {
+ var extractions = call.getExtractions();
+ if (extractions.isEmpty()) return true;
+
+ var extracted = new HashMap();
+ 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 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 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 wsdlErrors(SoapCall call, String body) throws Exception {
+ return WsdlValidations.responseErrors(call.getProjectPath(), call.getEndpointTemplate(), call.version, call.payload, body);
+ }
+
+ public static List 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 childElements(Element parent) {
+ var elements = new ArrayList();
+ 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();
+ 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 getPrefixes(String uri) {
+ return null;
+ }
+ });
+ return (String) xpath.evaluate(expression, document, XPathConstants.STRING);
+ }
+
+ private static void collectNamespaces(Element element, Map 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);
+ }
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapService.java b/src/main/java/com/molnarandrei/sopa/soap/SoapService.java
new file mode 100644
index 0000000..2c509d8
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/SoapService.java
@@ -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 currentlyRunningJobsByPath = new ConcurrentHashMap<>();
+
+ public static void createAndStartStepCalls(Iterable 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()
+ );
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/soap/SoapVersion.java b/src/main/java/com/molnarandrei/sopa/soap/SoapVersion.java
new file mode 100644
index 0000000..71bdecd
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/soap/SoapVersion.java
@@ -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));
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/step/StepRepository.java b/src/main/java/com/molnarandrei/sopa/step/StepRepository.java
new file mode 100644
index 0000000..34924a4
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/step/StepRepository.java
@@ -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(allSteps);
+ orderedSteps.add(shiftIndex, fromStepPath);
+
+ var shifting = new LinkedHashMap();
+ 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();
+ 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());
+ }
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/step/StepService.java b/src/main/java/com/molnarandrei/sopa/step/StepService.java
new file mode 100644
index 0000000..eddc900
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/step/StepService.java
@@ -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()
+ );
+ }
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java
new file mode 100644
index 0000000..e7e1f78
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseRepository.java
@@ -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 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());
+ }
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java
new file mode 100644
index 0000000..b5180c0
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/testcase/TestCaseService.java
@@ -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 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()
+ );
+ }
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/trash/TrashService.java b/src/main/java/com/molnarandrei/sopa/trash/TrashService.java
new file mode 100644
index 0000000..6d6df86
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/trash/TrashService.java
@@ -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 = 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;
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java b/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java
new file mode 100644
index 0000000..83ce8cd
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/PropertiesDialog.java
@@ -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 rows = new ArrayList<>();
+
+ private record Row(TextField key, TextField value, Button remove) {}
+
+ private final EventHandler selectionHandler = this::onSelection;
+ private final EventHandler 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();
+ 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 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();
+ 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 testCaseProperties = testCase == null ? null : testCase.getProperties();
+ if (testCase != null && testCaseProperties == null) {
+ testCaseProperties = new HashMap<>();
+ testCase.setProperties(testCaseProperties);
+ }
+
+ var newProject = new HashMap();
+ var newTestCase = new HashMap();
+ 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);
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java b/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java
new file mode 100644
index 0000000..7174199
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/SopaApplication.java
@@ -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 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()));
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java b/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java
new file mode 100644
index 0000000..6d3e965
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/create/CreateProjectDialog.java
@@ -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 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);
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/Destroyable.java b/src/main/java/com/molnarandrei/sopa/ui/editor/Destroyable.java
new file mode 100644
index 0000000..4b9a835
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/Destroyable.java
@@ -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();
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java
new file mode 100644
index 0000000..b6264b7
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/EditorPane.java
@@ -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);
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointWsdl.java b/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointWsdl.java
new file mode 100644
index 0000000..6c1fe38
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointWsdl.java
@@ -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 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 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();
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java
new file mode 100644
index 0000000..f86e99f
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/EndpointsPane.java
@@ -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 endpoints;
+ private final Runnable onSubmit;
+ private final GridPane endpointsGrid;
+ private final List 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 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 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()));
+ }
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java
new file mode 100644
index 0000000..476c2b4
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/HeadersPane.java
@@ -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 headers = Map.of();
+ Map inherited = Map.of();
+ private final Runnable onSubmit;
+
+ /**
+ * @param onSubmit called when enter is pressed on any header field.
+ */
+ public HeadersPane(Map 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 inherited) {
+ this.inherited = inherited;
+ update();
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java
new file mode 100644
index 0000000..dd2ee54
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/ProjectEditorPane.java
@@ -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() {
+ }
+}
diff --git a/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java b/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java
new file mode 100644
index 0000000..a01c0fe
--- /dev/null
+++ b/src/main/java/com/molnarandrei/sopa/ui/editor/TestCaseEditorPane.java
@@ -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