diff --git a/api/src/main/java/org/eclipse/daanse/xmla/api/RowStream.java b/api/src/main/java/org/eclipse/daanse/xmla/api/RowStream.java new file mode 100644 index 0000000..9866d0b --- /dev/null +++ b/api/src/main/java/org/eclipse/daanse/xmla/api/RowStream.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.api; + +import java.util.Iterator; +import java.util.List; + +/** + * An Execute result written row by row as the rows come, not at once -- what {@code Subscribe} to a trace answers: an + * open rowset, one row for each event, until the subscription ends. + *

+ * The transport writes the envelope and the inline schema at once, then each row as {@link #rows()} gives it, + * flushing after each, and closes the document when the iterator ends. {@code hasNext()} may block while no row is + * there. The transport closes the stream when it has written the last row or cannot write any more because the client + * is gone. + *

+ * A column has the name a client reads it by, as {@code sql:field}, and a short element name of its own, as Analysis + * Services writes a trace's rows: {@code 106SELECT …} under + * {@code }. + */ +public abstract class RowStream extends org.eclipse.emf.ecore.impl.MinimalEObjectImpl.Container + implements AutoCloseable { + + /** + * One column of the rows. + * + * @param field the name a client reads the column by + * @param name the element name of its values + * @param xsdType its type, e.g. {@code xsd:int}; {@code null} for none + */ + public record Column(String field, String name, String xsdType) { + } + + /** The columns, in the order the rows hold their values. */ + public abstract List columns(); + + /** The rows, each a value per column, {@code null} for one it does not have; {@code hasNext()} may block. */ + public abstract Iterator> rows(); + + /** Ends what the stream reads from; called once the transport has written its last row. */ + @Override + public void close() { + // nothing held by default + } +} diff --git a/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaRefusedException.java b/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaRefusedException.java index ff10874..d0eab05 100644 --- a/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaRefusedException.java +++ b/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaRefusedException.java @@ -32,11 +32,50 @@ public enum Side { CLIENT, SERVER } + /** + * One error of a refusal, as the fault's {@code detail} lists it. + * + * @param code the unsigned 32-bit number Analysis Services gives it + * @param description its sentence + */ + public record Error(long code, String description) { + } + private final Side side; + private final java.util.List errors; + + /** A refusal this server has no Analysis Services number for: the fault then carries no {@code Error} element. */ public XmlaRefusedException(Side side, String message) { + this(side, null, message); + } + + /** + * A refusal with the number Analysis Services answers the same refusal with. + *

+ * The number is what the client sees as {@code ErrorCode}, and the transport writes the fault code in the form + * SSAS uses for it, {@code XMLAnalysisError.0x}. Only the number Analysis Services gives the same refusal + * belongs here; a refusal it has no number for keeps the other constructor rather than an invented code. + * + * @param errorCode the unsigned 32-bit number, e.g. {@code 0xC1140002L}; {@code null} for none + */ + public XmlaRefusedException(Side side, Long errorCode, String message) { super(message); this.side = side; + this.errors = errorCode == null ? java.util.List.of() : java.util.List.of(new Error(errorCode, message)); + } + + /** + * A refusal Analysis Services answers with several errors -- an event number it does not know is a range error and + * then a parse error naming where the number stood. The fault lists them in this order; its code and its + * {@code faultstring} are the last one's, as there. + * + * @param errors at least one + */ + public XmlaRefusedException(Side side, java.util.List errors) { + super(errors.getLast().description()); + this.side = side; + this.errors = java.util.List.copyOf(errors); } /** @@ -73,4 +112,17 @@ public static XmlaRefusedException sessionNotOpened() { public Side side() { return side; } + + /** + * The Analysis Services number of this refusal -- of its last error where it has several -- or {@code null} when + * this server has none for it. + */ + public Long errorCode() { + return errors.isEmpty() ? null : errors.getLast().code(); + } + + /** The errors of this refusal in the order the fault lists them; none when this server has no number for it. */ + public java.util.List errors() { + return errors; + } } diff --git a/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaSession.java b/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaSession.java index 6a8b621..5632c65 100644 --- a/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaSession.java +++ b/api/src/main/java/org/eclipse/daanse/xmla/api/XmlaSession.java @@ -37,6 +37,7 @@ public final class XmlaSession { private volatile Instant lastUsedAt; private volatile Instant lastCommandStartedAt; private volatile Instant lastCommandEndedAt; + private volatile String lastCommand; private volatile AuthenticatedIdentity identity; XmlaSession(String id, Instant startedAt) { @@ -66,6 +67,14 @@ public Optional lastCommandEndedAt() { return Optional.ofNullable(lastCommandEndedAt); } + /** + * The text of the command the session ran last, or runs now: a statement as written, the request type of a + * Discover, the name of any other command -- what {@code SESSION_LAST_COMMAND} and {@code COMMAND_TEXT} report. + */ + public Optional lastCommand() { + return Optional.ofNullable(lastCommand); + } + /** * The identity the in-band handshake bound, or empty for a session that carries * none. @@ -94,8 +103,15 @@ void identity(AuthenticatedIdentity bound) { this.identity = bound; } + /** A command begins in the session; its text is not known. */ public void commandStarted() { + commandStarted(null); + } + + /** A command of this text begins in the session. */ + public void commandStarted(String text) { Instant now = Instant.now(); + lastCommand = text; lastCommandStartedAt = now; lastUsedAt = now; commandCount.incrementAndGet(); diff --git a/api/src/test/java/org/eclipse/daanse/xmla/api/SessionIdentityTest.java b/api/src/test/java/org/eclipse/daanse/xmla/api/SessionIdentityTest.java index 1af7557..d1dc2b7 100644 --- a/api/src/test/java/org/eclipse/daanse/xmla/api/SessionIdentityTest.java +++ b/api/src/test/java/org/eclipse/daanse/xmla/api/SessionIdentityTest.java @@ -170,9 +170,11 @@ void aSessionReportsWhatDiscoverSessionsAsksFor() { assertThat(session.busy()).isFalse(); assertThat(session.idle(session.startedAt())).isZero(); - session.commandStarted(); + assertThat(session.lastCommand()).isEmpty(); + session.commandStarted("SELECT FROM [Sales]"); assertThat(session.busy()).isTrue(); assertThat(session.commandCount()).isEqualTo(1); + assertThat(session.lastCommand()).contains("SELECT FROM [Sales]"); session.commandEnded(); assertThat(session.busy()).isFalse(); diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlReader.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlReader.java index eefc2ea..e067c10 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlReader.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlReader.java @@ -70,9 +70,32 @@ public enum Unknown { private static final Map> ATTRIBUTES = new ConcurrentHashMap<>(); private final Unknown unknown; + /** + * The element names from the envelope down to where the reader stands, while it records where it read what; null + * when it does not. + */ + private final java.util.List path; public EcoreXmlReader(Unknown unknown) { + this(unknown, null); + } + + /** + * A reader that records where it read each object ({@link ElementLocation}), its elements standing below the given + * path, and refuses an unknown element, under {@link Unknown#FAIL}, in the words Analysis Services uses. + * + * @param above the element names above the element read, from the envelope down; {@code null} records nothing + */ + public EcoreXmlReader(Unknown unknown, java.util.List above) { this.unknown = unknown; + this.path = above == null ? null : new java.util.ArrayList<>(above); + } + + private ElementLocation.Position here(XMLStreamReader in, String child) { + var at = in.getLocation(); + String joined = String.join("/", path); + return new ElementLocation.Position(child == null ? joined : joined + "/" + child, in.getNamespaceURI(), + at.getLineNumber(), at.getColumnNumber()); } /** @@ -83,6 +106,12 @@ public EcoreXmlReader(Unknown unknown) { */ public EObject read(XMLStreamReader in, EClass target) throws XMLStreamException { EObject object = target.getEPackage().getEFactoryInstance().create(target); + ElementLocation location = null; + if (path != null) { + path.add(in.getLocalName()); + location = new ElementLocation(here(in, null)); + object.eAdapters().add(location); + } readAttributes(in, target, object); // A type with simple content keeps the element's own text, as // $1,234.00 and 42 @@ -104,6 +133,10 @@ public EObject read(XMLStreamReader in, EClass target) throws XMLStreamException if (text != null && !text.isEmpty()) { set(object, simple, text.toString(), in); } + if (location != null) { + location.end(here(in, null)); + path.removeLast(); + } return object; } depth--; @@ -173,6 +206,12 @@ private void readChild(XMLStreamReader in, EClass target, EObject object) throws return; } if (unknown == Unknown.FAIL) { + if (path != null) { + var at = in.getLocation(); + throw new XmlaParseException(XmlaParseException.CANNOT_APPEAR, "The " + name + " element at line " + + at.getLineNumber() + ", column " + at.getColumnNumber() + " (namespace " + + in.getNamespaceURI() + ") cannot appear under " + String.join("/", path) + "."); + } throw new XmlaCodecException("element <" + name + "> is not a feature of " + target.getName(), in); } skipSubtree(in); @@ -186,6 +225,10 @@ private void readChild(XMLStreamReader in, EClass target, EObject object) throws // XML and kept as the column's value. set(object, feature, XmlFragment.read(in), in); } else { + if (path != null) { + ElementLocation.Position at = here(in, name); + ElementLocation.of(object).ifPresent(location -> location.child(name, at)); + } set(object, feature, in.getElementText(), in); } } @@ -207,6 +250,19 @@ private static EStructuralFeature wrappedBy(EClass target, String name) { * Reads the children of a wrapper as though they had been written without it. */ private void readWrapped(XMLStreamReader in, EClass target, EObject object) throws XMLStreamException { + if (path != null) { + path.add(in.getLocalName()); + } + try { + readWrappedChildren(in, target, object); + } finally { + if (path != null) { + path.removeLast(); + } + } + } + + private void readWrappedChildren(XMLStreamReader in, EClass target, EObject object) throws XMLStreamException { int depth = 1; while (in.hasNext() && depth > 0) { int event = in.next(); diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlWriter.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlWriter.java index c9469ee..2dcee60 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlWriter.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/EcoreXmlWriter.java @@ -17,12 +17,20 @@ import javax.xml.stream.XMLStreamWriter; import org.eclipse.emf.ecore.EAnnotation; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.InternalEObject; +import org.eclipse.emf.ecore.impl.BasicEObjectImpl; import org.eclipse.emf.ecore.util.ExtendedMetaData; /** @@ -58,8 +66,96 @@ public EcoreXmlWriter(String namespace) { this.namespace = namespace; } + /** + * What the writer asks of a feature, asked once per class: its place among the object's features, its name and + * namespaces on the wire, how its value is written. The answers are fixed by the model; asked for every object, + * three passes over every feature of the class with the annotations and the ExtendedMetaData looked up each time, + * they were a large part of the time spent writing an Execute answer. + * + * @param id the feature's id in the object's class, as {@code eDerivedStructuralFeatureID} gives it, or -1 + */ + private record Slot(EStructuralFeature feature, int id, String wireName, String qualifiedNamespace, String wrapper, + String elementNamespace, EDataType dataType, boolean many, boolean reference, boolean textColumn, + boolean xmlDocument) { + } + + /** + * The features of a class by the part of the element they become, each in the order of the class's features, and + * what names the element when it is the value of another: {@code elementNameFrom}, the group's element name and the + * class's own ExtendedMetaData name. + */ + private record Plan(Slot[] attributes, Slot[] simple, Slot[] elements, EStructuralFeature nameFrom, + String groupElementName, String extendedName) { + } + + private static final Slot[] NO_SLOTS = {}; + + /** + * The plans of the generated classes, one per class for the life of the model. A dynamic class (one without an + * instance class, such as the row of a trace) is planned anew for every object, so that the map does not keep it. + */ + private static final ConcurrentMap PLANS = new ConcurrentHashMap<>(); + + private static Plan planOf(EObject object) { + EClass eClass = object.eClass(); + if (eClass.getInstanceClass() == null) { + return plan(eClass, object); + } + Plan plan = PLANS.get(eClass); + if (plan == null) { + plan = plan(eClass, object); + Plan raced = PLANS.putIfAbsent(eClass, plan); + plan = raced == null ? plan : raced; + } + return plan; + } + + private static Plan plan(EClass eClass, EObject sample) { + // the id the object's own eIsSet and eGet would work out for the feature, on every call + BasicEObjectImpl basic = sample instanceof BasicEObjectImpl b ? b : null; + List attributes = new ArrayList<>(); + List simple = new ArrayList<>(); + List elements = new ArrayList<>(); + for (EStructuralFeature feature : eClass.getEAllStructuralFeatures()) { + EClassifier type = feature.getEType(); + Slot slot = new Slot(feature, basic == null ? -1 : basic.eDerivedStructuralFeatureID(feature), + RowsetSchemaWriter.wireNameOf(feature), qualifiedNamespaceOf(feature), wrapperNameOf(feature), + elementNamespaceOf(feature), + feature instanceof EAttribute && type instanceof EDataType dataType ? dataType : null, + feature.isMany(), feature instanceof EReference, isTextColumn(feature), + EcoreXmlReader.isXmlDocument(feature)); + if (isAttribute(feature)) { + if (!isElementName(feature)) { + attributes.add(slot); + } + } else if (isSimpleContent(feature)) { + simple.add(slot); + } else { + elements.add(slot); + } + } + EAnnotation daanse = eClass.getEAnnotation(DAANSE_XMLA); + String from = daanse == null ? null : daanse.getDetails().get("elementNameFrom"); + return new Plan(attributes.toArray(NO_SLOTS), simple.toArray(NO_SLOTS), elements.toArray(NO_SLOTS), + from == null ? null : eClass.getEStructuralFeature(from), + daanse == null ? null : daanse.getDetails().get("groupElementName"), + ExtendedMetaData.INSTANCE.getName(eClass)); + } + + private static boolean isSet(EObject object, Slot slot) { + return slot.id() >= 0 ? ((InternalEObject) object).eIsSet(slot.id()) : object.eIsSet(slot.feature()); + } + + private static Object valueOf(EObject object, Slot slot) { + return slot.id() >= 0 ? ((InternalEObject) object).eGet(slot.id(), true, true) : object.eGet(slot.feature()); + } + /** Writes {@code object} as an element named {@code elementName}. */ public void write(XMLStreamWriter out, EObject object, String elementName) throws XMLStreamException { + write(out, object, planOf(object), elementName); + } + + private void write(XMLStreamWriter out, EObject object, Plan plan, String elementName) throws XMLStreamException { boolean declare = out.getPrefix(namespace) == null; if (declare) { // Nothing has bound this namespace yet — usually because this element is the @@ -70,9 +166,7 @@ public void write(XMLStreamWriter out, EObject object, String elementName) throw if (declare) { out.writeDefaultNamespace(namespace); } - writeAttributes(out, object); - writeSimpleContent(out, object); - writeElements(out, object); + writeContent(out, object, plan); out.writeEndElement(); } @@ -80,17 +174,21 @@ public void write(XMLStreamWriter out, EObject object, String elementName) throw * Writes only the children, for a caller that has already opened the element. */ public void writeContent(XMLStreamWriter out, EObject object) throws XMLStreamException { - writeAttributes(out, object); - writeSimpleContent(out, object); - writeElements(out, object); + writeContent(out, object, planOf(object)); + } + + private void writeContent(XMLStreamWriter out, EObject object, Plan plan) throws XMLStreamException { + writeAttributes(out, object, plan); + writeSimpleContent(out, object, plan); + writeElements(out, object, plan); } - private void writeAttributes(XMLStreamWriter out, EObject object) throws XMLStreamException { - for (EStructuralFeature feature : object.eClass().getEAllStructuralFeatures()) { - if (!isAttribute(feature) || !object.eIsSet(feature) || isElementName(feature)) { + private void writeAttributes(XMLStreamWriter out, EObject object, Plan plan) throws XMLStreamException { + for (Slot slot : plan.attributes()) { + if (!isSet(object, slot)) { continue; } - String value = asString(feature, object.eGet(feature)); + String value = asString(slot, valueOf(object, slot)); if (value == null) { continue; } @@ -98,14 +196,14 @@ private void writeAttributes(XMLStreamWriter out, EObject object) throws XMLStre // default, and it is right for the rowset columns. The exception is // soap:mustUnderstand, which SOAP 1.1 requires to be qualified; writing it bare // means the receiver does not see it at all. - String attributeNamespace = qualifiedNamespaceOf(feature); + String attributeNamespace = slot.qualifiedNamespace(); if (attributeNamespace == null) { - out.writeAttribute(RowsetSchemaWriter.wireNameOf(feature), value); + out.writeAttribute(slot.wireName(), value); } else { if (out.getPrefix(attributeNamespace) == null) { out.writeNamespace("mu", attributeNamespace); } - out.writeAttribute(attributeNamespace, RowsetSchemaWriter.wireNameOf(feature), value); + out.writeAttribute(attributeNamespace, slot.wireName(), value); } } } @@ -116,10 +214,10 @@ private void writeAttributes(XMLStreamWriter out, EObject object) throws XMLStre * Written before any child element, so the two writers put mixed content in the * same order. */ - private void writeSimpleContent(XMLStreamWriter out, EObject object) throws XMLStreamException { - for (EStructuralFeature feature : object.eClass().getEAllStructuralFeatures()) { - if (object.eIsSet(feature) && isSimpleContent(feature)) { - String text = asString(feature, object.eGet(feature)); + private void writeSimpleContent(XMLStreamWriter out, EObject object, Plan plan) throws XMLStreamException { + for (Slot slot : plan.simple()) { + if (isSet(object, slot)) { + String text = asString(slot, valueOf(object, slot)); if (text != null) { out.writeCharacters(text); } @@ -127,33 +225,29 @@ private void writeSimpleContent(XMLStreamWriter out, EObject object) throws XMLS } } - private void writeElements(XMLStreamWriter out, EObject object) throws XMLStreamException { - for (EStructuralFeature feature : object.eClass().getEAllStructuralFeatures()) { - if (isAttribute(feature) || !object.eIsSet(feature)) { + private void writeElements(XMLStreamWriter out, EObject object, Plan plan) throws XMLStreamException { + for (Slot slot : plan.elements()) { + if (!isSet(object, slot)) { continue; } - if (isSimpleContent(feature)) { - continue; // written before the children, see writeSimpleContent - } - String name = RowsetSchemaWriter.wireNameOf(feature); - Object value = object.eGet(feature); - if (feature.isMany()) { + Object value = valueOf(object, slot); + if (slot.many()) { // ASSL wraps its collections: holds the s. The // wrapper carries nothing itself, which is why the model flattens it to a // list, but it is on the wire. - String wrapper = wrapperNameOf(feature); + String wrapper = slot.wrapper(); Iterable elements = (Iterable) value; if (wrapper != null && !((java.util.Collection) value).isEmpty()) { out.writeStartElement(namespace, wrapper); } for (Object element : elements) { - writeOne(out, feature, name, element); + writeOne(out, slot, element); } if (wrapper != null && !((java.util.Collection) value).isEmpty()) { out.writeEndElement(); } } else if (value != null) { - writeOne(out, feature, name, value); + writeOne(out, slot, value); } } } @@ -185,23 +279,24 @@ static String elementNamespaceOf(EStructuralFeature feature) { return daanse == null ? null : daanse.getDetails().get("elementNamespace"); } - private void writeOne(XMLStreamWriter out, EStructuralFeature feature, String name, Object value) - throws XMLStreamException { - String elementNamespace = qualifiedNamespaceOf(feature); - if (feature instanceof EReference && value instanceof EObject nested) { - String childName = elementNameOf(feature, nested, name); + private void writeOne(XMLStreamWriter out, Slot slot, Object value) throws XMLStreamException { + String elementNamespace = slot.qualifiedNamespace(); + String name = slot.wireName(); + if (slot.reference() && value instanceof EObject nested) { + Plan nestedPlan = planOf(nested); + String childName = elementNameOf(slot.feature(), nested, nestedPlan, name); if (elementNamespace == null) { - write(out, nested, childName); + write(out, nested, nestedPlan, childName); } else { // Reached across a namespace boundary - a WarningColumn stays in the engine // namespace wherever it appears. - new EcoreXmlWriter(elementNamespace).write(out, nested, childName); + new EcoreXmlWriter(elementNamespace).write(out, nested, nestedPlan, childName); } return; } - String text = asString(feature, value); + String text = asString(slot, value); if (text == null || text.isEmpty()) { - if (!isTextColumn(feature)) { + if (!slot.textColumn()) { // An empty element is not an empty value to a client that has been told the // column is a number, a date or a uuid: it parses "" against that type, and // ADOMD stores the resulting FormatException as the cell's value instead of @@ -211,7 +306,7 @@ private void writeOne(XMLStreamWriter out, EStructuralFeature feature, String na // , not . The two are the same XML // to a parser, but SSAS writes the short one and responses are compared byte // for byte. - String own = elementNamespaceOf(feature); + String own = slot.elementNamespace(); if (own == null) { out.writeEmptyElement(namespace, name); } else { @@ -220,14 +315,14 @@ private void writeOne(XMLStreamWriter out, EStructuralFeature feature, String na } return; } - String own = elementNamespaceOf(feature); + String own = slot.elementNamespace(); if (own == null) { out.writeStartElement(namespace, name); } else { out.writeStartElement("", name, own); out.writeDefaultNamespace(own); } - if (EcoreXmlReader.isXmlDocument(feature)) { + if (slot.xmlDocument()) { // The column holds a document, not a string. Escaping it would turn a // definition into the literal text "<Server>". XmlFragment.write(out, text); @@ -260,12 +355,9 @@ private static boolean isTextColumn(EStructuralFeature feature) { * says {@code elementNameFrom} and the name is a value the object carries (a * CellInfoItem is {@code }). */ - private static String elementNameOf(EStructuralFeature feature, EObject value, String declared) { - EAnnotation daanse = value.eClass().getEAnnotation(DAANSE_XMLA); - String from = daanse == null ? null : daanse.getDetails().get("elementNameFrom"); - if (from != null) { - EStructuralFeature naming = value.eClass().getEStructuralFeature(from); - Object name = naming == null ? null : value.eGet(naming); + private static String elementNameOf(EStructuralFeature feature, EObject value, Plan plan, String declared) { + if (plan.nameFrom() != null) { + Object name = value.eGet(plan.nameFrom()); if (name != null && !name.toString().isEmpty()) { return name.toString(); } @@ -273,11 +365,11 @@ private static String elementNameOf(EStructuralFeature feature, EObject value, S if (feature.getEType() != value.eClass()) { // Inside a group the alternative's element name is not its type's name: the // SetType choice calls a SetListType a . - String group = daanse == null ? null : daanse.getDetails().get("groupElementName"); + String group = plan.groupElementName(); if (group != null && !group.isEmpty()) { return group; } - String own = ExtendedMetaData.INSTANCE.getName(value.eClass()); + String own = plan.extendedName(); if (own != null && !own.isEmpty()) { return own; } @@ -327,11 +419,7 @@ private static boolean isAttribute(EStructuralFeature feature) { } /** Converts a value to its lexical form, preferring EMF's own conversion. */ - private static String asString(EStructuralFeature feature, Object value) { - EClassifier type = feature.getEType(); - if (feature instanceof EAttribute && type instanceof EDataType dataType) { - return Lexical.of(dataType, value); - } - return Lexical.of(value); + private static String asString(Slot slot, Object value) { + return slot.dataType() != null ? Lexical.of(slot.dataType(), value) : Lexical.of(value); } } diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementLocation.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementLocation.java new file mode 100644 index 0000000..5cbbb8f --- /dev/null +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementLocation.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.model.io; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +import org.eclipse.emf.common.notify.impl.AdapterImpl; +import org.eclipse.emf.ecore.EObject; + +/** + * Where in a request an object was read: the path of its element from the envelope down, its namespace, the line and + * column where it starts and ends, and the same for each of its simple child elements. A refusal of what the object + * says names the place as Analysis Services does: "at line 1, column 332 … under + * Envelope/Body/Execute/Command/Create/ObjectDefinition/Trace/Events/Event/EventID". + *

+ * The reader attaches it while it reads a command; an object built in code carries none. + */ +public final class ElementLocation extends AdapterImpl { + + /** + * One place in the request. + * + * @param path the element names from the envelope down to the element, joined by {@code /} + * @param namespace the element's namespace + * @param line the line, from 1 + * @param column the column, from 1 + */ + public record Position(String path, String namespace, int line, int column) { + } + + private final Position start; + private Position end; + private final Map children = new LinkedHashMap<>(); + + ElementLocation(Position start) { + this.start = start; + } + + /** Where the object read from a request was, if it was read from one. */ + public static Optional of(EObject object) { + if (object == null) { + return Optional.empty(); + } + return object.eAdapters().stream().filter(ElementLocation.class::isInstance).map(ElementLocation.class::cast) + .findFirst(); + } + + /** Where the element starts. */ + public Position start() { + return start; + } + + /** Where it ends; empty while it is being read. */ + public Optional end() { + return Optional.ofNullable(end); + } + + /** Where a simple child element of that name starts, if the object had one. */ + public Optional child(String elementName) { + return Optional.ofNullable(children.get(elementName)); + } + + void end(Position at) { + this.end = at; + } + + void child(String elementName, Position at) { + children.putIfAbsent(elementName, at); + } + + @Override + public boolean isAdapterForType(Object type) { + return type == ElementLocation.class; + } +} diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementNames.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementNames.java index d54b3d9..eca1595 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementNames.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ElementNames.java @@ -22,20 +22,23 @@ *

* A column whose name is not a valid XML element name - a JDBC label, a member * unique name like {@code [Measures].[Profit]} - is hex-escaped the way SSAS - * escapes it ({@code _x005b_Measures_x005d_...}); the model documents this - * contract on {@code RowsetColumn}, and this is its one implementation. The - * fixed schema-rowset column names never need it - encoding those is a no-op by - * construction. + * escapes it ({@code _x005B_Measures_x005D_._x005B_Profit_x005D_}): a character + * is escaped only where it cannot stand, so a digit, a dot or a hyphen is kept + * after the first character and escaped as the first; the colon is escaped + * everywhere, an element name being a local name; an underscore only when an + * escape follows it, so that decoding is unambiguous (.NET + * {@code XmlConvert.EncodeLocalName}, which clients decode with). The model + * documents this contract on {@code RowsetColumn}, and this is its one + * implementation. The fixed schema-rowset column names never need it - encoding + * those is a no-op by construction. *

* {@link #normalizeNumericString(String)} is the trailing-zero normalisation * SSAS applies before writing a numeric cell value. */ public final class ElementNames { - /** XML 1.0 Name production, one character at a time. */ - private static final String VALID_CHARACTERS_EXP = "^[:A-Z_a-zÀÖØ-öø-˿Ͱ-ͽ" + "Ϳ-῿‌‍⁰-↏Ⰰ-⿯、-퟿" + "豈-﷏ﷰ-�]" - + "[:A-Z_a-zÀÖØ-ö" + "ø-˿Ͱ-ͽͿ-῿‌‍⁰-↏" + "Ⰰ-⿯、-\udfff豈-﷏ﷰ-�\\-\\.0-9" + "·̀-ͯ‿-⁀]*\\Z"; - private static final Pattern VALID_CHARACTERS = Pattern.compile(VALID_CHARACTERS_EXP); + /** An escape as a decoder reads it, after an underscore: {@code xHHHH_} or {@code xHHHHHHHH_}. */ + private static final Pattern ESCAPE_AHEAD = Pattern.compile("[Xx](?:[0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); /** Caches the encoding, because the same names recur in every row. */ private static final Map ENCODED = new ConcurrentHashMap<>(); @@ -78,24 +81,41 @@ public static String normalizeNumericString(String numericStr) { } private static String encodeElementName(String name) { - StringBuilder buf = new StringBuilder(); - for (char ch : name.toCharArray()) { - if (VALID_CHARACTERS.matcher(String.valueOf(ch)).matches()) { - buf.append(ch); + StringBuilder buf = new StringBuilder(name.length() + 16); + int i = 0; + while (i < name.length()) { + int codePoint = name.codePointAt(i); + int width = Character.charCount(codePoint); + boolean first = i == 0; + if (codePoint == '_' && ESCAPE_AHEAD.matcher(name).region(i + 1, name.length()).lookingAt()) { + buf.append(escape(codePoint)); + } else if (codePoint != ':' && (first ? isNameStartChar(codePoint) : isNameChar(codePoint))) { + buf.appendCodePoint(codePoint); } else { - buf.append(encodeChar(ch)); + buf.append(escape(codePoint)); } + i += width; } return buf.toString(); } - private static String encodeChar(char c) { - StringBuilder buf = new StringBuilder(); - buf.append("_x"); - String str = Integer.toHexString(c); - for (int i = 4 - str.length(); i > 0; i--) { - buf.append("0"); - } - return buf.append(str).append("_").toString(); + /** {@code _xHHHH_} with upper-case digits, eight of them beyond the basic plane. */ + private static String escape(int codePoint) { + return String.format(java.util.Locale.ROOT, codePoint > 0xFFFF ? "_x%08X_" : "_x%04X_", codePoint); + } + + /** XML 1.0 (fifth edition) {@code NameStartChar}. */ + static boolean isNameStartChar(int c) { + return c == ':' || c >= 'A' && c <= 'Z' || c == '_' || c >= 'a' && c <= 'z' || c >= 0xC0 && c <= 0xD6 + || c >= 0xD8 && c <= 0xF6 || c >= 0xF8 && c <= 0x2FF || c >= 0x370 && c <= 0x37D + || c >= 0x37F && c <= 0x1FFF || c >= 0x200C && c <= 0x200D || c >= 0x2070 && c <= 0x218F + || c >= 0x2C00 && c <= 0x2FEF || c >= 0x3001 && c <= 0xD7FF || c >= 0xF900 && c <= 0xFDCF + || c >= 0xFDF0 && c <= 0xFFFD || c >= 0x10000 && c <= 0xEFFFF; + } + + /** XML 1.0 (fifth edition) {@code NameChar}. */ + static boolean isNameChar(int c) { + return isNameStartChar(c) || c == '-' || c == '.' || c >= '0' && c <= '9' || c == 0xB7 + || c >= 0x300 && c <= 0x36F || c >= 0x203F && c <= 0x2040; } } diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestReader.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestReader.java index 676ebfd..7fcb842 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestReader.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestReader.java @@ -99,12 +99,21 @@ public static Execute read(XMLStreamReader in) throws XMLStreamException { return execute; } + /** The elements a command stands under in a request. */ + private static final java.util.List COMMAND_PATH = java.util.List.of("Envelope", "Body", "Execute", + "Command"); + private static Command readCommand(XMLStreamReader in, String name) throws XMLStreamException { EClassifier classifier = XmlaPackage.eINSTANCE.getEClassifier(name); if (!(classifier instanceof EClass eClass)) { throw new UnknownCommandException(name); } - EObject read = new EcoreXmlReader(EcoreXmlReader.Unknown.SKIP).read(in, eClass); + // what a command says is read with where it said it, so a refusal can name the place as Analysis Services + // does; an object definition (Create, Alter) refuses an element that cannot appear in it, as there, where + // the other commands pass over what they do not know + EcoreXmlReader.Unknown unknown = "Create".equals(name) || "Alter".equals(name) ? EcoreXmlReader.Unknown.FAIL + : EcoreXmlReader.Unknown.SKIP; + EObject read = new EcoreXmlReader(unknown, COMMAND_PATH).read(in, eClass); if (!(read instanceof Command command)) { // A type this package has that is not a command: and // are, is not. diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestWriter.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestWriter.java index 0610f07..f885f96 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestWriter.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/ExecuteRequestWriter.java @@ -51,6 +51,15 @@ static String namespaceOf(Command command) { return stated == null ? XmlaNamespaces.XMLA : stated; } + /** + * Writes one command alone, its element in its own namespace with everything under it: the text a server trace + * reports for the command (Command Begin and End), as Analysis Services writes it there, + * {@code …}. + */ + public static void writeCommand(XMLStreamWriter out, Command command) throws XMLStreamException { + new EcoreXmlWriter(namespaceOf(command)).write(out, command, ExtendedMetaData.INSTANCE.getName(command.eClass())); + } + /** Writes the {@code } element: the command, then the properties. */ public static void write(XMLStreamWriter out, Command command, PropertyList properties) throws XMLStreamException { out.setDefaultNamespace(XmlaNamespaces.XMLA); diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/SoapFaultWriter.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/SoapFaultWriter.java index 5b4541d..7db6871 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/SoapFaultWriter.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/SoapFaultWriter.java @@ -67,12 +67,32 @@ private SoapFaultWriter() { */ public static void write(OutputStream target, Kind kind, String faultString, Long errorCode, String description, String source) throws XMLStreamException { + write(target, kind, faultString, errorCode == null ? List.of() + : List.of(new Entry(errorCode, description == null ? faultString : description)), source); + } + + /** + * One {@code Error} of a fault's detail. + * + * @param code the unsigned 32-bit number + * @param description its sentence + */ + public record Entry(long code, String description) { + } + + /** + * A fault with several errors, as Analysis Services writes one for a request that fails twice -- an event out of + * range and the parse error naming where it stood: every {@code Error} in order, the fault code the last one's. + */ + public static void write(OutputStream target, Kind kind, String faultString, List errors, String source) + throws XMLStreamException { + Long errorCode = errors.isEmpty() ? null : errors.getLast().code(); XMLStreamWriter out = OUTPUT.createXMLStreamWriter(target, StandardCharsets.UTF_8.name()); SoapEnvelopeWriter.write(out, List.of(), body -> { body.writeStartElement(XmlaNamespaces.SOAP_ENV, "Fault"); // Unqualified on purpose - see the class comment. - writeUnqualified(body, "faultcode", XmlaNamespaces.SOAP_ENV_PREFIX + ":" + kind.code); + writeUnqualified(body, "faultcode", faultCode(kind, errorCode)); writeUnqualified(body, "faultstring", faultString); // Only with a code. A client reads the ErrorCode attribute unconditionally - @@ -81,16 +101,19 @@ public static void write(OutputStream target, Kind kind, String faultString, Lon // failure. A fault needs either this element or a faultstring, and the // faultstring above is always written, so leaving it out is the honest // option: better no Error element than one carrying an invented code. - if (errorCode != null) { + if (!errors.isEmpty()) { body.writeStartElement("detail"); body.setPrefix(XmlaNamespaces.EXCEPTION_PREFIX, XmlaNamespaces.EXCEPTION); - body.writeStartElement(XmlaNamespaces.EXCEPTION, "Error"); - body.writeNamespace(XmlaNamespaces.EXCEPTION_PREFIX, XmlaNamespaces.EXCEPTION); - body.writeAttribute("ErrorCode", Long.toUnsignedString(errorCode)); - body.writeAttribute("Description", description == null ? faultString : description); - body.writeAttribute("Source", source == null ? "" : source); - body.writeAttribute("HelpFile", ""); - body.writeEndElement(); + for (Entry error : errors) { + body.writeStartElement(XmlaNamespaces.EXCEPTION, "Error"); + body.writeNamespace(XmlaNamespaces.EXCEPTION_PREFIX, XmlaNamespaces.EXCEPTION); + body.writeAttribute("ErrorCode", Long.toUnsignedString(error.code())); + body.writeAttribute("Description", + error.description() == null ? faultString : error.description()); + body.writeAttribute("Source", source == null ? "" : source); + body.writeAttribute("HelpFile", ""); + body.writeEndElement(); + } body.writeEndElement(); } @@ -98,6 +121,23 @@ public static void write(OutputStream target, Kind kind, String faultString, Lon }); } + /** + * The fault code as Analysis Services writes it. + *

+ * A fault that carries a number has {@code XMLAnalysisError.0x} and the number in lower-case hexadecimal as its + * code, unprefixed: Analysis Services writes every such fault in this form and no other, e.g. + * {@code XMLAnalysisError.0xc1140002} beside {@code ErrorCode="3239313410"}. A fault without a number keeps SOAP's + * own {@code Client}/{@code Server}, since an invented number would be worse, and so does a header nobody + * understood (SOAP's {@code MustUnderstand}). ADOMD.NET does not read the code (it parses the {@code Error} + * element), so the form matters to clients that compare answers, not to ADOMD. + */ + static String faultCode(Kind kind, Long errorCode) { + if (errorCode == null || kind == Kind.MUST_UNDERSTAND) { + return XmlaNamespaces.SOAP_ENV_PREFIX + ":" + kind.code; + } + return "XMLAnalysisError.0x" + Long.toHexString(errorCode); + } + /** * The one-argument form writes the element in no namespace without touching the * namespace context. The three-argument form with empty strings looks diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaMessageCodec.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaMessageCodec.java index 3a8e7f4..5d4bd7f 100644 --- a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaMessageCodec.java +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaMessageCodec.java @@ -244,6 +244,69 @@ public static EObject errorMessages(Long errorCode, String description, String s return messages; } + /** + * The padding written after the inline schema and after each row of a stream: Analysis Services writes 4095 spaces + * there in a trace's Subscribe answer, which pushes each event through every buffer between server and client. + */ + static final int STREAM_PADDING = 4095; + + /** + * Writes an Execute response that is a stream of rows: the envelope, {@code ExecuteResponse/return/root} and the + * inline schema at once, then each row as the iterator gives it -- after the schema and after each row the padding + * Analysis Services writes, and a flush through to the target -- and the closing elements when the iterator ends. + * The iterator may block between rows; the response stays open meanwhile. + * + * @param values each row's values in column order, {@code null} for a value the row does not have + */ + public static void writeExecuteRowStream(OutputStream target, List headers, + List columns, Iterator> values) throws XMLStreamException { + XMLStreamWriter out = OUTPUT.createXMLStreamWriter(target, StandardCharsets.UTF_8.name()); + String padding = " ".repeat(STREAM_PADDING); + SoapEnvelopeWriter.write(out, headers, body -> { + body.setDefaultNamespace(XmlaNamespaces.XMLA); + body.writeStartElement(XmlaNamespaces.XMLA, "ExecuteResponse"); + body.writeDefaultNamespace(XmlaNamespaces.XMLA); + body.writeStartElement(XmlaNamespaces.XMLA, "return"); + body.setDefaultNamespace(XmlaNamespaces.ROWSET); + body.writeStartElement(XmlaNamespaces.ROWSET, "root"); + body.writeDefaultNamespace(XmlaNamespaces.ROWSET); + body.writeNamespace(XmlaNamespaces.XSI_PREFIX, XmlaNamespaces.XSI); + body.writeNamespace(XmlaNamespaces.XSD_PREFIX, XmlaNamespaces.XSD); + RowsetSchemaWriter.write(body, columns); + body.writeCharacters(padding); + flushThrough(body, target); + while (values.hasNext()) { + List row = values.next(); + body.writeStartElement(XmlaNamespaces.ROWSET, "row"); + for (int i = 0; i < columns.size() && i < row.size(); i++) { + Object value = row.get(i); + if (value == null) { + continue; + } + body.writeStartElement(XmlaNamespaces.ROWSET, columns.get(i).name()); + body.writeCharacters(String.valueOf(value)); + body.writeEndElement(); + } + body.writeEndElement(); // row + body.writeCharacters(padding); + flushThrough(body, target); + } + body.writeEndElement(); // root + body.writeEndElement(); // return + body.writeEndElement(); // ExecuteResponse + }); + out.flush(); + } + + private static void flushThrough(XMLStreamWriter out, OutputStream target) throws XMLStreamException { + out.flush(); + try { + target.flush(); + } catch (java.io.IOException gone) { + throw new XMLStreamException("the client is gone", gone); + } + } + /** * Writes an Execute response. *

diff --git a/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaParseException.java b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaParseException.java new file mode 100644 index 0000000..b10872d --- /dev/null +++ b/model/io/src/main/java/org/eclipse/daanse/xmla/model/io/XmlaParseException.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.model.io; + +/** + * A request that will not parse, refused with the number and the sentence Analysis Services refuses it with -- an + * element that cannot appear where it stands is {@code 0xC10F0007}, "The EventType element at line 1, column 306 + * (namespace …) cannot appear under Envelope/Body/Execute/Command/Create/ObjectDefinition/Trace." + */ +public class XmlaParseException extends XmlaCodecException { + + private static final long serialVersionUID = 1L; + + /** An element that cannot appear under the element it stands in. */ + public static final long CANNOT_APPEAR = 0xC10F0007L; + + private final long errorCode; + + public XmlaParseException(long errorCode, String message) { + super(message); + this.errorCode = errorCode; + } + + /** The unsigned 32-bit number Analysis Services answers this refusal with. */ + public long errorCode() { + return errorCode; + } +} diff --git a/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AColumnNameIsEscapedOnlyWhereItCannotStandTest.java b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AColumnNameIsEscapedOnlyWhereItCannotStandTest.java new file mode 100644 index 0000000..c65d6a1 --- /dev/null +++ b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AColumnNameIsEscapedOnlyWhereItCannotStandTest.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * SmartCity Jena - initial + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.model.io; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * A column of a tabular answer is an XML element, and its name is escaped where a character cannot stand: the first + * character must start a name, the others may also be digits, dots and hyphens. The first two rows are names of the + * kind an answer carries, a measure and a column of a table whose name starts with a dollar sign; escapes are written + * with upper-case digits, the colon is escaped because an element name is a local name, an underscore only when an + * escape follows it. + */ +class AColumnNameIsEscapedOnlyWhereItCannotStandTest { + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "[Measures].[N]|_x005B_Measures_x005D_._x005B_N_x005D_", + "[$Shipment Details].[Delivery Number]" + + "|_x005B__x0024_Shipment_x0020_Details_x005D_._x005B_Delivery_x0020_Number_x005D_", + "Measure1|Measure1", + "store_id|store_id", + "store-name.v2|store-name.v2", + "1st|_x0031_st", + "-x|_x002D_x", + ".x|_x002E_x", + "a:b|a_x003A_b", + "_x0041_|_x005F_x0041_", + "my_x|my_x", + "Größe|Größe", + "￾|_xFFFE_" }) + void aCharacterIsEscapedOnlyWhereItCannotStand(String name, String onTheWire) { + assertThat(ElementNames.encode(name)).isEqualTo(onTheWire); + } + + @org.junit.jupiter.api.Test + void aCharacterBeyondTheBasicPlaneIsKeptOrEscapedWhole() { + String doubleStruck = new String(Character.toChars(0x1D538)); + assertThat(ElementNames.encode(doubleStruck + "1")).as("a letter outside the basic plane starts a name") + .isEqualTo(doubleStruck + "1"); + assertThat(ElementNames.encode(new String(Character.toChars(0xF0000)))).isEqualTo("_x000F0000_"); + } +} diff --git a/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/ACommandIsReadWithWhereItStoodTest.java b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/ACommandIsReadWithWhereItStoodTest.java new file mode 100644 index 0000000..777b796 --- /dev/null +++ b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/ACommandIsReadWithWhereItStoodTest.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.model.io; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import org.eclipse.daanse.xmla.model.engine.Event; +import org.eclipse.daanse.xmla.model.engine.Trace; +import org.eclipse.daanse.xmla.model.xmla.Create; +import org.eclipse.daanse.xmla.model.xmla.Execute; +import org.eclipse.daanse.xmla.model.xmla.Statement; +import org.junit.jupiter.api.Test; + +/** + * A command is read with where each of its parts stood -- the path from the envelope down, the line and the column -- + * so a refusal of what it says can name the place as Analysis Services does; and an object definition refuses an + * element that cannot appear in it, in Analysis Services' words. + */ +class ACommandIsReadWithWhereItStoodTest { + + private static final String ENGINE = "http://schemas.microsoft.com/analysisservices/2003/engine"; + + private static Execute read(String command) throws Exception { + String xml = "" + command + + ""; + XMLStreamReader in = XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml)); + while (in.next() != XMLStreamConstants.START_ELEMENT) { + // to + } + return ExecuteRequestReader.read(in); + } + + private static String trace(String inside) { + return "TT" + inside + + ""; + } + + @Test + void anEventKnowsWhereItAndItsEventIdStood() throws Exception { + Execute execute = read(trace("10")); + Trace definition = ((Create) execute.getCommand()).getObjectDefinition().getTrace(); + Event event = definition.getEventType().getEvents().get(0); + + ElementLocation location = ElementLocation.of(event).orElseThrow(); + assertThat(location.start().path()) + .isEqualTo("Envelope/Body/Execute/Command/Create/ObjectDefinition/Trace/Events/Event"); + assertThat(location.start().namespace()).isEqualTo(ENGINE); + assertThat(location.start().line()).isEqualTo(1); + assertThat(location.end()).hasValueSatisfying( + end -> assertThat(end.column()).isGreaterThan(location.start().column())); + assertThat(location.child("EventID")).hasValueSatisfying(id -> { + assertThat(id.path()).isEqualTo(location.start().path() + "/EventID"); + assertThat(id.column()).isGreaterThan(location.start().column()); + }); + } + + @Test + void anElementThatCannotAppearInATraceIsRefusedWithItsPlace() { + assertThatThrownBy(() -> read(trace(""))) + .isInstanceOfSatisfying(XmlaParseException.class, refused -> { + assertThat(refused.errorCode()).isEqualTo(0xC10F0007L); + assertThat(refused).hasMessageMatching("The EventType element at line 1, column \\d+ \\(namespace " + + ENGINE.replace(".", "\\.") + "\\) cannot appear under" + + " Envelope/Body/Execute/Command/Create/ObjectDefinition/Trace\\."); + }); + } + + @Test + void aStatementPassesOverWhatItDoesNotKnow() throws Exception { + Execute execute = read("SELECT FROM [Sales]"); + + assertThat(((Statement) execute.getCommand()).getStatement()).isEqualTo("SELECT FROM [Sales]"); + } +} diff --git a/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/ARowStreamIsWrittenAsItComesTest.java b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/ARowStreamIsWrittenAsItComesTest.java new file mode 100644 index 0000000..fb16719 --- /dev/null +++ b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/ARowStreamIsWrittenAsItComesTest.java @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.model.io; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.junit.jupiter.api.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * A stream of rows is written as the rows come, in the form Analysis Services answers a trace's Subscribe with: the + * envelope and the inline schema at once -- each column with its client name as {@code sql:field} and a short element + * name -- then each row, each followed by 4095 spaces and a flush through to the client, and the closing elements when + * the stream ends. + */ +class ARowStreamIsWrittenAsItComesTest { + + private static final List COLUMNS = List.of( + new RowsetSchemaWriter.Column("EventClass", "a", "xsd:int"), + new RowsetSchemaWriter.Column("Duration", "b", "xsd:long"), + new RowsetSchemaWriter.Column("TextData", "c", "xsd:string")); + + /** What reached the target at each flush. */ + private static final class Flushes extends FilterOutputStream { + + final List seen = new CopyOnWriteArrayList<>(); + private final ByteArrayOutputStream bytes; + + Flushes(ByteArrayOutputStream bytes) { + super(bytes); + this.bytes = bytes; + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + bytes.write(b, off, len); + } + + @Override + public void flush() throws IOException { + super.flush(); + seen.add(bytes.toString(StandardCharsets.UTF_8)); + } + } + + /** Rows handed over one at a time; an empty list ends the stream. */ + private static Iterator> from(SynchronousQueue> handover) { + return new Iterator<>() { + private List next; + + @Override + public boolean hasNext() { + if (next == null) { + try { + next = handover.take(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + return !next.isEmpty(); + } + + @Override + public List next() { + List row = next; + next = null; + return row; + } + }; + } + + @Test + void theSchemaGoesOutAtOnceAndEachRowWhenItComes() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + Flushes target = new Flushes(bytes); + SynchronousQueue> handover = new SynchronousQueue<>(); + Thread writer = new Thread(() -> { + try { + XmlaMessageCodec.writeExecuteRowStream(target, List.of(), COLUMNS, from(handover)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + writer.start(); + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (target.seen.isEmpty() && System.nanoTime() < deadline) { + Thread.onSpinWait(); + } + Thread.sleep(200); + assertThat(target.seen.getLast()).as("the schema is out before any row") + .contains("sql:field=\"EventClass\" name=\"a\"").doesNotContain(""); + + handover.put(List.of(10, 6L, "SELECT {[Measures].DefaultMember} ON 0 FROM [Sales]")); + while (!target.seen.getLast().contains("") && System.nanoTime() < deadline) { + Thread.onSpinWait(); + } + assertThat(target.seen.getLast()).as("the row is out before the next one comes") + .contains("106SELECT {[Measures].DefaultMember} ON 0 FROM [Sales]"); + + java.util.ArrayList withoutDuration = new java.util.ArrayList<>(java.util.Arrays.asList(10, null, "x")); + handover.put(withoutDuration); + handover.put(List.of()); + writer.join(TimeUnit.SECONDS.toMillis(10)); + + String answer = bytes.toString(StandardCharsets.UTF_8); + assertThat(answer).contains("" + " ".repeat(4095) + ""); + assertThat(answer).contains("10x"); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + Document document = factory.newDocumentBuilder() + .parse(new ByteArrayInputStream(answer.getBytes(StandardCharsets.UTF_8))); + assertThat(document.getElementsByTagNameNS(XmlaNamespaces.ROWSET, "row").getLength()).isEqualTo(2); + Element column = (Element) document.getElementsByTagNameNS(XmlaNamespaces.XSD, "element").item(2); + assertThat(column.getAttributeNS(XmlaNamespaces.SQL, "field")).isEqualTo("EventClass"); + assertThat(column.getAttribute("type")).isEqualTo("xsd:int"); + } +} diff --git a/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AnAsslCommandIsWrittenAsAnalysisServicesReadsItTest.java b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AnAsslCommandIsWrittenAsAnalysisServicesReadsItTest.java index 24b4f35..4edecdc 100644 --- a/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AnAsslCommandIsWrittenAsAnalysisServicesReadsItTest.java +++ b/model/io/src/test/java/org/eclipse/daanse/xmla/model/io/AnAsslCommandIsWrittenAsAnalysisServicesReadsItTest.java @@ -135,6 +135,27 @@ void aStatementStaysInTheXmlaNamespace() throws Exception { assertThat(written.getNamespaceURI()).isEqualTo(XmlaNamespaces.XMLA); } + /** + * A command written alone -- what a server trace reports as the text of Command Begin and End -- is its own element in + * its own namespace, as Analysis Services 2017 writes it there ({@code }). + */ + @Test + void aCommandWrittenAloneIsItsElementInItsNamespace() throws Exception { + java.io.StringWriter text = new java.io.StringWriter(); + javax.xml.stream.XMLStreamWriter out = javax.xml.stream.XMLOutputFactory.newFactory().createXMLStreamWriter(text); + ExecuteRequestWriter.writeCommand(out, createOfATrace()); + out.close(); + + assertThat(text.toString()).startsWith(""); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + Element create = factory.newDocumentBuilder() + .parse(new ByteArrayInputStream(text.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8))) + .getDocumentElement(); + assertThat(create.getNamespaceURI()).isEqualTo(XmlaNamespaces.ENGINE); + assertThat(only(only(create, "ObjectDefinition"), "Trace").getNamespaceURI()).isEqualTo(XmlaNamespaces.ENGINE); + } + @Test void whatIsWrittenIsReadBackWithItsEvents() throws Exception { XMLStreamReader in = XMLInputFactory.newFactory().createXMLStreamReader( diff --git a/server/adapter.emf/src/main/java/org/eclipse/daanse/xmla/server/adapter/emf/EmfXmlaAdapter.java b/server/adapter.emf/src/main/java/org/eclipse/daanse/xmla/server/adapter/emf/EmfXmlaAdapter.java index 92c52e7..45a53c2 100644 --- a/server/adapter.emf/src/main/java/org/eclipse/daanse/xmla/server/adapter/emf/EmfXmlaAdapter.java +++ b/server/adapter.emf/src/main/java/org/eclipse/daanse/xmla/server/adapter/emf/EmfXmlaAdapter.java @@ -207,7 +207,7 @@ private boolean serve(InputStream source, OutputStream target, Exchange exchange try { request = restoreIdentity(applySessionHeaders(envelope.headers(), exchange)); } catch (org.eclipse.daanse.xmla.api.XmlaRefusedException refused) { - writeFault(target, faultKindOf(refused), refused.getMessage(), null); + writeRefusal(target, refused); return false; } @@ -303,7 +303,7 @@ private boolean discover(SoapEnvelopeReader.Envelope envelope, OutputStream targ try { rows = connector.discover(discover, request); } catch (org.eclipse.daanse.xmla.api.XmlaRefusedException refused) { - writeFault(target, faultKindOf(refused), refused.getMessage(), null); + writeRefusal(target, refused); return false; } catch (org.eclipse.daanse.xmla.api.XmlaCommandFailedException failed) { LOGGER.debug("answering with an in-band error", failed); @@ -367,6 +367,10 @@ private boolean execute(SoapEnvelopeReader.Envelope envelope, OutputStream targe } catch (UnknownCommandException unknown) { writeFault(target, SoapFaultWriter.Kind.CLIENT, unknown.getMessage(), null); return false; + } catch (org.eclipse.daanse.xmla.model.io.XmlaParseException unparsable) { + // a command that will not parse, in the number and words Analysis Services refuses it with + writeFault(target, SoapFaultWriter.Kind.CLIENT, unparsable.getMessage(), unparsable.errorCode()); + return false; } if (!policy.allowsExecute(!request.isAuthenticated())) { @@ -377,7 +381,7 @@ private boolean execute(SoapEnvelopeReader.Envelope envelope, OutputStream targe try { result = connector.execute(execute, request); } catch (org.eclipse.daanse.xmla.api.XmlaRefusedException refused) { - writeFault(target, faultKindOf(refused), refused.getMessage(), null); + writeRefusal(target, refused); return false; } catch (org.eclipse.daanse.xmla.api.XmlaCommandFailedException failed) { // Ran and failed, and the session lives: the answer is a result root @@ -387,10 +391,34 @@ private boolean execute(SoapEnvelopeReader.Envelope envelope, OutputStream targe messagesOf(failed)); return true; } + if (result instanceof org.eclipse.daanse.xmla.api.RowStream stream) { + writeStream(target, responseHeaders(request, envelope.headers()), stream); + return true; + } XmlaMessageCodec.writeExecuteResponse(target, responseHeaders(request, envelope.headers()), result); return true; } + /** + * A result that comes row by row, written as it comes. Once the first byte is out a failure cannot become a fault + * any more -- most often the client has gone away -- so it ends the stream and is logged; the stream is closed + * either way, which ends what it reads from. + */ + private static void writeStream(OutputStream target, List headers, + org.eclipse.daanse.xmla.api.RowStream stream) { + List columns = stream.columns().stream() + .map(column -> new org.eclipse.daanse.xmla.model.io.RowsetSchemaWriter.Column(column.field(), + column.name(), column.xsdType())) + .toList(); + try { + XmlaMessageCodec.writeExecuteRowStream(target, headers, columns, stream.rows()); + } catch (XMLStreamException | RuntimeException ended) { + LOGGER.debug("a row stream ended before its last row: {}", ended.getMessage()); + } finally { + stream.close(); + } + } + /** The {@code } a failed-but-answered command is reported with. */ private static EObject messagesOf(org.eclipse.daanse.xmla.api.XmlaCommandFailedException failed) { return XmlaMessageCodec.errorMessages(failed.errorCode(), failed.description(), failed.source(), @@ -495,6 +523,17 @@ private XmlaRequest restoreIdentity(XmlaRequest request) { return sessions.identityOf(request.sessionId()).map(request::withIdentity).orElse(request); } + /** A refusal as a fault: every error it carries, its code the last one's. */ + private void writeRefusal(OutputStream target, org.eclipse.daanse.xmla.api.XmlaRefusedException refused) { + List errors = refused.errors().stream() + .map(error -> new SoapFaultWriter.Entry(error.code(), error.description())).toList(); + try { + SoapFaultWriter.write(target, faultKindOf(refused), refused.getMessage(), errors, ERROR_SOURCE); + } catch (XMLStreamException e) { + LOGGER.error("could not write the SOAP fault for: {}", refused.getMessage(), e); + } + } + private void writeFault(OutputStream target, SoapFaultWriter.Kind kind, String message, Long errorCode) { try { SoapFaultWriter.write(target, kind, message, errorCode, message, ERROR_SOURCE); diff --git a/server/adapter.emf/src/test/java/org/eclipse/daanse/xmla/server/adapter/emf/FaultShapeTest.java b/server/adapter.emf/src/test/java/org/eclipse/daanse/xmla/server/adapter/emf/FaultShapeTest.java index b6a6f6a..c694321 100644 --- a/server/adapter.emf/src/test/java/org/eclipse/daanse/xmla/server/adapter/emf/FaultShapeTest.java +++ b/server/adapter.emf/src/test/java/org/eclipse/daanse/xmla/server/adapter/emf/FaultShapeTest.java @@ -20,12 +20,17 @@ import java.nio.charset.StandardCharsets; import java.util.List; +import javax.xml.parsers.DocumentBuilderFactory; + import org.eclipse.daanse.xmla.api.XmlaConnector; +import org.eclipse.daanse.xmla.api.XmlaRefusedException; import org.eclipse.daanse.xmla.api.XmlaRequest; import org.eclipse.daanse.xmla.model.xmla.Discover; import org.eclipse.daanse.xmla.model.xmla.Execute; import org.eclipse.emf.ecore.EObject; import org.junit.jupiter.api.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; /** * The shape of a fault, and the one rule that makes it readable at the far end. @@ -65,22 +70,131 @@ public EObject execute(Execute request, XmlaRequest context) { } }; + private static final String EXECUTE = """ + \ + SELECT FROM [C]\ + """; + private static String send(String body) { + return send(STUB, body); + } + + private static String send(XmlaConnector connector, String body) { ByteArrayOutputStream answer = new ByteArrayOutputStream(); - new EmfXmlaAdapter(STUB, null, null).handle( + new EmfXmlaAdapter(connector, null, null).handle( new ByteArrayInputStream(ENVELOPE.formatted(body).getBytes(StandardCharsets.UTF_8)), answer, XmlaRequest.anonymous()); return answer.toString(StandardCharsets.UTF_8); } + /** A connector that refuses every request with the given refusal. */ + private static XmlaConnector refusing(XmlaRefusedException refusal) { + return new XmlaConnector() { + + @Override + public List discover(Discover request, XmlaRequest context) { + throw refusal; + } + + @Override + public EObject execute(Execute request, XmlaRequest context) { + throw refusal; + } + }; + } + + private static Document parsed(String answer) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + return factory.newDocumentBuilder().parse(new ByteArrayInputStream(answer.getBytes(StandardCharsets.UTF_8))); + } + + private static String faultCodeOf(Document answer) { + return answer.getElementsByTagNameNS("*", "faultcode").item(0).getTextContent(); + } + + private static Element errorOf(Document answer) { + return (Element) answer.getElementsByTagNameNS("*", "Error").item(0); + } + @Test - void anUnknownRequestTypeFaultsWithItsCode() { - String answer = send(discoverOf("NO_SUCH_ROWSET")); + void anUnknownRequestTypeFaultsWithItsCode() throws Exception { + Document answer = parsed(send(discoverOf("NO_SUCH_ROWSET"))); - assertThat(answer).contains("Fault"); - assertThat(answer).contains("Error"); - // Present, and a decimal unsigned 32-bit number - the client parses it as one. - assertThat(answer).containsPattern("ErrorCode=\"\\d+\""); + // Present, and a decimal unsigned 32-bit number - the client parses it as one; the fault code names the same + // number in hexadecimal, as Analysis Services writes it. + assertThat(errorOf(answer).getAttribute("ErrorCode")).isEqualTo("3238789172"); + assertThat(faultCodeOf(answer)).isEqualTo("XMLAnalysisError.0xc10c0034"); + } + + /** + * A trace that exists already, as Analysis Services 2017 answers it: {@code XMLAnalysisError.0xc1140002} with + * {@code ErrorCode} 3239313410 and the sentence as {@code Description}. A connector's refusal with that number is + * answered alike, on Discover and on Execute. + */ + @Test + void aRefusalWithANumberFaultsAsAnalysisServicesDoes() throws Exception { + XmlaRefusedException refusal = new XmlaRefusedException(XmlaRefusedException.Side.CLIENT, 0xC1140002L, + "Errors in the metadata manager. The trace with the name of 'T' already exists in the 'S' server."); + + for (String request : List.of(discoverOf("DISCOVER_TRACES"), EXECUTE)) { + Document answer = parsed(send(refusing(refusal), request)); + + assertThat(faultCodeOf(answer)).isEqualTo("XMLAnalysisError.0xc1140002"); + assertThat(errorOf(answer).getAttribute("ErrorCode")).isEqualTo("3239313410"); + assertThat(errorOf(answer).getAttribute("Description")).isEqualTo(refusal.getMessage()); + } + } + + /** + * An event number Analysis Services does not know is refused with two errors, the range error and the parse error + * naming where the number stood; the fault lists both in that order, and its code and faultstring are the second's. + */ + @Test + void aRefusalWithTwoErrorsListsBothAndIsCodedByTheLast() throws Exception { + XmlaRefusedException refusal = new XmlaRefusedException(XmlaRefusedException.Side.CLIENT, List.of( + new XmlaRefusedException.Error(0xC11B0002L, "Trace: An event number encountered while evaluating the" + + " trace definition was not within the range of acceptable values."), + new XmlaRefusedException.Error(0xC10F0014L, "An error occurred while parsing the 'EventID' element."))); + + Document answer = parsed(send(refusing(refusal), EXECUTE)); + + assertThat(faultCodeOf(answer)).isEqualTo("XMLAnalysisError.0xc10f0014"); + assertThat(answer.getElementsByTagNameNS("*", "faultstring").item(0).getTextContent()) + .isEqualTo("An error occurred while parsing the 'EventID' element."); + var errors = answer.getElementsByTagNameNS("*", "Error"); + assertThat(errors.getLength()).isEqualTo(2); + assertThat(((Element) errors.item(0)).getAttribute("ErrorCode")).isEqualTo("3239772162"); + assertThat(((Element) errors.item(1)).getAttribute("ErrorCode")).isEqualTo("3238985748"); + } + + /** + * An element an object definition cannot hold is refused as Analysis Services refuses it: {@code 0xC10F0007}, the + * element named with its line, column and namespace, and the path of the element it stands in. + */ + @Test + void anElementThatCannotAppearInATraceIsRefusedWhereItStands() throws Exception { + String create = """ + \ + \ + TT\ + """; + + Document answer = parsed(send(create)); + + assertThat(faultCodeOf(answer)).isEqualTo("XMLAnalysisError.0xc10f0007"); + assertThat(errorOf(answer).getAttribute("Description")).matches("The EventType element at line 1, column \\d+" + + " \\(namespace http://schemas.microsoft.com/analysisservices/2003/engine\\) cannot appear under" + + " Envelope/Body/Execute/Command/Create/ObjectDefinition/Trace\\."); + } + + @Test + void aRefusalWithoutANumberKeepsSoapsOwnCode() throws Exception { + Document answer = parsed(send(refusing(new XmlaRefusedException(XmlaRefusedException.Side.CLIENT, + "A trace with a log file (LogFileName) is not supported by this server.")), EXECUTE)); + + assertThat(faultCodeOf(answer)).isEqualTo("soap:Client"); + assertThat(errorOf(answer)).as("no invented number").isNull(); } @Test diff --git a/server/jdk.httpserver/src/main/java/org/eclipse/daanse/xmla/server/jdk/httpserver/JdkHttpServer.java b/server/jdk.httpserver/src/main/java/org/eclipse/daanse/xmla/server/jdk/httpserver/JdkHttpServer.java index 9c3a84a..aa4b377 100644 --- a/server/jdk.httpserver/src/main/java/org/eclipse/daanse/xmla/server/jdk/httpserver/JdkHttpServer.java +++ b/server/jdk.httpserver/src/main/java/org/eclipse/daanse/xmla/server/jdk/httpserver/JdkHttpServer.java @@ -137,9 +137,26 @@ String[] anonymousRowsets() default { "DISCOVER_PROPERTIES", "DISCOVER_DATASOURC int stopDelaySeconds() default 5; } + /** The JDK server's switch for {@code TCP_NODELAY} on the sockets it accepts. */ + static final String NO_DELAY = "sun.net.httpserver.nodelay"; + + /** + * Turns {@code TCP_NODELAY} on for the JDK's server unless the process says otherwise. The JDK server writes the + * head and the body of an answer apart; with Nagle's algorithm on, the body waits for the client's delayed + * acknowledgement -- 40 ms on Linux, on every Discover and every Execute. The JDK reads the switch once, when its + * server is first used in the process: a server another bundle started before this one keeps its setting, so a + * deployment sets {@code -Dsun.net.httpserver.nodelay=true} itself. + */ + static void noDelayUnlessSet() { + if (System.getProperty(NO_DELAY) == null) { + System.setProperty(NO_DELAY, "true"); + } + } + @Activate public void activate(Config config) throws IOException { LOGGER.debug("Starting JDK HTTP server"); + noDelayUnlessSet(); server = HttpServer.create(new InetSocketAddress(config.port()), config.backlog()); EmfXmlaAdapter adapter = new EmfXmlaAdapter(connector, sessionHandler, inbandAuthenticator, diff --git a/server/jdk.httpserver/src/test/java/org/eclipse/daanse/xmla/server/jdk/httpserver/TheServerTurnsNagleOffTest.java b/server/jdk.httpserver/src/test/java/org/eclipse/daanse/xmla/server/jdk/httpserver/TheServerTurnsNagleOffTest.java new file mode 100644 index 0000000..c391b5c --- /dev/null +++ b/server/jdk.httpserver/src/test/java/org/eclipse/daanse/xmla/server/jdk/httpserver/TheServerTurnsNagleOffTest.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Stefan Bischof (bipolis.org) - initial + */ +package org.eclipse.daanse.xmla.server.jdk.httpserver; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; + +/** + * The server turns Nagle's algorithm off for the JDK's server before it creates one, unless the process set the switch + * itself: with it on, an answer can wait for the client's delayed acknowledgement. The switch is a system property the + * JDK reads once per process, so what is tested here is that it is set; its effect on the time of an answer shows only + * where a server is the first in its process. + */ +@ResourceLock("system-properties") +class TheServerTurnsNagleOffTest { + + private String before; + + @BeforeEach + void remember() { + before = System.getProperty(JdkHttpServer.NO_DELAY); + } + + @AfterEach + void restore() { + if (before == null) { + System.clearProperty(JdkHttpServer.NO_DELAY); + } else { + System.setProperty(JdkHttpServer.NO_DELAY, before); + } + } + + @Test + void theSwitchIsSetWhenNobodySetIt() { + System.clearProperty(JdkHttpServer.NO_DELAY); + + JdkHttpServer.noDelayUnlessSet(); + + assertThat(System.getProperty(JdkHttpServer.NO_DELAY)).isEqualTo("true"); + } + + @Test + void aSwitchTheProcessSetStands() { + System.setProperty(JdkHttpServer.NO_DELAY, "false"); + + JdkHttpServer.noDelayUnlessSet(); + + assertThat(System.getProperty(JdkHttpServer.NO_DELAY)).isEqualTo("false"); + } +}