org.databene.edifatto.SegmentFormatter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of edifatto Show documentation
Show all versions of edifatto Show documentation
'Edifatto' is an open source software library for parsing,
generating and verifying EDIFACT and X12 documents written by Volker Bergmann.
/*
* Copyright (C) 2013-2015 Volker Bergmann ([email protected]).
* All rights reserved.
*
* 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 org.databene.edifatto;
import org.databene.commons.ProgrammerError;
import org.databene.edifatto.model.Component;
import org.databene.edifatto.model.Composite;
import org.databene.edifatto.model.Segment;
import org.databene.edifatto.model.SegmentItem;
/**
* Formats an EDI segment as text.
* Created: 18.10.2013 16:30:15
* @since 1.0
* @author Volker Bergmann
*/
public class SegmentFormatter {
private EdiFormatSymbols symbols;
public SegmentFormatter(EdiFormatSymbols symbols) {
this.symbols = symbols;
}
public String format(Segment segment) {
if ("UNA".equals(segment.getTag()))
return formatUNASegment(segment);
else
return formatStandardSegment(segment);
}
public static String formatUNASegment(Segment segment) {
return "UNA" + ((Component) segment.getChild(0)).getData();
}
private String formatStandardSegment(Segment segment) {
StringBuilder builder = new StringBuilder(segment.getTag()).append(symbols.elementSeparator);
for (int iE = 0; iE < segment.getChildren().size(); iE++) {
if (iE > 0)
builder.append(symbols.elementSeparator);
builder.append(format(segment.getChild(iE)));
}
return builder.append(symbols.segmentSeparator).toString();
}
public String format(SegmentItem item) {
if (item instanceof Composite)
return formatComposite((Composite) item);
else if (item instanceof Component)
return item.toString();
else
throw new ProgrammerError("Not a supported type: " + item.getClass());
}
private String formatComposite(Composite item) {
StringBuilder builder = new StringBuilder();
for (int iE = 0; iE < item.getChildCount(); iE++) {
if (iE > 0)
builder.append(symbols.componentSeparator);
builder.append(item.getChild(iE));
}
return builder.toString();
}
}