repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIStreamLocation.java | src/main/java/io/xlate/edi/internal/stream/StaEDIStreamLocation.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import io.xlate.edi.stream.Location;
public class StaEDIStreamLocation extends LocationView implements Location {
private boolean afterSegment = false;
private boolean composite = false;
private boolean repeating = false;
private int repeatCount = -1;
public StaEDIStreamLocation() {
super();
}
public StaEDIStreamLocation(Location source) {
super(source);
}
@Override
public String toString() {
return super.toString(afterSegment);
}
@Override
public StaEDIStreamLocation copy() {
StaEDIStreamLocation copy = new StaEDIStreamLocation(this);
copy.afterSegment = this.afterSegment;
copy.composite = this.composite;
copy.repeating = this.repeating;
copy.repeatCount = this.repeatCount;
return copy;
}
public void set(StaEDIStreamLocation source) {
lineNumber = source.getLineNumber();
columnNumber = source.getColumnNumber();
characterOffset = source.getCharacterOffset();
segmentPosition = source.getSegmentPosition();
segmentTag = source.getSegmentTag();
elementPosition = source.getElementPosition();
componentPosition = source.getComponentPosition();
elementOccurrence = source.getElementOccurrence();
afterSegment = source.afterSegment;
}
public void setElementPosition(int elementPosition) {
this.elementPosition = elementPosition;
}
public void setElementOccurrence(int elementOccurrence) {
this.elementOccurrence = elementOccurrence;
}
public void setComponentPosition(int componentPosition) {
this.componentPosition = componentPosition;
}
public void incrementOffset(int value) {
this.characterOffset++;
if (value == '\n') {
this.lineNumber++;
this.columnNumber = 0;
}
this.columnNumber++;
}
static int initOrIncrement(int position) {
if (position < 0) {
return 1;
}
return position + 1;
}
public void incrementSegmentPosition(String segmentTag) {
this.segmentPosition = initOrIncrement(segmentPosition);
this.segmentTag = segmentTag;
clearSegmentLocations(false);
}
public void clearSegmentLocations(boolean afterSegment) {
this.afterSegment = afterSegment;
this.elementPosition = -1;
this.elementOccurrence = -1;
this.repeating = false;
this.repeatCount = -1;
clearComponentPosition();
}
public void incrementElementPosition() {
this.elementPosition = initOrIncrement(elementPosition);
this.elementOccurrence = 1;
clearComponentPosition();
}
public void incrementElementOccurrence() {
this.elementPosition = Math.max(elementPosition, 1);
this.elementOccurrence = initOrIncrement(elementOccurrence);
clearComponentPosition();
}
public void incrementComponentPosition() {
this.componentPosition = initOrIncrement(componentPosition);
}
public void clearComponentPosition() {
this.composite = false;
this.componentPosition = -1;
}
public void setComposite(boolean composite) {
this.composite = composite;
}
public void setRepeating(boolean repeating) {
if (repeating) {
// Encountered a repeat delimiter
if (this.repeating) {
// Previous delimiter was repeat, increment
repeatCount++;
} else {
// First repeat delimiter for this element
repeatCount = 0;
}
} else if (this.repeating) {
// Previous delimiter was repeat, this one is not. The element just completed is a repeat
repeatCount++;
} else {
// Repeat does not apply
repeatCount = -1;
}
this.repeating = repeating;
}
public void incrementElement(boolean compositeBegin) {
if (composite) {
incrementComponentPosition();
} else if (elementPosition < 0 || repeatCount == -1) {
// First element of the segment or not a repeating element
incrementElementPosition();
} else if (repeating) {
if (compositeBegin) {
// Previous element delimiter was a repeater and the first component was encountered
incrementElementOccurrence();
} else if (repeatCount == 0) {
// First element of the repeating series is in a new element position
incrementElementPosition();
} else {
incrementElementOccurrence();
}
} else if (compositeBegin) {
incrementElementPosition();
} else {
incrementElementOccurrence();
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIFilteredStreamReader.java | src/main/java/io/xlate/edi/internal/stream/StaEDIFilteredStreamReader.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamException;
import io.xlate.edi.stream.EDIStreamFilter;
import io.xlate.edi.stream.EDIStreamReader;
import io.xlate.edi.stream.EDIStreamValidationError;
import io.xlate.edi.stream.Location;
class StaEDIFilteredStreamReader implements EDIStreamReader {
private final EDIStreamReader delegate;
private final EDIStreamFilter filter;
private EDIStreamEvent peekEvent = null;
public StaEDIFilteredStreamReader(EDIStreamReader delegate, EDIStreamFilter filter) {
this.delegate = delegate;
this.filter = filter;
}
@Override
public Object getProperty(String name) {
return delegate.getProperty(name);
}
@Override
public Map<String, Character> getDelimiters() {
return delegate.getDelimiters();
}
@Override
public EDIStreamEvent next() throws EDIStreamException {
EDIStreamEvent event;
if (peekEvent != null) {
event = peekEvent;
peekEvent = null;
return event;
}
do {
event = delegate.next();
} while (!filter.accept(delegate));
return event;
}
@Override
public EDIStreamEvent nextTag() throws EDIStreamException {
if (peekEvent == EDIStreamEvent.START_SEGMENT) {
peekEvent = null;
return EDIStreamEvent.START_SEGMENT;
}
EDIStreamEvent event;
do {
event = delegate.nextTag();
} while (!filter.accept(delegate));
return event;
}
@Override
public boolean hasNext() throws EDIStreamException {
if (peekEvent != null) {
return true;
}
while (delegate.hasNext()) {
EDIStreamEvent event = delegate.next();
if (filter.accept(delegate)) {
peekEvent = event;
return true;
}
}
return false;
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public EDIStreamEvent getEventType() {
return delegate.getEventType();
}
@Override
public String getStandard() {
return delegate.getStandard();
}
@Override
public String[] getVersion() {
return delegate.getVersion();
}
@Override
public String[] getTransactionVersion() {
return delegate.getTransactionVersion();
}
@Override
public String getTransactionVersionString() {
return delegate.getTransactionVersionString();
}
@Override
public String getTransactionType() {
return delegate.getTransactionType();
}
@Override
public Schema getControlSchema() {
return delegate.getControlSchema();
}
@Override
public void setControlSchema(Schema schema) {
delegate.setControlSchema(schema);
}
@Override
public Schema getTransactionSchema() {
return delegate.getTransactionSchema();
}
@Override
public void setTransactionSchema(Schema schema) {
delegate.setTransactionSchema(schema);
}
@Override
public String getReferenceCode() {
return delegate.getReferenceCode();
}
@Override
public EDIStreamValidationError getErrorType() {
return delegate.getErrorType();
}
@Override
public String getText() {
return delegate.getText();
}
@Override
public char[] getTextCharacters() {
return delegate.getTextCharacters();
}
@Override
public int getTextCharacters(int sourceStart,
char[] target,
int targetStart,
int length) {
return delegate.getTextCharacters(sourceStart,
target,
targetStart,
length);
}
@Override
public int getTextStart() {
return delegate.getTextStart();
}
@Override
public int getTextLength() {
return delegate.getTextLength();
}
@Override
public Location getLocation() {
return delegate.getLocation();
}
@Override
public void setBinaryDataLength(long length) throws EDIStreamException {
delegate.setBinaryDataLength(length);
}
@Override
public InputStream getBinaryData() {
return delegate.getBinaryData();
}
@Override
public EDIReference getSchemaTypeReference() {
return delegate.getSchemaTypeReference();
}
@Override
public boolean hasText() {
return delegate.hasText();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIOutputFactory.java | src/main/java/io/xlate/edi/internal/stream/StaEDIOutputFactory.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.xml.stream.XMLStreamWriter;
import io.xlate.edi.stream.EDIOutputErrorReporter;
import io.xlate.edi.stream.EDIOutputFactory;
import io.xlate.edi.stream.EDIStreamConstants;
import io.xlate.edi.stream.EDIStreamException;
import io.xlate.edi.stream.EDIStreamWriter;
public class StaEDIOutputFactory extends EDIOutputFactory {
private EDIOutputErrorReporter reporter;
public StaEDIOutputFactory() {
supportedProperties.add(EDIStreamConstants.Delimiters.SEGMENT);
supportedProperties.add(EDIStreamConstants.Delimiters.DATA_ELEMENT);
supportedProperties.add(EDIStreamConstants.Delimiters.COMPONENT_ELEMENT);
supportedProperties.add(EDIStreamConstants.Delimiters.REPETITION);
supportedProperties.add(EDIStreamConstants.Delimiters.DECIMAL);
supportedProperties.add(EDIStreamConstants.Delimiters.RELEASE);
supportedProperties.add(PRETTY_PRINT);
supportedProperties.add(TRUNCATE_EMPTY_ELEMENTS);
supportedProperties.add(FORMAT_ELEMENTS);
properties.put(PRETTY_PRINT, Boolean.FALSE);
}
@Override
public EDIStreamWriter createEDIStreamWriter(OutputStream stream) {
return new StaEDIStreamWriter(stream, StandardCharsets.UTF_8, properties, reporter);
}
@Override
public EDIStreamWriter createEDIStreamWriter(OutputStream stream, String encoding) throws EDIStreamException {
if (Charset.isSupported(encoding)) {
return new StaEDIStreamWriter(stream, Charset.forName(encoding), properties, reporter);
}
throw new EDIStreamException("Unsupported encoding: " + encoding);
}
@Override
public XMLStreamWriter createXMLStreamWriter(EDIStreamWriter writer) {
return new StaEDIXMLStreamWriter(writer);
}
@Override
public EDIOutputErrorReporter getErrorReporter() {
return this.reporter;
}
@Override
public void setErrorReporter(EDIOutputErrorReporter reporter) {
this.reporter = reporter;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIXMLStreamWriter.java | src/main/java/io/xlate/edi/internal/stream/StaEDIXMLStreamWriter.java | package io.xlate.edi.internal.stream;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import io.xlate.edi.internal.ThrowingRunnable;
import io.xlate.edi.stream.EDINamespaces;
import io.xlate.edi.stream.EDIStreamWriter;
final class StaEDIXMLStreamWriter implements XMLStreamWriter {
private static final QName INTERCHANGE = new QName(EDINamespaces.LOOPS, "INTERCHANGE");
static final String MSG_INVALID_COMPONENT_NAME = "Invalid component element name or position not given: %s";
static final String MSG_INVALID_COMPONENT_POSITION = "Invalid/non-numeric component element position: %s";
static final String MSG_INVALID_ELEMENT_NAME = "Invalid element name or position not numeric: %s";
static final String MSG_ILLEGAL_NONWHITESPACE = "Illegal non-whitespace characters";
private final EDIStreamWriter ediWriter;
private final Deque<QName> elementStack = new ArrayDeque<>();
private QName previousElement;
int lastElementPosition;
int lastComponentPosition;
private NamespaceContext namespaceContext;
private final Deque<Map<String, String>> namespaceStack = new ArrayDeque<>();
StaEDIXMLStreamWriter(EDIStreamWriter ediWriter) {
this.ediWriter = ediWriter;
namespaceStack.push(new HashMap<>()); // Root namespace scope
}
void execute(ThrowingRunnable<Exception> task) throws XMLStreamException {
ThrowingRunnable.run(task, XMLStreamException::new);
}
boolean repeatedElement(QName name, QName previousElement) {
if (previousElement == null) {
return false;
}
if (name.equals(previousElement)) {
return true;
}
return name.getLocalPart().equals(previousElement.getLocalPart());
}
int getPosition(QName name, boolean component) throws XMLStreamException {
int position;
String localPart = name.getLocalPart();
if (component) {
int componentIdx = localPart.indexOf('-');
if (componentIdx < 2) {
throw new XMLStreamException(String.format(MSG_INVALID_COMPONENT_NAME, name));
}
try {
position = Integer.parseInt(localPart.substring(componentIdx + 1));
} catch (NumberFormatException e) {
throw new XMLStreamException(String.format(MSG_INVALID_COMPONENT_POSITION, name));
}
} else {
try {
position = Integer.parseInt(localPart.substring(localPart.length() - 2));
} catch (NumberFormatException e) {
throw new XMLStreamException(String.format(MSG_INVALID_ELEMENT_NAME, name));
}
}
return position;
}
void writeStart(QName name) throws XMLStreamException {
namespaceStack.push(new HashMap<>());
switch (name.getNamespaceURI()) {
case EDINamespaces.COMPOSITES:
lastComponentPosition = 0;
writeElementStart(name);
break;
case EDINamespaces.ELEMENTS:
if (EDINamespaces.COMPOSITES.equals(elementStack.element().getNamespaceURI())) {
writeComponentStart(name);
} else {
writeElementStart(name);
}
break;
case EDINamespaces.LOOPS:
// Loops are implicit when writing
elementStack.push(name);
break;
case EDINamespaces.SEGMENTS:
lastElementPosition = 0;
lastComponentPosition = 0;
execute(() -> ediWriter.writeStartSegment(name.getLocalPart()));
elementStack.push(name);
break;
default:
break;
}
}
void writeComponentStart(QName name) throws XMLStreamException {
int position = getPosition(name, true);
while (position > lastComponentPosition + 1) {
lastComponentPosition++;
execute(ediWriter::writeEmptyComponent);
}
execute(ediWriter::startComponent);
lastComponentPosition++;
elementStack.push(name);
}
void writeElementStart(QName name) throws XMLStreamException {
int position = getPosition(name, false);
while (position > lastElementPosition + 1) {
lastElementPosition++;
execute(ediWriter::writeEmptyElement);
}
if (repeatedElement(name, previousElement)) {
execute(ediWriter::writeRepeatElement);
} else {
execute(ediWriter::writeStartElement);
}
lastElementPosition++;
elementStack.push(name);
}
void writeEnd() throws XMLStreamException {
QName name = elementStack.remove();
namespaceStack.remove();
switch (name.getNamespaceURI()) {
case EDINamespaces.COMPOSITES:
execute(ediWriter::endElement);
previousElement = name;
break;
case EDINamespaces.ELEMENTS:
if (EDINamespaces.COMPOSITES.equals(elementStack.element().getNamespaceURI())) {
execute(ediWriter::endComponent);
} else {
execute(ediWriter::endElement);
previousElement = name;
}
break;
case EDINamespaces.LOOPS:
// Loops are implicit when writing
break;
case EDINamespaces.SEGMENTS:
previousElement = null;
execute(ediWriter::writeEndSegment);
break;
default:
break;
}
}
@Override
public void writeStartElement(String localName) throws XMLStreamException {
String uri;
String local;
String prefix;
int idx = localName.indexOf(':');
if (idx >= 0) {
prefix = localName.substring(0, idx);
local = localName.substring(idx + 1);
uri = getNamespaceURI(prefix);
} else {
prefix = "";
local = localName;
uri = getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
}
if (INTERCHANGE.getLocalPart().equals(local)) {
writeStart(INTERCHANGE);
} else {
if (uri == null || uri.isEmpty()) {
throw new XMLStreamException("Element " + localName + " has an undefined namespace");
}
writeStart(new QName(uri, local, prefix));
}
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
writeStart(new QName(namespaceURI, localName));
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
writeStart(new QName(namespaceURI, localName, prefix));
}
@Override
public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
writeStartElement(namespaceURI, localName);
writeEnd();
}
@Override
public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
writeStartElement(prefix, localName, namespaceURI);
writeEnd();
}
@Override
public void writeEmptyElement(String localName) throws XMLStreamException {
writeStartElement(localName);
writeEnd();
}
@Override
public void writeEndElement() throws XMLStreamException {
writeEnd();
}
@Override
public void writeEndDocument() throws XMLStreamException {
execute(ediWriter::endInterchange);
}
@Override
public void close() throws XMLStreamException {
execute(ediWriter::close);
}
@Override
public void flush() throws XMLStreamException {
execute(ediWriter::flush);
}
@Override
public void writeAttribute(String localName, String value) throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeAttribute(String prefix,
String namespaceURI,
String localName,
String value)
throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
// No operation - ignored
}
@Override
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
// No operation - ignored
}
@Override
public void writeComment(String data) throws XMLStreamException {
// No operation - ignored
}
@Override
public void writeProcessingInstruction(String target) throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeCData(String data) throws XMLStreamException {
writeCharacters(data);
}
@Override
public void writeDTD(String dtd) throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeEntityRef(String name) throws XMLStreamException {
throw new UnsupportedOperationException();
}
@Override
public void writeStartDocument() throws XMLStreamException {
execute(ediWriter::startInterchange);
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
writeStartDocument();
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
writeStartDocument();
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
if (EDINamespaces.ELEMENTS.equals(elementStack.element().getNamespaceURI())) {
execute(() -> ediWriter.writeElementData(text));
} else {
for (int i = 0, m = text.length(); i < m; i++) {
if (!Character.isWhitespace(text.charAt(i))) {
throw new XMLStreamException(MSG_ILLEGAL_NONWHITESPACE);
}
}
}
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
if (EDINamespaces.ELEMENTS.equals(elementStack.element().getNamespaceURI())) {
execute(() -> ediWriter.writeElementData(text, start, start + len));
} else {
for (int i = start, m = start + len; i < m; i++) {
if (!Character.isWhitespace(text[i])) {
throw new XMLStreamException(MSG_ILLEGAL_NONWHITESPACE);
}
}
}
}
@Override
public String getPrefix(String uri) throws XMLStreamException {
return namespaceStack.stream()
.filter(m -> m.containsValue(uri))
.flatMap(m -> m.entrySet().stream())
.filter(e -> e.getValue().equals(uri))
.map(Map.Entry::getKey)
.findFirst()
.orElseGet(() -> getContextPrefix(uri));
}
String getNamespaceURI(String prefix) {
return namespaceStack.stream()
.filter(m -> m.containsKey(prefix))
.map(m -> m.get(prefix))
.findFirst()
.orElseGet(() -> getContextNamespaceURI(prefix));
}
String getContextNamespaceURI(String prefix) {
if (namespaceContext != null) {
return namespaceContext.getNamespaceURI(prefix);
}
return null;
}
String getContextPrefix(String uri) {
if (namespaceContext != null) {
return namespaceContext.getPrefix(uri);
}
return null;
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
Objects.requireNonNull(prefix);
if (uri != null) {
namespaceStack.element().put(prefix, uri);
} else {
namespaceStack.element().remove(prefix);
}
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
setPrefix(XMLConstants.DEFAULT_NS_PREFIX, uri);
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
if (this.namespaceContext != null) {
throw new XMLStreamException("NamespaceContext has already been set");
}
if (!elementStack.isEmpty()) {
throw new XMLStreamException("NamespaceContext must only be called at the start of the document");
}
this.namespaceContext = Objects.requireNonNull(context);
// Clear the root contexts (per setNamespaceContext JavaDoc)
namespaceStack.getLast().clear();
}
@Override
public NamespaceContext getNamespaceContext() {
return namespaceContext;
}
@Override
public Object getProperty(String name) {
throw new IllegalArgumentException("Properties not supported");
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIXMLStreamReader.java | src/main/java/io/xlate/edi/internal/stream/StaEDIXMLStreamReader.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.logging.Logger;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.internal.ThrowingRunnable;
import io.xlate.edi.internal.stream.tokenization.ProxyEventHandler;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.stream.EDIInputFactory;
import io.xlate.edi.stream.EDINamespaces;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamReader;
import io.xlate.edi.stream.EDIValidationException;
final class StaEDIXMLStreamReader implements XMLStreamReader {
private static final Logger LOGGER = Logger.getLogger(StaEDIXMLStreamReader.class.getName());
private static final QName DUMMY_QNAME = new QName("DUMMY");
private static final QName INTERCHANGE = new QName(EDINamespaces.LOOPS, "INTERCHANGE", prefixOf(EDINamespaces.LOOPS));
private static final QName TRANSACTION = new QName(EDINamespaces.LOOPS, ProxyEventHandler.LOOP_CODE_TRANSACTION, prefixOf(EDINamespaces.LOOPS));
private final EDIStreamReader ediReader;
private final Map<String, Object> properties;
private final boolean transactionDeclaresXmlns;
private final boolean wrapTransactionContents;
private final boolean useSegmentImplementationCodes;
private final Location location = new ProxyLocation();
private final Queue<Integer> eventQueue = new ArrayDeque<>(3);
private final Queue<QName> elementQueue = new ArrayDeque<>(3);
private final Deque<QName> elementStack = new ArrayDeque<>(5);
private final Deque<QName> standardNameStack = new ArrayDeque<>(5);
private boolean withinTransaction = false;
private boolean transactionWrapperEnqueued = false;
private String transactionStartSegment = null;
private String transactionEndSegment = null;
private int currentEvent = -1;
private QName currentElement;
private NamespaceContext namespaceContext;
private String compositeCode = null;
private final StringBuilder cdataBuilder = new StringBuilder();
private final OutputStream cdataStream = new OutputStream() {
@Override
public void write(int b) throws IOException {
cdataBuilder.append((char) b);
}
};
private char[] cdata;
StaEDIXMLStreamReader(EDIStreamReader ediReader, Map<String, Object> properties) throws XMLStreamException {
this.ediReader = ediReader;
this.properties = new HashMap<>(properties);
transactionDeclaresXmlns = Boolean.valueOf(String.valueOf(properties.get(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS)));
wrapTransactionContents = Boolean.valueOf(String.valueOf(properties.get(EDIInputFactory.XML_WRAP_TRANSACTION_CONTENTS)));
useSegmentImplementationCodes = Boolean.valueOf(String.valueOf(properties.get(EDIInputFactory.XML_USE_SEGMENT_IMPLEMENTATION_CODES)));
if (ediReader.getEventType() == EDIStreamEvent.START_INTERCHANGE) {
enqueueEvent(EDIStreamEvent.START_INTERCHANGE);
advanceEvent();
}
}
StaEDIXMLStreamReader(EDIStreamReader ediReader) throws XMLStreamException {
this(ediReader, Collections.emptyMap());
}
@Override
public Object getProperty(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
return properties.get(name);
}
boolean declareNamespaces(QName element) {
if (INTERCHANGE.equals(element)) {
return true;
}
return this.transactionDeclaresXmlns && TRANSACTION.equals(element);
}
private boolean isEvent(int... eventTypes) {
return Arrays.stream(eventTypes).anyMatch(type -> type == currentEvent);
}
private QName buildName(QName parent, String namespace) {
return buildName(parent, namespace, null);
}
private QName buildName(QName parent, String namespace, String name) {
String prefix = prefixOf(namespace);
if (name == null) {
final io.xlate.edi.stream.Location l = ediReader.getLocation();
final int componentPosition = l.getComponentPosition();
if (componentPosition > 0) {
String localPart = this.compositeCode != null ? this.compositeCode : parent.getLocalPart();
name = String.format("%s-%02d", localPart, componentPosition);
} else {
name = String.format("%s%02d", parent.getLocalPart(), l.getElementPosition());
}
}
return new QName(namespace, name, prefix);
}
private void enqueueEvent(int xmlEvent, QName element, boolean remember) {
enqueueEvent(xmlEvent, element, element, remember);
}
private void enqueueEvent(int xmlEvent, QName element, QName standardName, boolean remember) {
LOGGER.finer(() -> "Enqueue XML event: " + xmlEvent + ", element: " + element);
eventQueue.add(xmlEvent);
elementQueue.add(element);
if (remember) {
elementStack.addFirst(element);
standardNameStack.addFirst(standardName);
}
}
QName parentName() {
return standardNameStack.getFirst();
}
QName popElement() {
standardNameStack.removeFirst();
return elementStack.removeFirst();
}
private void advanceEvent() {
currentEvent = eventQueue.remove();
currentElement = elementQueue.remove();
}
private void enqueueEvent(EDIStreamEvent ediEvent) throws XMLStreamException {
LOGGER.finer(() -> "Enqueue EDI event: " + ediEvent);
final QName name;
cdataBuilder.setLength(0);
cdata = null;
String readerText = null;
switch (ediEvent) {
case ELEMENT_DATA:
name = buildName(parentName(), EDINamespaces.ELEMENTS);
enqueueEvent(START_ELEMENT, name, false);
enqueueEvent(CHARACTERS, DUMMY_QNAME, false);
enqueueEvent(END_ELEMENT, name, false);
break;
case ELEMENT_DATA_BINARY:
/*
* This section will read the binary data and Base64 the stream
* into an XML CDATA section.
* */
name = buildName(parentName(), EDINamespaces.ELEMENTS);
enqueueEvent(START_ELEMENT, name, false);
enqueueEvent(CDATA, DUMMY_QNAME, false);
copyBinaryDataToCDataBuilder();
enqueueEvent(END_ELEMENT, name, false);
break;
case START_INTERCHANGE:
enqueueEvent(START_DOCUMENT, DUMMY_QNAME, false);
enqueueEvent(START_ELEMENT, INTERCHANGE, true);
namespaceContext = new DocumentNamespaceContext();
break;
case START_SEGMENT:
readerText = ediReader.getText();
performTransactionWrapping(readerText);
QName standardName = buildName(parentName(), EDINamespaces.SEGMENTS, readerText);
name = useSegmentImplementationCodes ? buildName(parentName(), EDINamespaces.SEGMENTS, ediReader.getReferenceCode()) : standardName;
enqueueEvent(START_ELEMENT, name, standardName, true);
break;
case START_TRANSACTION:
withinTransaction = true;
name = buildName(parentName(), EDINamespaces.LOOPS, ediReader.getReferenceCode());
enqueueEvent(START_ELEMENT, name, true);
determineTransactionSegments();
break;
case START_GROUP:
case START_LOOP:
name = buildName(parentName(), EDINamespaces.LOOPS, ediReader.getReferenceCode());
enqueueEvent(START_ELEMENT, name, true);
break;
case START_COMPOSITE:
compositeCode = ediReader.getReferenceCode();
name = buildName(parentName(), EDINamespaces.COMPOSITES);
enqueueEvent(START_ELEMENT, name, true);
break;
case END_INTERCHANGE:
enqueueEvent(END_ELEMENT, popElement(), false);
namespaceContext = null;
enqueueEvent(END_DOCUMENT, DUMMY_QNAME, false);
break;
case END_TRANSACTION:
withinTransaction = false;
compositeCode = null;
enqueueEvent(END_ELEMENT, popElement(), false);
break;
case END_GROUP:
case END_LOOP:
case END_SEGMENT:
case END_COMPOSITE:
compositeCode = null;
enqueueEvent(END_ELEMENT, popElement(), false);
break;
case SEGMENT_ERROR:
case ELEMENT_OCCURRENCE_ERROR:
case ELEMENT_DATA_ERROR:
EDIValidationException cause = new EDIValidationException(ediEvent,
ediReader.getErrorType(),
ediReader.getLocation().copy(),
ediReader.getText());
throw new XMLStreamException("Validation exception reading EDI data as XML", this.location, cause);
default:
throw new IllegalStateException("Unknown state: " + ediEvent);
}
}
private void determineTransactionSegments() {
transactionStartSegment = null;
transactionEndSegment = null;
if (wrapTransactionContents) {
EDIComplexType tx = (EDIComplexType) ediReader.getSchemaTypeReference().getReferencedType();
List<EDIReference> segments = tx.getReferences();
transactionStartSegment = segments.get(0).getReferencedType().getId();
transactionEndSegment = segments.get(segments.size() - 1).getReferencedType().getId();
}
}
private void performTransactionWrapping(String readerText) {
if (withinTransaction && wrapTransactionContents) {
if (transactionWrapperEnqueued) {
if (readerText.equals(this.transactionEndSegment)) {
enqueueEvent(END_ELEMENT, popElement(), false);
transactionWrapperEnqueued = false;
}
} else {
if (!readerText.equals(this.transactionStartSegment)) {
String local = ediReader.getStandard() + '-' + ediReader.getTransactionType() + '-' + ediReader.getTransactionVersionString();
QName wrapper = new QName(EDINamespaces.LOOPS, local, prefixOf(EDINamespaces.LOOPS));
enqueueEvent(START_ELEMENT, wrapper, true);
transactionWrapperEnqueued = true;
}
}
}
}
private void copyBinaryDataToCDataBuilder() throws XMLStreamException {
// This only will work if using a validation filter!
InputStream input = ediReader.getBinaryData();
ThrowingRunnable.run(() -> {
byte[] buffer = new byte[4096];
int amount;
try (OutputStream output = Base64.getEncoder().wrap(cdataStream)) {
while ((amount = input.read(buffer)) > -1) {
output.write(buffer, 0, amount);
}
}
}, XMLStreamException::new);
}
private void requireCharacters() {
if (!isCharacters()) {
throw new IllegalStateException("Text only available for CHARACTERS");
}
}
@Override
public int next() throws XMLStreamException {
if (eventQueue.isEmpty()) {
LOGGER.finer(() -> "eventQueue is empty, calling ediReader.next()");
try {
enqueueEvent(ediReader.next());
} catch (XMLStreamException e) {
throw e;
} catch (Exception e) {
throw new XMLStreamException(e);
}
}
advanceEvent();
return getEventType();
}
@Override
public void require(int type, String namespaceURI, String localName) throws XMLStreamException {
final int currentType = getEventType();
if (currentType != type) {
throw new XMLStreamException("Current type " + currentType + " does not match required type " + type);
}
if (namespaceURI != null || localName != null) {
if (!hasName()) {
throw new XMLStreamException("Current type " + currentType + " does not have a corresponding name");
}
final QName name = getName();
if (localName != null) {
final String currentLocalPart = name.getLocalPart();
if (!localName.equals(currentLocalPart)) {
throw new XMLStreamException("Current localPart " + currentLocalPart
+ " does not match required localName " + localName);
}
}
if (namespaceURI != null) {
final String currentURI = name.getNamespaceURI();
if (!namespaceURI.equals(currentURI)) {
throw new XMLStreamException("Current namespace " + currentURI
+ " does not match required namespaceURI " + namespaceURI);
}
}
}
}
static XMLStreamException streamException(String message) {
return new XMLStreamException(message);
}
@Override
public String getElementText() throws XMLStreamException {
if (ediReader.getEventType() != EDIStreamEvent.ELEMENT_DATA) {
throw streamException("Element text only available for simple element");
}
if (getEventType() != START_ELEMENT) {
throw streamException("Element text only available on START_ELEMENT");
}
next(); // Advance to the text/CDATA
final String text = getText();
int eventType = next();
if (eventType != END_ELEMENT) {
throw streamException("Unexpected event type after text " + eventType);
}
return text;
}
@Override
public int nextTag() throws XMLStreamException {
int eventType;
do {
eventType = next();
} while (eventType != START_ELEMENT && eventType != END_ELEMENT);
return eventType;
}
@Override
public boolean hasNext() throws XMLStreamException {
try {
return !eventQueue.isEmpty() || ediReader.hasNext();
} catch (Exception e) {
throw new XMLStreamException(e);
}
}
@Override
public void close() throws XMLStreamException {
eventQueue.clear();
elementQueue.clear();
elementStack.clear();
standardNameStack.clear();
ThrowingRunnable.run(ediReader::close, XMLStreamException::new);
}
@Override
public String getNamespaceURI(String prefix) {
if (namespaceContext != null) {
return namespaceContext.getNamespaceURI(prefix);
}
return null;
}
@Override
public boolean isStartElement() {
return isEvent(START_ELEMENT);
}
@Override
public boolean isEndElement() {
return isEvent(END_ELEMENT);
}
@Override
public boolean isCharacters() {
return isEvent(CHARACTERS, CDATA);
}
@Override
public boolean isWhiteSpace() {
return false;
}
@Override
public String getAttributeValue(String namespaceURI, String localName) {
throw new UnsupportedOperationException();
}
@Override
public int getAttributeCount() {
return 0;
}
@Override
public QName getAttributeName(int index) {
throw new UnsupportedOperationException();
}
@Override
public String getAttributeNamespace(int index) {
throw new UnsupportedOperationException();
}
@Override
public String getAttributeLocalName(int index) {
throw new UnsupportedOperationException();
}
@Override
public String getAttributePrefix(int index) {
throw new UnsupportedOperationException();
}
@Override
public String getAttributeType(int index) {
throw new UnsupportedOperationException();
}
@Override
public String getAttributeValue(int index) {
throw new UnsupportedOperationException();
}
@Override
public boolean isAttributeSpecified(int index) {
throw new UnsupportedOperationException();
}
@Override
public int getNamespaceCount() {
if (declareNamespaces(currentElement)) {
return EDINamespaces.all().size();
}
return 0;
}
@Override
public String getNamespacePrefix(int index) {
if (declareNamespaces(currentElement)) {
String namespace = EDINamespaces.all().get(index);
return prefixOf(namespace);
}
return null;
}
@Override
public String getNamespaceURI(int index) {
if (declareNamespaces(currentElement)) {
return EDINamespaces.all().get(index);
}
return null;
}
@Override
public NamespaceContext getNamespaceContext() {
return this.namespaceContext;
}
@Override
public int getEventType() {
return currentEvent;
}
@Override
public String getText() {
requireCharacters();
if (cdataBuilder.length() > 0) {
if (cdata == null) {
cdata = new char[cdataBuilder.length()];
cdataBuilder.getChars(0, cdataBuilder.length(), cdata, 0);
}
return new String(cdata);
}
return ediReader.getText();
}
@Override
public char[] getTextCharacters() {
requireCharacters();
if (cdataBuilder.length() > 0) {
if (cdata == null) {
cdata = new char[cdataBuilder.length()];
cdataBuilder.getChars(0, cdataBuilder.length(), cdata, 0);
}
return cdata;
}
return ediReader.getTextCharacters();
}
@Override
public int getTextCharacters(int sourceStart,
char[] target,
int targetStart,
int length) throws XMLStreamException {
requireCharacters();
if (cdataBuilder.length() > 0) {
if (cdata == null) {
cdata = new char[cdataBuilder.length()];
cdataBuilder.getChars(0, cdataBuilder.length(), cdata, 0);
}
if (targetStart < 0) {
throw new IndexOutOfBoundsException("targetStart < 0");
}
if (targetStart > target.length) {
throw new IndexOutOfBoundsException("targetStart > target.length");
}
if (length < 0) {
throw new IndexOutOfBoundsException("length < 0");
}
if (targetStart + length > target.length) {
throw new IndexOutOfBoundsException("targetStart + length > target.length");
}
System.arraycopy(cdata, sourceStart, target, targetStart, length);
return length;
}
return ediReader.getTextCharacters(sourceStart, target, targetStart, length);
}
@Override
public int getTextStart() {
requireCharacters();
if (cdataBuilder.length() > 0) {
return 0;
}
return ediReader.getTextStart();
}
@Override
public int getTextLength() {
requireCharacters();
if (cdataBuilder.length() > 0) {
return cdataBuilder.length();
}
return ediReader.getTextLength();
}
@Override
public String getEncoding() {
return null;
}
@Override
public boolean hasText() {
return isCharacters();
}
@Override
public Location getLocation() {
return location;
}
@Override
public QName getName() {
if (hasName()) {
return currentElement;
}
throw new IllegalStateException("Text only available for START_ELEMENT or END_ELEMENT");
}
@Override
public String getLocalName() {
return getName().getLocalPart();
}
@Override
public boolean hasName() {
return isStartElement() || isEndElement();
}
@Override
public String getNamespaceURI() {
if (hasName()) {
return currentElement.getNamespaceURI();
}
return null;
}
@Override
public String getPrefix() {
return null;
}
@Override
public String getVersion() {
return null;
}
@Override
public boolean isStandalone() {
return false;
}
@Override
public boolean standaloneSet() {
return false;
}
@Override
public String getCharacterEncodingScheme() {
return null;
}
@Override
public String getPITarget() {
throw new UnsupportedOperationException();
}
@Override
public String getPIData() {
throw new UnsupportedOperationException();
}
static String prefixOf(String namespace) {
return String.valueOf(namespace.substring(namespace.lastIndexOf(':') + 1).charAt(0));
}
private class ProxyLocation implements Location {
@Override
public int getLineNumber() {
return ediReader.getLocation().getLineNumber();
}
@Override
public int getColumnNumber() {
return ediReader.getLocation().getColumnNumber();
}
@Override
public int getCharacterOffset() {
return ediReader.getLocation().getCharacterOffset();
}
@Override
public String getPublicId() {
return null;
}
@Override
public String getSystemId() {
return null;
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/LocationView.java | src/main/java/io/xlate/edi/internal/stream/LocationView.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import io.xlate.edi.stream.Location;
abstract class LocationView implements Location {
protected int lineNumber;
protected int columnNumber;
protected int characterOffset;
protected int segmentPosition;
protected String segmentTag;
protected int elementPosition;
protected int componentPosition;
protected int elementOccurrence;
protected LocationView(Location source) {
lineNumber = source.getLineNumber();
columnNumber = source.getColumnNumber();
characterOffset = source.getCharacterOffset();
segmentPosition = source.getSegmentPosition();
segmentTag = source.getSegmentTag();
elementPosition = source.getElementPosition();
elementOccurrence = source.getElementOccurrence();
componentPosition = source.getComponentPosition();
}
protected LocationView() {
lineNumber = 1;
columnNumber = 0;
characterOffset = 0;
segmentPosition = -1;
elementPosition = -1;
componentPosition = -1;
elementOccurrence = -1;
}
protected String toString(boolean afterSegment) {
StringBuilder display = new StringBuilder();
if (getSegmentPosition() < 0) {
display.append("at offset ");
display.append(getCharacterOffset());
} else {
display.append(afterSegment ? "after " : "in ");
display.append("segment ");
display.append(String.valueOf(getSegmentTag()));
display.append(" at position ");
display.append(String.valueOf(getSegmentPosition()));
if (getElementPosition() > -1) {
display.append(", element ");
display.append(String.valueOf(getElementPosition()));
if (getElementOccurrence() > 1) {
display.append(" (occurrence ");
display.append(String.valueOf(getElementOccurrence()));
display.append(')');
}
}
if (getComponentPosition() > -1) {
display.append(", component ");
display.append(String.valueOf(getComponentPosition()));
}
}
return display.toString();
}
@Override
public int getLineNumber() {
return lineNumber;
}
@Override
public int getColumnNumber() {
return columnNumber;
}
@Override
public int getCharacterOffset() {
return characterOffset;
}
@Override
public int getSegmentPosition() {
return segmentPosition;
}
@Override
public String getSegmentTag() {
return segmentTag;
}
@Override
public int getElementPosition() {
return elementPosition;
}
@Override
public int getComponentPosition() {
return componentPosition;
}
@Override
public int getElementOccurrence() {
return elementOccurrence;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/CharArraySequence.java | src/main/java/io/xlate/edi/internal/stream/CharArraySequence.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import java.nio.CharBuffer;
public class CharArraySequence implements CharSequence, Comparable<CharSequence> {
private static final char[] EMPTY = {};
private char[] text = EMPTY;
private int start = 0;
private int length = 0;
public void set(char[] text, int start, int length) {
this.text = text;
this.start = start;
this.length = length;
}
public void clear() {
this.text = EMPTY;
this.start = 0;
this.length = 0;
}
public void putToBuffer(CharBuffer buffer) {
buffer.put(text, start, length);
}
@Override
public int length() {
return length;
}
@Override
public char charAt(int index) {
if (index < 0 || index >= length) {
throw new StringIndexOutOfBoundsException(index);
}
return text[start + index];
}
@Override
public CharSequence subSequence(int start, int end) {
if (start < 0) {
throw new IndexOutOfBoundsException(Integer.toString(start));
}
if (end > length) {
throw new IndexOutOfBoundsException(Integer.toString(end));
}
if (start > end) {
throw new IndexOutOfBoundsException(Integer.toString(end - start));
}
return ((start == 0) && (end == length))
? this
: new String(text, this.start + start, end - start);
}
@Override
@SuppressWarnings("java:S1210") // equals & hashCode are not used with this class
public int compareTo(CharSequence other) {
int len1 = length;
int len2 = other.length();
int n = Math.min(len1, len2);
char[] v1 = text;
int i = start;
int j = 0;
while (n-- != 0) {
char c1 = v1[i++];
char c2 = other.charAt(j++);
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
}
@Override
public String toString() {
return (length > 0) ? new String(text, start, length) : "";
}
} | java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/Configurable.java | src/main/java/io/xlate/edi/internal/stream/Configurable.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import java.util.function.Function;
public interface Configurable {
Object getProperty(String name);
default <T> T getProperty(String name, Function<String, T> parser, T defaultValue) {
Object property = getProperty(name);
if (property == null) {
return defaultValue;
}
return parser.apply(property.toString());
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIInputFactory.java | src/main/java/io/xlate/edi/internal/stream/StaEDIInputFactory.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.internal.stream.json.JsonParserFactory;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.stream.EDIInputErrorReporter;
import io.xlate.edi.stream.EDIInputFactory;
import io.xlate.edi.stream.EDIStreamException;
import io.xlate.edi.stream.EDIStreamFilter;
import io.xlate.edi.stream.EDIStreamReader;
public class StaEDIInputFactory extends EDIInputFactory {
private EDIInputErrorReporter reporter;
@SuppressWarnings("deprecation")
public StaEDIInputFactory() {
supportedProperties.add(EDI_VALIDATE_CONTROL_STRUCTURE);
supportedProperties.add(EDI_VALIDATE_CONTROL_CODE_VALUES);
supportedProperties.add(EDI_IGNORE_EXTRANEOUS_CHARACTERS);
supportedProperties.add(EDI_NEST_HIERARCHICAL_LOOPS);
supportedProperties.add(EDI_ENABLE_LOOP_TEXT);
supportedProperties.add(EDI_TRIM_DISCRIMINATOR_VALUES);
supportedProperties.add(XML_DECLARE_TRANSACTION_XMLNS);
supportedProperties.add(XML_WRAP_TRANSACTION_CONTENTS);
supportedProperties.add(XML_USE_SEGMENT_IMPLEMENTATION_CODES);
supportedProperties.add(JSON_NULL_EMPTY_ELEMENTS);
supportedProperties.add(JSON_OBJECT_ELEMENTS);
}
@Override
public EDIStreamReader createEDIStreamReader(InputStream stream) {
return createEDIStreamReader(stream, (Schema) null);
}
@Override
public EDIStreamReader createEDIStreamReader(InputStream stream, String encoding) throws EDIStreamException {
return createEDIStreamReader(stream, encoding, null);
}
@Override
public EDIStreamReader createEDIStreamReader(InputStream stream, Schema schema) {
Objects.requireNonNull(stream, "stream must not be null");
return new StaEDIStreamReader(stream, StandardCharsets.UTF_8, schema, properties, getErrorReporter());
}
@SuppressWarnings("resource")
@Override
public EDIStreamReader createEDIStreamReader(InputStream stream, String encoding, Schema schema) throws EDIStreamException {
Objects.requireNonNull(stream, "stream must not be null");
if (Charset.isSupported(encoding)) {
return new StaEDIStreamReader(stream, Charset.forName(encoding), schema, properties, getErrorReporter());
}
throw new EDIStreamException("Unsupported encoding: " + encoding);
}
@Override
public EDIStreamReader createFilteredReader(EDIStreamReader reader, EDIStreamFilter filter) {
return new StaEDIFilteredStreamReader(reader, filter);
}
@Override
public XMLStreamReader createXMLStreamReader(EDIStreamReader reader) throws XMLStreamException {
return new StaEDIXMLStreamReader(reader, properties);
}
@Override
public <J> J createJsonParser(EDIStreamReader reader, Class<J> type) {
return JsonParserFactory.createJsonParser(reader, type, properties);
}
@Override
public EDIInputErrorReporter getErrorReporter() {
return reporter;
}
@Override
public void setErrorReporter(EDIInputErrorReporter reporter) {
this.reporter = reporter;
}
@Override
@SuppressWarnings({ "java:S1123", "java:S1133" })
@Deprecated /*(forRemoval = true, since = "1.9")*/
public io.xlate.edi.stream.EDIReporter getEDIReporter() {
EDIInputErrorReporter errorReporter = getErrorReporter();
if (errorReporter instanceof io.xlate.edi.stream.EDIReporter) {
return (io.xlate.edi.stream.EDIReporter) errorReporter;
}
throw new ClassCastException("Can not cast reporter to EDIReporter; did you mean to call getErrorReporter() ?");
}
@Override
@SuppressWarnings({ "java:S1123", "java:S1133" })
@Deprecated /*(forRemoval = true, since = "1.9")*/
public void setEDIReporter(io.xlate.edi.stream.EDIReporter reporter) {
setErrorReporter(reporter);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/ValidationEventHandler.java | src/main/java/io/xlate/edi/internal/stream/tokenization/ValidationEventHandler.java | package io.xlate.edi.internal.stream.tokenization;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamValidationError;
public interface ValidationEventHandler {
void loopBegin(EDIReference typeReference);
void loopEnd(EDIReference typeReference);
void segmentError(CharSequence token, EDIReference typeReference, EDIStreamValidationError error);
void elementError(EDIStreamEvent event,
EDIStreamValidationError error,
EDIReference typeReference,
CharSequence text,
int element,
int component,
int repetition);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/EDIException.java | src/main/java/io/xlate/edi/internal/stream/tokenization/EDIException.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import java.util.HashMap;
import java.util.Map;
import io.xlate.edi.stream.EDIStreamException;
import io.xlate.edi.stream.Location;
public class EDIException extends EDIStreamException {
private static final long serialVersionUID = -2724168743697298348L;
public static final Integer MISSING_HANDLER = 1;
public static final Integer UNSUPPORTED_DIALECT = 2;
public static final Integer INVALID_STATE = 3;
public static final Integer INVALID_CHARACTER = 4;
public static final Integer INCOMPLETE_STREAM = 5;
private static final Map<Integer, String> exceptionMessages = new HashMap<>();
static {
exceptionMessages.put(MISSING_HANDLER,
"EDIE001 - Missing required handler");
exceptionMessages.put(UNSUPPORTED_DIALECT,
"EDIE002 - Unsupported EDI dialect");
exceptionMessages.put(INVALID_STATE,
"EDIE003 - Invalid processing state");
exceptionMessages.put(INVALID_CHARACTER,
"EDIE004 - Invalid character");
exceptionMessages.put(INCOMPLETE_STREAM,
"EDIE005 - Unexpected end of stream");
}
public EDIException(String message) {
super(message);
}
EDIException(Integer id, Location location) {
super(exceptionMessages.get(id), location);
}
EDIException(Integer id, String message, Location location) {
super(buildMessage(exceptionMessages.get(id), location) + "; " + message, location);
}
public EDIException(Integer id, String message) {
super(exceptionMessages.get(id) + "; " + message);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/CharacterClass.java | src/main/java/io/xlate/edi/internal/stream/tokenization/CharacterClass.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
public enum CharacterClass {
/*
* Characters are mapped into these character classes. This allows for a
* significant reduction in the size of the state transition table.
*/
SPACE(ClassSequence.sequence++),
LATIN_A(ClassSequence.sequence++),
LATIN_B(ClassSequence.sequence++),
LATIN_D(ClassSequence.sequence++),
LATIN_E(ClassSequence.sequence++),
LATIN_I(ClassSequence.sequence++),
LATIN_N(ClassSequence.sequence++),
LATIN_S(ClassSequence.sequence++),
LATIN_T(ClassSequence.sequence++),
LATIN_U(ClassSequence.sequence++),
LATIN_X(ClassSequence.sequence++),
LATIN_Z(ClassSequence.sequence++),
ALPHANUMERIC(ClassSequence.sequence++),
SEGMENT_DELIMITER(ClassSequence.sequence++),
ELEMENT_DELIMITER(ClassSequence.sequence++),
COMPONENT_DELIMITER(ClassSequence.sequence++),
ELEMENT_REPEATER(ClassSequence.sequence++),
RELEASE_CHARACTER(ClassSequence.sequence++),
WHITESPACE(ClassSequence.sequence++), /* Other white space */
CONTROL(ClassSequence.sequence++), /* Control Characters */
OTHER(ClassSequence.sequence++), /* Everything else */
INVALID(ClassSequence.sequence++),
SEGMENT_TAG_DELIMITER(ClassSequence.sequence++) /* Used for TRADACOMS only */;
private static class ClassSequence {
static int sequence = 0;
}
protected final int code;
private CharacterClass(int code) {
this.code = code;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/EDIFACTDialect.java | src/main/java/io/xlate/edi/internal/stream/tokenization/EDIFACTDialect.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import io.xlate.edi.stream.EDIStreamConstants.Standards;
import io.xlate.edi.stream.Location;
public class EDIFACTDialect extends Dialect {
public static final String UNA = "UNA";
public static final String UNB = "UNB";
static final char DFLT_SEGMENT_TERMINATOR = '\'';
static final char DFLT_DATA_ELEMENT_SEPARATOR = '+';
static final char DFLT_COMPONENT_ELEMENT_SEPARATOR = ':';
static final char DFLT_REPETITION_SEPARATOR = '*';
static final char DFLT_RELEASE_CHARACTER = '?';
static final char DFLT_DECIMAL_MARK = '.';
static final char ALT_DECIMAL_MARK = ',';
private static final int EDIFACT_UNA_LENGTH = 9;
private final String headerTag;
private String[] version;
StringBuilder header;
private int index = -1;
private int unbStart = -1;
private boolean variableDecimalMark;
private static final int TX_AGENCY = 0;
private static final int TX_VERSION = 1;
private static final int TX_RELEASE = 2;
private static final int TX_ASSIGNED_CODE = 3;
EDIFACTDialect(String headerTag) {
super(State.DialectCode.EDIFACT, new String[4]);
componentDelimiter = DFLT_COMPONENT_ELEMENT_SEPARATOR;
elementDelimiter = DFLT_DATA_ELEMENT_SEPARATOR;
decimalMark = DFLT_DECIMAL_MARK;
releaseIndicator = DFLT_RELEASE_CHARACTER;
elementRepeater = DFLT_REPETITION_SEPARATOR;
segmentDelimiter = DFLT_SEGMENT_TERMINATOR;
this.headerTag = headerTag;
clearTransactionVersion();
}
@Override
public String getHeaderTag() {
return headerTag;
}
@Override
public boolean isDecimalMark(char value) {
if (variableDecimalMark) {
return value == DFLT_DECIMAL_MARK || value == ALT_DECIMAL_MARK;
}
return super.isDecimalMark(value);
}
boolean initialize(CharacterSet characters) {
String[] parsedVersion = parseVersion();
if (parsedVersion.length > 1) {
this.version = parsedVersion;
final String syntaxVersion = this.version[1];
final boolean v4plus = syntaxVersion.compareTo("4") >= 0;
characters.setClass(componentDelimiter, CharacterClass.COMPONENT_DELIMITER);
characters.setClass(elementDelimiter, CharacterClass.ELEMENT_DELIMITER);
if (v4plus || !isServiceAdviceSegment(headerTag)) {
/*
* Decimal mark is variable:
* - always in version 4
* - when UNA segment is not received prior to version 4
*/
variableDecimalMark = true;
}
if (v4plus || releaseIndicator != ' ') {
// Must not be blank for version 4 and above, may be blank before version 4 if not used
characters.setClass(releaseIndicator, CharacterClass.RELEASE_CHARACTER);
} else {
releaseIndicator = '\0';
}
if (v4plus) {
// Must not be blank for version 4 and above
characters.setClass(elementRepeater, CharacterClass.ELEMENT_REPEATER);
} else {
elementRepeater = '\0';
}
characters.setClass(segmentDelimiter, CharacterClass.SEGMENT_DELIMITER);
initialized = true;
} else {
rejectionMessage = "Unable to obtain version from EDIFACT header segment";
initialized = false;
}
return initialized;
}
private String[] parseVersion() {
final int versionStart = findVersionStart();
String versionComposite = findVersionString(versionStart, elementDelimiter);
if (versionComposite == null) {
// Handle the case where the segment was terminated prematurely (zero or one element)
versionComposite = findVersionString(versionStart, segmentDelimiter);
}
return versionComposite.split('\\' + String.valueOf(componentDelimiter));
}
int findVersionStart() {
// Skip four characters: UNB<delim>
return UNB.equals(headerTag) ? 4 : unbStart + 4;
}
String findVersionString(int versionStart, char delimiter) {
final int versionEnd = header.indexOf(String.valueOf(delimiter), versionStart);
if (versionEnd - versionStart > -1) {
return header.substring(versionStart, versionEnd);
}
return null;
}
@Override
public boolean isServiceAdviceSegment(CharSequence tag) {
return UNA.contentEquals(tag);
}
@Override
public State getTagSearchState() {
if (isServiceAdviceSegment(this.headerTag)) {
return State.HEADER_EDIFACT_UNB_SEARCH;
}
return State.TAG_SEARCH;
}
@Override
public String getStandard() {
return Standards.EDIFACT;
}
@Override
public String[] getVersion() {
return version;
}
@Override
public boolean appendHeader(CharacterSet characters, char value) {
boolean proceed = true;
if (++index == 0) {
header = new StringBuilder();
}
if (UNB.equals(headerTag)) {
if (characters.isIgnored(value)) {
index--;
} else {
header.append(value);
proceed = processInterchangeHeader(characters, value);
}
} else {
header.append(value);
proceed = processServiceStringAdvice(characters, value);
}
return proceed;
}
boolean processInterchangeHeader(CharacterSet characters, char value) {
if (index == 0) {
characters.setClass(componentDelimiter, CharacterClass.COMPONENT_DELIMITER);
} else if (index == 3) {
/*
* Do not set the element delimiter until after the segment tag has been passed
* to prevent triggering an "element data" event prematurely.
*/
characters.setClass(elementDelimiter, CharacterClass.ELEMENT_DELIMITER);
} else if (segmentDelimiter == value) {
initialize(characters);
return isConfirmed();
}
return true;
}
boolean processServiceStringAdvice(CharacterSet characters, char value) {
boolean proceed = true;
switch (index) {
case 3:
componentDelimiter = value;
setCharacterClass(characters, CharacterClass.COMPONENT_DELIMITER, value, true);
break;
case 4:
elementDelimiter = value;
setCharacterClass(characters, CharacterClass.ELEMENT_DELIMITER, value, true);
break;
case 5:
decimalMark = value;
break;
case 6:
releaseIndicator = value;
setCharacterClass(characters, CharacterClass.RELEASE_CHARACTER, value, false);
break;
case 7:
elementRepeater = value;
// Do not set the character class until initialize() is executed
break;
case 8:
segmentDelimiter = value;
setCharacterClass(characters, CharacterClass.SEGMENT_DELIMITER, value, true);
break;
default:
break;
}
if (index >= EDIFACT_UNA_LENGTH) {
if (characters.isIgnored(value)) {
header.deleteCharAt(index--);
} else if (isIndexBeyondUNBFirstElement()) {
if (value == elementDelimiter || value == segmentDelimiter) {
initialize(characters);
proceed = isConfirmed();
}
} else if (value == 'B') {
CharSequence un = header.subSequence(index - 2, index);
if ("UN".contentEquals(un)) {
unbStart = index - 2;
} else {
// Some other segment / element?
rejectionMessage = String.format("Expected UNB segment following UNA but received %s%s", un, value);
proceed = false;
}
} else if (isUnexpectedSegmentDetected(value)) {
// Some other segment / element?
rejectionMessage = String.format("Expected UNB segment following UNA but received %s", header.subSequence(EDIFACT_UNA_LENGTH, index));
proceed = false;
}
}
return proceed;
}
boolean isIndexBeyondUNBFirstElement() {
return unbStart > -1 && (index - unbStart) > 3;
}
boolean isUnexpectedSegmentDetected(int value) {
return unbStart < 0 && (value == elementDelimiter || value == segmentDelimiter);
}
void setCharacterClass(CharacterSet characters, CharacterClass charClass, char value, boolean allowSpace) {
if (value != ' ' || allowSpace) {
characters.setClass(value, charClass);
}
}
@Override
public void clearTransactionVersion() {
for (int i = 0; i < transactionVersion.length; i++) {
transactionVersion[i] = "";
}
updateTransactionVersionString(null);
}
@Override
public void elementData(CharSequence data, Location location) {
switch (location.getSegmentTag()) {
case "UNG":
groupHeaderElementData(data, location);
break;
case "UNH":
messageHeaderElementData(data, location);
break;
default:
break;
}
}
void groupHeaderElementData(CharSequence data, Location location) {
if (location.getElementPosition() == 1) {
clearTransactionVersion();
} else if (location.getElementPosition() == 6) {
setTransactionVersionElement(data, TX_AGENCY);
} else if (location.getElementPosition() == 7) {
switch (location.getComponentPosition()) {
case 1:
setTransactionVersionElement(data, TX_VERSION);
break;
case 2:
setTransactionVersionElement(data, TX_RELEASE);
break;
case 3:
setTransactionVersionElement(data, TX_ASSIGNED_CODE);
break;
default:
break;
}
}
}
void messageHeaderElementData(CharSequence data, Location location) {
if (location.getElementPosition() == 1) {
clearTransactionVersion();
} else if (location.getElementPosition() == 2) {
switch (location.getComponentPosition()) {
case 1:
transactionType = data.toString();
break;
case 2:
setTransactionVersionElement(data, TX_VERSION);
break;
case 3:
setTransactionVersionElement(data, TX_RELEASE);
break;
case 4:
setTransactionVersionElement(data, TX_AGENCY);
break;
case 5:
setTransactionVersionElement(data, TX_ASSIGNED_CODE);
break;
default:
break;
}
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/StreamEvent.java | src/main/java/io/xlate/edi/internal/stream/tokenization/StreamEvent.java | package io.xlate.edi.internal.stream.tokenization;
import java.nio.CharBuffer;
import io.xlate.edi.internal.stream.CharArraySequence;
import io.xlate.edi.internal.stream.StaEDIStreamLocation;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamValidationError;
public class StreamEvent {
private static final String TOSTRING_FORMAT = "type: %s, error: %s, data: %s, typeReference: %s, location: { %s }";
EDIStreamEvent type;
EDIStreamValidationError errorType;
CharBuffer data;
boolean dataNull = true;
EDIReference typeReference;
StaEDIStreamLocation location;
public void update(EDIStreamEvent type, EDIStreamValidationError errorType, CharSequence data, EDIReference typeReference, StaEDIStreamLocation location) {
this.type = type;
this.errorType = errorType;
setData(data);
setTypeReference(typeReference);
setLocation(location);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, type, errorType, data, typeReference, location);
}
public EDIStreamEvent getType() {
return type;
}
public EDIStreamValidationError getErrorType() {
return errorType;
}
public CharBuffer getData() {
return dataNull ? null : data;
}
public void setData(CharSequence data) {
if (data != null) {
this.data = put(this.data, data);
this.dataNull = false;
} else {
this.dataNull = true;
}
}
public String getReferenceCode() {
if (typeReference instanceof EDITypeImplementation) {
return ((EDITypeImplementation) typeReference).getCode();
}
if (typeReference != null) {
return typeReference.getReferencedType().getCode();
}
return null;
}
public EDIReference getTypeReference() {
return typeReference;
}
public void setTypeReference(EDIReference typeReference) {
this.typeReference = typeReference;
}
public StaEDIStreamLocation getLocation() {
return location;
}
public void setLocation(StaEDIStreamLocation location) {
if (this.location == null) {
this.location = new StaEDIStreamLocation(location);
}
this.location.set(location);
}
static CharBuffer put(CharBuffer buffer, CharSequence text) {
final int length = text.length();
if (buffer == null || buffer.capacity() < length) {
buffer = CharBuffer.allocate(length);
}
buffer.clear();
if (text instanceof CharArraySequence) {
if (length > 0) {
// Slightly optimized
((CharArraySequence) text).putToBuffer(buffer);
}
} else {
for (int i = 0; i < length; i++) {
buffer.put(text.charAt(i));
}
}
buffer.flip();
return buffer;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/DialectFactory.java | src/main/java/io/xlate/edi/internal/stream/tokenization/DialectFactory.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
public interface DialectFactory {
enum DialectTag {
X12("ISA"),
EDIFACT_A("UNA"),
EDIFACT_B("UNB"),
TRADACOMS("STX");
private String tag;
DialectTag(String tag) {
this.tag = tag;
}
public static DialectTag fromValue(String tag) {
for (DialectTag d : DialectTag.values()) {
if (d.tag.equals(tag)) {
return d;
}
}
return null;
}
}
public static Dialect getDialect(char[] buffer, int start, int length) throws EDIException {
String tag = new String(buffer, start, length);
return getDialect(tag);
}
public static Dialect getDialect(String tag) throws EDIException {
DialectTag type = DialectTag.fromValue(tag);
if (type != null) {
Dialect dialect;
switch (type) {
case X12:
dialect = new X12Dialect();
break;
case TRADACOMS:
dialect = new TradacomsDialect();
break;
default:
dialect = new EDIFACTDialect(tag);
break;
}
return dialect;
}
throw new EDIException(EDIException.UNSUPPORTED_DIALECT, tag);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/ElementDataHandler.java | src/main/java/io/xlate/edi/internal/stream/tokenization/ElementDataHandler.java | package io.xlate.edi.internal.stream.tokenization;
import java.io.InputStream;
public interface ElementDataHandler {
boolean elementData(CharSequence text, boolean fromStream);
boolean binaryData(InputStream binary);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/State.java | src/main/java/io/xlate/edi/internal/stream/tokenization/State.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import java.util.Objects;
/*
* Processing states.
*/
public enum State {
// Initial States
INVALID(DialectCode.UNKNOWN, Category.INVALID),
INITIAL(DialectCode.UNKNOWN, Category.INITIAL),
INTERCHANGE_END(DialectCode.UNKNOWN, Category.INITIAL),
HEADER_EDIFACT_U(DialectCode.UNKNOWN, Category.EDIFACT_1),
HEADER_EDIFACT_N(DialectCode.UNKNOWN, Category.EDIFACT_2),
HEADER_TRADACOMS_S(DialectCode.UNKNOWN, Category.TRADACOMS_1),
HEADER_TRADACOMS_T(DialectCode.UNKNOWN, Category.TRADACOMS_2),
HEADER_X12_I(DialectCode.UNKNOWN, Category.X12_1),
HEADER_X12_S(DialectCode.UNKNOWN, Category.X12_2),
// Common States (shared among dialects)
INTERCHANGE_CANDIDATE(Category.HEADER), // IC
HEADER_DATA(Category.HEADER), // HD
HEADER_SEGMENT_BEGIN(Category.HEADER),
HEADER_INVALID_DATA(Category.HEADER), // HV
HEADER_COMPONENT_END(Category.HEADER), // HC
HEADER_ELEMENT_END(Category.HEADER), // HE
HEADER_SEGMENT_END(Category.HEADER),
HEADER_RELEASE(Category.HEADER_RELEASE), // HR
TAG_SEARCH(Category.TAG_SEARCH),
SEGMENT_END(Category.TAG_SEARCH),
SEGMENT_EMPTY(Category.TAG_SEARCH),
TAG_1(Category.TAG_1),
TAG_2(Category.TAG_2),
TAG_3(Category.TAG_3),
SEGMENT_BEGIN(Category.ELEMENT_PROCESS),
ELEMENT_DATA(Category.ELEMENT_PROCESS),
ELEMENT_INVALID_DATA(Category.ELEMENT_PROCESS),
COMPONENT_END(Category.ELEMENT_PROCESS),
ELEMENT_REPEAT(Category.ELEMENT_PROCESS),
ELEMENT_END(Category.ELEMENT_PROCESS),
DATA_RELEASE(Category.DATA_RELEASE),
ELEMENT_DATA_BINARY(Category.DATA_BINARY),
ELEMENT_END_BINARY(Category.DATA_BINARY_END),
TRAILER_BEGIN(Category.TRAILER),
TRAILER_ELEMENT_DATA(Category.TRAILER),
TRAILER_ELEMENT_END(Category.TRAILER),
// EDIFACT
TRAILER_EDIFACT_U(Category.TERM_7),
TRAILER_EDIFACT_N(Category.TERM_8),
TRAILER_EDIFACT_Z(Category.TERM_9),
HEADER_EDIFACT_UNB_SEARCH(Category.EDIFACT_UNB_0), // EDIFACT UNA -> UNB Only
HEADER_EDIFACT_UNB_1(Category.EDIFACT_UNB_1), // EDIFACT UNA -> UNB Only
HEADER_EDIFACT_UNB_2(Category.EDIFACT_UNB_2), // EDIFACT UNA -> UNB Only
HEADER_EDIFACT_UNB_3(Category.EDIFACT_UNB_3), // EDIFACT UNA -> UNB Only
// TRADACOMS
TRAILER_TRADACOMS_E(Category.TERM_7),
TRAILER_TRADACOMS_N(Category.TERM_8),
TRAILER_TRADACOMS_D(Category.TERM_9),
// X12
TRAILER_X12_I(Category.TERM_7),
TRAILER_X12_E(Category.TERM_8),
TRAILER_X12_A(Category.TERM_9);
public static final class DialectCode {
private DialectCode() {}
public static final int UNKNOWN = 0;
public static final int EDIFACT = 1;
public static final int TRADACOMS = 2;
public static final int X12 = 3;
}
private static final class Category {
// Initial
static final int INVALID = -1;
static final int INITIAL = 0;
static final int EDIFACT_1 = 1;
static final int EDIFACT_2 = 2;
static final int TRADACOMS_1 = 3;
static final int TRADACOMS_2 = 4;
static final int X12_1 = 5;
static final int X12_2 = 6;
// Common (placed in dialect-specific tables)
static final int HEADER = 0;
static final int HEADER_RELEASE = 1;
static final int TAG_1 = 2;
static final int TAG_2 = 3; // Common for EDIFACT & X12, overridden TRADACOMS
static final int TAG_3 = 4; // Common for EDIFACT & X12, overridden TRADACOMS
static final int ELEMENT_PROCESS = 5;
static final int DATA_RELEASE = 6;
static final int DATA_BINARY = 7;
static final int DATA_BINARY_END = 8;
static final int TRAILER = 9;
// Dialect-Specific
static final int TAG_SEARCH = 10; // Each dialect has their own version to support transition to interchange end segments
static final int TERM_7 = 11; // EDIFACT Unz, TRADACOMS End, X12 Iea
static final int TERM_8 = 12; // EDIFACT uNz, TRADACOMS eNd, X12 iEa
static final int TERM_9 = 13; // EDIFACT unZ, TRADACOMS enD, X12 ieA
static final int EDIFACT_UNB_0 = 14;
static final int EDIFACT_UNB_1 = 15;
static final int EDIFACT_UNB_2 = 16;
static final int EDIFACT_UNB_3 = 17;
}
private static final State __ = State.INVALID;
private static final State II = State.INITIAL;
private static final State X1 = State.HEADER_X12_I;
private static final State X2 = State.HEADER_X12_S;
private static final State X7 = State.TRAILER_X12_I;
private static final State X8 = State.TRAILER_X12_E;
private static final State X9 = State.TRAILER_X12_A;
private static final State U1 = State.HEADER_EDIFACT_U;
private static final State U2 = State.HEADER_EDIFACT_N;
private static final State U7 = State.TRAILER_EDIFACT_U;
private static final State U8 = State.TRAILER_EDIFACT_N;
private static final State U9 = State.TRAILER_EDIFACT_Z;
private static final State C1 = State.HEADER_TRADACOMS_S;
private static final State C2 = State.HEADER_TRADACOMS_T;
private static final State C7 = State.TRAILER_TRADACOMS_E;
private static final State C8 = State.TRAILER_TRADACOMS_N;
private static final State C9 = State.TRAILER_TRADACOMS_D;
private static final State IC = State.INTERCHANGE_CANDIDATE;
private static final State HD = State.HEADER_DATA;
private static final State HR = State.HEADER_RELEASE;
private static final State HV = State.HEADER_INVALID_DATA;
private static final State HC = State.HEADER_COMPONENT_END;
private static final State HE = State.HEADER_ELEMENT_END;
private static final State HZ = State.HEADER_SEGMENT_END;
private static final State B0 = State.HEADER_EDIFACT_UNB_SEARCH;
private static final State B1 = State.HEADER_EDIFACT_UNB_1;
private static final State B2 = State.HEADER_EDIFACT_UNB_2;
private static final State B3 = State.HEADER_EDIFACT_UNB_3;
private static final State BB = State.HEADER_SEGMENT_BEGIN;
private static final State TS = State.TAG_SEARCH;
private static final State T1 = State.TAG_1;
private static final State T2 = State.TAG_2;
private static final State T3 = State.TAG_3;
private static final State SB = State.SEGMENT_BEGIN;
private static final State DR = State.DATA_RELEASE;
private static final State ED = State.ELEMENT_DATA;
private static final State EI = State.ELEMENT_INVALID_DATA;
private static final State CE = State.COMPONENT_END;
private static final State ER = State.ELEMENT_REPEAT;
private static final State EE = State.ELEMENT_END;
private static final State SE = State.SEGMENT_END;
private static final State SY = State.SEGMENT_EMPTY;
private static final State TB = State.TRAILER_BEGIN;
private static final State TD = State.TRAILER_ELEMENT_DATA;
private static final State TE = State.TRAILER_ELEMENT_END;
private static final State IE = State.INTERCHANGE_END;
/**
* BD - Binary Data
*/
private static final State BD = State.ELEMENT_DATA_BINARY;
/*
* The state transition table takes the current state and the current
* symbol, and returns either a new state or an action. An action is
* represented as a negative number. An EDI text is accepted if at the end
* of the text the state is initial and if the mode list is empty.
*/
// @formatter:off
/*-
* SPACE SEGMT CMPST RELSE CNTRL INVLD *
* | A B D E I N S T U X Z | | | | | *
* | | | | | | | | | | | | ALNUM | ELEMT | RPEAT | WHITE | OTHER | SEGTG *
* | | | | | | | | | | | | | | | | | | | | | | | *
* | | | | | | | | | | | | | | | | | | | | | | | */
/******************* Initial */
private static final State[] FROM_INITIAL = { II, __, __, __, __, X1, __, C1, __, U1, __, __, __, __, __, __, __, __, II, II, __, __, __ };
/* ^ 0 */
private static final State[] FROM_EDIFACT_1 = { __, __, __, __, __, __, U2, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_EDIFACT_2 = { __, IC, IC, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_TRADACOMS_1 = { __, __, __, __, __, __, __, __, C2, __, __, __, __, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_TRADACOMS_2 = { __, __, __, __, __, __, __, __, __, __, IC, __, __, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_X12_1 = { __, __, __, __, __, __, __, X2, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __ };
/* ^ 5 */
private static final State[] FROM_X12_2 = { __, IC, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __ };
/******************* Common */
private static final State[] FROM_HEADER = { HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HZ, HE, HC, __, HR, HD, HD, HD, HV, HE };
/* ^ 0 */
private static final State[] FROM_HEADER_RELEASE = { HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HD, HV, HV, HD, HV, HD };
private static final State[] FROM_TAG_1 = { __, T2, T2, T2, T2, T2, T2, T2, T2, T2, T2, T2, T2, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_TAG_2 = { __, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, SY, SB, __, __, __, __, __, __, __, __ };
private static final State[] FROM_TAG_3 = { __, __, __, __, __, __, __, __, __, __, __, __, __, SY, SB, __, __, __, __, __, __, __, __ };
private static final State[] FROM_ED = { ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, SE, EE, CE, ER, DR, EI, EI, ED, EI, __ };
/* ^ 5 */
private static final State[] FROM_DR = { ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, ED, EI, EI, ED, EI, ED };
private static final State[] FROM_BD = { BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD, BD };
private static final State[] FROM_BE = { __, __, __, __, __, __, __, __, __, __, __, __, __, SE, EE, __, __, __, __, __, __, __, __ };
private static final State[] FROM_TRAILER = { TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, TD, IE, TE, __, __, __, __, __, TD, __, __ };
/* ^ 9 */
/******************* EDIFACT */
private static final State[] FROM_TS_EDIFACT = { TS, T1, T1, T1, T1, T1, T1, T1, T1, U7, T1, T1, T1, __, __, __, __, __, TS, __, __, __, __ };
/* ^ 10 (follows common) */
private static final State[] FROM_EDIFACT_7 = { __, T2, T2, T2, T2, T2, U8, T2, T2, T2, T2, T2, T2, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_EDIFACT_8 = { __, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, U9, T3, __, SB, __, __, __, __, __, __, __, __ };
private static final State[] FROM_EDIFACT_9 = { __, __, __, __, __, __, __, __, __, __, __, __, __, __, TB, __, __, __, __, __, __, __, __ };
private static final State[] FROM_EDIFACT_UNB_0 = { B0, __, __, __, __, __, __, __, B1, B1, __, __, __, __, __, __, __, __, B0, __, __, __, __ };
private static final State[] FROM_EDIFACT_UNB_1 = { __, __, __, __, __, __, B2, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_EDIFACT_UNB_2 = { __, __, B3, __, __, __, __, __, __, __, __, __, __, __, BB, __, __, __, __, __, __, __, __ };
private static final State[] FROM_EDIFACT_UNB_3 = { __, __, __, __, __, __, __, __, __, __, __, __, __, __, BB, __, __, __, __, __, __, __, __ };
/******************* TRADACOMS */
private static final State[] FROM_TS_TRADACOMS = { TS, T1, T1, T1, C7, T1, T1, T1, T1, T1, T1, T1, T1, __, __, __, __, __, TS, __, __, __, __ };
/* ^ 10 (follows common) */
private static final State[] FROM_TRADACOMS_7 = { __, T2, T2, T2, T2, T2, C8, T2, T2, T2, T2, T2, T2, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_TRADACOMS_8 = { __, T3, T3, C9, T3, T3, T3, T3, T3, T3, T3, T3, T3, __, __, __, __, __, __, __, __, __, SB };
private static final State[] FROM_TRADACOMS_9 = { __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, TB };
private static final State[] FROM_TAG_2_TRADACOMS = { __, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, SY, __, __, __, __, __, __, __, __, SB };
private static final State[] FROM_TAG_3_TRADACOMS = { __, __, __, __, __, __, __, __, __, __, __, __, __, SY, __, __, __, __, __, __, __, __, SB };
/******************* X12 */
private static final State[] FROM_TS_X12 = { TS, T1, T1, T1, T1, X7, T1, T1, T1, T1, T1, T1, T1, __, __, __, __, __, TS, __, __, __, __ };
/* ^ 10 (follows common) */
private static final State[] FROM_X12_7 = { __, T2, T2, T2, X8, T2, T2, T2, T2, T2, T2, T2, T2, __, __, __, __, __, __, __, __, __, __ };
private static final State[] FROM_X12_8 = { __, X9, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, T3, __, SB, __, __, __, __, __, __, __, __ };
private static final State[] FROM_X12_9 = { __, __, __, __, __, __, __, __, __, __, __, __, __, __, TB, __, __, __, __, __, __, __, __ };
private static final State[][] TRANSITION_INITIAL = {
FROM_INITIAL,
FROM_EDIFACT_1,
FROM_EDIFACT_2,
FROM_TRADACOMS_1,
FROM_TRADACOMS_2,
FROM_X12_1,
FROM_X12_2
};
private static final State[][] TRANSITION_EDIFACT = {
// Common
FROM_HEADER,
FROM_HEADER_RELEASE,
FROM_TAG_1,
FROM_TAG_2,
FROM_TAG_3,
FROM_ED,
FROM_DR,
FROM_BD,
FROM_BE,
FROM_TRAILER,
// Dialect-specific
FROM_TS_EDIFACT,
FROM_EDIFACT_7,
FROM_EDIFACT_8,
FROM_EDIFACT_9,
FROM_EDIFACT_UNB_0,
FROM_EDIFACT_UNB_1,
FROM_EDIFACT_UNB_2,
FROM_EDIFACT_UNB_3
};
private static final State[][] TRANSITION_TRADACOMS = {
// Common
FROM_HEADER,
FROM_HEADER_RELEASE,
FROM_TAG_1,
FROM_TAG_2_TRADACOMS, // Overrides common transitions
FROM_TAG_3_TRADACOMS, // Overrides common transitions
FROM_ED,
FROM_DR,
FROM_BD,
FROM_BE,
FROM_TRAILER,
// Dialect-specific
FROM_TS_TRADACOMS,
FROM_TRADACOMS_7,
FROM_TRADACOMS_8,
FROM_TRADACOMS_9
};
private static final State[][] TRANSITION_X12 = {
// Common
FROM_HEADER,
FROM_HEADER_RELEASE,
FROM_TAG_1,
FROM_TAG_2,
FROM_TAG_3,
FROM_ED,
FROM_DR,
FROM_BD,
FROM_BE,
FROM_TRAILER,
// Dialect-specific
FROM_TS_X12,
FROM_X12_7,
FROM_X12_8,
FROM_X12_9
};
private static final State[][][] TRANSITIONS = {
TRANSITION_INITIAL,
TRANSITION_EDIFACT,
TRANSITION_TRADACOMS,
TRANSITION_X12
};
// @formatter:on
private final int table;
private final int code;
State(int table, int code) {
this.table = table;
this.code = code;
}
State(int code) {
this(-1, code);
}
public static State transition(State state, Dialect dialect, CharacterClass clazz) {
if (state.table != -1) {
/*
* A state's table is set to force transition to another table. For example,
* end of interchange states transition back to the unknown dialect transition
* table.
*/
return state.transition(state.table, clazz);
}
Objects.requireNonNull(dialect, "dialect was unexpectedly null");
return state.transition(dialect.getDialectStateCode(), clazz);
}
public State transition(int dialect, CharacterClass clazz) {
return TRANSITIONS[dialect][code][clazz.code];
}
public boolean isInvalid() {
return Category.INVALID == code;
}
public boolean isHeaderState() {
return Category.HEADER == code && DialectCode.UNKNOWN != table;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/ProxyEventHandler.java | src/main/java/io/xlate/edi/internal/stream/tokenization/ProxyEventHandler.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import java.io.InputStream;
import java.nio.CharBuffer;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.function.Function;
import io.xlate.edi.internal.stream.StaEDIStreamLocation;
import io.xlate.edi.internal.stream.validation.UsageError;
import io.xlate.edi.internal.stream.validation.Validator;
import io.xlate.edi.internal.stream.validation.ValidatorConfig;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDILoopType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamValidationError;
public class ProxyEventHandler implements EventHandler {
public static final String LOOP_CODE_GROUP = EDIType.Type.GROUP.toString();
public static final String LOOP_CODE_TRANSACTION = EDIType.Type.TRANSACTION.toString();
private final StaEDIStreamLocation location;
private final boolean nestHierarchicalLoops;
private final ValidatorConfig config;
private Schema controlSchema;
private Validator controlValidator;
private Schema transactionSchema;
private Validator transactionValidator;
private boolean transactionSchemaAllowed = false;
private boolean transaction = false;
private InputStream binary;
private String segmentTag;
private final Queue<StreamEvent> eventPool = new LinkedList<>();
// Use implementation to access as both Deque & List
private final LinkedList<StreamEvent> eventQueue = new LinkedList<>();
private final Deque<HierarchicalLevel> openLevels = new LinkedList<>();
static class HierarchicalLevel {
final String id;
final StreamEvent event;
HierarchicalLevel(String id, StreamEvent event) {
this.id = id;
this.event = event;
}
boolean isParentOf(String parentId) {
return !parentId.isEmpty() && parentId.equals(id);
}
}
private boolean levelCheckPending;
private StreamEvent currentSegmentBegin;
private StreamEvent startedLevel;
private EDIElementPosition levelIdPosition;
private String startedLevelId;
private EDIElementPosition parentIdPosition;
private String startedLevelParentId;
private Dialect dialect;
public ProxyEventHandler(StaEDIStreamLocation location, Schema controlSchema, boolean nestHierarchicalLoops, ValidatorConfig config) {
this.location = location;
this.config = config;
this.nestHierarchicalLoops = nestHierarchicalLoops;
setControlSchema(controlSchema);
}
public void setControlSchema(Schema controlSchema) {
if (controlValidator != null) {
throw new IllegalStateException("control validator already created");
}
this.controlSchema = controlSchema;
controlValidator = Validator.forSchema(controlSchema, null, config);
}
public boolean isTransactionSchemaAllowed() {
return transactionSchemaAllowed;
}
public Schema getTransactionSchema() {
return this.transactionSchema;
}
public void setTransactionSchema(Schema transactionSchema) {
if (!Objects.equals(this.transactionSchema, transactionSchema)) {
this.transactionSchema = transactionSchema;
transactionValidator = Validator.forSchema(transactionSchema, controlSchema, config);
}
}
public void resetEvents() {
eventPool.addAll(eventQueue);
eventQueue.clear();
}
public EDIStreamEvent getEvent() {
return current(StreamEvent::getType, null);
}
public boolean additionalEventsRequired() {
if (eventQueue.peekFirst().getType() == EDIStreamEvent.START_TRANSACTION) {
/*
* When the START_TRANSACTION event is next up in the queue, this will
* signal to the reader to continue feeding the lexer until the end of the
* transaction header segment so that all metadata (type and version) are
* available _starting with_ the START_TRANSACTION.
*/
return eventQueue.peekLast().getType() != EDIStreamEvent.END_SEGMENT;
}
return false;
}
public CharBuffer getCharacters() {
return current(StreamEvent::getData, null);
}
public boolean hasNext() {
// Current event is in the first position, second will be used for `nextEvent`
return eventQueue.size() > 1;
}
public boolean nextEvent() {
if (eventQueue.isEmpty()) {
return false;
}
StreamEvent lastEvent = eventQueue.removeFirst();
if (lastEvent.getType() == EDIStreamEvent.END_TRANSACTION) {
/*
* Retain the transaction metadata in the dialect until after
* the reader is past END_TRANSACTION.
*/
dialect.transactionEnd();
}
eventPool.add(lastEvent);
return !eventQueue.isEmpty();
}
public EDIStreamValidationError getErrorType() {
return current(StreamEvent::getErrorType, null);
}
public String getReferenceCode() {
return current(StreamEvent::getReferenceCode, null);
}
public StaEDIStreamLocation getLocation() {
return current(StreamEvent::getLocation, this.location);
}
<T> T current(Function<StreamEvent, T> mapper, T defaultValue) {
final T value;
if (eventQueue.isEmpty()) {
value = defaultValue;
} else {
value = mapper.apply(eventQueue.getFirst());
}
return value;
}
StreamEvent getPooledEvent() {
return eventPool.isEmpty() ? new StreamEvent() : eventPool.remove();
}
public InputStream getBinary() {
return binary;
}
public void setBinary(InputStream binary) {
this.binary = binary;
}
public EDIReference getSchemaTypeReference() {
return current(StreamEvent::getTypeReference, null);
}
@Override
public void interchangeBegin(Dialect dialect) {
this.dialect = dialect;
enqueueEvent(EDIStreamEvent.START_INTERCHANGE, EDIStreamValidationError.NONE, "", null, location);
}
@Override
public void interchangeEnd() {
Validator validator = validator();
if (validator != null) {
validator.validateLoopSyntax(this);
validator.reset();
}
enqueueEvent(EDIStreamEvent.END_INTERCHANGE, EDIStreamValidationError.NONE, "", null, location);
}
@Override
public void loopBegin(EDIReference typeReference) {
final String loopCode = typeReference.getReferencedType().getCode();
if (LOOP_CODE_TRANSACTION.equals(loopCode)) {
transaction = true;
transactionSchemaAllowed = true;
enqueueEvent(EDIStreamEvent.START_TRANSACTION, EDIStreamValidationError.NONE, null, typeReference, location);
if (transactionValidator != null) {
transactionValidator.reset();
}
} else if (LOOP_CODE_GROUP.equals(loopCode)) {
enqueueEvent(EDIStreamEvent.START_GROUP, EDIStreamValidationError.NONE, null, typeReference, location);
} else {
enqueueEvent(EDIStreamEvent.START_LOOP, EDIStreamValidationError.NONE, null, typeReference, location);
if (nestHierarchicalLoops && isHierarchicalLoop(typeReference.getReferencedType())) {
EDILoopType loop = (EDILoopType) typeReference.getReferencedType();
startedLevel = eventQueue.getLast();
levelIdPosition = loop.getLevelIdPosition();
parentIdPosition = loop.getParentIdPosition();
levelCheckPending = true;
}
}
}
@Override
public void loopEnd(EDIReference typeReference) {
final String loopCode = typeReference.getReferencedType().getCode();
// Validator can not be null when a loopEnd event has been signaled.
validator().validateLoopSyntax(this);
if (LOOP_CODE_TRANSACTION.equals(loopCode)) {
transaction = false;
enqueueEvent(EDIStreamEvent.END_TRANSACTION, EDIStreamValidationError.NONE, null, typeReference, location);
} else if (LOOP_CODE_GROUP.equals(loopCode)) {
dialect.groupEnd();
enqueueEvent(EDIStreamEvent.END_GROUP, EDIStreamValidationError.NONE, null, typeReference, location);
} else if (nestHierarchicalLoops && isHierarchicalLoop(typeReference.getReferencedType())) {
levelCheckPending = true;
} else {
enqueueEvent(EDIStreamEvent.END_LOOP, EDIStreamValidationError.NONE, null, typeReference, location);
}
}
@Override
public boolean segmentBegin(String segmentTag) {
location.incrementSegmentPosition(segmentTag);
this.segmentTag = segmentTag;
/*
* If this is the start of a transaction, loopStart will be called from the validator and
* transactionSchemaAllowed will be `true` for the duration of the start-transaction segment.
*/
transactionSchemaAllowed = false;
Validator validator = validator();
boolean eventsReady = true;
EDIReference typeReference = null;
clearLevelCheck();
if (validator != null && !dialect.isServiceAdviceSegment(segmentTag)) {
validator.validateSegment(this, segmentTag);
typeReference = validator.getSegmentReference();
eventsReady = !validator.isPendingDiscrimination();
}
if (exitTransaction(segmentTag)) {
// Validate the syntax for the elements directly within the transaction loop
if (validator != null) {
validator.validateLoopSyntax(this);
}
transaction = false;
// Now the control validator after setting transaction to false
validator = validator();
validator.validateSegment(this, segmentTag);
typeReference = validator().getSegmentReference();
}
if (controlValidator != null) {
controlValidator.countSegment(segmentTag);
}
enqueueEvent(EDIStreamEvent.START_SEGMENT, EDIStreamValidationError.NONE, segmentTag, typeReference, location);
currentSegmentBegin = eventQueue.getLast();
return !levelCheckPending && eventsReady;
}
boolean exitTransaction(CharSequence tag) {
return transaction
&& !transactionSchemaAllowed
&& controlSchema != null
&& controlSchema.containsSegment(tag.toString());
}
@Override
public boolean segmentEnd() {
Validator validator = validator();
EDIReference typeReference = null;
if (validator != null) {
validator.clearImplementationCandidates(this);
validator.validateSyntax(dialect, this, this, location, false);
validator.validateVersionConstraints(dialect, this, null);
typeReference = validator.getSegmentReference();
}
if (levelCheckPending) {
performLevelCheck();
}
location.clearSegmentLocations(true);
enqueueEvent(EDIStreamEvent.END_SEGMENT, EDIStreamValidationError.NONE, segmentTag, typeReference, location);
return true;
}
@Override
public boolean compositeBegin(boolean isNil, boolean derived) {
if (!derived) {
location.incrementElement(true);
}
location.setComposite(true);
EDIReference typeReference = null;
boolean eventsReady = true;
Validator validator = validator();
if (validator != null && !isNil) {
boolean invalid = !validator.validCompositeOccurrences(dialect, location);
typeReference = validator.getCompositeReference();
if (invalid) {
List<UsageError> errors = validator.getElementErrors();
for (UsageError error : errors) {
enqueueEvent(error.getError().getCategory(), error.getError(), "", error.getTypeReference(), location);
}
}
eventsReady = !validator.isPendingDiscrimination();
}
enqueueEvent(EDIStreamEvent.START_COMPOSITE, EDIStreamValidationError.NONE, "", typeReference, location);
return !levelCheckPending && eventsReady;
}
@Override
public boolean compositeEnd(boolean isNil) {
boolean eventsReady = true;
if (validator() != null && !isNil) {
validator().validateSyntax(dialect, this, this, location, true);
eventsReady = !validator().isPendingDiscrimination();
}
location.clearComponentPosition();
enqueueEvent(EDIStreamEvent.END_COMPOSITE, EDIStreamValidationError.NONE, "", null, location);
return !levelCheckPending && eventsReady;
}
@Override
public boolean elementData(CharSequence text, boolean fromStream) {
location.incrementElement(false);
boolean derivedComposite;
EDIReference typeReference;
final boolean compositeFromStream = location.getComponentPosition() > -1;
dialect.elementData(text, location);
Validator validator = validator();
boolean valid;
if (levelCheckPending && startedLevel != null) {
setLevelIdentifiers(text);
}
/*
* The first component of a composite was the only element received
* for the composite. It was found to be a composite via the schema
* and the composite begin/end events must be generated.
**/
final boolean componentReceivedAsSimple;
if (validator != null) {
derivedComposite = !compositeFromStream && validator.isComposite(dialect, location);
componentReceivedAsSimple = derivedComposite && fromStream;
if (componentReceivedAsSimple) {
this.compositeBegin(text.length() == 0, true);
location.incrementComponentPosition();
}
valid = validator.validateElement(dialect, location, text, derivedComposite, null);
typeReference = validator.getElementReference();
enqueueElementOccurrenceErrors(text, validator, valid);
} else {
valid = true;
derivedComposite = false;
componentReceivedAsSimple = false;
typeReference = null;
}
enqueueElementErrors(text, validator, valid);
boolean eventsReady = true;
if (fromStream && (!derivedComposite || text.length() > 0) /* Not an inferred element */) {
enqueueEvent(EDIStreamEvent.ELEMENT_DATA,
EDIStreamValidationError.NONE,
text,
typeReference,
location);
eventsReady = selectImplementationIfPending(validator, eventsReady);
}
if (componentReceivedAsSimple) {
this.compositeEnd(text.length() == 0);
location.clearComponentPosition();
}
return !levelCheckPending && eventsReady;
}
boolean selectImplementationIfPending(Validator validator, boolean eventsReadyDefault) {
if (validator != null && validator.isPendingDiscrimination()) {
return validator.selectImplementation(eventQueue, this);
}
return eventsReadyDefault;
}
void clearLevelCheck() {
levelCheckPending = false;
currentSegmentBegin = null;
startedLevel = null;
levelIdPosition = null;
startedLevelId = "";
parentIdPosition = null;
startedLevelParentId = "";
}
boolean isHierarchicalLoop(EDIType type) {
EDILoopType loop = (EDILoopType) type;
return loop.getLevelIdPosition() != null &&
loop.getParentIdPosition() != null;
}
void setLevelIdentifiers(CharSequence text) {
if (levelIdPosition.matchesLocation(location)) {
startedLevelId = text.toString();
}
if (parentIdPosition.matchesLocation(location)) {
startedLevelParentId = text.toString();
}
}
void performLevelCheck() {
if (startedLevel != null) {
completeLevel(startedLevel, startedLevelParentId);
StreamEvent openLevel = getPooledEvent();
openLevel.update(EDIStreamEvent.END_LOOP, startedLevel.errorType, startedLevel.data, startedLevel.typeReference, startedLevel.location);
/*
* startedLevelId will not be null due to Validator#validateSyntax.
* Although the client never sees the generated element event, here
* it will be an empty string.
*/
openLevels.addLast(new HierarchicalLevel(startedLevelId, openLevel));
} else {
completeLevel(currentSegmentBegin, "");
}
clearLevelCheck();
}
void completeLevel(StreamEvent successor, String parentId) {
while (!openLevels.isEmpty() && !openLevels.getLast().isParentOf(parentId)) {
HierarchicalLevel completed = openLevels.removeLast();
completed.event.location.set(location);
completed.event.location.clearSegmentLocations(true);
eventQueue.add(eventQueue.indexOf(successor), completed.event);
}
}
void enqueueElementOccurrenceErrors(CharSequence text, Validator validator, boolean valid) {
if (valid) {
return;
}
/*
* Process element-level errors before possibly starting a
* composite or reporting other data-related errors.
*/
List<UsageError> errors = validator.getElementErrors();
Iterator<UsageError> cursor = errors.iterator();
while (cursor.hasNext()) {
UsageError error = cursor.next();
switch (error.getError()) {
case TOO_MANY_DATA_ELEMENTS:
case TOO_MANY_REPETITIONS:
enqueueEvent(error.getError().getCategory(),
error.getError(),
text,
error.getTypeReference(),
location);
cursor.remove();
//$FALL-THROUGH$
default:
continue;
}
}
}
void enqueueElementErrors(CharSequence text, Validator validator, boolean valid) {
if (valid) {
return;
}
List<UsageError> errors = validator.getElementErrors();
for (UsageError error : errors) {
enqueueEvent(error.getError().getCategory(),
error.getError(),
text,
error.getTypeReference(),
location);
}
}
public boolean isBinaryElementLength() {
return validator() != null && validator().isBinaryElementLength();
}
@Override
public boolean binaryData(InputStream binaryStream) {
location.incrementElement(false);
Validator validator = validator();
EDIReference typeReference = validator != null ? validator.getElementReference() : null;
enqueueEvent(EDIStreamEvent.ELEMENT_DATA_BINARY, EDIStreamValidationError.NONE, "", typeReference, location);
setBinary(binaryStream);
return true;
}
@Override
public void segmentError(CharSequence token, EDIReference typeReference, EDIStreamValidationError error) {
enqueueEvent(EDIStreamEvent.SEGMENT_ERROR, error, token, typeReference, location);
}
@Override
public void elementError(final EDIStreamEvent event,
final EDIStreamValidationError error,
final EDIReference typeReference,
final CharSequence data,
final int element,
final int component,
final int repetition) {
StaEDIStreamLocation copy = location.copy();
copy.setElementPosition(element);
copy.setElementOccurrence(repetition);
copy.setComponentPosition(component);
enqueueEvent(event, error, data, typeReference, copy);
}
private Validator validator() {
// Do not use the transactionValidator in the period where it may be set/mutated by the user
return transaction && !transactionSchemaAllowed ? transactionValidator : controlValidator;
}
private void enqueueEvent(EDIStreamEvent event,
EDIStreamValidationError error,
CharSequence data,
EDIReference typeReference,
StaEDIStreamLocation location) {
StreamEvent target = getPooledEvent();
target.update(event, error, data, typeReference, location);
eventQueue.add(target);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/Lexer.java | src/main/java/io/xlate/edi/internal/stream/tokenization/Lexer.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.function.IntSupplier;
import java.util.logging.Logger;
import io.xlate.edi.internal.stream.CharArraySequence;
import io.xlate.edi.internal.stream.StaEDIStreamLocation;
public class Lexer {
private static final Logger LOGGER = Logger.getLogger(Lexer.class.getName());
private enum Mode {
INTERCHANGE,
SEGMENT,
COMPOSITE
}
private final Deque<Mode> modes = new ArrayDeque<>();
private State state = State.INITIAL;
private int previousInput = 0;
private State previous;
private interface Notifier {
boolean execute(State state, int start, int length);
}
private final Deque<Notifier> events = new ArrayDeque<>(20);
private final Deque<State> stateQueue = new ArrayDeque<>(20);
private final Deque<Integer> startQueue = new ArrayDeque<>(20);
private final Deque<Integer> lengthQueue = new ArrayDeque<>(20);
private final InputStream stream;
private final EventHandler handler;
private CharsetDecoder decoder;
private char[] readChar = new char[1];
private CharBuffer readCharBuf = CharBuffer.wrap(readChar);
private ByteBuffer readByteBuf = ByteBuffer.allocate(4);
private CharArraySequence elementHolder = new CharArraySequence();
private final StaEDIStreamLocation location;
private final CharacterSet characters;
private CharBuffer buffer = CharBuffer.allocate(4096);
private Dialect dialect;
private long binaryRemain = -1;
private InputStream binaryStream = null;
public Lexer(InputStream stream, Charset charset, EventHandler handler, StaEDIStreamLocation location, boolean extraneousIgnored) {
if (stream.markSupported()) {
this.stream = stream;
} else {
this.stream = new BufferedInputStream(stream);
}
this.handler = handler;
this.decoder = charset.newDecoder();
this.location = location;
this.characters = new CharacterSet(extraneousIgnored);
}
public Dialect getDialect() {
return dialect;
}
public void invalidate() {
if (state != State.INVALID) {
previous = state;
state = State.INVALID;
}
}
public void setBinaryLength(long binaryLength) {
this.binaryRemain = binaryLength;
this.binaryStream = new InputStream() {
@Override
public int read() throws IOException {
int binaryInput = -1;
if (binaryRemain-- < 1 || (binaryInput = stream.read()) < 0) {
state = State.ELEMENT_END_BINARY;
} else {
location.incrementOffset(binaryInput);
}
return binaryInput;
}
};
enqueue(this::binaryElement, 0);
state = State.ELEMENT_DATA_BINARY;
}
public boolean hasRemaining() throws IOException {
stream.mark(200);
int peekInput;
boolean spaceOnly = true;
while ((peekInput = stream.read()) > -1 && spaceOnly) {
spaceOnly = characters.isWhitespace(peekInput);
}
stream.reset();
return !spaceOnly;
}
public void parse() throws IOException, EDIException {
try {
parse(this::readCharacterUnchecked);
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
void parse(IntSupplier inputSource) throws EDIException {
if (nextEvent()) {
return;
}
if (state.isInvalid()) {
// Unable to proceed once the state becomes invalid
throw invalidStateError(previousInput, state, previous);
}
int input = 0;
boolean eventsReady = false;
while (!eventsReady && (input = inputSource.getAsInt()) > -1) {
eventsReady = processInputCharacter(input);
}
if (input < 0) {
throw error(EDIException.INCOMPLETE_STREAM);
}
}
boolean processInputCharacter(int input) throws EDIException {
boolean eventsReady = false;
location.incrementOffset(input);
CharacterClass clazz = characters.getClass(input);
previous = state;
previousInput = input;
state = State.transition(state, dialect, clazz);
LOGGER.finer(() -> String.format("%s + (%s, '%s', %s) -> %s", previous, Dialect.getStandard(dialect), (char) input, clazz, state));
switch (state) {
case INITIAL:
case TAG_SEARCH:
case HEADER_EDIFACT_UNB_SEARCH:
break;
case HEADER_X12_I:
case HEADER_X12_S:
case HEADER_EDIFACT_N:
case HEADER_EDIFACT_U:
case HEADER_TRADACOMS_S:
case HEADER_TRADACOMS_T:
case TAG_1:
case TAG_2:
case TAG_3:
case TRAILER_X12_I:
case TRAILER_X12_E:
case TRAILER_X12_A:
case TRAILER_EDIFACT_U:
case TRAILER_EDIFACT_N:
case TRAILER_EDIFACT_Z:
case TRAILER_TRADACOMS_E:
case TRAILER_TRADACOMS_N:
case TRAILER_TRADACOMS_D:
case ELEMENT_DATA:
case TRAILER_ELEMENT_DATA:
buffer.put((char) input);
break;
case ELEMENT_INVALID_DATA:
if (!characters.isIgnored(input)) {
buffer.put((char) input);
}
break;
case HEADER_EDIFACT_UNB_1: // U - When UNA is present
case HEADER_EDIFACT_UNB_2: // N - When UNA is present
case HEADER_EDIFACT_UNB_3: // B - When UNA is present
handleStateHeaderTag(input);
break;
case HEADER_RELEASE:
case DATA_RELEASE:
// Skip this character - next character will be literal value
break;
case ELEMENT_DATA_BINARY:
handleStateElementDataBinary();
break;
case INTERCHANGE_CANDIDATE:
// ISA, UNA, or UNB was found
handleStateInterchangeCandidate(input);
break;
case HEADER_DATA:
case HEADER_INVALID_DATA:
handleStateHeaderData((char) input);
eventsReady = dialectConfirmed(State.TAG_SEARCH);
break;
case HEADER_SEGMENT_BEGIN:
dialect.appendHeader(characters, (char) input);
openSegment();
eventsReady = dialectConfirmed(State.ELEMENT_END);
break;
case HEADER_ELEMENT_END:
dialect.appendHeader(characters, (char) input);
handleElement();
eventsReady = dialectConfirmed(State.ELEMENT_END);
break;
case HEADER_COMPONENT_END:
dialect.appendHeader(characters, (char) input);
handleComponent();
eventsReady = dialectConfirmed(State.COMPONENT_END);
break;
case SEGMENT_BEGIN:
case TRAILER_BEGIN:
openSegment();
eventsReady = nextEvent();
break;
case SEGMENT_END:
closeSegment();
eventsReady = nextEvent();
break;
case SEGMENT_EMPTY:
emptySegment();
eventsReady = nextEvent();
break;
case COMPONENT_END:
handleComponent();
eventsReady = nextEvent();
break;
case ELEMENT_END:
case TRAILER_ELEMENT_END:
case ELEMENT_REPEAT:
handleElement();
eventsReady = nextEvent();
break;
case INTERCHANGE_END:
closeInterchange();
eventsReady = nextEvent();
break;
default:
if (characters.isIgnored(input)) {
state = previous;
} else if (clazz != CharacterClass.INVALID) {
throw invalidStateError(input, this.state, this.previous);
} else {
throw error(EDIException.INVALID_CHARACTER);
}
}
return eventsReady;
}
int readCharacterUnchecked() {
try {
return readCharacter();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
int readCharacter() throws IOException {
int next = stream.read();
if (next < 0) {
return -1;
}
boolean endOfInput = false;
boolean complete = false;
int position = 0;
readCharBuf.clear();
readByteBuf.clear();
readByteBuf.put((byte) next);
do {
readByteBuf.flip();
CoderResult cr = decoder.decode(readByteBuf, readCharBuf, endOfInput);
if (!cr.isUnderflow()) {
cr.throwException();
}
if (endOfInput) {
complete = true;
} else if (readCharBuf.position() > 0) {
// Single character successfully written to the CharBuffer
complete = true;
} else {
next = stream.read();
if (next < 0) {
endOfInput = true;
decoder.reset();
} else {
readByteBuf.limit(readByteBuf.capacity());
readByteBuf.position(++position);
readByteBuf.put((byte) next);
}
}
} while (!complete);
if (endOfInput) {
decoder.reset();
}
if (readCharBuf.position() == 0 && endOfInput) {
// Nothing was written to the CharBuffer
return -1;
}
return readChar[0];
}
void handleStateHeaderTag(int input) {
buffer.put((char) input);
dialect.appendHeader(characters, (char) input);
}
void handleStateElementDataBinary() {
/*
* Not all of the binary data has been consumed. I.e. #next was
* called before completion.
*/
if (--binaryRemain < 1) {
state = State.ELEMENT_END_BINARY;
}
}
void handleStateInterchangeCandidate(int input) throws EDIException {
buffer.put((char) input);
final char[] header = buffer.array();
final int length = buffer.position();
dialect = DialectFactory.getDialect(header, 0, length);
for (int i = 0; i < length; i++) {
dialect.appendHeader(characters, header[i]);
}
openInterchange();
openSegment();
}
void handleStateHeaderData(char input) throws EDIException {
dialect.appendHeader(characters, input);
switch (characters.getClass(input)) {
case SEGMENT_DELIMITER:
closeSegment();
state = dialect.getTagSearchState();
break;
case SEGMENT_TAG_DELIMITER:
case ELEMENT_DELIMITER:
case ELEMENT_REPEATER:
case COMPONENT_DELIMITER:
case RELEASE_CHARACTER:
break;
default:
if (!characters.isIgnored(input)) {
buffer.put(input);
}
break;
}
}
/**
* Determine if the input text has been confirmed by the dialect as being
* initially accepted. If so, transition to the state given by the
* <code>confirmed</code> parameter.
*
* @param confirmed the state to transition to if the dialect is confirmed.
* @return true if the dialect is confirmed, otherwise false.
* @throws EDIException when the input text has been rejected by the dialect.
*/
private boolean dialectConfirmed(State confirmed) throws EDIException {
if (dialect.isConfirmed()) {
state = confirmed;
nextEvent();
return true;
} else if (dialect.isRejected()) {
buffer.clear();
clearQueues();
String rejectionMessage = dialect.getRejectionMessage();
dialect = null;
state = State.INITIAL;
throw error(EDIException.INVALID_STATE, rejectionMessage);
}
return false;
}
private EDIException invalidStateError(int input, State state, State previousState) {
StringBuilder message = new StringBuilder();
message.append(state);
message.append(" (previous: ");
message.append(previousState);
message.append("); input: '");
message.append((char) input);
message.append('\'');
return error(EDIException.INVALID_STATE, message);
}
private EDIException error(int code, CharSequence message) {
return new EDIException(code, message.toString(), location.copy());
}
private EDIException error(int code) {
return new EDIException(code, location.copy());
}
private boolean nextEvent() {
Notifier event = events.peek();
boolean eventsReady = false;
if (event != null) {
events.remove();
State nextState = stateQueue.remove();
int start = startQueue.remove();
int length = lengthQueue.remove();
eventsReady = event.execute(nextState, start, length);
if (events.isEmpty()) {
buffer.clear();
}
}
return eventsReady;
}
private void enqueue(Notifier task, int position) {
int start;
int length;
if (startQueue.isEmpty()) {
start = 0;
length = position;
} else {
start = startQueue.peekLast() + lengthQueue.peekLast();
length = position > 0 ? position - start : 0;
}
events.add(task);
stateQueue.add(this.state);
startQueue.add(start);
lengthQueue.add(length);
}
private void clearQueues() {
events.clear();
stateQueue.clear();
startQueue.clear();
lengthQueue.clear();
}
private void openInterchange() {
modes.push(Mode.INTERCHANGE);
enqueue(this::interchangeStart, 0);
}
private void closeInterchange() throws EDIException {
closeSegment();
popMode(Mode.INTERCHANGE);
enqueue(this::interchangeEnd, 0);
}
private void openSegment() {
modes.push(Mode.SEGMENT);
enqueue(this::segmentStart, buffer.position());
}
private void closeSegment() throws EDIException {
handleElement();
popMode(Mode.SEGMENT);
enqueue(this::segmentEnd, 0);
}
private void emptySegment() throws EDIException {
openSegment();
popMode(Mode.SEGMENT);
enqueue(this::segmentEnd, 0);
}
private void handleElement() throws EDIException {
location.setRepeating(State.ELEMENT_REPEAT.equals(state));
if (previous != State.ELEMENT_END_BINARY) {
addElementEvent();
}
if (inComposite()) {
closeComposite();
}
}
private void openComposite() {
modes.push(Mode.COMPOSITE);
enqueue(this::compositeStart, 0);
}
private void handleComponent() {
if (!inComposite()) {
openComposite();
}
addElementEvent();
}
private void addElementEvent() {
enqueue(this::element, buffer.position());
}
private boolean inComposite() {
return modes.peek() == Mode.COMPOSITE;
}
private void closeComposite() throws EDIException {
popMode(Mode.COMPOSITE);
enqueue(this::compositeEnd, 0);
}
void popMode(Mode expected) throws EDIException {
if (modes.pop() != expected) {
throw error(EDIException.INVALID_STATE);
}
}
/* test */
State currentState() {
return state;
}
/* test */
State previousState() {
return previous;
}
private boolean interchangeStart(State state, int start, int length) {
handler.interchangeBegin(dialect);
return true;
}
private boolean interchangeEnd(State state, int start, int length) {
handler.interchangeEnd();
dialect = null;
characters.reset();
return true;
}
private boolean segmentStart(State state, int start, int length) {
String segmentTag = new String(buffer.array(), start, length);
return handler.segmentBegin(segmentTag);
}
private boolean segmentEnd(State state, int start, int length) {
return handler.segmentEnd();
}
private boolean compositeStart(State state, int start, int length) {
return handler.compositeBegin(false, false);
}
private boolean compositeEnd(State state, int start, int length) {
return handler.compositeEnd(false);
}
private boolean binaryElement(State state, int start, int length) {
return handler.binaryData(binaryStream);
}
private boolean element(State state, int start, int length) {
elementHolder.set(buffer.array(), start, length);
return handler.elementData(elementHolder, true);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/CharacterSet.java | src/main/java/io/xlate/edi/internal/stream/tokenization/CharacterSet.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
public class CharacterSet {
private static final CharacterClass _SPACE = CharacterClass.SPACE;
private static final CharacterClass _LATNA = CharacterClass.LATIN_A;
private static final CharacterClass _LATNB = CharacterClass.LATIN_B;
private static final CharacterClass _LATND = CharacterClass.LATIN_D;
private static final CharacterClass _LATNE = CharacterClass.LATIN_E;
private static final CharacterClass _LATNI = CharacterClass.LATIN_I;
private static final CharacterClass _LATNN = CharacterClass.LATIN_N;
private static final CharacterClass _LATNS = CharacterClass.LATIN_S;
private static final CharacterClass _LATNT = CharacterClass.LATIN_T;
private static final CharacterClass _LATNU = CharacterClass.LATIN_U;
private static final CharacterClass _LATNX = CharacterClass.LATIN_X;
private static final CharacterClass _LATNZ = CharacterClass.LATIN_Z;
private static final CharacterClass _ALNUM = CharacterClass.ALPHANUMERIC;
private static final CharacterClass _OTHER = CharacterClass.OTHER;
private static final CharacterClass _WHITE = CharacterClass.WHITESPACE;
private static final CharacterClass _CNTRL = CharacterClass.CONTROL;
private static final CharacterClass _INVLD = CharacterClass.INVALID;
/*
* This array maps the 128 ASCII characters into character classes. The
* remaining Unicode characters should be mapped to _OTHER. Control
* characters are errors.
*/
// @formatter:off
private static final CharacterClass[] prototype = {
_INVLD, /* 00 NUL */
_CNTRL, /* 01 SOH */
_CNTRL, /* 02 STX */
_CNTRL, /* 03 ETX */
_CNTRL, /* 04 EOT */
_CNTRL, /* 05 ENQ */
_CNTRL, /* 06 ACK */
_CNTRL, /* 07 BEL */
_INVLD, /* 08 BS */
_WHITE, /* 09 HT */
_WHITE, /* 0A LF */
_WHITE, /* 0B VT */
_WHITE, /* 0C FF */
_WHITE, /* 0D CR */
_INVLD, /* 0E SO */
_INVLD, /* 0F SI */
_INVLD, /* 10 DLE */
_CNTRL, /* 11 DC1 */
_CNTRL, /* 12 DC2 */
_CNTRL, /* 13 DC3 */
_CNTRL, /* 14 DC4 */
_CNTRL, /* 15 NAK */
_CNTRL, /* 16 SYN */
_CNTRL, /* 17 ETB */
_INVLD, /* 18 CAN */
_INVLD, /* 19 EM */
_INVLD, /* 1A SUB */
_INVLD, /* 1B ESC */
_CNTRL, /* 1C FS */
_CNTRL, /* 1D GS */
_CNTRL, /* 1E RS */
_CNTRL, /* 1F US */
_SPACE, /* 20 Space */
_OTHER, /* 21 '!' */
_OTHER, /* 22 '"' */
_OTHER, /* 23 '#' */
_OTHER, /* 24 '$' */
_OTHER, /* 25 '%' */
_OTHER, /* 26 '&' */
_OTHER, /* 27 ''' */
_OTHER, /* 28 '(' */
_OTHER, /* 29 ')' */
_OTHER, /* 2A '*' */
_OTHER, /* 2B '+' */
_OTHER, /* 2C ',' */
_OTHER, /* 2D '-' */
_OTHER, /* 2E '.' */
_OTHER, /* 2F '/' */
_ALNUM, /* 30 '0' */
_ALNUM, /* 31 '1' */
_ALNUM, /* 32 '2' */
_ALNUM, /* 33 '3' */
_ALNUM, /* 34 '4' */
_ALNUM, /* 35 '5' */
_ALNUM, /* 36 '6' */
_ALNUM, /* 37 '7' */
_ALNUM, /* 38 '8' */
_ALNUM, /* 39 '9' */
_OTHER, /* 3A ':' */
_OTHER, /* 3B ';' */
_OTHER, /* 3C '<' */
_OTHER, /* 3D '=' */
_OTHER, /* 3E '>' */
_OTHER, /* 3F '?' */
_OTHER, /* 40 '@' */
_LATNA, /* 41 'A' */
_LATNB, /* 42 'B' */
_ALNUM, /* 43 'C' */
_LATND, /* 44 'D' */
_LATNE, /* 45 'E' */
_ALNUM, /* 46 'F' */
_ALNUM, /* 47 'G' */
_ALNUM, /* 48 'H' */
_LATNI, /* 49 'I' */
_ALNUM, /* 4A 'J' */
_ALNUM, /* 4B 'K' */
_ALNUM, /* 4C 'L' */
_ALNUM, /* 4D 'M' */
_LATNN, /* 4E 'N' */
_ALNUM, /* 4F 'O' */
_ALNUM, /* 50 'P' */
_ALNUM, /* 51 'Q' */
_ALNUM, /* 52 'R' */
_LATNS, /* 53 'S' */
_LATNT, /* 54 'T' */
_LATNU, /* 55 'U' */
_ALNUM, /* 56 'V' */
_ALNUM, /* 57 'W' */
_LATNX, /* 58 'X' */
_ALNUM, /* 59 'Y' */
_LATNZ, /* 5A 'Z' */
_OTHER, /* 5B '[' */
_OTHER, /* 5C '\' */
_OTHER, /* 5D ']' */
_OTHER, /* 5E '^' */
_OTHER, /* 5F '_' */
_OTHER, /* 60 '`' */
_ALNUM, /* 61 'a' */
_ALNUM, /* 62 'b' */
_ALNUM, /* 63 'c' */
_ALNUM, /* 64 'd' */
_ALNUM, /* 65 'e' */
_ALNUM, /* 66 'f' */
_ALNUM, /* 67 'g' */
_ALNUM, /* 68 'h' */
_ALNUM, /* 69 'i' */
_ALNUM, /* 6A 'j' */
_ALNUM, /* 6B 'k' */
_ALNUM, /* 6C 'l' */
_ALNUM, /* 6D 'm' */
_ALNUM, /* 6E 'n' */
_ALNUM, /* 6F 'o' */
_ALNUM, /* 70 'p' */
_ALNUM, /* 71 'q' */
_ALNUM, /* 72 'r' */
_ALNUM, /* 73 's' */
_ALNUM, /* 74 't' */
_ALNUM, /* 75 'u' */
_ALNUM, /* 76 'v' */
_ALNUM, /* 77 'w' */
_ALNUM, /* 78 'x' */
_ALNUM, /* 79 'y' */
_ALNUM, /* 7A 'z' */
_OTHER, /* 7B '{' */
_OTHER, /* 7C '|' */
_OTHER, /* 7D '}' */
_OTHER, /* 7E '~' */
_INVLD /* 7F DEL */
};
// @formatter:on
private final CharacterClass[] list;
private final Map<Integer, CharacterClass> auxilary;
private final boolean extraneousIgnored;
public CharacterSet() {
this(false);
}
public CharacterSet(boolean extraneousIgnored) {
this.list = Arrays.copyOf(prototype, prototype.length);
this.auxilary = new TreeMap<>();
this.extraneousIgnored = extraneousIgnored;
}
public CharacterClass getClass(int character) {
return (character < list.length) ? list[character] : auxilary.getOrDefault(character, _OTHER);
}
public void reset() {
System.arraycopy(prototype, 0, list, 0, prototype.length);
auxilary.clear();
}
public void setClass(int character, CharacterClass clazz) {
if (character < list.length) {
list[character] = clazz;
} else {
auxilary.put(character, clazz);
}
}
public boolean isDelimiter(int character) {
switch (getClass(character)) {
case ELEMENT_DELIMITER:
case ELEMENT_REPEATER:
case SEGMENT_DELIMITER:
case COMPONENT_DELIMITER:
case RELEASE_CHARACTER:
return true;
default:
return false;
}
}
public boolean isWhitespace(int character) {
CharacterClass clazz = getClass(character);
switch (clazz) {
case SPACE:
case WHITESPACE:
return true;
default:
return ignore(clazz);
}
}
public boolean isIgnored(int character) {
return ignore(getClass(character));
}
private boolean ignore(CharacterClass clazz) {
switch (clazz) {
case CONTROL:
case INVALID:
case WHITESPACE:
return extraneousIgnored;
default:
return false;
}
}
public boolean isCharacterClass(int character, CharacterClass clazz) {
return getClass(character).equals(clazz);
}
public boolean isValidDelimiter(int character) {
switch (getClass(character)) {
case CONTROL:
return !extraneousIgnored;
case WHITESPACE:
case OTHER:
return true;
default:
return false;
}
}
public static boolean isValid(int character) {
if (character >= prototype.length) {
return true;
}
switch (prototype[character]) {
case CONTROL:
case INVALID:
return false;
default:
return true;
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/X12Dialect.java | src/main/java/io/xlate/edi/internal/stream/tokenization/X12Dialect.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import io.xlate.edi.stream.EDIStreamConstants.Standards;
import io.xlate.edi.stream.Location;
public class X12Dialect extends Dialect {
private static final String ISA = "ISA";
private static final String ISX = "ISX";
private static final String GS = "GS";
private static final String ST = "ST";
private static final int RELEASE_ISX_SEGMENT = 704; // 007040 (Version 7, release 4)
private static final int RELEASE_ELEMENT_I65 = 402; // 004020 (Version 4, release 2)
static final char DFLT_SEGMENT_TERMINATOR = '~';
static final char DFLT_DATA_ELEMENT_SEPARATOR = '*';
static final char DFLT_COMPONENT_ELEMENT_SEPARATOR = ':';
static final char DFLT_REPETITION_SEPARATOR = '^';
private static final int X12_ISA_LENGTH = 106;
private static final int X12_ELEMENT_OFFSET = 3;
private static final int X12_COMPONENT_OFFSET = 104;
private static final int X12_SEGMENT_OFFSET = 105;
private static final int X12_REPEAT_OFFSET = 82;
private static final Integer[] X12_ISA_TOKENS = { 3, 6, 17, 20, 31, 34, 50, 53, 69, 76, 81, 83, 89, 99, 101, 103 };
private static final Set<Integer> elementDelimiterOffsets = new HashSet<>(Arrays.asList(X12_ISA_TOKENS));
private String[] version;
char[] header;
private int index = -1;
private CharacterSet characters;
private static final int TX_AGENCY = 0;
private static final int TX_VERSION = 1;
private String agencyCode;
private String groupVersion;
X12Dialect() {
super(State.DialectCode.X12, new String[2]);
segmentDelimiter = DFLT_SEGMENT_TERMINATOR;
elementDelimiter = DFLT_DATA_ELEMENT_SEPARATOR;
decimalMark = '.';
releaseIndicator = 0;
componentDelimiter = DFLT_COMPONENT_ELEMENT_SEPARATOR;
elementRepeater = DFLT_REPETITION_SEPARATOR;
clearTransactionVersion();
}
@Override
public String getStandard() {
return Standards.X12;
}
@Override
public String[] getVersion() {
return version;
}
boolean initialize(CharacterSet characters) {
for (int i = 0, m = X12_ISA_LENGTH; i < m; i++) {
if (elementDelimiterOffsets.contains(i)) {
if (elementDelimiter != header[i]) {
rejectionMessage = String.format("Element delimiter '%s' required in position %d of X12 header but not found", elementDelimiter, i + 1);
return false;
}
} else {
if (elementDelimiter == header[i]) {
rejectionMessage = String.format("Unexpected element delimiter value '%s' in X12 header position %d", elementDelimiter, i + 1);
return false;
}
}
}
componentDelimiter = header[X12_COMPONENT_OFFSET];
segmentDelimiter = header[X12_SEGMENT_OFFSET];
elementRepeater = header[X12_REPEAT_OFFSET];
characters.setClass(componentDelimiter, CharacterClass.COMPONENT_DELIMITER);
characters.setClass(segmentDelimiter, CharacterClass.SEGMENT_DELIMITER);
version = new String[] { new String(header, 84, 5) };
if (numericVersion() >= RELEASE_ELEMENT_I65 && characters.isValidDelimiter(elementRepeater)) {
characters.setClass(elementRepeater, CharacterClass.ELEMENT_REPEATER);
} else {
/*
* Exception parsing the version or older version - the ELEMENT_REPEATER
* will not be set.
*/
elementRepeater = '\0';
}
this.characters = characters;
initialized = true;
return true;
}
int numericVersion() {
try {
return Integer.parseInt(version[0]);
} catch (NumberFormatException nfe) {
return 0;
}
}
@Override
public String getHeaderTag() {
return ISA;
}
@Override
public boolean appendHeader(CharacterSet characters, char value) {
index++;
switch (index) {
case 0:
header = new char[X12_ISA_LENGTH];
break;
case X12_ELEMENT_OFFSET:
elementDelimiter = value;
characters.setClass(elementDelimiter, CharacterClass.ELEMENT_DELIMITER);
break;
case X12_REPEAT_OFFSET:
case X12_COMPONENT_OFFSET:
case X12_SEGMENT_OFFSET:
break;
default:
if (characters.isIgnored(value)) {
// Discard control character if not used as a delimiter
index--;
return true;
}
break;
}
header[index] = value;
boolean proceed = true;
if (index == X12_SEGMENT_OFFSET) {
initialize(characters);
proceed = isConfirmed();
}
return proceed;
}
@Override
public void clearTransactionVersion() {
agencyCode = "";
groupVersion = "";
transactionVersion[TX_AGENCY] = agencyCode;
transactionVersion[TX_VERSION] = groupVersion;
updateTransactionVersionString(null);
}
@Override
public void elementData(CharSequence data, Location location) {
if (ISX.equals(location.getSegmentTag()) && numericVersion() >= RELEASE_ISX_SEGMENT) {
if (location.getElementPosition() == 1 && data.length() == 1) {
releaseIndicator = data.charAt(0);
characters.setClass(releaseIndicator, CharacterClass.RELEASE_CHARACTER);
}
} else if (GS.equals(location.getSegmentTag())) {
switch (location.getElementPosition()) {
case 1:
clearTransactionVersion();
break;
case 7:
agencyCode = data.toString();
break;
case 8:
groupVersion = data.toString();
transactionVersion[TX_AGENCY] = agencyCode;
transactionVersion[TX_VERSION] = groupVersion;
updateTransactionVersionString(transactionVersion);
break;
default:
break;
}
} else if (ST.equals(location.getSegmentTag())) {
switch (location.getElementPosition()) {
case 1:
transactionType = data.toString();
break;
case 3:
if (data.length() > 0) {
setTransactionVersionElement(data, TX_VERSION);
}
break;
default:
break;
}
}
}
@Override
public void transactionEnd() {
transactionType = null;
transactionVersion[TX_VERSION] = groupVersion;
updateTransactionVersionString(transactionVersion);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/EventHandler.java | src/main/java/io/xlate/edi/internal/stream/tokenization/EventHandler.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
public interface EventHandler extends ElementDataHandler, ValidationEventHandler {
void interchangeBegin(Dialect dialect);
void interchangeEnd();
boolean segmentBegin(String tag);
boolean segmentEnd();
boolean compositeBegin(boolean isNil, boolean derived);
boolean compositeEnd(boolean isNil);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/TradacomsDialect.java | src/main/java/io/xlate/edi/internal/stream/tokenization/TradacomsDialect.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import io.xlate.edi.stream.EDIStreamConstants.Standards;
import io.xlate.edi.stream.Location;
public class TradacomsDialect extends Dialect {
public static final String STX = "STX";
public static final String MHD = "MHD";
private static final String[] EMPTY = new String[0];
private static final int TRADACOMS_ELEMENT_OFFSET = 3;
static final char DFLT_SEGMENT_TERMINATOR = '\'';
static final char DFLT_DATA_ELEMENT_SEPARATOR = '+';
static final char DFLT_COMPONENT_ELEMENT_SEPARATOR = ':';
static final char DFLT_RELEASE_CHARACTER = '?';
private String[] version;
StringBuilder header;
private int index = -1;
private static final int TX_VERSION = 0;
TradacomsDialect() {
super(State.DialectCode.TRADACOMS, new String[1]);
componentDelimiter = DFLT_COMPONENT_ELEMENT_SEPARATOR;
elementDelimiter = DFLT_DATA_ELEMENT_SEPARATOR;
releaseIndicator = DFLT_RELEASE_CHARACTER;
elementRepeater = 0;
segmentDelimiter = DFLT_SEGMENT_TERMINATOR;
segmentTagTerminator = '=';
clearTransactionVersion();
}
@Override
public String getHeaderTag() {
return STX;
}
boolean initialize(CharacterSet characters) {
String[] parsedVersion = parseVersion();
if (parsedVersion.length > 1) {
this.version = parsedVersion;
initialized = true;
characters.setClass(segmentDelimiter, CharacterClass.SEGMENT_DELIMITER);
} else {
rejectionMessage = "Unable to obtain version from TRADACOMS header segment";
initialized = false;
}
return initialized;
}
private String[] parseVersion() {
int versionStart = 4; // 4 = length of "STX="
int versionEnd = header.indexOf(String.valueOf(elementDelimiter), versionStart);
if (versionEnd - versionStart > 1) {
return header.substring(versionStart, versionEnd).split('\\' + String.valueOf(componentDelimiter));
}
return EMPTY;
}
@Override
public String getStandard() {
return Standards.TRADACOMS;
}
@Override
public String[] getVersion() {
return version;
}
@Override
public boolean appendHeader(CharacterSet characters, char value) {
boolean proceed = true;
switch (++index) {
case 0:
header = new StringBuilder();
break;
case TRADACOMS_ELEMENT_OFFSET:
if (value != segmentTagTerminator) {
rejectionMessage = String.format("Expected TRADACOMS segment tag delimiter '%s', but found '%s'", segmentTagTerminator, value);
return false;
}
/*
* TRADACOMS delimiters are fixed. Do not set the element delimiter
* until after the segment tag has been passed to prevent triggering
* an "element data" event prematurely.
*/
characters.setClass(segmentTagTerminator, CharacterClass.SEGMENT_TAG_DELIMITER);
characters.setClass(componentDelimiter, CharacterClass.COMPONENT_DELIMITER);
characters.setClass(elementDelimiter, CharacterClass.ELEMENT_DELIMITER);
characters.setClass(releaseIndicator, CharacterClass.RELEASE_CHARACTER);
break;
default:
break;
}
if (characters.isIgnored(value)) {
index--;
} else {
header.append(value);
proceed = processInterchangeHeader(characters, value);
}
return proceed;
}
boolean processInterchangeHeader(CharacterSet characters, char value) {
if (segmentDelimiter == value) {
initialize(characters);
return isConfirmed();
}
return true;
}
@Override
protected void clearTransactionVersion() {
transactionVersion[TX_VERSION] = ""; // Single position only
updateTransactionVersionString(null);
}
@Override
public void elementData(CharSequence data, Location location) {
if (MHD.contentEquals(location.getSegmentTag())) {
messageHeaderElementData(data, location);
}
}
void messageHeaderElementData(CharSequence data, Location location) {
if (location.getElementPosition() == 1) {
clearTransactionVersion();
} else if (location.getElementPosition() == 2) {
switch (location.getComponentPosition()) {
case 1:
transactionType = data.toString();
break;
case 2:
setTransactionVersionElement(data, TX_VERSION);
break;
default:
break;
}
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/tokenization/Dialect.java | src/main/java/io/xlate/edi/internal/stream/tokenization/Dialect.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.tokenization;
import io.xlate.edi.stream.Location;
public abstract class Dialect {
protected final String[] transactionVersion;
protected final int dialectStateCode;
protected char segmentDelimiter;
protected char segmentTagTerminator = '\0';
protected char elementDelimiter;
protected char decimalMark = '\0';
protected char releaseIndicator;
protected char componentDelimiter;
protected char elementRepeater;
protected boolean initialized;
protected String rejectionMessage;
protected String transactionType;
protected String transactionVersionString;
protected Dialect(int dialectStateCode, String[] initialTransactionVersion) {
this.dialectStateCode = dialectStateCode;
this.transactionVersion = initialTransactionVersion;
}
public static String getStandard(Dialect dialect) {
return dialect != null ? dialect.getStandard() : "UNKNOWN";
}
public int getDialectStateCode() {
return dialectStateCode;
}
public State getTagSearchState() {
return State.TAG_SEARCH;
}
public char getComponentElementSeparator() {
return componentDelimiter;
}
public char getDataElementSeparator() {
return elementDelimiter;
}
public char getDecimalMark() {
return decimalMark;
}
public char getReleaseIndicator() {
return releaseIndicator;
}
public char getRepetitionSeparator() {
return elementRepeater;
}
public char getSegmentTerminator() {
return segmentDelimiter;
}
public char getSegmentTagTerminator() {
return segmentTagTerminator;
}
public boolean isDecimalMark(char value) {
return value == getDecimalMark();
}
public boolean isConfirmed() {
return initialized;
}
public boolean isRejected() {
return rejectionMessage != null;
}
public String getRejectionMessage() {
return rejectionMessage;
}
/**
* Check if the given segment tag is this dialect's service advice segment.
* E.g. <code>UNA</code> resolves to <code>true</code> for EDIFACT.
*
* @param segmentTag the character tag of the segment
* @return true when the segmentTag is the dialect's service segment,
* otherwise false
*/
public boolean isServiceAdviceSegment(CharSequence segmentTag) {
return false; // Service segment not used by default
}
public abstract String getStandard();
public abstract String[] getVersion();
public abstract String getHeaderTag();
public abstract boolean appendHeader(CharacterSet characters, char value);
/**
* Notify the dialect of element data and its location in the stream. Does
* not support binary elements.
*
* @param data
* the element data
* @param location
* the location of the element
*/
public abstract void elementData(CharSequence data, Location location);
protected abstract void clearTransactionVersion();
void updateTransactionVersionString(String[] transactionVersion) {
transactionVersionString = transactionVersion != null ? String.join(".", transactionVersion) : "";
}
void setTransactionVersionElement(CharSequence data, int versionElement) {
transactionVersion[versionElement] = data.toString();
updateTransactionVersionString(transactionVersion);
}
/**
* Notify the dialect that a transaction is complete.
*/
public void transactionEnd() {
transactionType = null;
clearTransactionVersion();
}
/**
* Notify the dialect that a group is complete.
*/
public void groupEnd() {
clearTransactionVersion();
}
/**
* Returns the transaction type code, or null if not within a transaction
*
* @return the transaction type code, or null if not within a transaction
*
* @since 1.16
*/
public String getTransactionType() {
return transactionType;
}
/**
* Returns the identifying elements of the current transaction's version.
*
* @return the array of elements identifying the current transaction's
* version
*/
public String[] getTransactionVersion() {
return transactionVersionString.isEmpty() ? null : transactionVersion;
}
/**
* Returns the identifying elements of the current transaction's version as
* a single String joined with period `.` characters.
*
* @return the String representation of the elements identifying the current
* transaction's version
*/
public String getTransactionVersionString() {
return transactionVersionString;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/DecimalValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/DecimalValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.Dialect;
class DecimalValidator extends NumericValidator {
@Override
int validate(Dialect dialect, CharSequence value) {
int length = value.length();
int dec = 0;
int exp = 0;
boolean invalid = false;
for (int i = 0, m = length; i < m; i++) {
switch (value.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
case 'E':
length--;
if (++exp > 1) {
invalid = true;
}
break;
case '-':
length--;
invalid = invalidNegativeSymbol(i, value, invalid);
break;
default:
if (dialect.isDecimalMark(value.charAt(i))) {
length--;
invalid = invalidDecimalSymbol(++dec, exp, invalid);
} else {
invalid = true;
}
break;
}
}
return invalid ? -length : length;
}
boolean invalidNegativeSymbol(int currentIndex, CharSequence value, boolean currentlyInvalid) {
return currentlyInvalid || (currentIndex > 0 && value.charAt(currentIndex - 1) != 'E');
}
boolean invalidDecimalSymbol(int decimalCount, int exponentCount, boolean currentlyInvalid) {
return currentlyInvalid || decimalCount > 1 || exponentCount > 0;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/PairedSyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/PairedSyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class PairedSyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.elementCount == 0) {
return;
}
if (status.elementCount < syntax.getPositions().size()) {
signalConditionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/TimeValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/TimeValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import java.util.List;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.stream.EDIStreamValidationError;
class TimeValidator extends ElementValidator {
@Override
void validate(Dialect dialect,
EDISimpleType element,
CharSequence value,
List<EDIStreamValidationError> errors) {
final int length = value.length();
if (!validateLength(dialect, element, length, errors) || (length < 6 && length % 2 != 0) || !validValue(value)) {
errors.add(EDIStreamValidationError.INVALID_TIME);
}
}
@Override
void format(Dialect dialect, EDISimpleType element, CharSequence value, StringBuilder result) {
int length = value.length();
result.append(value);
for (long i = length, min = element.getMinLength(); i < min; i++) {
result.append('0');
}
}
static boolean validValue(CharSequence value) {
final int length = value.length();
int hr = 0;
int mi = 0;
int se = 0;
int ds = 0;
int index = 0;
for (int i = 0; i < length; i++) {
char current = value.charAt(i);
switch (current) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
default:
return false;
}
int digit = Character.digit(current, 10);
switch (++index) {
case 1:
case 2:
hr = hr * 10 + digit;
break;
case 3:
case 4:
mi = mi * 10 + digit;
break;
case 5:
case 6:
se = se * 10 + digit;
break;
default:
ds = ds * 10 + digit;
break;
}
}
return hr < 24 && mi < 60 && se < 60;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/ListSyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/ListSyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class ListSyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.anchorPresent && status.elementCount == 1) {
signalConditionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/SingleSyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/SingleSyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class SingleSyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.elementCount > 1) {
signalExclusionError(syntax, structure, handler);
} else if (status.elementCount == 0) {
signalConditionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/Validator.java | src/main/java/io/xlate/edi/internal/stream/validation/Validator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import static io.xlate.edi.stream.EDIStreamValidationError.IMPLEMENTATION_INVALID_CODE_VALUE;
import static io.xlate.edi.stream.EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES;
import static io.xlate.edi.stream.EDIStreamValidationError.IMPLEMENTATION_SEGMENT_BELOW_MINIMUM_USE;
import static io.xlate.edi.stream.EDIStreamValidationError.IMPLEMENTATION_TOO_FEW_REPETITIONS;
import static io.xlate.edi.stream.EDIStreamValidationError.IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT;
import static io.xlate.edi.stream.EDIStreamValidationError.IMPLEMENTATION_UNUSED_SEGMENT_PRESENT;
import static io.xlate.edi.stream.EDIStreamValidationError.INVALID_CODE_VALUE;
import static io.xlate.edi.stream.EDIStreamValidationError.LOOP_OCCURS_OVER_MAXIMUM_TIMES;
import static io.xlate.edi.stream.EDIStreamValidationError.MANDATORY_SEGMENT_MISSING;
import static io.xlate.edi.stream.EDIStreamValidationError.REQUIRED_DATA_ELEMENT_MISSING;
import static io.xlate.edi.stream.EDIStreamValidationError.SEGMENT_EXCEEDS_MAXIMUM_USE;
import static io.xlate.edi.stream.EDIStreamValidationError.SEGMENT_NOT_IN_DEFINED_TRANSACTION_SET;
import static io.xlate.edi.stream.EDIStreamValidationError.SEGMENT_NOT_IN_PROPER_SEQUENCE;
import static io.xlate.edi.stream.EDIStreamValidationError.TOO_MANY_COMPONENTS;
import static io.xlate.edi.stream.EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS;
import static io.xlate.edi.stream.EDIStreamValidationError.TOO_MANY_REPETITIONS;
import static io.xlate.edi.stream.EDIStreamValidationError.UNEXPECTED_SEGMENT;
import java.nio.CharBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.logging.Logger;
import io.xlate.edi.internal.schema.StaEDISchema;
import io.xlate.edi.internal.stream.StaEDIStreamLocation;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.internal.stream.tokenization.ElementDataHandler;
import io.xlate.edi.internal.stream.tokenization.StreamEvent;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIControlType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.EDIType.Type;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.schema.implementation.CompositeImplementation;
import io.xlate.edi.schema.implementation.Discriminator;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.schema.implementation.LoopImplementation;
import io.xlate.edi.schema.implementation.PolymorphicImplementation;
import io.xlate.edi.schema.implementation.SegmentImplementation;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamValidationError;
import io.xlate.edi.stream.Location;
public class Validator {
static final Logger LOGGER = Logger.getLogger(Validator.class.getName());
// Versions are not yet supported for segments
static final String SEGMENT_VERSION = "";
private Schema containerSchema;
private Schema schema;
private final boolean validateCodeValues;
private final boolean formatElements;
private final boolean trimDiscriminatorValues;
private boolean initial = true;
final UsageNode root;
final UsageNode implRoot;
private boolean segmentExpected;
private UsageNode segment;
private UsageNode correctSegment;
private UsageNode composite;
private UsageNode element;
private Queue<RevalidationNode> revalidationQueue = new LinkedList<>();
private boolean implSegmentSelected;
private UsageNode implNode;
private UsageNode implComposite;
private UsageNode implElement;
private List<UsageNode> implSegmentCandidates = new ArrayList<>();
private final Deque<UsageNode> loopStack = new ArrayDeque<>();
private final List<UsageError> useErrors = new ArrayList<>();
private final List<UsageError> elementErrors = new ArrayList<>(5);
private int depth = 1;
private final UsageCursor cursor = new UsageCursor();
static class UsageCursor {
UsageNode standard;
UsageNode impl;
boolean hasNextSibling() {
return standard.getNextSibling() != null;
}
void next(UsageNode nextImpl) {
standard = standard.getNextSibling();
if (nextImpl != null) {
impl = nextImpl;
}
}
void nagivateUp(int limit) {
standard = standard.getParent();
if (impl != null && impl.getDepth() > limit) {
impl = impl.getParent().getFirstSiblingSameType();
}
}
void reset(UsageNode root, UsageNode implRoot) {
standard = UsageNode.getFirstChild(root);
impl = UsageNode.getFirstChild(implRoot);
}
UsageCursor copy() {
UsageCursor copy = new UsageCursor();
copy.standard = this.standard;
copy.impl = this.impl;
return copy;
}
}
static class RevalidationNode {
final UsageNode standard;
final UsageNode impl;
final CharBuffer data;
final StaEDIStreamLocation location;
public RevalidationNode(UsageNode standard, UsageNode impl, CharSequence data, StaEDIStreamLocation location) {
this.standard = standard;
this.impl = impl;
this.data = CharBuffer.allocate(data.length());
this.data.append(data);
this.data.flip();
this.location = location.copy();
}
public RevalidationNode(UsageNode standard, UsageNode impl, StaEDIStreamLocation location) {
this.standard = standard;
this.impl = impl;
this.data = null;
this.location = location.copy();
}
}
public static Validator forSchema(Schema schema, Schema containerSchema, ValidatorConfig config) {
final Validator instance;
if (schema != null) {
instance = new Validator(schema, containerSchema, config);
} else {
instance = null;
}
return instance;
}
public Validator(Schema schema, Schema containerSchema, ValidatorConfig config) {
this.schema = schema;
this.validateCodeValues = config.validateControlCodeValues();
this.formatElements = config.formatElements();
this.trimDiscriminatorValues = config.trimDiscriminatorValues();
this.containerSchema = containerSchema;
LOGGER.finer(() -> "Creating usage tree");
root = buildTree(schema.getStandard());
LOGGER.finer(() -> "Done creating usage tree");
correctSegment = segment = root.getFirstChild();
if (schema.getImplementation() != null) {
implRoot = buildImplTree(null, 0, schema.getImplementation(), -1);
implNode = implRoot.getFirstChild();
} else {
implRoot = null;
implNode = null;
}
}
public void reset() {
if (initial) {
return;
}
root.reset();
correctSegment = segment = root.getFirstChild();
if (implRoot != null) {
implRoot.reset();
implNode = implRoot.getFirstChild();
}
cursor.reset(root, implRoot);
depth = 1;
segmentExpected = false;
implSegmentSelected = false;
clearElements();
implSegmentCandidates.clear();
useErrors.clear();
elementErrors.clear();
initial = true;
}
void clearElements() {
composite = null;
element = null;
implComposite = null;
implElement = null;
}
public boolean isPendingDiscrimination() {
return !implSegmentCandidates.isEmpty();
}
public EDIReference getSegmentReference() {
final EDIReference reference;
if (implSegmentSelected) {
reference = implNode.getLink();
} else if (segmentExpected) {
reference = segment.getLink();
} else {
reference = null;
}
return reference;
}
public EDIReference getCompositeReference() {
final EDIReference reference;
if (implSegmentSelected && implComposite != null) {
reference = implComposite.getLink();
} else if (composite != null) {
reference = composite.getLink();
} else {
reference = null;
}
return reference;
}
public boolean isBinaryElementLength() {
if (element != null) {
UsageNode next = element.getNextSibling();
if (next != null && next.isNodeType(EDIType.Type.ELEMENT)) {
EDISimpleType nextType = (EDISimpleType) next.getReferencedType();
return nextType.getBase() == EDISimpleType.Base.BINARY;
}
}
return false;
}
public EDIReference getElementReference() {
final EDIReference reference;
if (implSegmentSelected && implElement != null) {
reference = implElement.getLink();
} else if (element != null) {
reference = element.getLink();
} else {
reference = null;
}
return reference;
}
private static EDIReference referenceOf(EDIComplexType type, int minOccurs, int maxOccurs) {
return new EDIReference() {
@Override
public EDIType getReferencedType() {
return type;
}
@Override
public int getMinOccurs() {
return minOccurs;
}
@Override
public int getMaxOccurs() {
return maxOccurs;
}
@Override
public String getTitle() {
return type.getTitle();
}
@Override
public String getDescription() {
return type.getDescription();
}
};
}
private static UsageNode buildTree(final EDIComplexType root) {
return buildTree(null, 0, referenceOf(root, 1, 1), -1);
}
private static UsageNode buildTree(UsageNode parent, int parentDepth, EDIReference link, int index) {
int depth = parentDepth + 1;
EDIType referencedNode = link.getReferencedType();
if (referencedNode instanceof EDISimpleType) {
return new UsageNode(parent, depth, link, index);
}
final UsageNode node;
if (referencedNode instanceof EDIControlType) {
node = new ControlUsageNode(parent, depth, link, index);
} else {
node = new UsageNode(parent, depth, link, index);
}
EDIComplexType structure = (EDIComplexType) referencedNode;
List<? extends EDIReference> children = structure.getReferences();
List<UsageNode> childUsages = node.getChildren();
int childIndex = -1;
for (EDIReference child : children) {
childUsages.add(buildTree(node, depth, child, ++childIndex));
}
return node;
}
private static UsageNode buildImplTree(UsageNode parent, int parentDepth, EDITypeImplementation impl, int index) {
int depth = parentDepth + 1;
final UsageNode node = new UsageNode(parent, depth, impl, index);
final List<EDITypeImplementation> children;
switch (impl.getType()) {
case COMPOSITE:
children = CompositeImplementation.class.cast(impl).getSequence();
break;
case ELEMENT:
children = Collections.emptyList();
break;
case TRANSACTION:
case LOOP:
children = LoopImplementation.class.cast(impl).getSequence();
break;
case SEGMENT:
children = SegmentImplementation.class.cast(impl).getSequence();
break;
default:
throw new IllegalArgumentException("Illegal type of EDITypeImplementation: " + impl.getType());
}
List<UsageNode> childUsages = node.getChildren();
int childIndex = -1;
for (EDITypeImplementation child : children) {
++childIndex;
UsageNode childNode = null;
if (child != null) {
childNode = buildImplTree(node, depth, child, childIndex);
}
childUsages.add(childNode);
}
return node;
}
private UsageNode startLoop(UsageNode loop) {
loop.incrementUsage();
loop.resetChildren();
UsageNode startSegment = loop.getFirstChild();
startSegment.reset();
startSegment.incrementUsage();
depth++;
return startSegment;
}
private void completeLoops(ValidationEventHandler handler, int workingDepth) {
while (this.depth < workingDepth) {
handleMissingMandatory(handler, workingDepth);
UsageNode loop = loopStack.pop();
handler.loopEnd(loop.getLink());
workingDepth--;
if (loop.isImplementation()) {
implNode = loop;
}
}
}
public void validateSegment(ValidationEventHandler handler, CharSequence tag) {
initial = false;
segmentExpected = true;
implSegmentSelected = false;
clearElements();
final int startDepth = this.depth;
UsageCursor startLoop = null;
cursor.standard = correctSegment;
cursor.impl = implNode;
// Version specific validation must be complete by the end of a segment
revalidationQueue.clear();
useErrors.clear();
boolean handled = false;
while (!handled) {
handled = handleNode(tag, cursor.standard, cursor.impl, startDepth, handler);
if (!handled) {
/*
* The segment doesn't match the current node, ensure
* requirements for the current node are met.
*/
checkMinimumUsage(cursor.standard);
UsageNode nextImpl = getNextImplementationNode(cursor.impl, cursor.standard.getReferencedType());
if (cursor.hasNextSibling()) {
// Advance to the next segment in the loop
cursor.next(nextImpl); // Impl node may be unchanged
} else {
if (startLoop == null) {
/*
* Remember the position of the last known loop's segment in case
* the segment being validated is an earlier sibling that is out of
* proper sequence.
*/
startLoop = cursor.copy();
}
handled = handleLoopEnd(cursor, startLoop, tag, startDepth, handler);
}
}
}
handleMissingMandatory(handler);
}
public void countSegment(CharSequence tag) {
if (loopStack.isEmpty()) {
countSegment(root, tag);
} else {
for (UsageNode loop : loopStack) {
countSegment(loop, tag);
}
}
}
void countSegment(UsageNode node, CharSequence tag) {
int count;
if ((count = count(node, EDIControlType.Type.SEGMENTS)) > 0) {
LOGGER.finer(() -> "Counted tag " + tag + " @ " + count + " towards " + node);
}
}
void countControl() {
if (containerSchema == null) {
if (loopStack.isEmpty()) {
count(root, EDIControlType.Type.CONTROLS);
} else {
count(loopStack.peekLast(), EDIControlType.Type.CONTROLS);
}
}
}
int count(UsageNode node, EDIControlType.Type type) {
if (node instanceof ControlUsageNode) {
return ((ControlUsageNode) node).incrementCount(type);
}
return 0;
}
boolean handleNode(CharSequence tag, UsageNode current, UsageNode currentImpl, int startDepth, ValidationEventHandler handler) {
final boolean handled;
switch (current.getNodeType()) {
case SEGMENT:
handled = handleSegment(tag, current, currentImpl, startDepth, handler);
break;
case GROUP:
case TRANSACTION:
case LOOP:
handled = handleLoop(tag, current, currentImpl, startDepth, handler);
break;
default:
handled = false;
break;
}
return handled;
}
boolean handleSegment(CharSequence tag, UsageNode current, UsageNode currentImpl, int startDepth, ValidationEventHandler handler) {
if (!current.getId().contentEquals(tag)) {
/*
* The schema segment does not match the segment tag found
* in the stream.
*/
return false;
}
if (current.isUsed() && current.isFirstChild() &&
current.getParent().isNodeType(EDIType.Type.LOOP)) {
/*
* The current segment is the first segment in the loop and
* the loop has previous occurrences. This will occur when
* the previous loop occurrence contained only the loop start
* segment.
*/
return false;
}
completeLoops(handler, startDepth);
current.incrementUsage();
current.resetChildren();
if (current.exceedsMaximumUsage(SEGMENT_VERSION)) {
handleMissingMandatory(handler);
handler.segmentError(current.getId(), current.getLink(), SEGMENT_EXCEEDS_MAXIMUM_USE);
}
correctSegment = segment = current;
if (currentImpl != null) {
UsageNode impl = currentImpl;
while (impl != null && impl.getReferencedType().equals(current.getReferencedType())) {
implSegmentCandidates.add(impl);
impl = impl.getNextSibling();
}
if (implSegmentCandidates.isEmpty()) {
handleMissingMandatory(handler);
handler.segmentError(current.getId(), current.getLink(), IMPLEMENTATION_UNUSED_SEGMENT_PRESENT);
// Save the currentImpl so that the search is resumed from the correct location
implNode = currentImpl;
} else if (isSingleSegmentWithoutDescriminator(implSegmentCandidates)) {
currentImpl.incrementUsage();
currentImpl.resetChildren();
if (currentImpl.exceedsMaximumUsage(SEGMENT_VERSION)) {
handler.segmentError(currentImpl.getId(), current.getLink(), SEGMENT_EXCEEDS_MAXIMUM_USE);
}
implNode = currentImpl;
implSegmentCandidates.clear();
implSegmentSelected = true;
}
}
return true;
}
boolean isSingleSegmentWithoutDescriminator(List<UsageNode> candidates) {
if (candidates.size() != 1) {
return false;
}
PolymorphicImplementation candidate = (PolymorphicImplementation) candidates.get(0).getLink();
return candidate.getDiscriminator() == null;
}
static UsageNode toSegment(UsageNode node) {
UsageNode segmentNode;
switch (node.getNodeType()) {
case SEGMENT:
segmentNode = node;
break;
case GROUP:
case TRANSACTION:
case LOOP:
segmentNode = node.getFirstChild();
break;
default:
throw new IllegalStateException("Unexpected node type: " + node.getNodeType());
}
return segmentNode;
}
void checkMinimumUsage(UsageNode node) {
if (!node.hasMinimumUsage(SEGMENT_VERSION)) {
/*
* The schema segment has not met it's minimum usage
* requirement.
*/
final UsageNode segmentNode = toSegment(node);
if (!segmentNode.isImplementation()) {
useErrors.add(new UsageError(segmentNode.getLink(), MANDATORY_SEGMENT_MISSING, node.getDepth()));
} else if (node.getNodeType() == Type.SEGMENT) {
useErrors.add(new UsageError(segmentNode.getLink(), IMPLEMENTATION_SEGMENT_BELOW_MINIMUM_USE, node.getDepth()));
} else {
useErrors.add(new UsageError(segmentNode.getParent().getLink(), IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, node.getDepth()));
}
}
}
UsageNode getNextImplementationNode(UsageNode implNode, EDIType type) {
while (implNode != null && implNode.getReferencedType().equals(type)) {
// Advance past multiple implementations of the 'current' standard node
checkMinimumUsage(implNode);
implNode = implNode.getNextSibling();
}
// `implNode` will be an implementation of the type following `type`
return implNode;
}
boolean handleLoop(CharSequence tag, UsageNode current, UsageNode currentImpl, int startDepth, ValidationEventHandler handler) {
if (!current.getFirstChild().getId().contentEquals(tag)) {
return false;
}
completeLoops(handler, startDepth);
boolean implUnusedSegment = false;
if (currentImpl != null) {
UsageNode impl = currentImpl;
while (impl != null && impl.getReferencedType().equals(current.getReferencedType())) {
this.implSegmentCandidates.add(impl);
impl = impl.getNextSibling();
}
if (implSegmentCandidates.isEmpty()) {
implUnusedSegment = true;
// Save the currentImpl so that the search is resumed from the correct location
implNode = currentImpl;
} else if (implSegmentCandidates.size() == 1) {
handleImplementationSelected(currentImpl, currentImpl.getFirstChild(), handler);
}
}
if (currentImpl != null && implSegmentSelected) {
loopStack.push(currentImpl);
handler.loopBegin(currentImpl.getLink());
} else {
if (current instanceof ControlUsageNode) {
countControl();
}
loopStack.push(current);
handler.loopBegin(current.getLink());
}
correctSegment = segment = startLoop(current);
if (current.exceedsMaximumUsage(SEGMENT_VERSION)) {
handleMissingMandatory(handler);
handler.segmentError(tag, current.getLink(), LOOP_OCCURS_OVER_MAXIMUM_TIMES);
}
if (implUnusedSegment) {
handleMissingMandatory(handler);
handler.segmentError(segment.getId(), segment.getLink(), IMPLEMENTATION_UNUSED_SEGMENT_PRESENT);
}
return true;
}
boolean handleLoopEnd(UsageCursor cursor, UsageCursor startLoop, CharSequence tag, int startDepth, ValidationEventHandler handler) {
boolean handled;
if (depth > 1) {
// Determine if the segment is in a loop higher in the tree
cursor.nagivateUp(this.depth);
this.depth--;
handled = false;
} else {
// End of the loop - check if the segment appears earlier in the loop
handled = checkPeerSegments(tag, startLoop.standard, handler);
if (handled) {
// Found the segment among the last known segment's peers so reset the depth
this.depth = startDepth;
} else {
// Determine if the segment is in the transaction whatsoever
cursor.reset(this.root, this.implRoot);
handled = checkUnexpectedSegment(tag, cursor.standard, startDepth, handler);
}
}
return handled;
}
boolean checkPeerSegments(CharSequence tag, UsageNode current, ValidationEventHandler handler) {
boolean handled = false;
if (current != correctSegment) {
/*
* End of the loop; try to see if we can find the segment among
* the siblings of the last good segment. If the last good
* segment was the final segment of the loop, do not search
* here. Rather, go up a level and continue searching from
* there.
*/
UsageNode next = current.getSiblingById(tag);
if (next != null && !next.isFirstChild()) {
useErrors.clear();
handler.segmentError(next.getId(), next.getLink(), SEGMENT_NOT_IN_PROPER_SEQUENCE);
next.incrementUsage();
next.resetChildren();
if (next.exceedsMaximumUsage(SEGMENT_VERSION)) {
handler.segmentError(next.getId(), next.getLink(), SEGMENT_EXCEEDS_MAXIMUM_USE);
}
segment = next;
handled = true;
}
}
return handled;
}
boolean checkUnexpectedSegment(CharSequence tag, UsageNode current, int startDepth, ValidationEventHandler handler) {
boolean handled = false;
if (!current.getId().contentEquals(tag)) {
final String tagString = tag.toString();
if (containerSchema != null && containerSchema.containsSegment(tagString)) {
// The segment is defined in the containing schema.
// Complete any open loops (handling missing mandatory at each level).
completeLoops(handler, startDepth);
// Handle any remaining missing mandatory segments
handleMissingMandatory(handler);
} else {
// Unexpected segment... must reset our position!
segmentExpected = false;
this.depth = startDepth;
useErrors.clear();
if (schema.containsSegment(tagString)) {
handler.segmentError(tag, null, UNEXPECTED_SEGMENT);
} else {
handler.segmentError(tag, null, SEGMENT_NOT_IN_DEFINED_TRANSACTION_SET);
}
}
handled = true; // Wasn't found or it's in the control schema; cut our losses and go back.
}
return handled;
}
private void handleMissingMandatory(ValidationEventHandler handler) {
for (UsageError error : useErrors) {
error.handleSegmentError(handler);
}
useErrors.clear();
}
private void handleMissingMandatory(ValidationEventHandler handler, int depth) {
Iterator<UsageError> errors = useErrors.iterator();
while (errors.hasNext()) {
UsageError e = errors.next();
if (e.isDepthGreaterThan(depth)) {
e.handleSegmentError(handler);
errors.remove();
}
}
}
public void clearImplementationCandidates(ValidationEventHandler handler) {
if (!implSegmentCandidates.isEmpty()) {
handler.segmentError(segment.getId(), segment.getLink(), IMPLEMENTATION_UNUSED_SEGMENT_PRESENT);
implSegmentCandidates.clear();
}
}
public boolean selectImplementation(Deque<StreamEvent> eventQueue, ValidationEventHandler handler) {
StreamEvent currentEvent = eventQueue.getLast();
if (currentEvent.getType() != EDIStreamEvent.ELEMENT_DATA) {
return false;
}
for (UsageNode candidate : implSegmentCandidates) {
PolymorphicImplementation implType;
UsageNode implSeg = toSegment(candidate);
implType = (PolymorphicImplementation) candidate.getLink();
if (isMatch(implType, currentEvent)) {
handleImplementationSelected(candidate, implSeg, handler);
if (implNode.isFirstChild()) {
//start of loop, update the loop, segment, and element references that were already reported
updateEventReferences(eventQueue, implType, implSeg.getLink());
// Replace the standard loop with the implementation on the stack
loopStack.pop();
loopStack.push(implNode.getParent());
} else {
//update segment and element references that were already reported
updateEventReferences(eventQueue, null, implSeg.getLink());
}
return true;
}
}
return false;
}
void handleImplementationSelected(UsageNode candidate, UsageNode implSeg, ValidationEventHandler handler) {
implSegmentCandidates.clear();
implNode = implSeg;
implSegmentSelected = true;
/*
* NOTE: Validation of prior implementation elements will occur only occur
* for prior simple elements and composites (not prior components in the same
* composite when the discriminator is a component element and the position
* within the composite is > 1).
*/
if (this.isComposite()) {
this.implComposite = implSeg.getChild(this.composite.getIndex());
this.implElement = this.implComposite.getChild(this.element.getIndex());
checkPreviousSiblings(implSeg, handler);
} else if (this.element != null) {
// Set implementation when standard element is already set (e.g. via discriminator)
this.implComposite = null;
this.implElement = implSeg.getChild(this.element.getIndex());
checkPreviousSiblings(implSeg, handler);
}
if (candidate.isNodeType(Type.LOOP)) {
candidate.incrementUsage();
candidate.resetChildren();
implSeg.incrementUsage();
if (candidate.exceedsMaximumUsage(SEGMENT_VERSION)) {
handler.segmentError(implSeg.getId(), candidate.getLink(), LOOP_OCCURS_OVER_MAXIMUM_TIMES);
}
} else {
candidate.incrementUsage();
if (candidate.exceedsMaximumUsage(SEGMENT_VERSION)) {
handler.segmentError(implSeg.getId(), implSeg.getLink(), SEGMENT_EXCEEDS_MAXIMUM_USE);
}
}
}
/**
* Validate any implementation elements previously skipped while searching
* for the loop discriminator element. Validation of enumerated values specified
* by the implementation schema are currently not supported for elements occurring
* prior to the discriminator element.
*
* @param implSeg selected implementation segment
* @param handler validation handler
*/
void checkPreviousSiblings(UsageNode implSeg, ValidationEventHandler handler) {
for (RevalidationNode entry : this.revalidationQueue) {
UsageNode std = entry.standard;
UsageNode impl = implSeg.getChild(std.getIndex());
validateImplRepetitions(null, impl);
if (std.isUsed()) {
validateImplUnusedElementBlank(std, impl, true);
} else {
validateDataElementRequirement(null, std, impl, entry.location);
}
handleRevalidatedElementErrors(entry, elementErrors, handler);
}
revalidationQueue.clear();
}
boolean isMatch(PolymorphicImplementation implType, StreamEvent currentEvent) {
Discriminator discr = implType.getDiscriminator();
// If no discriminator, matches by default
if (discr == null) {
return true;
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | true |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/FirstOnlySyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/FirstOnlySyntaxValidator.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class FirstOnlySyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.anchorPresent && status.elementCount > 1) {
signalExclusionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/NumericValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/NumericValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import java.util.List;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.stream.EDIStreamValidationError;
class NumericValidator extends ElementValidator {
@Override
void validate(Dialect dialect, EDISimpleType element, CharSequence value, List<EDIStreamValidationError> errors) {
int length = validate(dialect, value);
validateLength(dialect, element, Math.abs(length), errors);
if (length < 0) {
errors.add(EDIStreamValidationError.INVALID_CHARACTER_DATA);
}
}
@Override
void format(Dialect dialect, EDISimpleType element, CharSequence value, StringBuilder result) {
int length = validate(dialect, value);
for (long i = length, min = element.getMinLength(); i < min; i++) {
result.append('0');
}
result.append(value);
}
/**
* Validate that the value contains only characters the represent an
* integer.
*
* @param dialect the dialect currently be parsed
* @param value the sequence of characters to validate
* @return true of the value is a valid integer representation, otherwise false
*/
int validate(Dialect dialect, CharSequence value) {
int length = value.length();
boolean invalid = false;
for (int i = 0, m = length; i < m; i++) {
switch (value.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
case '-':
length--;
if (i > 0) {
invalid = true;
}
break;
default:
invalid = true;
break;
}
}
return invalid ? -length : length;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/ElementValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/ElementValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.stream.EDIStreamValidationError;
abstract class ElementValidator {
static class ValidatorInstances {
static final Map<EDISimpleType.Base, ElementValidator> instances = new EnumMap<>(EDISimpleType.Base.class);
static {
instances.put(EDISimpleType.Base.IDENTIFIER, new AlphaNumericValidator());
instances.put(EDISimpleType.Base.STRING, new AlphaNumericValidator());
instances.put(EDISimpleType.Base.NUMERIC, new NumericValidator());
instances.put(EDISimpleType.Base.DECIMAL, new DecimalValidator());
instances.put(EDISimpleType.Base.DATE, new DateValidator());
instances.put(EDISimpleType.Base.TIME, new TimeValidator());
}
private ValidatorInstances() {
}
}
static ElementValidator getInstance(EDISimpleType.Base type) {
return ValidatorInstances.instances.get(type);
}
protected static boolean validateLength(Dialect dialect,
EDISimpleType element,
int length,
List<EDIStreamValidationError> errors) {
final String version = dialect.getTransactionVersionString();
if (length > element.getMaxLength(version)) {
errors.add(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG);
return false;
} else if (length < element.getMinLength(version)) {
errors.add(EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT);
return false;
}
return true;
}
abstract void validate(Dialect dialect,
EDISimpleType element,
CharSequence value,
List<EDIStreamValidationError> errors);
abstract void format(Dialect dialect,
EDISimpleType element,
CharSequence value,
StringBuilder result);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/SyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/SyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import static io.xlate.edi.stream.EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR;
import static io.xlate.edi.stream.EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING;
import static io.xlate.edi.stream.EDIStreamValidationError.CONDITIONAL_REQUIRED_SEGMENT_MISSING;
import static io.xlate.edi.stream.EDIStreamValidationError.EXCLUSION_CONDITION_VIOLATED;
import static io.xlate.edi.stream.EDIStreamValidationError.SEGMENT_EXCLUSION_CONDITION_VIOLATED;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.stream.EDIStreamValidationError;
interface SyntaxValidator {
static class ValidatorInstances {
static final Map<EDISyntaxRule.Type, SyntaxValidator> instances = new EnumMap<>(EDISyntaxRule.Type.class);
static {
instances.put(EDISyntaxRule.Type.CONDITIONAL, new ConditionSyntaxValidator());
instances.put(EDISyntaxRule.Type.EXCLUSION, new ExclusionSyntaxValidator());
instances.put(EDISyntaxRule.Type.FIRSTONLY, new FirstOnlySyntaxValidator());
instances.put(EDISyntaxRule.Type.LIST, new ListSyntaxValidator());
instances.put(EDISyntaxRule.Type.PAIRED, new PairedSyntaxValidator());
instances.put(EDISyntaxRule.Type.REQUIRED, new RequiredSyntaxValidator());
instances.put(EDISyntaxRule.Type.SINGLE, new SingleSyntaxValidator());
}
private ValidatorInstances() {
}
}
static SyntaxValidator getInstance(EDISyntaxRule.Type type) {
return ValidatorInstances.instances.get(type);
}
static class SyntaxStatus {
protected int elementCount = 0;
protected boolean anchorPresent = false;
}
default SyntaxStatus scanSyntax(EDISyntaxRule syntax, List<UsageNode> children) {
final SyntaxStatus status = new SyntaxStatus();
final AtomicBoolean anchorPosition = new AtomicBoolean(true);
syntax.getPositions()
.stream()
.filter(position -> position < children.size() + 1)
.map(position -> children.get(position - 1))
.forEach(node -> {
if (node.isUsed()) {
status.elementCount++;
if (anchorPosition.get()) {
status.anchorPresent = true;
}
}
anchorPosition.set(false);
});
return status;
}
default void signalConditionError(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler) {
final List<UsageNode> children = structure.getChildren();
final int limit = children.size() + 1;
for (int position : syntax.getPositions()) {
final boolean used;
EDIReference typeReference;
if (position < limit) {
UsageNode node = children.get(position - 1);
used = node.isUsed();
typeReference = node.getLink();
} else {
used = false;
typeReference = null;
}
if (!used) {
if (structure.isNodeType(EDIType.Type.SEGMENT, EDIType.Type.COMPOSITE)) {
signalElementError(structure, typeReference, position, CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING, handler);
} else if (typeReference != null) {
signalSegmentError(typeReference, CONDITIONAL_REQUIRED_SEGMENT_MISSING, handler);
}
}
}
}
default void signalExclusionError(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler) {
final List<UsageNode> children = structure.getChildren();
final int limit = children.size() + 1;
int tally = 0;
for (int position : syntax.getPositions()) {
if (position < limit
&& children.get(position - 1).isUsed()
&& ++tally > 1) {
EDIReference typeReference = children.get(position - 1).getLink();
if (structure.isNodeType(EDIType.Type.SEGMENT, EDIType.Type.COMPOSITE)) {
signalElementError(structure, typeReference, position, EXCLUSION_CONDITION_VIOLATED, handler);
} else {
signalSegmentError(typeReference, SEGMENT_EXCLUSION_CONDITION_VIOLATED, handler);
}
}
}
}
static void signalElementError(UsageNode structure,
EDIReference typeReference,
int position,
EDIStreamValidationError error,
ValidationEventHandler handler) {
final int element = getElementPosition(structure, position);
final int component = getComponentPosition(structure, position);
handler.elementError(ELEMENT_OCCURRENCE_ERROR, error, typeReference, null, element, component, -1);
}
static void signalSegmentError(EDIReference typeReference, EDIStreamValidationError error, ValidationEventHandler handler) {
EDIType type = typeReference.getReferencedType();
if (!type.isType(EDIType.Type.SEGMENT)) {
// Error is reported on the first sub-reference of a loop
typeReference = ((EDIComplexType) type).getReferences().get(0);
type = typeReference.getReferencedType();
}
handler.segmentError(type.getId(), typeReference, error);
}
static int getComponentPosition(UsageNode structure, int position) {
return structure.isNodeType(EDIType.Type.COMPOSITE) ? position : -1;
}
static int getElementPosition(UsageNode structure, int position) {
if (structure.isNodeType(EDIType.Type.COMPOSITE)) {
return structure.getIndex() + 1;
}
return position;
}
default void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler) {
validate(syntax, structure, handler, scanSyntax(syntax, structure.getChildren()));
}
void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/ExclusionSyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/ExclusionSyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class ExclusionSyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.elementCount > 1) {
signalExclusionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/ControlUsageNode.java | src/main/java/io/xlate/edi/internal/stream/validation/ControlUsageNode.java | package io.xlate.edi.internal.stream.validation;
import java.util.List;
import java.util.logging.Logger;
import io.xlate.edi.schema.EDIControlType;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.stream.EDIStreamValidationError;
import io.xlate.edi.stream.Location;
class ControlUsageNode extends UsageNode {
static final Logger LOGGER = Logger.getLogger(ControlUsageNode.class.getName());
String referenceValue;
EDIControlType type;
int count;
ControlUsageNode(UsageNode parent, int depth, EDIReference link, int siblingIndex) {
super(parent, depth, link, siblingIndex);
type = (EDIControlType) link.getReferencedType();
}
@Override
void reset() {
super.reset();
this.referenceValue = null;
this.count = 0;
}
@Override
void incrementUsage() {
super.incrementUsage();
this.referenceValue = null;
this.count = 0;
}
boolean matchesLocation(int segmentRef, EDIElementPosition position, Location location) {
return position != null
&& position.matchesLocation(location)
&& type.getReferences().get(segmentRef).getReferencedType().getId().equals(location.getSegmentTag());
}
void validateReference(Location location, CharSequence value, List<EDIStreamValidationError> errors) {
if (referenceValue == null) {
if (matchesLocation(0, type.getHeaderRefPosition(), location)) {
this.referenceValue = value.toString();
}
return;
}
if (matchesLocation(type.getReferences().size() - 1, type.getTrailerRefPosition(), location)
&& !referenceValue.contentEquals(value)) {
errors.add(EDIStreamValidationError.CONTROL_REFERENCE_MISMATCH);
}
}
void validateCount(Location location, CharSequence value, List<EDIStreamValidationError> errors) {
if (matchesLocation(type.getReferences().size() - 1, type.getTrailerCountPosition(), location)
// Don't bother comparing the actual value if it's not formatted correctly
&& !errors.contains(EDIStreamValidationError.INVALID_CHARACTER_DATA)
&& !countEqualsActual(value)) {
errors.add(EDIStreamValidationError.CONTROL_COUNT_DOES_NOT_MATCH_ACTUAL_COUNT);
}
}
/**
* Check whether the actual number counted matches the count given by the
* input. Leading zeros are stripped from the input string.
*/
boolean countEqualsActual(CharSequence value) {
int i = 0;
int len = value.length();
int max = len - 1;
while (i < max && value.charAt(i) == '0') {
i++;
}
return Integer.toString(count).contentEquals(value.subSequence(i, len));
}
int incrementCount(EDIControlType.Type countType) {
if (this.type.getCountType() == countType) {
count++;
return count;
}
return 0;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/AlphaNumericValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/AlphaNumericValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import java.util.List;
import java.util.Set;
import io.xlate.edi.internal.stream.tokenization.CharacterSet;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.stream.EDIStreamValidationError;
class AlphaNumericValidator extends ElementValidator {
@Override
void validate(Dialect dialect,
EDISimpleType element,
CharSequence value,
List<EDIStreamValidationError> errors) {
int length = value.length();
validateLength(dialect, element, length, errors);
Set<String> valueSet = element.getValueSet(dialect.getTransactionVersionString());
if (!valueSet.isEmpty() && !valueSet.contains(value.toString())) {
errors.add(EDIStreamValidationError.INVALID_CODE_VALUE);
} else {
for (int i = 0; i < length; i++) {
char character = value.charAt(i);
if (!CharacterSet.isValid(character)) {
errors.add(EDIStreamValidationError.INVALID_CHARACTER_DATA);
break;
}
}
}
}
@Override
void format(Dialect dialect, EDISimpleType element, CharSequence value, StringBuilder result) {
int length = value.length();
for (int i = 0; i < length; i++) {
result.append(value.charAt(i));
}
for (long i = length, min = element.getMinLength(); i < min; i++) {
result.append(' ');
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/UsageError.java | src/main/java/io/xlate/edi/internal/stream/validation/UsageError.java | package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.stream.EDIStreamValidationError;
public class UsageError {
final EDIReference typeReference;
final EDIStreamValidationError error;
final int depth;
UsageError(EDIReference typeReference, EDIStreamValidationError error, int depth) {
super();
this.typeReference = typeReference;
this.error = error;
this.depth = depth;
}
UsageError(EDIStreamValidationError error) {
super();
this.error = error;
this.typeReference = null;
this.depth = -1;
}
UsageError(UsageNode node, EDIStreamValidationError error) {
super();
this.typeReference = node.getLink();
this.depth = node.getDepth();
this.error = error;
}
boolean isDepthGreaterThan(int depth) {
return this.depth > depth;
}
void handleSegmentError(ValidationEventHandler handler) {
handler.segmentError(typeReference.getReferencedType().getId(), typeReference, error);
}
public EDIReference getTypeReference() {
return typeReference;
}
public EDIStreamValidationError getError() {
return error;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/RequiredSyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/RequiredSyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class RequiredSyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.elementCount < 1) {
signalConditionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/UsageNode.java | src/main/java/io/xlate/edi/internal/stream/validation/UsageNode.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.stream.EDIStreamValidationError;
class UsageNode {
private static final String TOSTRING_FORMAT = "usageCount: %d, depth: %d, link: { %s }";
private final UsageNode parent;
private final int depth;
private final EDIReference link;
private final int siblingIndex;
private final ElementValidator validator;
private final List<UsageNode> children = new ArrayList<>();
private int usageCount;
UsageNode(UsageNode parent, int depth, EDIReference link, int siblingIndex) {
Objects.requireNonNull(link, "link");
this.parent = parent;
this.depth = depth;
this.link = link;
EDIType referencedType = link.getReferencedType();
if (referencedType instanceof EDISimpleType) {
final EDISimpleType simple = (EDISimpleType) referencedType;
this.validator = ElementValidator.getInstance(simple.getBase());
} else {
this.validator = null;
}
this.siblingIndex = siblingIndex;
}
public static boolean hasMinimumUsage(String version, UsageNode node) {
return node == null || node.hasMinimumUsage(version);
}
public static UsageNode getFirstChild(UsageNode node) {
return node != null ? node.getFirstChild() : null;
}
static <I, T, R> R withTypeOrElseGet(I reference, Class<T> type, Function<T, R> mapper, Supplier<R> defaultValue) {
if (type.isInstance(reference)) {
return mapper.apply(type.cast(reference));
}
return defaultValue.get();
}
public UsageNode getFirstSiblingSameType() {
EDIType type = getReferencedType();
UsageNode sibling = getFirstSibling();
while (!type.equals(sibling.getReferencedType())) {
sibling = sibling.getNextSibling();
}
return sibling;
}
public static void resetChildren(UsageNode... nodes) {
for (UsageNode node : nodes) {
if (node != null) {
node.resetChildren();
}
}
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, usageCount, depth, link);
}
UsageNode getParent() {
return parent;
}
int getDepth() {
return depth;
}
EDIReference getLink() {
return link;
}
EDIType getReferencedType() {
return link.getReferencedType();
}
List<UsageNode> getChildren() {
return children;
}
UsageNode getChild(int index) {
return (index < children.size()) ? children.get(index) : null;
}
List<UsageNode> getChildren(String version) {
return children.stream().filter(c -> c == null || c.link.getMaxOccurs(version) > 0).collect(Collectors.toList());
}
UsageNode getChild(String version, int index) {
final List<UsageNode> versionedChildren = getChildren(version);
return (index < versionedChildren.size()) ? versionedChildren.get(index) : null;
}
boolean isImplementation() {
return (link instanceof EDITypeImplementation);
}
String getId() {
return withTypeOrElseGet(link, EDITypeImplementation.class, EDITypeImplementation::getId, link.getReferencedType()::getId);
}
EDISimpleType getSimpleType() {
return withTypeOrElseGet(link, EDISimpleType.class, EDISimpleType.class::cast, () -> (EDISimpleType) link.getReferencedType());
}
void validate(Dialect dialect, CharSequence value, List<EDIStreamValidationError> errors) {
validator.validate(dialect, getSimpleType(), value, errors);
}
void format(Dialect dialect, CharSequence value, StringBuilder result) {
validator.format(dialect, getSimpleType(), value, result);
}
List<EDISyntaxRule> getSyntaxRules() {
EDIType referencedNode = link.getReferencedType();
return withTypeOrElseGet(referencedNode, EDIComplexType.class, EDIComplexType::getSyntaxRules, Collections::emptyList);
}
int getIndex() {
return siblingIndex;
}
void incrementUsage() {
usageCount++;
}
boolean isUsed() {
return usageCount > 0;
}
boolean isFirstChild() {
return this == getFirstSibling();
}
boolean hasMinimumUsage(String version) {
return usageCount >= link.getMinOccurs(version);
}
boolean hasVersions() {
return getSimpleType().hasVersions();
}
boolean exceedsMaximumUsage(String version) {
return usageCount > link.getMaxOccurs(version);
}
boolean isNodeType(EDIType.Type... types) {
for (EDIType.Type type : types) {
if (link.getReferencedType().isType(type)) {
return true;
}
}
return false;
}
EDIType.Type getNodeType() {
return link.getReferencedType().getType();
}
void reset() {
usageCount = 0;
resetChildren();
}
void resetChildren() {
for (UsageNode node : children) {
if (node != null) {
node.reset();
}
}
}
private UsageNode getSibling(int index) {
return parent != null ? parent.getChild(index) : null;
}
UsageNode getFirstSibling() {
return getSibling(0);
}
UsageNode getNextSibling() {
return getSibling(siblingIndex + 1);
}
public UsageNode getFirstChild() {
return getChild(0);
}
private UsageNode getChildById(CharSequence id) {
for (UsageNode child : children) {
if (child.getId().contentEquals(id)) {
return child;
}
}
return null;
}
UsageNode getSiblingById(CharSequence id) {
return parent != null ? parent.getChildById(id) : null;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/DateValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/DateValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import java.time.LocalDate;
import java.util.List;
import io.xlate.edi.internal.stream.tokenization.Dialect;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.stream.EDIStreamValidationError;
class DateValidator extends ElementValidator {
@Override
void validate(Dialect dialect,
EDISimpleType element,
CharSequence value,
List<EDIStreamValidationError> errors) {
int length = value.length();
if (!validateLength(dialect, element, length, errors) || length % 2 != 0 || !validValue(value)) {
errors.add(EDIStreamValidationError.INVALID_DATE);
}
}
@Override
void format(Dialect dialect, EDISimpleType element, CharSequence value, StringBuilder result) {
result.append(value);
}
static boolean validValue(CharSequence value) {
int length = value.length();
int dateValue = 0;
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
dateValue = dateValue * 10 + Character.digit(c, 10);
break;
default:
return false;
}
}
int[] date = new int[3];
date[2] = dateValue % 100;
dateValue /= 100;
date[1] = dateValue % 100;
dateValue /= 100;
date[0] = dateValue;
/*-
* Add the century if the date is missing it - assume all dates
* are current year or in the past.
**/
if (length == 6) {
int year = LocalDate.now().getYear();
int century = year / 100;
if (date[0] > (year % 100)) {
date[0] = (century - 1) * 100 + date[0];
} else {
date[0] = century * 100 + date[0];
}
}
return dateIsValid(date[0], date[1], date[2]);
}
static boolean dateIsValid(int year, int month, int day) {
if (day < 1) {
return false;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return day <= 31;
case 4:
case 6:
case 9:
case 11:
return day <= 30;
case 2:
return day <= 28 || (isLeapYear(year) && day <= 29);
default:
return false;
}
}
static boolean isLeapYear(int year) {
return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/ConditionSyntaxValidator.java | src/main/java/io/xlate/edi/internal/stream/validation/ConditionSyntaxValidator.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.validation;
import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler;
import io.xlate.edi.schema.EDISyntaxRule;
class ConditionSyntaxValidator implements SyntaxValidator {
@Override
public void validate(EDISyntaxRule syntax, UsageNode structure, ValidationEventHandler handler, SyntaxStatus status) {
if (status.anchorPresent && status.elementCount < syntax.getPositions().size()) {
signalConditionError(syntax, structure, handler);
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/validation/ValidatorConfig.java | src/main/java/io/xlate/edi/internal/stream/validation/ValidatorConfig.java | package io.xlate.edi.internal.stream.validation;
public interface ValidatorConfig {
boolean validateControlCodeValues();
boolean formatElements();
boolean trimDiscriminatorValues();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/json/JsonParserFactory.java | src/main/java/io/xlate/edi/internal/stream/json/JsonParserFactory.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.json;
import java.util.Map;
import io.xlate.edi.stream.EDIStreamReader;
public final class JsonParserFactory {
private JsonParserFactory() {
}
@SuppressWarnings("unchecked")
public static <J> J createJsonParser(EDIStreamReader reader, Class<J> type, Map<String, Object> properties) {
final J parser;
switch (type.getName()) {
case "jakarta.json.stream.JsonParser":
parser = (J) new StaEDIJakartaJsonParser(reader, properties);
break;
case "javax.json.stream.JsonParser":
parser = (J) new StaEDIJavaxJsonParser(reader, properties);
break;
case "com.fasterxml.jackson.core.JsonParser":
parser = (J) new StaEDIJacksonJsonParser(reader, properties);
break;
default:
throw new IllegalArgumentException("Unsupported JSON parser type: " + type);
}
return parser;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/json/StaEDIJacksonJsonParser.java | src/main/java/io/xlate/edi/internal/stream/json/StaEDIJacksonJsonParser.java | package io.xlate.edi.internal.stream.json;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import com.fasterxml.jackson.core.Base64Variant;
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.core.base.ParserMinimalBase;
import com.fasterxml.jackson.core.io.ContentReference;
import io.xlate.edi.internal.stream.json.StaEDIJsonParser.Event;
import io.xlate.edi.stream.EDIStreamReader;
public class StaEDIJacksonJsonParser extends ParserMinimalBase {
private static final Version VERSION;
private static final BigDecimal MIN_LONG = BigDecimal.valueOf(Long.MIN_VALUE);
private static final BigDecimal MAX_LONG = BigDecimal.valueOf(Long.MAX_VALUE);
private static final BigDecimal MIN_INTEGER = BigDecimal.valueOf(Integer.MIN_VALUE);
private static final BigDecimal MAX_INTEGER = BigDecimal.valueOf(Integer.MAX_VALUE);
private static final BigDecimal MIN_DOUBLE = BigDecimal.valueOf(-Double.MAX_VALUE);
private static final BigDecimal MAX_DOUBLE = BigDecimal.valueOf(Double.MAX_VALUE);
private static final BigDecimal MIN_FLOAT = BigDecimal.valueOf(-Float.MAX_VALUE);
private static final BigDecimal MAX_FLOAT = BigDecimal.valueOf(Float.MAX_VALUE);
private StaEDIJsonParser<JsonParseException> parser;
private ObjectCodec codec;
private final Deque<StaEDIJsonStreamContext> context = new ArrayDeque<>();
private StaEDIJsonStreamContext pendingContext = null;
StaEDIJacksonJsonParser(EDIStreamReader ediReader, Map<String, Object> properties) {
super(JsonParser.Feature.collectDefaults(), StreamReadConstraints.defaults());
parser = new JacksonJsonParser(ediReader, properties);
context.addLast(new StaEDIJsonStreamContext(JsonStreamContext.TYPE_ROOT, null));
}
/* test */ boolean hasNext() throws IOException {
return parser.hasNext();
}
/* test */ JsonToken next() throws IOException {
return nextToken();
}
/* test */ String getString() throws IOException {
return getText();
}
/* test */ int getInt() {
return getIntValue();
}
/* test */ JsonLocation getLocation() {
return getTokenLocation();
}
@Override
public JsonToken nextToken() throws IOException {
if (!parser.hasNext()) {
return null;
}
if (pendingContext != null) {
context.add(pendingContext);
pendingContext = null;
}
final Event next = parser.nextEvent();
final JsonToken token;
switch (next) {
case END_ARRAY:
context.removeLast();
token = JsonToken.END_ARRAY;
break;
case END_OBJECT:
context.removeLast();
token = JsonToken.END_OBJECT;
break;
case KEY_NAME:
context.getLast().incrementIndex();
context.getLast().setCurrentName(getText());
token = JsonToken.FIELD_NAME;
break;
case START_ARRAY:
context.getLast().incrementIndexIfArray();
pendingContext = new StaEDIJsonStreamContext(JsonStreamContext.TYPE_ARRAY, context.getLast());
token = JsonToken.START_ARRAY;
break;
case START_OBJECT:
context.getLast().incrementIndexIfArray();
pendingContext = new StaEDIJsonStreamContext(JsonStreamContext.TYPE_OBJECT, context.getLast());
token = JsonToken.START_OBJECT;
break;
case VALUE_NULL:
context.getLast().incrementIndexIfArray();
token = JsonToken.VALUE_NULL;
break;
case VALUE_NUMBER:
context.getLast().incrementIndexIfArray();
if (parser.isIntegralNumber()) {
token = JsonToken.VALUE_NUMBER_INT;
} else {
token = JsonToken.VALUE_NUMBER_FLOAT;
}
break;
case VALUE_STRING:
context.getLast().incrementIndexIfArray();
token = JsonToken.VALUE_STRING;
break;
default:
throw new JsonParseException(this, StaEDIJsonParser.MSG_UNEXPECTED + next);
}
super._currToken = token;
return token;
}
@Override
public void close() throws IOException {
parser.close();
}
@Override
public String getText() throws IOException {
return parser.getString();
}
@Override
public char[] getTextCharacters() throws IOException {
return parser.ediReader.getTextCharacters();
}
@Override
public int getTextLength() throws IOException {
return parser.ediReader.getTextLength();
}
@Override
public int getTextOffset() throws IOException {
return parser.ediReader.getTextStart();
}
@Override
public BigInteger getBigIntegerValue() throws IOException {
return parser.getBigDecimal().toBigInteger();
}
@Override
public ObjectCodec getCodec() {
return this.codec;
}
@Override
public void setCodec(ObjectCodec c) {
this.codec = c;
}
@Override
public JsonLocation getCurrentLocation() {
return getTokenLocation();
}
@Override
public JsonLocation getTokenLocation() {
return new JacksonJsonLocation(parser.getStreamOffset(), parser.getLineNumber(), parser.getColumnNumber());
}
@Override
protected void _handleEOF() throws JsonParseException {
// Not supported, do nothing
}
@Override
public boolean isClosed() {
return parser.closed;
}
@Override
public JsonStreamContext getParsingContext() {
return context.getLast().deepCopy();
}
@Override
public String getCurrentName() throws IOException {
return context.getLast().getCurrentName();
}
@Override
public void overrideCurrentName(String name) {
// Not supported, do nothing
}
@Override
public boolean hasTextCharacters() {
switch (parser.currentEvent) {
case KEY_NAME:
case VALUE_STRING:
return true;
default:
return false;
}
}
@Override
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException {
return parser.currentBinaryValue.toByteArray();
}
@Override
public Version version() {
return VERSION;
}
static <T extends Number & Comparable<T>> boolean between(T value, T min, T max) {
return value.compareTo(min) >= 0 && value.compareTo(max) <= 0;
}
@Override
public Number getNumberValue() throws IOException {
if (parser.currentEvent != Event.VALUE_NUMBER) {
throw new JsonParseException(this, "Current token is not a number");
}
BigDecimal value = parser.getBigDecimal();
Number result;
switch (getNumberType()) {
case BIG_INTEGER:
result = value.toBigInteger();
break;
case DOUBLE:
result = value.doubleValue();
break;
case FLOAT:
result = value.floatValue();
break;
case INT:
result = value.intValue();
break;
case LONG:
result = value.longValue();
break;
default:
result = value;
break;
}
return result;
}
@Override
public NumberType getNumberType() throws IOException {
if (parser.currentEvent != Event.VALUE_NUMBER) {
return null;
}
BigDecimal value = parser.getBigDecimal();
NumberType type;
if (value.scale() == 0) {
if (between(value, MIN_INTEGER, MAX_INTEGER)) {
type = NumberType.INT;
} else if (between(value, MIN_LONG, MAX_LONG)) {
type = NumberType.LONG;
} else {
type = NumberType.BIG_INTEGER;
}
} else {
int exp = value.precision() - value.scale() - 1;
if (between(value, MIN_FLOAT, MAX_FLOAT)
&& between(exp, Float.MIN_EXPONENT, Float.MAX_EXPONENT)) {
type = NumberType.FLOAT;
} else if (between(value, MIN_DOUBLE, MAX_DOUBLE)
&& between(exp, Double.MIN_EXPONENT, Double.MAX_EXPONENT)) {
type = NumberType.DOUBLE;
} else {
type = NumberType.BIG_DECIMAL;
}
}
return type;
}
@Override
public int getIntValue() {
return parser.getInt();
}
@Override
public long getLongValue() {
return parser.getLong();
}
@Override
public float getFloatValue() {
return parser.getBigDecimal().floatValue();
}
@Override
public double getDoubleValue() {
return parser.getBigDecimal().doubleValue();
}
@Override
public BigDecimal getDecimalValue() throws IOException {
return parser.getBigDecimal();
}
class JacksonJsonParser extends StaEDIJsonParser<JsonParseException> {
JacksonJsonParser(EDIStreamReader ediReader, Map<String, Object> properties) {
super(ediReader, properties);
}
@Override
protected JsonParseException newJsonException(String message, Throwable cause) {
return new JsonParseException(StaEDIJacksonJsonParser.this, message, cause);
}
@Override
protected JsonParseException newJsonParsingException(String message, Throwable cause) {
return newJsonException(message, cause);
}
}
static class JacksonJsonLocation extends JsonLocation {
private static final long serialVersionUID = 1L;
public JacksonJsonLocation(long streamOffset, long lineNumber, long columnNumber) {
super(ContentReference.unknown(), streamOffset, (int) lineNumber, (int) columnNumber);
}
public long getStreamOffset() {
return _totalChars;
}
public long getLineNumber() {
return _lineNr;
}
public long getColumnNumber() {
return _columnNr;
}
}
static class StaEDIJsonStreamContext extends JsonStreamContext {
StaEDIJsonStreamContext parent;
String name;
StaEDIJsonStreamContext(int type, StaEDIJsonStreamContext parent) {
super(type, -1);
this.parent = parent;
}
StaEDIJsonStreamContext(StaEDIJsonStreamContext source) {
super(source);
this.parent = source.parent != null ? source.parent.deepCopy() : null;
this.name = source.name;
}
void incrementIndexIfArray() {
if (inArray()) {
incrementIndex();
}
}
void incrementIndex() {
this._index++;
}
@Override
public JsonStreamContext getParent() {
return parent;
}
@Override
public String getCurrentName() {
return name;
}
public void setCurrentName(String name) {
this.name = name;
}
public StaEDIJsonStreamContext deepCopy() {
return new StaEDIJsonStreamContext(this);
}
}
static {
VERSION = Optional.ofNullable(StaEDIJacksonJsonParser.class.getResourceAsStream("/io/xlate/edi/internal/project.properties"))
.map(stream -> {
try (InputStream source = stream) {
Properties projectProperties = new Properties();
projectProperties.load(source);
return projectProperties;
} catch (IOException e) {
return null;
}
})
.map(StaEDIJacksonJsonParser::toVersion)
.orElseGet(Version::unknownVersion);
}
static Version toVersion(Properties projectProperties) {
String[] version = projectProperties.getProperty("version").split("[.-]");
return new Version(
Integer.parseInt(version[0]),
Integer.parseInt(version[1]),
Integer.parseInt(version[2]),
version.length > 3 ? version[3] : null,
projectProperties.getProperty("groupId"),
projectProperties.getProperty("artifactId"));
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/json/StaEDIJakartaJsonParser.java | src/main/java/io/xlate/edi/internal/stream/json/StaEDIJakartaJsonParser.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.json;
import java.util.Map;
import io.xlate.edi.stream.EDIStreamReader;
final class StaEDIJakartaJsonParser extends StaEDIJsonParser<jakarta.json.JsonException>
implements jakarta.json.stream.JsonParser, jakarta.json.stream.JsonLocation {
static final jakarta.json.stream.JsonParser.Event[] eventMap = mapEvents(jakarta.json.stream.JsonParser.Event.class);
static final jakarta.json.spi.JsonProvider jsonProvider = jakarta.json.spi.JsonProvider.provider();
StaEDIJakartaJsonParser(EDIStreamReader ediReader, Map<String, Object> properties) {
super(ediReader, properties);
}
@Override
protected jakarta.json.JsonException newJsonException(String message, Throwable cause) {
return new jakarta.json.JsonException(message, cause);
}
@Override
protected jakarta.json.JsonException newJsonParsingException(String message, Throwable cause) {
return new jakarta.json.stream.JsonParsingException(message, cause, this);
}
@Override
public jakarta.json.stream.JsonLocation getLocation() {
return this;
}
@Override
public jakarta.json.stream.JsonParser.Event next() {
return eventMap[nextEvent().ordinal()];
}
@Override
public jakarta.json.JsonValue getValue() {
assertEventSet("getValue illegal when data stream has not yet been read");
switch (currentEvent) {
case START_OBJECT:
return getObject();
case START_ARRAY:
return getArray();
case VALUE_NULL:
return jakarta.json.JsonValue.NULL;
case VALUE_NUMBER:
return isIntegralNumber() ?
jsonProvider.createValue(getLong()) :
jsonProvider.createValue(getBigDecimal());
case VALUE_STRING:
case KEY_NAME:
return jsonProvider.createValue(getString());
default:
throw new IllegalStateException("getValue illegal when at current position");
}
}
@Override
public jakarta.json.JsonArray getArray() {
assertEvent(StaEDIJsonParser.Event.START_ARRAY, current -> "getArray illegal when not at start of array");
jakarta.json.JsonArrayBuilder builder = jsonProvider.createArrayBuilder();
while (nextEvent() != StaEDIJsonParser.Event.END_ARRAY) {
builder.add(getValue());
}
return builder.build();
}
@Override
public jakarta.json.JsonObject getObject() {
assertEvent(StaEDIJsonParser.Event.START_OBJECT, current -> "getObject illegal when not at start of object");
jakarta.json.JsonObjectBuilder builder = jsonProvider.createObjectBuilder();
StaEDIJsonParser.Event next;
String key = null;
while ((next = nextEvent()) != StaEDIJsonParser.Event.END_OBJECT) {
if (next == StaEDIJsonParser.Event.KEY_NAME) {
key = getString();
} else {
builder.add(key, getValue());
}
}
return builder.build();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/json/StaEDIJsonParser.java | src/main/java/io/xlate/edi/internal/stream/json/StaEDIJsonParser.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.ArrayDeque;
import java.util.Base64;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.xlate.edi.internal.stream.Configurable;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.schema.EDISimpleType.Base;
import io.xlate.edi.stream.EDIInputFactory;
import io.xlate.edi.stream.EDIStreamEvent;
import io.xlate.edi.stream.EDIStreamReader;
import io.xlate.edi.stream.EDIValidationException;
abstract class StaEDIJsonParser<E extends Exception> implements Configurable {
private static final Logger LOGGER = Logger.getLogger(StaEDIJsonParser.class.getName());
static final String MSG_EXCEPTION = "Exception reading the EDI stream as JSON";
static final String MSG_UNEXPECTED = "Unexpected event reached parsing JSON: ";
static final String KEY_TYPE = "type";
static final String KEY_NAME = "name";
static final String KEY_META = "meta";
static final String KEY_DATA = "data";
protected final EDIStreamReader ediReader;
protected final Map<String, Object> properties;
protected final boolean emptyElementsNull;
protected final boolean elementsAsObject;
final Queue<Event> eventQueue = new ArrayDeque<>();
final Queue<String> valueQueue = new ArrayDeque<>();
final DecimalFormat decimalParser = new DecimalFormat();
final ParsePosition decimalPosition = new ParsePosition(0);
Event currentEvent;
String currentValue;
ByteArrayOutputStream currentBinaryValue = new ByteArrayOutputStream();
BigDecimal currentNumber;
boolean closed = false;
enum Event {
/**
* @see jakarta.json.stream.JsonParser.Event#START_ARRAY
*/
START_ARRAY,
/**
* @see jakarta.json.stream.JsonParser.Event#START_OBJECT
*/
START_OBJECT,
/**
* @see jakarta.json.stream.JsonParser.Event#KEY_NAME
*/
KEY_NAME,
/**
* @see jakarta.json.stream.JsonParser.Event#VALUE_STRING
*/
VALUE_STRING,
/**
* @see jakarta.json.stream.JsonParser.Event#VALUE_NUMBER
*/
VALUE_NUMBER,
/**
* @see jakarta.json.stream.JsonParser.Event#VALUE_NULL
*/
VALUE_NULL,
/**
* @see jakarta.json.stream.JsonParser.Event#END_OBJECT
*/
END_OBJECT,
/**
* @see jakarta.json.stream.JsonParser.Event#END_ARRAY
*/
END_ARRAY
}
StaEDIJsonParser(EDIStreamReader ediReader, Map<String, Object> properties) {
super();
this.ediReader = ediReader;
this.properties = properties;
this.emptyElementsNull = getProperty(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, Boolean::parseBoolean, false);
this.elementsAsObject = getProperty(EDIInputFactory.JSON_OBJECT_ELEMENTS, Boolean::parseBoolean, false);
}
@SuppressWarnings("unchecked")
static <E extends Enum<E>> E[] mapEvents(Class<E> eventType) {
Map<String, Integer> ordinals = Stream.of(Event.values()).collect(Collectors.toMap(Enum::name, Enum::ordinal));
ToIntFunction<E> ordinal = e -> ordinals.get(e.name());
return Stream.of(eventType.getEnumConstants())
.filter(c -> ordinals.containsKey(c.name()))
.sorted((c1, c2) -> Integer.compare(ordinal.applyAsInt(c1), ordinal.applyAsInt(c2)))
.map(eventType::cast)
.toArray(size -> (E[]) Array.newInstance(eventType, size));
}
protected abstract E newJsonException(String message, Throwable cause);
protected abstract E newJsonParsingException(String message, Throwable cause);
@Override
public Object getProperty(String name) {
return properties.get(name);
}
<T> T executeWithReader(Callable<T> runner) throws E {
try {
return runner.call();
} catch (Exception e) {
if (e.getCause() instanceof IOException) {
throw newJsonException(MSG_EXCEPTION, e);
} else {
throw newJsonParsingException(MSG_EXCEPTION, e);
}
}
}
void advanceEvent() {
currentEvent = eventQueue.remove();
currentValue = valueQueue.remove();
}
void parseNumber(EDISimpleType elementType, String text) {
if (elementType.getBase() == Base.NUMERIC) {
final Integer scale = elementType.getScale();
try {
final long unscaled = Long.parseLong(text);
this.currentNumber = BigDecimal.valueOf(unscaled, scale);
} catch (NumberFormatException e) {
final BigInteger unscaled = new BigInteger(text);
this.currentNumber = new BigDecimal(unscaled, scale);
}
} else {
decimalPosition.setIndex(0);
decimalParser.setParseBigDecimal(true);
this.currentNumber = (BigDecimal) decimalParser.parse(text, decimalPosition);
}
}
void enqueue(Event event, String value) {
eventQueue.add(event);
valueQueue.add(value != null ? value : "");
}
void enqueueStructureBegin(String typeName, String structureName) {
enqueue(Event.START_OBJECT, null);
enqueue(Event.KEY_NAME, KEY_NAME);
enqueue(Event.VALUE_STRING, structureName);
enqueue(Event.KEY_NAME, KEY_TYPE);
enqueue(Event.VALUE_STRING, typeName);
enqueue(Event.KEY_NAME, KEY_DATA);
enqueue(Event.START_ARRAY, null);
}
void readBinaryValue() throws E {
try (InputStream binaryStream = ediReader.getBinaryData()) {
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = binaryStream.read(buffer)) > -1) {
currentBinaryValue.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw newJsonException(MSG_EXCEPTION, e);
}
}
boolean isNumber(EDISimpleType elementType) {
return elementType.getBase() == Base.DECIMAL || elementType.getBase() == Base.NUMERIC;
}
void enqueueDataElement(boolean binaryData) throws E {
EDIReference referencedType = ediReader.getSchemaTypeReference();
EDISimpleType elementType = null;
if (referencedType != null) {
elementType = (EDISimpleType) referencedType.getReferencedType();
}
if (elementsAsObject) {
enqueue(Event.START_OBJECT, null);
enqueue(Event.KEY_NAME, KEY_TYPE);
enqueue(Event.VALUE_STRING, "element");
enqueue(Event.KEY_NAME, KEY_DATA);
}
final Event dataEvent;
final String dataText = ediReader.hasText() ? ediReader.getText() : "";
if (elementType == null) {
dataEvent = Event.VALUE_STRING;
} else if (binaryData) {
readBinaryValue();
dataEvent = Event.VALUE_STRING;
} else if (dataText.isEmpty()) {
dataEvent = this.emptyElementsNull ? Event.VALUE_NULL : Event.VALUE_STRING;
} else if (isNumber(elementType)) {
Event numberEvent;
try {
parseNumber(elementType, dataText);
numberEvent = Event.VALUE_NUMBER;
} catch (Exception e) {
numberEvent = Event.VALUE_STRING;
}
dataEvent = numberEvent;
} else {
dataEvent = Event.VALUE_STRING;
}
enqueue(dataEvent, dataText);
if (elementsAsObject) {
enqueue(Event.END_OBJECT, null);
}
}
void enqueueEvent(EDIStreamEvent ediEvent) throws E {
LOGGER.finer(() -> "Enqueue EDI event: " + ediEvent);
currentNumber = null;
currentValue = null;
currentBinaryValue.reset();
switch (ediEvent) {
case ELEMENT_DATA:
enqueueDataElement(false);
break;
case ELEMENT_DATA_BINARY:
enqueueDataElement(true);
break;
case START_INTERCHANGE:
enqueueStructureBegin("loop", "INTERCHANGE");
break;
case START_GROUP:
case START_TRANSACTION:
case START_LOOP:
enqueueStructureBegin("loop", ediReader.getReferenceCode());
break;
case START_SEGMENT:
enqueueStructureBegin("segment", ediReader.getText());
break;
case START_COMPOSITE:
enqueueStructureBegin("composite", ediReader.getReferenceCode());
break;
case END_INTERCHANGE:
case END_GROUP:
case END_TRANSACTION:
case END_LOOP:
case END_SEGMENT:
case END_COMPOSITE:
enqueue(Event.END_ARRAY, null);
enqueue(Event.END_OBJECT, null);
break;
case SEGMENT_ERROR:
case ELEMENT_OCCURRENCE_ERROR:
case ELEMENT_DATA_ERROR:
Throwable cause = new EDIValidationException(ediEvent, ediReader.getErrorType(), ediReader.getLocation(), ediReader.getText());
throw newJsonParsingException("Unhandled EDI validation error", cause);
default:
throw new IllegalStateException("Unknown state: " + ediEvent);
}
}
Event nextEvent() throws E {
if (eventQueue.isEmpty()) {
LOGGER.finer(() -> "eventQueue is empty, calling ediReader.next()");
enqueueEvent(executeWithReader(ediReader::next));
}
advanceEvent();
return currentEvent;
}
/**
* @see jakarta.json.stream.JsonLocation#getLineNumber()
*/
public long getLineNumber() {
return ediReader.getLocation().getLineNumber();
}
/**
* @see jakarta.json.stream.JsonLocation#getColumnNumber()
*/
public long getColumnNumber() {
return ediReader.getLocation().getColumnNumber();
}
/**
* @see jakarta.json.stream.JsonLocation#getStreamOffset()
*/
public long getStreamOffset() {
return ediReader.getLocation().getCharacterOffset();
}
public void close() throws E {
try {
ediReader.close();
} catch (IOException e) {
throw newJsonException(MSG_EXCEPTION, e);
} finally {
closed = true;
}
}
void assertEventSet(String message) {
if (this.currentEvent == null) {
throw new IllegalStateException(message);
}
}
void assertEvent(Event required, Function<Event, String> message) {
final Event current = this.currentEvent;
if (current != required) {
throw new IllegalStateException(message.apply(current));
}
}
void assertEventValueNumber() {
assertEvent(Event.VALUE_NUMBER, current -> "Unable to get number value for event [" + current + ']');
}
void assertEventValueString() {
final Event current = this.currentEvent;
switch (current) {
case KEY_NAME:
case VALUE_STRING:
case VALUE_NUMBER:
break;
default:
throw new IllegalStateException("Unable to get string value for event [" + current + ']');
}
}
/**
* @see jakarta.json.stream.JsonParser#hasNext()
* @see javax.json.stream.JsonParser#hasNext()
*/
public boolean hasNext() throws E {
return !eventQueue.isEmpty() || executeWithReader(ediReader::hasNext);
}
/**
* @see jakarta.json.stream.JsonParser#getBigDecimal()
*/
public BigDecimal getBigDecimal() {
assertEventValueNumber();
return currentNumber;
}
/**
* @see jakarta.json.stream.JsonParser#getInt()
*/
public int getInt() {
return (int) getLong();
}
/**
* @see jakarta.json.stream.JsonParser#getLong()
*/
public long getLong() {
assertEventValueNumber();
return currentNumber.longValue();
}
/**
* @see jakarta.json.stream.JsonParser#getString()
*/
public String getString() {
assertEventValueString();
if (currentBinaryValue.size() > 0) {
return Base64.getEncoder().encodeToString(currentBinaryValue.toByteArray());
}
return this.currentValue;
}
/**
* @see jakarta.json.stream.JsonParser#isIntegralNumber()
*/
public boolean isIntegralNumber() {
assertEventValueNumber();
return currentNumber.scale() == 0;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/json/StaEDIJavaxJsonParser.java | src/main/java/io/xlate/edi/internal/stream/json/StaEDIJavaxJsonParser.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.stream.json;
import java.util.Map;
import io.xlate.edi.stream.EDIStreamReader;
final class StaEDIJavaxJsonParser extends StaEDIJsonParser<javax.json.JsonException>
implements javax.json.stream.JsonParser, javax.json.stream.JsonLocation {
static final javax.json.stream.JsonParser.Event[] eventMap = mapEvents(javax.json.stream.JsonParser.Event.class);
static final javax.json.spi.JsonProvider jsonProvider = javax.json.spi.JsonProvider.provider();
StaEDIJavaxJsonParser(EDIStreamReader ediReader, Map<String, Object> properties) {
super(ediReader, properties);
}
@Override
protected javax.json.JsonException newJsonException(String message, Throwable cause) {
return new javax.json.JsonException(message, cause);
}
@Override
protected javax.json.JsonException newJsonParsingException(String message, Throwable cause) {
return new javax.json.stream.JsonParsingException(message, cause, this);
}
@Override
public javax.json.stream.JsonLocation getLocation() {
return this;
}
@Override
public javax.json.stream.JsonParser.Event next() {
return eventMap[nextEvent().ordinal()];
}
@Override
public javax.json.JsonValue getValue() {
assertEventSet("getValue illegal when data stream has not yet been read");
switch (currentEvent) {
case START_OBJECT:
return getObject();
case START_ARRAY:
return getArray();
case VALUE_NULL:
return javax.json.JsonValue.NULL;
case VALUE_NUMBER:
return isIntegralNumber() ?
jsonProvider.createValue(getLong()) :
jsonProvider.createValue(getBigDecimal());
case VALUE_STRING:
case KEY_NAME:
return jsonProvider.createValue(getString());
default:
throw new IllegalStateException("getValue illegal when at current position");
}
}
@Override
public javax.json.JsonArray getArray() {
assertEvent(StaEDIJsonParser.Event.START_ARRAY, current -> "getArray illegal when not at start of array");
javax.json.JsonArrayBuilder builder = jsonProvider.createArrayBuilder();
while (nextEvent() != StaEDIJsonParser.Event.END_ARRAY) {
builder.add(getValue());
}
return builder.build();
}
@Override
public javax.json.JsonObject getObject() {
assertEvent(StaEDIJsonParser.Event.START_OBJECT, current -> "getObject illegal when not at start of object");
javax.json.JsonObjectBuilder builder = jsonProvider.createObjectBuilder();
StaEDIJsonParser.Event next;
String key = null;
while ((next = nextEvent()) != StaEDIJsonParser.Event.END_OBJECT) {
if (next == StaEDIJsonParser.Event.KEY_NAME) {
key = getString();
} else {
builder.add(key, getValue());
}
}
return builder.build();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SchemaReaderV2.java | src/main/java/io/xlate/edi/internal/schema/SchemaReaderV2.java | package io.xlate.edi.internal.schema;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.unexpectedElement;
import java.util.Map;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
class SchemaReaderV2 extends SchemaReaderBase implements SchemaReader {
public SchemaReaderV2(XMLStreamReader reader, Map<String, Object> properties) {
super(StaEDISchemaFactory.XMLNS_V2, reader, properties);
}
@Override
protected void readInclude(XMLStreamReader reader, Map<String, EDIType> types) throws EDISchemaException {
// Included schema not supported in V2 Schema
throw unexpectedElement(reader.getName(), reader);
}
@Override
protected void readImplementation(XMLStreamReader reader, Map<String, EDIType> types) {
// Implementations not supported in V2 Schema
}
@Override
protected String readReferencedId(XMLStreamReader reader) {
return reader.getAttributeValue(null, "ref");
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/LoopType.java | src/main/java/io/xlate/edi/internal/schema/LoopType.java | package io.xlate.edi.internal.schema;
import java.util.List;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDILoopType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
@SuppressWarnings("java:S2160") // Intentionally inherit 'equals' from superclass
class LoopType extends StructureType implements EDILoopType {
private final EDIElementPosition levelIdPosition;
private final EDIElementPosition parentIdPosition;
LoopType(String code,
List<EDIReference> references,
List<EDISyntaxRule> syntaxRules,
EDIElementPosition levelIdPosition,
EDIElementPosition parentIdPosition,
String title,
String description) {
super(code, EDIType.Type.LOOP, code, references, syntaxRules, title, description);
this.levelIdPosition = levelIdPosition;
this.parentIdPosition = parentIdPosition;
}
@Override
public EDIElementPosition getLevelIdPosition() {
return levelIdPosition;
}
@Override
public EDIElementPosition getParentIdPosition() {
return parentIdPosition;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/StaEDISchemaFactory.java | src/main/java/io/xlate/edi/internal/schema/StaEDISchemaFactory.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.schema.SchemaFactory;
public class StaEDISchemaFactory implements SchemaFactory {
static final Logger LOGGER = Logger.getLogger(StaEDISchemaFactory.class.getName());
static final XMLInputFactory FACTORY = XMLInputFactory.newInstance();
static final String SCHEMA_TAG = "schema";
static final String XMLNS_V2 = "http://xlate.io/EDISchema/v2";
static final String XMLNS_V3 = "http://xlate.io/EDISchema/v3";
static final String XMLNS_V4 = "http://xlate.io/EDISchema/v4";
static final Map<QName, BiFunction<XMLStreamReader, Map<String, Object>, SchemaReader>> readerFactories = new HashMap<>(3);
static final Set<String> supportedProperties = new HashSet<>();
static {
readerFactories.put(new QName(XMLNS_V2, SCHEMA_TAG), SchemaReaderV2::new);
readerFactories.put(new QName(XMLNS_V3, SCHEMA_TAG), SchemaReaderV3::new);
readerFactories.put(new QName(XMLNS_V4, SCHEMA_TAG), SchemaReaderV4::new);
supportedProperties.add(SCHEMA_LOCATION_URL_CONTEXT);
}
private final Map<String, Object> properties = new HashMap<>();
@Override
public Schema createSchema(InputStream stream) throws EDISchemaException {
Map<String, EDIType> types = readSchemaTypes(stream, properties, true);
StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID,
StaEDISchema.TRANSACTION_ID,
StaEDISchema.IMPLEMENTATION_ID);
schema.setTypes(types);
LOGGER.log(Level.FINE, "Schema created, contains {0} types", types.size());
return schema;
}
@Override
public Schema createSchema(URL location) throws EDISchemaException {
LOGGER.fine(() -> "Creating schema from URL: " + location);
try (InputStream stream = location.openStream()) {
return createSchema(stream);
} catch (IOException e) {
throw new EDISchemaException("Unable to read URL stream", e);
}
}
@Override
public Schema getControlSchema(String standard, String[] version) throws EDISchemaException {
return SchemaUtils.getControlSchema(standard, version);
}
@Override
public boolean isPropertySupported(String name) {
return supportedProperties.contains(name);
}
@Override
public Object getProperty(String name) {
if (isPropertySupported(name)) {
return properties.get(name);
} else {
throw new IllegalArgumentException("Unsupported property: " + name);
}
}
@Override
public void setProperty(String name, Object value) {
if (isPropertySupported(name)) {
if (value != null) {
properties.put(name, value);
} else {
properties.remove(name);
}
} else {
throw new IllegalArgumentException("Unsupported property: " + name);
}
}
static Map<String, EDIType> readSchemaTypes(URL location, Map<String, Object> properties) throws EDISchemaException {
LOGGER.fine(() -> "Reading schema from URL: " + location);
try (InputStream stream = location.openStream()) {
return readSchemaTypes(stream, properties, false);
} catch (IOException e) {
throw new EDISchemaException("Unable to read URL stream", e);
}
}
static Map<String, EDIType> readSchemaTypes(InputStream stream, Map<String, Object> properties, boolean setReferences) throws EDISchemaException {
try {
return getReader(stream, properties).readTypes(setReferences);
} catch (StaEDISchemaReadException e) {
throw wrapped(e);
}
}
private static SchemaReader getReader(InputStream stream, Map<String, Object> properties) throws EDISchemaException {
QName schemaElement;
try {
LOGGER.fine(() -> "Creating schema from stream");
XMLStreamReader reader = FACTORY.createXMLStreamReader(stream);
reader.nextTag();
schemaElement = reader.getName();
if (readerFactories.containsKey(schemaElement)) {
return readerFactories.get(schemaElement).apply(reader, properties);
}
throw unexpectedElement(schemaElement, reader);
} catch (XMLStreamException e) {
throw new EDISchemaException("Exception checking start of schema XML", e);
}
}
private static EDISchemaException wrapped(StaEDISchemaReadException e) {
Location errorLocation = e.getLocation();
if (errorLocation != null) {
return new EDISchemaException(e.getMessage(), errorLocation, e);
}
return new EDISchemaException(e.getMessage(), e);
}
static StaEDISchemaReadException schemaException(String message) {
return new StaEDISchemaReadException(message, null, null);
}
static StaEDISchemaReadException schemaException(String message, XMLStreamReader reader) {
return schemaException(message, reader, null);
}
static StaEDISchemaReadException unexpectedElement(QName element, XMLStreamReader reader) {
return schemaException("Unexpected XML element [" + element.toString() + ']', reader);
}
static StaEDISchemaReadException unexpectedEvent(XMLStreamReader reader) {
return schemaException("Unexpected XML event [" + reader.getEventType() + ']', reader);
}
static StaEDISchemaReadException schemaException(String message, XMLStreamReader reader, Throwable cause) {
return new StaEDISchemaReadException(message, reader.getLocation(), cause);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/ElementType.java | src/main/java/io/xlate/edi/internal/schema/ElementType.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import io.xlate.edi.schema.EDISimpleType;
//java:S107 : Constructor has 8 arguments
//java:S2160 : Intentionally inherit 'equals' from superclass
@SuppressWarnings({ "java:S107", "java:S2160" })
class ElementType extends BasicType implements EDISimpleType {
private static final String TOSTRING_FORMAT = "id: %s, type: %s, base: %s, code: %s, minLength: %d, maxLength: %d, values: %s";
final Base base;
final int scale;
final String code;
final int number;
final long minLength;
final long maxLength;
final Map<String, String> values;
final List<Version> versions;
static class Version extends VersionedProperty {
final Optional<Long> minLength;
final Optional<Long> maxLength;
final Optional<Map<String, String>> values;
Version(String minVersion, String maxVersion, Long minLength, Long maxLength, Map<String, String> values) {
super(minVersion, maxVersion);
this.minLength = Optional.ofNullable(minLength);
this.maxLength = Optional.ofNullable(maxLength);
this.values = Optional.ofNullable(values);
}
public long getMinLength(ElementType defaultElement) {
return minLength.orElseGet(defaultElement::getMinLength);
}
public long getMaxLength(ElementType defaultElement) {
return maxLength.orElseGet(defaultElement::getMaxLength);
}
public Map<String, String> getValues(ElementType defaultElement) {
return values.orElseGet(defaultElement::getValues);
}
}
ElementType(String id, Base base, int scale, String code, int number, long minLength, long maxLength, Map<String, String> values, List<Version> versions, String title, String description) {
super(id, Type.ELEMENT, title, description);
this.base = base;
this.scale = scale;
this.code = code;
this.number = number;
this.minLength = minLength;
this.maxLength = maxLength;
this.values = Collections.unmodifiableMap(new LinkedHashMap<>(values));
this.versions = Collections.unmodifiableList(new ArrayList<>(versions));
}
<T> T getVersionAttribute(String version, BiFunction<Version, ElementType, T> versionedSupplier, Supplier<T> defaultSupplier) {
for (Version ver : versions) {
if (ver.appliesTo(version)) {
return versionedSupplier.apply(ver, this);
}
}
return defaultSupplier.get();
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, getId(), getType(), base, code, minLength, maxLength, values);
}
@Override
public Base getBase() {
return base;
}
@Override
public Integer getScale() {
if (scale > -1) {
return Integer.valueOf(scale);
}
// Use the default value otherwise
return EDISimpleType.super.getScale();
}
@Override
public String getCode() {
return code;
}
@Override
public boolean hasVersions() {
return !versions.isEmpty();
}
/**
* @see io.xlate.edi.schema.EDISimpleType#getNumber()
* @deprecated
*/
@SuppressWarnings({ "java:S1123", "java:S1133" })
@Override
@Deprecated
public int getNumber() {
return number;
}
@Override
public long getMinLength() {
return minLength;
}
@Override
public long getMinLength(String version) {
return getVersionAttribute(version, Version::getMinLength, this::getMinLength);
}
@Override
public long getMaxLength() {
return maxLength;
}
@Override
public long getMaxLength(String version) {
return getVersionAttribute(version, Version::getMaxLength, this::getMaxLength);
}
@Override
public Map<String, String> getValues() {
return values;
}
@Override
public Map<String, String> getValues(String version) {
return getVersionAttribute(version, Version::getValues, this::getValues);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SchemaReaderBase.java | src/main/java/io/xlate/edi/internal/schema/SchemaReaderBase.java | package io.xlate.edi.internal.schema;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.schemaException;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.unexpectedElement;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.unexpectedEvent;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIControlType;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.schema.EDISimpleType.Base;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.EDIType.Type;
abstract class SchemaReaderBase implements SchemaReader {
private static final Logger LOGGER = Logger.getLogger(SchemaReaderBase.class.getName());
static final String REFERR_UNDECLARED = "Type %s references undeclared %s with ref='%s'";
static final String REFERR_ILLEGAL = "Type '%s' must not be referenced as '%s' in definition of type '%s'";
static final String LOCALNAME_ELEMENT = "element";
static final String LOCALNAME_COMPOSITE = "composite";
static final String ATTR_MIN_OCCURS = "minOccurs";
static final String ATTR_MAX_OCCURS = "maxOccurs";
static final String ATTR_TITLE = "title";
static final String ATTR_HEADER_REF_POSITION = "headerRefPosition";
static final String ATTR_TRAILER_REF_POSITION = "trailerRefPosition";
static final String ATTR_TRAILER_COUNT_POSITION = "trailerCountPosition";
static final String ATTR_COUNT_TYPE = "countType";
static final String ATTR_LEVEL_ID_POSITION = "levelIdPosition";
static final String ATTR_PARENT_ID_POSITION = "parentIdPosition";
static final EDIReference ANY_ELEMENT_REF_OPT = new Reference(StaEDISchema.ANY_ELEMENT_ID, EDIType.Type.ELEMENT, 0, 1, null, null);
static final EDIReference ANY_COMPOSITE_REF_OPT = new Reference(StaEDISchema.ANY_COMPOSITE_ID, EDIType.Type.COMPOSITE, 0, 99, null, null);
static final EDIReference ANY_ELEMENT_REF_REQ = new Reference(StaEDISchema.ANY_ELEMENT_ID, EDIType.Type.ELEMENT, 1, 1, null, null);
static final EDIReference ANY_COMPOSITE_REF_REQ = new Reference(StaEDISchema.ANY_COMPOSITE_ID, EDIType.Type.COMPOSITE, 1, 99, null, null);
static final EDISimpleType ANY_ELEMENT = new ElementType(StaEDISchema.ANY_ELEMENT_ID,
Base.STRING,
-1,
"ANY",
0,
0,
99_999,
Collections.emptyMap(),
Collections.emptyList(),
null,
null);
static final EDIComplexType ANY_COMPOSITE = new StructureType(StaEDISchema.ANY_COMPOSITE_ID,
Type.COMPOSITE,
"ANY",
IntStream.rangeClosed(0, 99).mapToObj(i -> ANY_ELEMENT_REF_OPT)
.collect(toList()),
Collections.emptyList(),
null,
null);
final String xmlns;
final QName qnSchema;
final QName qnInclude;
final QName qnDescription;
final QName qnInterchange;
final QName qnGroup;
final QName qnTransaction;
final QName qnImplementation;
final QName qnLoop;
final QName qnSegment;
final QName qnComposite;
final QName qnElement;
final QName qnSyntax;
final QName qnPosition;
final QName qnSequence;
final QName qnEnumeration;
final QName qnValue;
final QName qnVersion;
final QName qnAny;
final QName qnCompositeType;
final QName qnElementType;
final QName qnSegmentType;
final Map<QName, EDIType.Type> complex;
final Map<QName, EDIType.Type> typeDefinitions;
final Map<QName, EDIType.Type> references;
protected XMLStreamReader reader;
protected Map<String, Object> properties;
protected SchemaReaderBase(String xmlns, XMLStreamReader reader, Map<String, Object> properties) {
this.xmlns = xmlns;
qnSchema = new QName(xmlns, "schema");
qnInclude = new QName(xmlns, "include");
qnDescription = new QName(xmlns, "description");
qnInterchange = new QName(xmlns, "interchange");
qnGroup = new QName(xmlns, "group");
qnTransaction = new QName(xmlns, "transaction");
qnImplementation = new QName(xmlns, "implementation");
qnLoop = new QName(xmlns, "loop");
qnSegment = new QName(xmlns, "segment");
qnComposite = new QName(xmlns, LOCALNAME_COMPOSITE);
qnElement = new QName(xmlns, LOCALNAME_ELEMENT);
qnSyntax = new QName(xmlns, "syntax");
qnPosition = new QName(xmlns, "position");
qnSequence = new QName(xmlns, "sequence");
qnEnumeration = new QName(xmlns, "enumeration");
qnValue = new QName(xmlns, "value");
qnVersion = new QName(xmlns, "version");
qnAny = new QName(xmlns, "any");
qnCompositeType = new QName(xmlns, "compositeType");
qnElementType = new QName(xmlns, "elementType");
qnSegmentType = new QName(xmlns, "segmentType");
complex = new HashMap<>(4);
complex.put(qnInterchange, EDIType.Type.INTERCHANGE);
complex.put(qnGroup, EDIType.Type.GROUP);
complex.put(qnTransaction, EDIType.Type.TRANSACTION);
complex.put(qnLoop, EDIType.Type.LOOP);
complex.put(qnSegmentType, EDIType.Type.SEGMENT);
complex.put(qnCompositeType, EDIType.Type.COMPOSITE);
typeDefinitions = new HashMap<>(3);
typeDefinitions.put(qnSegmentType, EDIType.Type.SEGMENT);
typeDefinitions.put(qnCompositeType, EDIType.Type.COMPOSITE);
typeDefinitions.put(qnElementType, EDIType.Type.ELEMENT);
references = new HashMap<>(4);
references.put(qnSegment, EDIType.Type.SEGMENT);
references.put(qnComposite, EDIType.Type.COMPOSITE);
references.put(qnElement, EDIType.Type.ELEMENT);
this.reader = reader;
this.properties = properties;
}
@Override
public Map<String, EDIType> readTypes(boolean setReferences) throws EDISchemaException {
Map<String, EDIType> types = new HashMap<>(100);
types.put(StaEDISchema.ANY_ELEMENT_ID, ANY_ELEMENT);
types.put(StaEDISchema.ANY_COMPOSITE_ID, ANY_COMPOSITE);
nextTag(reader, "advancing to first schema element");
QName element = reader.getName();
while (qnInclude.equals(element)) {
readInclude(reader, types);
element = reader.getName();
}
if (qnInterchange.equals(element)) {
readInterchange(reader, types);
} else if (qnTransaction.equals(element)) {
readTransaction(reader, types);
readImplementation(reader, types);
} else if (qnImplementation.equals(element)) {
readImplementation(reader, types);
} else if (!typeDefinitions.containsKey(reader.getName())) {
throw unexpectedElement(element, reader);
}
readTypeDefinitions(reader, types);
try {
reader.next();
} catch (XMLStreamException xse) {
throw schemaException("XMLStreamException reading end of document", reader, xse);
}
requireEvent(XMLStreamConstants.END_DOCUMENT, reader);
if (setReferences) {
setReferences(types);
}
return types;
}
String readDescription(XMLStreamReader reader) {
nextTag(reader, "seeking description element");
QName element = reader.getName();
String description = null;
if (qnDescription.equals(element)) {
description = getElementText(reader, "description");
nextTag(reader, "after description element");
}
return description;
}
void readInterchange(XMLStreamReader reader, Map<String, EDIType> types) {
QName element;
Reference header = createControlReference(reader, "header");
Reference trailer = createControlReference(reader, "trailer");
EDIElementPosition headerRefPos = parseElementPosition(reader, ATTR_HEADER_REF_POSITION);
EDIElementPosition trailerRefPos = parseElementPosition(reader, ATTR_TRAILER_REF_POSITION);
EDIElementPosition trailerCountPos = parseElementPosition(reader, ATTR_TRAILER_COUNT_POSITION);
EDIControlType.Type countType = parseAttribute(reader, ATTR_COUNT_TYPE, EDIControlType.Type::fromString, EDIControlType.Type.NONE);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
String descr = readDescription(reader);
element = reader.getName();
if (!qnSequence.equals(element)) {
throw unexpectedElement(element, reader);
}
nextTag(reader, "reading interchange sequence");
element = reader.getName();
List<EDIReference> refs = new ArrayList<>(3);
refs.add(header);
while (qnSegment.equals(element)) {
addReferences(reader, EDIType.Type.SEGMENT, refs, readReference(reader, types));
nextTag(reader, "completing interchange segment"); // Advance to end element
nextTag(reader, "reading after interchange segment"); // Advance to next start element
element = reader.getName();
}
if (qnGroup.equals(element)) {
refs.add(readControlStructure(reader, element, qnTransaction, types));
nextTag(reader, "completing group"); // Advance to end element
nextTag(reader, "reading after group"); // Advance to next start element
element = reader.getName();
}
if (qnTransaction.equals(element)) {
refs.add(readControlStructure(reader, element, null, types));
nextTag(reader, "completing transaction"); // Advance to end element
nextTag(reader, "reading after transaction"); // Advance to next start element
element = reader.getName();
}
refs.add(trailer);
final List<EDISyntaxRule> rules;
if (qnSyntax.equals(element)) {
rules = new ArrayList<>(2);
readSyntaxList(reader, rules);
} else {
rules = Collections.emptyList();
}
StructureType interchange = new ControlType(StaEDISchema.INTERCHANGE_ID,
EDIType.Type.INTERCHANGE,
"INTERCHANGE",
refs,
rules,
headerRefPos,
trailerRefPos,
trailerCountPos,
countType,
title,
descr);
types.put(interchange.getId(), interchange);
nextTag(reader, "advancing after interchange");
}
Reference readControlStructure(XMLStreamReader reader,
QName element,
QName subelement,
Map<String, EDIType> types) {
int minOccurs = 0;
int maxOccurs = 99999;
String use = parseAttribute(reader, "use", String::valueOf, "optional");
switch (use) {
case "required":
minOccurs = 1;
break;
case "optional":
minOccurs = 0;
break;
case "prohibited":
maxOccurs = 0;
break;
default:
throw schemaException("Invalid value for 'use': " + use, reader);
}
Reference header = createControlReference(reader, "header");
Reference trailer = createControlReference(reader, "trailer");
EDIElementPosition headerRefPos = parseElementPosition(reader, ATTR_HEADER_REF_POSITION);
EDIElementPosition trailerRefPos = parseElementPosition(reader, ATTR_TRAILER_REF_POSITION);
EDIElementPosition trailerCountPos = parseElementPosition(reader, ATTR_TRAILER_COUNT_POSITION);
EDIControlType.Type countType = parseAttribute(reader, ATTR_COUNT_TYPE, EDIControlType.Type::fromString, EDIControlType.Type.NONE);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
String descr = readDescription(reader);
if (subelement != null) {
requireElementStart(subelement, reader);
}
List<EDIReference> refs = new ArrayList<>(3);
refs.add(header);
if (subelement != null) {
refs.add(readControlStructure(reader, subelement, null, types));
}
refs.add(trailer);
Type elementType = complex.get(element);
String elementId = StaEDISchema.ID_PREFIX + elementType.name();
StructureType struct = new ControlType(elementId,
elementType,
elementType.toString(),
refs,
Collections.emptyList(),
headerRefPos,
trailerRefPos,
trailerCountPos,
countType,
title,
descr);
/*
* Built-in X12 control schemas include a prohibited transaction element in the
* schema to indicate that a transaction may not be used directly within an interchange
* envelope. The use of `putIfAbsent` prevents this transaction from overlaying the
* actual transaction type nested within the group envelope. EDIFACT and TRADACOMS
* transactions may appear in either location, the `putIfAbsent` has no effect.
*/
types.putIfAbsent(struct.getId(), struct);
Reference structRef = new Reference(struct.getId(), elementType, minOccurs, maxOccurs, title, descr);
structRef.setReferencedType(struct);
return structRef;
}
Reference createControlReference(XMLStreamReader reader, String attributeName) {
final String refId = parseAttribute(reader, attributeName, String::valueOf);
return new Reference(refId, EDIType.Type.SEGMENT, 1, 1, null, null);
}
void readTransaction(XMLStreamReader reader, Map<String, EDIType> types) {
QName element = reader.getName();
types.put(StaEDISchema.TRANSACTION_ID, readComplexType(reader, element, types));
nextTag(reader, "seeking next element after transaction");
}
void readTypeDefinitions(XMLStreamReader reader, Map<String, EDIType> types) {
boolean schemaEnd = reader.getName().equals(qnSchema);
// Cursor is already positioned on a type definition (e.g. from an earlier look-ahead)
if (typeDefinitions.containsKey(reader.getName())
&& reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
readTypeDefinition(types, reader);
}
while (!schemaEnd) {
if (nextTag(reader, "reading schema types") == XMLStreamConstants.START_ELEMENT) {
readTypeDefinition(types, reader);
} else {
schemaEnd = reader.getName().equals(qnSchema);
}
}
}
void readTypeDefinition(Map<String, EDIType> types, XMLStreamReader reader) {
QName element = reader.getName();
String name;
if (complex.containsKey(element)) {
name = parseAttribute(reader, "name", String::valueOf);
nameCheck(name, types, reader);
types.put(name, readComplexType(reader, element, types));
} else if (qnElementType.equals(element)) {
name = parseAttribute(reader, "name", String::valueOf);
nameCheck(name, types, reader);
types.put(name, readSimpleType(reader));
} else {
throw unexpectedElement(element, reader);
}
}
void nameCheck(String name, Map<String, EDIType> types, XMLStreamReader reader) {
if (types.containsKey(name)) {
throw schemaException("duplicate name: " + name, reader);
}
}
StructureType readComplexType(XMLStreamReader reader,
QName complexType,
Map<String, EDIType> types) {
final EDIType.Type type = complex.get(complexType);
final String id;
String code = parseAttribute(reader, "code", String::valueOf, null);
// Loop attributes
EDIElementPosition levelIdPosition = null;
EDIElementPosition parentIdPosition = null;
switch (type) {
case TRANSACTION:
// "Standard" transaction structure, not the control type from control schema
id = StaEDISchema.TRANSACTION_ID;
break;
case LOOP:
id = code;
levelIdPosition = parseElementPosition(reader, ATTR_LEVEL_ID_POSITION);
parentIdPosition = parseElementPosition(reader, ATTR_PARENT_ID_POSITION);
break;
case SEGMENT:
id = parseAttribute(reader, "name", String::valueOf);
if (!id.matches("^[A-Z][A-Z0-9]{1,2}$")) {
throw schemaException("Invalid segment name [" + id + ']', reader);
}
break;
case COMPOSITE:
default: /* Only COMPOSITE remains */
id = parseAttribute(reader, "name", String::valueOf);
break;
}
if (code == null) {
code = id;
}
final List<EDIReference> refs = new ArrayList<>(8);
final List<EDISyntaxRule> rules = new ArrayList<>(2);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
String descr = readDescription(reader);
requireElementStart(qnSequence, reader);
readReferences(reader, types, type, refs);
int event = nextTag(reader, "searching for syntax element");
if (event == XMLStreamConstants.START_ELEMENT) {
requireElementStart(qnSyntax, reader);
readSyntaxList(reader, rules);
}
event = reader.getEventType();
if (event == XMLStreamConstants.END_ELEMENT) {
StructureType structure;
if (type == Type.LOOP) {
structure = new LoopType(code, refs, rules, levelIdPosition, parentIdPosition, title, descr);
} else {
structure = new StructureType(id, type, code, refs, rules, title, descr);
}
return structure;
} else {
throw unexpectedEvent(reader);
}
}
void readReferences(XMLStreamReader reader,
Map<String, EDIType> types,
EDIType.Type parentType,
List<EDIReference> refs) {
boolean endOfReferences = false;
while (!endOfReferences) {
int event = nextTag(reader, "reading sequence");
if (event == XMLStreamConstants.START_ELEMENT) {
addReferences(reader, parentType, refs, readReference(reader, types));
} else {
if (reader.getName().equals(qnSequence)) {
endOfReferences = true;
}
}
}
}
void addReferences(XMLStreamReader reader, EDIType.Type parentType, List<EDIReference> refs, Reference reference) {
if ("ANY".equals(reference.getRefId())) {
final EDIReference optRef;
final EDIReference reqRef;
switch (parentType) {
case SEGMENT:
optRef = ANY_COMPOSITE_REF_OPT;
reqRef = ANY_COMPOSITE_REF_REQ;
break;
case COMPOSITE:
optRef = ANY_ELEMENT_REF_OPT;
reqRef = ANY_ELEMENT_REF_REQ;
break;
default:
throw schemaException("Element " + qnAny + " may only be present for segmentType and compositeType", reader);
}
final int min = reference.getMinOccurs();
final int max = reference.getMaxOccurs();
for (int i = 0; i < max; i++) {
refs.add(i < min ? reqRef : optRef);
}
} else {
refs.add(reference);
}
}
Reference readReference(XMLStreamReader reader, Map<String, EDIType> types) {
QName element = reader.getName();
String refId = null;
EDIType.Type refTag;
if (qnAny.equals(element)) {
refId = "ANY";
refTag = null;
} else if (references.containsKey(element)) {
refId = readReferencedId(reader);
refTag = references.get(element);
Objects.requireNonNull(refId);
} else if (qnLoop.equals(element)) {
refId = parseAttribute(reader, "code", String::valueOf);
refTag = EDIType.Type.LOOP;
} else {
throw unexpectedElement(element, reader);
}
int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, 0);
int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, 1);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
Reference ref;
if (qnLoop.equals(element)) {
StructureType loop = readComplexType(reader, element, types);
nameCheck(refId, types, reader);
types.put(refId, loop);
ref = new Reference(refId, refTag, minOccurs, maxOccurs, title, null);
ref.setReferencedType(loop);
} else if (qnComposite.equals(element) || qnElement.equals(element)) {
List<Reference.Version> versions = null;
if (nextTag(reader, "reading " + element + " contents") != XMLStreamConstants.END_ELEMENT) {
requireElementStart(qnVersion, reader);
versions = new ArrayList<>();
do {
versions.add(readReferenceVersion(reader));
} while (nextTag(reader, "reading after " + element + " version") != XMLStreamConstants.END_ELEMENT);
} else {
versions = Collections.emptyList();
}
ref = new Reference(refId, refTag, minOccurs, maxOccurs, versions, title, null);
} else {
ref = new Reference(refId, refTag, minOccurs, maxOccurs, title, null);
}
return ref;
}
Reference.Version readReferenceVersion(XMLStreamReader reader) {
requireElementStart(qnVersion, reader);
String minVersion = parseAttribute(reader, "minVersion", String::valueOf, "");
String maxVersion = parseAttribute(reader, "maxVersion", String::valueOf, "");
Integer minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::valueOf, null);
Integer maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::valueOf, null);
if (nextTag(reader, "reading version contents") != XMLStreamConstants.END_ELEMENT) {
throw unexpectedElement(reader.getName(), reader);
}
return new Reference.Version(minVersion, maxVersion, minOccurs, maxOccurs);
}
void readSyntaxList(XMLStreamReader reader, List<EDISyntaxRule> rules) {
do {
readSyntax(reader, rules);
nextTag(reader, "reading after syntax element");
} while (qnSyntax.equals(reader.getName()));
}
void readSyntax(XMLStreamReader reader, List<EDISyntaxRule> rules) {
String type = parseAttribute(reader, "type", String::valueOf);
EDISyntaxRule.Type typeInt = null;
try {
typeInt = EDISyntaxRule.Type.fromString(type);
} catch (IllegalArgumentException e) {
throw schemaException("Invalid syntax 'type': [" + type + ']', reader, e);
}
rules.add(new SyntaxRestriction(typeInt, readSyntaxPositions(reader)));
}
List<Integer> readSyntaxPositions(XMLStreamReader reader) {
final List<Integer> positions = new ArrayList<>(5);
boolean endOfSyntax = false;
while (!endOfSyntax) {
final int event = nextTag(reader, "reading syntax positions");
final QName element = reader.getName();
if (event == XMLStreamConstants.START_ELEMENT) {
if (element.equals(qnPosition)) {
final String position = getElementText(reader, "syntax position");
try {
positions.add(Integer.parseInt(position));
} catch (@SuppressWarnings("unused") NumberFormatException e) {
throw schemaException("invalid position [" + position + ']', reader);
}
}
} else {
endOfSyntax = true;
}
}
return positions;
}
ElementType readSimpleType(XMLStreamReader reader) {
String name = parseAttribute(reader, "name", String::valueOf);
String code = parseAttribute(reader, "code", String::valueOf, name);
Base base = parseAttribute(reader, "base", Base::fromString, Base.STRING);
int scale = (Base.NUMERIC == base) ? parseAttribute(reader, "scale", Integer::parseInt, 0) : -1;
int number = parseAttribute(reader, "number", Integer::parseInt, -1);
long minLength = parseAttribute(reader, "minLength", Long::parseLong, 1L);
long maxLength = parseAttribute(reader, "maxLength", Long::parseLong, 1L);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
String descr = readDescription(reader);
final Map<String, String> values;
final List<ElementType.Version> versions;
// Reader was advanced by `readDescription`, check the current state to proceed.
if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
values = Collections.emptyMap();
versions = Collections.emptyList();
} else {
if (qnEnumeration.equals(reader.getName())) {
values = readEnumerationValues(reader);
nextTag(reader, "reading after elementType enumeration");
} else {
values = Collections.emptyMap();
}
if (qnVersion.equals(reader.getName())) {
versions = new ArrayList<>();
do {
versions.add(readSimpleTypeVersion(reader));
} while (nextTag(reader, "reading after elementType version") != XMLStreamConstants.END_ELEMENT);
} else {
versions = Collections.emptyList();
}
}
return new ElementType(name, base, scale, code, number, minLength, maxLength, values, versions, title, descr);
}
ElementType.Version readSimpleTypeVersion(XMLStreamReader reader) {
requireElementStart(qnVersion, reader);
String minVersion = parseAttribute(reader, "minVersion", String::valueOf, "");
String maxVersion = parseAttribute(reader, "maxVersion", String::valueOf, "");
Long minLength = parseAttribute(reader, "minLength", Long::valueOf, null);
Long maxLength = parseAttribute(reader, "maxLength", Long::valueOf, null);
Map<String, String> values;
if (nextTag(reader, "reading elementType version contents") == XMLStreamConstants.END_ELEMENT) {
// Set to null instead of empty to indicate that no enumeration is present in this version
values = null;
} else if (qnEnumeration.equals(reader.getName())) {
values = readEnumerationValues(reader);
nextTag(reader, "reading after elementType version enumeration");
} else {
throw unexpectedElement(reader.getName(), reader);
}
return new ElementType.Version(minVersion, maxVersion, minLength, maxLength, values);
}
Map<String, String> readEnumerationValues(XMLStreamReader reader) {
Map<String, String> values = null;
boolean endOfEnumeration = false;
while (!endOfEnumeration) {
final int event = nextTag(reader, "reading enumeration");
final QName element = reader.getName();
if (event == XMLStreamConstants.START_ELEMENT) {
if (element.equals(qnValue)) {
values = readEnumerationValue(reader, values);
} else {
throw unexpectedElement(element, reader);
}
} else {
endOfEnumeration = true;
}
}
return requireNonNullElseGet(values, Collections::emptyMap);
}
Map<String, String> readEnumerationValue(XMLStreamReader reader, Map<String, String> values) {
if (values == null) {
values = new LinkedHashMap<>();
}
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
values.put(getElementText(reader, "enumeration value"), title);
return values;
}
<T> T parseAttribute(XMLStreamReader reader, String attrName, Function<String, T> converter, T defaultValue) {
String attr = reader.getAttributeValue(null, attrName);
try {
return attr != null ? converter.apply(attr) : defaultValue;
} catch (Exception e) {
throw schemaException("Invalid " + attrName, reader, e);
}
}
<T> T parseAttribute(XMLStreamReader reader, String attrName, Function<String, T> converter) {
String attr = reader.getAttributeValue(null, attrName);
if (attr != null) {
try {
return converter.apply(attr);
} catch (Exception e) {
throw schemaException("Invalid " + attrName, reader, e);
}
} else {
throw schemaException("Missing required attribute: [" + attrName + ']', reader);
}
}
int nextTag(XMLStreamReader reader, String activity) {
try {
if (!reader.hasNext()) {
throw schemaException("End of stream reached while " + activity, reader, null);
}
return reader.nextTag();
} catch (XMLStreamException xse) {
throw schemaException("XMLStreamException while " + activity, reader, xse);
}
}
String getElementText(XMLStreamReader reader, String context) {
try {
return reader.getElementText();
} catch (XMLStreamException xse) {
throw schemaException("XMLStreamException reading element text: " + context, reader, xse);
}
}
void requireEvent(int eventId, XMLStreamReader reader) {
Integer event = reader.getEventType();
if (event != eventId) {
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | true |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/ControlType.java | src/main/java/io/xlate/edi/internal/schema/ControlType.java | package io.xlate.edi.internal.schema;
import java.util.List;
import io.xlate.edi.schema.EDIControlType;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
@SuppressWarnings("java:S2160") // Intentionally inherit 'equals' from superclass
class ControlType extends StructureType implements EDIControlType {
private final EDIElementPosition headerRefPosition;
private final EDIElementPosition trailerRefPosition;
private final EDIElementPosition trailerCountPosition;
private final EDIControlType.Type countType;
@SuppressWarnings("java:S107")
ControlType(String id,
EDIType.Type type,
String code,
List<EDIReference> references,
List<EDISyntaxRule> syntaxRules,
EDIElementPosition headerRefPosition,
EDIElementPosition trailerRefPosition,
EDIElementPosition trailerCountPosition,
EDIControlType.Type countType,
String title,
String description) {
super(id, type, code, references, syntaxRules, title, description);
this.headerRefPosition = headerRefPosition;
this.trailerRefPosition = trailerRefPosition;
this.trailerCountPosition = trailerCountPosition;
this.countType = countType;
}
@Override
public EDIElementPosition getHeaderRefPosition() {
return headerRefPosition;
}
@Override
public EDIElementPosition getTrailerRefPosition() {
return trailerRefPosition;
}
@Override
public EDIElementPosition getTrailerCountPosition() {
return trailerCountPosition;
}
@Override
public EDIControlType.Type getCountType() {
return countType;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/StaEDISchema.java | src/main/java/io/xlate/edi/internal/schema/StaEDISchema.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.EDIType.Type;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.schema.implementation.LoopImplementation;
public class StaEDISchema implements Schema {
public static final String ID_PREFIX = "io.xlate.edi.internal.schema.";
public static final String INTERCHANGE_ID = ID_PREFIX + Type.INTERCHANGE.name();
public static final String GROUP_ID = ID_PREFIX + Type.GROUP.name();
public static final String TRANSACTION_ID = ID_PREFIX + Type.TRANSACTION.name();
public static final String IMPLEMENTATION_ID = ID_PREFIX + "IMPLEMENTATION";
public static final String ANY_ELEMENT_ID = ID_PREFIX + "ANY_ELEMENT";
public static final String ANY_COMPOSITE_ID = ID_PREFIX + "ANY_COMPOSITE";
private volatile Integer hash = null;
final String interchangeName;
final String transactionStandardName;
final String implementationName;
Map<String, EDIType> types = Collections.emptyMap();
EDIComplexType standardLoop = null;
LoopImplementation implementationLoop = null;
public StaEDISchema(String interchangeName, String transactionStandardName, String implementationName) {
super();
this.interchangeName = interchangeName;
this.transactionStandardName = transactionStandardName;
this.implementationName = implementationName;
}
public StaEDISchema(String interchangeName, String transactionStandardName) {
this(interchangeName, transactionStandardName, null);
}
@Override
public boolean equals(Object o) {
if (o instanceof Schema) {
Schema other = (Schema) o;
// Count the differences of each entry
return StreamSupport.stream(spliterator(), false)
.filter(type -> {
final EDIType otherType = other.getType(type.getId());
return !type.equals(otherType);
})
.count() == 0;
}
return false;
}
@Override
public synchronized int hashCode() {
Integer localHash = hash;
if (localHash == null) {
localHash = hash = StreamSupport.stream(spliterator(), false)
.collect(Collectors.summingInt(EDIType::hashCode));
}
return localHash.intValue();
}
@Override
public EDIComplexType getStandard() {
return standardLoop;
}
@Override
public LoopImplementation getImplementation() {
return implementationLoop;
}
void setTypes(Map<String, EDIType> types) throws EDISchemaException {
if (types == null) {
throw new NullPointerException("types cannot be null");
}
this.types = Collections.unmodifiableMap(types);
if (types.containsKey(interchangeName)) {
this.standardLoop = (EDIComplexType) types.get(interchangeName);
} else if (types.containsKey(transactionStandardName)) {
this.standardLoop = (EDIComplexType) types.get(transactionStandardName);
} else {
throw new EDISchemaException("Schema must contain either " +
interchangeName + " or " + transactionStandardName);
}
if (implementationName != null && types.containsKey(implementationName)) {
this.implementationLoop = (LoopImplementation) types.get(implementationName);
}
}
@Override
public EDIType getType(String name) {
return types.get(name);
}
@Override
public boolean containsSegment(String name) {
final EDIType type = getType(name);
return type != null && type.isType(EDIType.Type.SEGMENT);
}
@Override
public Iterator<EDIType> iterator() {
return types.values().iterator();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SyntaxRestriction.java | src/main/java/io/xlate/edi/internal/schema/SyntaxRestriction.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import io.xlate.edi.schema.EDISyntaxRule;
class SyntaxRestriction implements EDISyntaxRule {
private static final String TOSTRING_FORMAT = "type: %s, positions: %s";
private EDISyntaxRule.Type type;
private List<Integer> positions;
SyntaxRestriction(EDISyntaxRule.Type type, List<Integer> positions) {
Objects.requireNonNull(type, "syntax rule type must not be null");
Objects.requireNonNull(positions, "syntax rule positions must not be null");
if (positions.isEmpty()) {
throw new IllegalArgumentException("syntax rule positions must not be em");
}
this.type = type;
this.positions = new ArrayList<>(positions);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, type, positions);
}
@Override
public EDISyntaxRule.Type getType() {
return type;
}
@Override
public List<Integer> getPositions() {
return positions;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/StructureType.java | src/main/java/io/xlate/edi/internal/schema/StructureType.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISyntaxRule;
import io.xlate.edi.schema.EDIType;
@SuppressWarnings("java:S2160") // Intentionally inherit 'equals' from superclass
class StructureType extends BasicType implements EDIComplexType {
private static final String TOSTRING_FORMAT = "id: %s, type: %s, code: %s, references: [%s], syntaxRestrictions: [%s]";
private String code;
private List<EDIReference> references;
private List<EDISyntaxRule> syntaxRules;
StructureType(String id, EDIType.Type type, String code, List<EDIReference> references, List<EDISyntaxRule> syntaxRules, String title, String description) {
super(id, type, title, description);
Objects.requireNonNull(code, "EDIComplexType code must not be null");
Objects.requireNonNull(references, "EDIComplexType references must not be null");
Objects.requireNonNull(syntaxRules, "EDIComplexType id must not be null");
this.code = code;
this.references = Collections.unmodifiableList(new ArrayList<>(references));
this.syntaxRules = Collections.unmodifiableList(new ArrayList<>(syntaxRules));
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, getId(), getType(), code,
references.stream().map(r -> "{" + r + '}').collect(Collectors.joining(",")),
syntaxRules.stream().map(r -> "{" + r + '}').collect(Collectors.joining(",")));
}
@Override
public String getCode() {
return code;
}
@Override
public List<EDIReference> getReferences() {
return references;
}
@Override
public List<EDISyntaxRule> getSyntaxRules() {
return syntaxRules;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/VersionedProperty.java | src/main/java/io/xlate/edi/internal/schema/VersionedProperty.java | package io.xlate.edi.internal.schema;
class VersionedProperty {
final String minVersion;
final String maxVersion;
public VersionedProperty(String minVersion, String maxVersion) {
this.minVersion = minVersion;
this.maxVersion = maxVersion;
}
boolean appliesTo(String version) {
return minVersionIncludes(version) && maxVersionIncludes(version);
}
boolean minVersionIncludes(String version) {
return minVersion.trim().isEmpty() || minVersion.compareTo(version) <= 0;
}
boolean maxVersionIncludes(String version) {
return maxVersion.trim().isEmpty() || maxVersion.compareTo(version) >= 0;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/BasicType.java | src/main/java/io/xlate/edi/internal/schema/BasicType.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.util.Objects;
import io.xlate.edi.schema.EDIType;
abstract class BasicType implements EDIType {
private final String id;
private final Type type;
private final String title;
private final String description;
BasicType(String id, Type type, String title, String description) {
Objects.requireNonNull(id, "EDIType id must not be null");
Objects.requireNonNull(type, "EDIType type must not be null");
this.id = id;
this.type = type;
this.title = title;
this.description = description;
}
@Override
public String getId() {
return id;
}
@Override
public Type getType() {
return type;
}
@Override
public String getTitle() {
return title;
}
@Override
public String getDescription() {
return description;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof BasicType) {
BasicType other = (BasicType) o;
return Objects.equals(id, other.id) && Objects.equals(type, other.type);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(id, type);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SchemaUtils.java | src/main/java/io/xlate/edi/internal/schema/SchemaUtils.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Properties;
import java.util.TreeMap;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.Schema;
import io.xlate.edi.schema.SchemaFactory;
import io.xlate.edi.stream.EDIStreamConstants.Standards;
public class SchemaUtils {
private SchemaUtils() {
}
static Properties controlIndex = new Properties();
static NavigableMap<String, String> controlVersions = new TreeMap<>();
static NavigableMap<String, Schema> controlSchemas = new TreeMap<>();
static {
try {
Enumeration<URL> resources = getStreams("staedi-control-index.properties");
while (resources.hasMoreElements()) {
try (InputStream stream = resources.nextElement().openStream()) {
controlIndex.load(stream);
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
for (Map.Entry<Object, Object> entry : controlIndex.entrySet()) {
final String standardVersion = entry.getKey().toString();
final String schemaPath = entry.getValue().toString();
controlVersions.put(standardVersion, schemaPath);
controlSchemas.put(standardVersion, null);
}
}
static Enumeration<URL> getStreams(String resource) throws IOException {
ClassLoader loader = SchemaUtils.class.getClassLoader();
return loader.getResources(resource);
}
static URL getURL(String resource) {
return SchemaUtils.class.getResource(resource);
}
public static Schema getControlSchema(String standard, String[] version) throws EDISchemaException {
String key;
if (Standards.EDIFACT.equals(standard)) {
key = standard + '.' + version[1] + (version.length > 4 ? '.' + version[4] : "");
} else {
key = standard + '.' + String.join(".", version);
}
Entry<String, Schema> controlEntry = controlSchemas.floorEntry(key);
if (isValidEntry(controlEntry, standard)) {
return controlEntry.getValue();
}
Entry<String, String> pathEntry = controlVersions.floorEntry(key);
if (isValidEntry(pathEntry, standard)) {
Schema created = getXmlSchema(pathEntry.getValue());
controlSchemas.put(pathEntry.getKey(), created);
return created;
}
return null;
}
static boolean isValidEntry(Entry<String, ?> entry, String standard) {
if (entry == null) {
return false;
}
if (!entry.getKey().startsWith(standard)) {
return false;
}
return entry.getValue() != null;
}
private static Schema getXmlSchema(String resource) throws EDISchemaException {
final URL location = getURL(resource);
final URL locationContext;
try {
final String external = location.toExternalForm();
locationContext = new URL(external.substring(0, external.lastIndexOf('/') + 1));
} catch (MalformedURLException e) {
throw new EDISchemaException("Unable to resolve schema location context", e);
}
SchemaFactory schemaFactory = SchemaFactory.newFactory();
schemaFactory.setProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, locationContext);
return schemaFactory.createSchema(location);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/Reference.java | src/main/java/io/xlate/edi/internal/schema/Reference.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.internal.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDIType;
class Reference implements EDIReference {
private static final String TOSTRING_FORMAT = "refId: %s, minOccurs: %d, maxOccurs: %d, type: { %s }";
private String refId;
private EDIType.Type refTag;
private EDIType referencedType;
final int minOccurs;
final int maxOccurs;
final List<Version> versions;
private final String title;
private final String description;
static class Version extends VersionedProperty {
final Optional<Integer> minOccurs;
final Optional<Integer> maxOccurs;
Version(String minVersion, String maxVersion, Integer minOccurs, Integer maxOccurs) {
super(minVersion, maxVersion);
this.minOccurs = Optional.ofNullable(minOccurs);
this.maxOccurs = Optional.ofNullable(maxOccurs);
}
public int getMinOccurs(Reference defaultElement) {
return minOccurs.orElseGet(defaultElement::getMinOccurs);
}
public int getMaxOccurs(Reference defaultElement) {
return maxOccurs.orElseGet(defaultElement::getMaxOccurs);
}
}
Reference(String refId, EDIType.Type refTag, int minOccurs, int maxOccurs, List<Version> versions, String title, String description) {
this.refId = refId;
this.refTag = refTag;
this.minOccurs = minOccurs;
this.maxOccurs = maxOccurs;
this.versions = Collections.unmodifiableList(new ArrayList<>(versions));
this.title = title;
this.description = description;
}
Reference(String refId, EDIType.Type refTag, int minOccurs, int maxOccurs, String title, String description) {
this(refId, refTag, minOccurs, maxOccurs, Collections.emptyList(), title, description);
}
Reference(EDIType referencedType, int minOccurs, int maxOccurs) {
this.referencedType = referencedType;
this.minOccurs = minOccurs;
this.maxOccurs = maxOccurs;
this.versions = Collections.emptyList();
this.title = null;
this.description = null;
}
<T> T getVersionAttribute(String version, BiFunction<Version, Reference, T> versionedSupplier, Supplier<T> defaultSupplier) {
for (Version ver : versions) {
if (ver.appliesTo(version)) {
return versionedSupplier.apply(ver, this);
}
}
return defaultSupplier.get();
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, refId, minOccurs, maxOccurs, referencedType);
}
String getRefId() {
return refId;
}
EDIType.Type getRefTag() {
return refTag;
}
@Override
public EDIType getReferencedType() {
return referencedType;
}
void setReferencedType(EDIType referencedType) {
this.referencedType = referencedType;
}
@Override
public int getMinOccurs() {
return minOccurs;
}
@Override
public int getMaxOccurs() {
return maxOccurs;
}
@Override
public boolean hasVersions() {
return !versions.isEmpty();
}
@Override
public int getMinOccurs(String version) {
return getVersionAttribute(version, Version::getMinOccurs, this::getMinOccurs);
}
@Override
public int getMaxOccurs(String version) {
return getVersionAttribute(version, Version::getMaxOccurs, this::getMaxOccurs);
}
@Override
public String getTitle() {
return title;
}
@Override
public String getDescription() {
return description;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SchemaReader.java | src/main/java/io/xlate/edi/internal/schema/SchemaReader.java | package io.xlate.edi.internal.schema;
import java.util.Map;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
interface SchemaReader {
default Map<String, EDIType> readTypes() throws EDISchemaException {
return readTypes(true);
}
Map<String, EDIType> readTypes(boolean setReferences) throws EDISchemaException;
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/ClasspathURLStreamHandler.java | src/main/java/io/xlate/edi/internal/schema/ClasspathURLStreamHandler.java | package io.xlate.edi.internal.schema;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
class ClasspathURLStreamHandler extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader;
public ClasspathURLStreamHandler(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
final String resourcePath = u.getPath();
final URL resourceUrl = classLoader.getResource(resourcePath);
if (resourceUrl == null) {
throw new FileNotFoundException("Class-path resource not found: " + resourcePath);
}
return resourceUrl.openConnection();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SchemaReaderV3.java | src/main/java/io/xlate/edi/internal/schema/SchemaReaderV3.java | package io.xlate.edi.internal.schema;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.schemaException;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.unexpectedElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Logger;
import java.util.stream.StreamSupport;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.internal.schema.implementation.BaseComplexImpl;
import io.xlate.edi.internal.schema.implementation.BaseImpl;
import io.xlate.edi.internal.schema.implementation.CompositeImpl;
import io.xlate.edi.internal.schema.implementation.DiscriminatorImpl;
import io.xlate.edi.internal.schema.implementation.ElementImpl;
import io.xlate.edi.internal.schema.implementation.LoopImpl;
import io.xlate.edi.internal.schema.implementation.Positioned;
import io.xlate.edi.internal.schema.implementation.SegmentImpl;
import io.xlate.edi.internal.schema.implementation.TransactionImpl;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.EDIType.Type;
import io.xlate.edi.schema.implementation.Discriminator;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.schema.implementation.LoopImplementation;
class SchemaReaderV3 extends SchemaReaderBase implements SchemaReader {
private static final Logger LOGGER = Logger.getLogger(SchemaReaderV3.class.getName());
private static final String ATTR_POSITION = "position";
private static final String ATTR_DISCRIMINATOR = "discriminator";
final Deque<EDITypeImplementation> implementedTypes = new LinkedList<>();
static class ValueSet {
Map<String, String> value;
void set(Map<String, String> value) {
this.value = value;
}
Map<String, String> get() {
return requireNonNullElseGet(value, Collections::emptyMap);
}
void clear() {
this.value = null;
}
}
final ValueSet valueSet = new ValueSet();
protected SchemaReaderV3(String xmlns, XMLStreamReader reader, Map<String, Object> properties) {
super(xmlns, reader, properties);
}
public SchemaReaderV3(XMLStreamReader reader, Map<String, Object> properties) {
this(StaEDISchemaFactory.XMLNS_V3, reader, properties);
}
@Override
protected String readReferencedId(XMLStreamReader reader) {
String id = reader.getAttributeValue(null, "type");
if (id == null) {
id = reader.getAttributeValue(null, "ref");
if (id != null) {
Location parseLocation = reader.getLocation();
LOGGER.warning("Attribute 'ref' is deprecated at line "
+ parseLocation.getLineNumber()
+ ", column " + parseLocation.getColumnNumber());
}
}
return id;
}
@Override
protected void readInclude(XMLStreamReader reader, Map<String, EDIType> types) throws EDISchemaException {
// Included schema not supported in V3 Schema
throw unexpectedElement(reader.getName(), reader);
}
@Override
protected void readImplementation(XMLStreamReader reader, Map<String, EDIType> types) {
QName element = reader.getName();
if (qnImplementation.equals(element)) {
LoopImplementation impl = readImplementation(reader, element, types);
if (impl != null) {
types.put(StaEDISchema.IMPLEMENTATION_ID, impl);
}
nextTag(reader, "seeking next element after implementation end");
}
}
@Override
void setReferences(Map<String, EDIType> types) {
super.setReferences(types);
StreamSupport.stream(Spliterators.spliteratorUnknownSize(implementedTypes.descendingIterator(),
Spliterator.ORDERED),
false)
.filter(type -> type.getType() != Type.ELEMENT)
.map(BaseComplexImpl.class::cast)
.forEach(type -> setReferences(type, types));
}
void setReferences(BaseComplexImpl type, Map<String, EDIType> types) {
String typeId = type.getTypeId();
EDIComplexType standard = (EDIComplexType) types.get(typeId);
if (standard == null) {
throw schemaException("Type " + typeId + " does not correspond to a standard type");
}
List<EDIReference> standardRefs = standard.getReferences();
List<EDITypeImplementation> implSequence = type.getSequence();
if (implSequence.isEmpty()) {
implSequence.addAll(getDefaultSequence(standardRefs));
return;
}
AtomicBoolean verifyOrder = new AtomicBoolean(false);
implSequence.stream()
.filter(BaseImpl.class::isInstance)
.map(BaseImpl.class::cast)
.forEach(typeImpl -> {
if (typeImpl instanceof Positioned) {
typeImpl.setStandardReference(getReference((Positioned) typeImpl, standard));
} else {
typeImpl.setStandardReference(getReference(typeImpl, standard));
verifyOrder.set(true);
}
});
if (verifyOrder.get()) {
verifyOrder(standard, implSequence);
}
}
EDIReference getReference(Positioned positionedTypeImpl, EDIComplexType standard) {
final int position = positionedTypeImpl.getPosition();
final List<EDIReference> standardRefs = standard.getReferences();
final int offset = position - 1;
if (offset < standardRefs.size()) {
return standardRefs.get(offset);
} else {
throw schemaException("Position " + position + " does not correspond to an entry in type " + standard.getId());
}
}
EDIReference getReference(BaseImpl<?> typeImpl, EDIComplexType standard) {
final String refTypeId = typeImpl.getTypeId();
for (EDIReference stdRef : standard.getReferences()) {
if (stdRef.getReferencedType().getId().equals(refTypeId)) {
return stdRef;
}
}
throw schemaException("Reference " + refTypeId + " does not correspond to an entry in type " + standard.getId());
}
void verifyOrder(EDIComplexType standard, List<EDITypeImplementation> implSequence) {
Iterator<String> standardTypes = standard.getReferences()
.stream()
.map(EDIReference::getReferencedType)
.map(EDIType::getId)
.iterator();
String stdId = standardTypes.next();
for (EDITypeImplementation implRef : implSequence) {
String implId = implRef.getReferencedType().getId();
while (!implId.equals(stdId)) {
if (standardTypes.hasNext()) {
stdId = standardTypes.next();
} else {
String template = "%s reference %s is not in the correct order for the sequence of standard type %s";
throw schemaException(String.format(template, implRef.getType(), implRef.getCode(), standard.getId()));
}
}
}
}
List<EDITypeImplementation> getDefaultSequence(List<EDIReference> standardRefs) {
List<EDITypeImplementation> sequence = new ArrayList<>(standardRefs.size());
int position = 0;
for (EDIReference ref : standardRefs) {
sequence.add(getDefaultImplementation(ref, ++position));
}
return sequence;
}
EDITypeImplementation getDefaultImplementation(EDIReference standardReference, int position) {
EDIType std = standardReference.getReferencedType();
switch (std.getType()) {
case ELEMENT:
return new ElementImpl(standardReference, position);
case COMPOSITE:
return new CompositeImpl(standardReference, position, getDefaultSequence(((EDIComplexType) std).getReferences()));
case SEGMENT:
return new SegmentImpl(standardReference, getDefaultSequence(((EDIComplexType) std).getReferences()));
case LOOP:
return new LoopImpl(standardReference, getDefaultSequence(((EDIComplexType) std).getReferences()));
default:
throw schemaException("Implementation of " + std.getId() + " must not be empty");
}
}
LoopImplementation readImplementation(XMLStreamReader reader,
QName complexType,
Map<String, EDIType> types) {
LoopImplementation loop = readLoopImplementation(reader, complexType, true);
String typeId = StaEDISchema.TRANSACTION_ID;
EDIComplexType standard = (EDIComplexType) types.get(typeId);
LoopImpl impl = new TransactionImpl(StaEDISchema.IMPLEMENTATION_ID, typeId, loop.getSequence());
impl.setStandardReference(new Reference(standard, 1, 1));
implementedTypes.add(impl);
return impl;
}
LoopImplementation readLoopImplementation(XMLStreamReader reader, QName complexType, boolean transactionLoop) {
List<EDITypeImplementation> sequence = new ArrayList<>();
String id;
String typeId;
int minOccurs;
int maxOccurs;
EDIElementPosition discriminatorPos;
String title;
if (transactionLoop) {
id = StaEDISchema.IMPLEMENTATION_ID;
typeId = null;
minOccurs = 0;
maxOccurs = 0;
discriminatorPos = null;
title = null;
} else {
id = parseAttribute(reader, "code", String::valueOf);
typeId = parseAttribute(reader, "type", String::valueOf);
minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
discriminatorPos = parseElementPosition(reader, ATTR_DISCRIMINATOR);
title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
}
return readTypeImplementation(reader,
() -> readSequence(reader, e -> readLoopSequenceEntry(e, sequence)),
descr -> whenExpected(reader, complexType, () -> {
Discriminator disc = null;
if (discriminatorPos != null) {
SegmentImpl segImpl = (SegmentImpl) sequence.get(0);
disc = buildDiscriminator(discriminatorPos, segImpl.getSequence());
}
return new LoopImpl(minOccurs, maxOccurs, id, typeId, disc, sequence, title, descr);
}));
}
void readLoopSequenceEntry(QName entryName, List<EDITypeImplementation> sequence) {
if (entryName.equals(qnLoop)) {
if (sequence.isEmpty()) {
throw schemaException("segment element must be first child of loop sequence", reader);
}
LoopImplementation loop = readLoopImplementation(reader, entryName, false);
implementedTypes.add(loop);
sequence.add(loop);
} else if (entryName.equals(qnSegment)) {
sequence.add(readSegmentImplementation());
} else {
throw unexpectedElement(entryName, reader);
}
}
SegmentImpl readSegmentImplementation() {
List<EDITypeImplementation> sequence = new ArrayList<>();
String typeId = parseAttribute(reader, "type", String::valueOf);
String code = parseAttribute(reader, "code", String::valueOf, typeId);
int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
EDIElementPosition discriminatorPos = parseElementPosition(reader, ATTR_DISCRIMINATOR);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
return readTypeImplementation(reader,
() -> readSequence(reader, e -> readPositionedSequenceEntry(e, sequence, true)),
descr -> whenExpected(reader, qnSegment, () -> {
Discriminator disc = buildDiscriminator(discriminatorPos, sequence);
SegmentImpl segment = new SegmentImpl(minOccurs,
maxOccurs,
typeId,
code,
disc,
sequence,
title,
descr);
implementedTypes.add(segment);
return segment;
}));
}
void readPositionedSequenceEntry(QName entryName, List<EDITypeImplementation> sequence, boolean composites) {
EDITypeImplementation type;
if (entryName.equals(qnElement)) {
type = readElementImplementation(reader);
} else if (composites && entryName.equals(qnComposite)) {
type = readCompositeImplementation(reader);
} else {
throw unexpectedElement(entryName, reader);
}
implementedTypes.add(type);
int position = ((Positioned) type).getPosition();
while (position > sequence.size()) {
sequence.add(null);
}
EDITypeImplementation previous = sequence.set(position - 1, type);
if (previous != null) {
throw schemaException("Duplicate value for position " + position, reader);
}
}
Discriminator buildDiscriminator(EDIElementPosition discriminatorPos,
List<EDITypeImplementation> sequence) {
Discriminator disc = null;
if (discriminatorPos != null) {
final int elementPosition = discriminatorPos.getElementPosition();
final int componentPosition = discriminatorPos.getComponentPosition();
EDITypeImplementation eleImpl = getDiscriminatorElement(discriminatorPos, elementPosition, sequence, "element");
if (eleImpl instanceof CompositeImpl) {
sequence = ((CompositeImpl) eleImpl).getSequence();
eleImpl = getDiscriminatorElement(discriminatorPos, componentPosition, sequence, "component");
}
Set<String> discValues;
if (eleImpl != null) {
discValues = ((ElementImpl) eleImpl).getValueSet();
} else {
throw schemaException("Discriminator position is unused (not specified): " + discriminatorPos, reader);
}
if (!discValues.isEmpty()) {
disc = new DiscriminatorImpl(discriminatorPos, discValues);
} else {
throw schemaException("Discriminator element does not specify value enumeration: " + discriminatorPos, reader);
}
}
return disc;
}
EDITypeImplementation getDiscriminatorElement(EDIElementPosition discriminatorPos,
int position,
List<EDITypeImplementation> sequence,
String type) {
validatePosition(position, 1, sequence.size(), () -> "Discriminator " + type + " position invalid: " + discriminatorPos);
return sequence.get(position - 1);
}
CompositeImpl readCompositeImplementation(XMLStreamReader reader) {
List<EDITypeImplementation> sequence = new ArrayList<>(5);
int position = parseAttribute(reader, ATTR_POSITION, Integer::parseInt, -1);
int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
validatePosition(position, 1, Integer.MAX_VALUE, () -> "Invalid position");
return readTypeImplementation(reader,
() -> readSequence(reader, e -> readPositionedSequenceEntry(e, sequence, false)),
descr -> whenExpected(reader,
qnComposite,
() -> new CompositeImpl(minOccurs,
maxOccurs,
null,
position,
sequence,
title,
descr)));
}
void readSequence(XMLStreamReader reader, Consumer<QName> startHandler) {
requireElementStart(qnSequence, reader);
do {
if (nextTag(reader, "reading sequence") == XMLStreamConstants.START_ELEMENT) {
startHandler.accept(reader.getName());
}
} while (!reader.getName().equals(qnSequence));
}
ElementImpl readElementImplementation(XMLStreamReader reader) {
this.valueSet.clear();
int position = parseAttribute(reader, ATTR_POSITION, Integer::parseInt, -1);
int minOccurs = parseAttribute(reader, ATTR_MIN_OCCURS, Integer::parseInt, -1);
int maxOccurs = parseAttribute(reader, ATTR_MAX_OCCURS, Integer::parseInt, -1);
String title = parseAttribute(reader, ATTR_TITLE, String::valueOf, null);
validatePosition(position, 1, Integer.MAX_VALUE, () -> "Invalid position");
return readTypeImplementation(reader,
() -> valueSet.set(super.readEnumerationValues(reader)),
descr -> whenExpected(reader,
qnElement,
() -> new ElementImpl(minOccurs,
maxOccurs,
(String) null,
position,
valueSet.get(),
title,
descr)));
}
void validatePosition(int position, int min, int max, Supplier<String> message) {
if (position < min || position > max) {
throw schemaException(message.get(), reader);
}
}
<T> T whenExpected(XMLStreamReader reader, QName expected, Supplier<T> supplier) {
requireElement(expected, reader);
return supplier.get();
}
<T> T readTypeImplementation(XMLStreamReader reader, Runnable contentHandler, Function<String, T> endHandler) {
String descr = readDescription(reader);
if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
contentHandler.run();
} else {
return endHandler.apply(descr);
}
nextTag(reader, "reading type implementation end element");
requireEvent(XMLStreamConstants.END_ELEMENT, reader);
return endHandler.apply(descr);
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/ElementPosition.java | src/main/java/io/xlate/edi/internal/schema/ElementPosition.java | package io.xlate.edi.internal.schema;
import java.util.Objects;
import io.xlate.edi.schema.EDIElementPosition;
public class ElementPosition implements EDIElementPosition {
private static final String TOSTRING_FORMAT = "%d.%d";
final int elementIndex;
final int componentIndex;
public ElementPosition(int elementPosition, int componentPosition) {
super();
this.elementIndex = elementPosition;
this.componentIndex = componentPosition;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!getClass().isInstance(o)) {
return false;
}
ElementPosition other = (ElementPosition) o;
return Objects.equals(elementIndex, other.elementIndex) &&
Objects.equals(componentIndex, other.componentIndex);
}
@Override
public int hashCode() {
return Objects.hash(elementIndex, componentIndex);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, elementIndex, componentIndex);
}
@Override
public int getElementPosition() {
return elementIndex;
}
@Override
public int getComponentPosition() {
return componentIndex > 0 ? componentIndex : -1;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/SchemaReaderV4.java | src/main/java/io/xlate/edi/internal/schema/SchemaReaderV4.java | package io.xlate.edi.internal.schema;
import static io.xlate.edi.internal.schema.StaEDISchemaFactory.schemaException;
import java.net.URL;
import java.util.Map;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamReader;
import io.xlate.edi.schema.EDISchemaException;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.SchemaFactory;
public class SchemaReaderV4 extends SchemaReaderV3 {
private static final Logger LOGGER = Logger.getLogger(SchemaReaderV4.class.getName());
public SchemaReaderV4(XMLStreamReader reader, Map<String, Object> properties) {
super(StaEDISchemaFactory.XMLNS_V4, reader, properties);
}
@Override
void nameCheck(String name, Map<String, EDIType> types, XMLStreamReader reader) {
if (types.containsKey(name)) {
LOGGER.fine(() -> "Duplicate type name encountered: [" + name + ']');
}
}
@Override
protected String readReferencedId(XMLStreamReader reader) {
return parseAttribute(reader, "type", String::valueOf);
}
@Override
protected void readInclude(XMLStreamReader reader, Map<String, EDIType> types) throws EDISchemaException {
String location = parseAttribute(reader, "schemaLocation", String::valueOf);
URL context = null;
try {
if (properties.containsKey(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT)) {
Object ctx = properties.get(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT);
if (ctx instanceof URL) {
context = (URL) ctx;
} else {
context = new URL(String.valueOf(ctx));
}
}
URL schemaLocation;
if (location.startsWith("classpath:")) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (location.startsWith("classpath:/")) {
location = location.substring(0, "classpath:".length()) + location.substring("classpath:/".length());
}
schemaLocation = new URL(null, location, new ClasspathURLStreamHandler(loader));
} else {
schemaLocation = new URL(context, location);
}
types.putAll(StaEDISchemaFactory.readSchemaTypes(schemaLocation, super.properties));
reader.nextTag(); // End of include
} catch (Exception e) {
throw schemaException("Exception reading included schema", reader, e);
}
nextTag(reader, "seeking next element after include");
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/StaEDISchemaReadException.java | src/main/java/io/xlate/edi/internal/schema/StaEDISchemaReadException.java | package io.xlate.edi.internal.schema;
import javax.xml.stream.Location;
class StaEDISchemaReadException extends RuntimeException {
private static final long serialVersionUID = -5555580673080112522L;
protected final transient Location location;
public StaEDISchemaReadException(String message, Location location, Throwable cause) {
super(message, cause);
this.location = location;
}
public Location getLocation() {
return location;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/CompositeImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/CompositeImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.List;
import java.util.Objects;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.implementation.CompositeImplementation;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
public class CompositeImpl extends BaseComplexImpl implements CompositeImplementation, Positioned {
private static final String TOSTRING_FORMAT = "typeId: %s, minOccurs: %d, maxOccurs: %d, position: %d, sequence { %s }, standard: { %s }";
private final int position;
public CompositeImpl(int minOccurs,
int maxOccurs,
String typeId,
int position,
List<EDITypeImplementation> sequence,
String title,
String description) {
super(sequence, title, description);
super.minOccurs = minOccurs;
super.maxOccurs = maxOccurs;
super.typeId = typeId;
this.position = position;
}
public CompositeImpl(EDIReference standardReference, int position, List<EDITypeImplementation> sequence) {
super(sequence, null, null);
this.setStandardReference(standardReference);
this.position = position;
}
@Override
public boolean equals(Object o) {
return super.equals(o) &&
Objects.equals(position, ((CompositeImpl) o).position);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), position);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, typeId, minOccurs, maxOccurs, position, sequence, standard);
}
@Override
public int getPosition() {
return position;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/BaseImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/BaseImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.Objects;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDIType;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
public abstract class BaseImpl<T extends EDIType> implements EDITypeImplementation {
protected String typeId;
protected T standard;
protected int minOccurs = -1;
protected int maxOccurs = -1;
protected String title;
protected String description;
protected BaseImpl(String title, String description) {
super();
this.title = title;
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !getClass().isInstance(o)) {
return false;
}
@SuppressWarnings("unchecked")
BaseImpl<T> other = (BaseImpl<T>) o;
return Objects.equals(typeId, other.typeId) &&
Objects.equals(standard, other.standard) &&
Objects.equals(minOccurs, other.minOccurs) &&
Objects.equals(maxOccurs, other.maxOccurs) &&
Objects.equals(title, other.title) &&
Objects.equals(description, other.description);
}
@Override
public int hashCode() {
return Objects.hash(typeId, standard, minOccurs, maxOccurs, title, description);
}
@Override
public String getId() {
return typeId;
}
@Override
public String getCode() {
return typeId;
}
@Override
public EDIType getReferencedType() {
return getStandard();
}
@Override
public int getMinOccurs() {
return minOccurs;
}
@Override
public int getMaxOccurs() {
return maxOccurs;
}
@Override
public String getTitle() {
return title;
}
@Override
public String getDescription() {
return description;
}
public String getTypeId() {
return typeId;
}
public T getStandard() {
return standard;
}
@SuppressWarnings("unchecked")
public void setStandardReference(EDIReference reference) {
this.standard = (T) reference.getReferencedType();
if (this.typeId == null) {
this.typeId = standard.getId();
}
if (this.minOccurs < 0) {
this.minOccurs = reference.getMinOccurs();
}
if (this.maxOccurs < 0) {
this.maxOccurs = reference.getMaxOccurs();
}
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/package-info.java | src/main/java/io/xlate/edi/internal/schema/implementation/package-info.java | package io.xlate.edi.internal.schema.implementation;
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/SegmentImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/SegmentImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.List;
import java.util.Objects;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.implementation.Discriminator;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.schema.implementation.SegmentImplementation;
public class SegmentImpl extends BaseComplexImpl implements SegmentImplementation {
private static final String TOSTRING_FORMAT = "typeId: %s, code: %s, minOccurs: %d, maxOccurs: %d, discriminator: { %s }, sequence { %s }, standard: { %s }";
private final String code;
private final Discriminator discriminator;
@SuppressWarnings("java:S107")
public SegmentImpl(int minOccurs,
int maxOccurs,
String typeId,
String code,
Discriminator discriminator,
List<EDITypeImplementation> sequence,
String title,
String description) {
super(sequence, title, description);
super.minOccurs = minOccurs;
super.maxOccurs = maxOccurs;
super.typeId = typeId;
this.code = code;
this.discriminator = discriminator;
}
public SegmentImpl(EDIReference standardReference, List<EDITypeImplementation> sequence) {
super(sequence, null, null);
this.setStandardReference(standardReference);
this.code = standard.getCode();
this.discriminator = null;
}
@Override
public boolean equals(Object o) {
return super.equals(o) &&
Objects.equals(code, ((SegmentImpl) o).code) &&
Objects.equals(discriminator, ((SegmentImpl) o).discriminator);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), code, discriminator);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, typeId, code, minOccurs, maxOccurs, discriminator, sequence, standard);
}
@Override
public String getCode() {
return code;
}
@Override
public Discriminator getDiscriminator() {
return discriminator;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/TransactionImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/TransactionImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.List;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
public class TransactionImpl extends LoopImpl {
public TransactionImpl(String id,
String typeId,
List<EDITypeImplementation> sequence) {
super(0, 0, id, typeId, null, sequence, null, null);
}
@Override
public Type getType() {
return Type.TRANSACTION;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/ElementImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/ElementImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDISimpleType;
import io.xlate.edi.schema.implementation.ElementImplementation;
public class ElementImpl extends BaseImpl<EDISimpleType> implements ElementImplementation, Positioned {
private static final String TOSTRING_FORMAT = "typeId: %s, minOccurs: %d, maxOccurs: %d, position: %d, values: %s, standard: { %s }";
private final int position;
private final Map<String, String> values;
public ElementImpl(int minOccurs,
int maxOccurs,
String typeId,
int position,
Map<String, String> values,
String title,
String description) {
super(title, description);
super.minOccurs = minOccurs;
super.maxOccurs = maxOccurs;
super.typeId = typeId;
this.position = position;
this.values = Collections.unmodifiableMap(new LinkedHashMap<>(values));
}
public ElementImpl(EDIReference standardReference, int position) {
super(null, null);
this.setStandardReference(standardReference);
this.typeId = standard.getId();
this.position = position;
this.values = standard.getValues();
}
@Override
public boolean equals(Object o) {
return super.equals(o) &&
Objects.equals(position, ((ElementImpl) o).position) &&
Objects.equals(values, ((ElementImpl) o).values);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), position, values);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, typeId, minOccurs, maxOccurs, position, values, standard);
}
@Override
public Map<String, String> getValues() {
return values;
}
@Override
public int getPosition() {
return position;
}
@Override
public Base getBase() {
return standard.getBase();
}
/**
* @see io.xlate.edi.schema.EDISimpleType#getNumber()
* @deprecated
*/
@SuppressWarnings({ "java:S1123", "java:S1133" })
@Override
@Deprecated
public int getNumber() {
return standard.getNumber();
}
@Override
public long getMinLength() {
return standard.getMinLength();
}
@Override
public long getMaxLength() {
return standard.getMaxLength();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/BaseComplexImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/BaseComplexImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.List;
import java.util.Objects;
import io.xlate.edi.schema.EDIComplexType;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
public abstract class BaseComplexImpl extends BaseImpl<EDIComplexType> {
protected final List<EDITypeImplementation> sequence;
protected BaseComplexImpl(List<EDITypeImplementation> sequence, String title, String description) {
super(title, description);
this.sequence = sequence;
}
@Override
public boolean equals(Object o) {
return super.equals(o) && Objects.equals(sequence, ((BaseComplexImpl) o).sequence);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sequence);
}
public List<EDITypeImplementation> getSequence() {
return sequence;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/Positioned.java | src/main/java/io/xlate/edi/internal/schema/implementation/Positioned.java | package io.xlate.edi.internal.schema.implementation;
public interface Positioned {
int getPosition();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/DiscriminatorImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/DiscriminatorImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.Objects;
import java.util.Set;
import io.xlate.edi.schema.EDIElementPosition;
import io.xlate.edi.schema.implementation.Discriminator;
public class DiscriminatorImpl implements Discriminator {
private static final String TOSTRING_FORMAT = "position: %s, values: %s";
final EDIElementPosition position;
final Set<String> valueSet;
public DiscriminatorImpl(EDIElementPosition position, Set<String> valueSet) {
this.position = position;
this.valueSet = valueSet;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DiscriminatorImpl)) {
return false;
}
DiscriminatorImpl other = (DiscriminatorImpl) o;
return Objects.equals(position, other.position) &&
Objects.equals(valueSet, other.valueSet);
}
@Override
public int hashCode() {
return Objects.hash(position, valueSet);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, position, valueSet);
}
@Override
public int getElementPosition() {
return position.getElementPosition();
}
@Override
public int getComponentPosition() {
return position.getComponentPosition();
}
@Override
public Set<String> getValueSet() {
return valueSet;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/schema/implementation/LoopImpl.java | src/main/java/io/xlate/edi/internal/schema/implementation/LoopImpl.java | package io.xlate.edi.internal.schema.implementation;
import java.util.List;
import java.util.Objects;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.implementation.Discriminator;
import io.xlate.edi.schema.implementation.EDITypeImplementation;
import io.xlate.edi.schema.implementation.LoopImplementation;
public class LoopImpl extends BaseComplexImpl implements LoopImplementation {
private static final String TOSTRING_FORMAT = "id: %s, minOccurs: %d, maxOccurs: %d, discriminator: { %s }, sequence { %s }, standard: { %s }";
private final String code;
private final Discriminator discriminator;
@SuppressWarnings("java:S107")
public LoopImpl(int minOccurs,
int maxOccurs,
String code,
String typeId,
Discriminator discriminator,
List<EDITypeImplementation> sequence,
String title,
String description) {
super(sequence, title, description);
this.minOccurs = minOccurs;
this.maxOccurs = maxOccurs;
this.code = code;
this.typeId = typeId;
this.discriminator = discriminator;
}
public LoopImpl(EDIReference standardReference, List<EDITypeImplementation> sequence) {
super(sequence, null, null);
this.setStandardReference(standardReference);
this.code = standard.getCode();
this.discriminator = null;
}
@Override
public boolean equals(Object o) {
return super.equals(o) &&
Objects.equals(code, ((LoopImpl) o).code) &&
Objects.equals(discriminator, ((LoopImpl) o).discriminator);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), code, discriminator);
}
@Override
public String toString() {
return String.format(TOSTRING_FORMAT, code, minOccurs, maxOccurs, discriminator, sequence, standard);
}
@Override
public String getId() {
return getCode();
}
@Override
public String getCode() {
return code;
}
@Override
public Discriminator getDiscriminator() {
return discriminator;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDIControlType.java | src/main/java/io/xlate/edi/schema/EDIControlType.java | package io.xlate.edi.schema;
/**
* Provides access to attributes specified for a control structure complex type
* such as the interchange, group, and transaction envelope structures.
*
* @since 1.21
*/
public interface EDIControlType extends EDIComplexType {
public enum Type {
/**
* Nothing will be counted or validated
*/
NONE,
/**
* Indicates that the element identified by {@link EDIControlType#getTrailerCountPosition()} will
* contain a count of the control structures internal to the {@link EDIControlType}.
*/
CONTROLS,
/**
* Indicates that the element identified by {@link EDIControlType#getTrailerCountPosition()} will
* contain a count of the segments within the {@link EDIControlType}, <em>including</em> the header
* and trailer segments.
*/
SEGMENTS;
public static Type fromString(String value) {
for (Type entry : values()) {
if (entry.name().equalsIgnoreCase(value)) {
return entry;
}
}
throw new IllegalArgumentException("No enum constant for " + Type.class.getName() + "." + value);
}
}
/**
* Get the position of the element within the header segment that is used as
* the control reference/number for the envelope.
*
* @return the position of the element holding the structure's header
* control reference
*/
EDIElementPosition getHeaderRefPosition();
/**
* Get the position of the element within the trailer segment that is used as
* the control reference/number for the envelope.
*
* @return the position of the element holding the structure's trailer
* control reference
*/
EDIElementPosition getTrailerRefPosition();
/**
* Get the position of the element within the trailer segment that is used as
* the control count for the envelope. The actual structures counted are determined
* by the value returned by {@link #getCountType()}.
*
* @return the position of the element holding the structure's trailer
* control count
*/
EDIElementPosition getTrailerCountPosition();
/**
* Get the type of structures
*
* @return the type of count
*/
Type getCountType();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDIComplexType.java | src/main/java/io/xlate/edi/schema/EDIComplexType.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
import java.util.List;
/**
* An interface representing the schema of an EDI complex type such as a loop,
* segment, or composite element.
*/
public interface EDIComplexType extends EDIType {
/**
* Retrieve the {@link EDIReference}s (child elements) for a this complex
* type.
*
* @return the references (child elements) without regard to version
*/
List<EDIReference> getReferences();
/**
* Retrieve the {@link EDISyntaxRule}s associated with this EDIComplexType.
*
* @return a list of associated {@link EDISyntaxRule}s
*/
List<EDISyntaxRule> getSyntaxRules();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDISyntaxRule.java | src/main/java/io/xlate/edi/schema/EDISyntaxRule.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
import java.util.List;
public interface EDISyntaxRule {
public enum Type {
/**
* X12: N/A
* EDIFACT: (D1) One and only one
*/
SINGLE,
/**
* X12: Type P
* EDIFACT: (D2) All or none
*/
PAIRED,
/**
* X12: Type R
* EDIFACT: (D3) One or more
*/
REQUIRED,
/**
* X12: Type E
* EDIFACT: (D4) One or none
*/
EXCLUSION,
/**
* X12: Type C
* EDIFACT: (D5) If first, then all
*/
CONDITIONAL,
/**
* X12: Type L
* EDIFACT: (D6) If first, then at least one more
*/
LIST,
/**
* X12: N/A
* EDIFACT: (D7) If first, then none of the others
*/
FIRSTONLY;
public static Type fromString(String value) {
for (Type entry : values()) {
if (entry.name().equalsIgnoreCase(value)) {
return entry;
}
}
throw new IllegalArgumentException("No enum constant for " + Type.class.getName() + "." + value);
}
}
Type getType();
List<Integer> getPositions();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDISchemaException.java | src/main/java/io/xlate/edi/schema/EDISchemaException.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
import javax.xml.stream.Location;
public class EDISchemaException extends Exception {
private static final long serialVersionUID = -1232370584780899896L;
protected final transient Location location;
protected final String message;
/**
* Construct an exception with the associated message.
*
* @param message
* the message to report
*/
public EDISchemaException(String message) {
super(message);
this.location = null;
this.message = message;
}
/**
* Construct an exception with the associated message and exception
*
* @param cause
* a nested exception
* @param message
* the message to report
*/
public EDISchemaException(String message, Throwable cause) {
super(message, cause);
this.location = null;
this.message = message;
}
/**
* Construct an exception with the associated message, exception and
* location.
*
* @param message
* the message to report
* @param location
* the location of the error
* @param cause
* a nested exception
*/
public EDISchemaException(String message, Location location, Throwable cause) {
super("EDISchemaException at [row,col]:[" + location.getLineNumber()
+ "," + location.getColumnNumber() + "];" + "Message: "
+ message,
cause);
this.location = location;
this.message = message;
}
/**
* Gets the location of the exception
*
* @return the location of the exception, may be null if none is available
*/
public Location getLocation() {
return location;
}
public String getOriginalMessage() {
return this.message;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/Schema.java | src/main/java/io/xlate/edi/schema/Schema.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
import io.xlate.edi.schema.implementation.LoopImplementation;
public interface Schema extends Iterable<EDIType> {
/**
* Retrieve the {@link EDIComplexType} that is the entry point of the
* standard schema.
*
* @return the standard schema root type
*
* @deprecated use {@link #getStandard()} instead
*/
@SuppressWarnings({ "java:S1123", "java:S1133" })
@Deprecated /*(forRemoval = true, since = "1.2")*/
default EDIComplexType getMainLoop() {
return getStandard();
}
/**
* Retrieve the {@link EDIComplexType} that is the entry point of the
* standard schema.
*
* @return the standard schema root type
*
*/
EDIComplexType getStandard();
/**
* Retrieve the {@link LoopImplementation} that is the entry point of the
* implementation schema.
*
* @return the implementation schema root type
*
*/
LoopImplementation getImplementation();
/**
* Retrieve an {@link EDIType} by name.
*
* @param name name of the type (e.g. segment tag or an element's unique identifier)
* @return the type having the name requested, null if not present in this schema.
*/
EDIType getType(String name);
/**
* Determine if the named segment is present in this schema.
*
* @param name segment tag
* @return true if a segment with the given name is present, otherwise false
*/
boolean containsSegment(String name);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDISimpleType.java | src/main/java/io/xlate/edi/schema/EDISimpleType.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
import java.util.Map;
import java.util.Set;
/**
* An interface representing the schema of an EDI simple type, AKA an element.
*/
public interface EDISimpleType extends EDIType {
public enum Base {
STRING,
NUMERIC,
DECIMAL,
DATE,
TIME,
BINARY,
IDENTIFIER;
public static Base fromString(String value) {
for (Base entry : values()) {
if (entry.name().equalsIgnoreCase(value)) {
return entry;
}
}
throw new IllegalArgumentException("No enum constant for " + Base.class.getName() + "." + value);
}
}
Base getBase();
/**
* Returns the <i>scale</i> of this {@code EDISimpleType} when the
* <i>base</i> is <i>NUMERIC</i>. The scale is the number of digits to the
* right of an implied decimal point.
*
* @return the scale of this {@code EDISimpleType} if <i>NUMERIC</i>,
* otherwise null.
*
* @since 1.13
*/
default Integer getScale() {
return null;
}
/**
* Returns true if this element has additional version(s) defined beyond the
* default. Versions may be used to specify different minimum/maximum length
* restrictions or enumerated values that only apply to specific versions a
* transaction.
*
* @return true if this element has version(s), otherwise false
*
* @since 1.8
*/
default boolean hasVersions() {
return false;
}
/**
* Retrieve the element reference number for this type.
*
* @return the element reference number as declared in the EDI schema, or
* <code>-1</code> if not declared
*
* @deprecated (since 1.8, for removal) use {@link #getCode()} and
* <code>code</code> attribute instead
*/
@SuppressWarnings({ "java:S1123", "java:S1133" })
@Deprecated /*(forRemoval = true, since = "1.8")*/
int getNumber();
/**
* Retrieve the minLength attribute of the element.
*
* @return the minLength attribute
*/
long getMinLength();
/**
* Retrieve the minLength attribute for a particular version of the element.
*
* The default implementation returns the default (un-versioned) value for
* the element.
*
* @param version
* the version to select
* @return the minLength attribute for version
*
* @since 1.8
*/
default long getMinLength(String version) {
return getMinLength();
}
/**
* Retrieve the maxLength attribute of the element.
*
* @return the maxLength attribute
*/
long getMaxLength();
/**
* Retrieve the maxLength attribute for a particular version of the element.
*
* The default implementation returns the default (un-versioned) value for
* the element.
*
* @param version
* the version to select
* @return the maxLength attribute for version
*
* @since 1.8
*/
default long getMaxLength(String version) {
return getMaxLength();
}
/**
* Retrieve the set of enumerated values allowed for this element.
*
* @return the set of enumerated values allowed for this element
*/
default Set<String> getValueSet() {
return getValues().keySet();
}
/**
* Retrieve the set of enumerated values allowed for this element for a
* particular version of the element.
*
* The default implementation returns the default (un-versioned) value for
* the element.
*
* @param version
* the version to select
* @return the set of enumerated values allowed for this element for the
* given version
*
* @since 1.8
*/
default Set<String> getValueSet(String version) {
return getValues(version).keySet();
}
/**
* Retrieve the mapping of enumerated values allowed for this element with
* the associated title values.
*
* @return the map of enumerated values and titles allowed for this element
*
* @since 1.22
*/
Map<String, String> getValues();
/**
* Retrieve the mapping of enumerated values allowed for this element with
* the associated title values for a particular version of the element.
*
* The default implementation returns the default (un-versioned) values for
* the element.
*
* @param version
* the version to select
* @return the map of enumerated values and titles allowed for this element
* for the given version
*
* @since 1.22
*/
default Map<String, String> getValues(String version) {
return getValues();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDIReference.java | src/main/java/io/xlate/edi/schema/EDIReference.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
public interface EDIReference {
EDIType getReferencedType();
int getMinOccurs();
int getMaxOccurs();
/**
* Returns true if this element has additional version(s) defined beyond the
* default. Versions may be used to specify different minimum/maximum
* occurrence restrictions that only apply to specific versions of a
* transaction.
*
* @return true if this element has version(s), otherwise false
*
* @since 1.8
*/
default boolean hasVersions() {
return false;
}
/**
* Retrieve the minOccurs attribute for a particular version of the element.
*
* The default implementation returns the default (un-versioned) value for
* the element.
*
* @param version
* the version to select
* @return the minOccurs attribute for version
*
* @since 1.8
*/
default int getMinOccurs(String version) {
return getMinOccurs();
}
/**
* Retrieve the maxOccurs attribute for a particular version of the element.
*
* The default implementation returns the default (un-versioned) value for
* the element.
*
* @param version
* the version to select
* @return the maxOccurs attribute for version
*
* @since 1.8
*/
default int getMaxOccurs(String version) {
return getMaxOccurs();
}
/**
* Retrieve the title for this reference, if available.
*
* @return the reference's title
*
* @since 1.10
*/
String getTitle();
/**
* Retrieve the description for this reference, if available.
*
* @return the reference's description
*
* @since 1.10
*/
String getDescription();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDIElementPosition.java | src/main/java/io/xlate/edi/schema/EDIElementPosition.java | package io.xlate.edi.schema;
import io.xlate.edi.stream.Location;
/**
* Specification of the position of an element. Provides information about the
* element position within a segment and (optionally) a component element
* position within a composite element.
*
* @since 1.18
* @see io.xlate.edi.schema.implementation.Discriminator
*/
public interface EDIElementPosition {
/**
* Get the element position within a segment.
*
* @return the element position within a segment
*/
int getElementPosition();
/**
* Get the component position within a composite element. Returns -1 if not
* available.
*
* @return the component position with a composite element or -1
*/
int getComponentPosition();
/**
* Determine if the given location's element and component matches this
* element position specification.
*
* @param location
* the location to match against this position
* @return true if the element and component positions match, otherwise
* false
*/
default boolean matchesLocation(Location location) {
return location.getElementPosition() == getElementPosition()
&& location.getComponentPosition() == getComponentPosition();
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDILoopType.java | src/main/java/io/xlate/edi/schema/EDILoopType.java | package io.xlate.edi.schema;
/**
* Provides access to attributes specified for a loop complex type.
*
* @since 1.18
*/
public interface EDILoopType extends EDIComplexType {
/**
* For hierarchical loops, get the position of the element within the first
* segment that identifies the loop. If not a hierarchical loop, null is
* returned.
*
* @return the position of the element holding the loop's level ID
*/
EDIElementPosition getLevelIdPosition();
/**
* For hierarchical loops, get the position of the element within the first
* segment that identifies the parent of the loop. If not a hierarchical
* loop, null is returned.
*
* @return the position of the element holding the loop's parent level ID
*/
EDIElementPosition getParentIdPosition();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/EDIType.java | src/main/java/io/xlate/edi/schema/EDIType.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
public interface EDIType {
public enum Type {
INTERCHANGE,
GROUP,
TRANSACTION,
LOOP,
SEGMENT,
COMPOSITE,
ELEMENT;
}
String getId();
String getCode();
Type getType();
default boolean isType(Type type) {
return getType() == type;
}
/**
* Retrieve the title for this type, if available.
*
* @return the type's title
*
* @since 1.10
*/
String getTitle();
/**
* Retrieve the description for this type, if available.
*
* @return the type's description
*
* @since 1.10
*/
String getDescription();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/SchemaFactory.java | src/main/java/io/xlate/edi/schema/SchemaFactory.java | /*******************************************************************************
* Copyright 2017 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema;
import java.io.InputStream;
import java.net.URL;
@SuppressWarnings("java:S1214") // Allow constant string value to be used in this interface
public interface SchemaFactory {
/**
* Property key for a URL (<code>java.lang.String</code> or
* <code>java.net.URL</code>) to be used with relative file URLs in
* <code><include schemaLocation="..."></code> element/attributes
* processed by a SchemaFactory. Besides a java.net.URL, any class with a
* toString method that returns a valid URL-formated String may be used as
* the value for this property.
*
* @since 1.8
*/
public static final String SCHEMA_LOCATION_URL_CONTEXT = "io.xlate.edi.schema.SCHEMA_LOCATION_URL_CONTEXT";
/**
* Create a new instance of the factory. This static method creates a new
* factory instance.
*
* Once an application has obtained a reference to an EDIOutputFactory it
* can use the factory to configure and obtain stream instances.
*
* @return the factory implementation
*/
public static SchemaFactory newFactory() {
return new io.xlate.edi.internal.schema.StaEDISchemaFactory();
}
public abstract Schema createSchema(URL location) throws EDISchemaException;
public abstract Schema createSchema(InputStream stream) throws EDISchemaException;
/**
* Retrieve the control schema for the provided standard and version. This
* method loads an internal, immutable schema provided by StAEDI.
*
* @param standard
* the standard, e.g. X12 or EDIFACT
* @param version
* the version of the standard
* @return the control schema corresponding to the standard and version
* @throws EDISchemaException
* when the schema can not be loaded.
*
* @since 1.5
*/
public Schema getControlSchema(String standard, String[] version) throws EDISchemaException;
/**
* Query the set of properties that this factory supports.
*
* @param name
* - The name of the property (may not be null)
* @return true if the property is supported and false otherwise
*/
public abstract boolean isPropertySupported(String name);
/**
* Get the value of a feature/property from the underlying implementation
*
* @param name
* - The name of the property (may not be null)
* @return The value of the property
* @throws IllegalArgumentException
* if the property is not supported
*/
public abstract Object getProperty(String name);
/**
* Allows the user to set specific feature/property on the underlying
* implementation. The underlying implementation is not required to support
* every setting of every property in the specification and may use
* IllegalArgumentException to signal that an unsupported property may not
* be set with the specified value.
*
* @param name
* - The name of the property (may not be null)
* @param value
* - The value of the property
* @throws IllegalArgumentException
* if the property is not supported
*/
public abstract void setProperty(String name, Object value);
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/SegmentImplementation.java | src/main/java/io/xlate/edi/schema/implementation/SegmentImplementation.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema.implementation;
public interface SegmentImplementation extends PolymorphicImplementation {
@Override
default Type getType() {
return Type.SEGMENT;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/package-info.java | src/main/java/io/xlate/edi/schema/implementation/package-info.java | package io.xlate.edi.schema.implementation;
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/ElementImplementation.java | src/main/java/io/xlate/edi/schema/implementation/ElementImplementation.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema.implementation;
import io.xlate.edi.schema.EDISimpleType;
public interface ElementImplementation extends EDITypeImplementation, EDISimpleType {
@Override
default Type getType() {
return Type.ELEMENT;
}
@Override
default boolean hasVersions() {
return false;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/EDITypeImplementation.java | src/main/java/io/xlate/edi/schema/implementation/EDITypeImplementation.java | package io.xlate.edi.schema.implementation;
import io.xlate.edi.schema.EDIReference;
import io.xlate.edi.schema.EDIType;
public interface EDITypeImplementation extends EDIReference, EDIType {
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/LoopImplementation.java | src/main/java/io/xlate/edi/schema/implementation/LoopImplementation.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema.implementation;
public interface LoopImplementation extends PolymorphicImplementation {
@Override
default Type getType() {
return Type.LOOP;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/PolymorphicImplementation.java | src/main/java/io/xlate/edi/schema/implementation/PolymorphicImplementation.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema.implementation;
import java.util.List;
public interface PolymorphicImplementation extends EDITypeImplementation {
Discriminator getDiscriminator();
List<EDITypeImplementation> getSequence();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/CompositeImplementation.java | src/main/java/io/xlate/edi/schema/implementation/CompositeImplementation.java | /*******************************************************************************
* Copyright 2020 xlate.io LLC, http://www.xlate.io
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package io.xlate.edi.schema.implementation;
import java.util.List;
public interface CompositeImplementation extends EDITypeImplementation {
List<EDITypeImplementation> getSequence();
@Override
default Type getType() {
return Type.COMPOSITE;
}
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
xlate/staedi | https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/schema/implementation/Discriminator.java | src/main/java/io/xlate/edi/schema/implementation/Discriminator.java | package io.xlate.edi.schema.implementation;
import java.util.Set;
import io.xlate.edi.schema.EDIElementPosition;
public interface Discriminator extends EDIElementPosition {
Set<String> getValueSet();
}
| java | Apache-2.0 | c23c1fd73e63f17e9b124a3e0c50959d5be83e46 | 2026-01-05T02:37:40.525758Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/src/test/java/com/virtuslab/archunit/BaseArchUnitTestSuite.java | src/test/java/com/virtuslab/archunit/BaseArchUnitTestSuite.java | package com.virtuslab.archunit;
import java.util.function.BiPredicate;
import com.tngtech.archunit.core.domain.AccessTarget;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.JavaCodeUnit;
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
import io.vavr.collection.List;
import io.vavr.control.Option;
import lombok.val;
public class BaseArchUnitTestSuite {
protected static final JavaClasses productionClasses = new ClassFileImporter()
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
.importPackages("com.virtuslab");
protected static ArchCondition<JavaCodeUnit> callAnyCodeUnitsThat(String description,
BiPredicate<? super JavaCodeUnit, AccessTarget.CodeUnitCallTarget> predicate) {
return new ArchCondition<JavaCodeUnit>("call code units that " + description) {
@Override
public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
codeUnit.getCallsFromSelf().forEach(call -> {
val callTarget = call.getTarget();
if (predicate.test(codeUnit, callTarget)) {
String message = codeUnit.getFullName() + " calls " + callTarget.getFullName();
events.add(SimpleConditionEvent.satisfied(codeUnit, message));
}
});
}
};
}
protected static ArchCondition<JavaCodeUnit> callAtLeastOnceACodeUnitThat(String description,
BiPredicate<? super JavaCodeUnit, AccessTarget.CodeUnitCallTarget> predicate) {
return new ArchCondition<JavaCodeUnit>("call a code unit that " + description) {
@Override
public void check(JavaCodeUnit codeUnit, ConditionEvents events) {
if (codeUnit.getCallsFromSelf().stream().noneMatch(call -> predicate.test(codeUnit, call.getTarget()))) {
String message = "code unit ${codeUnit.getFullName()} does not call any code unit that " + description;
events.add(SimpleConditionEvent.violated(codeUnit, message));
}
}
};
}
protected static ArchCondition<JavaMethod> overrideAnyMethodThat(String description,
BiPredicate<JavaMethod, JavaMethod> predicate) {
return new ArchCondition<JavaMethod>("override any method that " + description) {
@Override
public void check(JavaMethod method, ConditionEvents events) {
JavaClass owner = method.getOwner();
val superTypes = List.ofAll(owner.getAllRawInterfaces()).appendAll(owner.getAllRawSuperclasses());
val paramTypeNames = method.getParameters().stream().map(p -> p.getRawType().getFullName()).toArray(String[]::new);
val overriddenMethods = superTypes
.flatMap(s -> Option.ofOptional(s.tryGetMethod(method.getName(), paramTypeNames)));
for (val overriddenMethod : overriddenMethods) {
if (predicate.test(method, overriddenMethod)) {
String message = method.getFullName() + " overrides " + overriddenMethod.getFullName();
events.add(SimpleConditionEvent.satisfied(method, message));
}
}
}
};
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/src/test/java/com/virtuslab/archunit/ClassStructureTestSuite.java | src/test/java/com/virtuslab/archunit/ClassStructureTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.core.domain.JavaModifier.ABSTRACT;
import static com.tngtech.archunit.core.domain.JavaModifier.SYNTHETIC;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathFactory;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaAccess;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaConstructorCall;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Test;
public class ClassStructureTestSuite extends BaseArchUnitTestSuite {
@Test
public void abstract_classes_should_not_declare_LOG_field() {
classes()
.that()
.haveModifier(ABSTRACT)
.should(new ArchCondition<JavaClass>("not declare a LOG field, but use log() abstract method instead") {
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
// Using getFields() and not getAllFields() to only check declared members.
// We don't care about potential private logger fields from superclasses.
javaClass.getFields().forEach(field -> {
if (field.getName().equals("LOG")) {
String message = javaClass.getFullName() + " should use `abstract Logger log()` instead of `LOG` field";
events.add(SimpleConditionEvent.violated(javaClass, message));
}
});
}
})
.because("the SLF4J logger name should reflect the name of the concrete class, not an abstract base")
.check(productionClasses);
}
@Test
public void actions_implementing_DumbAware_should_extend_DumbAwareAction() {
classes()
.that().areAssignableTo(com.intellij.openapi.actionSystem.AnAction.class)
.and().implement(com.intellij.openapi.project.DumbAware.class)
.should().beAssignableTo(com.intellij.openapi.project.DumbAwareAction.class)
.because("`extends DumbAwareAction` should be used instead of " +
"extending `AnAction` and implementing `DumbAware` separately")
.check(productionClasses);
}
static class BeReferencedFromOutsideItself extends ArchCondition<JavaClass> {
BeReferencedFromOutsideItself() {
super("be referenced from some other class");
}
@Override
public void check(JavaClass javaClass, ConditionEvents events) {
Set<JavaAccess<?>> accessesFromOtherClasses = new HashSet<>(javaClass.getAccessesToSelf());
accessesFromOtherClasses.removeAll(javaClass.getAccessesFromSelf());
if (accessesFromOtherClasses.isEmpty() && javaClass.getDirectDependenciesToSelf().isEmpty()) {
String message = javaClass.getDescription() + " is NOT referenced from any other class";
events.add(SimpleConditionEvent.violated(javaClass, message));
}
}
}
@SneakyThrows
private Set<Class<?>> extractAllClassesReferencedFromPluginXmlAttributes() {
Set<Class<?>> result = new HashSet<>();
val classLoader = Thread.currentThread().getContextClassLoader();
val documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Note that there might be multiple plugin.xml files on the classpath,
// not only from our plugin, but also from the dependencies.
val resourceUrls = classLoader.getResources("META-INF/plugin.xml");
while (resourceUrls.hasMoreElements()) {
val resourceUrl = resourceUrls.nextElement();
try (val inputStream = resourceUrl.openStream()) {
val document = documentBuilder.parse(inputStream);
val xPathfactory = XPathFactory.newInstance();
val xpath = xPathfactory.newXPath();
val expr = xpath.compile("//idea-plugin/id/text()");
// Let's check if the given plugin.xml corresponds to our plugin, or to one of dependencies.
if (!expr.evaluate(document).equals("com.virtuslab.git-machete"))
continue;
val nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
val node = nodeList.item(i);
val attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
val attribute = attributes.item(j);
val maybeFqcn = attribute.getNodeValue();
try {
val clazz = Class.forName(maybeFqcn, /* initialize */ false, classLoader);
result.add(clazz);
} catch (ClassNotFoundException e) {
// Not all XML attributes found in plugin.xml correspond to class names,
// let's ignore those that don't.
}
}
}
}
}
return result;
}
@Test
public void all_classes_should_be_referenced() {
val classesReferencedFromPluginXmlAttributes = extractAllClassesReferencedFromPluginXmlAttributes().toArray(Class[]::new);
classes()
.that().doNotHaveModifier(SYNTHETIC)
// For some reason, ArchUnit (com.tngtech.archunit.core.domain.JavaClass.getAccessesFromSelf)
// doesn't see accesses to static fields
.and().resideOutsideOfPackages("com.virtuslab.gitmachete.frontend.defs")
.and().doNotBelongToAnyOf(classesReferencedFromPluginXmlAttributes)
// SubtypingBottom is processed by CheckerFramework based on its annotations
.and().doNotHaveFullyQualifiedName(com.virtuslab.qual.subtyping.internal.SubtypingBottom.class.getName())
.should(new BeReferencedFromOutsideItself())
.check(productionClasses);
}
@Test
public void inner_classes_should_not_be_instantiated_from_constructor_of_enclosing_class() {
noClasses()
.that()
.doNotHaveFullyQualifiedName(com.virtuslab.gitmachete.frontend.actions.dialogs.GitPushDialog.class.getName())
.and()
.doNotHaveFullyQualifiedName(com.virtuslab.gitmachete.frontend.ui.impl.root.GitMachetePanel.class.getName())
.and()
.doNotHaveFullyQualifiedName(com.virtuslab.gitmachete.frontend.actions.dialogs.SlideInDialog.class.getName())
.should()
.callConstructorWhere(
new DescribedPredicate<JavaConstructorCall>(
"an inner class is instantiated in a constructor of the enclosing class") {
@Override
public boolean test(JavaConstructorCall input) {
if (input.getOrigin().isConstructor()) {
JavaClass constructingClass = input.getOriginOwner();
JavaClass constructedClass = input.getTargetOwner();
JavaClass parentOfConstructedClass = constructedClass.getEnclosingClass().orElse(null);
return constructedClass.isInnerClass() && parentOfConstructedClass == constructingClass;
} else {
return false;
}
}
})
.because("the enclosing object might not be fully initialized yet when it's passed to inner class constructor. " +
"See https://github.com/typetools/checker-framework/issues/3407 for details. " +
"Consider using a static nested class " +
"and passing a reference to the enclosing object (or to the fields thereof) explicitly")
.check(productionClasses);
}
@Test
public void no_classes_declaring_LOG_field_should_call_log_method() {
noClasses()
.that(new DescribedPredicate<JavaClass>("declare `LOG` field") {
@Override
public boolean test(JavaClass javaClass) {
return javaClass.getFields().stream().anyMatch(field -> field.getName().equals("LOG"));
}
})
.should()
.callMethodWhere(name("log"))
.because("LOG field should be used explicitly instead")
.check(productionClasses);
}
@Test
@SneakyThrows
public void no_classes_should_contain_unprocessed_string_interpolations() {
Method getConstantPool = Class.class.getDeclaredMethod("getConstantPool");
getConstantPool.setAccessible(true);
noClasses()
.should(new ArchCondition<>("contain unprocessed string interpolations") {
@SneakyThrows
@Override
public void check(JavaClass clazz, ConditionEvents events) {
val constantPool = getConstantPool.invoke(clazz.reflect());
int constantPoolSize = (int) constantPool.getClass().getDeclaredMethod("getSize").invoke(constantPool);
for (int i = 0; i < constantPoolSize; i++) {
try {
String constant = (String) constantPool.getClass().getDeclaredMethod("getUTF8At", int.class)
.invoke(constantPool, i);
if (constant.matches("^.*\\$\\{.+}.*$")) {
events.add(SimpleConditionEvent.satisfied(clazz, "class " + clazz.getName() + " contains " + constant));
}
} catch (InvocationTargetException e) {
if (!(e.getCause() instanceof IllegalArgumentException)) {
// IllegalArgumentException wrapped into InvocationTargetException is expected
// when `getUTF8At` is called for an index in constant pool that doesn't correspond to a String.
// All other errors are unexpected.
throw e;
}
}
}
}
})
.because("it's likely that better-strings annotation processor has not been properly applied on some subproject(s)")
.check(productionClasses);
}
@Test
public void side_effecting_backgroundables_should_not_access_my_project() {
noClasses()
.that()
.areAssignableTo(com.virtuslab.gitmachete.frontend.actions.backgroundables.SideEffectingBackgroundable.class)
.should()
.accessFieldWhere(name("myProject"))
.because("`myProject` is nullable, which leads to redundant nullness checks; used `project` instead")
.check(productionClasses);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/src/test/java/com/virtuslab/archunit/NamingTestSuite.java | src/test/java/com/virtuslab/archunit/NamingTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import org.junit.jupiter.api.Test;
public class NamingTestSuite extends BaseArchUnitTestSuite {
@Test
public void exception_class_names_should_end_with_Exception() {
classes()
.that().areAssignableTo(Exception.class)
.should().haveSimpleNameEndingWith("Exception")
.check(productionClasses);
}
@Test
public void class_names_should_not_end_with_Manager() {
noClasses()
.should().haveSimpleNameEndingWith("Manager")
.because("classes called `...Manager` are an indicator of poor design; " +
"likely a redesign (and not just a rename) is needed")
.check(productionClasses);
}
@Test
public void class_names_should_not_end_with_Util() {
noClasses()
.should().haveSimpleNameEndingWith("Util")
.because("we use `...Utils` (not `...Util`) naming convention")
.check(productionClasses);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
VirtusLab/git-machete-intellij-plugin | https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/src/test/java/com/virtuslab/archunit/UIThreadUnsafeMethodInvocationsTestSuite.java | src/test/java/com/virtuslab/archunit/UIThreadUnsafeMethodInvocationsTestSuite.java | package com.virtuslab.archunit;
import static com.tngtech.archunit.core.domain.JavaModifier.ABSTRACT;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.codeUnits;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noCodeUnits;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noMethods;
import java.util.Arrays;
import com.intellij.openapi.progress.Task;
import com.intellij.util.concurrency.annotations.RequiresEdt;
import com.tngtech.archunit.core.domain.AccessTarget;
import com.tngtech.archunit.core.domain.JavaCodeUnit;
import io.vavr.collection.List;
import lombok.experimental.ExtensionMethod;
import lombok.val;
import org.checkerframework.checker.guieffect.qual.UIEffect;
import org.junit.jupiter.api.Test;
import com.virtuslab.qual.guieffect.IgnoreUIThreadUnsafeCalls;
import com.virtuslab.qual.guieffect.UIThreadUnsafe;
@ExtensionMethod(Arrays.class)
public class UIThreadUnsafeMethodInvocationsTestSuite extends BaseArchUnitTestSuite {
private static final String UIThreadUnsafeName = "@" + UIThreadUnsafe.class.getSimpleName();
@Test
public void task_backgroundable_run_methods_must_be_ui_thread_unsafe() {
methods()
.that()
.haveNameMatching("^(doRun|run)$")
.and()
.areDeclaredInClassesThat()
.areAssignableTo(Task.Backgroundable.class)
.should()
.beAnnotatedWith(UIThreadUnsafe.class)
.because("it probably doesn't make sense to extract a backgroundable task " +
"for actions that can as well be executed on UI thread")
.check(productionClasses);
}
@Test
public void ui_thread_unsafe_code_units_should_not_be_uieffect() {
codeUnits()
.that()
.areAnnotatedWith(UIThreadUnsafe.class)
.should()
.notBeAnnotatedWith(UIEffect.class)
.check(productionClasses);
}
@Test
public void code_units_with_requires_edt_should_only_be_called_from_ui_effect_code_units() {
noCodeUnits()
.that()
.areNotAnnotatedWith(UIEffect.class)
.should(callAnyCodeUnitsThat("are annotated with @RequiresEdt",
(codeUnit, calledCodeUnit) -> calledCodeUnit.isAnnotatedWith(RequiresEdt.class)))
.check(productionClasses);
}
private static List<String> extractWhitelistedCodeUnitsFromAnnotation(JavaCodeUnit codeUnit) {
if (codeUnit.isAnnotatedWith(IgnoreUIThreadUnsafeCalls.class)) {
return List.of(codeUnit.getAnnotationOfType(IgnoreUIThreadUnsafeCalls.class).value());
} else {
return List.empty();
}
}
@Test
public void only_ui_thread_unsafe_code_units_should_call_other_ui_thread_unsafe_code_units() {
noCodeUnits()
.that()
.areNotAnnotatedWith(UIThreadUnsafe.class)
.and()
// As of early 2023, the only place where such methods are generated are the calls of `Try.of(...)`,
// which require a parameter of type `CheckedFunction0`, which implements `Serializable`.
// See https://www.baeldung.com/java-serialize-lambda for details.
.doNotHaveName("$deserializeLambda$")
.should(callAnyCodeUnitsThat("are UI thread unsafe",
(codeUnit, calledCodeUnit) -> isUIThreadUnsafe(calledCodeUnit)
&& !extractWhitelistedCodeUnitsFromAnnotation(codeUnit).contains(calledCodeUnit.getFullName())))
.check(productionClasses);
}
private static final String[] knownBlockingCodeUnits = {
"com.intellij.dvcs.push.PushController.push(boolean)",
"com.intellij.openapi.vcs.changes.VcsFreezingProcess.execute()",
"java.lang.Process.waitFor(long, java.util.concurrent.TimeUnit)",
"java.lang.Thread.sleep(long)",
};
private static final String[] uiThreadUnsafePackagePrefixes = {
"git4idea",
"java.io",
"java.nio",
"org.eclipse.jgit",
};
private static final String[] uiThreadSafeCodeUnitsInUnsafePackages = {
"git4idea.GitLocalBranch.getName()",
"git4idea.GitRemoteBranch.getName()",
"git4idea.GitRemoteBranch.getNameForRemoteOperations()",
"git4idea.GitUtil.findGitDir(com.intellij.openapi.vfs.VirtualFile)",
"git4idea.GitUtil.getRepositories(com.intellij.openapi.project.Project)",
"git4idea.GitUtil.getRepositoryManager(com.intellij.openapi.project.Project)",
"git4idea.branch.GitBranchUtil.sortBranchNames(java.util.Collection)",
"git4idea.branch.GitBranchOperationType.getDescription()",
"git4idea.branch.GitBranchOperationType.getText()",
"git4idea.branch.GitBrancher.checkout(java.lang.String, boolean, java.util.List, java.lang.Runnable)",
"git4idea.branch.GitBrancher.compareAny(java.lang.String, java.lang.String, java.util.List)",
"git4idea.branch.GitBrancher.createBranch(java.lang.String, java.util.Map)",
"git4idea.branch.GitBrancher.deleteBranch(java.lang.String, java.util.List)",
"git4idea.branch.GitBrancher.deleteBranches(java.util.Map, java.lang.Runnable)",
"git4idea.branch.GitBrancher.getInstance(com.intellij.openapi.project.Project)",
"git4idea.branch.GitBrancher.merge(java.lang.String, git4idea.branch.GitBrancher$DeleteOnMergeOption, java.util.List)",
"git4idea.branch.GitBrancher.renameBranch(java.lang.String, java.lang.String, java.util.List)",
"git4idea.branch.GitBranchesCollection.findBranchByName(java.lang.String)",
"git4idea.branch.GitBranchesCollection.findLocalBranch(java.lang.String)",
"git4idea.branch.GitBranchesCollection.findRemoteBranch(java.lang.String)",
"git4idea.branch.GitBranchesCollection.getHash(git4idea.GitBranch)",
"git4idea.branch.GitBranchesCollection.getLocalBranches()",
"git4idea.branch.GitBranchesCollection.getRemoteBranches()",
"git4idea.branch.GitNewBranchDialog.<init>(com.intellij.openapi.project.Project, java.util.Collection, java.lang.String, java.lang.String, boolean, boolean, boolean)",
"git4idea.branch.GitNewBranchDialog.<init>(com.intellij.openapi.project.Project, java.util.Collection, java.lang.String, java.lang.String, boolean, boolean, boolean, boolean, git4idea.branch.GitBranchOperationType)",
"git4idea.branch.GitNewBranchDialog.showAndGetOptions()",
"git4idea.branch.GitNewBranchOptions.getName()",
"git4idea.branch.GitNewBranchOptions.shouldCheckout()",
"git4idea.branch.GitRebaseParams.<init>(git4idea.config.GitVersion, java.lang.String, java.lang.String, java.lang.String, boolean, boolean)",
"git4idea.config.GitConfigUtil.getBooleanValue(java.lang.String)",
"git4idea.config.GitSharedSettings.getInstance(com.intellij.openapi.project.Project)",
"git4idea.config.GitSharedSettings.isBranchProtected(java.lang.String)",
"git4idea.config.GitVcsSettings.getInstance(com.intellij.openapi.project.Project)",
"git4idea.config.GitVcsSettings.getRecentRootPath()",
"git4idea.fetch.GitFetchResult.showNotification()",
"git4idea.fetch.GitFetchSupport.fetchSupport(com.intellij.openapi.project.Project)",
"git4idea.fetch.GitFetchSupport.isFetchRunning()",
"git4idea.push.GitPushSource.create(git4idea.GitLocalBranch)",
"git4idea.repo.GitRemote.getName()",
"git4idea.repo.GitRepository.getBranches()",
"git4idea.repo.GitRepository.getCurrentBranch()",
"git4idea.repo.GitRepository.getCurrentBranchName()",
"git4idea.repo.GitRepository.getProject()",
"git4idea.repo.GitRepository.getRemotes()",
"git4idea.repo.GitRepository.getRoot()",
"git4idea.repo.GitRepository.getState()",
"git4idea.repo.GitRepository.getVcs()",
"git4idea.repo.GitRepository.toString()",
"git4idea.ui.ComboBoxWithAutoCompletion.<init>(javax.swing.ComboBoxModel, com.intellij.openapi.project.Project)",
"git4idea.ui.ComboBoxWithAutoCompletion.addDocumentListener(com.intellij.openapi.editor.event.DocumentListener)",
"git4idea.ui.ComboBoxWithAutoCompletion.getModel()",
"git4idea.ui.ComboBoxWithAutoCompletion.getText()",
"git4idea.ui.ComboBoxWithAutoCompletion.selectAll()",
"git4idea.ui.ComboBoxWithAutoCompletion.setPlaceholder(java.lang.String)",
"git4idea.ui.ComboBoxWithAutoCompletion.setPrototypeDisplayValue(java.lang.Object)",
"git4idea.ui.ComboBoxWithAutoCompletion.setUI(javax.swing.plaf.ComboBoxUI)",
"git4idea.ui.branch.GitBranchCheckoutOperation.<init>(com.intellij.openapi.project.Project, java.util.Collection)",
"git4idea.ui.branch.GitBranchPopupActions$RemoteBranchActions$CheckoutRemoteBranchAction.checkoutRemoteBranch(com.intellij.openapi.project.Project, java.util.List, java.lang.String)",
"git4idea.validators.GitBranchValidatorKt.checkRefName(java.lang.String)",
"git4idea.validators.GitBranchValidatorKt.checkRefNameEmptyOrHead(java.lang.String)",
"git4idea.validators.GitBranchValidatorKt.conflictsWithLocalBranch(java.util.Collection, java.lang.String)",
"git4idea.validators.GitBranchValidatorKt.conflictsWithLocalBranchDirectory(java.util.Set, java.lang.String)",
"git4idea.validators.GitBranchValidatorKt.conflictsWithRemoteBranch(java.util.Collection, java.lang.String)",
"git4idea.validators.GitRefNameValidator.cleanUpBranchName(java.lang.String)",
"git4idea.validators.GitRefNameValidator.cleanUpBranchNameOnTyping(java.lang.String)",
"git4idea.validators.GitRefNameValidator.getInstance()",
// Some of these java.(n)io methods might actually access the filesystem;
// still, they're lightweight enough so that we can give them a free pass.
"java.io.BufferedOutputStream.<init>(java.io.OutputStream)",
"java.io.File.canExecute()",
"java.io.File.getAbsolutePath()",
"java.io.File.isFile()",
"java.io.File.toString()",
"java.io.IOException.getMessage()",
"java.nio.file.Files.isRegularFile(java.nio.file.Path, [Ljava.nio.file.LinkOption;)",
"java.nio.file.Files.readAttributes(java.nio.file.Path, java.lang.Class, [Ljava.nio.file.LinkOption;)",
"java.nio.file.Files.setLastModifiedTime(java.nio.file.Path, java.nio.file.attribute.FileTime)",
"java.nio.file.Path.equals(java.lang.Object)",
"java.nio.file.Path.getFileName()",
"java.nio.file.Path.getParent()",
"java.nio.file.Path.of(java.lang.String, [Ljava.lang.String;)",
"java.nio.file.Path.resolve(java.lang.String)",
"java.nio.file.Path.toAbsolutePath()",
"java.nio.file.Path.toFile()",
"java.nio.file.Path.toString()",
"java.nio.file.Paths.get(java.lang.String, [Ljava.lang.String;)",
"java.nio.file.attribute.BasicFileAttributes.lastModifiedTime()",
"java.nio.file.attribute.FileTime.fromMillis(long)",
"java.nio.file.attribute.FileTime.toMillis()",
"org.eclipse.jgit.lib.CheckoutEntry.getFromBranch()",
"org.eclipse.jgit.lib.CheckoutEntry.getToBranch()",
"org.eclipse.jgit.lib.ObjectId.equals(org.eclipse.jgit.lib.AnyObjectId)",
"org.eclipse.jgit.lib.ObjectId.getName()",
"org.eclipse.jgit.lib.ObjectId.zeroId()",
"org.eclipse.jgit.lib.PersonIdent.getWhen()",
"org.eclipse.jgit.lib.Ref.getName()",
"org.eclipse.jgit.lib.Ref.getObjectId()",
"org.eclipse.jgit.lib.ReflogEntry.getComment()",
"org.eclipse.jgit.lib.ReflogEntry.getNewId()",
"org.eclipse.jgit.lib.ReflogEntry.getOldId()",
"org.eclipse.jgit.lib.ReflogEntry.getWho()",
"org.eclipse.jgit.lib.ReflogEntry.parseCheckout()",
"org.eclipse.jgit.lib.RepositoryState.ordinal()",
"org.eclipse.jgit.lib.RepositoryState.values()",
"org.eclipse.jgit.revwalk.RevCommit.getCommitTime()",
"org.eclipse.jgit.revwalk.RevCommit.getFullMessage()",
"org.eclipse.jgit.revwalk.RevCommit.getId()",
"org.eclipse.jgit.revwalk.RevCommit.getTree()",
"org.eclipse.jgit.revwalk.RevTree.getId()",
};
private static boolean isUIThreadUnsafe(AccessTarget.CodeUnitCallTarget codeUnit) {
String packageName = codeUnit.getOwner().getPackageName();
String fullName = codeUnit.getFullName();
return uiThreadUnsafePackagePrefixes.stream().anyMatch(prefix -> packageName.startsWith(prefix))
&& !uiThreadSafeCodeUnitsInUnsafePackages.asList().contains(fullName)
|| knownBlockingCodeUnits.asList().contains(fullName)
|| codeUnit.isAnnotatedWith(UIThreadUnsafe.class);
}
private static final String[] knownMethodsOverridableAsUIThreadUnsafe = {
// These two methods have been experimentally verified to be executed by IntelliJ outside of UI thread.
"com.intellij.codeInsight.completion.CompletionContributor.fillCompletionVariants(com.intellij.codeInsight.completion.CompletionParameters, com.intellij.codeInsight.completion.CompletionResultSet)",
"com.intellij.lang.annotation.Annotator.annotate(com.intellij.psi.PsiElement, com.intellij.lang.annotation.AnnotationHolder)",
// This method (overridden in Backgroundables) is meant to run outside of UI thread by design.
"com.intellij.openapi.progress.Progressive.run(com.intellij.openapi.progress.ProgressIndicator)",
};
@Test
public void ui_thread_unsafe_methods_should_not_override_ui_thread_safe_methods() {
noMethods()
.that()
.areAnnotatedWith(UIThreadUnsafe.class)
.should(overrideAnyMethodThat("is NOT ${UIThreadUnsafeName} itself", (method, overriddenMethod) -> {
val overriddenMethodFullName = overriddenMethod.getFullName();
if (overriddenMethod.isAnnotatedWith(UIThreadUnsafe.class)) {
return false;
}
if (knownMethodsOverridableAsUIThreadUnsafe.asList().contains(overriddenMethodFullName)) {
return false;
}
return true;
}))
.check(productionClasses);
}
@Test
public void concrete_ui_thread_unsafe_code_units_should_call_at_least_one_ui_thread_unsafe_code_unit() {
codeUnits()
.that()
.doNotHaveModifier(ABSTRACT)
.and()
.areAnnotatedWith(UIThreadUnsafe.class)
.should(callAtLeastOnceACodeUnitThat("is UI-thread unsafe",
(codeUnit, calledCodeUnit) -> isUIThreadUnsafe(calledCodeUnit)
&& !extractWhitelistedCodeUnitsFromAnnotation(codeUnit).contains(calledCodeUnit.getFullName())))
.check(productionClasses);
}
}
| java | MIT | 2b736d89bd073f82456de77481c7f6714716efca | 2026-01-05T02:37:01.395349Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.